Changeset 9e6aeaf in sasview for src/sas/sascalc


Ignore:
Timestamp:
Sep 25, 2017 3:35:29 PM (7 years ago)
Author:
Paul Kienzle <pkienzle@…>
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, magnetic_scatt, release-4.2.2, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
3cb3a51
Parents:
9efdb29 (diff), 0315b63 (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.
Message:

Merge branch 'ticket-853-fit-gui-to-calc' into py3

Location:
src/sas/sascalc
Files:
43 edited

Legend:

Unmodified
Added
Removed
  • src/sas/sascalc/dataloader/data_info.py

    r574adc7 r9e6aeaf  
    11761176        final_dataset.yaxis(data._yaxis, data._yunit) 
    11771177        final_dataset.zaxis(data._zaxis, data._zunit) 
    1178         final_dataset.x_bins = data.x_bins 
    1179         final_dataset.y_bins = data.y_bins 
     1178        if len(data.data.shape) == 2: 
     1179            n_rows, n_cols = data.data.shape 
     1180            final_dataset.y_bins = data.qy_data[0::int(n_cols)] 
     1181            final_dataset.x_bins = data.qx_data[:int(n_cols)] 
    11801182    else: 
    11811183        return_string = "Should Never Happen: _combine_data_info_with_plottable input is not a plottable1d or " + \ 
  • src/sas/sascalc/dataloader/file_reader_base_class.py

    r7b50f14 r9e6aeaf  
    197197                    dataset.x_bins = dataset.qx_data[:int(n_cols)] 
    198198                dataset.data = dataset.data.flatten() 
     199                if len(dataset.data) > 0: 
     200                    dataset.xmin = np.min(dataset.qx_data) 
     201                    dataset.xmax = np.max(dataset.qx_data) 
     202                    dataset.ymin = np.min(dataset.qy_data) 
     203                    dataset.ymax = np.max(dataset.qx_data) 
    199204 
    200205    def format_unit(self, unit=None): 
     
    221226        self.output = [] 
    222227 
    223     def remove_empty_q_values(self, has_error_dx=False, has_error_dy=False, 
    224                               has_error_dxl=False, has_error_dxw=False): 
     228    def data_cleanup(self): 
     229        """ 
     230        Clean up the data sets and refresh everything 
     231        :return: None 
     232        """ 
     233        self.remove_empty_q_values() 
     234        self.send_to_output()  # Combine datasets with DataInfo 
     235        self.current_datainfo = DataInfo()  # Reset DataInfo 
     236 
     237    def remove_empty_q_values(self): 
    225238        """ 
    226239        Remove any point where Q == 0 
    227240        """ 
    228         x = self.current_dataset.x 
    229         self.current_dataset.x = self.current_dataset.x[x != 0] 
    230         self.current_dataset.y = self.current_dataset.y[x != 0] 
    231         if has_error_dy: 
    232             self.current_dataset.dy = self.current_dataset.dy[x != 0] 
    233         if has_error_dx: 
    234             self.current_dataset.dx = self.current_dataset.dx[x != 0] 
    235         if has_error_dxl: 
    236             self.current_dataset.dxl = self.current_dataset.dxl[x != 0] 
    237         if has_error_dxw: 
    238             self.current_dataset.dxw = self.current_dataset.dxw[x != 0] 
     241        if isinstance(self.current_dataset, plottable_1D): 
     242            # Booleans for resolutions 
     243            has_error_dx = self.current_dataset.dx is not None 
     244            has_error_dxl = self.current_dataset.dxl is not None 
     245            has_error_dxw = self.current_dataset.dxw is not None 
     246            has_error_dy = self.current_dataset.dy is not None 
     247            # Create arrays of zeros for non-existent resolutions 
     248            if has_error_dxw and not has_error_dxl: 
     249                array_size = self.current_dataset.dxw.size - 1 
     250                self.current_dataset.dxl = np.append(self.current_dataset.dxl, 
     251                                                    np.zeros([array_size])) 
     252                has_error_dxl = True 
     253            elif has_error_dxl and not has_error_dxw: 
     254                array_size = self.current_dataset.dxl.size - 1 
     255                self.current_dataset.dxw = np.append(self.current_dataset.dxw, 
     256                                                    np.zeros([array_size])) 
     257                has_error_dxw = True 
     258            elif not has_error_dxl and not has_error_dxw and not has_error_dx: 
     259                array_size = self.current_dataset.x.size - 1 
     260                self.current_dataset.dx = np.append(self.current_dataset.dx, 
     261                                                    np.zeros([array_size])) 
     262                has_error_dx = True 
     263            if not has_error_dy: 
     264                array_size = self.current_dataset.y.size - 1 
     265                self.current_dataset.dy = np.append(self.current_dataset.dy, 
     266                                                    np.zeros([array_size])) 
     267                has_error_dy = True 
     268 
     269            # Remove points where q = 0 
     270            x = self.current_dataset.x 
     271            self.current_dataset.x = self.current_dataset.x[x != 0] 
     272            self.current_dataset.y = self.current_dataset.y[x != 0] 
     273            if has_error_dy: 
     274                self.current_dataset.dy = self.current_dataset.dy[x != 0] 
     275            if has_error_dx: 
     276                self.current_dataset.dx = self.current_dataset.dx[x != 0] 
     277            if has_error_dxl: 
     278                self.current_dataset.dxl = self.current_dataset.dxl[x != 0] 
     279            if has_error_dxw: 
     280                self.current_dataset.dxw = self.current_dataset.dxw[x != 0] 
     281        elif isinstance(self.current_dataset, plottable_2D): 
     282            has_error_dqx = self.current_dataset.dqx_data is not None 
     283            has_error_dqy = self.current_dataset.dqy_data is not None 
     284            has_error_dy = self.current_dataset.err_data is not None 
     285            has_mask = self.current_dataset.mask is not None 
     286            x = self.current_dataset.qx_data 
     287            self.current_dataset.data = self.current_dataset.data[x != 0] 
     288            self.current_dataset.qx_data = self.current_dataset.qx_data[x != 0] 
     289            self.current_dataset.qy_data = self.current_dataset.qy_data[x != 0] 
     290            self.current_dataset.q_data = np.sqrt( 
     291                np.square(self.current_dataset.qx_data) + np.square( 
     292                    self.current_dataset.qy_data)) 
     293            if has_error_dy: 
     294                self.current_dataset.err_data = self.current_dataset.err_data[x != 0] 
     295            if has_error_dqx: 
     296                self.current_dataset.dqx_data = self.current_dataset.dqx_data[x != 0] 
     297            if has_error_dqy: 
     298                self.current_dataset.dqy_data = self.current_dataset.dqy_data[x != 0] 
     299            if has_mask: 
     300                self.current_dataset.mask = self.current_dataset.mask[x != 0] 
    239301 
    240302    def reset_data_list(self, no_lines=0): 
  • src/sas/sascalc/dataloader/readers/abs_reader.py

    r46cf4c9 r9e6aeaf  
    104104                # Sample thickness in mm 
    105105                try: 
    106                     value = float(line_toks[5]) 
     106                    # ABS writer adds 'C' with no space to the end of the 
     107                    # thickness column.  Remove it if it is there before 
     108                    # converting the thickness. 
     109                    if line_toks[5][:-1] not in '012345679.': 
     110                        value = float(line_toks[5][:-1]) 
     111                    else: 
     112                        value = float(line_toks[5]) 
    107113                    if self.current_datainfo.sample.thickness_unit != 'cm': 
    108114                        conv = Converter('cm') 
     
    196202                is_data_started = True 
    197203 
    198         self.remove_empty_q_values(True, True) 
     204        self.remove_empty_q_values() 
    199205 
    200206        # Sanity check 
  • src/sas/sascalc/dataloader/readers/ascii_reader.py

    rf7d720f r9e6aeaf  
    156156            raise FileContentsException(msg) 
    157157 
    158         self.remove_empty_q_values(has_error_dx, has_error_dy) 
     158        self.remove_empty_q_values() 
    159159        self.current_dataset.xaxis("\\rm{Q}", 'A^{-1}') 
    160160        self.current_dataset.yaxis("\\rm{Intensity}", "cm^{-1}") 
  • src/sas/sascalc/dataloader/readers/cansas_reader.py

    r9efdb29 r9e6aeaf  
    100100            xml_file = self.f_open.name 
    101101        # We don't sure f_open since lxml handles opnening/closing files 
    102         if not self.f_open.closed: 
    103             self.f_open.close() 
    104  
    105         basename, _ = os.path.splitext(os.path.basename(xml_file)) 
    106  
    107102        try: 
    108103            # Raises FileContentsException 
    109104            self.load_file_and_schema(xml_file, schema_path) 
    110             self.current_datainfo = DataInfo() 
    111             # Raises FileContentsException if file doesn't meet CanSAS schema 
     105            # Parse each SASentry 
     106            entry_list = self.xmlroot.xpath('/ns:SASroot/ns:SASentry', 
     107                                            namespaces={ 
     108                                                'ns': self.cansas_defaults.get( 
     109                                                    "ns") 
     110                                            }) 
    112111            self.is_cansas(self.extension) 
    113             self.invalid = False # If we reach this point then file must be valid CanSAS 
    114  
    115             # Parse each SASentry 
    116             entry_list = self.xmlroot.xpath('/ns:SASroot/ns:SASentry', namespaces={ 
    117                 'ns': self.cansas_defaults.get("ns") 
    118             }) 
    119             # Look for a SASentry 
    120             self.names.append("SASentry") 
    121112            self.set_processing_instructions() 
    122  
    123113            for entry in entry_list: 
    124                 self.current_datainfo.filename = basename + self.extension 
    125                 self.current_datainfo.meta_data["loader"] = "CanSAS XML 1D" 
    126                 self.current_datainfo.meta_data[PREPROCESS] = self.processing_instructions 
    127114                self._parse_entry(entry) 
    128115                self.data_cleanup() 
     
    146133                    invalid_xml = self.find_invalid_xml() 
    147134                    if invalid_xml != "": 
     135                        basename, _ = os.path.splitext( 
     136                            os.path.basename(self.f_open.name)) 
    148137                        invalid_xml = INVALID_XML.format(basename + self.extension) + invalid_xml 
    149138                        raise DataReaderException(invalid_xml) # Handled by base class 
     
    160149        except Exception as e: # Convert all other exceptions to FileContentsExceptions 
    161150            raise FileContentsException(str(e)) 
    162  
     151        finally: 
     152            if not self.f_open.closed: 
     153                self.f_open.close() 
    163154 
    164155    def load_file_and_schema(self, xml_file, schema_path=""): 
     
    205196        if not self._is_call_local() and not recurse: 
    206197            self.reset_state() 
     198        if not recurse: 
     199            self.current_datainfo = DataInfo() 
     200            # Raises FileContentsException if file doesn't meet CanSAS schema 
     201            self.invalid = False 
     202            # Look for a SASentry 
    207203            self.data = [] 
    208             self.current_datainfo = DataInfo() 
     204            self.parent_class = "SASentry" 
    209205            self.names.append("SASentry") 
    210             self.parent_class = "SASentry" 
     206            self.current_datainfo.meta_data["loader"] = "CanSAS XML 1D" 
     207            self.current_datainfo.meta_data[ 
     208                PREPROCESS] = self.processing_instructions 
     209        if self._is_call_local() and not recurse: 
     210            basename, _ = os.path.splitext(os.path.basename(self.f_open.name)) 
     211            self.current_datainfo.filename = basename + self.extension 
    211212        # Create an empty dataset if no data has been passed to the reader 
    212213        if self.current_dataset is None: 
    213             self.current_dataset = plottable_1D(np.empty(0), np.empty(0), 
    214                 np.empty(0), np.empty(0)) 
     214            self._initialize_new_data_set(dom) 
    215215        self.base_ns = "{" + CANSAS_NS.get(self.cansas_version).get("ns") + "}" 
    216216 
     
    224224            tagname_original = tagname 
    225225            # Skip this iteration when loading in save state information 
    226             if tagname == "fitting_plug_in" or tagname == "pr_inversion" or tagname == "invariant": 
     226            if tagname in ["fitting_plug_in", "pr_inversion", "invariant", "corfunc"]: 
    227227                continue 
    228228            # Get where to store content 
     
    254254                self._add_intermediate() 
    255255            else: 
     256                # TODO: Clean this up to make it faster (fewer if/elifs) 
    256257                if isinstance(self.current_dataset, plottable_2D): 
    257258                    data_point = node.text 
     
    498499            self.sort_two_d_data() 
    499500            self.reset_data_list() 
    500             empty = None 
    501             return self.output[0], empty 
    502  
    503     def data_cleanup(self): 
    504         """ 
    505         Clean up the data sets and refresh everything 
    506         :return: None 
    507         """ 
    508         has_error_dx = self.current_dataset.dx is not None 
    509         has_error_dxl = self.current_dataset.dxl is not None 
    510         has_error_dxw = self.current_dataset.dxw is not None 
    511         has_error_dy = self.current_dataset.dy is not None 
    512         self.remove_empty_q_values(has_error_dx=has_error_dx, 
    513                                    has_error_dxl=has_error_dxl, 
    514                                    has_error_dxw=has_error_dxw, 
    515                                    has_error_dy=has_error_dy) 
    516         self.send_to_output()  # Combine datasets with DataInfo 
    517         self.current_datainfo = DataInfo()  # Reset DataInfo 
     501            return self.output[0], None 
    518502 
    519503    def _is_call_local(self): 
     
    549533            self.aperture = Aperture() 
    550534        elif self.parent_class == 'SASdata': 
    551             self._check_for_empty_resolution() 
    552535            self.data.append(self.current_dataset) 
    553536 
     
    605588        if 'unit' in attr and attr.get('unit') is not None: 
    606589            try: 
    607                 local_unit = attr['unit'] 
     590                unit = attr['unit'] 
     591                unit_list = unit.split("|") 
     592                if len(unit_list) > 1: 
     593                    self.current_dataset.xaxis(unit_list[0].strip(), 
     594                                               unit_list[1].strip()) 
     595                    local_unit = unit_list[1] 
     596                else: 
     597                    local_unit = unit 
    608598                unitname = self.ns_list.current_level.get("unit", "") 
    609599                if "SASdetector" in self.names: 
     
    659649        return node_value, value_unit 
    660650 
    661     def _check_for_empty_resolution(self): 
    662         """ 
    663         a method to check all resolution data sets are the same size as I and q 
    664         """ 
    665         dql_exists = False 
    666         dqw_exists = False 
    667         dq_exists = False 
    668         di_exists = False 
    669         if self.current_dataset.dxl is not None: 
    670             dql_exists = True 
    671         if self.current_dataset.dxw is not None: 
    672             dqw_exists = True 
    673         if self.current_dataset.dx is not None: 
    674             dq_exists = True 
    675         if self.current_dataset.dy is not None: 
    676             di_exists = True 
    677         if dqw_exists and not dql_exists: 
    678             array_size = self.current_dataset.dxw.size 
    679             self.current_dataset.dxl = np.zeros(array_size) 
    680         elif dql_exists and not dqw_exists: 
    681             array_size = self.current_dataset.dxl.size 
    682             self.current_dataset.dxw = np.zeros(array_size) 
    683         elif not dql_exists and not dqw_exists and not dq_exists: 
    684             array_size = self.current_dataset.x.size 
    685             self.current_dataset.dx = np.append(self.current_dataset.dx, 
    686                                                 np.zeros([array_size])) 
    687         if not di_exists: 
    688             array_size = self.current_dataset.y.size 
    689             self.current_dataset.dy = np.append(self.current_dataset.dy, 
    690                                                 np.zeros([array_size])) 
    691  
    692651    def _initialize_new_data_set(self, node=None): 
    693652        if node is not None: 
  • src/sas/sascalc/fit/pagestate.py

    r574adc7 r9e6aeaf  
    12261226                                            namespaces=CANSAS_NS) 
    12271227                    for entry in entry_list: 
    1228                         try: 
    1229                             sas_entry, _ = self._parse_save_state_entry(entry) 
    1230                         except: 
    1231                             raise 
    12321228                        fitstate = self._parse_state(entry) 
    1233  
    12341229                        # state could be None when .svs file is loaded 
    12351230                        # in this case, skip appending to output 
    12361231                        if fitstate is not None: 
     1232                            try: 
     1233                                sas_entry, _ = self._parse_save_state_entry( 
     1234                                    entry) 
     1235                            except: 
     1236                                raise 
    12371237                            sas_entry.meta_data['fitstate'] = fitstate 
    12381238                            sas_entry.filename = fitstate.file 
  • src/sas/sascalc/calculator/BaseComponent.py

    r9a5097c r574adc7  
    143143                qdist[1].__class__.__name__ != 'ndarray': 
    144144                msg = "evalDistribution expects a list of 2 ndarrays" 
    145                 raise RuntimeError, msg 
     145                raise RuntimeError(msg) 
    146146 
    147147            # Extract qx and qy for code clarity 
     
    167167            mesg = "evalDistribution is expecting an ndarray of scalar q-values" 
    168168            mesg += " or a list [qx,qy] where qx,qy are 2D ndarrays." 
    169             raise RuntimeError, mesg 
     169            raise RuntimeError(mesg) 
    170170 
    171171 
     
    228228                    return 
    229229 
    230         raise ValueError, "Model does not contain parameter %s" % name 
     230        raise ValueError("Model does not contain parameter %s" % name) 
    231231 
    232232    def getParam(self, name): 
     
    250250                    return self.params[item] 
    251251 
    252         raise ValueError, "Model does not contain parameter %s" % name 
     252        raise ValueError("Model does not contain parameter %s" % name) 
    253253 
    254254    def getParamList(self): 
     
    294294        add 
    295295        """ 
    296         raise ValueError, "Model operation are no longer supported" 
     296        raise ValueError("Model operation are no longer supported") 
    297297    def __sub__(self, other): 
    298298        """ 
    299299        sub 
    300300        """ 
    301         raise ValueError, "Model operation are no longer supported" 
     301        raise ValueError("Model operation are no longer supported") 
    302302    def __mul__(self, other): 
    303303        """ 
    304304        mul 
    305305        """ 
    306         raise ValueError, "Model operation are no longer supported" 
     306        raise ValueError("Model operation are no longer supported") 
    307307    def __div__(self, other): 
    308308        """ 
    309309        div 
    310310        """ 
    311         raise ValueError, "Model operation are no longer supported" 
     311        raise ValueError("Model operation are no longer supported") 
    312312 
    313313 
  • src/sas/sascalc/calculator/c_extensions/sld2i_module.cpp

    rb523c0e r1d014cb  
    55#include <stdio.h> 
    66#include <sld2i.hh> 
     7 
     8#if PY_MAJOR_VERSION < 3 
     9typedef void (*PyCapsule_Destructor)(PyObject *); 
     10typedef void (*PyCObject_Destructor)(void *); 
     11#define PyCapsule_New(pointer, name, destructor) (PyCObject_FromVoidPtr(pointer, (PyCObject_Destructor)destructor)) 
     12#define PyCapsule_GetPointer(capsule, name) (PyCObject_AsVoidPtr(capsule)) 
     13#endif 
     14 
    715 
    816// Utilities 
     
    2533 * Delete a GenI object 
    2634 */ 
    27 void del_sld2i(void *ptr){ 
    28         GenI* sld2i = static_cast<GenI *>(ptr); 
     35void 
     36del_sld2i(PyObject *obj){ 
     37        GenI* sld2i = static_cast<GenI *>(PyCapsule_GetPointer(obj, "GenI")); 
    2938        delete sld2i; 
    3039        return; 
     
    7180        OUTVECTOR(vol_pix_obj, vol_pix, n_x); 
    7281        GenI* sld2i = new GenI(n_pix,x_val,y_val,z_val,sldn_val,mx_val,my_val,mz_val,vol_pix,inspin,outspin,stheta); 
    73         return PyCObject_FromVoidPtr(sld2i, del_sld2i); 
     82        return PyCapsule_New(sld2i, "GenI", del_sld2i); 
    7483} 
    7584 
     
    97106 
    98107        // Set the array pointers 
    99         void *temp = PyCObject_AsVoidPtr(gen_obj); 
     108        void *temp = PyCapsule_GetPointer(gen_obj, "GenI"); 
    100109        GenI* s = static_cast<GenI *>(temp); 
    101110 
     
    125134 
    126135        // Set the array pointers 
    127         void *temp = PyCObject_AsVoidPtr(gen_obj); 
     136        void *temp = PyCapsule_GetPointer(gen_obj, "GenI"); 
    128137        GenI* s = static_cast<GenI *>(temp); 
    129138 
     
    146155}; 
    147156 
    148  
    149 #ifndef PyMODINIT_FUNC  /* declarations for DLL import/export */ 
    150 #define PyMODINIT_FUNC void 
     157#define MODULE_DOC "Sld2i C Library" 
     158#define MODULE_NAME "sld2i" 
     159#define MODULE_INIT2 initsld2i 
     160#define MODULE_INIT3 PyInit_sld2i 
     161#define MODULE_METHODS module_methods 
     162 
     163/* ==== boilerplate python 2/3 interface bootstrap ==== */ 
     164 
     165 
     166#if defined(WIN32) && !defined(__MINGW32__) 
     167    #define DLL_EXPORT __declspec(dllexport) 
     168#else 
     169    #define DLL_EXPORT 
    151170#endif 
    152 PyMODINIT_FUNC 
    153 initsld2i(void) 
    154 { 
    155     Py_InitModule3("sld2i", module_methods, "Sld2i module"); 
    156 } 
     171 
     172#if PY_MAJOR_VERSION >= 3 
     173 
     174  DLL_EXPORT PyMODINIT_FUNC MODULE_INIT3(void) 
     175  { 
     176    static struct PyModuleDef moduledef = { 
     177      PyModuleDef_HEAD_INIT, 
     178      MODULE_NAME,         /* m_name */ 
     179      MODULE_DOC,          /* m_doc */ 
     180      -1,                  /* m_size */ 
     181      MODULE_METHODS,      /* m_methods */ 
     182      NULL,                /* m_reload */ 
     183      NULL,                /* m_traverse */ 
     184      NULL,                /* m_clear */ 
     185      NULL,                /* m_free */ 
     186    }; 
     187    return PyModule_Create(&moduledef); 
     188  } 
     189 
     190#else /* !PY_MAJOR_VERSION >= 3 */ 
     191 
     192  DLL_EXPORT PyMODINIT_FUNC MODULE_INIT2(void) 
     193  { 
     194    Py_InitModule4(MODULE_NAME, 
     195                 MODULE_METHODS, 
     196                 MODULE_DOC, 
     197                 0, 
     198                 PYTHON_API_VERSION 
     199                 ); 
     200  } 
     201 
     202#endif /* !PY_MAJOR_VERSION >= 3 */ 
  • src/sas/sascalc/calculator/instrument.py

    r9a5097c r574adc7  
    222222        """ 
    223223        # check if the wavelength is in range 
    224         if min(band) < self.min or\ 
    225                 max(band) > self.max: 
    226             raise 
     224        if min(band) < self.min or max(band) > self.max: 
     225            raise ValueError("band out of range") 
    227226        self.band = band 
    228227 
     
    239238        """ 
    240239        # check if the wavelength is in range 
    241         if wavelength < min(self.band) or\ 
    242                 wavelength > max(self.band): 
    243             raise 
     240        if wavelength < min(self.band) or wavelength > max(self.band): 
     241            raise ValueError("wavelength out of range") 
    244242        self.wavelength = wavelength 
    245243        validate(wavelength) 
     
    324322            plt.show() 
    325323        except: 
    326             raise RuntimeError, "Can't import matplotlib required to plot..." 
     324            raise RuntimeError("Can't import matplotlib required to plot...") 
    327325 
    328326 
  • src/sas/sascalc/calculator/resolution_calculator.py

    r7432acb r574adc7  
    44instrumental parameters. 
    55""" 
    6 from instrument import Sample 
    7 from instrument import Detector 
    8 from instrument import TOF as Neutron 
    9 from instrument import Aperture 
    10 # import math stuffs 
    11 from math import pi 
    12 from math import sqrt 
     6import sys 
     7from math import pi, sqrt 
    138import math 
     9import logging 
     10 
    1411import numpy as np 
    15 import sys 
    16 import logging 
     12 
     13from .instrument import Sample 
     14from .instrument import Detector 
     15from .instrument import TOF as Neutron 
     16from .instrument import Aperture 
    1717 
    1818logger = logging.getLogger(__name__) 
     
    208208        if wavelength == 0: 
    209209            msg = "Can't compute the resolution: the wavelength is zero..." 
    210             raise RuntimeError, msg 
     210            raise RuntimeError(msg) 
    211211        return self.intensity 
    212212 
     
    379379        if qx_min < self.qx_min: 
    380380            self.qx_min = qx_min 
    381             #raise ValueError, msg 
     381            #raise ValueError(msg) 
    382382        if qx_max > self.qx_max: 
    383383            self.qx_max = qx_max 
    384             #raise ValueError, msg 
     384            #raise ValueError(msg) 
    385385        if qy_min < self.qy_min: 
    386386            self.qy_min = qy_min 
    387             #raise ValueError, msg 
     387            #raise ValueError(msg) 
    388388        if qy_max > self.qy_max: 
    389389            self.qy_max = qy_max 
    390             #raise ValueError, msg 
     390            #raise ValueError(msg) 
    391391        if not full_cal: 
    392392            return None 
     
    503503        # otherwise 
    504504        else: 
    505             raise ValueError, " Improper input..." 
     505            raise ValueError(" Improper input...") 
    506506        # get them squared 
    507507        sigma = x_comp * x_comp 
     
    706706            #self.set_wavelength(wavelength) 
    707707        else: 
    708             raise 
     708            raise TypeError("invalid wavlength---should be list or float") 
    709709 
    710710    def set_wave_spread(self, wavelength_spread): 
     
    717717            self.wave.set_wave_spread_list([wavelength_spread]) 
    718718        else: 
    719             raise 
     719            raise TypeError("invalid wavelength spread---should be list or float") 
    720720 
    721721    def set_wavelength(self, wavelength): 
     
    766766        """ 
    767767        if len(size) < 1 or len(size) > 2: 
    768             raise RuntimeError, "The length of the size must be one or two." 
     768            raise RuntimeError("The length of the size must be one or two.") 
    769769        self.aperture.set_source_size(size) 
    770770 
     
    783783        """ 
    784784        if len(size) < 1 or len(size) > 2: 
    785             raise RuntimeError, "The length of the size must be one or two." 
     785            raise RuntimeError("The length of the size must be one or two.") 
    786786        self.aperture.set_sample_size(size) 
    787787 
     
    806806        """ 
    807807        if len(distance) < 1 or len(distance) > 2: 
    808             raise RuntimeError, "The length of the size must be one or two." 
     808            raise RuntimeError("The length of the size must be one or two.") 
    809809        self.aperture.set_sample_distance(distance) 
    810810 
     
    816816        """ 
    817817        if len(distance) < 1 or len(distance) > 2: 
    818             raise RuntimeError, "The length of the size must be one or two." 
     818            raise RuntimeError("The length of the size must be one or two.") 
    819819        self.sample.set_distance(distance) 
    820820 
     
    826826        """ 
    827827        if len(distance) < 1 or len(distance) > 2: 
    828             raise RuntimeError, "The length of the size must be one or two." 
     828            raise RuntimeError("The length of the size must be one or two.") 
    829829        self.detector.set_distance(distance) 
    830830 
     
    998998            pix_y_size = detector_pix_size[1] 
    999999        else: 
    1000             raise ValueError, " Input value format error..." 
     1000            raise ValueError(" Input value format error...") 
    10011001        # Sample to detector distance = sample slit to detector 
    10021002        # minus sample offset 
  • src/sas/sascalc/calculator/sas_gen.py

    rf2ea95a r1d014cb  
    55from __future__ import print_function 
    66 
    7 import sas.sascalc.calculator.core.sld2i as mod 
    8 from sas.sascalc.calculator.BaseComponent import BaseComponent 
     7import os 
     8import sys 
     9import copy 
     10import logging 
     11 
    912from periodictable import formula 
    1013from periodictable import nsf 
    1114import numpy as np 
    12 import os 
    13 import copy 
    14 import sys 
    15 import logging 
     15 
     16from .core import sld2i as mod 
     17from .BaseComponent import BaseComponent 
    1618 
    1719logger = logging.getLogger(__name__) 
     20 
     21if sys.version_info[0] < 3: 
     22    def decode(s): 
     23        return s 
     24else: 
     25    def decode(s): 
     26        return s.decode() if isinstance(s, bytes) else s 
    1827 
    1928MFACTOR_AM = 2.853E-12 
     
    3443        factor = MFACTOR_MT 
    3544    else: 
    36         raise ValueError, "Invalid valueunit" 
     45        raise ValueError("Invalid valueunit") 
    3746    sld_m = factor * mag 
    3847    return sld_m 
     
    100109        """ 
    101110        if self.data_vol is None: 
    102             raise 
     111            raise TypeError("data_vol is missing") 
    103112        self.data_vol = volume 
    104113 
     
    174183            if len(x[1]) > 0: 
    175184                msg = "Not a 1D." 
    176                 raise ValueError, msg 
     185                raise ValueError(msg) 
    177186            i_out = np.zeros_like(x[0]) 
    178187            # 1D I is found at y =0 in the 2D pattern 
     
    181190        else: 
    182191            msg = "Q must be given as list of qx's and qy's" 
    183             raise ValueError, msg 
     192            raise ValueError(msg) 
    184193 
    185194    def runXY(self, x=0.0): 
     
    196205        else: 
    197206            msg = "Q must be given as list of qx's and qy's" 
    198             raise ValueError, msg 
     207            raise ValueError(msg) 
    199208 
    200209    def evalDistribution(self, qdist): 
     
    214223            mesg = "evalDistribution is expecting an ndarray of " 
    215224            mesg += "a list [qx,qy] where qx,qy are arrays." 
    216             raise RuntimeError, mesg 
     225            raise RuntimeError(mesg) 
    217226 
    218227class OMF2SLD(object): 
     
    288297                z_dir2 *= z_dir2 
    289298                mask = (x_dir2 + y_dir2 + z_dir2) <= 1.0 
    290             except: 
     299            except Exception: 
    291300                logger.error(sys.exc_value) 
    292301        self.output = MagSLD(self.pos_x[mask], self.pos_y[mask], 
     
    313322        :Params length: data length 
    314323        """ 
    315         msg = "Error: Inconsistent data length." 
    316         if len(self.pos_x) != length: 
    317             raise ValueError, msg 
    318         if len(self.pos_y) != length: 
    319             raise ValueError, msg 
    320         if len(self.pos_z) != length: 
    321             raise ValueError, msg 
    322         if len(self.mx) != length: 
    323             raise ValueError, msg 
    324         if len(self.my) != length: 
    325             raise ValueError, msg 
    326         if len(self.mz) != length: 
    327             raise ValueError, msg 
     324        parts = (self.pos_x, self.pos_y, self.pos_z, self.mx, self.my, self.mz) 
     325        if any(len(v) != length for v in parts): 
     326            raise ValueError("Error: Inconsistent data length.") 
    328327 
    329328    def remove_null_points(self, remove=False, recenter=False): 
     
    378377        try: 
    379378            input_f = open(path, 'rb') 
    380             buff = input_f.read() 
     379            buff = decode(input_f.read()) 
    381380            lines = buff.split('\n') 
    382381            input_f.close() 
     
    384383            valueunit = None 
    385384            for line in lines: 
    386                 toks = line.split() 
     385                line = line.strip() 
    387386                # Read data 
    388                 try: 
    389                     _mx = float(toks[0]) 
    390                     _my = float(toks[1]) 
    391                     _mz = float(toks[2]) 
    392                     _mx = mag2sld(_mx, valueunit) 
    393                     _my = mag2sld(_my, valueunit) 
    394                     _mz = mag2sld(_mz, valueunit) 
    395                     mx = np.append(mx, _mx) 
    396                     my = np.append(my, _my) 
    397                     mz = np.append(mz, _mz) 
    398                 except: 
    399                     # Skip non-data lines 
    400                     logger.error(sys.exc_value) 
     387                if line and not line.startswith('#'): 
     388                    try: 
     389                        toks = line.split() 
     390                        _mx = float(toks[0]) 
     391                        _my = float(toks[1]) 
     392                        _mz = float(toks[2]) 
     393                        _mx = mag2sld(_mx, valueunit) 
     394                        _my = mag2sld(_my, valueunit) 
     395                        _mz = mag2sld(_mz, valueunit) 
     396                        mx = np.append(mx, _mx) 
     397                        my = np.append(my, _my) 
     398                        mz = np.append(mz, _mz) 
     399                    except Exception as exc: 
     400                        # Skip non-data lines 
     401                        logger.error(str(exc)+" when processing %r"%line) 
    401402                #Reading Header; Segment count ignored 
    402403                s_line = line.split(":", 1) 
     
    415416                        msg = "Error: \n" 
    416417                        msg += "We accept only m as meshunit" 
    417                         raise ValueError, msg 
     418                        raise ValueError(msg) 
    418419                if s_line[0].lower().count("xbase") > 0: 
    419420                    xbase = s_line[1].lstrip() 
     
    482483            output.set_m(mx, my, mz) 
    483484            return output 
    484         except: 
     485        except Exception: 
    485486            msg = "%s is not supported: \n" % path 
    486487            msg += "We accept only Text format OMF file." 
    487             raise RuntimeError, msg 
     488            raise RuntimeError(msg) 
    488489 
    489490class PDBReader(object): 
     
    522523        try: 
    523524            input_f = open(path, 'rb') 
    524             buff = input_f.read() 
     525            buff = decode(input_f.read()) 
    525526            lines = buff.split('\n') 
    526527            input_f.close() 
     
    536537                            float(line[12]) 
    537538                            atom_name = atom_name[1].upper() 
    538                         except: 
     539                        except Exception: 
    539540                            if len(atom_name) == 4: 
    540541                                atom_name = atom_name[0].upper() 
     
    559560                            vol = 1.0e+24 * atom.mass / atom.density / NA 
    560561                            vol_pix = np.append(vol_pix, vol) 
    561                         except: 
     562                        except Exception: 
    562563                            print("Error: set the sld of %s to zero"% atom_name) 
    563564                            sld_n = np.append(sld_n, 0.0) 
     
    573574                            try: 
    574575                                int_val = int(val) 
    575                             except: 
     576                            except Exception: 
    576577                                break 
    577578                            if int_val == 0: 
     
    592593                        y_lines.append(y_line) 
    593594                        z_lines.append(z_line) 
    594                 except: 
     595                except Exception: 
    595596                    logger.error(sys.exc_value) 
    596597 
     
    604605            output.sld_unit = '1/A^(2)' 
    605606            return output 
    606         except: 
    607             raise RuntimeError, "%s is not a sld file" % path 
     607        except Exception: 
     608            raise RuntimeError("%s is not a sld file" % path) 
    608609 
    609610    def write(self, path, data): 
     
    657658                elif ncols == 7: 
    658659                    vol_pix = None 
    659             except: 
     660            except Exception: 
    660661                # For older version of numpy 
    661662                input_f = open(path, 'rb') 
    662                 buff = input_f.read() 
     663                buff = decode(input_f.read()) 
    663664                lines = buff.split('\n') 
    664665                input_f.close() 
     
    683684                            _vol_pix = float(toks[7]) 
    684685                            vol_pix = np.append(vol_pix, _vol_pix) 
    685                         except: 
     686                        except Exception: 
    686687                            vol_pix = None 
    687                     except: 
     688                    except Exception: 
    688689                        # Skip non-data lines 
    689690                        logger.error(sys.exc_value) 
     
    696697                output.set_pixel_volumes(vol_pix) 
    697698            return output 
    698         except: 
    699             raise RuntimeError, "%s is not a sld file" % path 
     699        except Exception: 
     700            raise RuntimeError("%s is not a sld file" % path) 
    700701 
    701702    def write(self, path, data): 
     
    706707        """ 
    707708        if path is None: 
    708             raise ValueError, "Missing the file path." 
     709            raise ValueError("Missing the file path.") 
    709710        if data is None: 
    710             raise ValueError, "Missing the data to save." 
     711            raise ValueError("Missing the data to save.") 
    711712        x_val = data.pos_x 
    712713        y_val = data.pos_y 
     
    977978                self.ynodes = int(ydist) + 1 
    978979                self.znodes = int(zdist) + 1 
    979             except: 
     980            except Exception: 
    980981                self.xnodes = None 
    981982                self.ynodes = None 
     
    10121013                self.set_pixel_volumes(vol) 
    10131014                self.has_stepsize = True 
    1014             except: 
     1015            except Exception: 
    10151016                self.xstepsize = None 
    10161017                self.ystepsize = None 
     
    10571058    reader = SLDReader() 
    10581059    oreader = OMFReader() 
    1059     output = reader.read(tfpath) 
    1060     ooutput = oreader.read(ofpath) 
     1060    output = decode(reader.read(tfpath)) 
     1061    ooutput = decode(oreader.read(ofpath)) 
    10611062    foutput = OMF2SLD() 
    10621063    foutput.set_data(ooutput) 
     
    10991100            break 
    11001101    oreader = OMFReader() 
    1101     ooutput = oreader.read(ofpath) 
     1102    ooutput = decode(oreader.read(ofpath)) 
    11021103    foutput = OMF2SLD() 
    11031104    foutput.set_data(ooutput) 
  • src/sas/sascalc/corfunc/corfunc_calculator.py

    ra859f99 r574adc7  
    8888        # Only process data of the class Data1D 
    8989        if not issubclass(data.__class__, Data1D): 
    90             raise ValueError, "Data must be of the type DataLoader.Data1D" 
     90            raise ValueError("Data must be of the type DataLoader.Data1D") 
    9191 
    9292        # Prepare the data 
     
    161161            err = ("Incorrect transform type supplied, must be 'fourier'", 
    162162                " or 'hilbert'") 
    163             raise ValueError, err 
     163            raise ValueError(err) 
    164164 
    165165        self._transform_thread.queue() 
  • src/sas/sascalc/data_util/calcthread.py

    ra1b8fee r574adc7  
    66from __future__ import print_function 
    77 
    8 import thread 
    98import traceback 
    109import sys 
    1110import logging 
     11try: 
     12    import _thread as thread 
     13except ImportError: # CRUFT: python 2 support 
     14    import thread 
    1215 
    1316if sys.platform.count("darwin") > 0: 
    1417    import time 
    1518    stime = time.time() 
    16      
     19 
    1720    def clock(): 
    1821        return time.time() - stime 
    19      
     22 
    2023    def sleep(t): 
    2124        return time.sleep(t) 
     
    3538    CalcThread.__init__, passing it the keyword arguments for 
    3639    yieldtime, worktime, update and complete. 
    37      
     40 
    3841    When defining the compute() method you need to include code which 
    3942    allows the GUI to run.  They are as follows: :: 
     
    211214            self._lock.release() 
    212215            self._time_for_update += 1e6  # No more updates 
    213              
     216 
    214217            self.updatefn(**kwargs) 
    215218            sleep(self.yieldtime) 
  • src/sas/sascalc/data_util/nxsunit.py

    r8e9536f r574adc7  
    1313in the NeXus definition files. 
    1414 
    15 Unlike other units packages, this package does not carry the units along with  
     15Unlike other units packages, this package does not carry the units along with 
    1616the value but merely provides a conversion function for transforming values. 
    1717 
     
    6868    Ack! Allows, e.g., Coulomb and coulomb even though Coulomb is not 
    6969    a unit because some NeXus files store it that way! 
    70      
     70 
    7171    Returns a dictionary of names and scales. 
    7272    """ 
     
    7878                        n=1e-9,p=1e-12,f=1e-15) 
    7979    map = {abbr:1} 
    80     map.update([(P+abbr,scale) for (P,scale) in short_prefix.iteritems()]) 
     80    map.update([(P+abbr,scale) for (P,scale) in short_prefix.items()]) 
    8181    for name in [unit,unit.capitalize()]: 
    8282        map.update({name:1,name+'s':1}) 
    83         map.update([(P+name,scale) for (P,scale) in prefix.iteritems()]) 
    84         map.update([(P+'*'+name,scale) for (P,scale) in prefix.iteritems()]) 
    85         map.update([(P+name+'s',scale) for (P,scale) in prefix.iteritems()]) 
     83        map.update([(P+name,scale) for (P,scale) in prefix.items()]) 
     84        map.update([(P+'*'+name,scale) for (P,scale) in prefix.items()]) 
     85        map.update([(P+name+'s',scale) for (P,scale) in prefix.items()]) 
    8686    return map 
    8787 
     
    9191    """ 
    9292    map = {} 
    93     map.update([(name,scale) for name,scale in kw.iteritems()]) 
    94     map.update([(name+'s',scale) for name,scale in kw.iteritems()]) 
     93    map.update([(name,scale) for name,scale in kw.items()]) 
     94    map.update([(name+'s',scale) for name,scale in kw.items()]) 
    9595    return map 
    9696 
     
    101101    * WARNING * this will incorrect transform 10^3 to 103. 
    102102    """ 
    103     s.update((k.replace('^',''),v)  
    104              for k,v in s.items() 
     103    s.update((k.replace('^',''),v) 
     104             for k, v in list(s.items()) 
    105105             if '^' in k) 
    106106 
     
    130130    temperature.update(_build_metric_units('Celcius', 'C')) 
    131131    temperature.update(_build_metric_units('celcius', 'C')) 
    132      
     132 
    133133    charge = _build_metric_units('coulomb','C') 
    134134    charge.update({'microAmp*hour':0.0036}) 
    135135 
    136136    sld = { '10^-6 Angstrom^-2': 1e-6, 'Angstrom^-2': 1 } 
    137     Q = { 'invA': 1, 'invAng': 1, 'invAngstroms': 1, '1/A': 1,  
     137    Q = { 'invA': 1, 'invAng': 1, 'invAngstroms': 1, '1/A': 1, 
    138138          '10^-3 Angstrom^-1': 1e-3, '1/cm': 1e-8, '1/m': 1e-10, 
    139139          'nm^-1': 0.1, '1/nm': 0.1, 'n_m^-1': 0.1 } 
     
    189189 
    190190def _check(expect,get): 
    191     if expect != get: raise ValueError, "Expected %s but got %s"%(expect,get) 
     191    if expect != get: 
     192        raise ValueError("Expected %s but got %s"%(expect, get)) 
    192193     #print expect,"==",get 
    193194 
     
    202203    _check(123,Converter('a.u.')(123,units='s')) # arbitrary units always returns the same value 
    203204    _check(123,Converter('a.u.')(123,units='')) # arbitrary units always returns the same value 
    204     try: Converter('help') 
    205     except KeyError: pass 
    206     else: raise Exception("unknown unit did not raise an error") 
     205    try: 
     206        Converter('help') 
     207    except KeyError: 
     208        pass 
     209    else: 
     210        raise Exception("unknown unit did not raise an error") 
    207211 
    208212    # TODO: more tests 
  • src/sas/sascalc/data_util/odict.py

    rb699768 r574adc7  
    3939    """ 
    4040    A class of dictionary that keeps the insertion order of keys. 
    41      
     41 
    4242    All appropriate methods return keys, items, or values in an ordered way. 
    43      
     43 
    4444    All normal dictionary methods are available. Update and comparison is 
    4545    restricted to other OrderedDict objects. 
    46      
     46 
    4747    Various sequence methods are available, including the ability to explicitly 
    4848    mutate the key ordering. 
    49      
     49 
    5050    __contains__ tests: 
    51      
     51 
    5252    >>> d = OrderedDict(((1, 3),)) 
    5353    >>> 1 in d 
     
    5555    >>> 4 in d 
    5656    0 
    57      
     57 
    5858    __getitem__ tests: 
    59      
     59 
    6060    >>> OrderedDict(((1, 3), (3, 2), (2, 1)))[2] 
    6161    1 
     
    6363    Traceback (most recent call last): 
    6464    KeyError: 4 
    65      
     65 
    6666    __len__ tests: 
    67      
     67 
    6868    >>> len(OrderedDict()) 
    6969    0 
    7070    >>> len(OrderedDict(((1, 3), (3, 2), (2, 1)))) 
    7171    3 
    72      
     72 
    7373    get tests: 
    74      
     74 
    7575    >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    7676    >>> d.get(1) 
     
    8282    >>> d 
    8383    OrderedDict([(1, 3), (3, 2), (2, 1)]) 
    84      
     84 
    8585    has_key tests: 
    86      
     86 
    8787    >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    8888    >>> d.has_key(1) 
     
    9696        Create a new ordered dictionary. Cannot init from a normal dict, 
    9797        nor from kwargs, since items order is undefined in those cases. 
    98          
     98 
    9999        If the ``strict`` keyword argument is ``True`` (``False`` is the 
    100100        default) then when doing slice assignment - the ``OrderedDict`` you are 
    101101        assigning from *must not* contain any keys in the remaining dict. 
    102          
     102 
    103103        >>> OrderedDict() 
    104104        OrderedDict([]) 
     
    283283        """ 
    284284        Used for __repr__ and __str__ 
    285          
     285 
    286286        >>> r1 = repr(OrderedDict((('a', 'b'), ('c', 'd'), ('e', 'f')))) 
    287287        >>> r1 
     
    321321        >>> d 
    322322        OrderedDict([(0, 1), (1, 2), (5, 6), (7, 8), (3, 4)]) 
    323          
     323 
    324324        >>> a = OrderedDict(((0, 1), (1, 2), (2, 3)), strict=True) 
    325325        >>> a[3] = 4 
     
    345345        >>> a 
    346346        OrderedDict([(3, 4), (2, 3), (1, 2), (0, 1)]) 
    347          
     347 
    348348        >>> d = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) 
    349349        >>> d[:1] = 3 
    350350        Traceback (most recent call last): 
    351351        TypeError: slice assignment requires an OrderedDict 
    352          
     352 
    353353        >>> d = OrderedDict([(0, 1), (1, 2), (2, 3), (3, 4)]) 
    354354        >>> d[:1] = OrderedDict([(9, 8)]) 
     
    444444        """ 
    445445        Implemented so that access to ``sequence`` raises a warning. 
    446          
     446 
    447447        >>> d = OrderedDict() 
    448448        >>> d.sequence 
     
    463463        """ 
    464464        To allow deepcopy to work with OrderedDict. 
    465          
     465 
    466466        >>> from copy import deepcopy 
    467467        >>> a = OrderedDict([(1, 1), (2, 2), (3, 3)]) 
     
    490490    def items(self): 
    491491        """ 
    492         ``items`` returns a list of tuples representing all the  
     492        ``items`` returns a list of tuples representing all the 
    493493        ``(key, value)`` pairs in the dictionary. 
    494          
     494 
    495495        >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    496496        >>> d.items() 
     
    505505        """ 
    506506        Return a list of keys in the ``OrderedDict``. 
    507          
     507 
    508508        >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    509509        >>> d.keys() 
     
    515515        """ 
    516516        Return a list of all the values in the OrderedDict. 
    517          
     517 
    518518        Optionally you can pass in a list of values, which will replace the 
    519519        current list. The value list must be the same len as the OrderedDict. 
    520          
     520 
    521521        >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    522522        >>> d.values() 
     
    596596        """ 
    597597        No dict.pop in Python 2.2, gotta reimplement it 
    598          
     598 
    599599        >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    600600        >>> d.pop(3) 
     
    612612        """ 
    613613        if len(args) > 1: 
    614             raise TypeError, ('pop expected at most 2 arguments, got %s' % 
     614            raise TypeError('pop expected at most 2 arguments, got %s' % 
    615615                (len(args) + 1)) 
    616616        if key in self: 
     
    628628        Delete and return an item specified by index, not a random one as in 
    629629        dict. The index is -1 by default (the last item). 
    630          
     630 
    631631        >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    632632        >>> d.popitem() 
     
    674674        """ 
    675675        Update from another OrderedDict or sequence of (key, value) pairs 
    676          
     676 
    677677        >>> d = OrderedDict(((1, 0), (0, 1))) 
    678678        >>> d.update(OrderedDict(((1, 3), (3, 2), (2, 1)))) 
     
    706706        """ 
    707707        Rename the key for a given value, without modifying sequence order. 
    708          
     708 
    709709        For the case where new_key already exists this raise an exception, 
    710710        since if new_key exists, it is ambiguous as to what happens to the 
    711711        associated values, and the position of new_key in the sequence. 
    712          
     712 
    713713        >>> od = OrderedDict() 
    714714        >>> od['a'] = 1 
     
    732732            raise ValueError("New key already exists: %r" % new_key) 
    733733        # rename sequence entry 
    734         value = self[old_key]  
     734        value = self[old_key] 
    735735        old_idx = self._sequence.index(old_key) 
    736736        self._sequence[old_idx] = new_key 
     
    742742        """ 
    743743        This method allows you to set the items in the dict. 
    744          
     744 
    745745        It takes a list of tuples - of the same sort returned by the ``items`` 
    746746        method. 
    747          
     747 
    748748        >>> d = OrderedDict() 
    749749        >>> d.setitems(((3, 1), (2, 3), (1, 2))) 
     
    760760        replace the current set. This must contain the same set of keys, but 
    761761        need not be in the same order. 
    762          
     762 
    763763        If you pass in new keys that don't match, a ``KeyError`` will be 
    764764        raised. 
    765          
     765 
    766766        >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    767767        >>> d.keys() 
     
    791791        You can pass in a list of values, which will replace the 
    792792        current list. The value list must be the same len as the OrderedDict. 
    793          
     793 
    794794        (Or a ``ValueError`` is raised.) 
    795          
     795 
    796796        >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    797797        >>> d.setvalues((1, 2, 3)) 
     
    813813        """ 
    814814        Return the position of the specified key in the OrderedDict. 
    815          
     815 
    816816        >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    817817        >>> d.index(3) 
     
    826826        """ 
    827827        Takes ``index``, ``key``, and ``value`` as arguments. 
    828          
     828 
    829829        Sets ``key`` to ``value``, so that ``key`` is at position ``index`` in 
    830830        the OrderedDict. 
    831          
     831 
    832832        >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    833833        >>> d.insert(0, 4, 0) 
     
    850850        """ 
    851851        Reverse the order of the OrderedDict. 
    852          
     852 
    853853        >>> d = OrderedDict(((1, 3), (3, 2), (2, 1))) 
    854854        >>> d.reverse() 
     
    861861        """ 
    862862        Sort the key order in the OrderedDict. 
    863          
     863 
    864864        This method takes the same arguments as the ``list.sort`` method on 
    865865        your version of Python. 
    866          
     866 
    867867        >>> d = OrderedDict(((4, 1), (2, 2), (3, 3), (1, 4))) 
    868868        >>> d.sort() 
     
    876876    """ 
    877877    Custom object for accessing the keys of an OrderedDict. 
    878      
     878 
    879879    Can be called like the normal ``OrderedDict.keys`` method, but also 
    880880    supports indexing and sequence methods. 
     
    897897        You cannot assign to keys, but you can do slice assignment to re-order 
    898898        them. 
    899          
     899 
    900900        You can only do slice assignment if the new set of keys is a reordering 
    901901        of the original set. 
     
    967967    """ 
    968968    Custom object for accessing the items of an OrderedDict. 
    969      
     969 
    970970    Can be called like the normal ``OrderedDict.items`` method, but also 
    971971    supports indexing and sequence methods. 
     
    10771077    """ 
    10781078    Custom object for accessing the values of an OrderedDict. 
    1079      
     1079 
    10801080    Can be called like the normal ``OrderedDict.values`` method, but also 
    10811081    supports indexing and sequence methods. 
     
    10991099        """ 
    11001100        Set the value at position i to value. 
    1101          
     1101 
    11021102        You can only do slice assignment to values if you supply a sequence of 
    11031103        equal length to the slice you are replacing. 
     
    11681168    Experimental version of OrderedDict that has a custom object for ``keys``, 
    11691169    ``values``, and ``items``. 
    1170      
     1170 
    11711171    These are callable sequence objects that work as methods, or can be 
    11721172    manipulated directly as sequences. 
    1173      
     1173 
    11741174    Test for ``keys``, ``items`` and ``values``. 
    1175      
     1175 
    11761176    >>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4))) 
    11771177    >>> d 
     
    12931293    >>> d 
    12941294    SequenceOrderedDict([(1, 1), (2, 2), (3, 3)]) 
    1295      
     1295 
    12961296    >>> d = SequenceOrderedDict(((1, 2), (2, 3), (3, 4))) 
    12971297    >>> d 
  • src/sas/sascalc/data_util/registry.py

    r5a8cdbb rdc8d1c2  
    101101        extlist = [ext for ext in self.extensions() if path.endswith(ext)] 
    102102        # Sort matching extensions by decreasing order of length 
    103         extlist.sort(lambda a,b: len(a)<len(b)) 
     103        extlist.sort(key=len) 
    104104        # Combine loaders for matching extensions into one big list 
    105105        loaders = [] 
  • src/sas/sascalc/data_util/uncertainty.py

    r9a5097c r574adc7  
    22Uncertainty propagation class for arithmetic, log and exp. 
    33 
    4 Based on scalars or numpy vectors, this class allows you to store and  
     4Based on scalars or numpy vectors, this class allows you to store and 
    55manipulate values+uncertainties, with propagation of gaussian error for 
    66addition, subtraction, multiplication, division, power, exp and log. 
    77 
    88Storage properties are determined by the numbers used to set the value 
    9 and uncertainty.  Be sure to use floating point uncertainty vectors  
     9and uncertainty.  Be sure to use floating point uncertainty vectors 
    1010for inplace operations since numpy does not do automatic type conversion. 
    1111Normal operations can use mixed integer and floating point.  In place 
     
    1818 
    1919import numpy as np 
    20 import err1d 
    21 from formatnum import format_uncertainty 
     20 
     21from .import err1d 
     22from .formatnum import format_uncertainty 
    2223 
    2324__all__ = ['Uncertainty'] 
     
    2829    # Make standard deviation available 
    2930    def _getdx(self): return np.sqrt(self.variance) 
    30     def _setdx(self,dx):  
     31    def _setdx(self,dx): 
    3132        # Direct operation 
    3233        #    variance = dx**2 
     
    3839    # Constructor 
    3940    def __init__(self, x, variance=None): 
    40         self.x, self.variance = x, variance     
    41   
     41        self.x, self.variance = x, variance 
     42 
    4243    # Numpy array slicing operations 
    43     def __len__(self):  
     44    def __len__(self): 
    4445        return len(self.x) 
    45     def __getitem__(self,key):  
     46    def __getitem__(self,key): 
    4647        return Uncertainty(self.x[key],self.variance[key]) 
    4748    def __setitem__(self,key,value): 
     
    137138    def __idiv__(self, other): return self.__itruediv__(other) 
    138139 
    139          
     140 
    140141    # Unary ops 
    141142    def __neg__(self): 
     
    151152            return format_uncertainty(self.x,np.sqrt(self.variance)) 
    152153        else: 
    153             return [format_uncertainty(v,dv)  
     154            return [format_uncertainty(v,dv) 
    154155                    for v,dv in zip(self.x,np.sqrt(self.variance))] 
    155156    def __repr__(self): 
     
    219220    z = a/4 
    220221    assert z.x == 5./4 and z.variance == 3./4**2 
    221      
     222 
    222223    # Reverse scalar operations 
    223224    z = 4+a 
     
    229230    z = 4/a 
    230231    assert z.x == 4./5 and abs(z.variance - 3./5**4 * 4**2) < 1e-15 
    231      
     232 
    232233    # Power operations 
    233234    z = a**2 
     
    250251    assert z.x == 5./4 and abs(z.variance - (3./5**2 + 2./4**2)*(5./4)**2) < 1e-15 
    251252 
    252     # ===== Inplace operations =====     
     253    # ===== Inplace operations ===== 
    253254    # Scalar operations 
    254255    y = a+0; y += 4 
     
    308309    assert (z.x == 5./4).all() 
    309310    assert (abs(z.variance - (3./5**2 + 2./4**2)*(5./4)**2) < 1e-15).all() 
    310      
     311 
    311312    # printing; note that sqrt(3) ~ 1.7 
    312313    assert str(Uncertainty(5,3)) == "5.0(17)" 
  • src/sas/sascalc/dataloader/__init__.py

    rb699768 r574adc7  
    1 from data_info import * 
    2 from manipulations import * 
    3 from readers import * 
     1from .data_info import * 
     2from .manipulations import * 
     3from .readers import * 
  • src/sas/sascalc/dataloader/loader.py

    rdcb91cf rdc8d1c2  
    2626import time 
    2727from zipfile import ZipFile 
     28 
    2829from sas.sascalc.data_util.registry import ExtensionRegistry 
     30 
    2931# Default readers are defined in the readers sub-module 
    30 import readers 
    31 from loader_exceptions import NoKnownLoaderException, FileContentsException,\ 
     32from . import readers 
     33from .loader_exceptions import NoKnownLoaderException, FileContentsException,\ 
    3234    DefaultReaderException 
    33 from readers import ascii_reader 
    34 from readers import cansas_reader 
    35 from readers import cansas_reader_HDF5 
     35from .readers import ascii_reader 
     36from .readers import cansas_reader 
     37from .readers import cansas_reader_HDF5 
    3638 
    3739logger = logging.getLogger(__name__) 
     
    7375        try: 
    7476            return super(Registry, self).load(path, format=format) 
     77        #except Exception: raise  # for debugging, don't use fallback loader 
    7578        except NoKnownLoaderException as nkl_e: 
    7679            pass  # Try the ASCII reader 
     
    327330        extlist = [ext for ext in self.extensions() if path.endswith(ext)] 
    328331        # Sort matching extensions by decreasing order of length 
    329         extlist.sort(lambda a, b: len(a) < len(b)) 
     332        extlist.sort(key=len) 
    330333        # Combine loaders for matching extensions into one big list 
    331334        writers = [] 
     
    341344        # Raise an error if there are no matching extensions 
    342345        if len(writers) == 0: 
    343             raise ValueError, "Unknown file type for " + path 
     346            raise ValueError("Unknown file type for " + path) 
    344347        # All done 
    345348        return writers 
     
    360363            try: 
    361364                return fn(path, data) 
    362             except: 
     365            except Exception: 
    363366                pass  # give other loaders a chance to succeed 
    364367        # If we get here it is because all loaders failed 
  • src/sas/sascalc/dataloader/manipulations.py

    r324e0bf r574adc7  
    2626 
    2727#from data_info import plottable_2D 
    28 from data_info import Data1D 
     28from .data_info import Data1D 
    2929 
    3030 
  • src/sas/sascalc/dataloader/readers/__init__.py

    r488f3a5 raaa801e  
    11# Method to associate extensions to default readers 
    2 from associations import read_associations 
     2from .associations import read_associations 
  • src/sas/sascalc/dataloader/readers/anton_paar_saxs_reader.py

    rfafe52a ra5bd87a  
    6363        ## Reinitialize the class when loading a new data file to reset all class variables 
    6464        self.reset_state() 
    65         buff = self.f_open.read() 
     65        buff = self.readall() 
    6666        self.raw_data = buff.splitlines() 
    6767        self.read_data() 
  • src/sas/sascalc/dataloader/readers/associations.py

    rce8c7bd r574adc7  
    4040    """ 
    4141    # For each FileType entry, get the associated reader and extension 
    42     for ext, reader in settings.iteritems(): 
     42    for ext, reader in settings.items(): 
    4343        if reader is not None and ext is not None: 
    4444            # Associate the extension with a particular reader 
     
    4747            # and remove the extra line below. 
    4848            try: 
    49                 exec "import %s" % reader 
    50                 exec "loader.associate_file_type('%s', %s)" % (ext.lower(), 
    51                                                                 reader) 
    52                 exec "loader.associate_file_type('%s', %s)" % (ext.upper(), 
    53                                                                 reader) 
     49                exec("from . import %s" % reader) 
     50                exec("loader.associate_file_type('%s', %s)" 
     51                     % (ext.lower(), reader)) 
     52                exec("loader.associate_file_type('%s', %s)" 
     53                     % (ext.upper(), reader)) 
    5454            except: 
    5555                msg = "read_associations: skipping association" 
  • src/sas/sascalc/dataloader/readers/cansas_reader_HDF5.py

    rcd57c7d4 r7b50f14  
    99import sys 
    1010 
    11 from sas.sascalc.dataloader.data_info import plottable_1D, plottable_2D,\ 
     11from ..data_info import plottable_1D, plottable_2D,\ 
    1212    Data1D, Data2D, DataInfo, Process, Aperture, Collimation, \ 
    1313    TransmissionSpectrum, Detector 
    14 from sas.sascalc.dataloader.data_info import combine_data_info_with_plottable 
    15 from sas.sascalc.dataloader.loader_exceptions import FileContentsException, DefaultReaderException 
    16 from sas.sascalc.dataloader.file_reader_base_class import FileReader 
    17  
     14from ..data_info import combine_data_info_with_plottable 
     15from ..loader_exceptions import FileContentsException, DefaultReaderException 
     16from ..file_reader_base_class import FileReader, decode 
     17 
     18def h5attr(node, key, default=None): 
     19    return decode(node.attrs.get(key, default)) 
    1820 
    1921class Reader(FileReader): 
     
    130132            # Get all information for the current key 
    131133            value = data.get(key) 
    132             if value.attrs.get(u'canSAS_class') is not None: 
    133                 class_name = value.attrs.get(u'canSAS_class') 
    134             else: 
    135                 class_name = value.attrs.get(u'NX_class') 
     134            class_name = h5attr(value, u'canSAS_class') 
     135            if class_name is None: 
     136                class_name = h5attr(value, u'NX_class') 
    136137            if class_name is not None: 
    137138                class_prog = re.compile(class_name) 
     
    225226 
    226227                for data_point in data_set: 
     228                    if data_point.dtype.char == 'S': 
     229                        data_point = decode(bytes(data_point)) 
    227230                    # Top Level Meta Data 
    228231                    if key == u'definition': 
     
    231234                        self.current_datainfo.run.append(data_point) 
    232235                        try: 
    233                             run_name = value.attrs['name'] 
     236                            run_name = h5attr(value, 'name') 
    234237                            run_dict = {data_point: run_name} 
    235238                            self.current_datainfo.run_name = run_dict 
    236                         except: 
     239                        except Exception: 
    237240                            pass 
    238241                    elif key == u'title': 
     
    576579        :return: unit for the value passed to the method 
    577580        """ 
    578         unit = value.attrs.get(u'units') 
     581        unit = h5attr(value, u'units') 
    579582        if unit is None: 
    580             unit = value.attrs.get(u'unit') 
     583            unit = h5attr(value, u'unit') 
    581584        # Convert the unit formats 
    582585        if unit == "1/A": 
  • src/sas/sascalc/dataloader/readers/danse_reader.py

    ra78a02f raf3e9f5  
    1414import math 
    1515import os 
     16import logging 
     17 
    1618import numpy as np 
    17 import logging 
    18 from sas.sascalc.dataloader.data_info import plottable_2D, DataInfo, Detector 
    19 from sas.sascalc.dataloader.manipulations import reader2D_converter 
    20 from sas.sascalc.dataloader.file_reader_base_class import FileReader 
    21 from sas.sascalc.dataloader.loader_exceptions import FileContentsException, DataReaderException 
     19 
     20from ..data_info import plottable_2D, DataInfo, Detector 
     21from ..manipulations import reader2D_converter 
     22from ..file_reader_base_class import FileReader 
     23from ..loader_exceptions import FileContentsException, DataReaderException 
    2224 
    2325logger = logging.getLogger(__name__) 
     
    7880        data_start_line = 1 
    7981        while read_on: 
    80             line = self.f_open.readline() 
     82            line = self.nextline() 
    8183            data_start_line += 1 
    8284            if line.find("DATA:") >= 0: 
     
    112114            raise FileContentsException(msg) 
    113115 
    114         for line_num, data_str in enumerate(self.f_open.readlines()): 
     116        for line_num, data_str in enumerate(self.nextlines()): 
    115117            toks = data_str.split() 
    116118            try: 
  • src/sas/sascalc/dataloader/readers/red2d_reader.py

    r2f85af7 rc8321cfc  
    1010###################################################################### 
    1111import os 
     12import math 
     13import time 
     14 
    1215import numpy as np 
    13 import math 
    14 from sas.sascalc.dataloader.data_info import plottable_2D, DataInfo, Detector 
    15 from sas.sascalc.dataloader.file_reader_base_class import FileReader 
    16 from sas.sascalc.dataloader.loader_exceptions import FileContentsException 
    17  
    18 # Look for unit converter 
    19 has_converter = True 
    20 try: 
    21     from sas.sascalc.data_util.nxsunit import Converter 
    22 except: 
    23     has_converter = False 
     16 
     17from sas.sascalc.data_util.nxsunit import Converter 
     18 
     19from ..data_info import plottable_2D, DataInfo, Detector 
     20from ..file_reader_base_class import FileReader 
     21from ..loader_exceptions import FileContentsException 
    2422 
    2523 
     
    3129    try: 
    3230        return float(x_point) 
    33     except: 
     31    except Exception: 
    3432        return 0 
    3533 
     
    5149        :param data: data2D 
    5250        """ 
    53         import time 
    5451        # Write the file 
    5552        try: 
     
    7269    def get_file_contents(self): 
    7370        # Read file 
    74         buf = self.f_open.read() 
     71        buf = self.readall() 
    7572        self.f_open.close() 
    7673        # Instantiate data object 
     
    119116                try: 
    120117                    wavelength = float(line_toks[1]) 
    121                     # Units 
    122                     if has_converter == True and \ 
    123                     self.current_datainfo.source.wavelength_unit != 'A': 
     118                    # Wavelength is stored in angstroms; convert if necessary 
     119                    if self.current_datainfo.source.wavelength_unit != 'A': 
    124120                        conv = Converter('A') 
    125121                        wavelength = conv(wavelength, 
    126122                                          units=self.current_datainfo.source.wavelength_unit) 
    127                 except: 
    128                     #Not required 
    129                     pass 
    130                 # Distance in mm 
     123                except Exception: 
     124                    pass  # Not required 
    131125                try: 
    132126                    distance = float(line_toks[3]) 
    133                     # Units 
    134                     if has_converter == True and self.current_datainfo.detector[0].distance_unit != 'm': 
     127                    # Distance is stored in meters; convert if necessary 
     128                    if self.current_datainfo.detector[0].distance_unit != 'm': 
    135129                        conv = Converter('m') 
    136130                        distance = conv(distance, 
    137131                            units=self.current_datainfo.detector[0].distance_unit) 
    138                 except: 
    139                     #Not required 
    140                     pass 
    141  
    142                 # Distance in meters 
     132                except Exception: 
     133                    pass  # Not required 
     134 
    143135                try: 
    144136                    transmission = float(line_toks[4]) 
    145                 except: 
    146                     #Not required 
    147                     pass 
     137                except Exception: 
     138                    pass  # Not required 
    148139 
    149140            if line.count("LAMBDA") > 0: 
     
    170161 
    171162            ## Read and get data. 
    172             if data_started == True: 
     163            if data_started: 
    173164                line_toks = line.split() 
    174165                if len(line_toks) == 0: 
     
    178169                col_num = len(line_toks) 
    179170                break 
     171 
    180172        # Make numpy array to remove header lines using index 
    181173        lines_array = np.array(lines) 
     
    203195        # Change it(string) into float 
    204196        #data_list = map(float,data_list) 
    205         data_list1 = map(check_point, data_list) 
     197        data_list1 = list(map(check_point, data_list)) 
    206198 
    207199        # numpy array form 
     
    211203        try: 
    212204            data_point = data_array.reshape(row_num, col_num).transpose() 
    213         except: 
     205        except Exception: 
    214206            msg = "red2d_reader can't read this file: Incorrect number of data points provided." 
    215207            raise FileContentsException(msg) 
     
    325317 
    326318        # Units of axes 
    327         self.current_dataset.xaxis("\\rm{Q_{x}}", 'A^{-1}') 
    328         self.current_dataset.yaxis("\\rm{Q_{y}}", 'A^{-1}') 
    329         self.current_dataset.zaxis("\\rm{Intensity}", "cm^{-1}") 
     319        self.current_dataset.xaxis(r"\rm{Q_{x}}", 'A^{-1}') 
     320        self.current_dataset.yaxis(r"\rm{Q_{y}}", 'A^{-1}') 
     321        self.current_dataset.zaxis(r"\rm{Intensity}", "cm^{-1}") 
    330322 
    331323        # Store loading process information 
  • src/sas/sascalc/dataloader/readers/sesans_reader.py

    rbe43448 r849094a  
    66    Jurrian Bakker 
    77""" 
     8import os 
     9 
    810import numpy as np 
    9 import os 
    10 from sas.sascalc.dataloader.file_reader_base_class import FileReader 
    11 from sas.sascalc.dataloader.data_info import plottable_1D, DataInfo 
    12 from sas.sascalc.dataloader.loader_exceptions import FileContentsException, DataReaderException 
     11 
     12from ..file_reader_base_class import FileReader 
     13from ..data_info import plottable_1D, DataInfo 
     14from ..loader_exceptions import FileContentsException, DataReaderException 
    1315 
    1416# Check whether we have a converter available 
     
    4244        self.output = [] 
    4345 
    44         line = self.f_open.readline() 
     46        line = self.nextline() 
    4547        params = {} 
    4648        while not line.startswith("BEGIN_DATA"): 
     
    4850            if len(terms) >= 2: 
    4951                params[terms[0]] = " ".join(terms[1:]) 
    50             line = self.f_open.readline() 
     52            line = self.nextline() 
    5153        self.params = params 
    5254 
     
    6870                               "handled by other software.") 
    6971 
    70         headers = self.f_open.readline().split() 
     72        headers = self.nextline().split() 
    7173 
    7274        self._insist_header(headers, "SpinEchoLength") 
  • src/sas/sascalc/dataloader/readers/tiff_reader.py

    r959eb01 r574adc7  
    22#This software was developed by the University of Tennessee as part of the 
    33#Distributed Data Analysis of Neutron Scattering Experiments (DANSE) 
    4 #project funded by the US National Science Foundation.  
     4#project funded by the US National Science Foundation. 
    55#See the license text in license.txt 
    66#copyright 2008, University of Tennessee 
     
    3131    ## Extension 
    3232    ext = ['.tif', '.tiff'] 
    33          
     33 
    3434    def read(self, filename=None): 
    3535        """ 
    3636        Open and read the data in a file 
    37          
     37 
    3838        :param file: path of the file 
    3939        """ 
     
    4444        except: 
    4545            msg = "tiff_reader: could not load file. Missing Image module." 
    46             raise RuntimeError, msg 
    47          
     46            raise RuntimeError(msg) 
     47 
    4848        # Instantiate data object 
    4949        output = Data2D() 
    5050        output.filename = os.path.basename(filename) 
    51              
     51 
    5252        # Read in the image 
    5353        try: 
    5454            im = Image.open(filename) 
    5555        except: 
    56             raise  RuntimeError, "cannot open %s"%(filename) 
     56            raise  RuntimeError("cannot open %s"%(filename)) 
    5757        data = im.getdata() 
    5858 
     
    6161        output.err_data = np.zeros([im.size[0], im.size[1]]) 
    6262        output.mask = np.ones([im.size[0], im.size[1]], dtype=bool) 
    63          
     63 
    6464        # Initialize 
    6565        x_vals = [] 
     
    6969        for i_x in range(im.size[0]): 
    7070            x_vals.append(i_x) 
    71              
     71 
    7272        itot = 0 
    7373        for i_y in range(im.size[1]): 
     
    8080                logger.error("tiff_reader: had to skip a non-float point") 
    8181                continue 
    82              
     82 
    8383            # Get bin number 
    8484            if math.fmod(itot, im.size[0]) == 0: 
     
    8787            else: 
    8888                i_x += 1 
    89                  
     89 
    9090            output.data[im.size[1] - 1 - i_y][i_x] = value 
    91              
     91 
    9292            itot += 1 
    93                  
     93 
    9494        output.xbins = im.size[0] 
    9595        output.ybins = im.size[1] 
     
    102102        output.ymin = 0 
    103103        output.ymax = im.size[0] - 1 
    104          
     104 
    105105        # Store loading process information 
    106106        output.meta_data['loader'] = self.type_name 
  • src/sas/sascalc/dataloader/readers/xml_reader.py

    rcd57c7d4 r7b50f14  
    1616 
    1717import logging 
     18 
    1819from lxml import etree 
    1920from lxml.builder import E 
    20 from sas.sascalc.dataloader.file_reader_base_class import FileReader 
     21 
     22from ..file_reader_base_class import FileReader, decode 
    2123 
    2224logger = logging.getLogger(__name__) 
     
    151153        Converts an etree element into a string 
    152154        """ 
    153         return etree.tostring(elem, pretty_print=pretty_print, \ 
    154                               encoding=encoding) 
     155        return decode(etree.tostring(elem, pretty_print=pretty_print, 
     156                                     encoding=encoding)) 
    155157 
    156158    def break_processing_instructions(self, string, dic): 
  • src/sas/sascalc/file_converter/c_ext/bsl_loader.c

    r2ab9c432 rd04ac05  
    11#include <Python.h> 
    2 //#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION 
     2#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION 
    33#include <numpy/arrayobject.h> 
    44#include <stdio.h> 
     
    4444static void CLoader_dealloc(CLoader *self) { 
    4545    free(self->params.filename); 
    46     self->ob_type->tp_free((PyObject *)self); 
     46    Py_TYPE(self)->tp_free((PyObject *)self); 
    4747} 
    4848 
     
    237237 
    238238static PyTypeObject CLoaderType = { 
    239     PyObject_HEAD_INIT(NULL) 
    240     0,                         /*ob_size*/ 
     239    //PyObject_HEAD_INIT(NULL) 
     240    //0,                         /*ob_size*/ 
     241    PyVarObject_HEAD_INIT(NULL, 0) 
    241242    "CLoader",             /*tp_name*/ 
    242243    sizeof(CLoader),             /*tp_basicsize*/ 
     
    278279}; 
    279280 
    280 PyMODINIT_FUNC 
    281 initbsl_loader(void) 
    282 { 
    283     PyObject *module; 
    284     module = Py_InitModule("bsl_loader", NULL); 
    285     import_array(); 
    286  
     281static PyMethodDef module_methods[] = { 
     282    {NULL} 
     283}; 
     284 
     285/** 
     286 * Function used to add the model class to a module 
     287 * @param module: module to add the class to 
     288 */ 
     289void addCLoader(PyObject *module) { 
    287290    if (PyType_Ready(&CLoaderType) < 0) 
    288291        return; 
    289292 
    290293    Py_INCREF(&CLoaderType); 
    291     PyModule_AddObject(module, "CLoader", (PyObject *)&CLoaderType); 
    292 } 
     294    PyModule_AddObject(module, "bsl_loader", (PyObject *)&CLoaderType); 
     295} 
     296 
     297 
     298#define MODULE_DOC "C module for loading bsl." 
     299#define MODULE_NAME "bsl_loader" 
     300#define MODULE_INIT2 initbsl_loader 
     301#define MODULE_INIT3 PyInit_bsl_loader 
     302#define MODULE_METHODS module_methods 
     303 
     304/* ==== boilerplate python 2/3 interface bootstrap ==== */ 
     305 
     306 
     307#if defined(WIN32) && !defined(__MINGW32__) 
     308    #define DLL_EXPORT __declspec(dllexport) 
     309#else 
     310    #define DLL_EXPORT 
     311#endif 
     312 
     313#if PY_MAJOR_VERSION >= 3 
     314 
     315  DLL_EXPORT PyMODINIT_FUNC MODULE_INIT3(void) 
     316  { 
     317    static struct PyModuleDef moduledef = { 
     318      PyModuleDef_HEAD_INIT, 
     319      MODULE_NAME,         /* m_name */ 
     320      MODULE_DOC,          /* m_doc */ 
     321      -1,                  /* m_size */ 
     322      MODULE_METHODS,      /* m_methods */ 
     323      NULL,                /* m_reload */ 
     324      NULL,                /* m_traverse */ 
     325      NULL,                /* m_clear */ 
     326      NULL,                /* m_free */ 
     327    }; 
     328        PyObject* m = PyModule_Create(&moduledef); 
     329        addCLoader(m); 
     330        return m; 
     331  } 
     332 
     333#else /* !PY_MAJOR_VERSION >= 3 */ 
     334 
     335  DLL_EXPORT PyMODINIT_FUNC MODULE_INIT2(void) 
     336  { 
     337    PyObject* m = Py_InitModule4(MODULE_NAME, 
     338                 MODULE_METHODS, 
     339                 MODULE_DOC, 
     340                 0, 
     341                 PYTHON_API_VERSION 
     342                 ); 
     343        addCLoader(m); 
     344  } 
     345 
     346#endif /* !PY_MAJOR_VERSION >= 3 */ 
  • src/sas/sascalc/file_converter/cansas_writer.py

    r7432acb r574adc7  
    3232        valid_class = all([issubclass(data.__class__, Data1D) for data in frame_data]) 
    3333        if not valid_class: 
    34             raise RuntimeError, ("The cansas writer expects an array of " 
     34            raise RuntimeError("The cansas writer expects an array of " 
    3535                "Data1D instances") 
    3636 
  • src/sas/sascalc/file_converter/nxcansas_writer.py

    r5e906207 r574adc7  
    166166            'wavelength_max': 'wavelength_max', 
    167167            'wavelength_spread': 'incident_wavelength_spread' } 
    168         for sasname, nxname in wavelength_keys.iteritems(): 
     168        for sasname, nxname in wavelength_keys.items(): 
    169169            value = getattr(data_info.source, sasname) 
    170170            units = getattr(data_info.source, sasname + '_unit') 
  • src/sas/sascalc/fit/AbstractFitEngine.py

    r50fcb09 r574adc7  
    251251            msg = "FitData1D: invalid error array " 
    252252            msg += "%d <> %d" % (np.shape(self.dy), np.size(fx)) 
    253             raise RuntimeError, msg 
     253            raise RuntimeError(msg) 
    254254        return (self.y[self.idx] - fx[self.idx]) / self.dy[self.idx], fx[self.idx] 
    255255 
  • src/sas/sascalc/fit/Loader.py

    ra1b8fee r574adc7  
    1818        self.dy = dy 
    1919        self.filename = None 
    20          
     20 
    2121    def set_filename(self, path=None): 
    2222        """ 
    23         Store path into a variable.If the user doesn't give  
     23        Store path into a variable.If the user doesn't give 
    2424        a path as a parameter a pop-up 
    2525        window appears to select the file. 
    26          
     26 
    2727        :param path: the path given by the user 
    28          
     28 
    2929        """ 
    3030        self.filename = path 
    31         
     31 
    3232    def get_filename(self): 
    3333        """ return the file's path""" 
    3434        return self.filename 
    35      
     35 
    3636    def set_values(self): 
    3737        """ Store the values loaded from file in local variables""" 
     
    4242            self.x = [] 
    4343            self.y = [] 
    44             self.dx = []  
     44            self.dx = [] 
    4545            self.dy = [] 
    4646            for line in lines: 
     
    5050                    y = float(toks[1]) 
    5151                    dy = float(toks[2]) 
    52                      
     52 
    5353                    self.x.append(x) 
    5454                    self.y.append(y) 
     
    5959            # Sanity check 
    6060            if not len(self.x) == len(self.dx): 
    61                 raise ValueError, "x and dx have different length" 
     61                raise ValueError("x and dx have different length") 
    6262            if not len(self.y) == len(self.dy): 
    63                 raise ValueError, "y and dy have different length" 
    64              
    65              
     63                raise ValueError("y and dy have different length") 
     64 
     65 
    6666    def get_values(self): 
    6767        """ Return x, y, dx, dy""" 
    6868        return self.x, self.y, self.dx, self.dy 
    69      
     69 
    7070    def load_data(self, data): 
    7171        """ Return plottable""" 
     
    7777        #Load its View class 
    7878        #plottable.reset_view() 
    79         
    80      
    81 if __name__ == "__main__":  
     79 
     80 
     81if __name__ == "__main__": 
    8282    load = Load() 
    8383    load.set_filename("testdata_line.txt") 
    84     print(load.get_filename())  
     84    print(load.get_filename()) 
    8585    load.set_values() 
    8686    print(load.get_values()) 
    87      
    88              
     87 
  • src/sas/sascalc/fit/MultiplicationModel.py

    r7432acb r574adc7  
    109109        """ 
    110110        ##set dispersion only from p_model 
    111         for name , value in self.p_model.dispersion.iteritems(): 
     111        for name , value in self.p_model.dispersion.items(): 
    112112            self.dispersion[name] = value 
    113113 
     
    135135        """ 
    136136 
    137         for name , value in self.p_model.params.iteritems(): 
     137        for name , value in self.p_model.params.items(): 
    138138            if not name in self.params.keys() and name not in self.excluded_params: 
    139139                self.params[name] = value 
    140140 
    141         for name , value in self.s_model.params.iteritems(): 
     141        for name , value in self.s_model.params.items(): 
    142142            #Remove the radius_effective from the (P*S) model parameters. 
    143143            if not name in self.params.keys() and name not in self.excluded_params: 
     
    155155        this model's details 
    156156        """ 
    157         for name, detail in self.p_model.details.iteritems(): 
     157        for name, detail in self.p_model.details.items(): 
    158158            if name not in self.excluded_params: 
    159159                self.details[name] = detail 
    160160 
    161         for name , detail in self.s_model.details.iteritems(): 
     161        for name , detail in self.s_model.details.items(): 
    162162            if not name in self.details.keys() or name not in self.exluded_params: 
    163163                self.details[name] = detail 
     
    245245                    return 
    246246 
    247         raise ValueError, "Model does not contain parameter %s" % name 
     247        raise ValueError("Model does not contain parameter %s" % name) 
    248248 
    249249 
  • src/sas/sascalc/fit/expression.py

    ra1b8fee r574adc7  
    5959    occur multiple times.  The return value is a set with the elements in 
    6060    no particular order. 
    61      
     61 
    6262    This is the first step in computing a dependency graph. 
    6363    """ 
     
    8181        offset = end 
    8282    pieces.append(expr[offset:]) 
    83      
     83 
    8484    # Join the pieces and return them 
    8585    return "".join(pieces) 
     
    8888    """ 
    8989    Returns a list of pair-wise dependencies from the parameter expressions. 
    90      
     90 
    9191    For example, if p3 = p1+p2, then find_dependencies([p1,p2,p3]) will 
    9292    return [(p3,p1),(p3,p2)].  For base expressions without dependencies, 
     
    110110    """ 
    111111    Find the parameter substitution we need so that expressions can 
    112     be evaluated without having to traverse a chain of  
     112    be evaluated without having to traverse a chain of 
    113113    model.layer.parameter.value 
    114114    """ 
     
    122122    return definition, substitution 
    123123 
    124 def no_constraints():  
     124def no_constraints(): 
    125125    """ 
    126126    This parameter set has no constraints between the parameters. 
     
    163163 
    164164    Parameter names are assumed to contain only _.a-zA-Z0-9#[] 
    165      
     165 
    166166    Both names are provided for inverse functions, e.g., acos and arccos. 
    167167 
    168168    Should try running the function to identify syntax errors before 
    169169    running it in a fit. 
    170      
     170 
    171171    Use help(fn) to see the code generated for the returned function fn. 
    172172    dis.dis(fn) will show the corresponding python vm instructions. 
     
    239239        if independent == emptyset: 
    240240            cycleset = ", ".join(str(s) for s in left) 
    241             raise ValueError,"Cyclic dependencies amongst %s"%cycleset 
     241            raise ValueError("Cyclic dependencies amongst %s"%cycleset) 
    242242 
    243243        # The possibly resolvable items are those that depend on the independents 
     
    267267        n.sort() 
    268268        items = list(items); items.sort() 
    269         raise Exception,"%s expect %s to contain %s for %s"%(msg,n,items,pairs) 
     269        raise ValueError("%s expect %s to contain %s for %s"%(msg,n,items,pairs)) 
    270270    for lo,hi in pairs: 
    271271        if lo in n and hi in n and n.index(lo) >= n.index(hi): 
    272             raise Exception,"%s expect %s before %s in %s for %s"%(msg,lo,hi,n,pairs) 
     272            raise ValueError("%s expect %s before %s in %s for %s"%(msg,lo,hi,n,pairs)) 
    273273 
    274274def test_deps(): 
     
    288288    # Cycle test 
    289289    pairs = [(1,4),(4,3),(4,5),(5,1)] 
    290     try: n = order_dependencies(pairs) 
    291     except ValueError: pass 
    292     else: raise Exception,"test3 expect ValueError exception for %s"%(pairs,) 
     290    try: 
     291        n = order_dependencies(pairs) 
     292    except ValueError: 
     293        pass 
     294    else: 
     295        raise ValueError("test3 expect ValueError exception for %s"%(pairs,)) 
    293296 
    294297    # large test for gross speed check 
     
    308311    import inspect, dis 
    309312    import math 
    310      
     313 
    311314    symtab = {'a.b.x':1, 'a.c':2, 'a.b':3, 'b.x':4} 
    312315    expr = 'a.b.x + sin(4*pi*a.c) + a.b.x/a.b' 
    313      
     316 
    314317    # Check symbol lookup 
    315318    assert _symbols(expr, symtab) == set([1,2,3]) 
     
    357360    expected = 2*math.pi*math.sin(5/.1875) + 6 
    358361    assert p2.value == expected,"Value was %s, not %s"%(p2.value,expected) 
    359      
     362 
    360363    # Check empty dependency set doesn't crash 
    361364    fn = compile_constraints(*world(p1,p3)) 
     
    381384    fn() 
    382385    assert p5.value == 2.07,"Value for %s was %s"%(p5.expression,p5.value) 
    383      
     386 
    384387 
    385388    # Verify that we capture invalid expressions 
    386     for expr in ['G4.cage', 'M0.cage', 'M1.G1 + *2',  
     389    for expr in ['G4.cage', 'M0.cage', 'M1.G1 + *2', 
    387390                 'piddle', 
    388391                 '5; import sys; print "p0wned"', 
  • src/sas/sascalc/fit/pluginmodel.py

    r5213d22 r574adc7  
    3535            return self.function(x_val)*self.function(y_val) 
    3636        elif x.__class__.__name__ == 'tuple': 
    37             raise ValueError, "Tuples are not allowed as input to BaseComponent models" 
     37            raise ValueError("Tuples are not allowed as input to BaseComponent models") 
    3838        else: 
    3939            return self.function(x) 
     
    5252            return self.function(x[0])*self.function(x[1]) 
    5353        elif x.__class__.__name__ == 'tuple': 
    54             raise ValueError, "Tuples are not allowed as input to BaseComponent models" 
     54            raise ValueError("Tuples are not allowed as input to BaseComponent models") 
    5555        else: 
    5656            return self.function(x) 
  • src/sas/sascalc/invariant/invariant.py

    rb1f20d1 r574adc7  
    424424        if not issubclass(data.__class__, LoaderData1D): 
    425425            #Process only data that inherited from DataLoader.Data_info.Data1D 
    426             raise ValueError, "Data must be of type DataLoader.Data1D" 
     426            raise ValueError("Data must be of type DataLoader.Data1D") 
    427427        #from copy import deepcopy 
    428428        new_data = (self._scale * data) - self._background 
     
    484484            msg = "Length x and y must be equal" 
    485485            msg += " and greater than 1; got x=%s, y=%s" % (len(data.x), len(data.y)) 
    486             raise ValueError, msg 
     486            raise ValueError(msg) 
    487487        else: 
    488488            # Take care of smeared data 
     
    507507                #iterate between for element different 
    508508                #from the first and the last 
    509                 for i in xrange(1, n - 1): 
     509                for i in range(1, n - 1): 
    510510                    dxi = (data.x[i + 1] - data.x[i - 1]) / 2 
    511511                    total += gx[i] * data.y[i] * dxi 
     
    533533            msg = "Length of data.x and data.y must be equal" 
    534534            msg += " and greater than 1; got x=%s, y=%s" % (len(data.x), len(data.y)) 
    535             raise ValueError, msg 
     535            raise ValueError(msg) 
    536536        else: 
    537537            #Create error for data without dy error 
     
    560560                #iterate between for element different 
    561561                #from the first and the last 
    562                 for i in xrange(1, n - 1): 
     562                for i in range(1, n - 1): 
    563563                    dxi = (data.x[i + 1] - data.x[i - 1]) / 2 
    564564                    total += (gx[i] * dy[i] * dxi) ** 2 
     
    742742        range = range.lower() 
    743743        if range not in ['high', 'low']: 
    744             raise ValueError, "Extrapolation range should be 'high' or 'low'" 
     744            raise ValueError("Extrapolation range should be 'high' or 'low'") 
    745745        function = function.lower() 
    746746        if function not in ['power_law', 'guinier']: 
    747747            msg = "Extrapolation function should be 'guinier' or 'power_law'" 
    748             raise ValueError, msg 
     748            raise ValueError(msg) 
    749749 
    750750        if range == 'high': 
    751751            if function != 'power_law': 
    752752                msg = "Extrapolation only allows a power law at high Q" 
    753                 raise ValueError, msg 
     753                raise ValueError(msg) 
    754754            self._high_extrapolation_npts = npts 
    755755            self._high_extrapolation_power = power 
     
    852852        """ 
    853853        if contrast <= 0: 
    854             raise ValueError, "The contrast parameter must be greater than zero" 
     854            raise ValueError("The contrast parameter must be greater than zero") 
    855855 
    856856        # Make sure Q star is up to date 
     
    859859        if self._qstar <= 0: 
    860860            msg = "Invalid invariant: Invariant Q* must be greater than zero" 
    861             raise RuntimeError, msg 
     861            raise RuntimeError(msg) 
    862862 
    863863        # Compute intermediate constant 
     
    869869        if discrim < 0: 
    870870            msg = "Could not compute the volume fraction: negative discriminant" 
    871             raise RuntimeError, msg 
     871            raise RuntimeError(msg) 
    872872        elif discrim == 0: 
    873873            return 1 / 2 
     
    881881                return volume2 
    882882            msg = "Could not compute the volume fraction: inconsistent results" 
    883             raise RuntimeError, msg 
     883            raise RuntimeError(msg) 
    884884 
    885885    def get_qstar_with_error(self, extrapolation=None): 
  • src/sas/sascalc/pr/c_extensions/Cinvertor.c

    rcb62bd5 rd04ac05  
    5252    invertor_dealloc(&(self->params)); 
    5353 
    54     self->ob_type->tp_free((PyObject*)self); 
     54    Py_TYPE(self)->tp_free((PyObject*)self); 
    5555 
    5656} 
     
    10541054 
    10551055static PyTypeObject CinvertorType = { 
    1056     PyObject_HEAD_INIT(NULL) 
    1057     0,                         /*ob_size*/ 
     1056    //PyObject_HEAD_INIT(NULL) 
     1057    //0,                         /*ob_size*/ 
     1058    PyVarObject_HEAD_INIT(NULL, 0) 
    10581059    "Cinvertor",             /*tp_name*/ 
    10591060    sizeof(Cinvertor),             /*tp_basicsize*/ 
     
    11191120 
    11201121 
    1121 #ifndef PyMODINIT_FUNC  /* declarations for DLL import/export */ 
    1122 #define PyMODINIT_FUNC void 
     1122#define MODULE_DOC "C extension module for inversion to P(r)." 
     1123#define MODULE_NAME "pr_inversion" 
     1124#define MODULE_INIT2 initpr_inversion 
     1125#define MODULE_INIT3 PyInit_pr_inversion 
     1126#define MODULE_METHODS module_methods 
     1127 
     1128/* ==== boilerplate python 2/3 interface bootstrap ==== */ 
     1129 
     1130 
     1131#if defined(WIN32) && !defined(__MINGW32__) 
     1132    #define DLL_EXPORT __declspec(dllexport) 
     1133#else 
     1134    #define DLL_EXPORT 
    11231135#endif 
    1124 PyMODINIT_FUNC 
    1125 initpr_inversion(void) 
    1126 { 
    1127     PyObject* m; 
    1128  
    1129     m = Py_InitModule3("pr_inversion", module_methods, 
    1130                        "C extension module for inversion to P(r)."); 
    1131  
    1132     addCinvertor(m); 
    1133 } 
     1136 
     1137#if PY_MAJOR_VERSION >= 3 
     1138 
     1139  DLL_EXPORT PyMODINIT_FUNC MODULE_INIT3(void) 
     1140  { 
     1141    static struct PyModuleDef moduledef = { 
     1142      PyModuleDef_HEAD_INIT, 
     1143      MODULE_NAME,         /* m_name */ 
     1144      MODULE_DOC,          /* m_doc */ 
     1145      -1,                  /* m_size */ 
     1146      MODULE_METHODS,      /* m_methods */ 
     1147      NULL,                /* m_reload */ 
     1148      NULL,                /* m_traverse */ 
     1149      NULL,                /* m_clear */ 
     1150      NULL,                /* m_free */ 
     1151    }; 
     1152        PyObject* m = PyModule_Create(&moduledef); 
     1153        addCinvertor(m); 
     1154        return m; 
     1155  } 
     1156 
     1157#else /* !PY_MAJOR_VERSION >= 3 */ 
     1158 
     1159  DLL_EXPORT PyMODINIT_FUNC MODULE_INIT2(void) 
     1160  { 
     1161    PyObject* m = Py_InitModule4(MODULE_NAME, 
     1162                 MODULE_METHODS, 
     1163                 MODULE_DOC, 
     1164                 0, 
     1165                 PYTHON_API_VERSION 
     1166                 ); 
     1167        addCinvertor(m); 
     1168  } 
     1169 
     1170#endif /* !PY_MAJOR_VERSION >= 3 */ 
  • src/sas/sascalc/pr/fit/AbstractFitEngine.py

    r50fcb09 r574adc7  
    251251            msg = "FitData1D: invalid error array " 
    252252            msg += "%d <> %d" % (np.shape(self.dy), np.size(fx)) 
    253             raise RuntimeError, msg 
     253            raise RuntimeError(msg) 
    254254        return (self.y[self.idx] - fx[self.idx]) / self.dy[self.idx], fx[self.idx] 
    255255 
  • src/sas/sascalc/pr/fit/Loader.py

    ra1b8fee r574adc7  
    1818        self.dy = dy 
    1919        self.filename = None 
    20          
     20 
    2121    def set_filename(self, path=None): 
    2222        """ 
    23         Store path into a variable.If the user doesn't give  
     23        Store path into a variable.If the user doesn't give 
    2424        a path as a parameter a pop-up 
    2525        window appears to select the file. 
    26          
     26 
    2727        :param path: the path given by the user 
    28          
     28 
    2929        """ 
    3030        self.filename = path 
    31         
     31 
    3232    def get_filename(self): 
    3333        """ return the file's path""" 
    3434        return self.filename 
    35      
     35 
    3636    def set_values(self): 
    3737        """ Store the values loaded from file in local variables""" 
     
    4242            self.x = [] 
    4343            self.y = [] 
    44             self.dx = []  
     44            self.dx = [] 
    4545            self.dy = [] 
    4646            for line in lines: 
     
    5050                    y = float(toks[1]) 
    5151                    dy = float(toks[2]) 
    52                      
     52 
    5353                    self.x.append(x) 
    5454                    self.y.append(y) 
     
    5959            # Sanity check 
    6060            if not len(self.x) == len(self.dx): 
    61                 raise ValueError, "x and dx have different length" 
     61                raise ValueError("x and dx have different length") 
    6262            if not len(self.y) == len(self.dy): 
    63                 raise ValueError, "y and dy have different length" 
    64              
    65              
     63                raise ValueError("y and dy have different length") 
     64 
     65 
    6666    def get_values(self): 
    6767        """ Return x, y, dx, dy""" 
    6868        return self.x, self.y, self.dx, self.dy 
    69      
     69 
    7070    def load_data(self, data): 
    7171        """ Return plottable""" 
     
    7777        #Load its View class 
    7878        #plottable.reset_view() 
    79         
    80      
    81 if __name__ == "__main__":  
     79 
     80 
     81if __name__ == "__main__": 
    8282    load = Load() 
    8383    load.set_filename("testdata_line.txt") 
    84     print(load.get_filename())  
     84    print(load.get_filename()) 
    8585    load.set_values() 
    8686    print(load.get_values()) 
    87      
    88              
     87 
  • src/sas/sascalc/pr/fit/expression.py

    ra1b8fee r574adc7  
    5959    occur multiple times.  The return value is a set with the elements in 
    6060    no particular order. 
    61      
     61 
    6262    This is the first step in computing a dependency graph. 
    6363    """ 
     
    8181        offset = end 
    8282    pieces.append(expr[offset:]) 
    83      
     83 
    8484    # Join the pieces and return them 
    8585    return "".join(pieces) 
     
    8888    """ 
    8989    Returns a list of pair-wise dependencies from the parameter expressions. 
    90      
     90 
    9191    For example, if p3 = p1+p2, then find_dependencies([p1,p2,p3]) will 
    9292    return [(p3,p1),(p3,p2)].  For base expressions without dependencies, 
     
    110110    """ 
    111111    Find the parameter substitution we need so that expressions can 
    112     be evaluated without having to traverse a chain of  
     112    be evaluated without having to traverse a chain of 
    113113    model.layer.parameter.value 
    114114    """ 
     
    122122    return definition, substitution 
    123123 
    124 def no_constraints():  
     124def no_constraints(): 
    125125    """ 
    126126    This parameter set has no constraints between the parameters. 
     
    163163 
    164164    Parameter names are assumed to contain only _.a-zA-Z0-9#[] 
    165      
     165 
    166166    Both names are provided for inverse functions, e.g., acos and arccos. 
    167167 
    168168    Should try running the function to identify syntax errors before 
    169169    running it in a fit. 
    170      
     170 
    171171    Use help(fn) to see the code generated for the returned function fn. 
    172172    dis.dis(fn) will show the corresponding python vm instructions. 
     
    239239        if independent == emptyset: 
    240240            cycleset = ", ".join(str(s) for s in left) 
    241             raise ValueError,"Cyclic dependencies amongst %s"%cycleset 
     241            raise ValueError("Cyclic dependencies amongst %s"%cycleset) 
    242242 
    243243        # The possibly resolvable items are those that depend on the independents 
     
    267267        n.sort() 
    268268        items = list(items); items.sort() 
    269         raise Exception,"%s expect %s to contain %s for %s"%(msg,n,items,pairs) 
     269        raise ValueError("%s expect %s to contain %s for %s"%(msg,n,items,pairs)) 
    270270    for lo,hi in pairs: 
    271271        if lo in n and hi in n and n.index(lo) >= n.index(hi): 
    272             raise Exception,"%s expect %s before %s in %s for %s"%(msg,lo,hi,n,pairs) 
     272            raise ValueError("%s expect %s before %s in %s for %s"%(msg,lo,hi,n,pairs)) 
    273273 
    274274def test_deps(): 
     
    288288    # Cycle test 
    289289    pairs = [(1,4),(4,3),(4,5),(5,1)] 
    290     try: n = order_dependencies(pairs) 
    291     except ValueError: pass 
    292     else: raise Exception,"test3 expect ValueError exception for %s"%(pairs,) 
     290    try: 
     291        n = order_dependencies(pairs) 
     292    except ValueError: 
     293        pass 
     294    else: 
     295        raise Exception("test3 expect ValueError exception for %s"%(pairs,)) 
    293296 
    294297    # large test for gross speed check 
     
    308311    import inspect, dis 
    309312    import math 
    310      
     313 
    311314    symtab = {'a.b.x':1, 'a.c':2, 'a.b':3, 'b.x':4} 
    312315    expr = 'a.b.x + sin(4*pi*a.c) + a.b.x/a.b' 
    313      
     316 
    314317    # Check symbol lookup 
    315318    assert _symbols(expr, symtab) == set([1,2,3]) 
     
    357360    expected = 2*math.pi*math.sin(5/.1875) + 6 
    358361    assert p2.value == expected,"Value was %s, not %s"%(p2.value,expected) 
    359      
     362 
    360363    # Check empty dependency set doesn't crash 
    361364    fn = compile_constraints(*world(p1,p3)) 
     
    381384    fn() 
    382385    assert p5.value == 2.07,"Value for %s was %s"%(p5.expression,p5.value) 
    383      
     386 
    384387 
    385388    # Verify that we capture invalid expressions 
    386     for expr in ['G4.cage', 'M0.cage', 'M1.G1 + *2',  
     389    for expr in ['G4.cage', 'M0.cage', 'M1.G1 + *2', 
    387390                 'piddle', 
    388391                 '5; import sys; print "p0wned"', 
  • src/sas/sascalc/pr/invertor.py

    rcb62bd5 rd04ac05  
    148148                msg = "Invertor: one of your q-values is zero. " 
    149149                msg += "Delete that entry before proceeding" 
    150                 raise ValueError, msg 
     150                raise ValueError(msg) 
    151151            return self.set_x(value) 
    152152        elif name == 'y': 
     
    159159                msg = "Invertor: d_max must be greater than zero." 
    160160                msg += "Correct that entry before proceeding" 
    161                 raise ValueError, msg 
     161                raise ValueError(msg) 
    162162            return self.set_dmax(value) 
    163163        elif name == 'q_min': 
     
    181181                return self.set_est_bck(0) 
    182182            else: 
    183                 raise ValueError, "Invertor: est_bck can only be True or False" 
     183                raise ValueError("Invertor: est_bck can only be True or False") 
    184184 
    185185        return Cinvertor.__setattr__(self, name, value) 
     
    331331        if self.is_valid() <= 0: 
    332332            msg = "Invertor.invert: Data array are of different length" 
    333             raise RuntimeError, msg 
     333            raise RuntimeError(msg) 
    334334 
    335335        p = np.ones(nfunc) 
     
    364364        if self.is_valid() <= 0: 
    365365            msg = "Invertor.invert: Data arrays are of different length" 
    366             raise RuntimeError, msg 
     366            raise RuntimeError(msg) 
    367367 
    368368        p = np.ones(nfunc) 
     
    448448        if self.is_valid() < 0: 
    449449            msg = "Invertor: invalid data; incompatible data lengths." 
    450             raise RuntimeError, msg 
     450            raise RuntimeError(msg) 
    451451 
    452452        self.nfunc = nfunc 
     
    472472        try: 
    473473            self._get_matrix(nfunc, nq, a, b) 
    474         except: 
    475             raise RuntimeError, "Invertor: could not invert I(Q)\n  %s" % sys.exc_value 
     474        except Exception as exc: 
     475            raise RuntimeError("Invertor: could not invert I(Q)\n  %s" % str(exc)) 
    476476 
    477477        # Perform the inversion (least square fit) 
     
    756756            except: 
    757757                msg = "Invertor.from_file: corrupted file\n%s" % sys.exc_value 
    758                 raise RuntimeError, msg 
     758                raise RuntimeError(msg) 
    759759        else: 
    760760            msg = "Invertor.from_file: '%s' is not a file" % str(path) 
    761             raise RuntimeError, msg 
     761            raise RuntimeError(msg) 
Note: See TracChangeset for help on using the changeset viewer.