Ignore:
Timestamp:
Mar 5, 2015 10:29:42 AM (9 years ago)
Author:
Mathieu Doucet <doucetm@…>
Branches:
master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
dca6188
Parents:
74f419d
Message:

pylint fixes

File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/sas/perspectives/invariant/invariant_state.py

    rb9a5f0e r78a205a  
    11""" 
     2    State class for the invariant UI 
    23""" 
    34 
    4 #import time 
     5# import time 
    56import os 
    67import sys 
     
    89import copy 
    910import sas.dataloader 
    10 #from xml.dom.minidom import parse 
     11# from xml.dom.minidom import parse 
    1112from lxml import etree 
    1213from sas.dataloader.readers.cansas_reader import Reader as CansasReader 
     
    2021 
    2122# default state 
    22 list = {'file': 'None', 
    23         'compute_num':0, 
    24         'state_num':0, 
    25         'is_time_machine':False, 
    26         'background_tcl':0.0, 
    27         'scale_tcl':1.0, 
    28         'contrast_tcl':1.0, 
    29         'porod_constant_tcl':'', 
    30         'npts_low_tcl':10, 
    31         'npts_high_tcl':10, 
    32         'power_high_tcl':4.0, 
    33         'power_low_tcl': 4.0, 
    34         'enable_high_cbox':False, 
    35         'enable_low_cbox':False, 
    36         'guinier': True, 
    37         'power_law_high': False, 
    38         'power_law_low': False, 
    39         'fit_enable_high': False, 
    40         'fit_enable_low': False, 
    41         'fix_enable_high':True, 
    42         'fix_enable_low':True, 
    43         'volume_tcl':'', 
    44         'volume_err_tcl':'', 
    45         'surface_tcl':'', 
    46         'surface_err_tcl':''} 
    47 # list of states: This list will be filled as panel  
     23DEFAULT_STATE = {'file': 'None', 
     24                 'compute_num':0, 
     25                 'state_num':0, 
     26                 'is_time_machine':False, 
     27                 'background_tcl':0.0, 
     28                 'scale_tcl':1.0, 
     29                 'contrast_tcl':1.0, 
     30                 'porod_constant_tcl':'', 
     31                 'npts_low_tcl':10, 
     32                 'npts_high_tcl':10, 
     33                 'power_high_tcl':4.0, 
     34                 'power_low_tcl': 4.0, 
     35                 'enable_high_cbox':False, 
     36                 'enable_low_cbox':False, 
     37                 'guinier': True, 
     38                 'power_law_high': False, 
     39                 'power_law_low': False, 
     40                 'fit_enable_high': False, 
     41                 'fit_enable_low': False, 
     42                 'fix_enable_high':True, 
     43                 'fix_enable_low':True, 
     44                 'volume_tcl':'', 
     45                 'volume_err_tcl':'', 
     46                 'surface_tcl':'', 
     47                 'surface_err_tcl':''} 
     48# list of states: This list will be filled as panel 
    4849# init and the number of states increases 
    4950state_list = {} 
    5051bookmark_list = {} 
    51 # list of input parameters (will be filled up on panel init) used by __str__  
     52# list of input parameters (will be filled up on panel init) used by __str__ 
    5253input_list = {'background_tcl':0, 
    53         'scale_tcl':0, 
    54         'contrast_tcl':0, 
    55         'porod_constant_tcl':'', 
    56         'npts_low_tcl':0, 
    57         'npts_high_tcl':0, 
    58         'power_high_tcl':0, 
    59         'power_low_tcl': 0}   
    60 # list of output parameters (order sensitive) used by __str__     
    61 output_list = [["qstar_low",      "Q* from low Q extrapolation [1/(cm*A)]"], 
    62                ["qstar_low_err",             "dQ* from low Q extrapolation"], 
    63                ["qstar_low_percent",  "Q* percent from low Q extrapolation"], 
    64                ["qstar",              "Q* from data [1/(cm*A)]"], 
    65                ["qstar_err",                                "dQ* from data"], 
    66                ["qstar_percent",                     "Q* percent from data"], 
    67                ["qstar_high",    "Q* from high Q extrapolation [1/(cm*A)]"], 
    68                ["qstar_high_err",           "dQ* from high Q extrapolation"], 
     54              'scale_tcl':0, 
     55              'contrast_tcl':0, 
     56              'porod_constant_tcl':'', 
     57              'npts_low_tcl':0, 
     58              'npts_high_tcl':0, 
     59              'power_high_tcl':0, 
     60              'power_low_tcl': 0} 
     61# list of output parameters (order sensitive) used by __str__ 
     62output_list = [["qstar_low", "Q* from low Q extrapolation [1/(cm*A)]"], 
     63               ["qstar_low_err", "dQ* from low Q extrapolation"], 
     64               ["qstar_low_percent", "Q* percent from low Q extrapolation"], 
     65               ["qstar", "Q* from data [1/(cm*A)]"], 
     66               ["qstar_err", "dQ* from data"], 
     67               ["qstar_percent", "Q* percent from data"], 
     68               ["qstar_high", "Q* from high Q extrapolation [1/(cm*A)]"], 
     69               ["qstar_high_err", "dQ* from high Q extrapolation"], 
    6970               ["qstar_high_percent", "Q* percent from low Q extrapolation"], 
    70                ["qstar_total",         "total Q* [1/(cm*A)]"], 
    71                ["qstar_total_err",                              "total dQ*"], 
    72                ["volume",                                 "volume fraction"], 
    73                ["volume_err",                       "volume fraction error"], 
    74                ["surface",                               "specific surface"], 
    75                ["surface_err",                     "specific surface error"]] 
    76  
    77     
     71               ["qstar_total", "total Q* [1/(cm*A)]"], 
     72               ["qstar_total_err", "total dQ*"], 
     73               ["volume", "volume fraction"], 
     74               ["volume_err", "volume fraction error"], 
     75               ["surface", "specific surface"], 
     76               ["surface_err", "specific surface error"]] 
     77 
     78 
    7879 
    7980class InvariantState(object): 
     
    8586        Default values 
    8687        """ 
    87         # Input  
    88         self.file  = None 
     88        # Input 
     89        self.file = None 
    8990        self.data = Data1D(x=[], y=[], dx=None, dy=None) 
    90         self.theory_lowQ =  Data1D(x=[], y=[], dy=None) 
     91        self.theory_lowQ = Data1D(x=[], y=[], dy=None) 
    9192        self.theory_lowQ.symbol = GUIFRAME_ID.CURVE_SYMBOL_NUM 
    9293        self.theory_highQ = Data1D(x=[], y=[], dy=None) 
    9394        self.theory_highQ.symbol = GUIFRAME_ID.CURVE_SYMBOL_NUM 
    94         #self.is_time_machine = False 
    95         self.saved_state = list 
     95        # self.is_time_machine = False 
     96        self.saved_state = DEFAULT_STATE 
    9697        self.state_list = state_list 
    9798        self.bookmark_list = bookmark_list 
    9899        self.input_list = input_list 
    99100        self.output_list = output_list 
    100          
     101 
    101102        self.compute_num = 0 
    102103        self.state_num = 0 
    103104        self.timestamp = ('00:00:00', '00/00/0000') 
    104105        self.container = None 
    105         #plot image 
     106        # plot image 
    106107        self.wximbmp = None 
    107108        # report_html strings 
    108109        import sas.perspectives.invariant as invariant 
    109110        path = invariant.get_data_path(media='media') 
    110         path_report_html = os.path.join(path,"report_template.html") 
    111         html_template = open(path_report_html,"r") 
     111        path_report_html = os.path.join(path, "report_template.html") 
     112        html_template = open(path_report_html, "r") 
    112113        self.template_str = html_template.read() 
    113114        self.report_str = self.template_str 
    114         #self.report_str_save = None 
     115        # self.report_str_save = None 
    115116        html_template.close() 
    116          
     117 
    117118    def __str__(self): 
    118119        """ 
    119120        Pretty print 
    120              
     121 
    121122        : return: string representing the state 
    122123        """ 
     
    132133        state += "State No.: %d \n" % state_num 
    133134        state += "\n=== Inputs ===\n" 
    134          
     135 
    135136        # text ctl general inputs ( excluding extrapolation text ctl) 
    136         for key, value in self.input_list.iteritems():  
     137        for key, value in self.input_list.iteritems(): 
    137138            if value == '': 
    138139                continue 
    139             key_split = key.split('_')  
    140             max_ind = len(key_split)-1 
    141             if key_split[max_ind] == 'tcl':  
     140            key_split = key.split('_') 
     141            max_ind = len(key_split) - 1 
     142            if key_split[max_ind] == 'tcl': 
    142143                name = "" 
    143144                if key_split[1] == 'low' or key_split[1] == 'high': 
     
    146147                    name += " %s" % key_split[ind] 
    147148                state += "%s:   %s\n" % (name.lstrip(" "), value) 
    148                  
    149         # other input parameters        
     149 
     150        # other input parameters 
    150151        extra_lo = compute_state['enable_low_cbox'] 
    151152        if compute_state['enable_low_cbox']: 
     
    157158        if compute_state['enable_high_cbox']: 
    158159            extra_hi = 'Power law' 
    159         state += "\nExtrapolation:  High=%s; Low=%s\n" %(extra_hi, extra_lo)    
     160        state += "\nExtrapolation:  High=%s; Low=%s\n" % (extra_hi, extra_lo) 
    160161        low_off = False 
    161162        high_off = False 
    162         for key, value in self.input_list.iteritems():  
    163             key_split = key.split('_')  
    164             max_ind = len(key_split) - 1    
    165             if key_split[max_ind] == 'tcl':  
    166                 name = ""  
     163        for key, value in self.input_list.iteritems(): 
     164            key_split = key.split('_') 
     165            max_ind = len(key_split) - 1 
     166            if key_split[max_ind] == 'tcl': 
     167                name = "" 
    167168                # check each buttons whether or not ON or OFF 
    168169                if key_split[1] == 'low' or key_split[1] == 'high': 
    169170                    if not compute_state['enable_low_cbox'] and \ 
    170                         key_split[max_ind-1] == 'low': 
     171                        key_split[max_ind - 1] == 'low': 
    171172                        low_off = True 
    172                         continue               
     173                        continue 
    173174                    elif not compute_state['enable_high_cbox'] and \ 
    174                         key_split[max_ind-1] == 'high': 
     175                        key_split[max_ind - 1] == 'high': 
    175176                        high_off = True 
    176177                        continue 
    177178                    elif extra_lo == 'Guinier' and key_split[0] == 'power' and \ 
    178                         key_split[max_ind-1] == 'low': 
     179                        key_split[max_ind - 1] == 'low': 
    179180                        continue 
    180181                    for ind in range(0, max_ind): 
    181182                        name += " %s" % key_split[ind] 
    182183                    name = name.lstrip(" ") 
    183                     if name == "power low" : 
     184                    if name == "power low": 
    184185                        if compute_state['fix_enable_low']: 
    185186                            name += ' (Fixed)' 
    186187                        else: 
    187188                            name += ' (Fitted)' 
    188                     if name == "power high" : 
     189                    if name == "power high": 
    189190                        if compute_state['fix_enable_high']: 
    190191                            name += ' (Fixed)' 
     
    195196        state += "\n=== Outputs ===" 
    196197        for item in output_list: 
    197             item_split = item[0].split('_')  
     198            item_split = item[0].split('_') 
    198199            # Exclude the extrapolation that turned off 
    199200            if len(item_split) > 1: 
     
    204205            max_ind = len(item_split) - 1 
    205206            value = None 
    206             try: 
     207            if hasattr(self.container, item[0]): 
    207208                # Q* outputs 
    208                 exec "value = self.container.%s\n" % item[0] 
    209             except: 
     209                value = getattr(self.container, item[0]) 
     210            else: 
    210211                # other outputs than Q* 
    211212                name = item[0] + "_tcl" 
    212213                if name in self.saved_state.keys(): 
    213                     exec "value = self.saved_state['%s']" % name 
    214                  
    215             # Exclude the outputs w/''     
     214                    value = self.saved_state[name] 
     215 
     216            # Exclude the outputs w/'' 
    216217            if value == '': 
    217                 continue     
     218                continue 
    218219            # Error outputs 
    219220            if item_split[max_ind] == 'err': 
     
    221222            # Percentage outputs 
    222223            elif item_split[max_ind] == 'percent': 
    223                 try: 
    224                     value = float(value) * 100 
    225                 except: 
    226                     pass 
     224                value = float(value) * 100 
    227225                state += "(%s %s)" % (format_number(value), '%') 
    228226            # Outputs 
    229227            else: 
    230                 state += "\n%s:   %s " % (item[1],  
    231                                         format_number(value, high=True)) 
     228                state += "\n%s:   %s " % (item[1], 
     229                                          format_number(value, high=True)) 
    232230        # Include warning msg 
    233231        if self.container is not None: 
     
    244242        """ 
    245243        Writes the state of the InversionControl panel to file, as XML. 
    246          
     244 
    247245        Compatible with standalone writing, or appending to an 
    248246        already existing XML document. In that case, the XML document 
    249         is required. An optional entry node in the XML document  
     247        is required. An optional entry node in the XML document 
    250248        may also be given. 
    251          
     249 
    252250        : param file: file to write to 
    253251        : param doc: XML document object [optional] 
    254         : param entry_node: XML node within the XML document at which we will append the data [optional] 
     252        : param entry_node: XML node within the document at which we will append the data [optional] 
    255253        """ 
    256254        # TODO: Get this to work 
     
    261259        if doc is None: 
    262260            impl = getDOMImplementation() 
    263          
    264             doc_type = impl.createDocumentType(INVNODE_NAME, "1.0", "1.0")      
    265          
     261 
     262            doc_type = impl.createDocumentType(INVNODE_NAME, "1.0", "1.0") 
     263 
    266264            newdoc = impl.createDocument(None, INVNODE_NAME, doc_type) 
    267265            top_element = newdoc.documentElement 
     
    274272            else: 
    275273                entry_node.appendChild(top_element) 
    276                  
     274 
    277275        attr = newdoc.createAttribute("version") 
    278276        attr.nodeValue = '1.0' 
    279277        top_element.setAttributeNode(attr) 
    280          
     278 
    281279        # File name 
    282280        element = newdoc.createElement("filename") 
     
    286284            element.appendChild(newdoc.createTextNode(str(file))) 
    287285        top_element.appendChild(element) 
    288          
     286 
    289287        element = newdoc.createElement("timestamp") 
    290288        element.appendChild(newdoc.createTextNode(time.ctime(timestamp))) 
     
    293291        element.setAttributeNode(attr) 
    294292        top_element.appendChild(element) 
    295          
     293 
    296294        # Current state 
    297295        state = newdoc.createElement("state") 
    298296        top_element.appendChild(state) 
    299          
    300         for name,value in self.saved_state.iteritems(): 
     297 
     298        for name, value in self.saved_state.iteritems(): 
    301299            element = newdoc.createElement(str(name)) 
    302300            element.appendChild(newdoc.createTextNode(str(value))) 
    303301            state.appendChild(element) 
    304                
     302 
    305303        # State history list 
    306304        history = newdoc.createElement("history") 
    307305        top_element.appendChild(history) 
    308          
     306 
    309307        for name, value in self.state_list.iteritems(): 
    310308            history_element = newdoc.createElement('state_' + str(name)) 
    311             for state_name,state_value in value.iteritems(): 
     309            for state_name, state_value in value.iteritems(): 
    312310                state_element = newdoc.createElement(str(state_name)) 
    313311                child = newdoc.createTextNode(str(state_value)) 
    314312                state_element.appendChild(child) 
    315313                history_element.appendChild(state_element) 
    316             #history_element.appendChild(state_list_element) 
     314            # history_element.appendChild(state_list_element) 
    317315            history.appendChild(history_element) 
    318316 
    319317        # Bookmarks  bookmark_list[self.bookmark_num] = [\ 
    320         #my_time,date,state,comp_state] 
     318        # my_time,date,state,comp_state] 
    321319        bookmark = newdoc.createElement("bookmark") 
    322320        top_element.appendChild(bookmark) 
    323         item_list = ['time','date','state','comp_state'] 
     321        item_list = ['time', 'date', 'state', 'comp_state'] 
    324322        for name, value_list in self.bookmark_list.iteritems(): 
    325             element = newdoc.createElement('mark_'+ str(name)) 
    326             _,date,state,comp_state = value_list 
     323            element = newdoc.createElement('mark_' + str(name)) 
     324            _, date, state, comp_state = value_list 
    327325            time_element = newdoc.createElement('time') 
    328326            time_element.appendChild(newdoc.createTextNode(str(value_list[0]))) 
     
    354352        else: 
    355353            return newdoc 
    356          
     354 
    357355    def fromXML(self, file=None, node=None): 
    358356        """ 
    359357        Load invariant states from a file 
    360              
     358 
    361359        : param file: .inv file 
    362         : param node: node of a XML document to read from        
     360        : param node: node of a XML document to read from 
    363361        """ 
    364362        if file is not None: 
     
    366364            msg += " format for invariant files" 
    367365            raise RuntimeError, msg 
    368          
     366 
    369367        if node.get('version')\ 
    370368            and node.get('version') == '1.0': 
     
    384382                    msg += " timestamp\n %s" % sys.exc_value 
    385383                    logging.error(msg) 
    386              
     384 
    387385            # Parse bookmarks 
    388386            entry_bookmark = get_content('ns:bookmark', node) 
     
    391389                temp_state = {} 
    392390                temp_bookmark = {} 
    393                 entry = get_content('ns:mark_%s' % ind, entry_bookmark)  
    394                                  
     391                entry = get_content('ns:mark_%s' % ind, entry_bookmark) 
     392 
    395393                if entry is not None: 
    396394                    my_time = get_content('ns:time', entry) 
     
    399397                    val_date = str(date.text.strip()) 
    400398                    state_entry = get_content('ns:state', entry) 
    401                     for item in list: 
    402  
     399                    for item in DEFAULT_STATE: 
    403400                        input_field = get_content('ns:%s' % item, state_entry) 
    404401                        val = str(input_field.text.strip()) 
    405402                        if input_field is not None: 
    406                             try: 
    407                                 exec "temp_state['%s'] = %s" % (item, val)       
    408                             except: 
    409                                 exec "temp_state['%s'] = '%s'" % (item, val) 
     403                            temp_state[item] = val 
    410404                    comp_entry = get_content('ns:comp_state', entry) 
    411                      
    412                     for item in list: 
     405 
     406                    for item in DEFAULT_STATE: 
    413407                        input_field = get_content('ns:%s' % item, comp_entry) 
    414408                        val = str(input_field.text.strip()) 
    415409                        if input_field is not None: 
    416                             try: 
    417                                 exec "temp_bookmark['%s'] = %s" % (item, val)       
    418                             except: 
    419                                 exec "temp_bookmark['%s'] = '%s'" % (item, val) 
     410                            temp_bookmark[item] = val 
    420411                    try: 
    421                         cmd = "self.bookmark_list[%s] = [val_time," 
    422                         cmd += "val_date,temp_state,temp_bookmark]" 
    423                         exec cmd % ind 
     412                        self.bookmark_list[ind] = [val_time, val_date, temp_state, temp_bookmark] 
    424413                    except: 
    425414                        raise "missing components of bookmarks..." 
     
    429418            for ind in range(0, len(entry_history)): 
    430419                temp_state = {} 
    431                 entry = get_content('ns:state_%s' % ind, entry_history)  
     420                entry = get_content('ns:state_%s' % ind, entry_history) 
    432421 
    433422                if entry is not None: 
    434                     for item in list: 
    435                         input_field = get_content('ns:%s' % item, entry ) 
     423                    for item in DEFAULT_STATE: 
     424                        input_field = get_content('ns:%s' % item, entry) 
    436425                        val = str(input_field.text.strip()) 
    437  
    438426                        if input_field is not None: 
    439                             try: 
    440                                 exec "temp_state['%s'] = %s" % (item, val)          
    441                             except: 
    442                                 exec "temp_state['%s'] = '%s'" % (item, val) 
    443                             finally: 
    444                                 exec "self.state_list['%s'] = temp_state" % ind  
     427                            temp_state[item] = val 
     428                            self.state_list[ind] = temp_state 
     429 
    445430            # Parse current state (ie, saved_state) 
    446             entry = get_content('ns:state', node)            
     431            entry = get_content('ns:state', node) 
    447432            if entry is not None: 
    448                 for item in list: 
     433                for item in DEFAULT_STATE: 
    449434                    input_field = get_content('ns:%s' % item, entry) 
    450435                    val = str(input_field.text.strip()) 
     
    452437                        self.set_saved_state(name=item, value=val) 
    453438            self.file = file_name 
    454              
     439 
    455440    def set_report_string(self): 
    456441        """ 
    457         Get the values (strings) from __str__ for report  
     442        Get the values (strings) from __str__ for report 
    458443        """ 
    459444        strings = self.__str__() 
    460      
     445 
    461446        # default string values 
    462         for num in range (1, 19): 
     447        for num in range(1, 19): 
    463448            exec "s_%s = 'NA'" % str(num) 
    464449        lines = strings.split('\n') 
     
    491476                    s_10 = item[1] 
    492477                elif item[0] == "volume fraction": 
    493                     val=item[1].split("+-")[0].strip() 
     478                    val = item[1].split("+-")[0].strip() 
    494479                    error = item[1].split("+-")[1].strip() 
    495480                    s_17 = val + " &plusmn; " + error 
     
    499484                    s_18 = val + " &plusmn; " + error 
    500485                elif item[0].split("(")[0].strip() == "power low": 
    501                     s_11 = item[0]+" ="+item[1] 
     486                    s_11 = item[0] + " =" + item[1] 
    502487                elif item[0].split("(")[0].strip() == "power high": 
    503                     s_12 = item[0]+" ="+item[1] 
     488                    s_12 = item[0] + " =" + item[1] 
    504489                elif item[0].split("[")[0].strip() == "Q* from low Q extrapolation": 
    505                     #looks messy but this way the symbols +_ and % work on html 
     490                    # looks messy but this way the symbols +_ and % work on html 
    506491                    val = item[1].split("+-")[0].strip() 
    507492                    error = item[1].split("+-")[1].strip() 
     
    532517 
    533518        # make plot image 
    534         self.set_plot_state(extra_high=bool_0[1],extra_low=bool_1[1]) 
     519        self.set_plot_state(extra_high=bool_0[1], extra_low=bool_1[1]) 
    535520        # get ready for report with setting all the html strings 
    536521        self.report_str = str(self.template_str) % (s_1, s_2, 
    537                                         s_3, s_4, s_5, s_6, s_7, s_8, 
    538                                     s_9, s_10, s_11, s_12, s_13, s_14, s_15, 
    539                                         s_16, s_17, s_18, file_name, "%s") 
     522                                                    s_3, s_4, s_5, s_6, s_7, s_8, 
     523                                                    s_9, s_10, s_11, s_12, s_13, s_14, s_15, 
     524                                                    s_16, s_17, s_18, file_name, "%s") 
    540525 
    541526    def _check_html_format(self, name): 
     
    545530        if name.count('%'): 
    546531            name = name.replace('%', '&#37') 
    547          
     532 
    548533        return name 
    549          
     534 
    550535    def set_saved_state(self, name, value): 
    551536        """ 
    552         Set the state list  
    553                      
     537        Set the state list 
     538 
    554539        : param name: name of the state component 
    555540        : param value: value of the state component 
    556541        """ 
    557         rb_list = [['power_law_low','guinier'], 
    558                    ['fit_enable_low','fix_enable_low'], 
    559                    ['fit_enable_high','fix_enable_high']] 
    560  
    561         try: 
    562             if value == None or value.lstrip().rstrip() == '': 
    563                 exec "self.%s = '%s'" % (name, value) 
    564                 exec "self.saved_state['%s'] = '%s'" % (name, value) 
    565             else: 
    566                 exec 'self.%s = %s' % (name, value) 
    567                 exec "self.saved_state['%s'] = %s" % (name, value) 
    568             # set the count part of radio button clicked  
    569             # False for the saved_state 
    570             for title, content in rb_list: 
    571                 if name ==  title: 
    572                     name = content  
    573                     value = False      
    574                 elif name == content: 
    575                     name = title 
    576                     value = False  
    577             exec "self.saved_state['%s'] = '%s'" % (name, value)      
    578             self.state_num = self.saved_state['state_num'] 
    579         except:            
    580             pass 
     542        rb_list = [['power_law_low', 'guinier'], 
     543                   ['fit_enable_low', 'fix_enable_low'], 
     544                   ['fit_enable_high', 'fix_enable_high']] 
     545 
     546        self.name = value 
     547        self.saved_state[name] = value 
     548        # set the count part of radio button clicked 
     549        # False for the saved_state 
     550        for title, content in rb_list: 
     551            if name == title: 
     552                name = content 
     553                value = False 
     554            elif name == content: 
     555                name = title 
     556                value = False 
     557        self.saved_state[name] = value 
     558        self.state_num = self.saved_state['state_num'] 
    581559 
    582560    def set_plot_state(self, extra_high=False, extra_low=False): 
     
    584562        Build image state that wx.html understand 
    585563        by plotting, putting it into wx.FileSystem image object 
    586          
     564 
    587565        : extrap_high,extra_low: low/high extrapolations 
    588566        are possible extra-plots 
     
    593571        from matplotlib.backends.backend_agg import FigureCanvasAgg 
    594572 
    595         #we use simple plot, not plotpanel 
    596         #make matlab figure 
     573        # we use simple plot, not plotpanel 
     574        # make matlab figure 
    597575        fig = plt.figure() 
    598576        fig.set_facecolor('w') 
    599577        graph = fig.add_subplot(111) 
    600578 
    601         #data plot 
     579        # data plot 
    602580        graph.errorbar(self.data.x, self.data.y, yerr=self.data.dy, fmt='o') 
    603         #low Q extrapolation fit plot 
     581        # low Q extrapolation fit plot 
    604582        if not extra_low == 'False': 
    605             graph.plot(self.theory_lowQ.x,self.theory_lowQ.y) 
    606         #high Q extrapolation fit plot 
     583            graph.plot(self.theory_lowQ.x, self.theory_lowQ.y) 
     584        # high Q extrapolation fit plot 
    607585        if not extra_high == 'False': 
    608             graph.plot(self.theory_highQ.x,self.theory_highQ.y) 
     586            graph.plot(self.theory_highQ.x, self.theory_highQ.y) 
    609587        graph.set_xscale("log", nonposx='clip') 
    610588        graph.set_yscale("log", nonposy='clip') 
    611         graph.set_xlabel('$\\rm{Q}(\\AA^{-1})$', fontsize = 12) 
    612         graph.set_ylabel('$\\rm{Intensity}(cm^{-1})$', fontsize = 12) 
     589        graph.set_xlabel('$\\rm{Q}(\\AA^{-1})$', fontsize=12) 
     590        graph.set_ylabel('$\\rm{Intensity}(cm^{-1})$', fontsize=12) 
    613591        canvas = FigureCanvasAgg(fig) 
    614         #actually make image 
     592        # actually make image 
    615593        canvas.draw() 
    616          
    617         #make python.Image object  
    618         #size 
     594 
     595        # make python.Image object 
     596        # size 
    619597        w, h = canvas.get_width_height() 
    620         #convert to wx.Image 
    621         wximg = wx.EmptyImage(w,h) 
    622         #wxim.SetData(img.convert('RGB').tostring() )  
    623         wximg.SetData(canvas.tostring_rgb())  
    624         #get the dynamic image for the htmlwindow 
     598        # convert to wx.Image 
     599        wximg = wx.EmptyImage(w, h) 
     600        # wxim.SetData(img.convert('RGB').tostring() ) 
     601        wximg.SetData(canvas.tostring_rgb()) 
     602        # get the dynamic image for the htmlwindow 
    625603        wximgbmp = wx.BitmapFromImage(wximg) 
    626         #store the image in wx.FileSystem Object  
     604        # store the image in wx.FileSystem Object 
    627605        wx.FileSystem.AddHandler(wx.MemoryFSHandler()) 
    628606        # use wx.MemoryFSHandler 
    629607        self.imgRAM = wx.MemoryFSHandler() 
    630         #AddFile, image can be retrieved with 'memory:filename' 
     608        # AddFile, image can be retrieved with 'memory:filename' 
    631609        self.imgRAM.AddFile('img_inv.png', wximgbmp, wx.BITMAP_TYPE_PNG) 
    632          
     610 
    633611        self.wximgbmp = 'memory:img_inv.png' 
    634612        self.image = fig 
     
    638616    Class to load a .inv invariant file 
    639617    """ 
    640     ## File type 
     618    # # File type 
    641619    type_name = "Invariant" 
    642      
    643     ## Wildcards 
     620 
     621    # # Wildcards 
    644622    type = ["Invariant file (*.inv)|*.inv", 
    645623            "SASView file (*.svs)|*.svs"] 
    646     ## List of allowed extensions 
    647     ext = ['.inv', '.INV', '.svs', 'SVS']   
    648      
     624    # # List of allowed extensions 
     625    ext = ['.inv', '.INV', '.svs', 'SVS'] 
     626 
    649627    def __init__(self, call_back, cansas=True): 
    650628        """ 
    651629        Initialize the call-back method to be called 
    652630        after we load a file 
    653          
     631 
    654632        : param call_back: call-back method 
    655633        : param cansas:  True = files will be written/read in CanSAS format 
    656                         False = write CanSAS format   
    657         """ 
    658         ## Call back method to be executed after a file is read 
     634                        False = write CanSAS format 
     635        """ 
     636        # # Call back method to be executed after a file is read 
    659637        self.call_back = call_back 
    660         ## CanSAS format flag 
     638        # # CanSAS format flag 
    661639        self.cansas = cansas 
    662640        self.state = None 
    663641 
    664642    def read(self, path): 
    665         """  
     643        """ 
    666644        Load a new invariant state from file 
    667          
     645 
    668646        : param path: file path 
    669647        : return: None 
     
    673651        else: 
    674652            return self._read_standalone(path) 
    675          
     653 
    676654    def _read_standalone(self, path): 
    677         """  
     655        """ 
    678656        Load a new invariant state from file. 
    679657        The invariant node is assumed to be the top element. 
    680          
     658 
    681659        : param path: file path 
    682660        : return: None 
     
    686664 
    687665        state.fromXML(file=path) 
    688          
     666 
    689667        # Call back to post the new state 
    690668        self.call_back(state) 
    691669        return None 
    692      
     670 
    693671    def _parse_state(self, entry): 
    694672        """ 
    695673        Read an invariant result from an XML node 
    696          
    697         : param entry: XML node to read from  
     674 
     675        : param entry: XML node to read from 
    698676        : return: InvariantState object 
    699677        """ 
     
    710688            msg = "XML document does not contain invariant" 
    711689            msg += " information.\n %s" % sys.exc_value 
    712             logging.info(msg)   
     690            logging.info(msg) 
    713691        return state 
    714      
     692 
    715693    def _read_cansas(self, path): 
    716         """  
     694        """ 
    717695        Load data and invariant information from a CanSAS XML file. 
    718          
     696 
    719697        : param path: file path 
    720         : return: Data1D object if a single SASentry was found,  
     698        : return: Data1D object if a single SASentry was found, 
    721699                    or a list of Data1D objects if multiple entries were found, 
    722700                    or None of nothing was found 
     
    726704        output = [] 
    727705        if os.path.isfile(path): 
    728             basename  = os.path.basename(path) 
     706            basename = os.path.basename(path) 
    729707            root, extension = os.path.splitext(basename) 
    730              
     708 
    731709            if  extension.lower() in self.ext or \ 
    732710                extension.lower() == '.xml': 
    733711                tree = etree.parse(path, parser=etree.ETCompatXMLParser()) 
    734         
     712 
    735713                # Check the format version number 
    736                 # Specifying the namespace will take care of  
    737                 # the file format version  
     714                # Specifying the namespace will take care of 
     715                # the file format version 
    738716                root = tree.getroot() 
    739                  
     717 
    740718                entry_list = root.xpath('/ns:SASroot/ns:SASentry', 
    741719                                        namespaces={'ns': CANSAS_NS}) 
    742                  
     720 
    743721                for entry in entry_list: 
    744                      
     722 
    745723                    sas_entry, _ = self._parse_entry(entry) 
    746724                    invstate = self._parse_state(entry) 
    747                      
    748                     #invstate could be None when .svs file is loaded 
    749                     #in this case, skip appending to output 
     725 
     726                    # invstate could be None when .svs file is loaded 
     727                    # in this case, skip appending to output 
    750728                    if invstate != None: 
    751729                        sas_entry.meta_data['invstate'] = invstate 
     
    762740            self.state = output[0].meta_data['invstate'] 
    763741            self.call_back(state=output[0].meta_data['invstate'], 
    764                           datainfo = output[0]) 
     742                           datainfo=output[0]) 
    765743            return output[0] 
    766744        else: 
    767             return output                 
    768      
     745            return output 
     746 
    769747    def get_state(self): 
    770748        return self.state 
    771      
     749 
    772750    def write(self, filename, datainfo=None, invstate=None): 
    773751        """ 
    774752        Write the content of a Data1D as a CanSAS XML file 
    775          
     753 
    776754        : param filename: name of the file to write 
    777755        : param datainfo: Data1D object 
     
    780758        # Sanity check 
    781759        if self.cansas == True: 
    782             doc = self.write_toXML(datainfo,invstate) 
     760            doc = self.write_toXML(datainfo, invstate) 
    783761            # Write the XML document 
    784762            fd = open(filename, 'w') 
     
    787765        else: 
    788766            invstate.toXML(file=filename) 
    789          
     767 
    790768    def write_toXML(self, datainfo=None, state=None): 
    791769        """ 
    792770        Write toXML, a helper for write() 
    793          
     771 
    794772        : return: xml doc 
    795773        """ 
    796774        if datainfo is None: 
    797             datainfo = sas.dataloader.data_info.Data1D(x=[], y=[])     
     775            datainfo = sas.dataloader.data_info.Data1D(x=[], y=[]) 
    798776        elif not issubclass(datainfo.__class__, sas.dataloader.data_info.Data1D): 
    799777            msg = "The cansas writer expects a Data1D" 
    800778            msg += " instance: %s" % str(datainfo.__class__.__name__) 
    801779            raise RuntimeError, msg 
    802         #make sure title and data run is filled up. 
     780        # make sure title and data run is filled up. 
    803781        if datainfo.title == None or datainfo.title == '': 
    804782            datainfo.title = datainfo.name 
    805         if datainfo.run_name == None or datainfo.run_name == {}:  
     783        if datainfo.run_name == None or datainfo.run_name == {}: 
    806784            datainfo.run = [str(datainfo.name)] 
    807785            datainfo.run_name[0] = datainfo.name 
     
    810788        # Add the invariant information to the XML document 
    811789        if state is not None: 
    812             doc = state.toXML(datainfo.name,doc=doc, entry_node=sasentry) 
     790            doc = state.toXML(datainfo.name, doc=doc, entry_node=sasentry) 
    813791        return doc 
    814792 
Note: See TracChangeset for help on using the changeset viewer.