Changeset 574adc7 in sasview for src/sas/sascalc/data_util


Ignore:
Timestamp:
Sep 22, 2017 2:01:32 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:
34d7b35
Parents:
9706d88
Message:

convert sascalc to python 2/3 syntax

Location:
src/sas/sascalc/data_util
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • 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/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)" 
Note: See TracChangeset for help on using the changeset viewer.