source: 1dwg/tags/v1.1/python/example.py

Last change on this file was 313, checked in by prjemian, 6 years ago
  • 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)
  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision URL
File size: 4.4 KB
Line 
1#!/usr/bin/env python
2
3'''Extended example use of cansas1d reader'''
4
5# Copyright (c) 2013, UChicago Argonne, LLC
6# This file is distributed subject to a Software License Agreement found
7# in the file LICENSE that is included with this distribution.
8
9
10import os
11import sys
12import cansas1d
13
14__svn_id__ = "$Id$"
15
16
17
18def indra_metadata(SASentry):
19    '''print metadata from APS/USAXS Indra package'''
20    if 'metadata' in SASentry.__dict__:
21        for metadata in SASentry.metadata:
22            '''loop through the USAXS metadata'''
23            print metadata.xmlns
24            for index in metadata.usaxs:
25                '''multiple invocations of the usaxs element'''
26                for item in dir(index):
27                    '''discover the element names'''
28                    if item[0] == '_':    # sift out data structure management terms
29                        continue
30                    if item in ('PCDATA', 'name', 'xmlns'):  # sift this out
31                        continue
32                    s = ''
33                    s += '('+index.xmlns+') '
34                    s += '('+index.name+') '
35                    s += item + ': '
36                    s += index.__dict__[item].PCDATA
37                    print s
38
39
40def print_SASdata(sd):
41    '''print the contents of the SASdata element'''
42    numPts = len(sd.Idata)
43    if 'name' in sd.__dict__:
44        print 'SASdata name:', sd.name
45    print '# points:', numPts
46    columns = [
47        ['Q ('+sd.Idata[0].Q.unit+')'],
48        ['I ('+sd.Idata[0].I.unit+')'],
49        ['Idev ('+sd.Idata[0].Idev.unit+')'],
50    ]
51    for Idata in sd.Idata:
52        values = (Idata.Q.PCDATA, Idata.I.PCDATA, Idata.Idev.PCDATA)
53        for item, value in enumerate(values):
54            columns[item].append(str(value))
55    print columnsToText(columns)
56
57
58def print_optional_item(title, parent, item):
59    ''' this item is optional and may not be present'''
60    if item in parent.__dict__:
61        #print item, item in parent.__dict__
62        obj = parent.__dict__[item]
63        s = title+':\t'
64        s += obj.PCDATA
65        if 'unit' in obj.__dict__:
66            s += ' (' + obj.unit + ')'
67        print s
68
69
70def columnsToText(columns):
71    '''
72    convert a list of column lists into rows of text
73   
74    column widths will be chosen from the maximum character width of each column
75   
76    :param [[str]] columns: list of column lists (all same length)
77    :returns str: text block, with line separators
78   
79    Example::
80   
81        >>> columns = [ ['1A', '2A'], ['1B is long', '2B'], ['1C', '2C'] ]
82        >>> print columnsToText( columns )
83        1A  1B is long  1C
84        2A  2B          2C
85   
86    '''
87    # get the largest width for each column
88    widths = [max(map(len, item)) for item in columns]
89    # left-align each column
90    sep = ' '*2
91    fmt = sep.join(['%%-%ds' % item for item in widths])
92    # rows = zip(*columns) : matrix transpose
93    result = [fmt % tuple(row) for row in zip(*columns)]
94    return '\n'.join(result)
95
96
97def demo(xmlFile):
98    print '#---------------------------------------------------'
99    print 'XML:', xmlFile
100    # read in the XML file
101    try:
102        sasxml = cansas1d.readCanSasFile(xmlFile)
103    except cansas1d.Exception_canSAS_namespace, answer:
104        print "wrong XML namespace:", answer
105        return
106    except cansas1d.Exception_canSAS_version, answer:
107        print "wrong version string:", answer
108        return
109    print 'namespace:', sasxml.xmlns
110    print 'version:', sasxml.version
111    SASentry = sasxml.SASentry                  # just the first one
112    print 'title:', SASentry.Title.PCDATA
113    print 'run:', SASentry.Run.PCDATA
114    print_optional_item('instrument', SASentry.SASinstrument, 'name')
115    indra_metadata(SASentry)        # foreign XML elements from APS/USAXS
116    print_optional_item('sample ID', SASentry.SASsample, 'ID')
117    print_optional_item('sample thickness', SASentry.SASsample, 'thickness')
118    print_optional_item('sample transmission', SASentry.SASsample, 'transmission')
119    if 'position' in SASentry.SASsample.__dict__:
120        print_optional_item('sample X', SASentry.SASsample.position, 'x')
121        print_optional_item('sample Y', SASentry.SASsample.position, 'y')
122    print_SASdata(SASentry.SASdata)
123
124
125if __name__ == "__main__":
126    if len(sys.argv) == 2:
127        demo(sys.argv[1])
128    else:
129        demo(os.path.join('..', 'examples', 'bimodal-test1.xml'))
130        demo(os.path.join('..', 'examples', 's81-polyurea.xml'))
Note: See TracBrowser for help on using the repository browser.