Changeset 4a96b8b in sasview
- Timestamp:
- Apr 27, 2012 9:37:14 AM (13 years ago)
- 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
- Location:
- sansutil
- Files:
-
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
sansutil/calcthread.py
r4025019 r4a96b8b 5 5 # 6 6 7 import thread , traceback8 7 import thread 8 import traceback 9 9 import sys 10 10 11 if sys.platform.count("darwin") >0:11 if sys.platform.count("darwin") > 0: 12 12 import time 13 13 stime = time.time() 14 14 15 def clock(): 15 return time.time()-stime 16 return time.time() - stime 17 16 18 def sleep(t): 17 return time.sleep(t) 19 return time.sleep(t) 18 20 else: 19 21 from time import clock 20 22 from time import sleep 23 21 24 22 25 class CalcThread: … … 113 116 """ 114 117 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): 121 120 """Prepare the calculator""" 122 121 self.yieldtime = yieldtime … … 134 133 method for details of the arguments to the work unit.""" 135 134 self._lock.acquire() 136 self._queue.append((args, kwargs))135 self._queue.append((args, kwargs)) 137 136 # Cannot do start_new_thread call within the lock 138 137 self._lock.release() 139 138 if not self._running: 140 self._time_for_update = clock() +1e6141 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): 144 143 """Replace the work unit on the end of the queue. See the compute() 145 144 method for details of the arguments to the work unit.""" … … 147 146 self._queue = self._queue[:-1] 148 147 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): 152 151 """Clear the queue and start a new work unit. See the compute() 153 152 method for details of the arguments to the work unit.""" 154 153 self.stop() 155 self.queue(*args, **kwargs)154 self.queue(*args, **kwargs) 156 155 157 156 def stop(self): … … 171 170 self._lock.release() 172 171 173 def isrunning(self): return self._running 172 def isrunning(self): 173 return self._running 174 174 175 175 def ready(self, delay=0.): … … 189 189 190 190 # 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: 193 193 sleep(self.yieldtime) 194 194 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): 198 199 199 200 """Update GUI with the lastest results from the current work unit.""" … … 206 207 self.updatefn(**kwargs) 207 208 sleep(self.yieldtime) 208 if self._interrupting: raise KeyboardInterrupt 209 if self._interrupting: 210 raise KeyboardInterrupt 209 211 else: 210 212 self.isquit() 211 213 return 212 214 213 def complete(self, **kwargs):215 def complete(self, **kwargs): 214 216 """Update the GUI with the completed results from a work unit.""" 215 217 if self.completefn != None: … … 218 220 return 219 221 220 def compute(self, *args,**kwargs):222 def compute(self, *args, **kwargs): 221 223 """Perform a work unit. The subclass will provide details of 222 224 the arguments.""" … … 233 235 while 1: 234 236 self._lock.acquire() 235 # print "lock aquired" 236 self._time_for_nap = clock()+self.worktime 237 self._time_for_nap = clock() + self.worktime 237 238 self._running = True 238 if self._queue == []: break 239 if self._queue == []: 240 break 239 241 self._interrupting = False 240 args, kwargs = self._queue[0]242 args, kwargs = self._queue[0] 241 243 self._queue = self._queue[1:] 242 244 self._lock.release() 243 # print "lock released"244 245 try: 245 self.compute(*args, **kwargs)246 self.compute(*args, **kwargs) 246 247 except KeyboardInterrupt: 247 248 pass … … 251 252 self._running = False 252 253 254 253 255 # ====================================================================== 254 256 # Demonstration of calcthread in action 255 257 class CalcDemo(CalcThread): 256 258 """Example of a calculation thread.""" 257 def compute(self, n):259 def compute(self, n): 258 260 total = 0. 259 261 for i in range(n): … … 264 266 self.complete(total=total) 265 267 268 266 269 class CalcCommandline: 270 """ 271 Test method 272 """ 267 273 def __init__(self, n=20000): 268 274 print thread.get_ident() … … 283 289 while not self.done: 284 290 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) 289 297 self.work.ready(2.5) 290 298 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) 293 303 self.done = True 294 295 if __name__ == "__main__":296 CalcCommandline()297 298 # version299 __id__ = "$Id: calcthread.py 249 2007-06-15 17:03:01Z ziwen $"300 301 # End of file -
sansutil/err1d.py
r4025019 r4a96b8b 1 1 # This program is public domain 2 3 2 """ 4 3 Error propogation algorithms for simple arithmetic … … 8 7 integers, so be sure to create them with floating point inputs. 9 8 """ 10 11 12 9 from __future__ import division # Get true division 13 10 import numpy 14 11 15 def div(X,varX, Y,varY): 12 13 def div(X, varX, Y, varY): 16 14 """Division with error propagation""" 17 15 # Direct algorithm: … … 28 26 return Z, varZ 29 27 30 def mul(X,varX, Y,varY): 28 29 def mul(X, varX, Y, varY): 31 30 """Multiplication with error propagation""" 32 31 # Direct algorithm: … … 43 42 return Z, varZ 44 43 45 def sub(X,varX, Y, varY): 44 45 def sub(X, varX, Y, varY): 46 46 """Subtraction with error propagation""" 47 47 Z = X - Y … … 49 49 return Z, varZ 50 50 51 def add(X,varX, Y,varY): 51 52 def add(X, varX, Y, varY): 52 53 """Addition with error propagation""" 53 54 Z = X + Y … … 55 56 return Z, varZ 56 57 57 def exp(X,varX): 58 59 def exp(X, varX): 58 60 """Exponentiation with error propagation""" 59 61 Z = numpy.exp(X) 60 62 varZ = varX * Z**2 61 return Z, varZ63 return Z, varZ 62 64 63 def log(X,varX): 65 66 def log(X, varX): 64 67 """Logarithm with error propagation""" 65 68 Z = numpy.log(X) 66 69 varZ = varX / X**2 67 return Z, varZ70 return Z, varZ 68 71 69 72 # Confirm this formula before using it … … 74 77 # 75 78 76 def pow(X,varX,n): 79 80 def pow(X, varX, n): 77 81 """X**n with error propagation""" 78 82 # Direct algorithm … … 81 85 # Indirect algorithm to minimize intermediates 82 86 Z = X**n 83 varZ = varX /X87 varZ = varX / X 84 88 varZ /= X 85 89 varZ *= Z … … 88 92 return Z, varZ 89 93 90 def div_inplace(X,varX, Y,varY): 94 95 def div_inplace(X, varX, Y, varY): 91 96 """In-place division with error propagation""" 92 97 # Z = X/Y … … 98 103 del T # may want to use T[:] = Y for vectors 99 104 T = Y # reuse T for Y 100 T ** =2 # T now has Y**2105 T ** = 2 # T now has Y**2 101 106 varX /= T # varX now has varZ 102 return X, varX107 return X, varX 103 108 104 def mul_inplace(X,varX, Y,varY): 109 110 def mul_inplace(X, varX, Y, varY): 105 111 """In-place multiplication with error propagation""" 106 112 # Z = X * Y … … 114 120 varX += T # varX now has varZ 115 121 X *= Y # X now has Z 116 return X, varX122 return X, varX 117 123 118 def sub_inplace(X,varX, Y, varY): 124 125 def sub_inplace(X, varX, Y, varY): 119 126 """In-place subtraction with error propagation""" 120 127 # Z = X - Y … … 122 129 X -= Y 123 130 varX += varY 124 return X, varX131 return X, varX 125 132 126 def add_inplace(X,varX, Y,varY): 133 134 def add_inplace(X, varX, Y, varY): 127 135 """In-place addition with error propagation""" 128 136 # Z = X + Y … … 130 138 X += Y 131 139 varX += varY 132 return X, varX140 return X, varX 133 141 134 def pow_inplace(X,varX,n): 142 143 def pow_inplace(X, varX, n): 135 144 """In-place X**n with error propagation""" 136 145 # Direct algorithm … … 141 150 varX /= X # varX now has varX/X**2 142 151 X **= n # X now has Z = X**n 143 varX *= X 152 varX *= X 144 153 varX *= X # varX now has varX/X**2 * Z**2 145 154 varX *= n**2 # varX now has varZ 146 return X, varX155 return X, varX -
sansutil/formatnum.py
r4025019 r4a96b8b 6 6 :func:`format_uncertainty_pm`(v,err) produces the expanded format v +/- err. 7 7 8 :func:`format_uncertainty_compact`(v,err) produces the compact format v(##), 8 :func:`format_uncertainty_compact`(v,err) produces the compact format v(##), 9 9 where the number in parenthesis is the uncertainty in the last two digits of v. 10 10 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 12 12 can be changed to use the expanded +/- format by setting 13 13 format_uncertainty.compact to False. … … 34 34 757.236 +/- 0.010 35 35 36 UncertaintyFormatter() returns a private formatter with its own 36 UncertaintyFormatter() returns a private formatter with its own 37 37 formatter.compact flag. 38 38 """ … … 62 62 # such as 1 g/cm**3 -> 1 kg/L. 63 63 64 64 65 def format_uncertainty_pm(value, uncertainty): 65 66 """ … … 68 69 return _format_uncertainty(value, uncertainty, compact=False) 69 70 71 70 72 def format_uncertainty_compact(value, uncertainty): 71 73 """ 72 74 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 74 76 the uncertainty. 75 77 """ 76 78 return _format_uncertainty(value, uncertainty, compact=True) 77 79 80 78 81 class UncertaintyFormatter: 79 82 """ 80 83 Value and uncertainty formatter. 81 84 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 84 87 True or False. The default is True. 85 88 """ 86 89 compact = True 90 87 91 def __call__(self, value, uncertainty): 88 92 """ … … 92 96 format_uncertainty = UncertaintyFormatter() 93 97 98 94 99 def _format_uncertainty(value, uncertainty, compact): 95 100 """ … … 103 108 104 109 # Handle indefinite uncertainty 105 if uncertainty is None or uncertainty <=0 or numpy.isnan(uncertainty):106 return "%g" %value110 if uncertainty is None or uncertainty <= 0 or numpy.isnan(uncertainty): 111 return "%g" % value 107 112 if numpy.isinf(uncertainty): 108 113 if compact: 109 return "%.2g(inf)" %value114 return "%.2g(inf)" % value 110 115 else: 111 return "%.2g +/- inf" %value116 return "%.2g +/- inf" % value 112 117 113 118 # Handle zero and negative values … … 125 130 # Degenerate case: error bigger than value 126 131 # The mantissa is 0.#(##)e#, 0.0#(##)e# or 0.00#(##)e# 127 val_place = err_place +2132 val_place = err_place + 2 128 133 elif err_place == val_place: 129 134 # Degenerate case: error and value the same order of magnitude 130 135 # The value is ##(##)e#, #.#(##)e# or 0.##(##)e# 131 val_place = err_place +1136 val_place = err_place + 1 132 137 elif err_place <= 1 and val_place >= -3: 133 138 # Normal case: nice numbers and errors … … 140 145 141 146 # Force engineering notation, with exponent a multiple of 3 142 val_place = int(math.floor(val_place /3.))*3147 val_place = int(math.floor(val_place / 3.)) * 3 143 148 144 149 # Format the result 145 150 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 "" 148 153 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)) 151 156 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)) 155 159 return result 156 160
Note: See TracChangeset
for help on using the changeset viewer.