Changeset e090ba90 in sasview


Ignore:
Timestamp:
Oct 11, 2018 11:59:57 AM (5 years ago)
Author:
Paul Kienzle <pkienzle@…>
Branches:
master, magnetic_scatt, release-4.2.2, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1249
Children:
88d2e70
Parents:
67ed543
Message:

remove errors and warnings from py37 tests of sascalc

Location:
src/sas/sascalc
Files:
22 edited

Legend:

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

    rf4775563 re090ba90  
    128128            self.size = 0 
    129129        else: 
    130             self.size = size 
     130            # TODO: Make sure detector size is number of pixels 
     131            # Could be detector dimensions in e.g., mm, but 
     132            # the resolution calculator assumes it is pixels. 
     133            # Being pixels, it has to be integers rather than float 
     134            self.size = [int(s) for s in size] 
    131135            validate(size[0]) 
    132136 
  • src/sas/sascalc/calculator/resolution_calculator.py

    r574adc7 re090ba90  
    10071007        try: 
    10081008            detector_offset = self.sample2detector_distance[1] 
    1009         except: 
    1010             logger.error(sys.exc_value) 
     1009        except Exception as exc: 
     1010            logger.error(exc) 
    10111011 
    10121012        # detector size in [no of pix_x,no of pix_y] 
     
    10941094            output.qx_data = qx_value 
    10951095            output.qy_data = qy_value 
    1096         except: 
    1097             logger.error(sys.exc_value) 
     1096        except Exception as exc: 
     1097            logger.error(exc) 
    10981098 
    10991099        return output 
  • src/sas/sascalc/corfunc/corfunc_calculator.py

    ra26f67f re090ba90  
    3030            self.start = start 
    3131            self.stop = stop 
    32             self._lastx = [] 
    33             self._lasty = [] 
     32            self._lastx = np.empty(0, dtype='d') 
     33            self._lasty = None 
    3434 
    3535        def __call__(self, x): 
    3636            # If input is a single number, evaluate the function at that number 
    3737            # and return a single number 
    38             if type(x) == float or type(x) == int: 
     38            if isinstance(x, (float, int)): 
    3939                return self._smoothed_function(np.array([x]))[0] 
    4040            # If input is a list, and is different to the last input, evaluate 
     
    4242            # the function was called, return the result that was calculated 
    4343            # last time instead of explicity evaluating the function again. 
    44             elif self._lastx == [] or x.tolist() != self._lastx.tolist(): 
    45                 self._lasty = self._smoothed_function(x) 
    46                 self._lastx = x 
     44            if not np.array_equal(x, self._lastx): 
     45                self._lastx, self._lasty = x, self._smoothed_function(x) 
    4746            return self._lasty 
    4847 
     
    8887        # Only process data of the class Data1D 
    8988        if not issubclass(data.__class__, Data1D): 
    90             raise ValueError("Data must be of the type DataLoader.Data1D") 
     89            raise ValueError("Correlation function cannot be computed with 2D data.") 
    9190 
    9291        # Prepare the data 
     
    246245        """Fit the Guinier region of the curve""" 
    247246        A = np.vstack([q**2, np.ones(q.shape)]).T 
    248         return lstsq(A, np.log(iq)) 
     247        return lstsq(A, np.log(iq), rcond=None) 
    249248 
    250249    def _fit_porod(self, q, iq): 
  • src/sas/sascalc/data_util/calcthread.py

    r574adc7 re090ba90  
    66from __future__ import print_function 
    77 
    8 import traceback 
    98import sys 
    109import logging 
     10import traceback 
     11from time import sleep 
     12 
    1113try: 
    1214    import _thread as thread 
    1315except ImportError: # CRUFT: python 2 support 
    1416    import thread 
    15  
    16 if sys.platform.count("darwin") > 0: 
    17     import time 
    18     stime = time.time() 
    19  
    20     def clock(): 
    21         return time.time() - stime 
    22  
    23     def sleep(t): 
    24         return time.sleep(t) 
    25 else: 
    26     from time import clock 
    27     from time import sleep 
     17try: 
     18    from time import perf_counter as clock 
     19except ImportError: # CRUFT: python < 3.3 
     20    if sys.platform.count("darwin") > 0: 
     21        from time import time as clock 
     22    else: 
     23        from time import clock 
    2824 
    2925logger = logging.getLogger(__name__) 
    30  
    3126 
    3227class CalcThread: 
     
    248243                self.exception_handler(*sys.exc_info()) 
    249244                return 
    250             except Exception: 
     245            except Exception as exc: 
    251246                pass 
    252247        logger.error(traceback.format_exc()) 
  • src/sas/sascalc/data_util/nxsunit.py

    r574adc7 re090ba90  
    9999    Strip '^' from unit names. 
    100100 
    101     * WARNING * this will incorrect transform 10^3 to 103. 
    102     """ 
    103     s.update((k.replace('^',''),v) 
    104              for k, v in list(s.items()) 
    105              if '^' in k) 
     101    * WARNING * this will incorrectly transform 10^3 to 103. 
     102    """ 
     103    stripped = [(k.replace('^',''),v) for k, v in s.items() if '^' in k] 
     104    s.update(stripped) 
    106105 
    107106def _build_all_units(): 
  • src/sas/sascalc/data_util/ordereddicttest.py

    rb699768 re090ba90  
    147147                    ]): 
    148148            self.assert_(dup is not od) 
    149             self.assertEquals(dup, od) 
    150             self.assertEquals(list(dup.items()), list(od.items())) 
    151             self.assertEquals(len(dup), len(od)) 
    152             self.assertEquals(type(dup), type(od)) 
     149            self.assertEqual(dup, od) 
     150            self.assertEqual(list(dup.items()), list(od.items())) 
     151            self.assertEqual(len(dup), len(od)) 
     152            self.assertEqual(type(dup), type(od)) 
    153153 
    154154    def test_repr(self): 
  • src/sas/sascalc/data_util/registry.py

    ra26f67f re090ba90  
    148148            # If file has associated loader(s) and they;ve failed 
    149149            raise last_exc 
    150         raise NoKnownLoaderException(e.message)  # raise generic exception 
     150        raise NoKnownLoaderException(str(message))  # raise generic exception 
  • src/sas/sascalc/data_util/uncertainty.py

    r574adc7 re090ba90  
    1919import numpy as np 
    2020 
    21 from .import err1d 
     21from . import err1d 
    2222from .formatnum import format_uncertainty 
    2323 
  • src/sas/sascalc/dataloader/data_info.py

    r9e6aeaf re090ba90  
    2626import numpy as np 
    2727import math 
     28from math import fabs 
    2829 
    2930class plottable_1D(object): 
     
    656657        return self._perform_operation(other, operation) 
    657658 
    658     def __div__(self, other): 
     659    def __truediv__(self, other): 
    659660        """ 
    660661        Divided a data set by another 
     
    667668            return a/b 
    668669        return self._perform_operation(other, operation) 
    669  
    670     def __rdiv__(self, other): 
     670    __div__ = __truediv__ 
     671 
     672    def __rtruediv__(self, other): 
    671673        """ 
    672674        Divided a data set by another 
     
    679681            return b/a 
    680682        return self._perform_operation(other, operation) 
     683    __rdiv__ = __rtruediv__ 
    681684 
    682685    def __or__(self, other): 
     
    800803            TOLERANCE = 0.01 
    801804            for i in range(len(self.x)): 
    802                 if math.fabs((self.x[i] - other.x[i])/self.x[i]) > TOLERANCE: 
     805                if fabs(self.x[i] - other.x[i]) > self.x[i]*TOLERANCE: 
    803806                    msg = "Incompatible data sets: x-values do not match" 
    804807                    raise ValueError(msg) 
     
    10221025                raise ValueError(msg) 
    10231026            for ind in range(len(self.data)): 
    1024                 if math.fabs((self.qx_data[ind] - other.qx_data[ind])/self.qx_data[ind]) > TOLERANCE: 
     1027                if fabs(self.qx_data[ind] - other.qx_data[ind]) > fabs(self.qx_data[ind])*TOLERANCE: 
    10251028                    msg = "Incompatible data sets: qx-values do not match: %s %s" % (self.qx_data[ind], other.qx_data[ind]) 
    10261029                    raise ValueError(msg) 
    1027                 if math.fabs((self.qy_data[ind] - other.qy_data[ind])/self.qy_data[ind]) > TOLERANCE: 
     1030                if fabs(self.qy_data[ind] - other.qy_data[ind]) > fabs(self.qy_data[ind])*TOLERANCE: 
    10281031                    msg = "Incompatible data sets: qy-values do not match: %s %s" % (self.qy_data[ind], other.qy_data[ind]) 
    10291032                    raise ValueError(msg) 
  • src/sas/sascalc/dataloader/loader.py

    r4a8d55c re090ba90  
    169169                        if self._identify_plugin(module): 
    170170                            readers_found += 1 
    171                     except: 
     171                    except Exception as exc: 
    172172                        msg = "Loader: Error importing " 
    173                         msg += "%s\n  %s" % (item, sys.exc_value) 
     173                        msg += "%s\n  %s" % (item, exc) 
    174174                        logger.error(msg) 
    175175 
     
    191191                                if self._identify_plugin(module): 
    192192                                    readers_found += 1 
    193                             except: 
     193                            except Exception as exc: 
    194194                                msg = "Loader: Error importing" 
    195                                 msg += " %s\n  %s" % (mfile, sys.exc_value) 
     195                                msg += " %s\n  %s" % (mfile, exc) 
    196196                                logger.error(msg) 
    197197 
    198                     except: 
     198                    except Exception as exc: 
    199199                        msg = "Loader: Error importing " 
    200                         msg += " %s\n  %s" % (item, sys.exc_value) 
     200                        msg += " %s\n  %s" % (item, exc) 
    201201                        logger.error(msg) 
    202202 
     
    242242                    self.writers[ext].append(loader.write) 
    243243 
    244             except: 
     244            except Exception as exc: 
    245245                msg = "Loader: Error accessing" 
    246                 msg += " Reader in %s\n  %s" % (module.__name__, sys.exc_value) 
     246                msg += " Reader in %s\n  %s" % (module.__name__, exc) 
    247247                logger.error(msg) 
    248248        return reader_found 
     
    275275                    self.wildcards.append(wcard) 
    276276 
    277         except: 
     277        except Exception as exc: 
    278278            msg = "Loader: Error accessing Reader " 
    279             msg += "in %s\n  %s" % (loader.__name__, sys.exc_value) 
     279            msg += "in %s\n  %s" % (loader.__name__, exc) 
    280280            logger.error(msg) 
    281281        return reader_found 
     
    320320                        self.writers[ext].insert(0, loader.write) 
    321321 
    322             except: 
     322            except Exception as exc: 
    323323                msg = "Loader: Error accessing Reader" 
    324                 msg += " in %s\n  %s" % (module.__name__, sys.exc_value) 
     324                msg += " in %s\n  %s" % (module.__name__, exc) 
    325325                logger.error(msg) 
    326326        return reader_found 
  • src/sas/sascalc/dataloader/manipulations.py

    r574adc7 re090ba90  
    928928 
    929929        # Organize the results 
    930         for i in range(self.nbins): 
    931             y[i] = y[i] / y_counts[i] 
    932             y_err[i] = math.sqrt(y_err[i]) / y_counts[i] 
    933  
     930        with np.errstate(divide='ignore', invalid='ignore'): 
     931            y = y/y_counts 
     932            y_err = np.sqrt(y_err)/y_counts 
    934933            # The type of averaging: phi,q2, or q 
    935934            # Calculate x[i]should be at the center of the bin 
    936935            if run.lower() == 'phi': 
    937                 x[i] = (self.phi_max - self.phi_min) / self.nbins * \ 
    938                     (1.0 * i + 0.5) + self.phi_min 
     936                step  = (self.phi_max - self.phi_min) / self.nbins 
     937                x = (np.arange(self.nbins) + 0.5) * step + self.phi_min 
    939938            else: 
    940939                # We take the center of ring area, not radius. 
     
    944943                # r_outer = r_inner + delta_r 
    945944                # x[i] = math.sqrt((r_inner * r_inner + r_outer * r_outer) / 2) 
    946                 x[i] = x[i] / y_counts[i] 
    947         y_err[y_err == 0] = np.average(y_err) 
     945                x = x/y_counts 
     946 
    948947        idx = (np.isfinite(y) & np.isfinite(y_err)) 
    949948        if x_err is not None: 
  • src/sas/sascalc/dataloader/readers/associations.py

    ra32c19c re090ba90  
    5353                exec("loader.associate_file_type('%s', %s)" 
    5454                     % (ext.upper(), reader)) 
    55             except: 
     55            except Exception as exc: 
    5656                msg = "read_associations: skipping association" 
    57                 msg += " for %s\n  %s" % (ext.lower(), sys.exc_value) 
     57                msg += " for %s\n  %s" % (ext.lower(), exc) 
    5858                logger.error(msg) 
  • src/sas/sascalc/dataloader/readers/cansas_reader.py

    r2469df7 re090ba90  
    12391239                        conv = Converter(units) 
    12401240                        setattrchain(storage, variable, conv(value, units=local_unit)) 
    1241                     except Exception: 
    1242                         _, exc_value, _ = sys.exc_info() 
     1241                    except Exception as exc: 
    12431242                        err_mess = "CanSAS reader: could not convert" 
    12441243                        err_mess += " %s unit [%s]; expecting [%s]\n  %s" \ 
    1245                             % (variable, units, local_unit, exc_value) 
     1244                            % (variable, units, local_unit, exc) 
    12461245                        self.errors.add(err_mess) 
    12471246                        if optional: 
  • src/sas/sascalc/dataloader/readers/cansas_reader_HDF5.py

    r61f329f0 re090ba90  
    475475                for i in range(0, dataset.mask.size - 1): 
    476476                    zeros[i] = dataset.mask[i] 
    477             except: 
    478                 self.errors.add(sys.exc_value) 
     477            except Exception as exc: 
     478                self.errors.add(exc) 
    479479            dataset.mask = zeros 
    480480            # Calculate the actual Q matrix 
  • src/sas/sascalc/fit/expression.py

    r574adc7 re090ba90  
    210210 
    211211    #print("Function: "+functiondef) 
    212     exec functiondef in globals,locals 
     212    exec(functiondef, globals, locals) 
    213213    retfn = locals['eval_expressions'] 
    214214 
  • src/sas/sascalc/fit/models.py

    rb963b20 re090ba90  
    1212import py_compile 
    1313import shutil 
     14 
     15from six import reraise 
    1416 
    1517from sasmodels.sasview_model import load_custom_model, load_standard_models 
     
    6264    try: 
    6365        new_instance = model() 
    64     except Exception: 
    65         msg = "Plugin %s error in __init__ \n\t: %s %s\n" % (str(name), 
    66                                                              str(sys.exc_type), 
    67                                                              sys.exc_info()[1]) 
     66    except Exception as exc: 
     67        msg = ("Plugin %s error in __init__ \n\t: %s %s\n" 
     68               % (name, type(exc), exc)) 
    6869        plugin_log(msg) 
    6970        return None 
     
    7273        try: 
    7374            value = new_instance.function() 
    74         except Exception: 
     75        except Exception as exc: 
    7576            msg = "Plugin %s: error writing function \n\t :%s %s\n " % \ 
    76                     (str(name), str(sys.exc_type), sys.exc_info()[1]) 
     77                    (str(name), str(type(exc)), exc) 
    7778            plugin_log(msg) 
    7879            return None 
     
    139140        if type is not None and issubclass(type, py_compile.PyCompileError): 
    140141            print("Problem with", repr(value)) 
    141             raise type, value, tb 
     142            reraise(type, value, tb) 
    142143        return 1 
    143144 
     
    153154        compileall.compile_dir(dir=dir, ddir=dir, force=0, 
    154155                               quiet=report_problem) 
    155     except Exception: 
    156         return sys.exc_info()[1] 
     156    except Exception as exc: 
     157        return exc 
    157158    return None 
    158159 
     
    185186                    model.name = PLUGIN_NAME_BASE + model.name 
    186187                plugins[model.name] = model 
    187             except Exception: 
     188            except Exception as exc: 
    188189                msg = traceback.format_exc() 
    189190                msg += "\nwhile accessing model in %r" % path 
  • src/sas/sascalc/fit/pagestate.py

    r863ac2c re090ba90  
    650650                    #Truncating string so print doesn't complain of being outside margins 
    651651                    if sys.platform != "win32": 
    652                         MAX_STRING_LENGHT = 50 
    653                         if len(file_value) > MAX_STRING_LENGHT: 
    654                             file_value = "File name:.."+file_value[-MAX_STRING_LENGHT+10:] 
     652                        MAX_STRING_LENGTH = 50 
     653                        if len(file_value) > MAX_STRING_LENGTH: 
     654                            file_value = "File name:.."+file_value[-MAX_STRING_LENGTH+10:] 
    655655                    file_name = CENTRE % file_value 
    656656                    if len(title) == 0: 
     
    905905                doc_model = newdoc.createElement('model_list_item') 
    906906                doc_model.setAttribute('checked', str(model[0].GetValue())) 
    907                 keys = model[1].keys() 
     907                keys = list(model[1].keys()) 
    908908                doc_model.setAttribute('name', str(keys[0])) 
    909909                values = model[1].get(keys[0]) 
     
    964964        if node.get('version'): 
    965965            # Get the version for model conversion purposes 
    966             x = re.sub('[^\d.]', '', node.get('version')) 
     966            x = re.sub(r'[^\d.]', '', node.get('version')) 
    967967            self.version = tuple(int(e) for e in str.split(x, ".")) 
    968968            # The tuple must be at least 3 items long 
     
    984984                try: 
    985985                    self.timestamp = float(entry.get('epoch')) 
    986                 except Exception: 
     986                except Exception as exc: 
    987987                    msg = "PageState.fromXML: Could not" 
    988                     msg += " read timestamp\n %s" % sys.exc_value 
     988                    msg += " read timestamp\n %s" % exc 
    989989                    logger.error(msg) 
    990990 
     
    12821282                        if isinstance(data.run_name, dict): 
    12831283                            # Note: key order in dict is not guaranteed, so sort 
    1284                             name = data.run_name.keys()[0] 
     1284                            name = list(data.run_name.keys())[0] 
    12851285                        else: 
    12861286                            name = data.run_name 
  • src/sas/sascalc/invariant/invariant.py

    r574adc7 re090ba90  
    344344        else: 
    345345            A = np.vstack([linearized_data.x / linearized_data.dy, 1.0 / linearized_data.dy]).T 
    346             (p, residuals, _, _) = np.linalg.lstsq(A, linearized_data.y / linearized_data.dy) 
     346            p, residuals, _, _ = np.linalg.lstsq(A, linearized_data.y / linearized_data.dy, 
     347                                                 rcond=None) 
    347348 
    348349            # Get the covariance matrix, defined as inv_cov = a_transposed * a 
  • src/sas/sascalc/pr/distance_explorer.py

    r959eb01 re090ba90  
    9999                results.pos_err.append(pos_err) 
    100100                results.osc.append(osc) 
    101             except: 
     101            except Exception as exc: 
    102102                # This inversion failed, skip this D_max value 
    103103                msg = "ExploreDialog: inversion failed for " 
    104                 msg += "D_max=%s\n %s" % (str(d), sys.exc_value) 
     104                msg += "D_max=%s\n %s" % (str(d), exc) 
    105105                results.errors.append(msg) 
    106106 
  • src/sas/sascalc/pr/fit/expression.py

    r574adc7 re090ba90  
    210210 
    211211    #print("Function: "+functiondef) 
    212     exec functiondef in globals,locals 
     212    exec(functiondef, globals, locals) 
    213213    retfn = locals['eval_expressions'] 
    214214 
  • src/sas/sascalc/pr/num_term.py

    r2469df7 re090ba90  
    182182                data_y = np.append(data_y, test_y) 
    183183                data_err = np.append(data_err, err) 
    184             except: 
    185                 logger.error(sys.exc_value) 
     184            except Exception as exc: 
     185                logger.error(exc) 
    186186 
    187187    return data_x, data_y, data_err 
  • src/sas/sascalc/realspace/VolumeCanvas.py

    r98e3f24 re090ba90  
    472472            Return a list of the shapes 
    473473        """ 
    474         return self.shapes.keys() 
     474        return list(self.shapes.keys()) 
    475475 
    476476    def _addSingleShape(self, shapeDesc): 
Note: See TracChangeset for help on using the changeset viewer.