Changeset 4a96b8b in sasview


Ignore:
Timestamp:
Apr 27, 2012 11:37:14 AM (12 years ago)
Author:
Mathieu Doucet <doucetm@…>
Branches:
master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
507c68f
Parents:
7d6351e
Message:

Pep-8-ification

Location:
sansutil
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • sansutil/calcthread.py

    r4025019 r4a96b8b  
    55# 
    66 
    7 import thread, traceback 
    8  
     7import thread 
     8import traceback 
    99import sys 
    1010 
    11 if sys.platform.count("darwin")>0: 
     11if sys.platform.count("darwin") > 0: 
    1212    import time 
    1313    stime = time.time() 
     14     
    1415    def clock(): 
    15         return time.time()-stime 
     16        return time.time() - stime 
     17     
    1618    def sleep(t): 
    17         return time.sleep(t)     
     19        return time.sleep(t) 
    1820else: 
    1921    from time import clock 
    2022    from time import sleep 
     23 
    2124 
    2225class CalcThread: 
     
    113116    """ 
    114117 
    115     def __init__(self, 
    116                  completefn = None, 
    117                  updatefn   = None, 
    118                  yieldtime  = 0.01, 
    119                  worktime   = 0.01 
    120                  ): 
     118    def __init__(self, completefn=None, updatefn=None, 
     119                 yieldtime=0.01, worktime=0.01): 
    121120        """Prepare the calculator""" 
    122121        self.yieldtime     = yieldtime 
     
    134133        method for details of the arguments to the work unit.""" 
    135134        self._lock.acquire() 
    136         self._queue.append((args,kwargs)) 
     135        self._queue.append((args, kwargs)) 
    137136        # Cannot do start_new_thread call within the lock 
    138137        self._lock.release() 
    139138        if not self._running: 
    140             self._time_for_update = clock()+1e6 
    141             thread.start_new_thread(self._run,()) 
    142  
    143     def requeue(self,*args,**kwargs): 
     139            self._time_for_update = clock() + 1e6 
     140            thread.start_new_thread(self._run, ()) 
     141 
     142    def requeue(self, *args, **kwargs): 
    144143        """Replace the work unit on the end of the queue.  See the compute() 
    145144        method for details of the arguments to the work unit.""" 
     
    147146        self._queue = self._queue[:-1] 
    148147        self._lock.release() 
    149         self.queue(*args,**kwargs) 
    150  
    151     def reset(self,*args,**kwargs): 
     148        self.queue(*args, **kwargs) 
     149 
     150    def reset(self, *args, **kwargs): 
    152151        """Clear the queue and start a new work unit.  See the compute() 
    153152        method for details of the arguments to the work unit.""" 
    154153        self.stop() 
    155         self.queue(*args,**kwargs) 
     154        self.queue(*args, **kwargs) 
    156155 
    157156    def stop(self): 
     
    171170        self._lock.release() 
    172171 
    173     def isrunning(self): return self._running 
     172    def isrunning(self): 
     173        return self._running 
    174174 
    175175    def ready(self, delay=0.): 
     
    189189 
    190190        # Only called from within the running thread so no need to lock 
    191         if self._running and self.yieldtime>0 and clock()>self._time_for_nap: 
    192             # print "sharing" 
     191        if self._running and self.yieldtime > 0 \ 
     192            and clock() > self._time_for_nap: 
    193193            sleep(self.yieldtime) 
    194194            self._time_for_nap = clock() + self.worktime 
    195         if self._interrupting: raise KeyboardInterrupt 
    196  
    197     def update(self,**kwargs): 
     195        if self._interrupting: 
     196            raise KeyboardInterrupt 
     197 
     198    def update(self, **kwargs): 
    198199 
    199200        """Update GUI with the lastest results from the current work unit.""" 
     
    206207            self.updatefn(**kwargs) 
    207208            sleep(self.yieldtime) 
    208             if self._interrupting: raise KeyboardInterrupt 
     209            if self._interrupting: 
     210                raise KeyboardInterrupt 
    209211        else: 
    210212            self.isquit() 
    211213        return 
    212214 
    213     def complete(self,**kwargs): 
     215    def complete(self, **kwargs): 
    214216        """Update the GUI with the completed results from a work unit.""" 
    215217        if self.completefn != None: 
     
    218220        return 
    219221 
    220     def compute(self,*args,**kwargs): 
     222    def compute(self, *args, **kwargs): 
    221223        """Perform a work unit.  The subclass will provide details of 
    222224        the arguments.""" 
     
    233235        while 1: 
    234236            self._lock.acquire() 
    235             # print "lock aquired" 
    236             self._time_for_nap = clock()+self.worktime 
     237            self._time_for_nap = clock() + self.worktime 
    237238            self._running = True 
    238             if self._queue == []: break 
     239            if self._queue == []: 
     240                break 
    239241            self._interrupting = False 
    240             args,kwargs = self._queue[0] 
     242            args, kwargs = self._queue[0] 
    241243            self._queue = self._queue[1:] 
    242244            self._lock.release() 
    243             # print "lock released" 
    244245            try: 
    245                 self.compute(*args,**kwargs) 
     246                self.compute(*args, **kwargs) 
    246247            except KeyboardInterrupt: 
    247248                pass 
     
    251252        self._running = False 
    252253 
     254 
    253255# ====================================================================== 
    254256# Demonstration of calcthread in action 
    255257class CalcDemo(CalcThread): 
    256258    """Example of a calculation thread.""" 
    257     def compute(self,n): 
     259    def compute(self, n): 
    258260        total = 0. 
    259261        for i in range(n): 
     
    264266        self.complete(total=total) 
    265267 
     268 
    266269class CalcCommandline: 
     270    """ 
     271        Test method 
     272    """ 
    267273    def __init__(self, n=20000): 
    268274        print thread.get_ident() 
     
    283289        while not self.done: 
    284290            sleep(1) 
    285             print "Main thread %d at %.2f"%(thread.get_ident(),clock()-self.starttime) 
    286  
    287     def update(self,i=0): 
    288         print "Update i=%d from thread %d at %.2f"%(i,thread.get_ident(),clock()-self.starttime) 
     291            print "Main thread %d at %.2f" % (thread.get_ident(), 
     292                                              clock() - self.starttime) 
     293 
     294    def update(self, i=0): 
     295        print "Update i=%d from thread %d at %.2f" % (i, thread.get_ident(), 
     296                                                      clock() - self.starttime) 
    289297        self.work.ready(2.5) 
    290298 
    291     def complete(self,total=0.0): 
    292         print "Complete total=%g from thread %d at %.2f"%(total,thread.get_ident(),clock()-self.starttime) 
     299    def complete(self, total=0.0): 
     300        print "Complete total=%g from thread %d at %.2f" % (total, 
     301                                                    thread.get_ident(), 
     302                                                    clock() - self.starttime) 
    293303        self.done = True 
    294  
    295 if __name__ == "__main__": 
    296     CalcCommandline() 
    297  
    298 # version 
    299 __id__ = "$Id: calcthread.py 249 2007-06-15 17:03:01Z ziwen $" 
    300  
    301 # End of file 
  • sansutil/err1d.py

    r4025019 r4a96b8b  
    11# This program is public domain 
    2  
    32""" 
    43Error propogation algorithms for simple arithmetic 
     
    87integers, so be sure to create them with floating point inputs. 
    98""" 
    10  
    11  
    129from __future__ import division  # Get true division 
    1310import numpy 
    1411 
    15 def div(X,varX, Y,varY): 
     12 
     13def div(X, varX, Y, varY): 
    1614    """Division with error propagation""" 
    1715    # Direct algorithm: 
     
    2826    return Z, varZ 
    2927 
    30 def mul(X,varX, Y,varY): 
     28 
     29def mul(X, varX, Y, varY): 
    3130    """Multiplication with error propagation""" 
    3231    # Direct algorithm: 
     
    4342    return Z, varZ 
    4443 
    45 def sub(X,varX, Y, varY): 
     44 
     45def sub(X, varX, Y, varY): 
    4646    """Subtraction with error propagation""" 
    4747    Z = X - Y 
     
    4949    return Z, varZ 
    5050 
    51 def add(X,varX, Y,varY): 
     51 
     52def add(X, varX, Y, varY): 
    5253    """Addition with error propagation""" 
    5354    Z = X + Y 
     
    5556    return Z, varZ 
    5657 
    57 def exp(X,varX): 
     58 
     59def exp(X, varX): 
    5860    """Exponentiation with error propagation""" 
    5961    Z = numpy.exp(X) 
    6062    varZ = varX * Z**2 
    61     return Z,varZ 
     63    return Z, varZ 
    6264 
    63 def log(X,varX): 
     65 
     66def log(X, varX): 
    6467    """Logarithm with error propagation""" 
    6568    Z = numpy.log(X) 
    6669    varZ = varX / X**2 
    67     return Z,varZ 
     70    return Z, varZ 
    6871 
    6972# Confirm this formula before using it 
     
    7477# 
    7578 
    76 def pow(X,varX,n): 
     79 
     80def pow(X, varX, n): 
    7781    """X**n with error propagation""" 
    7882    # Direct algorithm 
     
    8185    # Indirect algorithm to minimize intermediates 
    8286    Z = X**n 
    83     varZ = varX/X 
     87    varZ = varX / X 
    8488    varZ /= X 
    8589    varZ *= Z 
     
    8892    return Z, varZ 
    8993 
    90 def div_inplace(X,varX, Y,varY): 
     94 
     95def div_inplace(X, varX, Y, varY): 
    9196    """In-place division with error propagation""" 
    9297    # Z = X/Y 
     
    98103    del T   # may want to use T[:] = Y for vectors 
    99104    T = Y   # reuse T for Y 
    100     T **=2     # T now has Y**2 
     105    T ** = 2     # T now has Y**2 
    101106    varX /= T  # varX now has varZ 
    102     return X,varX 
     107    return X, varX 
    103108 
    104 def mul_inplace(X,varX, Y,varY): 
     109 
     110def mul_inplace(X, varX, Y, varY): 
    105111    """In-place multiplication with error propagation""" 
    106112    # Z = X * Y 
     
    114120    varX += T  # varX now has varZ 
    115121    X *= Y     # X now has Z 
    116     return X,varX 
     122    return X, varX 
    117123 
    118 def sub_inplace(X,varX, Y, varY): 
     124 
     125def sub_inplace(X, varX, Y, varY): 
    119126    """In-place subtraction with error propagation""" 
    120127    # Z = X - Y 
     
    122129    X -= Y 
    123130    varX += varY 
    124     return X,varX 
     131    return X, varX 
    125132 
    126 def add_inplace(X,varX, Y,varY): 
     133 
     134def add_inplace(X, varX, Y, varY): 
    127135    """In-place addition with error propagation""" 
    128136    # Z = X + Y 
     
    130138    X += Y 
    131139    varX += varY 
    132     return X,varX 
     140    return X, varX 
    133141 
    134 def pow_inplace(X,varX,n): 
     142 
     143def pow_inplace(X, varX, n): 
    135144    """In-place X**n with error propagation""" 
    136145    # Direct algorithm 
     
    141150    varX /= X     # varX now has varX/X**2 
    142151    X **= n       # X now has Z = X**n 
    143     varX *= X      
     152    varX *= X 
    144153    varX *= X     # varX now has varX/X**2 * Z**2 
    145154    varX *= n**2  # varX now has varZ 
    146     return X,varX 
     155    return X, varX 
  • sansutil/formatnum.py

    r4025019 r4a96b8b  
    66:func:`format_uncertainty_pm`(v,err) produces the expanded format v +/- err. 
    77 
    8 :func:`format_uncertainty_compact`(v,err) produces the compact format v(##),  
     8:func:`format_uncertainty_compact`(v,err) produces the compact format v(##), 
    99where the number in parenthesis is the uncertainty in the last two digits of v. 
    1010 
    11 :func:`format_uncertainty`(v,err) uses the compact format by default, but this  
     11:func:`format_uncertainty`(v,err) uses the compact format by default, but this 
    1212can be changed to use the expanded +/- format by setting  
    1313format_uncertainty.compact to False. 
     
    3434    757.236 +/- 0.010 
    3535 
    36 UncertaintyFormatter() returns a private formatter with its own  
     36UncertaintyFormatter() returns a private formatter with its own 
    3737formatter.compact flag. 
    3838""" 
     
    6262# such as 1 g/cm**3 -> 1 kg/L. 
    6363 
     64 
    6465def format_uncertainty_pm(value, uncertainty): 
    6566    """ 
     
    6869    return _format_uncertainty(value, uncertainty, compact=False) 
    6970 
     71 
    7072def format_uncertainty_compact(value, uncertainty): 
    7173    """ 
    7274    Given *value* v and *uncertainty* dv, return the compact 
    73     representation v(##), where ## are the first two digits of  
     75    representation v(##), where ## are the first two digits of 
    7476    the uncertainty. 
    7577    """ 
    7678    return _format_uncertainty(value, uncertainty, compact=True) 
    7779 
     80 
    7881class UncertaintyFormatter: 
    7982    """ 
    8083    Value and uncertainty formatter. 
    8184 
    82     The *formatter* instance will use either the expanded v +/- dv form  
    83     or the compact v(##) form depending on whether *formatter.compact* is  
     85    The *formatter* instance will use either the expanded v +/- dv form 
     86    or the compact v(##) form depending on whether *formatter.compact* is 
    8487    True or False.  The default is True. 
    8588    """ 
    8689    compact = True 
     90     
    8791    def __call__(self, value, uncertainty): 
    8892        """ 
     
    9296format_uncertainty = UncertaintyFormatter() 
    9397 
     98 
    9499def _format_uncertainty(value, uncertainty, compact): 
    95100    """ 
     
    103108 
    104109    # Handle indefinite uncertainty 
    105     if uncertainty is None or uncertainty<=0 or numpy.isnan(uncertainty): 
    106         return "%g"%value 
     110    if uncertainty is None or uncertainty <= 0 or numpy.isnan(uncertainty): 
     111        return "%g" % value 
    107112    if numpy.isinf(uncertainty): 
    108113        if compact: 
    109             return "%.2g(inf)"%value 
     114            return "%.2g(inf)" % value 
    110115        else: 
    111             return "%.2g +/- inf"%value 
     116            return "%.2g +/- inf" % value 
    112117 
    113118    # Handle zero and negative values 
     
    125130        # Degenerate case: error bigger than value 
    126131        # The mantissa is 0.#(##)e#, 0.0#(##)e# or 0.00#(##)e# 
    127         val_place = err_place+2 
     132        val_place = err_place + 2 
    128133    elif err_place == val_place: 
    129134        # Degenerate case: error and value the same order of magnitude 
    130135        # The value is ##(##)e#, #.#(##)e# or 0.##(##)e# 
    131         val_place = err_place+1 
     136        val_place = err_place + 1 
    132137    elif err_place <= 1 and val_place >= -3: 
    133138        # Normal case: nice numbers and errors 
     
    140145     
    141146    # Force engineering notation, with exponent a multiple of 3 
    142     val_place = int(math.floor(val_place/3.))*3 
     147    val_place = int(math.floor(val_place / 3.)) * 3 
    143148 
    144149    # Format the result 
    145150    digits_after_decimal = abs(val_place - err_place + 1) 
    146     val_str = "%.*f"%(digits_after_decimal,value/10.**val_place) 
    147     exp_str = "e%d"%val_place if val_place != 0 else "" 
     151    val_str = "%.*f" % (digits_after_decimal, value / 10.**val_place) 
     152    exp_str = "e%d" % val_place if val_place != 0 else "" 
    148153    if compact: 
    149         err_str = "(%2d)"%int(uncertainty/10.**(err_place-1)+0.5) 
    150         result = "".join((sign,val_str,err_str,exp_str)) 
     154        err_str = "(%2d)" % int(uncertainty / 10.**(err_place - 1) + 0.5) 
     155        result = "".join((sign, val_str, err_str, exp_str)) 
    151156    else: 
    152         err_str = "%.*f"%(digits_after_decimal,uncertainty/10.**val_place) 
    153         result = "".join((sign,val_str,exp_str+" +/- ",err_str,exp_str)) 
    154     #print sign,value, uncertainty, "=>", result 
     157        err_str = "%.*f" % (digits_after_decimal, uncertainty / 10.**val_place) 
     158        result = "".join((sign, val_str, exp_str + " +/- ", err_str, exp_str)) 
    155159    return result 
    156160 
Note: See TracChangeset for help on using the changeset viewer.