Changeset 278ddee in sasview for src/sas/sascalc


Ignore:
Timestamp:
Apr 11, 2017 9:51:05 AM (7 years ago)
Author:
krzywon
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.2.2, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
beba407
Parents:
7f75a3f (diff), 97c60f8 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
git-author:
Jeff Krzywon <krzywon@…> (04/11/17 09:51:05)
git-committer:
krzywon <krzywon@…> (04/11/17 09:51:05)
Message:

Merge branch 'master' into ticket-876

# Conflicts:
# src/sas/sascalc/dataloader/readers/ascii_reader.py
# src/sas/sascalc/dataloader/readers/xml_reader.py

Location:
src/sas/sascalc
Files:
1 added
27 edited

Legend:

Unmodified
Added
Removed
  • src/sas/sascalc/calculator/kiessig_calculator.py

    rb699768 r235f514  
    4949            return None 
    5050        # check if delta_q is zero 
    51         if dq == 0.0 or dq == None: 
     51        if dq == 0.0 or dq is None: 
    5252            return None 
    5353        else: 
  • src/sas/sascalc/calculator/resolution_calculator.py

    r9a5097c r7432acb  
    1515import sys 
    1616import logging 
     17 
     18logger = logging.getLogger(__name__) 
    1719 
    1820#Plank's constant in cgs unit 
     
    606608        a_value *= 1.0E-16 
    607609        # if lamda is give (broad meanning of A)  return 2* lamda^2 * A 
    608         if lamda != None: 
     610        if lamda is not None: 
    609611            a_value *= (4 * lamda * lamda) 
    610612        return a_value 
     
    10061008            detector_offset = self.sample2detector_distance[1] 
    10071009        except: 
    1008             logging.error(sys.exc_value) 
     1010            logger.error(sys.exc_value) 
    10091011 
    10101012        # detector size in [no of pix_x,no of pix_y] 
     
    10931095            output.qy_data = qy_value 
    10941096        except: 
    1095             logging.error(sys.exc_value) 
     1097            logger.error(sys.exc_value) 
    10961098 
    10971099        return output 
  • src/sas/sascalc/calculator/sas_gen.py

    r9a5097c r7432acb  
    1212import sys 
    1313import logging 
     14 
     15logger = logging.getLogger(__name__) 
    1416 
    1517MFACTOR_AM = 2.853E-12 
     
    9597        :Param volume: pixel volume [float] 
    9698        """ 
    97         if self.data_vol == None: 
     99        if self.data_vol is None: 
    98100            raise 
    99101        self.data_vol = volume 
     
    117119        pos_z = self.data_z 
    118120        len_x = len(pos_x) 
    119         if self.is_avg == None: 
     121        if self.is_avg is None: 
    120122            len_x *= -1 
    121123            pos_x, pos_y, pos_z = transform_center(pos_x, pos_y, pos_z) 
     
    255257        self.sld_n = np.zeros(length) 
    256258 
    257         if omfdata.mx == None: 
     259        if omfdata.mx is None: 
    258260            self.mx = np.zeros(length) 
    259         if omfdata.my == None: 
     261        if omfdata.my is None: 
    260262            self.my = np.zeros(length) 
    261         if omfdata.mz == None: 
     263        if omfdata.mz is None: 
    262264            self.mz = np.zeros(length) 
    263265 
     
    285287                mask = (x_dir2 + y_dir2 + z_dir2) <= 1.0 
    286288            except: 
    287                 logging.error(sys.exc_value) 
     289                logger.error(sys.exc_value) 
    288290        self.output = MagSLD(self.pos_x[mask], self.pos_y[mask], 
    289291                             self.pos_z[mask], self.sld_n[mask], 
     
    394396                except: 
    395397                    # Skip non-data lines 
    396                     logging.error(sys.exc_value) 
     398                    logger.error(sys.exc_value) 
    397399                #Reading Header; Segment count ignored 
    398400                s_line = line.split(":", 1) 
     
    589591                        z_lines.append(z_line) 
    590592                except: 
    591                     logging.error(sys.exc_value) 
     593                    logger.error(sys.exc_value) 
    592594 
    593595            output = MagSLD(pos_x, pos_y, pos_z, sld_n, sld_mx, sld_my, sld_mz) 
     
    683685                    except: 
    684686                        # Skip non-data lines 
    685                         logging.error(sys.exc_value) 
     687                        logger.error(sys.exc_value) 
    686688            output = MagSLD(pos_x, pos_y, pos_z, sld_n, 
    687689                            sld_mx, sld_my, sld_mz) 
     
    689691            output.set_pix_type('pixel') 
    690692            output.set_pixel_symbols('pixel') 
    691             if vol_pix != None: 
     693            if vol_pix is not None: 
    692694                output.set_pixel_volumes(vol_pix) 
    693695            return output 
     
    701703        :Param data: MagSLD data object 
    702704        """ 
    703         if path == None: 
     705        if path is None: 
    704706            raise ValueError, "Missing the file path." 
    705         if data == None: 
     707        if data is None: 
    706708            raise ValueError, "Missing the data to save." 
    707709        x_val = data.pos_x 
     
    711713        length = len(x_val) 
    712714        sld_n = data.sld_n 
    713         if sld_n == None: 
     715        if sld_n is None: 
    714716            sld_n = np.zeros(length) 
    715717        sld_mx = data.sld_mx 
    716         if sld_mx == None: 
     718        if sld_mx is None: 
    717719            sld_mx = np.zeros(length) 
    718720            sld_my = np.zeros(length) 
     
    865867        self.sld_theta = None 
    866868        self.pix_symbol = None 
    867         if sld_mx != None and sld_my != None and sld_mz != None: 
     869        if sld_mx is not None and sld_my is not None and sld_mz is not None: 
    868870            self.set_sldms(sld_mx, sld_my, sld_mz) 
    869871        self.set_nodes() 
     
    933935        :Params pixel: str; pixel or atomic symbol, or array of strings 
    934936        """ 
    935         if self.sld_n == None: 
     937        if self.sld_n is None: 
    936938            return 
    937939        if symbol.__class__.__name__ == 'str': 
     
    945947        :Params pixel: str; pixel or atomic symbol, or array of strings 
    946948        """ 
    947         if self.sld_n == None: 
     949        if self.sld_n is None: 
    948950            return 
    949951        if vol.__class__.__name__ == 'ndarray': 
  • src/sas/sascalc/data_util/calcthread.py

    r934ce649 r7432acb  
    88import traceback 
    99import sys 
     10import logging 
    1011 
    1112if sys.platform.count("darwin") > 0: 
     
    2122    from time import clock 
    2223    from time import sleep 
     24 
     25logger = logging.getLogger(__name__) 
    2326 
    2427 
     
    202205    def update(self, **kwargs): 
    203206        """Update GUI with the lastest results from the current work unit.""" 
    204         if self.updatefn != None and clock() > self._time_for_update: 
     207        if self.updatefn is not None and clock() > self._time_for_update: 
    205208            self._lock.acquire() 
    206209            self._time_for_update = clock() + self._delay 
     
    218221    def complete(self, **kwargs): 
    219222        """Update the GUI with the completed results from a work unit.""" 
    220         if self.completefn != None: 
     223        if self.completefn is not None: 
    221224            self.completefn(**kwargs) 
    222225            sleep(self.yieldtime) 
     
    243246            except Exception: 
    244247                pass 
    245         import logging 
    246         logging.error(traceback.format_exc()) 
     248        logger.error(traceback.format_exc()) 
    247249        #print 'CalcThread exception', 
    248250 
  • src/sas/sascalc/data_util/qsmearing.py

    r9a5097c r235f514  
    4242    # This checks for 2D data (does not throw exception because fail is common) 
    4343    if  data.__class__.__name__ not in ['Data1D', 'Theory1D']: 
    44         if data == None: 
     44        if data is None: 
    4545            return None 
    46         elif data.dqx_data == None or data.dqy_data == None: 
     46        elif data.dqx_data is None or data.dqy_data is None: 
    4747            return None 
    4848        return PySmear2D(data) 
  • src/sas/sascalc/dataloader/data_info.py

    r9a5097c r7432acb  
    353353    details = None 
    354354    ## SESANS zacceptance 
    355     zacceptance = None 
     355    zacceptance = (0,"") 
     356    yacceptance = (0,"") 
    356357 
    357358    def __init__(self): 
     
    805806            # create zero vector 
    806807            dy_other = other.dy 
    807             if other.dy == None or (len(other.dy) != len(other.y)): 
     808            if other.dy is None or (len(other.dy) != len(other.y)): 
    808809                dy_other = np.zeros(len(other.y)) 
    809810 
    810811        # Check that we have errors, otherwise create zero vector 
    811812        dy = self.dy 
    812         if self.dy == None or (len(self.dy) != len(self.y)): 
     813        if self.dy is None or (len(self.dy) != len(self.y)): 
    813814            dy = np.zeros(len(self.y)) 
    814815 
     
    821822        dy, dy_other = self._validity_check(other) 
    822823        result = self.clone_without_data(len(self.x)) 
    823         if self.dxw == None: 
     824        if self.dxw is None: 
    824825            result.dxw = None 
    825826        else: 
    826827            result.dxw = np.zeros(len(self.x)) 
    827         if self.dxl == None: 
     828        if self.dxl is None: 
    828829            result.dxl = None 
    829830        else: 
     
    883884        self._validity_check_union(other) 
    884885        result = self.clone_without_data(len(self.x) + len(other.x)) 
    885         if self.dy == None or other.dy is None: 
     886        if self.dy is None or other.dy is None: 
    886887            result.dy = None 
    887888        else: 
    888889            result.dy = np.zeros(len(self.x) + len(other.x)) 
    889         if self.dx == None or other.dx is None: 
     890        if self.dx is None or other.dx is None: 
    890891            result.dx = None 
    891892        else: 
    892893            result.dx = np.zeros(len(self.x) + len(other.x)) 
    893         if self.dxw == None or other.dxw is None: 
     894        if self.dxw is None or other.dxw is None: 
    894895            result.dxw = None 
    895896        else: 
    896897            result.dxw = np.zeros(len(self.x) + len(other.x)) 
    897         if self.dxl == None or other.dxl is None: 
     898        if self.dxl is None or other.dxl is None: 
    898899            result.dxl = None 
    899900        else: 
     
    906907        result.y = np.append(self.y, other.y) 
    907908        result.y = result.y[ind] 
    908         if result.dy != None: 
     909        if result.dy is not None: 
    909910            result.dy = np.append(self.dy, other.dy) 
    910911            result.dy = result.dy[ind] 
     
    10291030            # Check that the scales match 
    10301031            err_other = other.err_data 
    1031             if other.err_data == None or \ 
     1032            if other.err_data is None or \ 
    10321033                (len(other.err_data) != len(other.data)): 
    10331034                err_other = np.zeros(len(other.data)) 
     
    10351036        # Check that we have errors, otherwise create zero vector 
    10361037        err = self.err_data 
    1037         if self.err_data == None or \ 
     1038        if self.err_data is None or \ 
    10381039            (len(self.err_data) != len(self.data)): 
    10391040            err = np.zeros(len(other.data)) 
     
    10501051        dy, dy_other = self._validity_check(other) 
    10511052        result = self.clone_without_data(np.size(self.data)) 
    1052         if self.dqx_data == None or self.dqy_data == None: 
     1053        if self.dqx_data is None or self.dqy_data is None: 
    10531054            result.dqx_data = None 
    10541055            result.dqy_data = None 
     
    11241125        result.ymin = self.ymin 
    11251126        result.ymax = self.ymax 
    1126         if self.dqx_data == None or self.dqy_data == None or \ 
    1127                 other.dqx_data == None or other.dqy_data == None: 
     1127        if self.dqx_data is None or self.dqy_data is None or \ 
     1128                other.dqx_data is None or other.dqy_data is None: 
    11281129            result.dqx_data = None 
    11291130            result.dqy_data = None 
  • src/sas/sascalc/dataloader/loader.py

    r7f75a3f r278ddee  
    3434from readers import cansas_reader_HDF5 
    3535 
     36 
     37logger = logging.getLogger(__name__) 
    3638 
    3739class Registry(ExtensionRegistry): 
     
    114116            msg = "DataLoader couldn't locate DataLoader plugin folder." 
    115117            msg += """ "%s" does not exist""" % dir 
    116             logging.warning(msg) 
     118            logger.warning(msg) 
    117119            return readers_found 
    118120 
     
    132134                        msg = "Loader: Error importing " 
    133135                        msg += "%s\n  %s" % (item, sys.exc_value) 
    134                         logging.error(msg) 
     136                        logger.error(msg) 
    135137 
    136138                # Process zip files 
     
    154156                                msg = "Loader: Error importing" 
    155157                                msg += " %s\n  %s" % (mfile, sys.exc_value) 
    156                                 logging.error(msg) 
     158                                logger.error(msg) 
    157159 
    158160                    except: 
    159161                        msg = "Loader: Error importing " 
    160162                        msg += " %s\n  %s" % (item, sys.exc_value) 
    161                         logging.error(msg) 
     163                        logger.error(msg) 
    162164 
    163165        return readers_found 
     
    205207                msg = "Loader: Error accessing" 
    206208                msg += " Reader in %s\n  %s" % (module.__name__, sys.exc_value) 
    207                 logging.error(msg) 
     209                logger.error(msg) 
    208210        return reader_found 
    209211 
     
    238240            msg = "Loader: Error accessing Reader " 
    239241            msg += "in %s\n  %s" % (loader.__name__, sys.exc_value) 
    240             logging.error(msg) 
     242            logger.error(msg) 
    241243        return reader_found 
    242244 
     
    283285                msg = "Loader: Error accessing Reader" 
    284286                msg += " in %s\n  %s" % (module.__name__, sys.exc_value) 
    285                 logging.error(msg) 
     287                logger.error(msg) 
    286288        return reader_found 
    287289 
  • src/sas/sascalc/dataloader/manipulations.py

    rdd11014 r7432acb  
    210210            y[i_q] += frac * data[npts] 
    211211 
    212             if err_data == None or err_data[npts] == 0.0: 
     212            if err_data is None or err_data[npts] == 0.0: 
    213213                if data[npts] < 0: 
    214214                    data[npts] = -data[npts] 
     
    333333                continue 
    334334            y += frac * data[npts] 
    335             if err_data == None or err_data[npts] == 0.0: 
     335            if err_data is None or err_data[npts] == 0.0: 
    336336                if data[npts] < 0: 
    337337                    data[npts] = -data[npts] 
     
    422422 
    423423        # Get the dq for resolution averaging 
    424         if data2D.dqx_data != None and data2D.dqy_data != None: 
     424        if data2D.dqx_data is not None and data2D.dqy_data is not None: 
    425425            # The pinholes and det. pix contribution present 
    426426            # in both direction of the 2D which must be subtracted when 
     
    462462 
    463463        #q_data_max = numpy.max(q_data) 
    464         if len(data2D.q_data) == None: 
     464        if len(data2D.q_data) is None: 
    465465            msg = "Circular averaging: invalid q_data: %g" % data2D.q_data 
    466466            raise RuntimeError, msg 
     
    502502            # Take dqs from data to get the q_average 
    503503            x[i_q] += frac * q_value 
    504             if err_data == None or err_data[npt] == 0.0: 
     504            if err_data is None or err_data[npt] == 0.0: 
    505505                if data_n < 0: 
    506506                    data_n = -data_n 
     
    508508            else: 
    509509                err_y[i_q] += frac * frac * err_data[npt] * err_data[npt] 
    510             if dq_data != None: 
     510            if dq_data is not None: 
    511511                # To be consistent with dq calculation in 1d reduction, 
    512512                # we need just the averages (not quadratures) because 
     
    523523                err_y[n] = -err_y[n] 
    524524            err_y[n] = math.sqrt(err_y[n]) 
    525             #if err_x != None: 
     525            #if err_x is not None: 
    526526            #    err_x[n] = math.sqrt(err_x[n]) 
    527527 
     
    532532        idx = (numpy.isfinite(y)) & (numpy.isfinite(x)) 
    533533 
    534         if err_x != None: 
     534        if err_x is not None: 
    535535            d_x = err_x[idx] / y_counts[idx] 
    536536        else: 
     
    623623            phi_bins[i_phi] += frac * data[npt] 
    624624 
    625             if err_data == None or err_data[npt] == 0.0: 
     625            if err_data is None or err_data[npt] == 0.0: 
    626626                if data_n < 0: 
    627627                    data_n = -data_n 
     
    777777 
    778778        # Get the dq for resolution averaging 
    779         if data2D.dqx_data != None and data2D.dqy_data != None: 
     779        if data2D.dqx_data is not None and data2D.dqy_data is not None: 
    780780            # The pinholes and det. pix contribution present 
    781781            # in both direction of the 2D which must be subtracted when 
     
    888888            y[i_bin] += frac * data_n 
    889889            x[i_bin] += frac * q_value 
    890             if err_data[n] == None or err_data[n] == 0.0: 
     890            if err_data[n] is None or err_data[n] == 0.0: 
    891891                if data_n < 0: 
    892892                    data_n = -data_n 
     
    895895                y_err[i_bin] += frac * frac * err_data[n] * err_data[n] 
    896896 
    897             if dq_data != None: 
     897            if dq_data is not None: 
    898898                # To be consistent with dq calculation in 1d reduction, 
    899899                # we need just the averages (not quadratures) because 
     
    925925        y_err[y_err == 0] = numpy.average(y_err) 
    926926        idx = (numpy.isfinite(y) & numpy.isfinite(y_err)) 
    927         if x_err != None: 
     927        if x_err is not None: 
    928928            d_x = x_err[idx] / y_counts[idx] 
    929929        else: 
  • src/sas/sascalc/dataloader/readers/ascii_reader.py

    r7f75a3f r235f514  
    1717import os 
    1818from sas.sascalc.dataloader.data_info import Data1D 
    19 from sas.sascalc.dataloader.loader_exceptions import FileContentsException 
    2019 
    2120# Check whether we have a converter available 
     
    129128                        if new_lentoks > 2: 
    130129                            _dy = float(toks[2]) 
    131                         has_error_dy = False if _dy == None else True 
     130                        has_error_dy = False if _dy is None else True 
    132131 
    133132                        # If a 4th row is present, consider it dx 
    134133                        if new_lentoks > 3: 
    135134                            _dx = float(toks[3]) 
    136                         has_error_dx = False if _dx == None else True 
     135                        has_error_dx = False if _dx is None else True 
    137136 
    138137                        # Delete the previously stored lines of data candidates if 
     
    174173                if not is_data: 
    175174                    msg = "ascii_reader: x has no data" 
    176                     raise FileContentsException, msg 
     175                    raise RuntimeError, msg 
    177176                # Sanity check 
    178177                if has_error_dy == True and not len(ty) == len(tdy): 
    179178                    msg = "ascii_reader: y and dy have different length" 
    180                     raise FileContentsException, msg 
     179                    raise RuntimeError, msg 
    181180                if has_error_dx == True and not len(tx) == len(tdx): 
    182181                    msg = "ascii_reader: y and dy have different length" 
    183                     raise FileContentsException, msg 
     182                    raise RuntimeError, msg 
    184183                # If the data length is zero, consider this as 
    185184                # though we were not able to read the file. 
    186185                if len(tx) == 0: 
    187                     raise FileContentsException, "ascii_reader: could not load file" 
     186                    raise RuntimeError, "ascii_reader: could not load file" 
    188187 
    189188                #Let's re-order the data to make cal. 
  • src/sas/sascalc/dataloader/readers/associations.py

    re5c09cf r959eb01  
    1818import logging 
    1919import json 
     20 
     21logger = logging.getLogger(__name__) 
    2022 
    2123FILE_NAME = 'defaults.json' 
     
    6769                    msg = "read_associations: skipping association" 
    6870                    msg += " for %s\n  %s" % (ext.lower(), sys.exc_value) 
    69                     logging.error(msg) 
     71                    logger.error(msg) 
    7072    else: 
    7173        print "Could not find reader association settings\n  %s [%s]" % (__file__, os.getcwd()) 
     
    8183    :param registry_function: function to be called to register each reader 
    8284    """ 
    83     logging.info("register_readers is now obsolete: use read_associations()") 
     85    logger.info("register_readers is now obsolete: use read_associations()") 
    8486    import abs_reader 
    8587    import ascii_reader 
  • src/sas/sascalc/dataloader/readers/cansas_constants.py

    rad4632c r63d773c  
    135135                             "Sesans": {"storeas": "content"}, 
    136136                             "zacceptance": {"storeas": "float"}, 
     137                             "yacceptance": {"storeas": "float"}, 
    137138                             "<any>" : ANY 
    138139                            } 
  • src/sas/sascalc/dataloader/readers/cansas_reader.py

    r7f75a3f r278ddee  
    3434import xml.dom.minidom 
    3535from xml.dom.minidom import parseString 
     36 
     37logger = logging.getLogger(__name__) 
    3638 
    3739PREPROCESS = "xmlpreprocess" 
     
    291293                elif tagname == 'Sesans': 
    292294                    self.current_datainfo.isSesans = bool(data_point) 
     295                elif tagname == 'yacceptance': 
     296                    self.current_datainfo.sample.yacceptance = (data_point, unit) 
    293297                elif tagname == 'zacceptance': 
    294298                    self.current_datainfo.sample.zacceptance = (data_point, unit) 
     
    809813        :param data1d: presumably a Data1D object 
    810814        """ 
    811         if self.current_dataset == None: 
     815        if self.current_dataset is None: 
    812816            x_vals = np.empty(0) 
    813817            y_vals = np.empty(0) 
     
    897901        # Write the file 
    898902        file_ref = open(filename, 'w') 
    899         if self.encoding == None: 
     903        if self.encoding is None: 
    900904            self.encoding = "UTF-8" 
    901905        doc.write(file_ref, encoding=self.encoding, 
     
    10171021        :param entry_node: lxml node ElementTree object to be appended to 
    10181022        """ 
    1019         if datainfo.run == None or datainfo.run == []: 
     1023        if datainfo.run is None or datainfo.run == []: 
    10201024            datainfo.run.append(RUN_NAME_DEFAULT) 
    10211025            datainfo.run_name[RUN_NAME_DEFAULT] = RUN_NAME_DEFAULT 
     
    10611065            sesans.text = str(datainfo.isSesans) 
    10621066            node.append(sesans) 
     1067            self.write_node(node, "yacceptance", datainfo.sample.yacceptance[0], 
     1068                             {'unit': datainfo.sample.yacceptance[1]}) 
    10631069            self.write_node(node, "zacceptance", datainfo.sample.zacceptance[0], 
    10641070                             {'unit': datainfo.sample.zacceptance[1]}) 
     
    11331139                self.write_node(point, "T", spectrum.transmission[i], 
    11341140                                {'unit': spectrum.transmission_unit}) 
    1135                 if spectrum.transmission_deviation != None \ 
     1141                if spectrum.transmission_deviation is not None \ 
    11361142                and len(spectrum.transmission_deviation) >= i: 
    11371143                    self.write_node(point, "Tdev", 
     
    12131219                                 str(datainfo.source.name)) 
    12141220        self.append(source, instr) 
    1215         if datainfo.source.radiation == None or datainfo.source.radiation == '': 
     1221        if datainfo.source.radiation is None or datainfo.source.radiation == '': 
    12161222            datainfo.source.radiation = "neutron" 
    12171223        self.write_node(source, "radiation", datainfo.source.radiation) 
     
    12541260        :param instr: lxml node ElementTree object to be appended to 
    12551261        """ 
    1256         if datainfo.collimation == [] or datainfo.collimation == None: 
     1262        if datainfo.collimation == [] or datainfo.collimation is None: 
    12571263            coll = Collimation() 
    12581264            datainfo.collimation.append(coll) 
     
    12991305        :param inst: lxml instrument node to be appended to 
    13001306        """ 
    1301         if datainfo.detector == None or datainfo.detector == []: 
     1307        if datainfo.detector is None or datainfo.detector == []: 
    13021308            det = Detector() 
    13031309            det.name = "" 
     
    14641470                local_unit = None 
    14651471                exec "local_unit = storage.%s_unit" % toks[0] 
    1466                 if local_unit != None and units.lower() != local_unit.lower(): 
     1472                if local_unit is not None and units.lower() != local_unit.lower(): 
    14671473                    if HAS_CONVERTER == True: 
    14681474                        try: 
     
    14771483                            self.errors.add(err_mess) 
    14781484                            if optional: 
    1479                                 logging.info(err_mess) 
     1485                                logger.info(err_mess) 
    14801486                            else: 
    14811487                                raise ValueError, err_mess 
     
    14861492                        self.errors.add(err_mess) 
    14871493                        if optional: 
    1488                             logging.info(err_mess) 
     1494                            logger.info(err_mess) 
    14891495                        else: 
    14901496                            raise ValueError, err_mess 
  • src/sas/sascalc/dataloader/readers/danse_reader.py

    r9a5097c r235f514  
    1919from sas.sascalc.dataloader.data_info import Data2D, Detector 
    2020from sas.sascalc.dataloader.manipulations import reader2D_converter 
     21 
     22logger = logging.getLogger(__name__) 
    2123 
    2224# Look for unit converter 
     
    142144                            error.append(err) 
    143145                        except: 
    144                             logging.info("Skipping line:%s,%s" %(data_str, 
     146                            logger.info("Skipping line:%s,%s" %(data_str, 
    145147                                                                sys.exc_value)) 
    146148             
     
    164166                 
    165167                x_vals.append(qx) 
    166                 if xmin == None or qx < xmin: 
     168                if xmin is None or qx < xmin: 
    167169                    xmin = qx 
    168                 if xmax == None or qx > xmax: 
     170                if xmax is None or qx > xmax: 
    169171                    xmax = qx 
    170172             
     
    179181                 
    180182                y_vals.append(qy) 
    181                 if ymin == None or qy < ymin: 
     183                if ymin is None or qy < ymin: 
    182184                    ymin = qy 
    183                 if ymax == None or qy > ymax: 
     185                if ymax is None or qy > ymax: 
    184186                    ymax = qy 
    185187             
     
    196198                    msg = "Skipping entry (v1.0):%s,%s" % (str(data[i_pt]), 
    197199                                                           sys.exc_value) 
    198                     logging.info(msg) 
     200                    logger.info(msg) 
    199201                 
    200202                # Get bin number 
     
    271273                raise ValueError, msg 
    272274            else: 
    273                 logging.info("Danse_reader Reading %s \n" % filename) 
     275                logger.info("Danse_reader Reading %s \n" % filename) 
    274276             
    275277            # Store loading process information 
  • src/sas/sascalc/dataloader/readers/tiff_reader.py

    r9a5097c r959eb01  
    1616from sas.sascalc.dataloader.data_info import Data2D 
    1717from sas.sascalc.dataloader.manipulations import reader2D_converter 
    18      
     18 
     19logger = logging.getLogger(__name__) 
     20 
    1921class Reader: 
    2022    """ 
     
    7678                value = float(val) 
    7779            except: 
    78                 logging.error("tiff_reader: had to skip a non-float point") 
     80                logger.error("tiff_reader: had to skip a non-float point") 
    7981                continue 
    8082             
  • src/sas/sascalc/dataloader/readers/xml_reader.py

    r7f75a3f r235f514  
    1818from lxml import etree 
    1919from lxml.builder import E 
     20 
     21logger = logging.getLogger(__name__) 
    2022 
    2123PARSER = etree.ETCompatXMLParser(remove_comments=True, remove_pis=False) 
     
    7072            self.xmldoc = etree.parse(self.xml, parser=PARSER) 
    7173            self.xmlroot = self.xmldoc.getroot() 
    72         except etree.XMLSyntaxError: 
    73             raise 
     74        except etree.XMLSyntaxError as xml_error: 
     75            logger.info(xml_error) 
    7476        except Exception: 
    7577            self.xml = None 
     
    8890            self.xmlroot = etree.fromstring(tag_soup) 
    8991        except etree.XMLSyntaxError as xml_error: 
    90             logging.info(xml_error) 
     92            logger.info(xml_error) 
    9193        except Exception: 
    9294            self.xml = None 
     
    102104            self.schemadoc = etree.parse(self.schema, parser=PARSER) 
    103105        except etree.XMLSyntaxError as xml_error: 
    104             logging.info(xml_error) 
     106            logger.info(xml_error) 
    105107        except Exception: 
    106108            self.schema = None 
     
    238240        :param name: The name of the element to be created 
    239241        """ 
    240         if attrib == None: 
     242        if attrib is None: 
    241243            attrib = {} 
    242244        return etree.Element(name, attrib, nsmap) 
     
    297299        """ 
    298300        text = str(text) 
    299         if attrib == None: 
     301        if attrib is None: 
    300302            attrib = {} 
    301303        elem = E(elementname, attrib, text) 
  • src/sas/sascalc/file_converter/cansas_writer.py

    r0b1a677 r7432acb  
    1717        # Write the file 
    1818        file_ref = open(filename, 'w') 
    19         if self.encoding == None: 
     19        if self.encoding is None: 
    2020            self.encoding = "UTF-8" 
    2121        doc.write(file_ref, encoding=self.encoding, 
     
    9696                self.write_node(point, "I", datainfo.y[i], 
    9797                                {'unit': datainfo.y_unit}) 
    98             if datainfo.dy != None and len(datainfo.dy) > i: 
     98            if datainfo.dy is not None and len(datainfo.dy) > i: 
    9999                self.write_node(point, "Idev", datainfo.dy[i], 
    100100                                {'unit': datainfo.y_unit}) 
    101             if datainfo.dx != None and len(datainfo.dx) > i: 
     101            if datainfo.dx is not None and len(datainfo.dx) > i: 
    102102                self.write_node(point, "Qdev", datainfo.dx[i], 
    103103                                {'unit': datainfo.x_unit}) 
    104             if datainfo.dxw != None and len(datainfo.dxw) > i: 
     104            if datainfo.dxw is not None and len(datainfo.dxw) > i: 
    105105                self.write_node(point, "dQw", datainfo.dxw[i], 
    106106                                {'unit': datainfo.x_unit}) 
    107             if datainfo.dxl != None and len(datainfo.dxl) > i: 
     107            if datainfo.dxl is not None and len(datainfo.dxl) > i: 
    108108                self.write_node(point, "dQl", datainfo.dxl[i], 
    109109                                {'unit': datainfo.x_unit}) 
  • src/sas/sascalc/fit/AbstractFitEngine.py

    r9a5097c r7432acb  
    190190        if qmin == 0.0 and not np.isfinite(self.y[qmin]): 
    191191            self.qmin = min(self.x[self.x != 0]) 
    192         elif qmin != None: 
     192        elif qmin is not None: 
    193193            self.qmin = qmin 
    194         if qmax != None: 
     194        if qmax is not None: 
    195195            self.qmax = qmax 
    196196        # Determine the range needed in unsmeared-Q to cover 
     
    202202        self._last_unsmeared_bin = len(self.x) - 1 
    203203         
    204         if self.smearer != None: 
     204        if self.smearer is not None: 
    205205            self._first_unsmeared_bin, self._last_unsmeared_bin = \ 
    206206                    self.smearer.get_bin_range(self.qmin, self.qmax) 
     
    294294         
    295295        ## fitting range 
    296         if qmin == None: 
     296        if qmin is None: 
    297297            self.qmin = 1e-16 
    298         if qmax == None: 
     298        if qmax is None: 
    299299            self.qmax = math.sqrt(x_max * x_max + y_max * y_max) 
    300300        ## new error image for fitting purpose 
    301         if self.err_data == None or self.err_data == []: 
     301        if self.err_data is None or self.err_data == []: 
    302302            self.res_err_data = np.ones(len(self.data)) 
    303303        else: 
     
    318318            Set smearer 
    319319        """ 
    320         if smearer == None: 
     320        if smearer is None: 
    321321            return 
    322322        self.smearer = smearer 
     
    330330        if qmin == 0.0: 
    331331            self.qmin = 1e-16 
    332         elif qmin != None: 
     332        elif qmin is not None: 
    333333            self.qmin = qmin 
    334         if qmax != None: 
     334        if qmax is not None: 
    335335            self.qmax = qmax 
    336336        self.radius = np.sqrt(self.qx_data**2 + self.qy_data**2) 
     
    357357        return the residuals 
    358358        """ 
    359         if self.smearer != None: 
     359        if self.smearer is not None: 
    360360            fn.set_index(self.idx) 
    361361            gn = fn.get_value() 
     
    612612        """ 
    613613        """ 
    614         if self.pvec == None and self.model is None and self.param_list is None: 
     614        if self.pvec is None and self.model is None and self.param_list is None: 
    615615            return "No results" 
    616616 
  • src/sas/sascalc/fit/Loader.py

    r9a5097c rac07a3a  
    3434    def set_values(self): 
    3535        """ Store the values loaded from file in local variables""" 
    36         if not self.filename == None: 
     36        if self.filename is not None: 
    3737            input_f =  open(self.filename, 'r') 
    3838            buff = input_f.read() 
  • src/sas/sascalc/fit/MultiplicationModel.py

    r9a5097c r7432acb  
    178178        """ 
    179179        value = self.params['volfraction'] 
    180         if value != None: 
     180        if value is not None: 
    181181            factor = self.p_model.calculate_VR() 
    182             if factor == None or factor == NotImplemented or factor == 0.0: 
     182            if factor is None or factor == NotImplemented or factor == 0.0: 
    183183                val = value 
    184184            else: 
     
    195195        effective_radius = self.p_model.calculate_ER() 
    196196        #Reset the effective_radius of s_model just before the run 
    197         if effective_radius != None and effective_radius != NotImplemented: 
     197        if effective_radius is not None and effective_radius != NotImplemented: 
    198198            self.s_model.setParam('radius_effective', effective_radius) 
    199199 
  • src/sas/sascalc/invariant/invariant.py

    r9a5097c r7432acb  
    329329 
    330330        ##power is given only for function = power_law 
    331         if power != None: 
     331        if power is not None: 
    332332            sigma2 = linearized_data.dy * linearized_data.dy 
    333333            a = -(power) 
     
    389389        self._data = self._get_data(data) 
    390390        # get the dxl if the data is smeared: This is done only once on init. 
    391         if self._data.dxl != None and self._data.dxl.all() > 0: 
     391        if self._data.dxl is not None and self._data.dxl.all() > 0: 
    392392            # assumes constant dxl 
    393393            self._smeared = self._data.dxl[0] 
     
    579579 
    580580        result_data = LoaderData1D(x=q, y=iq, dy=diq) 
    581         if self._smeared != None: 
     581        if self._smeared is not None: 
    582582            result_data.dxl = self._smeared * np.ones(len(q)) 
    583583        return result_data 
  • src/sas/sascalc/pr/fit/AbstractFitEngine.py

    r9a5097c r7432acb  
    190190        if qmin == 0.0 and not np.isfinite(self.y[qmin]): 
    191191            self.qmin = min(self.x[self.x != 0]) 
    192         elif qmin != None: 
     192        elif qmin is not None: 
    193193            self.qmin = qmin 
    194         if qmax != None: 
     194        if qmax is not None: 
    195195            self.qmax = qmax 
    196196        # Determine the range needed in unsmeared-Q to cover 
     
    202202        self._last_unsmeared_bin = len(self.x) - 1 
    203203         
    204         if self.smearer != None: 
     204        if self.smearer is not None: 
    205205            self._first_unsmeared_bin, self._last_unsmeared_bin = \ 
    206206                    self.smearer.get_bin_range(self.qmin, self.qmax) 
     
    294294         
    295295        ## fitting range 
    296         if qmin == None: 
     296        if qmin is None: 
    297297            self.qmin = 1e-16 
    298         if qmax == None: 
     298        if qmax is None: 
    299299            self.qmax = math.sqrt(x_max * x_max + y_max * y_max) 
    300300        ## new error image for fitting purpose 
    301         if self.err_data == None or self.err_data == []: 
     301        if self.err_data is None or self.err_data == []: 
    302302            self.res_err_data = np.ones(len(self.data)) 
    303303        else: 
     
    318318            Set smearer 
    319319        """ 
    320         if smearer == None: 
     320        if smearer is None: 
    321321            return 
    322322        self.smearer = smearer 
     
    330330        if qmin == 0.0: 
    331331            self.qmin = 1e-16 
    332         elif qmin != None: 
     332        elif qmin is not None: 
    333333            self.qmin = qmin 
    334         if qmax != None: 
     334        if qmax is not None: 
    335335            self.qmax = qmax 
    336336        self.radius = np.sqrt(self.qx_data**2 + self.qy_data**2) 
     
    357357        return the residuals 
    358358        """ 
    359         if self.smearer != None: 
     359        if self.smearer is not None: 
    360360            fn.set_index(self.idx) 
    361361            # Get necessary data from self.data and set the data for smearing 
     
    615615        """ 
    616616        """ 
    617         if self.pvec == None and self.model is None and self.param_list is None: 
     617        if self.pvec is None and self.model is None and self.param_list is None: 
    618618            return "No results" 
    619619 
  • src/sas/sascalc/pr/fit/Loader.py

    r9a5097c rac07a3a  
    3434    def set_values(self): 
    3535        """ Store the values loaded from file in local variables""" 
    36         if not self.filename == None: 
     36        if self.filename is not None: 
    3737            input_f =  open(self.filename, 'r') 
    3838            buff = input_f.read() 
  • src/sas/sascalc/pr/invertor.py

    r9a5097c r45dffa69  
    1818from scipy import optimize 
    1919from sas.sascalc.pr.core.pr_inversion import Cinvertor 
     20 
     21logger = logging.getLogger(__name__) 
    2022 
    2123def help(): 
     
    160162            return self.set_dmax(value) 
    161163        elif name == 'q_min': 
    162             if value == None: 
     164            if value is None: 
    163165                return self.set_qmin(-1.0) 
    164166            return self.set_qmin(value) 
    165167        elif name == 'q_max': 
    166             if value == None: 
     168            if value is None: 
    167169                return self.set_qmax(-1.0) 
    168170            return self.set_qmax(value) 
     
    393395        Check q-value against user-defined range 
    394396        """ 
    395         if not self.q_min == None and q < self.q_min: 
     397        if self.q_min is not None and q < self.q_min: 
    396398            return False 
    397         if not self.q_max == None and q > self.q_max: 
     399        if self.q_max is not None and q > self.q_max: 
    398400            return False 
    399401        return True 
     
    495497            # We were not able to estimate the errors 
    496498            # Return an empty error matrix 
    497             logging.error(sys.exc_value) 
     499            logger.error(sys.exc_value) 
    498500 
    499501        # Keep a copy of the last output 
     
    541543            # number of terms 
    542544            best_alpha, _, _ = self.estimate_alpha(self.nfunc) 
    543             logging.warning("Invertor.estimate_numterms: %s" % sys.exc_value) 
     545            logger.warning("Invertor.estimate_numterms: %s" % sys.exc_value) 
    544546            return self.nfunc, best_alpha, "Could not estimate number of terms" 
    545547 
     
    656658            file.write("#has_bck=0\n") 
    657659        file.write("#alpha_estimate=%g\n" % self.suggested_alpha) 
    658         if not self.out == None: 
     660        if self.out is not None: 
    659661            if len(self.out) == len(self.cov): 
    660662                for i in range(len(self.out)): 
  • src/sas/sascalc/pr/num_term.py

    r9a5097c r7432acb  
    55import logging 
    66from sas.sascalc.pr.invertor import Invertor 
     7 
     8logger = logging.getLogger(__name__) 
    79 
    810class NTermEstimator(object): 
     
    6567        self.alpha_list = [] 
    6668        for k in range(self.nterm_min, self.nterm_max, 1): 
    67             if self.isquit_func != None: 
     69            if self.isquit_func is not None: 
    6870                self.isquit_func() 
    6971            best_alpha, message, _ = inver.estimate_alpha(k) 
     
    157159    scale = None 
    158160    min_err = 0.0 
    159     if not path == None: 
     161    if path is not None: 
    160162        input_f = open(path, 'r') 
    161163        buff = input_f.read() 
     
    169171                    err = float(toks[2]) 
    170172                else: 
    171                     if scale == None: 
     173                    if scale is None: 
    172174                        scale = 0.05 * math.sqrt(test_y) 
    173175                        #scale = 0.05/math.sqrt(y) 
     
    180182                data_err = np.append(data_err, err) 
    181183            except: 
    182                 logging.error(sys.exc_value) 
     184                logger.error(sys.exc_value) 
    183185 
    184186    return data_x, data_y, data_err 
  • src/sas/sascalc/realspace/VolumeCanvas.py

    rd85c194 r235f514  
    293293        """ 
    294294        # If the handle is not provided, create one 
    295         if id == None: 
     295        if id is None: 
    296296            id = shapeDesc.params["type"]+str(self.shapecount) 
    297297          
     
    303303        self.shapecount += 1 
    304304 
    305         #model changed, need to recalculate P(r) 
     305        # model changed, need to recalculate P(r) 
    306306        self._model_changed() 
    307307 
     
    325325        """ 
    326326        # If the handle is not provided, create one 
    327         if id == None: 
     327        if id is None: 
    328328            id = "shape"+str(self.shapecount) 
    329329  
    330         #shapeDesc = ShapeDescriptor(shape.lower()) 
     330        # shapeDesc = ShapeDescriptor(shape.lower()) 
    331331        if shape.lower() in shape_dict: 
    332332            shapeDesc = shape_dict[shape.lower()]() 
     
    335335            shapeDesc = PDBDescriptor(shape) 
    336336        else: 
    337             raise ValueError, "VolumeCanvas.add: Unknown shape %s" % shape 
     337            raise ValueError("VolumeCanvas.add: Unknown shape %s" % shape) 
    338338         
    339339        return self.addObject(shapeDesc, id) 
     
    345345        """ 
    346346 
    347         if self.shapes.has_key(id): 
     347        if id in self.shapes: 
    348348            del self.shapes[id] 
    349349        else: 
    350             raise KeyError, "VolumeCanvas.delete: could not find shape ID" 
    351  
    352         #model changed, need to recalculate P(r) 
     350            raise KeyError("VolumeCanvas.delete: could not find shape ID") 
     351 
     352        # model changed, need to recalculate P(r) 
    353353        self._model_changed() 
    354354 
     
    379379        # If a shape identifier was given, look the shape up 
    380380        # in the dictionary 
    381         if len(toks)>1: 
    382             if toks[0] in self.shapes.keys(): 
     381        if len(toks): 
     382            if toks[0] in self.shapes: 
    383383                # The shape was found, now look for the parameter 
    384384                if toks[1] in self.shapes[toks[0]].params: 
     
    387387                    self._model_changed() 
    388388                else: 
    389                     raise ValueError, "Could not find parameter %s" % name 
     389                    raise ValueError("Could not find parameter %s" % name) 
    390390            else: 
    391                 raise ValueError, "Could not find shape %s" % toks[0] 
     391                raise ValueError("Could not find shape %s" % toks[0]) 
    392392         
    393393        else: 
     
    410410        if len(toks) == 1: 
    411411            try: 
    412                 self.params.has_key(toks[0]) 
     412                value = self.params[toks[0]] 
    413413            except KeyError: 
    414                 raise ValueError, \ 
    415                     "VolumeCanvas.getParam: Could not find %s" % name 
    416  
    417             value = self.params[toks[0]] 
     414                raise ValueError("VolumeCanvas.getParam: Could not find" 
     415                                 " %s" % name) 
    418416            if isinstance(value, ShapeDescriptor): 
    419                 raise ValueError, \ 
    420                     "VolumeCanvas.getParam: Cannot get parameter value."  
     417                raise ValueError("VolumeCanvas.getParam: Cannot get parameter" 
     418                                 " value.") 
    421419            else: 
    422420                return value 
     
    424422        elif len(toks) == 2: 
    425423            try: 
    426                 self.shapes.has_key(toks[0]) 
     424                shapeinstance = self.shapes[toks[0]] 
    427425            except KeyError: 
    428                 raise ValueError, \ 
    429                     "VolumeCanvas.getParam: Could not find %s" % name 
    430  
    431             shapeinstance = self.shapes[toks[0]] 
    432  
    433             try: 
    434                 shapeinstance.params.has_key(toks[1]) 
    435             except KeyError: 
    436                 raise ValueError, \ 
    437                     "VolumeCanvas.getParam: Could not find %s" % name 
     426                raise ValueError("VolumeCanvas.getParam: Could not find " 
     427                                 "%s" % name) 
     428 
     429            if not toks[1] in shapeinstance.params: 
     430                raise ValueError("VolumeCanvas.getParam: Could not find " 
     431                                 "%s" % name) 
    438432 
    439433            return shapeinstance.params[toks[1]] 
    440434 
    441435        else: 
    442             raise ValueError, \ 
    443                 "VolumeCanvas.getParam: Could not find %s" % name 
    444              
    445     def getParamList(self, shapeid = None): 
     436            raise ValueError("VolumeCanvas.getParam: Could not find %s" % name) 
     437             
     438    def getParamList(self, shapeid=None): 
    446439        """ 
    447440               return a full list of all available parameters from  
     
    455448 
    456449        param_list = [] 
    457         if shapeid == None:         
    458             for key1 in self.params.keys(): 
     450        if shapeid is None: 
     451            for key1 in self.params: 
    459452                #value1 = self.params[key1] 
    460453                param_list.append(key1) 
    461             for key2 in self.shapes.keys(): 
     454            for key2 in self.shapes: 
    462455                value2 = self.shapes[key2] 
    463456                header = key2 + '.' 
    464                 for key3 in value2.params.keys():    
     457                for key3 in value2.params: 
    465458                    fullname = header + key3                  
    466459                    param_list.append(fullname) 
    467460      
    468461        else: 
    469             try: 
    470                 self.shapes.has_key(shapeid) 
    471             except KeyError: 
    472                 raise ValueError, \ 
    473                     "VolumeCanvas: getParamList: Could not find %s" % shapeid 
     462            if not shapeid in self.shapes: 
     463                raise ValueError("VolumeCanvas: getParamList: Could not find " 
     464                                 "%s" % shapeid) 
     465 
    474466            header = shapeid + '.' 
    475             param_list = self.shapes[shapeid].params.keys()   
    476             for i in range(len(param_list)): 
    477                 param_list[i] = header + param_list[i] 
    478  
     467            param_list = [header + param for param in self.shapes[shapeid].params] 
    479468        return param_list 
    480469 
     
    490479            @param shapeDesc: shape description 
    491480        """ 
    492         #Create the object model 
     481        # Create the object model 
    493482        shapeDesc.create() 
    494483                     
     
    605594        # type we recognize 
    606595        else: 
    607             raise ValueError, "run(q): bad type for q" 
     596            raise ValueError("run(q): bad type for q") 
    608597     
    609598    def runXY(self, q = 0): 
     
    625614        # type we recognize 
    626615        else: 
    627             raise ValueError, "runXY(q): bad type for q" 
     616            raise ValueError("runXY(q): bad type for q") 
    628617     
    629618    def _create_modelObject(self): 
     
    674663        # If this is the first simulation call, we need to generate the 
    675664        # space points 
    676         if self.points == None: 
     665        if self.points is None: 
    677666            self._create_modelObject() 
    678667             
    679668            # Protect against empty model 
    680             if self.points == None: 
     669            if self.points is None: 
    681670                return 0 
    682671                
  • src/sas/sascalc/data_util/registry.py

    rb699768 r7f75a3f  
    77""" 
    88 
    9 import os.path 
     9from sas.sascalc.dataloader.loader_exceptions import NoKnownLoaderException 
     10 
    1011 
    1112class ExtensionRegistry(object): 
     
    6162    def __init__(self, **kw): 
    6263        self.loaders = {} 
     64 
    6365    def __setitem__(self, ext, loader): 
    6466        if ext not in self.loaders: 
    6567            self.loaders[ext] = [] 
    6668        self.loaders[ext].insert(0,loader) 
     69 
    6770    def __getitem__(self, ext): 
    6871        return self.loaders[ext] 
     72 
    6973    def __contains__(self, ext): 
    7074        return ext in self.loaders 
     75 
    7176    def formats(self): 
    7277        """ 
     
    7681        names.sort() 
    7782        return names 
     83 
    7884    def extensions(self): 
    7985        """ 
     
    8389        exts.sort() 
    8490        return exts 
     91 
    8592    def lookup(self, path): 
    8693        """ 
    8794        Return the loader associated with the file type of path. 
    8895         
    89         Raises ValueError if file type is not known. 
     96        :param path: Data file path 
     97        :raises ValueError: When no loaders are found for the file. 
     98        :return: List of available readers for the file extension 
    9099        """         
    91100        # Find matching extensions 
     
    105114        # Raise an error if there are no matching extensions 
    106115        if len(loaders) == 0: 
    107             raise ValueError, "Unknown file type for "+path 
    108         # All done 
     116            raise ValueError("Unknown file type for "+path) 
    109117        return loaders 
     118 
    110119    def load(self, path, format=None): 
    111120        """ 
    112121        Call the loader for the file type of path. 
    113122 
    114         Raises ValueError if no loader is available. 
    115         Raises KeyError if format is not available. 
    116         May raise a loader-defined exception if loader fails.         
     123        :raise ValueError: if no loader is available. 
     124        :raise KeyError: if format is not available. 
     125        May raise a loader-defined exception if loader fails. 
    117126        """ 
     127        loaders = [] 
    118128        if format is None: 
    119             loaders = self.lookup(path) 
     129            try: 
     130                loaders = self.lookup(path) 
     131            except ValueError as e: 
     132                pass 
    120133        else: 
    121             loaders = self.loaders[format] 
     134            try: 
     135                loaders = self.loaders[format] 
     136            except KeyError as e: 
     137                pass 
    122138        for fn in loaders: 
    123139            try: 
    124140                return fn(path) 
    125             except: 
    126                 pass # give other loaders a chance to succeed 
     141            except Exception as e: 
     142                pass  # give other loaders a chance to succeed 
    127143        # If we get here it is because all loaders failed 
    128         raise # reraises last exception 
    129  
    130 def test(): 
    131     reg = ExtensionRegistry() 
    132     class CxError(Exception): pass 
    133     def cx(file): return 'cx' 
    134     def new_cx(file): return 'new_cx' 
    135     def fail_cx(file): raise CxError 
    136     def cat(file): return 'cat' 
    137     def gunzip(file): return 'gunzip' 
    138     reg['.cx'] = cx 
    139     reg['.cx1'] = cx 
    140     reg['.cx'] = new_cx 
    141     reg['.gz'] = gunzip 
    142     reg['.cx.gz'] = new_cx 
    143     reg['.cx1.gz'] = fail_cx 
    144     reg['.cx1'] = fail_cx 
    145     reg['.cx2'] = fail_cx 
    146     reg['new_cx'] = new_cx 
    147  
    148     # Two loaders associated with .cx 
    149     assert reg.lookup('hello.cx') == [new_cx,cx] 
    150     # Make sure the last loader applies first 
    151     assert reg.load('hello.cx') == 'new_cx' 
    152     # Make sure the next loader applies if the first fails 
    153     assert reg.load('hello.cx1') == 'cx' 
    154     # Make sure the format override works 
    155     assert reg.load('hello.cx1',format='.cx.gz') == 'new_cx' 
    156     # Make sure the format override works 
    157     assert reg.load('hello.cx1',format='new_cx') == 'new_cx' 
    158     # Make sure the case of all loaders failing is correct 
    159     try:  reg.load('hello.cx2') 
    160     except CxError: pass # correct failure 
    161     else: raise AssertError,"Incorrect error on load failure" 
    162     # Make sure the case of no loaders fails correctly 
    163     try: reg.load('hello.missing') 
    164     except ValueError,msg: 
    165         assert str(msg)=="Unknown file type for hello.missing",'Message: <%s>'%(msg) 
    166     else: raise AssertError,"No error raised for missing extension" 
    167     assert reg.formats() == ['new_cx'] 
    168     assert reg.extensions() == ['.cx','.cx.gz','.cx1','.cx1.gz','.cx2','.gz'] 
    169     # make sure that it supports multiple '.' in filename 
    170     assert reg.load('hello.extra.cx1') == 'cx' 
    171     assert reg.load('hello.gz') == 'gunzip' 
    172     assert reg.load('hello.cx1.gz') == 'gunzip' # Since .cx1.gz fails 
    173  
    174 if __name__ == "__main__": test() 
     144        raise NoKnownLoaderException(e.message)  # raise generic exception 
  • src/sas/sascalc/dataloader/readers/cansas_reader_HDF5.py

    rc94280c r7f75a3f  
    1313    TransmissionSpectrum, Detector 
    1414from sas.sascalc.dataloader.data_info import combine_data_info_with_plottable 
     15from sas.sascalc.dataloader.loader_exceptions import FileContentsException 
    1516 
    1617 
     
    7576            if extension in self.ext or self.allow_all: 
    7677                # Load the data file 
    77                 self.raw_data = h5py.File(filename, 'r') 
     78                try: 
     79                    self.raw_data = h5py.File(filename, 'r') 
     80                except Exception as e: 
     81                    raise FileContentsException, e 
    7882                # Read in all child elements of top level SASroot 
    7983                self.read_children(self.raw_data, []) 
Note: See TracChangeset for help on using the changeset viewer.