Ignore:
Timestamp:
Mar 6, 2015 2:05:50 PM (9 years ago)
Author:
Doucet, Mathieu <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:
b1e609c
Parents:
c1c14ba
Message:

pylint fixes

File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/sas/perspectives/pr/inversion_state.py

    rc4f6851 r8b21fa7  
    55#This software was developed by the University of Tennessee as part of the 
    66#Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
    7 #project funded by the US National Science Foundation.  
     7#project funded by the US National Science Foundation. 
    88# 
    99#See the license text in license.txt 
     
    2626 
    2727# Translation of names between stored and object data 
    28 ## List of P(r) inversion inputs  
    29 in_list =  [["nterms",      "nfunc"], 
    30            ["d_max",        "d_max"], 
    31            ["alpha",        "alpha"], 
    32            ["slit_width",   "width"], 
    33            ["slit_height",  "height"], 
    34            ["qmin",         "qmin"], 
    35            ["qmax",         "qmax"], 
    36            ["estimate_bck", "estimate_bck"]]                       
     28## List of P(r) inversion inputs 
     29in_list = [["nterms", "nfunc"], 
     30           ["d_max", "d_max"], 
     31           ["alpha", "alpha"], 
     32           ["slit_width", "width"], 
     33           ["slit_height", "height"], 
     34           ["qmin", "qmin"], 
     35           ["qmax", "qmax"], 
     36           ["estimate_bck", "estimate_bck"]] 
    3737 
    3838## List of P(r) inversion outputs 
    3939out_list = [["elapsed", "elapsed"], 
    40            ["rg",      "rg"], 
    41            ["iq0",    "iq0"], 
    42            ["bck",    "bck"], 
    43            ["chi2",    "chi2"], 
    44            ["osc",    "osc"], 
    45            ["pos",    "pos"], 
    46            ["pos_err", "pos_err"], 
    47            ["alpha_estimate", "alpha_estimate"], 
    48            ["nterms_estimate", "nterms_estimate"]] 
     40            ["rg", "rg"], 
     41            ["iq0", "iq0"], 
     42            ["bck", "bck"], 
     43            ["chi2", "chi2"], 
     44            ["osc", "osc"], 
     45            ["pos", "pos"], 
     46            ["pos_err", "pos_err"], 
     47            ["alpha_estimate", "alpha_estimate"], 
     48            ["nterms_estimate", "nterms_estimate"]] 
    4949 
    5050class InversionState(object): 
     
    5656        Default values 
    5757        """ 
    58         # Input  
    59         self.file  = None 
     58        # Input 
     59        self.file = None 
    6060        self.estimate_bck = False 
    6161        self.timestamp = time.time() 
    62          
     62 
    6363        # Inversion parameters 
    6464        self.nfunc = None 
    6565        self.d_max = None 
    6666        self.alpha = None 
    67          
     67 
    6868        # Slit parameters 
    6969        self.height = None 
    70         self.width  = None 
    71          
     70        self.width = None 
     71 
    7272        # Q range 
    73         self.qmin  = None 
    74         self.qmax  = None 
    75          
     73        self.qmin = None 
     74        self.qmax = None 
     75 
    7676        # Outputs 
    7777        self.elapsed = None 
    78         self.rg    = None 
    79         self.iq0   = None 
    80         self.bck   = None 
    81         self.chi2  = None 
    82         self.osc   = None 
    83         self.pos   = None 
     78        self.rg = None 
     79        self.iq0 = None 
     80        self.bck = None 
     81        self.chi2 = None 
     82        self.osc = None 
     83        self.pos = None 
    8484        self.pos_err = None 
    85          
     85 
    8686        # Estimates 
    8787        self.alpha_estimate = None 
    8888        self.nterms_estimate = None 
    89          
     89 
    9090        # Data 
    91         self.q       = None 
    92         self.iq_obs  = None 
     91        self.q = None 
     92        self.iq_obs = None 
    9393        self.iq_calc = None 
    94          
     94 
    9595        # Coefficients 
    9696        self.coefficients = None 
    9797        self.covariance = None 
    98      
     98 
    9999    def __str__(self): 
    100100        """ 
    101101        Pretty print 
    102          
     102 
    103103        :return: string representing the state 
    104          
    105         """ 
    106         state  = "File:         %s\n" % self.file 
     104 
     105        """ 
     106        state = "File:         %s\n" % self.file 
    107107        state += "Timestamp:    %s\n" % self.timestamp 
    108108        state += "Estimate bck: %s\n" % str(self.estimate_bck) 
     
    110110        state += "D_max:        %s\n" % str(self.d_max) 
    111111        state += "Alpha:        %s\n" % str(self.alpha) 
    112          
     112 
    113113        state += "Slit height:  %s\n" % str(self.height) 
    114114        state += "Slit width:   %s\n" % str(self.width) 
    115          
     115 
    116116        state += "Qmin:         %s\n" % str(self.qmin) 
    117117        state += "Qmax:         %s\n" % str(self.qmax) 
    118          
     118 
    119119        state += "\nEstimates:\n" 
    120120        state += "  Alpha:      %s\n" % str(self.alpha_estimate) 
    121121        state += "  Nterms:     %s\n" % str(self.nterms_estimate) 
    122          
     122 
    123123        state += "\nOutputs:\n" 
    124124        state += "  Elapsed:    %s\n" % str(self.elapsed) 
     
    130130        state += "  Positive:   %s\n" % str(self.pos) 
    131131        state += "  1-sigma pos:%s\n" % str(self.pos_err) 
    132          
     132 
    133133        return state 
    134          
     134 
    135135    def toXML(self, file="pr_state.prv", doc=None, entry_node=None): 
    136136        """ 
    137137        Writes the state of the InversionControl panel to file, as XML. 
    138          
     138 
    139139        Compatible with standalone writing, or appending to an 
    140140        already existing XML document. In that case, the XML document 
    141         is required. An optional entry node in the XML document  
     141        is required. An optional entry node in the XML document 
    142142        may also be given. 
    143          
     143 
    144144        :param file: file to write to 
    145145        :param doc: XML document object [optional] 
    146         :param entry_node: XML node within the XML document at which  
     146        :param entry_node: XML node within the XML document at which 
    147147            we will append the data [optional] 
    148          
     148 
    149149        """ 
    150150        #TODO: Get this to work 
     
    154154        if doc is None: 
    155155            impl = getDOMImplementation() 
    156          
    157             doc_type = impl.createDocumentType(PRNODE_NAME, "1.0", "1.0")      
    158          
     156 
     157            doc_type = impl.createDocumentType(PRNODE_NAME, "1.0", "1.0") 
     158 
    159159            newdoc = impl.createDocument(None, PRNODE_NAME, doc_type) 
    160160            top_element = newdoc.documentElement 
     
    167167            else: 
    168168                entry_node.appendChild(top_element) 
    169              
     169 
    170170        attr = newdoc.createAttribute("version") 
    171171        attr.nodeValue = '1.0' 
    172172        top_element.setAttributeNode(attr) 
    173          
     173 
    174174        # File name 
    175175        element = newdoc.createElement("filename") 
     
    179179            element.appendChild(newdoc.createTextNode(str(file))) 
    180180        top_element.appendChild(element) 
    181          
     181 
    182182        element = newdoc.createElement("timestamp") 
    183183        element.appendChild(newdoc.createTextNode(time.ctime(self.timestamp))) 
     
    186186        element.setAttributeNode(attr) 
    187187        top_element.appendChild(element) 
    188          
     188 
    189189        # Inputs 
    190190        inputs = newdoc.createElement("inputs") 
    191191        top_element.appendChild(inputs) 
    192          
     192 
    193193        for item in in_list: 
    194194            element = newdoc.createElement(item[0]) 
    195195            element.appendChild(newdoc.createTextNode(str(getattr(self, item[1])))) 
    196196            inputs.appendChild(element) 
    197                
     197 
    198198        # Outputs 
    199199        outputs = newdoc.createElement("outputs") 
    200200        top_element.appendChild(outputs) 
    201          
     201 
    202202        for item in out_list: 
    203203            element = newdoc.createElement(item[0]) 
    204204            element.appendChild(newdoc.createTextNode(str(getattr(self, item[1])))) 
    205205            outputs.appendChild(element) 
    206                      
     206 
    207207        # Save output coefficients and its covariance matrix 
    208208        element = newdoc.createElement("coefficients") 
     
    212212        element.appendChild(newdoc.createTextNode(str(self.covariance))) 
    213213        outputs.appendChild(element) 
    214                      
     214 
    215215        # Save the file 
    216216        if doc is None: 
     
    225225        """ 
    226226        Load a P(r) inversion state from a file 
    227          
     227 
    228228        :param file: .prv file 
    229229        :param node: node of a XML document to read from 
    230          
     230 
    231231        """ 
    232232        if file is not None: 
     
    234234            msg += " format for P(r) files" 
    235235            raise RuntimeError, msg 
    236              
     236 
    237237        if node.get('version') and node.get('version') == '1.0': 
    238              
     238 
    239239            # Get file name 
    240240            entry = get_content('ns:filename', node) 
    241241            if entry is not None: 
    242242                self.file = entry.text.strip() 
    243              
     243 
    244244            # Get time stamp 
    245245            entry = get_content('ns:timestamp', node) 
     
    251251                    msg += "timestamp\n %s" % sys.exc_value 
    252252                    logging.error(msg) 
    253              
     253 
    254254            # Parse inversion inputs 
    255255            entry = get_content('ns:inputs', node) 
     
    265265                if input_field is not None: 
    266266                    try: 
    267                         self.estimate_bck = input_field.text.strip()=='True' 
     267                        self.estimate_bck = input_field.text.strip() == 'True' 
    268268                    except: 
    269269                        self.estimate_bck = False 
    270                      
     270 
    271271            # Parse inversion outputs 
    272272            entry = get_content('ns:outputs', node) 
     
    280280                        except: 
    281281                            setattr(self, item[1], None) 
    282              
     282 
    283283                # Look for coefficients 
    284284                # Format is [value, value, value, value] 
     
    286286                if coeff is not None: 
    287287                    # Remove brackets 
    288                     c_values = coeff.text.strip().replace('[','') 
    289                     c_values = c_values.replace(']','') 
     288                    c_values = coeff.text.strip().replace('[', '') 
     289                    c_values = c_values.replace(']', '') 
    290290                    toks = c_values.split() 
    291291                    self.coefficients = [] 
     
    308308                        logging.error(err_msg) 
    309309                        self.coefficients = None 
    310                  
     310 
    311311                # Look for covariance matrix 
    312312                # Format is [ [value, value], [value, value] ] 
     
    320320                        if len(row) == 0: continue 
    321321                        # Remove end bracket 
    322                         row = row.replace(']','') 
     322                        row = row.replace(']', '') 
    323323                        c_values = row.split() 
    324324                        cov_row = [] 
     
    345345                        logging.error(err_msg) 
    346346                        self.covariance = None 
    347      
     347 
    348348class Reader(CansasReader): 
    349349    """ 
     
    352352    ## File type 
    353353    type_name = "P(r)" 
    354      
     354 
    355355    ## Wildcards 
    356356    type = ["P(r) files (*.prv)|*.prv", 
    357357            "SASView files (*.svs)|*.svs"] 
    358358    ## List of allowed extensions 
    359     ext = ['.prv', '.PRV', '.svs', '.SVS']   
    360      
     359    ext = ['.prv', '.PRV', '.svs', '.SVS'] 
     360 
    361361    def __init__(self, call_back, cansas=True): 
    362362        """ 
    363363        Initialize the call-back method to be called 
    364364        after we load a file 
    365          
     365 
    366366        :param call_back: call-back method 
    367367        :param cansas:  True = files will be written/read in CanSAS format 
    368368                        False = write CanSAS format 
    369              
     369 
    370370        """ 
    371371        ## Call back method to be executed after a file is read 
     
    374374        self.cansas = cansas 
    375375        self.state = None 
    376          
     376 
    377377    def read(self, path): 
    378         """  
     378        """ 
    379379        Load a new P(r) inversion state from file 
    380          
     380 
    381381        :param path: file path 
    382          
     382 
    383383        :return: None 
    384          
    385         """ 
    386         if self.cansas==True: 
     384 
     385        """ 
     386        if self.cansas == True: 
    387387            return self._read_cansas(path) 
    388388        else: 
    389389            return self._read_standalone(path) 
    390          
     390 
    391391    def _read_standalone(self, path): 
    392         """  
     392        """ 
    393393        Load a new P(r) inversion state from file. 
    394394        The P(r) node is assumed to be the top element. 
    395          
     395 
    396396        :param path: file path 
    397          
     397 
    398398        :return: None 
    399          
     399 
    400400        """ 
    401401        # Read the new state from file 
    402402        state = InversionState() 
    403403        state.fromXML(file=path) 
    404          
     404 
    405405        # Call back to post the new state 
    406406        self.state = state 
    407407        #self.call_back(state) 
    408408        return None 
    409      
     409 
    410410    def _parse_prstate(self, entry): 
    411411        """ 
    412412        Read a p(r) inversion result from an XML node 
    413          
    414         :param entry: XML node to read from  
    415          
     413 
     414        :param entry: XML node to read from 
     415 
    416416        :return: InversionState object 
    417          
     417 
    418418        """ 
    419419        state = None 
    420          
     420 
    421421        # Locate the P(r) node 
    422422        try: 
    423423            nodes = entry.xpath('ns:%s' % PRNODE_NAME, 
    424424                                namespaces={'ns': CANSAS_NS}) 
    425             if nodes !=[]: 
     425            if nodes != []: 
    426426                # Create an empty state 
    427                 state =  InversionState() 
     427                state = InversionState() 
    428428                state.fromXML(node=nodes[0]) 
    429429        except: 
     
    431431            msg += "information.\n %s" % sys.exc_value 
    432432            logging.info(msg) 
    433              
     433 
    434434        return state 
    435      
     435 
    436436    def _read_cansas(self, path): 
    437         """  
     437        """ 
    438438        Load data and P(r) information from a CanSAS XML file. 
    439          
     439 
    440440        :param path: file path 
    441          
    442         :return: Data1D object if a single SASentry was found,  
     441 
     442        :return: Data1D object if a single SASentry was found, 
    443443                    or a list of Data1D objects if multiple entries were found, 
    444444                    or None of nothing was found 
    445                      
     445 
    446446        :raise RuntimeError: when the file can't be opened 
    447447        :raise ValueError: when the length of the data vectors are inconsistent 
    448          
     448 
    449449        """ 
    450450        output = [] 
    451          
     451 
    452452        if os.path.isfile(path): 
    453             basename  = os.path.basename(path) 
     453            basename = os.path.basename(path) 
    454454            root, extension = os.path.splitext(basename) 
    455455            #TODO: eventually remove the check for .xml once 
    456456            # the P(r) writer/reader is truly complete. 
    457457            if  extension.lower() in self.ext or extension.lower() == '.xml': 
    458                  
     458 
    459459                tree = etree.parse(path, parser=etree.ETCompatXMLParser()) 
    460460                # Check the format version number 
     
    462462                #format version  
    463463                root = tree.getroot() 
    464                  
     464 
    465465                entry_list = root.xpath('/ns:SASroot/ns:SASentry', 
    466466                                        namespaces={'ns': CANSAS_NS}) 
     
    477477        else: 
    478478            raise RuntimeError, "%s is not a file" % path 
    479          
     479 
    480480        # Return output consistent with the loader's api 
    481481        if len(output) == 0: 
     
    483483        elif len(output) == 1: 
    484484            # Call back to post the new state 
    485             self.call_back(output[0].meta_data['prstate'], datainfo = output[0]) 
     485            self.call_back(output[0].meta_data['prstate'], datainfo=output[0]) 
    486486            #self.state = output[0].meta_data['prstate'] 
    487487            return output[0] 
    488488        else: 
    489             return output                 
    490      
    491      
     489            return output 
     490 
     491 
    492492    def write(self, filename, datainfo=None, prstate=None): 
    493493        """ 
    494494        Write the content of a Data1D as a CanSAS XML file 
    495          
     495 
    496496        :param filename: name of the file to write 
    497497        :param datainfo: Data1D object 
    498498        :param prstate: InversionState object 
    499          
     499 
    500500        """ 
    501501        # Sanity check 
    502502        if self.cansas == True: 
    503             doc = self.write_toXML(datainfo, prstate)         
     503            doc = self.write_toXML(datainfo, prstate) 
    504504            # Write the XML document 
    505505            fd = open(filename, 'w') 
     
    508508        else: 
    509509            prstate.toXML(file=filename) 
    510          
     510 
    511511    def write_toXML(self, datainfo=None, state=None): 
    512512        """ 
    513513        Write toXML, a helper for write() 
    514          
     514 
    515515        : return: xml doc 
    516516        """ 
    517517        if datainfo is None: 
    518             datainfo = Data1D(x=[], y=[])     
     518            datainfo = Data1D(x=[], y=[]) 
    519519        elif not issubclass(datainfo.__class__, Data1D): 
    520520            msg = "The cansas writer expects a Data1D " 
    521521            msg += "instance: %s" % str(datainfo.__class__.__name__) 
    522522            raise RuntimeError, msg 
    523      
     523 
    524524        # Create basic XML document 
    525525        doc, sasentry = self._to_xml_doc(datainfo) 
    526          
     526 
    527527        # Add the invariant information to the XML document 
    528528        if state is not None: 
    529529            doc = state.toXML(doc=doc, entry_node=sasentry) 
    530              
    531         return doc  
    532      
     530 
     531        return doc 
Note: See TracChangeset for help on using the changeset viewer.