Ignore:
Timestamp:
Mar 29, 2013 1:00:46 AM (7 years ago)
Author:
prjemian
Message:
  • refs #23
  • applied license text
  • cleaned up the Python binding documentation
  • added list of authors and contributors
  • for each binding, show how to get I(Q)
  • retrieve CanSas1dType.java from repository (example in the Java binding documentation calls for it)
File:
1 moved

Legend:

Unmodified
Added
Removed
  • 1dwg/trunk/python/cansas1d.py

    • Property svn:keywords changed from Author Date Id Revision URL Header to Author Date Id Revision URL
    r310 r313  
    11#!/usr/bin/env python 
     2 
    23'''  
    3 Example use of Gnosis_utils to read both cansas1d:1.1  
    4 and cansas1d/1.0 files 
     4read canSAS 1-D XML data files (either v1.0 or v1.1) 
    55 
    6 This demonstrates full access to the contents of  
    7 the XML file using a single line to open the file:: 
     6:requires:  
     7    gnosis.xml.objectify     # easy_install -U gnosis 
    88 
    9     sasxml = readCanSasFile(xmlFile) 
     9basic use in a program:: 
    1010 
    11 .. note:: Since :meth:`readCanSasFile` raises exceptions  
    12    if the namespace or version does not match, it is best 
    13    to wrap this call in ``try ... except``` block, 
    14    as shown in :meth:`demo`. 
     11    import cansas1d 
     12    try: 
     13        sasxml = cansas1d.readCanSasFile(xmlFile) 
     14    except cansas1d.Exception_canSAS_namespace, answer: 
     15        print "wrong XML namespace:", answer 
     16        return 
     17    except cansas1d.Exception_canSAS_version, answer: 
     18        print "wrong version string:", answer 
     19        return 
    1520 
     21Copyright (c) 2013, UChicago Argonne, LLC 
     22This file is distributed subject to a Software License Agreement found 
     23in the file LICENSE that is included with this distribution.  
    1624''' 
    1725 
     
    4351    open a canSAS XML data file as a gnosis file object 
    4452     
    45     usage:: 
    46      
    47         try: 
    48             sasxml = readCanSasFile(xmlFile) 
    49         except (Exception_canSAS_namespace, Exception_canSAS_version), answer: 
    50             print answer 
    51             return 
    52         print 'namespace:', sasxml.xmlns 
    53         print 'version:', sasxml.version 
    54         SASentry = sasxml.SASentry                  # just the first one 
    55         # ... 
    56      
     53    :param str xmlFile: name of canSAS 1D XML data file 
     54    :returns: gnosis object with XML data structure 
     55    :raises Exception_canSAS_namespace: if namespace does not match 
     56    :raises Exception_canSAS_version: if version does not match 
    5757    ''' 
    5858    # read in the XML file 
    5959    sasxml = gnosis.xml.objectify.XML_Objectify(xmlFile).make_instance() 
     60     
    6061    # namespace check to accept file as canSAS XML 
    6162    if sasxml.xmlns not in CANSAS_NAMESPACES.values(): 
    62         msg = "Not a canSAS data file (namespace found: %s)" % sasxml.xmlns 
    63         raise Exception_canSAS_namespace, msg 
     63        raise Exception_canSAS_namespace, str(sasxml.xmlns) 
     64     
     65    # version check 
    6466    if sasxml.version not in CANSAS_NAMESPACES.keys(): 
    65         msg = "Not v1.1 file (found: %s)" % msg 
    66         raise Exception_canSAS_version, msg 
     67        raise Exception_canSAS_version, str(sasxml.version) 
     68     
    6769    return sasxml 
    68  
    6970 
    7071class Exception_canSAS_namespace(Exception): 
     
    7677    pass 
    7778 
    78  
    79 def indra_metadata(SASentry): 
    80     '''print metadata from APS/USAXS Indra package''' 
    81     if 'metadata' in SASentry.__dict__: 
    82         for metadata in SASentry.metadata: 
    83             '''loop through the USAXS metadata''' 
    84             print metadata.xmlns 
    85             for index in metadata.usaxs: 
    86                 '''multiple invocations of the usaxs element''' 
    87                 for item in dir(index): 
    88                     '''discover the element names''' 
    89                     if item[0] == '_':    # sift out data structure management terms 
    90                         continue 
    91                     if item in ('PCDATA', 'name', 'xmlns'):  # sift this out 
    92                         continue 
    93                     s = '' 
    94                     s += '('+index.xmlns+') ' 
    95                     s += '('+index.name+') ' 
    96                     s += item + ': ' 
    97                     s += index.__dict__[item].PCDATA 
    98                     print s 
    99  
    100  
    101 def print_SASdata(sd): 
    102     '''print the contents of the SASdata element''' 
    103     numPts = len(sd.Idata) 
    104     if 'name' in sd.__dict__: 
    105         print 'SASdata name:', sd.name 
    106     print '# points:', numPts 
    107     columns = [ 
    108         ['Q ('+sd.Idata[0].Q.unit+')'], 
    109         ['I ('+sd.Idata[0].I.unit+')'], 
    110         ['Idev ('+sd.Idata[0].Idev.unit+')'], 
    111     ] 
    112     for Idata in sd.Idata: 
    113         values = (Idata.Q.PCDATA, Idata.I.PCDATA, Idata.Idev.PCDATA) 
    114         for item, value in enumerate(values): 
    115             columns[item].append(str(value)) 
    116     print columnsToText(columns) 
    117  
    118  
    119 def print_optional_item(title, parent, item): 
    120     ''' this item is optional and may not be present''' 
    121     if item in parent.__dict__: 
    122         #print item, item in parent.__dict__ 
    123         obj = parent.__dict__[item] 
    124         s = title+':\t' 
    125         s += obj.PCDATA 
    126         if 'unit' in obj.__dict__: 
    127             s += ' (' + obj.unit + ')' 
    128         print s 
    129  
    130  
    131 def columnsToText(columns): 
    132     ''' 
    133     convert a list of column lists into rows of text 
    134      
    135     column widths will be chosen from the maximum character width of each column 
    136      
    137     :param [[str]] columns: list of column lists (all same length) 
    138     :returns str: text block, with line separators 
    139      
    140     Example:: 
    141      
    142         >>> columns = [ ['1A', '2A'], ['1B is long', '2B'], ['1C', '2C'] ] 
    143         >>> print columnsToText( columns ) 
    144         1A  1B is long  1C 
    145         2A  2B          2C 
    146      
    147     ''' 
    148     # get the largest width for each column 
    149     widths = [max(map(len, item)) for item in columns] 
    150     # left-align each column 
    151     sep = ' '*2 
    152     fmt = sep.join(['%%-%ds' % item for item in widths]) 
    153     # rows = zip(*columns) : matrix transpose 
    154     result = [fmt % tuple(row) for row in zip(*columns)] 
    155     return '\n'.join(result) 
    156  
    157  
    158 def demo(xmlFile): 
    159     print '#---------------------------------------------------' 
    160     print 'XML:', xmlFile 
    161     # read in the XML file 
    162     try: 
    163         sasxml = readCanSasFile(xmlFile) 
    164     except (Exception_canSAS_namespace, Exception_canSAS_version), answer: 
    165         print answer 
    166         return 
    167     print 'namespace:', sasxml.xmlns 
    168     print 'version:', sasxml.version 
    169     SASentry = sasxml.SASentry                  # just the first one 
    170     print 'title:', SASentry.Title.PCDATA 
    171     print 'run:', SASentry.Run.PCDATA 
    172     print_optional_item('instrument', SASentry.SASinstrument, 'name') 
    173     indra_metadata(SASentry)        # foreign XML elements from APS/USAXS 
    174     print_optional_item('sample ID', SASentry.SASsample, 'ID') 
    175     print_optional_item('sample thickness', SASentry.SASsample, 'thickness') 
    176     print_optional_item('sample transmission', SASentry.SASsample, 'transmission') 
    177     if 'position' in SASentry.SASsample.__dict__: 
    178         print_optional_item('sample X', SASentry.SASsample.position, 'x') 
    179         print_optional_item('sample Y', SASentry.SASsample.position, 'y') 
    180     print_SASdata(SASentry.SASdata) 
    181  
    182  
    18379if __name__ == "__main__": 
    184     if len(sys.argv) == 2: 
    185         demo(sys.argv[1]) 
    186     else: 
    187         demo(os.path.join('..', 'examples', 'bimodal-test1.xml')) 
    188         demo(os.path.join('..', 'examples', 's81-polyurea.xml')) 
     80    '''just for demonstration using example data files''' 
     81    for xmlFile in ('bimodal-test1', 's81-polyurea'): 
     82        path = os.path.abspath(os.path.join('..', 'examples', xmlFile+'.xml')) 
     83        if not os.path.exists(path): 
     84            continue 
     85        try: 
     86            sasxml = readCanSasFile(path) 
     87        except Exception_canSAS_namespace, answer: 
     88            print xmlFile, "wrong XML namespace:", answer 
     89            continue 
     90        except Exception_canSAS_version, answer: 
     91            print xmlFile, "wrong version string:", answer 
     92            continue 
     93        print '%s has %d data points' % (xmlFile, len(sasxml.SASentry.SASdata.Idata)) 
     94         
Note: See TracChangeset for help on using the changeset viewer.