H# coding=utf-8 """ Main module for the uncertainties package, with internal functions.H # The idea behind this[is to replaceeresult of mathematical # operaZ by a local approxi' on6defining . For # example, sin(0.2+/-0.01) becomeseaffine=Q # (AScalarFunc object) whose nomivalue is_s) and #&Cvariare givendelta) = 0.98...*Y. # Uz0cann be calculatedJ usaPlinea(Aorig( # Many analy} derivatives depend ois import sys $re Q from +qrt, log, isnan0infyqOptimiz%: no attribute look-up try: Y@isin teL!! Python 3.2+ except IRErrorFFdef 9(x): returnb(x) or5(x)Dcopy0warnitertooldnspect0enumberacollec /`followrestrictp getarg\ ()Hcommon # featuresi.1Gand EfullN@: if.version_info < (3,)8~?__ else) o7 asA0at /always exped (some other's+&ponly if0g NumPyz available...): __all__ = [DAll sub-m sjC notdefault,# in partirdDause@ight&uny'ufloat',Bs a G y{B_2strJ5antOPiform acces standard dev'-_"' 'std_dev',# Utilityps (more#ifBis present1'codnce_matrix[RClass0est[2whe=n W]. Not usually cre{Sers (gpthroughwEV0blePc), but possibly manip2extQCcodeD'['()' method, etc.].&2'UF<TqWrapperaWnon-pure-Python function to handle # quanties with uncertainties:'q'wrap' O] #; def set_doc(doc_string)}1"""yDecorator0hat9s the doc9given text.It is useful fJhs whosCis calculated(including gsubstituY1s).&(| ._@__ =)H"Rretur*. # Some types know>not depend on Variable objects are put in # CONSTANT_TYPES. The most common \Tcan b7 front, a} is # may slightly improveAexec% speed. FLOAT_LIKEr = (numbers.N:,) < = 6+(complex,)@# Utility)@issupdepreca warnings(message1'''@Warn-erm4T, by na8DtC2ingkX!# stacklevel = 3 pointsoriginalw`call ( toBfrom this modul at 0ledQ#().# gpignoreddefault: w uswB. ('Obsolete: %s Code rautomatiPy updAZ-' python -m .1to2 -w ProgramDirectory.G%% _/=3lBD@fini#a$ravailabof NumPy: try'import numpy except IRError%pass else:#I6}1 do8G " +py.generic,) +T[-1:]@Ente# vs_a block of corre values. Only i#enstallv#! It would@ossito dispense\, but a routine sh9# written& ob8(aeigenvbsa symmetric matrix. Sei0nce{Gal Recipes: (1) redutri-diagonal [Gs or Householder-]; (2) QR / QL decomposition. def correlated_values(nom , covariance_mat, tags=None):BF5""" -Return numbers with uncertainties (AffineScalarFunc objects)EBthat ctly reproduce the given matrix, and haveG.(float) 0 asJir nominal2The_norm() funcD! rL same result,but takes aO3ion instead of i @list* ndQ must blength*K:2 be a square (symmetric) onered depend on newly0crejB, in#Aent blVm5ble| -- sequencecU(real)ofSto be'edy }Ofull{lC  . For example, first elemS#is! inL:'e<nVy. ThJ'MNumPy array-like (t7s, !, etc.). H4@if ' '@not .B, ithL0tag@each%.l # !!! It would in principlePpossiMto handle 0m&nc&##byCselectingCsub-,Pdoes 0conGsuchQ(@helpnumpy.ix_())kGthem separately$std_devs =gpy.sqrt(^Zdiag(&))#unumerical stabilitjasons, we go through'5ion#, because is enive to any changePscale(thaquanti"rF. However, cSn : calcula@ canbe simply donby divid by-@ndarviations. W0us specific&9Aaliz/md@no nMS2_vector = f.copy((&[ ector==0] = C1 return correlated_values_norm('.# !! The following zip() is a bit suboptimal:R+()N separates back the nominal A andstandard deviations:MPlist(3nom, std_devs)),-covariance_mat/x_vector [:,numpy.newaxis]ERtags)G__all__.append('L')>defic_with_,,0ion  f=None)5'''RhEliken(), but takesEinstead as input:-t(float)``along >ir ,e5- aion matrix (i.e. a valized %&).V -- sequence of (s5ks) pairs.7&ed$ed@have%seE essD betweenmc given, exceptthat any ?a 0a must 8itsset to 0,IPdiagoelement "an arbitrar{(somethingQcloseQ -1Lrecommend_0for]etter numerical precision). WhenN#no ha$0 `, thisaj 8U%byOs@ thu`symmetricones on it6%@. Tpbe an NumPy array-(s)h, etc.0B?9.  # If no CBwereV@, werBpareWFnewly cre:Gt7ble"if;0is :q0= (,) * len(I3 =)py.transposeK T# We !iz ofr Mp, becauis generally morey&bl #ly. In factN31can efficients ys, through changes of units #+its input variables. This creates numerical instabilities.H q The coKnce matrix is diagonalized in order to defineCthe independen that model %given values:A(}s, transform) =py.linalg.eigh(correlation_mat) E5# Nerrors might make some/ nc!egative: we setF@themFzero[ < 0] = 0.C0ionOnew,:3aWe use Bfact4.eigenvectEin 'H' arspecial:#!is>Rary: 4PverseMGposeQ = tuple(#-%`repres"pure" uncertaino><V(0, sqrty), tag)iEfor ! list(zip1Yags)) Qordinof each newy as a funcO(thU/must includ scale (standard devi)m *= std_devs[:,newaxis]  4# RfU initial -edXh_s AfScalarFuncD,LinearCombdion(dict(Ip, coord),)3P, nom_K?TreturS__all__.ap&('(G_norm') #;` # MaG!atAopers with loapproxim!(aMEar # s) class NotUpcast(Excepb'Raised when an object cannot bpnvertedau2bery' def to__Car(xg1""" Ts x into a coj2nt ;8(o), unless itpalready +A (inEwhich case}"s  edh7#d)sMe0ox belongsBAfic l|oKsare known X ]M on 9E(t psideredconstants).  """ if isinstance(x, AffineScalarFunc):(,return x:CONSTANT_TYPES8# No variable => no derivative` LinearCombination({}))# Case of lists, etc.*raise NotUpcast("%s cannot be converted to a number with">" uncertainty" % type(x`# StepRIPt forPgericals in # partial_(). Value chosens ge7tteR4 # results: STEP_SIZE = sqrt(sys.float_info.epsilon) # !! It wouldPpossito split theq calculx # into two funcas: one@posial arguments (cinteger #_ref) and=pkeyword :gstring9. However, thiseither duplicate2codXthe #ifferenti, or require a l, which is probably morGexpensive in timl!anqptests dhere. defW f,rRiabV that ly!essRV! f9@pect[0itsl .T0arg -- describes Vto usZdRP. If a2ledf(*args, **kw )}!s, ane+q represGPindex%an5G,MaB0 >1nam( =3B1# W0setpG`parame0con #beBchanged?!or#op+ ?A?_( =S, streN_of_qoP,h#(-U3, + )Egmethod90P prec#th$'(0= 5ER. s_@_varfxfe 7#E_0musk shifted, as a mut0objAP(becaJ_@willemodified):Zp# The vBs ne4be 4,T6+# c@: it  if change_kwargs7: args_with_var = kw#Oelse1 Plist(4%) 6(# The step is relative to the parameter being varied, s'atFPshift#%it does not suffer from finite precision limitations= STEP_SIZE*abs[arg_ref])~"ifn6tepJ9 # Arbitrary, but "small" F respect18 />1 +=C(if change_ `-ed_f_plus = f(*Z1, *brE=N~g"La -= 2* # Optimiz: only 1 =_ copy?min0 Freturn (%&- P@)/2/6partial_deriv_of_f class NumericalD s(object)1"""Convenient accesslXb bs of a func,@calculated nu1ly.d israqbecauseanumber_qrgumentl1theH#tDknown in advance, general.)`def ____(self,F ''gi whose can be computedFRw%._F=ugetitemnR0Fn-thoC!sD(D, n)RIndexableIterK1'''".pvalues )@also.bed through iV3inginput iterLFare cachjmSome attributes:R7&--Cused for $3elejne by one(5ed_#"-- =directly>Bibleu P Addi95al Y`obtain4`none_cr%--I that takes asdex ands_0H#beed when None0orm8BA(instead of None). :''' def __init__(self, iterable, none_converter=lambda index: None):EIRB5 --N whose values will be returned.= uCfunction applied to ~>^C. Thj that replaces6+is(%),GRwhered is th !of element.1E.=-!_Ljs = []$ =3vgetitem"):#Vp47tryBFx[B];except IError: # E8 not yet cached6cfor pos in range(len("),(+1@q = next)m-"ifV:S4 O(posX .append(K 1-Y 3str~@'<%s: [%s...]>' % (__class__.__name__', '.join(map(str, 8d%edP))) wrap(f, derivatives_args=[]!kw#{}1"""Wraps a hf intopalso ac\s numberL!thFuncertainties (UFloat objects);6pedjE of f with5correct aay and  lasuB ciBtendbe used aPdrop-WExoriginal:Py can@`called--exact sameD@way,. only difference beingEA1canGbe givenwf /ffx@argus Dou`so maynecessary when f"be expressedpanalyti1y ( ies-compatible operators>\s like +, *, umath.sin(), etc.)Pf mus:-:T(i.e.@, an>31t apBlist), unless"ed^#no8yT=s because generally@ rtainties: t6hey represent a probability distribution over the real numbers. )!Ifwrapped func4is called with no argumnthat has anluncertainty,Mvalue of f is returned.qParameters:-derivatives_* p can be usor definingt1sombpartial J}Q. Alld(non-None)=)0mus!ve)same signature as f4_args --E`terablDat, when i1ted~,ps eitheF(}`s) or .x in)pticular%aEsimple sequence (listOqtuple) gn5 ofFWfirst posi als_FEach;Sb e4 <Uvrespectvo0coroonding. TheseusE"ak{sm?The[aX0 arBuallY<-or-keywordrlike in1allO5(a, b=). However8y also include var-j_FeQroughmB(a, b, *) syntax. I/Ve lasv0exa3,kCbe a5theI @ to @ andne/"opWB9yq%A S8 (instead@) ob"he>L sRis automatiYvlaced brelevantC er-4g. This1notio  s 2aa1berJ;g1. AVPefore4escalarGms=f 0ke -%ng's)}"7yields fewlneeded, j+()r@setsQ rema0 unUifiedH 0.e.B=0cal0vLRAn ink teF'oft by havt^eHn#tePor; t6&foaspecifying the derivatives of functions with a undefined number-argument (like sum(), whose partialGhall return 1). $ _kwargs --!Diary that maps keywordlameters to their,aFor None (as in$_r+K\ ar/as being t3of ewhen frhas a signature6the form f(..., **;). In Python 3_thesealso includ W-only^Non-mappedM re replaced automatically by>:b2 wrK1 will use, if necessary,/ erJEdifferentiak S5{6 BNotefthis d- -C*paree* fromb**f. The wawe0is $%edEis immaterial:bexampl f e f(a, b=X) " should bwe emptyf, evenfV@ can;$ a_f(a=123$42E (for illustr`purpos/bnly, a+uncertainties.umath.sin() runs fasternstfollow):(@2) iA%ne4applied toF s ; W Its beSculat2numJly. 0, [A]) whave produ6@AsameoresultAAcos]4Q, butGan analy/N s meaningless "thwis not ble (e.g., hypot(x, y)F =(0, 0), and sqrt(x$bx = 0)Mcorrespond@ Gxeither A(cas@) or raise an excepLB3cal :fPsuch QPs, itdrecommended (bu mandatory)]supply instead aarPs NaNnrk %iT) staRk/,ance by using +the uncertainties.core.partial_derivative() function. 7The correctness of the supplied analytical Gbs an bxtested by setting@m to None insteaHd compar#~^0and:b numerpifferentia resultsNote on efficiency:@uwrapped assumes that f cannot~Pcceptrbers withG as arguments. If f actually doesGhandle some. even when`y have6 y,B Qignoris fact, which might lRAto a>performance hit: OgaasG y is likelymake it slower.22"""E_args_index = IableIter(5# Automatic addi ofs in case.B }pshorterZgber ofb*:itertools.chain(e&, "prepeat(B))) 7# Dfor keyword#(includes var- # paramet@**kw, but also0o3-S, andCQW-only# (Python 3): 2ll_oR = {}!g(name,)7;7t.items(\qOptimiz:ZubnverteHr1awa}$ (iPof do@thisPry tiHq3encounteredqcalculaj+ifEXEl:%_a\[M0] = 0f, )OelseUt3# Wpis call9P# map 1pos?al-ZtheirC@look,or>. We definsi#+ 6try%/pec = get "(fS!exTypeError60# S"s do not provide meta-data about!ir#5(see PEP 362). OnexN use Dka with them: nothing has # to be done:2pas#7els# With Python 3, there is no needMhandle keyword-onlyX# arguments (andA@fore:use inspect.getfullarg7())D@beca,they are already {d by derivatives_kwG%. Cfor (index, name) in enumerate(.@pec.&):73# The followLCtestxs case ofl5positional-or- parameter which automaticBical differentiaSused: when{wrappedBDfunc1called wa2thi# nP mustQcalculatt ret6theY2. Io`R,wy; | E2Aits / F1be  (N=U_M[]8'if.N_Ss_all[0] =PVtial_'#(f Y6]# Optimiz : sN&e js# convertF0cor0ondjn ?(instead of do;` over t r every time aG Tfound Tnone_r = lambda :z)/}K  2rgs;.returned_eleO)Cx&s_VE = ( )# Future QvalueV alsoFally n: =  \B## Wr#! SettPc str afp"def f_...()" doet`# seemwork. We define it explicitly@set_doc("""\@pVersion%s(...) that qs an afOpapproxi!on<!(AScalarFunc object), if result depends on variables (Variabl8e objects). Otherwise, returns a simple constant (when applied to pargumenP %Warning:  of the function that are not AffineScalarFuncEQ must&depend on uncertainties.Variablq in anyE:wayIDenceresult i_ will be incorrect.Original doca:%s""" % (f.__name__, qdoc__))%def f_with_a_output(*args, **kw "):q#a10 Thvolved random vDsoPfirst gaged, soCthey can($inUtly updatedvA0con( a?y (F);pas posipPs or b s;r#y replaced by#air nom@valua orderalculate@Dnecessary derivativesOfbpos_w_O@ = [&qx for ( !, q)enumerate(oaif isi1ce(@,A%)]@  2key8key]r.items(y #1! Vof f() at RT9Bw%y0@usuaahavior () is kept, if no number W1provided$@if (R) and )8<- f ( Nv!(sA !! Possi*bptimiz0 If>$is empty,vris actually"e reate a mut@vers ofs on[auld do _1s =. However wrappedAFis typic!eds  7iesG6 al{s (i.e.,wemtpy),Eso this "oT"0Hwed here ##~Blistt # Nowm: modifiGelowA with an uncertainty are converted to their nominal # value: for index in pos_w_uncert#;Qargs_;!s[/@] = .i$ _## Keyword.wuments: For efficiency reasons, kw^ is not copied. Instead, itsdrs with modifiedvThe orig>1iesUpneeded:PfwPsaved8the following dictionary (which only)^fs = {}E@name_%O# =g[7]P# Sav^future us9%L" =Wo ` 44is  (~)y)f_` = f(*whB, **\)n@# If a float,n this code canuprovide#( result, as it returns a UFL=`repres9' aA`random1l variable. Tzhappens =instance when?u()*numpy.array()calculat4AffineScalarFunc.__mul__ operator, obhrough wrap(),F@NumPTAray,F!if$is(, FLOAT_LIKE_TYPESn NotImple'ed#2# C!Rion o linear part1fun( deGd by (co!rg") pairs,Sre 'a'Flis an 1>allxfound aXf8_F= []R0posj,?.5d((76# Cderivatives_u_[pos]cA># L 3 ex`Nsion{u'._)>} # Optimiza`: cach`Bautomatic numeric for keyword arguments that are %# discovered. This gives a speedup when the originalAfunction is called repeatedly with>same keywordB:derivative = s_all_kwargs.setdefault(<]name,6# DXnever needed beforeHpartial_@(f, ^9)) `plinear_1.append(# Coefficientnf*_values, **)Lz z1 ofq AffineScalarFunc expressionv[s_uncerts[7]._e# The now returnke necessary @ approxima-7A# toIN RPf_nom", aCombink( f_!_a#_output = set_doc("""\0Ver0Sr%s(...)GRs an D( object), if its result de*s on variables~#(V:s). Otherwise,oa simple constant (Dpappliedfp").Warning:.E}are notjas must&Wainties.q in anyE:wayyI@ence:!in5_ will be incorrectOA doc$/%s""" % (f.__@__, doc__))(B@# It `easierzBwork 7p, which60res`# a wrG6d v0'f'1en it bearo_r as 'f'D# ! read-only,uPython 2.3..T= "__3 3 def forcec_E_( )m1"""0Takon operator op(x, y) and4s isfructed5s? to{Qine_s@(y))xg0canbupcast 1F); ol$ito@NotIs[#edQRThus,)nimon two:Y@firsJ-an:./F rop_on_upcast_args(xs, y): 5""" (Return %s(self, to_affine_scalar(y)) if y can be upcast@}through8. Otherwise res NotImplemented.E""" % func.__name__ 6tryy_with_uncert ={5(y)=`exceptyU J)# This module does not know how to handle the comparisonF@(exa: y is a NumPy array, in which casJ#- will decid*!at() should{applied>eU-obetween x and all#Is of'cJelse0I(x, )#bop_on_5_args # # Definitionboolean operators, that assum1* #a are ASFodThe factLWainties mustv smGis used, here:V' #smsupposedGb?nstant for most value #L random variables.qEven the d,Ds # p3+/-0.1A 3.0d correctly (eqAx ==,iIDa co0unc `interval). \8x/qtoo, whvhas an ay. In, # as explainedmain docu_a@, itb`possibo give a #ful meaningfi1ese`def eq@aff_A 7qe__eq__Y,~Tboth   objectsMidifference =R-PL`# Onlyh exWzero ;s7>equal numericallFnot(M._nominal_7 orj.std_dev) Y/neY/neYN/gt/gt,AffineScalarFunc objects. """return self._nominal_value > y_with_uncert def ge_on_aff_funcs(H,8!):iq__ge__ operator, assuming that bothJ andIA areKAffineScalar'?(gt1_or eq4)l_ /ltN * <\  l\~$#-first_digit(@1'''RiAthe + + position of agiven A an integer. HA0 is*@just beforeecimal point. DAs toQrightFnd. have a negativezP0 for'2ullR2tryint(math.floor log10(abs/1)))except VError: # Case$Q == 0-d0PDG_precision(std_dev`numberZsignificant7qbe used{standard devia, accordr1ounPrulesg"th Particle Data Group (2010(http://pdg.lbl.gov//reviews/rpp-rev-rpp-intro.pdf)RAlso 1Qeffec"vdisplayexponent =i5# TTthreeRPare wmatters: we getqm as anf# in [100; 999)#*In order@prevunderflow or ov when calculatingAD10**, l sl6ly modifi aBQfactopbe appl'after "removing"Z8new^@ dedFurthermore, $(-)2notbbecaus" # range for very small and)big floats is generally different. if exponent >= 0:!# The -2 here means "take two additional digits":(R, factor) = a-2, 1)gOelse7+1, 1000:t = int(std_dev/10.**|*{ #% rounds towards zero r# Rules#ifr <= 354return (2, p)el4>949414i paheses matter, fQlarge#xj (B/) # Defin of a basic (format specifica only, no full-feature #-ctring)ting func;that works whatever the`sion #~Python. This;exists so E6more capableo() is # used insteadT/%$operator,PavailF: robust_=3 class Cal(qStdDev(Y)q1'''C)standard devi;results, whichBto bc^. Provided compatibility with old code. Issues an}obsolescence warn~Pupon \-q2is Bis a). It must be set ts.e F`aonstru.R`def __y__ (self+RdepreQ ('N attribute should noH"eddAP' any:S$ .LB().'AE lez:keys are Ppossiomain_fmt_type val%of_num(): EXP_LETTERS = {'f': 'e', 'F PE'} )xalign(orig_still_char, 0_opIs, widthPA=sqgiven s3dPfill TSacters4 --7wed (str or uniz object)?T@Mmpty, spacey+.as accepted byDmat(Y wdBrcontain  print "ALIGNING", reprZ), "WITH", +,H1WID-m<*YP+:l0MapCme ULQpoints ("-", "+",) ir # superscript version: TO_SUPERSCRIPT = { 0x2b: '⁺',d!30f1: '¹234A56789!'} # Inverted T.table, for use with unicode.translate(): # #! Python 2.7+ can3a dictionary comprehension instead: FROMdord(sup): normal( ,  in iter(.items())} def to_superscript(value):"''Return a (U) stringthe given =0 asR characters. W3The* is0mat`BL%d %-operator!;a-- integer.Q rr('%d' %e) )Ifromnumber_str!Co 9s a? digits and sigAto aVeError is raised if cecannot be done -- basefobjectint(str(< d ))1Funa that @form exponent produced by`_num()3o #rrespond2@nota (A non-default modes): EXP_PRINW'pretty-print': lambda:mon_exp: '×10%s 3com&)'xGr' \times 10^{%d}QBpSymbolsd` group(typically between parentheses02mat,: GROUP_SYMBOLSF ('(', ')'`# Beca|of possiblysD1ide (case of a # specified field width), itbetter to auto-adjustingA^. This hasxs`effectr0mak 0parG( Pbreaki (DtextvLaTeX math 1resJQ$...$ybe broken)*(r'\lefter'\rightl'6':  # Basic Y.nom_val_main, e U@fmt_'s, prec, >_pres_type, opB,2r [uncertaintyRBNull6s () are displayedinteger 0, wi th no decimal point.  The formatting can be partially customized glob0. 6EXP_PRINTH0maps non-default modes ("latex", "pretty-print") to a function that transs a common exponent in60strS(of t"times 10]tpower <@>", where *"=represented, e.g., a`red docstead zmultiplicassymbol)$GROUP_SYMBOLS mapp,CeachH#se. to@pair`s usedQ grouF exsions (typic=rentheses3ichBinstance replaced by "\left(" andD`"\righin LaTeX soto create abreakable)Ynom_val_main, error  -- nominal valuer , before usingb_exp ("1.23e2" would havfO0of #;@similarly, "12.3+/-0.01> 42.3--- to. If None,e2i@fmt_as contains at leastp follow96!ofU)at specif: fill, align, szero, width,"a,EAype;f3re s.s d!Qs areFqhandled2e is appliedbr, or, iPshort=F1notH<,rI1G Bal (NaN, inf)hpas muchPpossir @preciguse with3u_E_typ) (see belowN 1 --@mat E#enA, either "f" orP0"F"bis defines howntissas,xsWrNaN/infJA (inDsame wayfor float).mQempty@"@ "%" not acceptedA op (Spn objecupport membership tes1lik[ a`). "S"P-QM (10P0\("±" betwee H1and,, superscriptx`, etc.lLlaADoutput. Or`combinDR dd|f&@percD%pa O notation is #not used. The P option has priority over the L(if both are given).?A''' #?nt (nom_val_main, error common_exp,3 fmt_parts, prec, <_pres_type,$s)kIf a decimal point were alwayesent in zero roundeds|Athat',formatting would be difficult,SsgeneralG(because=XsbSvery 7): an exampleDis'{:04.0f}'.(0.1), whichqs "0000" andshave toE$.". Anotherh is '{:ificant digitv$ifMand fmt_s['type']^p('', 'g#G'a# The 4between 1 Np10 beca!Sany p)Ais taken care#'by,Wit is<formatted8:outotherwise,5Aw#? to5handled for4W%suffix_n = (s['prec'] or '')+N}Belse_$M'.%d%s' % (L,__@_C$) [print "FMT_SUFFIX_N",N*<jCalculqostly fsnumerica valueQ(no %#,global width applied).! ES # Shorts:/3/# uncertaintyN<6if V == 0\#@exac$]0elif isnan e =rrobust_4x70' f'\mathrm{%s}_7infUx Vinfty!F ? = U=lNa meaningful firs (!0,Creal86undn, prec)  # The representation uncert_str of theainty (which will H # be put inside parentheses) is calculated: 9ucmight straddledecimal point: weCkeep it asis, in thxse (e.g. 1.2(3.4),' EQmakesoresult easier to read);shorthand>#no@pthen esQially coincides withE?+/-?:if first_digit(&) >= 0 and prec > 06Pinclua zero rounded error`s|F0aft:he  +7= '%.*f' % (,B)Nelse#if./Wimportant because 566.9M canFWobtained w0567Wwanted (%c1intJpintegerat, noted value) 3d18`*10.**B)|="  indicates a trun }d floatZD(! @easy*doUj, sinc;# fmt_prefix_eFignored 60.')T# Endfinal numbera(widthalignmen#Pd). TastringG1forl%of"#h_end = '(%s)%s%sR, exp apercen_@any_"@fact'p = TrueV`Single@@onen_goutput'#1Nom1 formatting3# C(ofn0fix;vCiAmain( nz)p`arts['!']1a'']6T@PaddF;Ps musp done oe|m aloneK ReM6( znom_val_ = max(int() - len(yF), 0Q5!n:6#%d:[*.rsign'],  ,E fmt_parts['comma']) Uelse: # Any 'zero' part should not do anything: it is @includedfmt_prefix_n = arts['sign']+# print "FMT_PREFIX_N",FUn -8SUF-1suf[ nom_val_str = robust_format(JmainmMO#Overriding of Uqfor LaTeX,; possibly based on theFPexistDpvalue (<NaN vs nan)if 'L' in options:if isnan@$= r'\mathrm{%s}' %7!ela?infa a# !! IEwasteful,this case, to replac d#1: c;be avoided whil;)toGduplicateq 0ulaa@the /onG* (Am...))?- Z%s\inftyWf('-' i'|P < 0 7 ''m S+6end# Global width,a7any"ifM&P']:  individual alignmengneededFQvDefault,,>numbers:Jqright ( ##:aspecified, a str"is$#edN AKleftv(;*ifill']@'] or '>',IR]0+/-AaH5# Tkc exponr`factorr8r, depen[ 1s0. TNgives nicQlumnsnominal Fs an#errors (no shift duev`a vary), when a #nany_exp_=BTrueb hay+directly attach1# (Xof anAboth 1and  non-0, real ').B@goal"toSpstrangePe-10, #5F0e102an exactly zero uncertainty, .# because .0e can give this for a non-zero error (the goal isFto have a ,ul be very explicit):8S_has_exp = not any_factored andspecial_5 Dr # LikeL, but onlyreal number handlingA # re is no g meaning tonominal value4nomx isinfinite(6val_main)# PrefixlVparts3qif fmt_ ['width']: # Individual sUA# Ifs are needed, then4taken into#@account now (befor)ePonent=Wadded: :']:' =z(#-@# Re>(minimum)after includ 9the@1exp_rZ_Amax( -len(exp_str), 0_n = '%s%s%d%s' % (p2['sign'],42 0if [UBelse?ycomma'] eN.A|+ #DD23DGlob>M0M  1@ ## print "ANY_EXP_FACTORED",|6ERROR_HAS<*",w07NOM.#J( NwwmattingC# !! The follow fails with Python < 2.6 wPformakccepted by% operator. T%ahappenM?;true, asIq@usedSD]<essentiall?fproviduser, whichF0mayxempty:  # print "FMT_PREFIX_N", fmt_prefix_n  -8SUF-2suf-. nom_val_str = robust_format(Jmainm+zM%) N|NOM_VAL_STR", I7str,#IbError Wting::+ !! Note: .0f applied to a float has no decimal point, butathis doe*tE0earDbe documented0(http://docs.python.org/2/library/string.html#-specification-mini-language). Thisb+feature is used anyway, because it allows a possible commaE parametehandled mor4nveniently than if theG3'd'}2 wa. p The fo0ingal integer representH of zero uncertainty:_@if e_#zyof NaN/inf inuinal value identical to_HOthe Hstandard devi if (isinfinite5)jnOnly som6fs have a nic* jA2andarts['type']p('', 'gNG')):1Od can bted indepen%lrPe = (pprec'] or '') NelseML]'.%d%s' % (\ ,  s_STN J0I BI 8 e# Overrid cxfor LaTeX`if 'L' op;sif isnano@$u= r'\mathrm{%s}b7!ela?infa%s\infty^@('-'ZfOP < 0 /us.7![ ifT_has_expl`+= expW= ;r ### # Final alignment of each field, if needed: 5if fmt_parts['width']: # An individuU.isF# Default, for numbers: to the right (oB is specified, a string is^#edN Aileft):effective_^( ='] or '>'robust_format()~ used because it may handlex # options, where% operator does not}nom_val_str = (_ ,,fill'], ,A) _error*@%##if 'P' inp # Unicode has priority over LaTeX, sat users with a_hD-compatible= source can?: ±~pm_symbol = '±'W elL:xr' \pm >/sei7+/-># Construc:fQqvalue, , possibly&DPgroup(typically inside parentheses)(LEFT_GROUPING, RIGHA) = _SYMBOLS[print_type]# The nomA andk! mt@have8be explicitly[agether% asD@prevd'anAambiguouaJ`. This:@doneparallel]7the@@percUBsignWMotJv1too?d.if any_exp_factored`common{not NonO~'.join( y3%, !, P 3 Sstr, 1F%))G,el[]S(ifp y e.* 2Z  percent_str))  return value_str def signif_dgt_to_limit(#d, num_0): D1'''RLthe precision = necessary to displayuQ with?Zicant digits. &T^is given as -1 for 16p after qdecimalEpoint, 0+integer rounding, etc. It can be positive.< Afst_d = fir))D_no_],*-"+12 # number o uncertainty, when#ed at this dlevel,too large by 1Ea(e.g.,  = 1, 0.99s^= -1, butK#ed"at is 1.0, i.e. has 29g pinstead=). We correctF0effby adjusting~f=J=, -)b edO>if 1>V >s*o F;A#bu@onlyq1 aboveInon-b C += 5 # class LinearCombination(object01"""'& c(Variable differentiall^_7o attribute`changeQmallyB itsxualways remainssame. Typic6f "cac@thusJexpandedGis a mappTfrom As to{coefficientCYtheirG4p# ! Inv8Lnt: srepresented  rn exactly asE{ <Pargumto __init__(__slots__ = "6"F4Yself,FIbe modifiedKP, durG"it?AfetiRallow5}# @*0 ov;Pime (S|1anc'G and replac-original ex%C`sed one)`jOY-- ifWLpa dict,O@n it~( an expa(nded linear combination and must map Variables to the coefficient ofir differential. Otherwise, it should be aE1lis>(N1, LC) pairs (that=represents a ex esion).5E""" Rself._3o =I*def __bool__(3%):BO Return True only iR cis non-empty, i.e. ifU?the5contains any termr )@expa%!ifY isinstance m, dict)E:.!AThe  i:`collecs.defaulty(float)<$isbe called 2yet:ded  # derivatives are built progressively byLing eachD ` until/ re#no%B to9'gFinal , constructed80? =  `while  02: 5OsaiPT# One*9P`ed or,"nok7Bneeded, simply adZ0` exist@ NrOptimiz note: since Python's oper ?left-associ@,pong sum0can[ EPsuch n$Q lastrTst0ial [ (andEnot a Nested`: popp@fromh ?`remain!allows thisquickly put inDKfresult, which limitLe numberg A whose sizn temporarily grow(P_factG >) =S.pop(<# print "MAINS", C P "if'j.( 'for (var, factor) in main_expr.linear_combo.items(): derivatives[var] +=HX* < else: # Non-expanded form'nD , X# The is applied toU:Jself append(())# print "DERIV", .* h. =)def __getstate__(6Mt false, otherwise __s3) will not be calledqreturn Y ,P!, A" =' class AffineScalarFunc(objectF1""" &! functions that support basic mathematical opera+@P(addi, etc.). SuchQ0canx instance"usCrepresenting the loi(!) behavior of any[.RThis kEalsoc5to ^1 co%ts9e variables]2! s3gss are V) FD?e includeqilitiestcalcula'error' ona, fromuncertainHfon its Main attributes and methods:*- nominal_valueWqd_dev: 1 atnorigin /.,Q hndard devi !.   be NaN or infinity- n, s: abbrK) {1 st:6?`ponent> 0[x]Ws due toxW?:#I(/ of/)%Vwith respectf'6a DC!diary whose keyQ;PwhichBG0 deQ!s.IQnumerC P Alle  <}C#inX'Y'Z-score(x): posWnumber x Y3theS/Pin un%9 # To save memorylarge arrays__slots__ = ('_uN', '_linear_part') # !! Fix for mean() in NumPy 1.8.0:(class dtype(object)E = staticmethod(lambda value:)s! The coduld be modified}order to accommodatenon-float# nominal^s. This coTinstanceadone through?the operatpodule: 4ead of delegating'sions to?g.__*__ c, they$beE&ed9t<Qfunct[(while takt@care pr1ly handlingdreversA: __radd__, etc.).rdef __init__(self,;_, linear_par1"""ll12 --uGP whenR R5 isGCzeroVxTLpCombina that describesZRb!ofAffineScalarFunc.& # ! A technical consistency requirement iq at[<0can]Anestside a N Ep(becaus isiDhow F\s on calculateGtheir result: bxanstrucpexpress"GDthem@# De8e origin:G,QOnly C-lik0 s ed. One reasoniEdoes not make sens1a s Abe aCD?Ryield`Anothe ! w(no`to havtcomplex'\, here (itI"beed correctly at all):d1ver#to shGbe possible%*._=C(a5In Ib execu^"imxlong sums_4generally left a(pwise, eac`@succ|rve term9` expan# a)ply growgsum of9s: efficienWj-!chZs [so, without copies]Fiqobvious,algorithm Q work)7allAabeyond0)c0=>D#Bfollp"nt{'' attribufrom be0 byR user@0!tyVlue(self):  "Nominal value of the random number." , return self._n:_: $# Abbreviation (for formulas, etc.):)On = @#'Making derivatives a property guser a clean syntax, # which is consistent withU0becpg a dicAary.B@o8def9(>X&""`R``a mapp from each Variable object on1funpUe depends to!@respY%toFcthat vy.a^EThisshould not be modified.Des are always floats. \`ached,G subsequRcallsnE!ifh._linear_part.expanded(>*%()T'# AttemptQ1getUcontribu\a2 @;theFQ doesraise a KeyError/~ combo.default_factory = None : F/'%##B Operators:  appliedAffineScalarFunc and/or02###D-likas onlyAsupported. 5is why methodsDCg7AusedMimplementhVthese#$no reflem:-. __nonzero__()et^aQa boo0(it*1 by#q()). Iminstance +dconvers resultEof comparisona, in si(lf we wanE to!to* (s,d cannoFa<P. Siss (such!as-()) don't hav[0ver&aningful<uncertainty unless u0, tbehavior' __l"__ypEquival*elf != 0)"#!Qmight%be relevantfCain values in a linear space which does not convert # the float 0 intonull vector (see__eq__ function:E__nonzero__ works fine if subtractingE0mgfrom aCn!of'(liR asPR0 werA"at) return self != 0. # Usesp AfScalarFunc.__ne i#. Logical operators: warning:wQresulvalue cancalwayss be differentiated.` The booleancions are6ble everywhere, bu# almost..UP(1) I rely on`assumpQ thatuser only has "small"p errors>variables, amis is used i\qcalcula]Estandard devi (performs )approxim%4s):"p(2) Howw, this irelevant for some~RV, andEhave to hold,5 cases. Thiq comes g ac9Iat lcr (e.g. dc(x,y))many usual~`For in9Tce, iis desirax == xx = n+/-e, what0size of e.FurthermoF2N ',e/e'H3 orJ&e's!3)p !Jd~#be@# with derivativs8ese! ei& 0don't exist (i.e.2er should probably_vRlUcode)!! In Python 2.7+@ mayPpossi torools.total_ora%ngN*K"if data[None, ()]",e. It efore import to*0ndlq!ise@ tooWG`aken cpof whenupce_aff_1_args(eq_onss NotImplemen=P3/ne__gt__ 2+gt2eP# __g"Eqopposit10__lS`becaus?RF yield a(, 0 <= numpy.arange(10Byields an array). __ge__ = force_aff_func_args(ge_on3s) 3/lt3+lt3elele# # Uncertainties handling: def error_components(self):5""" Individual 1 of the standard deviationeaffineFH(in absolute value), returned as a dic+ary withDVariable objects.keys. TheDv'Ps areAindependent &@that'  -Rs on.;This methoesumes Bderivatives conPed in_ take scalaras (andnot a tuple, like whatBmath.frexp() s,0 in#ce:# Calcul 6nce V = {}Qfor (6b)L.s.items()# print "TYPE", typeU)Gp:'# u due to xC0 is7qed even<fa NaN r tucase noFmultiplicM by@is performed): an exacGH obviously leadsEno uy]&thT@b on it'%if._std_dev == 0'# !!! Shouldn'\s always be floats,aB`conven7module?-[[Y] = 0/7elsjA Fabs(*\Zr @propertyGE> S! ncsC|resultsG/ed+fcurrenV3s []4s (sfvolved#p#! It wlWPpossi1to Allow@userZupdat1#st',8awhich AScalarFunc  )#objects could have a pre-calculated or, better, cached =2 #std_dev value (in fact, many intermediate AffineScalarFunc doGnot need todtheir ^: only the finalC `breturnT0user does).6$ CallableStdDev(sqrt(sum((delta**2 for  in iter(self.error_components().0s() M# Abbreviation (Lformulas, etc.):)4s =:def __repr__q)'# Not putting spaces around "+/-" helps with arrays ofh?@Vari, as each1n uncertainty is a; block of signs (otherwise,standard dgcan beCmistakenZ!anB elementZ"). != ~ # Optimizbt, sinceKMM# A zero Pis prd because ufloat_fromstr()l correctly parse back Cp("1.23"q@rpre1as f(1)"):$if4 p_str = 3()mOelse6 6'0'i'"%r+/-%s" % @.nom_,y)>/stAn emptypmat str0and () usually 8sam;3# (http://docs.python.org/2/library/3`.html#{at-specific3-mini-languagefo99('',_^G'''Formats a numbereT0 IA areEK@at(){s ded! P 2.6+ (recnqto what\%Eoperator accepts, if us earlier vers#of_%),B ex9$ t\nhAsentvP type1supported. InAPpartir[E ciup, align5wgn flagBtc. |0 us\[behaviorh`varioues (e, f, g, nonesimilar. Moreov0Eis extended:eof digitDcontrolled!is1"wa9`is inded (with ) +/- or with the short-hand notation 3.14(1), in LaTeX2#  a simple text string,...). $aBeyondeuse of op_As at0endeformat;specific,-main differencefloats is that a "u"Ejust beforeBcpresen type (f, e, g, none, etc.)@activate]"e "uncertainty control" mode (e.g.: ".6u"). ThisF"is also S`d whenq using any explicit precisionEbg", "10f+010,e" ; 3s IfDAdoes~ have a meaningful numberAsignndigits (0 1FNaN W@ies)"isutomatically%de/The nominal valueccy always QEsameX8. i@railfQzerosgeneral, evenLFWgV'`ary toS w case). However, FK Co?y'nolefined ( oy@t ha4H, so"reX matching. In thisae origyM@ UH@used (G"u" xignored6Anya (".p";@re pba) interpret%ifeJ!ol, as indN%ngDp displayed<P. Exa : .1uf will return aa6 on\mkZ (d noXonentGWIf noIis givenProundrules fromParticle Data Group areWd, if possibl(http://pdg.lbl.gov/2010/reviews/rpp-rev-rpp-i".pdf). For{e.0"f"N:mat 5ly &us*default 6Aps after decimal point, but appl hFAPDG !A commonuJif aFneedBlargB %in absolute)@standard deviPunlesis would resP !?Bbeing represented as 0e... or a NaN uncertainty as 0NaN($. Thanks to this common exponent, the quantity thatCbest describes)associated probabil7distribution has aEmZassa inBusual 1-10 rangee& ifactored (asE "(1.2+/-0.1)e-5"). unlesGformspecifica0con)1s a licit width (" 1.2e-5+/- 0.1Z(;allows numberR bepa singllumn, when printingE8over many lines). Sying a minimumhof 1 iQway of forc1-ny>to not be =Uout. The fill, align, zero andvpparamet!ofX are applied individuallyu@eachgunominalQvaluewstandard deviRor, i}`shorth2not!used, globt Usign  tis only:#e  a(sincepositive)I @casea non-LaTeX outpureturned ]eng cannc besed back with ufloat_fromstr()dis howeverDexcludes s%re"us"," thousands seLEtor,Ffor example Opr[n0add!at20endM . Multiple oO''edrWu(@ "S"5present (likR.1uS)T-U}]1.234(5)D^;ddigitszDrstraddl<decimal poijit uses a fixed-R12.3(4.5). ("P}pretty-m@modePactivd: "±" 0 ,9s` super!pt charac54etcLW )AnPwhich7rexactlySis ree*5theinteger 0 (i.e.)9no $0"%"im0ype c;@perc\a!tov> 0(itattached,Bnominal value and the standard deviation). Some details of2formatting can be customized as describedF2in 5u_num().6'''l# Conven on limits "between" digits: 0 = exactly atQ # decimal point, -1 = after(d first$ , `beforeF un{qW, etc %2is 8p(10**0)`qis tens'isbntenths]This method does> specific parsing,Ycalculat;pvarious.tdisplayed value>(mantissaPxponeFBposi laFX). ThAitself ilegated to |#1F:)match = re. (ry(?P[^{}]??)align>[<>=^]?) # #0note{ or }J8s7m-+ ]?)ozero>0width>\d*4}comma>,50:\.pprec>\d+))?oquncert_#uPrecisio_%ZaintyB#P typeomitted. Opps must go here:?>[eEfFgG%\Jn4wsupport+Do_>[LSP]*)$''',Zh_ re.VERBOSE)?# DL look correct!if4 praise V=iError(' %rI/be used with objectal=%r'P# Sub-classes handledw8% ( 1.__8__.__name__)Effective presenth: f, e, g,FNone{# like in## https://docs.python.org/3.4/library/string.html#--mini-language.$t9gpto whati wrAn inTdocum1, i$~0tru'atGD"0ame'g'": "{}". ()p "{:g}" do"EgFApresult,a314150D.0. mthus kept ais instead bemreplaced by "g"F_1 = .group('$') # Shortcut:  fmt_prec = match.group('') # Can be None 7#2, Since the '%' (percentage) format specification can changew?value todisplayed, this must first b>calculated. C 1ingVstandard deviis also anqoptimiz"::generally<: it is  only once, herenom_val = self.nominalutstd_dev%'@ons'xa that 3be given]f_num()4)t(37'))v( T" rep internTc as a  zSlshould no applied individuEto each parif pres_type ==7# Becausdoes 0.0055*100e5Y0.549`obtainwhich roundsv0.5. ThG@orig*"edlK63 same behavior isfe in Python 2.7: '{:.1%}'.y(O055)Z{'0.5%'.F!If`fferenfoP needaa solu!to Dproblem wbd*eQbefor: =smultipl1 y *= 1009PI 'f'7fs.add('%'1 Atw point,@ isgeEfFgG orG (?%).(+Non-realsVm)#CQhandl% aF waygpRs = [e3forkin [abs(Y3), ~]j!ifisinfinite(T')]on of digits_limit, .qdefines is:%ofx#30andP"A (it{ 9P whenmatter, like NaN±NaN):!Re"c*} a possible exponent,3V @in (, 'e', 'Eg', 'G'):  # Reference value for the exponent:rlargest$ ;# defines what-; will be (another conventionDcould have been chosen, like usingZ of Ernominal, irrespective 1 standard devia)):F:tryexp_ref_"= max(real)s)Bexcept VNError: # No non-NaN: NaN±NaN…@q0meaningful common@ canXobtainedIpassVz## else* ##m print "EXP_REF_VAL",l LA# Sh$precisiointerpretedJa float, orCsC`numbersignificant digits on` uncer'tyE beOtrolled?Uif ((# Default behaviw Dx (if useful, i.e. only iAsituo'1ere A and eKaBPruncanwsame place(not fmt_h9len:==2 or match.group('B0'))Explicit OThe f [ mustG6be !, G2wisA@posi?C GQtPdoes !}fa clea@. This gives usB*effc* 0conK modystd_dev4isinfinite('6)):l I+ i Oled.`Dlimi_ \0nomc @# todisplayed is calcul2. IA1not6pused, tenerally difat fromflA:F(e.g. 314.15+/-0.01 hasx|=-2, buSgwith aas (3.14\001)e+02,&which co@onds84 decimals aftep point, K'2) # Number of significant digits to use: if fmt_prec$Bnum_H_d = int(-) # Can only be non-negativebIxif not Pn)raise ValueError("The8?ber"mH  " on the uncertainty should@posi)")O,el0Y(, std_dev) = PDGKdision( T_limit =r_dgt_to9,)G V# No control)?num7 D.o## print "PRECISION NOT BASED ON UNCERTAINTY"; bA hassame meaning as for floats (it isB that defineUh)Pusual8Vault is"d (this 0ful 3.141592±NaN with an "f",mat specPtion, Bexample) #& C+main parts[finalD0for"(iPsense0mmatting !https://docs.python.org/3.4/library/string.html#w- -mini-languag(  @elif`s_type2;NonI+12>,6 hn ('f', 'F'):)o@ = -S &MF n j, eEgG0V# We first calculateS F todisplayed (Qossib 2$receER #mi mM#required - 1 (becausrza singlQAEa befor5 decimal point, which4?notincluded EtiJG)3e/Eu  vd=>c+1else: # Present ation type in None, g, G  # Effective format specificIprecision: the ruleI/of http://docs.python.org/2.7/library/string.html#--mini-languagis used: The final number of signnt digits to bcdisplayed is not necessarily obvious: trailingzeros are removed (with`gG presentBP), so__!isIC56ica%if @wereD. This quantityPrelev[0forAounding implied by. exponent test{?g/GG20interpreted like 1 (as ySfloat ad a/):-;num=nc or 1 #  is"3ortS w# exampl` deter2)ngO"## print "NUM_SIGNIF_DIGITS",^v_limit = (umr_dgt_to,(exp_ref_valuek)Jrif real6s#Aelse)_LIMIT",7#1v Common"no: should it be?@_exp5setp# accorly. If a cXNKS (useKGTrue), '= 'lUjh#&d. if s_a('f', 'F' f= FalsP.elBeBEB if{ofu2 ,1B# !!acalcul might have been already d^Dinstance when usr!.0>mat# *) was call"efore, which{ # prompted a similar calculation:  common_exp = first_digit(round(exp_ref_value, -s_limit)) Oelse: # None, g, Gs# The rules from:0https://docs.python.org/3.4/library/string.html#format-specific-mini-languageaare applied.Pp's native ]ting (whose result could be parsedcin order to determine whether a k exponent shO Ebe used) is not because Ieshared in=ionGPtween2 nominal A andstandard error (sam4Qlast ,)Haextrac)Kthis h wq entailJi,it?p, which in principle inefficient(internally,}0perYss that yield aE}8  back into?aeparat3!ts6numbers @unnecessary)SB 7L?{/ ajp floats]3 ("-4 <=1of #edH<op"), or ifR realVs3useJFalsj |BCA*if*>_b'x# t "COMMON EXP TEST VALUE"<pt "LIMIT; 0 p/+1?BWITH)",  of sign?#ansteferencea;!N 2if sBi.e. possibly corrected?a factorized exponent)Dand std_devsimilarlyFstandarddeviation). common_exp also set toc if no%B should be used. $ ifX:w# Not 10.**(-~!),RlimitCs ofzG>" =IG l =/AX N=a.1# Llast digitz*s:gbignif_=3s-pelse: : %! =  V 'w ## print "SIGNIF_LIMIT", s>/#2g FormauAin (a@with) parts (QesentP typeM 3gk )main_pres_ = 'fF'[(or 'g').isupper()]The precision=#in@mustbPadjus!Hso ato take into accountspecial roleYxdecimalFoint)if 1notOI PpertiV # p pfB locdis always included in C>#ed'r (e.g.,Ting 3456 konly 2>fCicans requires]` at leKfourAQs, li`por 3500).- Pmax()B`import0pexampleP 5 127.89123+/-B.678f7Bmat:1i uJcase`S+3 (2 necessaryoerror, as pePDG rules), buj|(PythonDCloatWting) to6! H Bis 0 (all_shown1 for the None pres_type re ents "at least one # digit p the decimal point" of Python6(https://docs.p#8.org/3.4/library/string.html#format-specification-mini-language). This  # is only applied for null uncertainties. prec = max(-signif_limit,&hG1 if:is None and not std_dev>uelse 0)## print "PREC",Z'c #2P(D"FORMAT_NUM parameters: nom_val_mantissa={},"< & common_exp5match.groupdict()' Pmain_wx opbs={}". ,,# !  ())PFinalmatting:bcreturn__num(%  ( =  =9 =# Alternate name2 __1__,use with] < 2.6 (andEt# otherversionsuser so chooses: this helps movingFcode fromJfto more recent ])@set_doc(""R|sresult as self.(Q), oroequivalent s L-(DAmat_:w&+.wT`methodmeant to be usW numbersl :4 in,, '... %s ...' %;4numf'.2e')y2"""0defmat(*args, **kw crR8[0]B4G[1:]8YSscore6WvalueX'$0' -,PunitsnrstandarAdeviRaises a VzError exceJ BIzero0W2try~v# The ._nom ueDpa float!erno integer division, y# here:return (value - self._nominal_2) /ustd_dev@except ZeroDiq[Errorb`aise V`("The standard deviation is zero:"a " undefined result") 3def __deepcopy__(v, memo)&""aHook for t> module.Z~.Ped AfScalarFunca completely fresh JPwhich*fully independent of any variable qso far.5New%s are speciaPucreated= fobject^> T !.Clinear_part)getstateopickleslot attributesk0parybclasseKeed, as5well as those=__dict__XSE (ifBJany)d# In general (case wa this 01sub ed), dataA tored in two places: possibs!W, andG0in )s. Data from both locs"1 byAgmethod0@all_fs = {}H# Supportbat do not use __B__ (jn through inheritance): inWces have a_:  . Akeys/qYrhadowedeCnames (referenca# http://stackoverflow.com/quess/15139067/ -access-in-python-first-xps-then-:A208#C7208g#a belowXonly preservesis behavior, but alsoa( e  contentF.IiVobustkA# un`ing giJAbackn@origdq even iwQains Bthat :l6try$['B'] =w$ A= QFpasspQ# All`0gat%3# Coa# one of their parents (the first parent with their own # __slots__ in MRO). This is why3 ! names arXBgathered (erepetitions removed,\general), andX'irEvalues obtained later. "2all = set()pfor clsdtype(self).mro():&@# Inz diamond inheritance pattern, som7uclassesFmay not haveA:&5_5= getattr(cls, 'sW', ()^CSlotocan be givenvarious forms (string,x# sequence, iterable)if isins([, str,|G.add0) # Single Jelsew KhupdateNR# ThewxfstoredTao:try# !! It migh0ppe atpdict__' itJ! a F|.Rais casr!s A_saved9again. Alpatively,loop couldfdone ow%# ! -C('__/,) s[&] ,)except AttributeErrorL@passQUndefO l7areturns0defAetstate__a, data5"""@Hook5pickle module.$0+(,)4e`.items.^# Contrary toizdefault)pis doesH# necessarily L 0iong(becausem G/0con(s$tsl # Nicer,Ahusers:ufloat(...), UF ) is # True)so18...)Q test`P"is tPa # numberPuncerties from9 package?": P = AfiScalarFunc #;'SoperatornuQderivs but still # meaningfulpL"enZ ofir arguments[a zero # y. Such FaNaN whderivative is # not finite. This way, if the uncertainty o associated # variable isI0, a NaN9is produced, which # indicates an error;uPis 0,n total #_can be returned as 0. # Exception catchingpused so'!to slow down regular # opera<too much: def nan_if_e\(f): '''Wrapper around f(x, y) that let f'@whenaises one ofFa few numerical p!s. n wsd_f(*args, **kw 2try 0 4W"t (ValueE, ZeroDivisionOverflowrCeloat('nan') `]get_ops_with_reflec2():61""">R@ors 16 a 3r, alongtheir derivativesE`(for fIBnds)]g#1# Ocb# We dJinclude divmod(). SNor could*Sd, bykQallowts result (a tuple) to7differentC, in= _v|pHowevertsimilarX4achievedE!byeuser by calculatseparatel#d@ and4A.4# {6: (w wrt x,5y)}XBNote8@unknwpartial5#s +lP edpexpress@themQsometClike"d_(%.__...__, 1)"0StrYdons are k,lr}%4easto code,Vexecute revzefficiently{s_list = {}'add': ("1.", %),p# 'div'2'/'Ator __future__.vd# effect. Since Iis applied tor AffineScalarFunc._nominalbers, itDoos# is|Prefor)e "usual" ma!at;F /y-x/y**2"`'floor"(0A0."), # Non exact: discontinuitlW# Ther2nd argumentsB  (..., x//yS# but , convenience1'mo"1.", "partial_derivative(float.__mod__, 1)(x, y)"), 'mul': ("y", "x1sub 1.9-1.rtruediv"/?-x/y**2")_!} # Conversion to Python functions:&ops_with_refleQ = {}for (op, Xs) in_list.items()TX[op] = [[$eval("lambda *: %s" % expr) u" ]BjO"r"+nOy, xn re<8ed("] xX# The of pow() are more complicated:6case x**y is constant one the line x = 0 andy ;5##correspondingmust be zero;Sthese:wQs. IfDactually not defined (e.g. 0**-3}n an excepDP willqraised when_nominal value is@lcul . BsD;transformedNaN if anBerror happens durtheir ca]3ionp!de"_0if y == 0Preturn 0.selif x !or y % 19y*x**(y-1Oelsee-r('nan')$ 1x{?y >}`log(x)y|JQ'pow'4powJ, !1](<r=sJoCD# UnctY# itself canX op_[%(map(nan_if_C? [)7#3'r' .c ? # Operators that have a |, along J(ir/: W = get_ ()sSome effvely modified o(Pautom tests): ._.= [] modified_o6ps_with_reflection = [] # Custom versions of some operators (insteadextending%float # __*__3to AffineScalarFunc, thVAin c{ _ops # are used): if sys._info < (3,): 9 = {} else# !!! This code is not run bytests. It would be nice to haveb@# it,1ed. def no_complex_result(func):!5''' Return a $uthat does likea, but raises aAValueError ifu z (*args, **kw  >L"%s Qexcep E.Q''' %.__name__v! =# cf isinstance(8#,  Y ('The uncertainties module;fhandleH'y 9s') ;r&p #m %onrnumbers#A forcnominal "acannot#$calculated e7 anyo<o'pow':VY.__pow__),1r2 !&__y0} Eadd_L_to_(.1"""nAdds many0(__H_, etc.)2 Kb classOP#! Derivativ`re setqzs. For one thing)#generally involve >@, asy}based onP smal0riaparameter} Italso better to@`protecr from unexpec,sinteger,'beRbadlySydivision."5# O?Ia numeric0_sid`#(xif x >= 0r1$$-1 Single-argumentF$sh|@adap F [pobjectsAsociv to1ir 3: simple_numerical_operators_derivatives = { 'abs': _simple_add+,"neg': lambda x: -1. po@ Ytrunc=%0.Y!} for (op, a) in (Siter(/nu .items())):^@attribute_name = "__%s__" % op(# float objects don't exactly have the sETs between# different versions of Python (instance, __%g__ wasDintroduced with>U2.6):'6try 0set(AffineScalarFunc, 6cwrap(gC  8F), [5]))except AlZError2# VRwherexqi H6pas*Jelsemodified.append(op)## Final definition _  tH@# Re&edq(useful?p*E,/n 3s4@ops_.p_reflec$ [B = ''sdiv__ and}R# __rw.removed,&U3if op notcustom_opsfunc_to_? =  R:9 P{E[op]@%cs thatb-0s\jf,0Con /to pure numbers are meaningless. Not at # behavior @of float(1j) is similar. for coercion_type in ('complex', 'int', 'long', 'fK1'):>Bdef raise_error(self#a TypeE#"can't convert an affine function (%s)"cD ' to %s; use x.nominal_value': # In case AvScalarFuncub-classed }!% 1.__/:__,I5)) setattr(q, '__%s__' %>,T) add_operators_to_K() # Actual addiH1of  ibutes NegativeStdDev(Excep4@'''R"3a n. standard devia1"''p5pas]Variable^"""RepresentJa of a q-like s random vU, along withcits uncertainty.yObjects are meant2rqNas that&independent from]each other (correlXhandled through thVFt)t# To sav@mory|large arrays__slots__ = ('_std_devCtag'f__init__!, #, 0, tag=NoneCThe F;0 aneEl3setW]1o *^ can be NaN. It should normally$beC0 or[wintegeri'8aAusergassociate2u. Thism is1ful&vtracingZt !of( mis describedwEmainlmodule docum1Pg+0#! pw!ag assumed by __copy__() no%Hqcopied. Ei thD~be guaranteed here,vRIbe updatedb# Only b. One reason7thedPdivis>) +3s w0t produce a<qfferent!s: inEce, 3, 0.1)/2E[has aE of 3/2 = 1, but a "shifted"g@,".1.6.55" =#(2# IR changes by dx`, then value of affine # functio+at gives its6changes by 1*dx: :! Memory cycles are created. Howeveryhgarbag|#collected, if possible. Using a weakref.WeakKeyDi7arytakes much more mp. Thusis implementawchoosesE:nd a smallerO footprint insteadQ'noC >Olarg=.0super(Variable, self).__init__(, LinearCombin ({)v: 1.})).std_dev = # Assign through a Python propertyHtag = tag@'44def_(v%):areturn#._C# Standard devis can be modified (ths a feature)01# AScalarFunc objects that depend $e TP have!ir# automaticallyrecalculP with>K new@K%irks@b.settew 1,)MqWe forc error tofloat-likSince it is considered0# a>sm,4@mustR`eitheroitive or NaN# (Note:pNaN < 0pPFalseP0erepno needGtestseparately]d. But not guarante@evenmiEhould workmost platforms.)oi@and `PisinfM#e((raise NegaStdDev("The ?UCbe n1"~p = CallU aupportlegacy method1$etPf,): # ObsoletI0dep'('sF), please use'> '' CF...'e3`follow overridden so weJ r0senei __!__"1num <;@elf.ris Nonel^?els*p"< %s =Q>" % `$, Ef__hashwU# All?BQby de"in(env7"s,[ey never compare equal; therefore, Cir  # id() are allowed to diffe%4(http://docs.python.org/reference/datamodel.html#object.__hash__): qp returnwaself) def __copy__(11"""$AHook for standard 8 module.+7 1# ! The comment below might no valid anymore now thatGVariables do5contain derivatives@.b# Thisimplicitly takes c~!ofQ {v{ it%P (in .~!):IDnew Ev pointsJ,!to;original@ R#:  www.doughellmann.com/PyMOTW/a/index! foving assumesq@arguP*not*W ied upon construction, sinceZ1 issupposedI toFy "inside" informaG@.nom.r_value,sstd_dev9tag@deepv, memo)g6 A (qoreatedY_) #; # Utilities  L#(xR; thu ue,px if ita quantity withPuncerty (i.e., an AffineScalarFunc @); o2Swise,sGx unchangTBuQy funybuseful@ransO series ofAnumbers, when only somthem generally( ry!M0sin]ce(x,RZxGFelse) AdeviCWfloat 0.  This utility function Xseful for transforming a series of numbers, when only some of them generally carry an uncertainty. DA""" Mif isinstance(x, AffineScalarFunc):(5return x.std_devMelse#0. def covari[_matrix(nums_with_u_cRc"a / that consSs betweenQgivenqsequenc, rN( objects)#The resultimplicitly depends oir order,i'"'.tZs are floats (never int5r'ed)iexact linear approximabEA, if4nominal valu``4DBand k1ir 2bletheir mean. Otherwise,VDshould be close to itsP_Pis a listsi # See PSI.411 in EOL's notesWQ = [](i1, expr1)@enumerate3, 1$vatives1 =A. # Optimiz91var2Gset(0 1)2 !! Python 2.7+: viewkeys() wYAworkKacoefs_2 V[:i1]J22=0.apNU(sum($(h[var]*ySvar._M**2)G#ia iable commdo both[@zainties = vaas1.interseO2)),_r@lway ) no termsD@s anEGeger|B0.)) /# We symmetrize7(i,_E " r;.extend([sR[j][ijrange(i+1, len(Q3))]FsR try`import2py except IRError%pass else: def correlation_matrix(nums_with_uncert): 5''' Return the E E1 ofgiven sequence of?numbers i i ainties, as a NumPy arrayNufloats.@ 0cov = numpy.6(covariance%) Dstd_devsE@sqrtD=.diagonal()3r~/B [newaxis].Tn__all__.append('?lrix') #; # ParsingN_value}*: )(part of)Z. The reason whydecimal -@is # sed (if any), instead}u9pbuilt in (/EAthat`ApresA(or not)G%a woint does0tero9 # semantics30somOt s (e.g. .1(2.) = .1+/-2, whe! #0.2), so just gettSnumerical ^p #parenthesz@ould^ be sufficient. POSITIVE_DECIMAL_UNSIGNED_OR_NON_FINITE = r'((\d*)(\.\d*)?|nan|NAN|inf|INF)' # Regexp for a u ty, "-1.234(2)e-6") #Kpy is op4Pal (iich case+mplicit)>y can alsonan or NAN: NUMBER_WITH_UNCERT_RE_STR([+-])? # Sign %sCMain(?:\(%s\).O((?:[eE]|\s*×\s*10)".* Pexponent)''' % (,4y? 4/) )PMATCH+e.compile(_"%s$" % _, re.VERBOSE).matchN:a factored Sform # (... +/- ...)e10): thisPpa looseQchingdas to accommodate # multiple Omats/GLOBAL_EXP:rDp\(?P\ >Aexp_1O$'''Sclass NotPUj (VSErroru0RaiOwhen a stru#re an exactH an uncertainty indicated between parentheses was expec!ut not found. ''' def9se_error_in_H(representation):91"""Return (value, A) from a string A a number withC uncertainty like 12.34(5), 2142 R5(3.4 3(4.2)e3, orF13.4(nan)e10. If nois is given, an taof oneEon the last digit6assumed. #0Rai]VE/1 if5cannot be}s7s/?match = NUMBER_WITH_UNCERT_RE_MATCHqx1if <T# The 'main'mnominal i 'int'eger*dI'dec'imal". Z%' is similarly broken into itsJ1intfuand decTspop(sign, 2, _ S_dec,E_int gonent) =.groups()$Felse(rP NotPUn("Unparsabler: '%s'.Q" SeeTdocum% of ufloat_ _str()K %()# Global+iffactor = 10.**z_superscript(exp6%;wNFuQ1 = ( or '')+")*FB#ifD7NonC# No]:'1 #@ = '1' ,3oths,+@are # Do we have a fullytXlicit?N"f in {'nan', 'NAN0inf]INF'} pE#sL "s:4""of^qs afterPperioRfinesqower ofE10 that musapplied to2srovidedx$inB>`Anum_!s__5= 0 6 @len(r6)-1l_Cint(Qint)/`EP# We y{M as welly8*= Rrlvalue, uncert_value) # Regexp for catching the two variable parts of -1.2×10⁻¹²: PRETTY_PRINT_MATCH = re.compile(r'(.*?)\s*×\s*10(.*)').match def to_float(_str): '''PConvePa strrepresent !a ?C to !. 8The usual valid Python.5() Eations are correctlyAcparsedNpIn addi,,"pretty-print notG " is alsoPcSVPError'raised if no can be obtain7O2try)TreturJ)vexcept o7Bpass. # 0is tried8> = (y1if -8  -.group(1))*10.**from_superscript(&12))K` ('Mantissa or exponent inH in J'Dpm %s' %q!ueFelseNl `' recognizFn cannot_!_u7_msg_pat = (!'C%se %s: seesdocumen2CPstr()" a`' list5 ac edQmats'yn`follow@func[ 1notbecause it in effect be #` by doHKx =  ) and reading # x.nominalx.std_dev: str_to_number_with_uncert([1"""IeGiven FthattBs a Q Q Qrainty, suJV3S n0forT@Whennumerical egH, an@1 onQ lastTPdigitPimpliRs!d.6a   = NUMBER_WITH_UNCERT_GLOBAL_EXP_RE  sfied, butglobal fact# calculat /# We have2ormaL!ed: (1.23 +/- 0.01)e10,G3etcW2expl" =nA'') try:' exponent = from_superscript(exp_value_str)7except VeError:YWraise (cannot_parse_ufloat_msg_pat % representation) Lfactor = 10.** 9 = match.group('simple_num_with_uncert'Felsei # No global sBial $}ha = re. (r'(.*)(?:\+/-|±)-',"if:LB(nomh", )'s(6try?1# S form 1234.45+/-1.2 ora±1.2,p.23e-10#Ee-23qM0or ;×10⁻¹²±1e23udq = (to_")*4,`d85)mP 0# FH5 e parentheses@#noGaint  $_S0_inV( @NotPU n1`return#sec def ;str, tag=None)1"""RO a new random variable (V qobject)w a string.S :s '' of theQ'12.3b0.015'jq(15)', 'u'1.2±0.1' (Unicodeu) are recognized(see more coKte list below). Inlast case, anF0of h is assigned to9Sdigit{Invalid7"s aS10Exas;E Bl3e&5e(-3.1415 0.0001)e+02F%ed# Pretty-print noq (only B:a uk+>p ± 5e3k± symbol;$(%"u.0) × 0STimes3', @?aWMixedqu, but ep# Double- s >1e-4)e+200a(1e-20\f3)e100BE0.29(531. - '31G.1e1BV3(3.46v-1.34(51(6) 3(c4.2) 7-9(1234567(1#12.345(1566(78)e-6N(0.4)e-5f69.0(7>Y169.1Pf.123(4"u.1(.4) C# NaN uncertainties:u6nan?6NANb3±nanQSurrounding spaces are ignored.%About the "shorthand" notation: 1.23(3) == ± 0.03 but .!3.00. Thus,Zpresence of a decimal point inGy signals an absolutey (insteadSC?!onylast digits)enominal value).}2""" (_, std_dev) = str_to_number_with_q(Cf"re;.strip()return ufloath, tag) def) _oJete(]*b=None) 1'''Legacy versionr ). Will eventually be remov  d -- either a ) tuple, or a;ng K< <, in a formaTrecognized by fromstr(qPif is?anc'$ K[0],1[1]kaBelseo K_ S= # The argumentPnamed4newbearing # 0as thatcloser to?4ir * use (e.g. could be # *8_or_tag, si`it can,iK_# #((3, 0.14), "pi") m)Pis hae advantagCllowpew codexkeyword#s T=3, #=VPbreak:whe0 is@upported anymore.xr X?R a random variable (V sobject)only non-e2is:-r !),& 4...yOinput parametertemporarily s' #)( -f B"IOValid string representations str_ are listed in the docum8 for ufloat_fromstr(). -nominal_value --  !ofO random variable. It is moreFmeaningful to use aAPclosescentral#orCc. Thisis propagaby mathematical operas if itGawas a pstd_devstandard devi> DThe /Y3must be convertibla positive@, or'3NaN0tag op al@ing "b# Vms don't havm!to distinctAs. Tags0useT0racdBwhatXs(and errors) enter in a given result (through61_components() method). 2"""VAtry:4# SxFcaseereturn({#, ,Q=tag)Ra# ExceC types raised by,0pecly: tuple0str2tha%P# can4ed :@() (a number with nouncertainty), Ne_(no%b@h ep (TypeE0, V "):TK if {_7NonN tag_arg ='! #pkeyworddp+(el=zS # 2onal argVsRm KfTs$ =|obsoletey?:Ainpupincorrect, PS83# Od, two-V callKd~c((Rp'eitherV F>),'=3 )A?the?P funcW,Z +6s.'c # coding=utf-8 PTests @code,ies/__init__.py. The7j5rundGNe&g framework. (c) 2010-2016 by Eric O. LEBIGOT (EOL).G ^modules import copy tweakrefK U 1isnan, isin*80sysr3rd-party s#Dnose.tool) Lo%F ;.core as _core from un"certainties.core import ufloat, AffineScalarFunc,_fromstr 7 unHC$math # The following information is useful for mak! sure that the right # vers3rof Pyth=@runn3)ptests (Iinstance withF Travis # Continuous Integrsystem): print("TestYAps", sys.O) #;*PUtiliPunit ing def numbers_close(x, y, toler=1e-6): """Returns True if agiven as are N enough. 8(_hrelative differehaaed, orcabsoluteL(,Rone oZ0y0NaNQ@: itconsideredto itself.c T# !!!!3.5+ has 1.is(): maybe[could becd here# Instead us a try and ZeroDiviError, we do a,aappear silently:dif x != 0Uy if isinf(xr!y)m!el3?nan3 3&serE# Symmetricm *2*abs(x-y)/( )+Vy)) <else: # Either x/yEzeroZG" K  1'''Ys4twoG , as randomAvariables: thispstronge!an(1whetheir nominalC1luedard deviy |applied to bo^4 vaZ"thubu betweenP6-a = x-y(-%._7, 0cB@{std_dev:) class Derivx!sDx`(ExcepF Rpass 'compare_d5!(fnumerical num_args_list=Nonenr.aChecksBn7 a s ' 0' (RPed by5Vpwrap() Pper),P@them''nsARaises a; exception i,n case of problem. These functions all take the number5arguments listed in?num_args_P. If5 is None, it automatically obtained ests are done on random y.p2"""Atry:aname =. except AttributeError8 __:"__c# print "Testing",^ &eif not :Ap# Detec@ aacorrec> i isYIalways easy (because#RvalueBallowed, etc.)@tabl-{^b'atanh': [1],1log, 2] # BothJbers te# B}!ifFi0 inE._]+ =,[]\GelseD&[] # We loop until we find reason(h C?get3by trial and e5forrange(10)h+ #! Giving integer}Pgood h`preven6CP# cers from fail^>a thougJ is?ir ;(e.g. math.ldexp(x, i), where i must be an)Jt(*(1,)*M)% tag is None3Q# ... pas posiKo, 'pi'=!==Wckeyworl+,=O# Comparison=hqsolete tuTform:The following tupl(e is stored in a variable instead of being # repeat. the calls below, so that automatic code updateEdoes notN lace ufloat((3, 0.14)) byq3, 14):UCgoalD1herto make sure~obsolete form givesA4samresult a1new,!. `representation = O^ ';7x =S&x2 8)T, assert x.nominal_value == x2 /sstd_dev) #0tag2Non k(2.4p# With pas posi al argument:'r, "pi")&]q== 'pi' keywordOtag=*Negative standard devis should bBught4nice way8!(w6Phe ri$Pexcep:)B2try R =B-0.175 uncert_core.fStdDevCBpass{ Z%# 0stu(## IncorrectC'aise any dScI warning, but63# r* Oion:*14Frhas never been allowed[O/{FelseEF("An(d") def test__fromstr(`"Input@numbers painties~a string"1# S, and numerical sQs = {"-1.23(3.4)": ( , ,y"(NWFr, error>! 2@/ BSpaces ign; xD34(5v 34F05),#11(6H1, 6Q3(4.203, 42-9(X-9, 261234567(1< , B12.345(15)": (12.345, 0.015), "-12.3456(78)e-6": (e-6, 0.0078e-65@0.29*#1031.I31, --%# The following tests that the ufloat() routine does # not consider '31' like;tuple ('3', '1'), which wouldC%make it expect two numbers (instead of 2 1-character?strings):?"31P.1e10!-3 @B169.0(7)'0169#7 q-0.1+/-c iP13e-2! e2C-W, 1e2F'-14.(15)'94, v'-100.0!h00, 1.='A1@# GlobalTVonent`'(3.14^`1)E+02P314.17 L## Pretty-printgation:# ± sign, gv (p@'ed/±+& #eindividuWeUtimes symbol, superscript (= full  × 10²UwNaN uncertainty\±nanh'nan')K0e+0u3: (2 4(a1e10.4e10, / # WvaluePnan+/G4b=W, 314# "Double-&%s"_!'(C15 +/- 1e-4)e+20!e28e199Oe-10= 19: =# Special representb'-3(0.U3, 0)}Zfor (>!, *Rs) inM.items()3Without tagUSnum =s_fromstr_dassert+_close(num.nominal_?[0];ustd_dev515.tag is None1 # a as posi*al argum0, ' variable'S,==keyword argumcent: *num = ufloat_fromstr(representation, tag='test variable')Bassert numbers_close(num.nominal_value, Os[0];ustd_dev515.tag ==  ## Obsolete forms 6) 8Llvis None# Call with a list argum ,; keyword  #;P # T8of correctness of the fixed (usually analytical) derivatives: def test_1__basic_funcs()1"""kPre-calculatedRQ opers on AffineScalarFunc.CK def check_op(op,S_argst-Makes sure that '__op__'QclasssG , which t_1numds, arej.%If 4, a)P/ op_string = "__%s__" % op" = getattr(CPnumerLncert_core.N$D(v # The __neg__ etc. methodp 0 ons[pply,Gby definiM, to objects: wfrst mapossible sV!edq;ing.) 8lambda * :  (*g(map(uOAto_a_:Vgs)))xcompare(func, numerical._derivatives, [num_args]) # Operators that take 1 value:#for op in uncert_core.modified_o@.Ucheck_op(op, 1j 2js=ks_with_reflection8 u2) # Addi%al, more complex 0s, p@use U the nose unit testing # framework. defr_copy()~"Standard  module integra"Himport gczx = ufloat(3, 0.1)&assert x == x*1y =Z._+(x(H!= y:Anot(>y)ywlist(y..keys()) y must notodependence onzOdeepza# Copy5sCexpressiont = x + 2*zB# t v0xdHin tfqThe relpship betweenv of an @ andvoriginal variables should be Rervedptn# ShallowC:`Qon which arvri_ k #(!conce_matrix([t, z]) ==95 s:However,h a Z T~# Zbroken, sidGcreated new,C"in6entO:0(5xI_"`,!`w d@TestiBmentweak refer$s:W destroying a#n#W1ity tsRies (whappen if9"y keeps aF 1 to),Gits q member(E PbecomdSvalid4del`gc.col$( p ## Cl-sPpicklPps (put *$helevel, s atDthey can=!unBep # Subcbout slots: CNewVY_dict@pass R slots defined by a tuple: class NewVariable_slots_(uncert_core.!): _) _ = ('new_attr',) # SubYQwith R defined ~ostring?str}| def test_pickling("Standard e module integration." cimport(x = ufloat(2, 0.1)2_unP3d =2r.loads(.dumps(x)1assert x != x=C # P creates copiesi## Tests Pacorrels and Af[ScalarFunc objectsqf = 2*xisinstance(f,?)+&(f,/2) R2x))E8# Cmust be preservedq) -r O== 0sx2es:Dfor X in (_dict,, @S_str)n*,r!(3.4possibly uninitialized8";S` '2# U1ing B$x. = 'New u value' q0# Mexist (From the1 of qparent ;o.nominal_ s###uner case when anibute ispnt both{#\Pin __*`__, it7first looked up f<(referenc # http://docs.python.org/2/+/datamodel.html#invoking-descriptorsN"stackoverflow.com/a/15139208/42973). As a consequDW,process eo"ct' (i.e., notD-4J9x._"in;E: key whichaalso a7q name (bshadow~Pspond, so thisM0verVusual,Dough.*['#']@Addid&al{ x.1EA '+ p[# We make sure that theH data is still there and untouched: assert x_unpickled._nominal_value == 'in slots'4p_dict__.3x._ /### Corner case that should have no impact on code but which isN not prevented by-documentation:cof constant linearB terms (the potential gotch3!ifX8c_combo>attribute_empty, __getstate__()'s result cbe false,Fgso __s5! w,be called0@orig pC !in Dcset in.;x = uncert_core.LCCombHA({})*s.loads( dumps(x)).a{} def test_int_div()p"Integer division"h# We perform all opersfloats, because derivatives canCowise be meaninglesszI(3.9, 2)//2:-x.10 # All errors are supposed tolsmall, soueA#x violates!`assump@. TQfore,followingrcorrectpstd_devp70.0qcomparison_opsxQTest dBors"import random9# Oquantities equivalentPython numbers must{b#& )R-3, 0.b%10c Qa < be33" # Thisfirst givenint.__lt8b\c=b, 0.1)R# OnefPraint_?cusual for inequality1ingq#+P work0a reasonable way (=Qce, ihgenerallyDQdesir3@funcdrs defin+`differj0ula_@interval]do "if 0 < x < 1:..."`s agai(at5"'`" (as estimate ofBdard>)Tx > 1}The limit!iscobviou7not(x >= 3j <xx1# CQaR between VarikS Af`ScalarFuncKO + 0O52 _,_ Pt object`repres!ng4same value: assert x/2 ==8 # With uncorrelated result that have the same behavior (value and Fstandard error):] assert 2*ufloat(1, 0.1) != 2!2).%# Comparaison between 2 _different_ Variable objects99are xu3u11) = 2  to other types should workm@None`RNot c9blet -x0&ble, even though{m  Gr[1, 2] # Checks of[semanticlogical operations:%y return TruA# if@ y aalways1 wh e meters vary in an# infinitesimal interv side sigma (== 0 is a specialCbcase):def test_all_k_ops(x, y1"""A Takes twoV.X%Fails if any\$! f"to follow20 prDjf9: aE$nl]?iW aspond :Js for all6 s taken byFvJs (of x and y)y Fneighborhood withi0eirertaintyKAThis stochastic: it may, excepxQally,Yqctly implemenueators.4 import random@_84(vaGR9kMGvar,;AYg its@` The Jof a zero-Y'. "((.()-0.5) * min.std_dev, 1e-5O+).nominal_r:&H# AlQ"ed2% op+["__%s__" % namn#. in('ne', 'eq!ltg Sge')]%B6tryz_func = getattr(J, op AttributeE:Python 2.3'scs don'Fi__ne__continue0# D=Vc truthu0of  asampled_results = [] (# The "main" value is an important particular case, andD`the st(#ngF@for final result6(correct_*):ssampled s.append(float_func(x.nom`_:, y*))Rcheck_num in range(50): # Many points 'e7qrandom_I(x),C C,y)3min{ = min()s7max..ax. / ifS2&= @:) ; ,Kelse?# Almost al#s must be True, G ZG$to2Inum_2 .v.count(# 5b1 exception!considered OKt (;= 1h>tryI|assert P= getattr(x, op)(y! A>ionError^print("Si3ing[s:", % _traise E("SemanticPof %s@(%s)Mnot"J"ly reproduced.9"% D, y,D_Xi # With different numbers test_all_comparison_ops(uo3, 0.1 ,"-2-5Y `0, 0),sSpecial+ i_1, 1)fN.hE0ideEJC*e .a def rlogic()"Boolean : __nonzero__, bool."NCx = Syz".1,tS-1, 2ka(x) ==Iy]Falsez:rt bool(t) =J= True # Only infinitseimal neighborhood are used def test_obsolete(): 'Tests some  creation of number with uncertainties' @x = ufloat(3, 0.1)B# ObiP funcM, protected against automatic modificw x.set_std_dev.__call__(0.2)` px)S = x.5uassert !() == 0.2E ]&basic_access_to_data2!"A@ to  from Variable and AffineScalarFunc objects."40.14701, "x var"A@.tag .nominal_value&J3.14# B0.01`# CaseyNH + 0Tatype(yF >'yy Details on the sourcesRerroraF!-1D0}q2*x + 3Q2 + a?_PB= y.components(Blen("4;1'a'"'x  .3[x]5$a$Derivative s should be availk5y.d4sw5M\ETtandard devivvs]JH = 18vXANew  contribu!pCalcula _not have a sett=# s&2trypexcept At&eE_1ApassGFelseHqraise E<Aion(#0"r%be@ fornresults")`s in ug710/score(10 + x/"IjP" is always meaningful'y> rVV orbehavioracorrelsC betweenbsFEX&x*N)# ccancel "naive" addi :##!=+n ly_zero = y - (x*2 + 1)  assert normally_zero.nominal_value == 0 ,rstd_dev& def test_no_coercion():@1"""C of Variable object to a simple float. 4DThe P should be impossible, like for co?x numbers.A} Qx = u[a(4, 1)2try$ x)4&except TypeError3Bpass#6lseqraise E7 "Conversionb)fail withb'")Swrapped_func`@args kw f1'''pWrap a -tphat takes only posial-or-keyword paramet7NOf_auto_unc(x, y3return 2*x+umath.sin(y)1# L>, but does not acWuncertaintiesQ yt isinstance%A_core.UFJ5?y, 5  UraS1, 0.cyx#D0, 2)## Automaticerical derivativ ## Fully / #f_; "(fs_close(%, Kd$y)C CalJargument` y=y, x=x)dh 3add!non-defined,<and explicit None&m30, [6]) # No>yh CRV4# E hN)plambda 2: 2 5Qscos(y)]\`"ert ufloats_close(f_auto_unc(x, y), f_wrapped) # Call with keyword arguments:#assert ufloats_`y=y, x=xd) def test_func_args_no_kw "()m1'''upWrap a * tion that takes only posieal-or-!nd>Fvar-" parameters.e *0, *# return 2*x+umath.sin(y)+3)4[1]JVLike O, but does not accept numbersruncertaintienNny(isinstance(value, P_core.UF) Afor 6P in [$] + list(9 9x =}-r(1, 0.1Ky#B0, 2"s = 'string z7C0, 3 = [s, z, s]### Automaticerical derivativ<## Fully Q/ bf |"(f$Q  3add non-defined,and explicit None& 0, [6 ]){'No>yh:4# Ewlambda 2: 20 <:ocos(y)FQ+q#3]$w:5o:| ")]X:"noE*s): ^return 2*x+umath.sin(y)+3*kwargs['z'] # Like f_auto_unc, but does not accept numbers with uncertainties:Gdef f(x, y, *f!):fqassert Qny(isinstance(value, S_core.UFloat)=AAfor 6P in [s] + list(.Fs())D 9x = ufr(1, 0.1Ny#B0, 2"s = 'string arg'z7R0, 3)~ = {'s': s, 'z': z}Argumentin signature=### Automaticerical derivatives:*p Fully / vf_wrapped"(f.s_close(l,] n #b# Callpkeyworddp y=y, x=x8zaddition{ non-defined~## and explicit None&7 NoW3posrD-or-parameter!nos#;"op6zN0, []1, {G}*JMB5 plambda : 3}) assert ufloats_close(f_auto_unc(x, y, **kwargs), f_wrapped4!) 5# Call with keyword arguments:#_assery=y, x=x8 ## Explicit derivatives:# Fully defined#  = uncert_core. (&8[lambda Y_: 2, math.cos(y)]Ho{'z:':4#3}S   ^  Automatic additional for non-G# No32by or z?f, !])`Skdef test@`_func_o_v"()f1'''pWrap a ' that takes posC-or-gf, var-E1and$ parameters. m return 2*x+usin(y)+4*3S[1]+3MS['z']hf Like g, but does not accept numbersDnPainti|omXny(isinstance(value, UFc ;6P in [Mp]+list(~) .'Fs())M,%x]r(1, 0.1Uy#B0, 2"t"R00, 4$s = 'stringuz94, 3m rg<[s, t, s]@ = {'u': s, 'z': z} # Ain signature7###znumeric /f_wrapped = un@cert_core.wrap(f) assert ufloats_close(f_auto_unc(x, y, *args, **kwargs), < f_a?ped< tolerance=1e-5$## Automatic additional derivatives for non-defined## and explicit None&:G# NoW3posr-or-keyword parameter!no2#;"op6!z:3\ = un0, [,7`lambda Q: 4])G>w], {'z':~}23#4]i P 3k}D## E7As3# Fully {)f?[! 2* * math.cos(y)o{'z:':; $> %%+k_y or r 2Zx def testw _f): """ Test uncertainty-aware functions obed through wrapping. """ #.# Fb which can automatically handle numbers withiAies:`def f_A_unc(angle, *list_var)&return umath.cos,) + sum(1W"N # We make sure that thisA is only ever &ed#7 noy (since itI{'edassert no instance_core.UFloat)-v9fany(is=3rg,;?for arg in > n j#f_) =}B(f) &0my_d = [1, 2, 3]}## Test of a&eds the original>:cshould'.exact same result}rS(0, *i) == fl11 +/- 0, sobtype must be check)ooi%(no t)M"ACallH  ufr(1, 0.1o_value,3,2 The random variables(full correla"):ws_close,0, *e 1]), :s /, |$C'Non-numer`umentsd explicit and im derivativ(x, y, z, t, urx+2*z+3*t+4*u  f, [lambda *args: 1, None, 2]) # No . pw(10, 'string ',`A0, 0D"12xYB1{_ sxl0x, ).std_dev (1+2+3+4)*x/0) Atest__E_kwargs(): '*'' Tests wrap() on functions with keyword arguments. 7Includes both?eping a@ that takes opR$alNBR and callA6pedID(Zor not).2'''# Version of f()automatitcy workbnumber I# uncertainties:`def f_E_unc(x, y, *args, **kw )+a return x + umath.sin(y) + 25s[0] + 39T['t']We also add;w in the(bhich i2ped# We make sure'fL1noted directly"a .1"y:for value[3q]+list(- :.'7s()CB`assert isinstance(-,_core.UFloat)|2$f_=WB(f) &`x = ufi(1, 0.1)y0zt"0.M3111ks_close(z, t=t),, 4` tolerLS=1e-5w# =Qanalyc derivatives ardeed used. We#Atest^Q hand ofiJ; EabeyondBof suppliJ2EULf, [None, lambda  !: tcos(y)]JI Themust be perfPAiden+:P4parameteris given as a , /s# to try`confusce codej_R2S.1[y]W.==V 7 Dqthroughn-!diaary of#N,=%]x$thdtvar-posD(mC[0])3 !'&2]_{'t':W %3}B PhouldO1exasame, becay are # obtainedL with the exact same analytic formula: assert (f_wrapped3(x, y, z, t=t).derivatives[z] 4== f_auto_unc7 )ltl#At]) m#- Making sure that user-supplied d are indeed called:rclass FunctionC`(Excep)p<1'''v Raised to signal}3a fG: ism.;GBpassdef failing_E*args, **kw r K4 = uncert_core.+(%f, i[None,]Y{'t':}6trywT3.14,ieS ? [Felse?('U should be'0J 6Z*not*<' test_access_to_std_dev(@"Uni "_pstandar0via"xfloat(1, 0.1ry = 2*x$## eA VariablWd AffineScalar objects~cAJ(x) == x./y/y/0 _other![]R0Iy* (0covVEncesC matrixb-2*x+1z = -3*x@covss__2([x]p# DiagoelementsSsimpl_9numbers_close(m`[0][0]Q0R+B1][1+4z+B2][2+9+# Non-diagonal e)lements: assert numbers_close(covs[0][1], -0.02) #; def test_power_all_cases()1'''Checks all  for the value and derivatives of x**p.<D dQpow) /op.SQ-like| operator op (op is typically built-in pow(), or math.1). F#on5adetailspecial results zP 0, 1J4NaNCDifferentI9Q9itsU"ared by dividing(x, p) plane with:P- x <2x =1> 0- p integerbnot, p,p, p ,-B(not ombinations are distinct:instance x< gAPidentq'Pmulas S+p)*zero = ufloat(0, 0.1)F26one14@posi00.3 0U!Y "1negC-DI-cnon_int_larger_than_!3. o_small2~4## #**d = op(#,ot isnan(4.[;]3/"])c# Limi[d 9onea&Q == 14oneQ wWxBx Wy Cnon-#! # -C**..l/, G C a []j0# S i/, )Z "DO, 2*o M o/  atives[zero]) assert result.derivatives[posi _smaller_than_one] == 0 ?8 = op(zero, 2\ %Gbisnan(S /22])s4## (**...: this is a quite regular case where the value and!## are all defined.py, Onot =]3  U' D~w [zV 1neg2 T 3e/ #; def test_power_special_@As():01'''sChecks $ds of x**p."*M4pow We wantsame behavior for numbers with uncertainties#m# math.pow() aMir nominal"s:w = ufloat(0.3, 0.01e!-"oRhttp://stackoverflow.com/questions/10282674/difference-between-the-built-in-pow-and-math-pow-for- s-Rython2tryd, 0),  except ZeroDivisionErrorB1assFelseqraise E?ion("A proper Sion should hav1en 5#d" /.1G'']O YVJ R@# Th{ason why it+also fail in P 3"th#Q)a complexk, whicFPdoes handle (noD+onSgs). InD"2,`aalwayst, since$2 vE know how to calculate it*p(op): '',' Checks special cases of the uncertainty power operato q (whereEop is typically=built-in:7 orMies.umath.pow). CThe values x = 0,Q1 and tNaN areA, asQnull,Bintegral3/OQof p."2'''mzero = ufloat(0, 0)!6one1p0.3, 0.01)Jassert opFqp) == 0Km$,  # poutcomena1**nannan**0 was undefined before PythonC2.6 (http://docs.p.org/library/fQhtml# p:?'nan'), ,1.Xone, .(RP# …l== 1.0gpNYtL(-p)l9 ho(-10.3 0 [(1!b p@one**…&/-3/.1 0 Z 3Ywith two numbers 7y: should gCsameP/asnties: assert op(ufloat(-1, 0), 9) == ref_op9) a1.3o9) #; def test_PDG_precision():1'''Test of the calculation`numbersignificant digits forD<uncertainty.a # The 3 casesJ/rounding rules are covered in each0Qs = {P`# Very big s) 1.7976931348623157e308: (2, %),X30.5. 9\+]:-_smalld3e-323>5r4: (1, D9.99 3z!} for (std_dev, result)_Pd.items7j_core.;LOfDreprN1'''XepresentXTrs with n8 3 is a pow 2, so that it can be exactly # w"edCx = 3.14159265358979, 0.25@?!(x'/0+/-0'fX UR# Tagging, 1, "length"\"< " = 3.0+/-1.0 >'oformatt?of pway NaNA"edF, E and G depends onn0verof Python (NAN[2.5+ at leastNaN_EFG = '%F' %`r('nan')A# !!zSmight@, ifwqis like`(could\A6 2.3 or 2.4 vs7?Inf6infUC!EpoinbdocstryAffineScalarFunc.__2__(urn, mostlyhe same order.HQLaTeXOs do not usecustomiz~GGROUP_SYMBOLSEXP_PRINT: this@way, problems lthemselvASaught4 # (Nominal value,uB): {:#,...} # Usu$al float formatting, and individual widths, etc.: (3.1415, 0.0001): {#'*^+7.2f': '*+-P*+/-*.J**',,$+0+0+00,`+/-000-', # 0 fill51>10^ 21500+/- "009WZalignBP11.3eC82e+DEDuplicated exponentI10.4H90 'Forced doubleH5}, T # Full generalization ofa+09.2u1+c 150e;0100# A0ment is not availawith the %8# operatorPython < 2.6(&?0)=010+!>9h aQNumbe`digitsuncertainty fixed(123.456789>123".1e-71_''$68(2)3P5679*3+!2uu(1.2345U0012)e+02'}# Sign handling-.(1*-Ularger thannominal value12.3, 456.78I12+/-457 4!.3"?6.8... Same thAbut %anV#.13 5%$.4#1.12O.568+S0+&(4)y (.789123, 1232_1.6g\58I4.6)&[d# Testyvarious?.s:w shouldF have a similar representas if it were directly?0red as a "7.SF#.0u6[ $78 ?/102'E': '(1.23456789+/-0.010)E+06', 'f': '1234567.1,10&F&g&G&%&(U10)%'}&.89, 4.3): {('_8+/-4GF # Case where g triggers the exponent notationu0(1.\7?4)e,WE}, (3.1415, 1a+09.2u"+0-0010$\Q.A_\!.0X)T@.)',-Approximate error indicated with "."k"'e&6KP00010&3E,=E+0,?".5}#F3*10h# PercQ:P(0.42M0055# Because '%' doesq55*100,UvalueO{y# 0.549 is obtained, which rounds to0L. ThGoriginal*1ed lKj63 same behavisfe in Python 2.7: '{:.1%}'.format(O055)Zy'0.5%'.FA'.1ukA(42.L.5)%E%SI%(! %PD1±0Cg&# Particle Data Group automatic conven, including limit cases&06780354'935'1192Ecb4a, ,O0949+09_ 3b!23 101z5# AZextension ofPuncerPty upwdecimalCXpointw0!12(L 00K,12b# A nomhas 1 <= mantissa < 10Ppreci h#`numbersignificant digits$e': '(1.0+/-0.1)se+03' 5}, # Spectroscopic notation:"(-1.23, 3.4): {M`'S': '!(*',O.2uf" 3"3E'0)F}Q(-123.456, 0.123&H6(12H%.1ln23.5(1"F$5k3J?567 85(6F" .57F f.00"# The decimal point shows that the uncertainty isR v# exacta2*V6(0.00)PLaTeXY #i(1234.567890zeL': r'\left(457 \pm z 010\right) \times 10^{3}5EE1fE',10kF&L9%r"$23!%# ... combined with#st*uLr 2B  FZ=ial cases for(0, nan) and!5matL'# strings (extension S, L, U,..., global width, etc.).? Python 3.2i 3.3 give 1.4e-12*1e+12 =01Einstead of(X!1.problem doew appearE1.2, so 1.2FusedR>, 0`12.2gP@r' \×10⁻¹²±a $# Pure "." mats are not accepted by% operatorfZ#Bonly %-compatiblePL,%<G;2.6!130(0) 410PU ',\0\right) \times 10^{-12}', # No factored exponent, LaTeX*'1L': r'-1.2 \timUk \pm 0[&'S1<(0)4 .P_(0)×10⁻¹²'5}, # Python 3.2 and 3.3 give 1.4e-12*1e+12 =01Einstead of(F forX1. The problem does not appearEwith 1.2, so is used.$(6, float('nan')): {$'.2uG': '1+/-%s)E-12' % NaN_EFG, # u ign,1matp K@15GSK }(J 0\mathrm{nan}" F # Pretty-print priority, but=bINaN:6!'P}\(| '^Q\left.=o\right |# UppercaseL 0.1Er?(r's?%s}r q)&1051+/-1 6 -5@nan)35@(3.10, 0.01e-10# Character (Unicode) strings'U00±RA⁰'PDG rules: 2 digits 'PXrHYhas higherd U# Truncated non-zero uncertainty0.1es`+/-0.0E 1.1elE3.1($w Some special ]</(1 gO1+/-G(%s+ '%%R(100.K")%%:@typeilike fG# Should be the same as '+05'{si K, inF;2.7x1+05@+000.000# 5*minimal* width, 6default number ox0 afK0decJn point@+AC ATherBa difference between '{}'.format(1.)` @I'{:g$p, whichpfully obvious in Cdocumentation?h indicates that a None format type # is like g. The reason?the emptyBstring isGactually interpreted as str(), and Q does notEhave to be r ('{}'.(1.2345678901 )GmO'{:g6  are different).F'': '1.0+/-nan',`# This% ugly, but consistent with0f'{:+05pfloat('[!))|) (whicBcs fromi(1)!):j@'+05"+0 00c#5}, (9.9, 0.1): {P'.1ueF#0+/-$Ke+00P'.0fS'u10(0.)'D}.Bf Fe precision has an effect on }xponent,5forg1 # Ks&.29"0) # Same e[for 9.99 alon#01.0@0.01L/1'K# 0 uncertainty: nominal valursplayeda?, 0( 1&* ',No factored! rQ'.2uf2.238 m.23(0)626g\/45^ {# Alignm @fillcharacters (supporin Python 2.6+P(3.1415e10k!<1j3$0@.0  1<20 90(0)1 ,P# Tryqto trip)P parsm0 a  U!# PEan a.[/2'=>)==I+/-=0s(.8 }E}Pu ign{M11.21 $# DefaultP9= 6$'eL': r'\leftE68 \pm 0\right) \times 10^{3}/'E@,f@'0| gF'%' .789000 \pm 0\right) \%' 5}, (1e5, 0): {''g': '10I+/-0>!O(1e6=+# A default precision of 6 is used because the uncertainty# cannot be50forXpining a c(it doesGDhave a magnitude):% (1_)e+06?+10. p# Roundy,of that "changes"number ofg# significant digits(1, 0.994A.3uf'%',Y6'.2%$ #1# +/-1' # Discontinuity inh}s(12.3, 2.3A2ufS@2.3(#lecimal point olg1g1(2)cONo df!@MakeZe^first problematic#100.0 ',WSimple float formatting9t5 .2e-34, 5e-67z6B@(1.2~3000)7 213.0# 1&b+/- 076G6HE-346 6.6GL': r'\leftD \pml\times 10^{-34}(H('nan'), 10hNaN *nominal value*60nanB00.0Like '{}'.j(100.)9[: 8/:g: 0.1ev(= .0a2BSimilar to 1±nanu1.1E; %s.0)E+02' % NaN_EFG9.1uki T#1032   0e_/| r e8rx /e8w;89 {= '.1e': '(nan+/-1.0)e+08', A'.1E&#%s%E% % NaN_EFG/!ue0VTA10.1&i,a 1.0 # 'nan would be strange}}p(float(5'), 123456789): {NNaN *nominal value*G'<@.0',<Similar to '{}'.format(()KgLW7 N/:gP-RN v ?2)E/(.1ueL': r'\left(\mathrm{nan} \pm 1\right) \times 10^{8}D20x r+.2m*Double*C   >@k8k Vk 8'b would be strange23456789"= ( .'7u O * j 2O '2.jE-F'.1+/-\F pFiG: +/ !4JV/-inf',  'EL': r'-\infty \pm #' #E }, .# The Particle Data Group convention trumps the "at least oneFpdigit p'decimal point" for Python floats, buC'lyD with a non-zero uncertainty:'(724.2, 26.4): {'': '724+/-26??, 0:i.0+/-0;b# More NaN and infinity, in pBQular QLaTeX'wvariousF opVs('-inf'),$!('S+u(inf)',Z"'L(%C# LP("±0 qAfollowing is:rsistent i's own#matting, which depends wphe vers#ofA6B7"""){format(..., "020") giveE;'-0|CA 2.7 :/.0:6. However, F22.6dFbett+z(Q when @at()4 Fyg" instead, so this86 would be i Grinciple,similarlyF "%020g" % ... Thus7#'u() breakBofficial rule accord9+to noumat type_pequival_pto "g"," =RWs. IfS behavior was neededlternalB;1c1r!ce[!"g E1nonJn; h does not@`actualyu0tre  he%en6sama|@solup cannotLusedTas it;c other'^su code. Itthus best to mimicPnativ+ofDGVy(even ifIP lookKgoodE#ini 2.6).@'020C_(H(T, '015')+'{9}."(-3O'nan2nanPF\mathrm{nan} 'L': '\mathrm{nan} \pm \infty', K'LP'-#±*)5}, # Leading zeroes in the shorthand notation:4(-2, 3): {"020S": "-02.0(3.0)"+}}# ',' format opi introducedPython 2.7Dif sys.version_info >= (2, 7):]tests.update((1234.56789, 0.012B`',.1ufP!1,1@7+/-/'#Sb56.789123, qifP23,45ep5', # Particle Data Group conven, G',.4M0+/-RF"})@ # True if we can detect tha2e Jinterpreter is runnKthis code42try j:_QAed =3sub[0] == 'bexcept AttributeErrorS RFalsefor (values, represen s)_(hitems(@4 = ufloat(*s!ZP_spec_AsultV j.`C# print "FORMATTING {} WITH '{}'".`(O#),.tP7 2.5.2 dnot always NaN as nan or NANGC|@way:w example, '%.2g' % l'nan')Es '\ufffd'. The k(skipped,,#as,Ascontinu7b# Callworks with < 2.6 tooOg1 = ufassertx reY., #Y qPis us`1ter do F# support some characters like ±, superscripts,p'Incorr) !%r> %r of %r:;'expected. !% ] ,i An emptyq0stri@callLstr((http://docs.p.org/2/library/Mb.html# j ifH representation == str(value), ( 'Empty format should give the sam aing asN?):'H %s obtained instead of %s1% (representation,`9)) f`# Parsback into a number with uncer~ty (unless FLaTeX or comma no{ is used):0if (not set(!_spec).intersec('L,*%') # * = fill*M|# "0nan"Pand ''J in .lower()9R?infR?infRSpecific case=[*):5_= ufloat_from =# The originaltnew onebe consistent0.each other?try1nom can be rounded to 0 when}A#is larger (because p digits oE stxshow 0.00... !).cPrelatPerrorinfinite,Jtso this}.1an E`91if ?._15cassertrs_close BBw, 2.4e-1I@# If` Pzero, TAdchangeG std_dev=/ 3except A}@ionEA# !!H`follow0str>t requires)Gwork (to`raise TOion) s (which have0on-standard classo ?.$'Ov  pparsed ? %rH% (Apthrough)O %r)F ' are not close enough' % (value, (_back, representation, format_spec)) def test_unicode_ 1():h'''Test of the %E@tingnumbers with uncertainties''' Hx = ufloat(3.14159265358979, 0.25)(assert isinstance('Résultat = %s' % x.''), str)d<P=/ #;q # TheXs below require NumPy, which is an opal package: tryimport numpy except IRError%pass else:Dqarrays_9(m1, m2, precision=1e-4M1"""B Returns True iff m1 and m2 are almost equalere elementsDcan be either s or AffineScalarFunc objects.Two independent3bdeemed5 if@bothir nominalyEp (up to5FVgiven5)R2 -- o!k$ `ed thr5 tomCies.J.e%).: 2# !.B.all)grsimilarpis funcv, but does notGswork on that cona, becauseJ;5f()z-for (elmt1, 2) in zip(m1.flat )* # For a simpler comparis:pconvertogb11_core.to_a!_s482825 ifqN#1._,: 626 >r f Falsestd_dev0 B8_@%"C,a"."K*11.# G`differFtypeYx != [x, x]d#}s can be comp ared, through element-wise +# comparisons. Numbers with uncertainties should yield thDsame kind of results as pure floats (i.e., acPy array,wetc.). pWe testl operators both for" Fpackage *and**cNumPy :r`Equali , :Hassert len(x == numpy.arange(10))/100 +*x0?x !`+?!= ` ray([x, ]3 0 5*ll0 @)}5Iney w >*< >+<# More detailedQ atlws thaHs armeaningful (x >= 0, but not x <= 1)=3n3[True, Fals]P1def_correlated_values(l5"""C) variables.TGthe input (full) co:nce matrix@jM3u =Y1e.u (1, 0.1)';cov)a_aF([u]1# "1" is used insteau.nominali becau "might return a@. T0deae toyc 5newA u2 to b@0fin?an integer !# =u2, @[1],  expr = 2*u2 # Calculation2be possible, like#% Cs between out# an Wqxy23z = -3*x+y@covs2ncert_core.cov ariance_matrix([x, y, z])  # Test of the diagonal cov= elements:4assert arrays_close(Xanumpy. ([v.std_dev**2 for v in (O)]),<dcovs).)()"Inversion": creation#5newk!# 7ble(x_new, yz) = uncert_core.correlated_values[x.nominal<, yz] tags = ['x', 'y*z'AEvenainties should be ctly reconstructed    6C Q q... and_s too uB # $(])DH]), A[-3*k+j]_#0s well as func1al Vions:0ufloat(1, 0.05)8v012sum$F+2*vS6# CgcD3covp; 9 leu, v, l CiB canw from a!# x, if NumPy is available_q(u2, v22,x[* 7W)used insteadVumber#wbecauseit comparesW u u2s  AvAvA D?sumK0k _@-(u2 2)Spot checks<clmxa O3ion!(8pn][0,0], 1) 0 assert numbers_close(corr_matrix[1,2], 2*v.std_dev/sum_valueC) # Test ofperical robustness despite wildly different^p ordersBmagnitude (see#%https://github.com/lebigot/uncertainties/issues/95):?Pcov =py.diag([1e-70, H10])/[] = cov[1, 0 00.97 ()0, 2!i-3e-34 22, # variables = `_core.belateds([0]*3, Since the are very small, we need to compEthem# in a stricter way, that hand^@caseAa 0 (ncAin ``w{\` 1e66*g@0,0]566*N [0].s**2, tolerance=1e-5e>1,1e1e#sa bit special, sBion d cannot be calcu naively, sotlthere is noDtfic problemPthis :00,  #noU2, 3]nI Tfor (I%, ),j)Ezip(x;3s4s]gonal()4 A9V'.nWmE8 GUnce) s @TarrayaIcov,anumpy.1((hH3s)))@def 3ZrU0ion@(-5'''seAinpu2ed 3W. through54ir . (insteadU&thL$co%). xr`float(&.1yf2, 0.3z = -3*x+y0cov5Hrix([x, y, z]Y<Rsqrt( ^)|hj/S [Onewaxis].T?# We make sure that the correlation matrix is indeed diagonal: assert (7T_mat- .T).max() <= 1e-154# We make sure that there arekpones onw.M()-1y ztry to recoveraed variables through!A+ 0(no.1 coF ncC5): Cnominal_values = [v. for v in (x, y, z)]>sstd_dev82 x2, y2, z2 = uncert_core.#ede_norm(klist(zip(3s, zAs)),3)# arrays_close()Dused instead of number#ubecause# it comparesPainti'ooS`# TestTindividual  anumpy.`([x]),E2])). AyAyAzAzA# PartialwOtest0f-(-3*x2+y2)q]pthe fulz { KR/1cov8," v5Vrix([ ]))) ''' Mathematical operat generaliz(ny Afromstandardh module soy also workb with . Examplesbumath import sin3# ManipuvU jxjufloat(3, 0.1Aprin`q(x) # s 41120008...+/-0.098999...BThe functionsregular Python ysc/(3s@ ThO9s aBA. Iping all ;t:m0inte global namespace is possible.nencouraged when usishell as a calcSor.  1 .@0*s tan(), etco8 NwE.tan9  M handled by this module are objects from the uncertainties mo*, either &Variable o AffineScalarFunc class. (c) 2009-2016 by Eric O. LEBIGOT (EOL) . Please send feature requests, bug reports, or feedback to this addresTPsoftwQis re[d under a dual license. (1) The BSD (2) Any o-, as longit is obI"ed?8original author.''' | .umath_core import *__all__ # Focorrect help(J) #!! Whenevdocumentation belowupdated, setup.py should be # checkor consistency. aCalculQ s with full error propag for quantiX+ k . Derivatives can also be cded. Web user guide: https://pythonhosted5/]/. Examppf possi[ ion: (0.2 +/- 0.01)**2 = 4`04. Cibetween expressionsUly taken into account (for instance,5xk@2+/-|, 2*x-x-xexactly zeroc@is y D0y =.5). Ts: D "  *_float#)*wsin(), etc.n# Mathematical operPs: u^c 0,V 1)FC0.20 ,_Wstr("""7Ox rev<?(1)8 # Implicit@y ofA1 onlast digit ") print xC # Square:ss "0.04504"/R3PB,b399..."0 "se`.std_s7Y(0.17>-3.0": devi-3 sigmasD# Access *Pe nom value, and3ys+ = 7 # ).y_y7$.;dev(W04...&.dW1[x]4vartial p: 0.4 (Km)Cu = 1s5, "u v dwTag v+W1, "v+c sumP= u+vtu{1Standard3be 6fly\- u - v # Prints "0+/-0" (exact result) # List of all sources error: print sum_value3Ps "11.00+/-0.14" for (var, >F) in9. _components().iteritems()k$ o"%s: %f" %QE.tagU # Individualj VCovariance matricesaAcov_x = uncertainties.c2"v([u, v,%])Hb # 3x3fx}rrelated bles can be construcvfrom a zFA, ifNumPy is availableq(u2, v2/2)~s([1, 10, 11], d u2 V7andMy> u: correctly recovered (10L ])y ==7` - Thin function provided by this moduleOufloat, which creates numbers with`ies (VNble objects).  be used as if they were regular Python l&. pattribuQamethod iare definedcthe documenta0of 9`class.(Valid oper*&s  include basic mathematicalips (addix, etc.). MoUfstandardhC(sin<E(applied by usingiir generaliz u u{:($import sinBsin(?_7astr("1A01")C0.84)0591 .I) also work@s, e`ly lik"th.Q Log|d(>, ==>T0sup`ed. B [arrays or& <performed@2*numpy.N"([(1, 0.01), 2@1)])r _mplex 5o througha dedicf b sub-m(see its&aCalcul/ps that BpCnon-code (Fortran, C, dhandleA Jpinsteadgpwrap() 1perf #&0d_f`a versof f that can tBake arguments with # uncertainties, even if f only takes floats: wrapped_f = :.(f) If some derivatives of the $!ped function f are known (analytically, or numer ),Ay can be gi!toRp()--see!A doca_C for". - Utilitys~also provided:Fcovariance matrix between random DblescalculatedZ B_B(), or used as input `defini*RcorreL`quanti& (_values() I!--C"edio NumPy module is available)qMathemar expressionpvolving2ber. *` gener return AffineScalarFunc objects, which hint as a  Zy. Their most/ ful attributes and method described in b `. Not0@at V4ble 7"P. UFSn aliasi,Wconvenience: testcwhether a carri handled by this`shouldBdoneNpinsinst2(my-,?ly,,[is package, probabN2dis< se"re reduced to two num[: a nominal(anUus, both|, ()=R`resultNmAoper?s (P) conO ses (respecqly in tjwstd_devyH Thea}7Sy^tsimply qUdard deviYpunderlyg !.  Smanip~  assumed to have a(y l$ly`ed aroundi3ir Gmuan intervalPabout-P size 2Bis sCcoveRBpraccases. A good choicU  Athus`median?its#E locxhighest7,the averageUWhen Qensem#ofN"s,of which contain uncer 'ties, it can be useful to access the nominal value and@@y of all numbers in a uniform manner: x = ufloat_fromstr("3+/-0.1") print k_k(x) # Prints 3 %zstd_dev50.1! F3F:d works on sDe >30:  8 - Probability distributions (random variablesF calcula# results) are Qed as;+/- standard deviA but this does not imply any propertyp(beyond@ facGa iWrmally inside3p regionhhigh pensity), or thV "(CBthe  is symmetrical (is rarely `Actly case). - Linear approximsZ@funckrs (arou \s) are used fe!ofm~`Pmathepcal expressBwithpackage. ThZ/ed" s thus meaning as long ainvolved have precise l.Rexpan!inBwher Wtheiri}largest. IttMfore importanf9at seG. MT2ly,F%s N@term' `should|Qmuch 0mais er-order u@s ov 'he signific:`. For=tance, sin(0+01) yields a m` sinceuis quitO. However, cosg7 an&e(0 (becaus`cosineaVwell qed by aU ~0), which mightepenough mEbapplicComparis`2per (>, ==, etc.)}k N q a prag semantic3is :H7ies!!d ePython7=, most of mPtime R# a@ ideaj$ on`Dat w ob1ed : X onlyN bjects defined in this moduhle represent probability distributions and not pure numbers, comparison operator are interpreted in a specific way. Thvsult of a H ion ("==", ">", etc.) is defined so as to be esially consistpwith thj`quirem that uncertainties be small:-_valuePis Tr"`nly if4! oSyield" for all infinitesimal variaTof its random  bles, except, possibly, LnK"lycases. Example: "x = 3.14; y "E0sucat x == y but10pufloat(7, 0.01) ?1 is Q, since x8"y `depend  almost never give]a same `. How,x still holdWrboolean2 ((x), "if x...").a:%0y x6x != 0. - b.ies packageWPython 2.3Sabove:i-0cons tests. XPy canrun either manuor automaticnose unitLing framework (c\). (c) 2009-2016 by Eric O. LEBIGOT (EOL) . Please send feature requests, bugOorts, or feedback to this addresPIupport fuKqdevelopby donat0$10P0morrough PayPal!Ois softwiAs re] d under a dual license. (1)sE BSD (2) Any o{-, as long it obqed fromoriginalhor.'''  .c!im*__all__ # F0 correct help(k) # NumIersion: __v _info__ = (3, 1, 2)'.'.join(map(str, =)) __authorK'& ' #!/usr/bin/env p Fixes code likse 2to3 ;!uta, but ffixerso`local @s di. orV/13.@ # C~inspired/J3. sys if sys.l < (2, 6): cexit("rprogram`2.6+."]$ i0libp.main oP)('.lib1to2.v')) # ! Add a hea to the documentlation, that starts with something # like "uncertainties.UFloat-compatible version of...", for all functions. """ Implement{ of umath.py,{internals.0- # This module exists so as to define __all__, which in turn3s #f are visto the user: through from # import * and Python shell  leQ.. # Many analytical derivatives depend on this # Standard#s j %syitertool< Lo`m#" @core4_  `(to_af`_scalar, ASFunc,  LinearCombinO) #;>qWe wrapEY<they keep track of` by reJ]ing a object.FSome4zcannot be adaptedoay!aybo work tvs (eithertheir result # |spir argup0s):K(1) # a@a type whose valueq # vari9s (:&) represen-by7 # (e.g., d.frexps a tuple). Th0cep[p raised+@hen OpBthem31() 7re obviou an"n@ed wK4G(in fact[6ped # attempts operX[0sup+ed, suchacalcul- a # sub|)on2don't take continu" (Pcan #|`ed dur5different#):4sumactorial...cCcan !beb-/ispecial way)- excludO5rom6`by add name to # no_std_FMathVhave X SPface:y30r mf5,Jc: many Cs_to _`s = [] ^0qui| fic treatf@must0refObe ## 0. ~8 'modf', '^ ldexp', 'fsum', 'factDorial'] # Functions with numerical derivatives: # # !! Python2.7+: {..., ...} num_/ _funcs = set(['fmod', 'gamma l *])zare by defini locally constant (on real #bers): their value does not depend on uncertainty (because # thisis supposed to leaa good linear approximaQ # ofd. itregion). The type5%ir output # for floats is preserved, as users shouldc-@abou!vi3s #| .isQ0duethe natur%e '(0'1ituvrsimilarJat of # comparisU(==, >, etc.).H, 2IK_cstK@ceilBPfloor Risinf 0nan ltrunc'\qthat do<`belong+many_scalars_to t1, b:have a versiSat handle@1iess=@s arj2als} inpy (see unumpy/core.py). non_std_wrappedI = [ acopies|Prelev! attributes from generalizedcmath module: # Tis a copy&paste jobN1Cools6, changing8default arugmentassigned def s(eper, d9=('__doc__',)!rupdated 1ict!!):VA"""U! au6perook likeE~"!. EEr --3be {&d&original/!"@tuplqAming{(directly>d\6s C]?dCicorrespond!GdB-Aion.1"""9 0set  9, g]ttr))QP 9!r,P").((WC, {}[r# ReturBr so;@can /a5decorator via partial(rHDO #@ # Wp1of Y!s:D@ixedhPmulas Vpsome functions fr\om the math # module (some functions might not be present in all version of # Python). Singular points areADtaken into account. The user # should never give "large" uncertainties: problems c1only appeaFif this assumpQ doeshold. # F0men( ed_fixed_derivatives have+7ir  # calculated numericallybBthatCsi (possibRfinity) benefit # from analytYn(instead oe default0ionXOcaus` gener change very fast. # Even slowly varying(e.g., abs()) yield mor+ cise # results when differp6bly, beQloss \`precisk&in udef log_1arg(x): # """ D9log(x) (1-argu` form)6return 1/x eder0(*args): d c^.h`) withpect to its first ~!. JAWork0ther 1 or 2$sP!n..xqif len(R == 11[0]8Oelse#/41]) # 2)#`followgwabout asP:1# A 'try' isdwb most common case it,I!nor## exceis raisedC#try  !Anumber checkca TypeErrorT!1/%/0]6Div_copysign(x,yIif x >= 0i2Q1, y)-.{f#bu1c1Qppow_0(x@if y" 0!ely@!= 0_y % 12!y*1powb/-1float('nan')1@l=~and y >v0Ax) *K.) erf_coef = 2Qsqrt(5!piROptimiza~erf() 1= {0# IRphabeorder, her'acos': [lambda x: -1.sqrt(1-x**2)], 'acosh': [lambda x: 1/math.sqrt(x**2-1.?sin- 1-/ -[*1+.-ta[($2 y,!x/+y**2), # Correct for x == 0@(-yA]B ]'atan(qcopysigt_deriv_vtx, y: 07cosBx: -Ein(xbh>kdegreeB&(:erfj(Bexp(*erf_coef]Jerfc23 xp2ZJOxpm11fab>4Phypot4 8x(K)j /y/_1log] og|0F D2logp/TyQlog10Q_*)10+&f"0powKiv_pow_0, 1aradianBM}4cosC"si[Y20.5O+N ta4**2lT]0(x)+} # Many built-in functions in the c: module are wrapped with a # version which is uncertainty aware: this_moFb= sys. s[__name__] def__locally_cst_(!):1'''Return aq that rs0samguments as,Q, butCafter converting AffineScalarFunc objto its nominal value. H2Thi[9seful forp\ !atKDconstant:Cies should have no roleRresul`(since?y^supposed to keep linear and hencePhere,!).r2ped*args, **kw _float = list(map(c_core.H_H , 1!))o@# !! In Python 2.7+, diary comprehenz`: {argFU:...}E?(fA(arg~,(9(arg_name, value) in iter(kwargs.items())) return func(*$_float, **41-wrapped_5 # for (name, attrvvars(math)u : ('2dir!: 4if fixed_derivatives: # Priority toPtionsJ /PC= = ([q].'el2num~!s:"Pb# Funcyhwhose bare calculated numerically byDthis module fall here (isinf, fmod,...)we@= []fMeans:ezion requiredu0not0!loL_cstcontinueb' ' 5H by (__doc__, e, etc.)` = get, ku0 = _/(kAelse( with analyt7 or/Ti# Errors during thX!of< convertp)to a NaN result: it is assumed that a 2ema<1ionI*0canb ed indicates a non-definedG(.in must be written7way = uncert_core.(t, list(map(-nan_if_excepR,sI # !! The same effect couldachievedglobals()[...] = ...Es!_my,V s(,])many_scalars_to  s.!ndO) #;Q # Special cas.Ssome `s from no_std_Hing:g! #kp.factorTA#co#anainty-aware', becauseAdoesOahandleinteger arguments)*! #,make senseo1givK%an2aeP # (wY#as5relevant Qgamma()).qsum takiesingle~, which differenti. # However, eachr inside^1S! # variable. We ?0a sfic way: # Only fo>r Python 2.6+: # For drop-in compatibility with the math module: factorial =$.f non_std_wrapped_funcs. End('(0') y0We )Esum original:`Rsum optimization purposesM@The o*below exists so that temporary variables do not # pollute namespace: defsum(): """Return an uncertainty-aware vers&of, which mustA`be con8yed in _ .$m !# is flattened,Border to us:q#()1r: : _fP= lambda *args: ()3# =a_core.eZ%^, itertools.repeat(n#1)^rPHs$arg_list:|(%),tx ))! Documented? q 0sum#_6Somszseither multiple arg s (modf, frexp) # or take sMnon-float1@`should Bverted to # numbers ).!E1hav(R same0 asJ C # d:,a hestrings consistentthem. @.set_doc(e.  ._1__)x+(xqVU2odfgworks for, and also*+eregula3kRcode Tispired by). It isa# simpler becaeonly 1 is given'enq# delegho!volved (a__mul__, etc.4affPto_affine_scalar(x) # Uniform treatt of allI(frac_partbt )jA.nomSvalue5if q_linearC:!IfaBstanderivative0al 6m@y 1:Am'odf(x)[0]5L !x=!(A6S5HFunc )$FelseX0uncA wasbcalled-Rthe r7d7 ofG0, t$Oway ` might0(thW x coerca difference[int->floatgSance]`u -fr#(x1"""pVersionM!Qworks.y, and alsYregular 3.`h e code belowPinspi/by3. It is?tsimpler/u only 1PRgiven@Qdelegg5s involved (a__mul__, etc.)xP(mantissa, exponent) =?   7x0# W(~x(m, e), x`*2**e,Pm = x-&Ezfore dm/d?Q2**-eY@e in0intm0doet vary whenchangestHs\O:]))P;is suppoJto b#tinuous (errorssmall):  exponent) else: (# This function was not called with an AffineScalarFunc@argument: there iA need to return numbersPuncertainties+math.frexp(x) non_std_wrapped_ s. And(''_') #; # Exporteds: __all__ = many_sCs_to ? +  """ Tests of. code in !.u These t1can be run throughA#No"(ing framework. (c) 2010-2016 by Eric O. LEBIGOT (EOL). # Standard modules im5 sy +TLocal(j: from <dufloatJ score as9_) / y.m(_dABUnitQ def _fixed_derivatives_"()qComparisoUtweenb B@ and60erim!. }cMis useful forJ`that anPnalytP.C 22nam. # print "Check%s..." % Ta( = getattr(,()^# Num4Dh nominal value() resultsv#@used=the underlyNny( =.D(plambda *args:( ).ez(,) # %s V"##Cf():s a tupl4frac_part_modf(x.#1[0]_@?int?"1]9l ,)I x:d  / O(x))) ##  # frexp(): returns a tuple: def mantissa_+"x)4 umath_core.$5[0]AexponentA11] Btest_uncertainties.compare_derivatives(, ,CNumericalDBFlambda x:!))T / Pp(x))) #ound_expression(1"""Test equality between different formulas..6 x = ufloat(3, 0.1)# Prone to n_ errors (but not much more than GshassertMtan(x) == si/twcos(x) _examplespecific("s"0.14"01`result# In order @prevL4big s as a wrong, constant valueEfor all analytG and, which would makE Xfixed+_funcs() succeed despite incorrectcalculations("%.6f +/- R" % (.nominal_#,  stvFd== "0.001593L0.010000"WRegular 1 shstill work011f'3N"0.14112000806j8monte_carlo_DNaris;VFull 0a M; -C;.RBoth the scovariances are^$ed) dib@ pered in this module] F si 2tryG`importr!py7 q.randomexcept I4E Iwarnings0L. !("$because NumPy isCavailable"Ji# Works on.arrays of Vbble objects (whereas`ZQ# doeuQsin_uO# =dvectorize(q, otypes=[s]Eq q (with q,multiple "@blesQbinedM#a non-linear way(x, y): c """ 'Function that takes two NumPy arrays of the same size.?K# The uncertainty due to x is about equalP+Q#5%y: return 10 * x**2 - x * sin_u_Jq(y**3) 8x = ufloat(0.2, 0.01)y!10f _result_this_module = R(x, yKnominal_value/M.8# Covariances "f*f",x"y"c% panumpy.(f_core.2_matrix(,#))Odef monte_carlo_calc(n_samples)TCalculatecrU) on <VDR and snqmedian, 6s between X/))R0a M -C@ sim6ionx2 = crandom.normal(x, x.std_dev,  V+yw ywyw*# !! astype() fix for nV1.8.0+!(G%, #).ii0covr_cov([B]uGM" (0#, o:('&>) =!10#) mparisonRboth f#s:)>  must be close.pWe relyLBfactCs very ra11has# null element1!!!test could}done directly withT's coX tools, no? See assert_all,]_almost_S_nulpE*or(max_ulp. Thisrelevantall vectorizedCaccurreR ofQbers_.v5py.A(Uvies.num>)Eo1!00.05).all(), U"J9 Pdo nodincideQ"<ation and th e direct calculation:\n"  "* Monte-Carlo:\n%s\n* D6&%s8 % (covariances_samples, this_module)q!) # The nominal values must be close:(assert test_uncertainties.numbers_-(-S_S_,#scale of the comparison depends onstandard>Bdevii"can differ by a frac7 ofDu[ Q"math.sqrtf[2, 2]sc/ abs() * 0.5), B" (%f) does not coincide with that of"VC sim|J, for a p6%f.L+% $ J ? 34r) defy;"()Q"Opersec "x = ufloat(-1.5, 0.1exponent^b entiated, when nga # following (4partial derivativ@resp to< vEisdefinedzy(x**2).> == 2.25# Regular oare chosen tounchanged@^@isinAce(ufcore.sin(3), 9/factorial()."damaged"QJs, so asto help make it a drop-in replacem@ (evShoughB@work >abecaus{is restricted)integers, as&3.v $!4)4fsum is "ta fixed !# Ibles|sum([x, x]0$-31Funs;glocally cotPults H0ed:yqshould <Csame4:Rtheir? equivalentn/7in _cst_funcs:T2try< ! = getattr , [Gexcept AttributeErrorLcontinue # Not iY v eitherSfunc(x) == func(x.nominal_value) )# The type should be left untouched. For example, isnan(B9always give a boolean:jaassertk0(fuX)) == !) =same exceptionsgenerated when numbers with uncertaintiesNare used:_Pof thf0pecPo is first determined, becauseWit varies between vers of Python (OverflowError inDp2.6+, V ! 2.5,...)Q2try math.log(0$ E- as err_(: # "as", for~ xO#3 does not mak~Qlocal`ables:8By ar FarestriI to!iFCf blocku_args =.ion_clas(_"__ u__core$ T*oufloat, EFelseVraiseF('%s2 ex6' %.__name__ b(0, 0). S!01 def test_hypot( 1'''#Special cases re derivatives canbe calcul2BBx = 312y27# DZOthat_ simply return NaN,!no#q being d, normall`resultBx, y  .D.?[x];&Fy]) power_all_} iTest s7of apow(). f AB) #(_special_cases() is similar to # test_uncertainties.py:power_special_casA-, but with small # differences: the built-in pow() and math.re slightly>bt: defz: '''sChecks  P of ujR_coreo..6   F!) <# We want same behavior for numbers d3forG! aMir nominal values.r positive = ufloat(0.3, 0.01)LJnega!-"## The typeexpected exception first determined, becauseF it varies between versionsX Python (OverflowError in Dp2.6+, V ! 2.5,...)2try /40, .0_0 % Epas err_@: # "as", g# 3 does not make'Qs locSriablBy ar%Farestria to+#irCf blocku_args =.ion_clas(_"__/# http://stacko.com/quess/10282674/-T-the--pow-and-? Afor-as-in-py  <(&1)  Apass.Felse^VraiseC('%s6' %O.__name__ `resulti$,  Assumed: K1 as.Ocreason why it should also fail{ 3"thj(E&ofis a complex, which F+handle (no,; onSgs). InDf, thisAwayst, since2E know how to calculate it(I wrt_ref( 7)=er operatorIyNre.pow, mathn.pow) #!/usr/bin/env python ''' Unit tests for the uncertainties.lib1to2 code update package. Meant to be run through nosetV. (c) 2013 by Eric O. LEBIGOT (EOL).@ # Cd inspired by: # # - lib2to3._fixers.py import sys os # !! Would it be possiblesuse an :hook so as@stop$ # if! P7 version is not high en, instead of having # like here a whole indentlock? if.[_info < (2, 7) or "TRAVIS" in os.environAPPVEYORa: d# ThisT usesR, which requiresQ2.6+.=1sups is missing from 2.7.3 TraviKp,3s. KT!! NuY2.6 also fails (it look keStriesF"topdD via/$_refactor.py)pass else:o\2try-A$ Aseem-have moved;a new placKfU$as`except IVErrorLq# Pre-~VApathGP J~$/s.z12eR.k?PgivenK6t*local*gH(#to another!alled module).#ism1ant3theC"__@__()dE.getBer()@sys..insert(0,7cjoin(odirname(__file__)(brdir))def checkh(Yer, source, expectedjt1""" 0RaixPan As1ion ]W.\.i#.RingTool doe"" 'e' intoI''* -- strings (typically withCcode\Bd=A($%er_f(reformat(R), '<#$>'Ka3O7@) =={*, "7Ved: '{}' =>#". ,b.6p()=# print 'C0Fed:' F'=>'6` c@all(p!r,sN Takes a + " (Q from fixes) and a mapping that 3s rcode use obsolete syntax into updated ,, and checkEwhether the% is correctly?.t0'''~  refactorer = support.get_(-;fixer_pkg='lib1to2', 1s=[&])_for (input_str, o ) in list(tests.items()):k(/, Su@def T_fix_std_dev(X 'Tq/transformation of 0}2.' \\Ys = {3'x.-V()': *',(y(e; uncz9  JuncertaintiesFxF D6 (Kobj. &',!%9"""long_name # No argument!J)"""\;"""@# se D => Z(!(3KM = 34 3y0, )ne'func = x.?~asin(y) '~}eSall('!',BsRiufloatM'SXDZ<tuple,...)bstringrnominal_value,`, tag=L 0# Ts(3, 0.14G 4a, "pi": "%@'pi')": @ @Nx = D/7: "#L! (Simple expressionsucan be /ed?Rn, s)I"var  ;notP auto_callystr_reprw3: '6 e+*M "repr, tag="var")', 'ufloat(*t[0, 0])': ,2 =# Strings:@"-1.23(3.4)"X_fromstr( "'DS')": D DA, "vW3^Otag=bBf;g} # Automatic addition of a dotted accestests.update(dict(# !! DicHary comprehensYusable with Python 2.7+B(orig.replace(', 'unc.*')6O new2 )eAfor i,<) in iter(items()))))PTest 9space consistency@[' t = u("3")'] = "nExponentiaK Y gNa+'**2'" D/R['2**1+OppositeU-SQcheck_all}s1defj_uarray_umatrix()5'''o7of the transforphD(tuple,...%to=nominal_values, std_devs). Also perVse2sam sG5on .E = {e((arange(3)!  +H_arg@*  # Unmodified, correct codex ,{ lSs`7 ( o ) ) '1/) %  #&)'4Xcomprehensio n usable with Python 2.7+  (orig.replace('uarray', 'un. )),2O new1 )1Afor g,; ) in iter(tests.items()))5 S# Exponentiation H:s.update(dict(I# !! Dic:ary comprehensK2a+'**2' p# Test 9space consistency[' t = u(args)'] = * iASame5Rs, but{umatrixjGI'5/@$check_all_"',) ''' Fixerolib2to3. Transforms .std_dev() calls into! attribute access. (c) 2013 by Eric O. LEBIGOT.rd from nf_base import BaseFix'Dutil'Name, Assign class FixStdDev(E)PATTERN = """power< any* trailS'.' '7' >P(' ')>>|D?et_Hset_arg=anyT[0def~(self, node, results):Cif 'V'Z#`: # C^@of .!&()<9'# C => (!=.children[-2]jb:3%1]8(u)`Call ")": removed`[-\&R@mentAan aD.Ti(uclone()[z#]. Jelsef4# 'e' is followeduqno arguA theX#? d9  s s6Xlass FixStdDevs(BaseFix): PATTERN = """power< any* trail'.' 'std_devs' >P(' ')>?G 0def& nsform(self, node, resultsC# '._' is followed by a call with no argument: theoFis removed:u.children[-1].#() ''' Fixer for lib2to3. Tras uarray(tuple) intonominal_values, ss) and 8single_arg=*. (c) 2013Eric O. LEBIGOT (EOL).U fromf_base import 'Dutil'String, ArgList, Comma, syms #;$ # grammar parts. #! Warning: indentation0meaful! # !: _%(' atom< '(' testlist_gexpC> class FixUe|Umatrix# Non dotted access, .0# T&j-8,0'6' {s},|H 6object=NAME=O>Qs1l(a  @"""."at=;)o# Same pattern,wu)t'{}|{}'X,.replace($3, 'L1'))Bif 'D' inz: # Ifb: unc.(p=aargs =z!2] Belse2"1]6!% -g48# A star will be inserK1in O ofN 'F SS! Theing keeps spaces7cfront Yy,E if (but thissafer than add[forcefull  Fn{ument: the argument can &# be a name (where it works), but also anything else,B`includa lib2to3.pytree.Node that has no value.) ThisGs OK, as the syntax f(* (2, 1)) is?Iid. :`args_ni= results['*'])# We must make surts a single a0:j ifm.type == syms.arglist/greturn # NoBmodifiedSz (in position 1)[@new_ = [String('*'),.children[1].clone()] :7Tup 0NewZCs~%0'| 0Comma(),1:3# A vv update.replace(ArgList(3)) ''' Fixer for Transforms ufloat(t,...) andsrSinto .nominal_, std_dev(?_fromstr (c) 2013 by Eric O. LEBIGOT. +f_base import BaseFix'Dutil', Call, vq, Name,? #;$ # grammar parts. #! Warning: indenta`is meaful! # }1): _call = """trailer< '('\AatomP test$`_gexp<0=any ',' 1 u> ')' >Ci,?any class FixU4"):Fn dotted access, ."# &m $aNo-tag%"{PATTERN.1pow,6' {X}*|\6: r=STRINGJi string=STRING ',' tag=any>')' > any* | power< object=NAME trail'.' 'ufloatD{tuple_call}Q9?anyU7H(' sE )0L uarglist<~/ > """.format(|= ,yU.!) 30def nsc(self, node, results):(\ # Handling of the first argument3Bif 'D' in]a: # S; asFo | new_func_name =_fromstr'*U# NewsKcargs=[[].clone()]OAelseT \'% 6 = Uarg0'  Comma()f['arg1:esecondC (p with az$9tag q.extend([@!])i lQIf dotted access: unc.)().children[1] 5! ='$%2]$&g07)[1$Z# Function fupdatevP.valu)}H%! .changed()J Ne@ary when only M3is +H 3# A   .replace(ArgList()) """ Core s used by unumpy and someits submodules. (c) 2010-20165Eric O. LEBIGOT (EOL).g@ # TIps foundRthis U cannot be define!Yor # !: <creates import loops,I;explicitlyC'As onthe submodules in order to make it availablethe # user. # Standard modules: import sys itertool`nspect@3rd-partyAnumpy from c.core ^pnumericB]Local>uncertainties.umath_A6as  .(D7'deprecation __all__ = [ # Factory func$!s:'uarray', 'arix', p# Utili+nominal_values3std_devs4PClassv@'matRPO] #; : # t() and re defined as  (instead of #@addi&ethods of the u  c) because!ser # might well directly build qPnumbers with ! #out going throughbf` found;CthisB # (!ndtrix()). Thus,3."([n.ufloat((1, 0.1))]) would not # have arm.`. Addrsuch a  to, sayy H,\Qbreaksymmetry between NumPy<0andc^ces (no!),uobjects0in +E5.! Warning: __doc__ is set, but help(gc) doesdisplay i0XsYdocumentA forBtype `a (i.e.# 9cof itsk: to_:= veAize( 2,o1s=[ ],=BI) has side eff\ (d9,Qting)Ldoc=("Returre DT@ conC1ed"PV "a3(or) ( includes ces)."))& ,PsBdevis +, or zeromcother 3defE_F_8bx(arr)"""o Ifie  it.convertedaO.OPwise,is returned unchanged. """ if isinstance(arr, matrix): -return arr.view(numpy.'&Oelse0 def nominal_valuese]aRa4the, ,A of umbers in NumPya.Elements that arI3t n7with uncertainties (derived from aRclassthis module)Opassed througMtouched (becauseDarray can cont and pure floatssimultaneously) If1 isRype up,, ed+ ay- *^resulting does notM SA_to_z_()*std_dev$ dard deviation?) O) #;t ative(u, var+pu along3a, if uln-m_core.AffineScalarFunc o ,  ifB<0oneX1theDvariables on which it depends. Otherwise, s0W #u,86try_&u.as[var]"except KeyError?,"0.Qwrap_>`_func(p# !!! T5u!inccode, Rtests#LRe imp;H seems superficially similar to<J.0(): e /logic duplic`A(should be removed)?! a version "()works eve,efunc() is gi'ven a NumPy array that contains numbers with uncer ties, as first argument. ' This wrapper is similar toB`.core.)(), exceptFit handles ani instead of floa&ndFthe result can beMHowever, *turned function1morDtricted:*0`cannotc!gi[s a keyword#MBqname inD|original|0(itUa drop-in replaceo)6 --9[whoseJa single,and which re.%2"""@ _set_doc("""\'@Vers;of %s(...) works e|when it@xJe= OWarning: el&s%a Rqare nottAffineScalarFunc objects must& depend onVariableE4in any way. OtherwiselGDenced]@willjincorrec{OE1doca:%s""" % (00.__1__,7 ._A__))+3def d_.(arr, *args, **kw )WQ# NomVvalueRarr_n_9 = s[uIm 1' G# The algorithmsists inerically calculatingderivativesLeHunc:`s:d s XQcolle8Rv+s = set($orarr.flatPs, etc. mighvbpresen(Pif is-Sance(, Bq# !!!! Bforce`4'# Qp!? Isn'is very slow, ;/~ a large0berpj-s?9]|^..keys())!Ifmatrix has no Mn"U eV@# di#lyJ&ed!ifAV.z C ontEeachE=brespec # to the variables. Each element must be independof the p# other;The derivatives have, same shape asgoutputEarray (which might differ from4Aq input 6,G!in+Scase *pseudo-inverse)..$= numpy.vectorize(lambda _: {})(func_nominal_value)H0forB0 inI%: (# A basic assumptionis package i!atKuserBguarantee'uncertainties cover a zone wherePated s are linear enough. Thus,kericalestimatesp should/Qgood *standard devia interval~!is @rue YAtcommon a non-zero [ of[. If?the1S,{ has noEimpact ovyluk beingC`calcul: an incorrectJ| n\. Onscenario can givIresults, however, but i~extremely unn:  defines aD x with 0^, sets y =&(xE0thr this routine, chang x, and prinn;R4=yyBF, becausrogram had no idea oc@calec ()_x,Vn it  2num.cEly too smals .B@: we pminimum|k shift_var = max(var._std_dev/1e5, 1e-8*abs  ;qAn exce["alR exactly  I!is>E arbitrary usD/orbA"e  ewbe quitKdoesnot mattds long}uncertainty of var remains 0, # since it is, in this case, a constant.5if not shift_var:^ = 1e-8 "0# S; of all the elementsrr when var changes bypl arr = array_derivative(arr,H")*'ps, *arg0*kw )Enumerical@ = (IX- !)/e QUpdat@list variables and associated&# s, for each 1(0g_dict,A)(fjG(zipAs.flat, J))):E-ifo % }[var] ==b#bers with uncertaintiAre built fromfresult}`returnEpy.vectorize(H_core.AffineScalarFunc)% ?num[LinearCombination)g"))wrapped_j# =set_doc("""\pVersionI%s(...) that works evenvits first argu is a NumPyJ=0conTs'l.Warning:p l]0aret k objects must& depend onV4E4in any way. OtherwivGe'of1 inD]will be incorrectaal docSlr%s""" %/.__name__, ._X__))(0# I< easier to/, which represa## '& v'M'4 enQbears Psame 3 as@- (:Ris uso )uy62? #;@ # As def u(s, std_devs=None)1"""R+$ array of numbers with uncertainties initialized#the given nominal values and standard;deviations. 1_1, std_devs --Eid arguments for numpy.array,}F identical shapes (list of0$,  s,0py.JESetc.)=None is only usedsupporting legacy code, whereM can be )Qtuple,w2"""4&if'0is : # Obsolete, single kAQ callNadeprec1('uQ() should now1&wo5.')I(4) =return (vectorize(R# ! Look_#up_core.Variable beforehawthrough?%'_(=?' does not result in aBsignificant speed up: lambda v, s:`(), otypes=[object]5O) #;a def _derivative(like, var)eR4AEppect to($vWQThe rZ7ed Xis a NumPy kBsame" a~w_that conts floatY'K-5 "!, ) Iscalars tD 0vareuc.HQxK'u:"(u,A # M`set because an8 wintegerqt; gqoutput ~%of#}a*']))Pfunc_B_to__(s+0is #{0 in!ceacalculq# inver_d pseudo-of a matrix%Ya|!pappliedI sNssfEas. func_with_derivatives -- defines a function that tak&n array-like object containing scalars and return 4q. BothEthe value*vof thiswith respo!toCmultiplet paramete~re calculated byO6_O() argument. 'arr, input_type, , *args,?@**kwc) must  an iterator. The first ele{'F2@ is (6"e!he n-dimensionalDp'arr' (JAcorrPDype)PollowsFeaqpresentI rfor eac(Q fromB'$/s' )f"s:NumPy ndy#of6qs where!be0 erH ZPdata !/'biP 1is used &dmFR~)cshouldb<UF,eQ?`5* m}?variables. ;iEdE @thesBpg@addi9%al#atresult (example:pseudo-inverse numpy.linalg.pinv:erical cutoff)EQsGV ]: inv1().2"""def wrapped_H(_|o k @2  bWPuncerties (list, ^r matrix Detc.pare pas di3ly A A?L #lPbelowRnot lazy,0rareglinearDerror propaga\ done in Af7SFunc. MakDi]EiRe same way w be quite a ific task: bas`'lyD9@amouo generalizx coefficients i # core.LinearCombination to more general matrix # multiplic0`s, and6replace Variable differentials byD3fulZces of coefficients. This does not look verA.B, asJare quite bigsince caching the`resultRa fewH`x func ps that Utypicallstringed one afterc other (unlike a@ sumjnumbers)ashouldbe needed. !"So .flat works even if array_his a list:<@vers= numpy.asany(?)rs on which. dependscollectedtvs = set(for element inEo# floats, etc. might be present,if isinstance(e, uncert_core.AffineScalarFunc)nF$|=.derivatives.keys(*_nominal = s_values^ # c ),]'n i xR* ( ,re with respectFthe contained in7#< a_then_db (I: ,Ctype k lY5, ) :0var6)I*args, **kw HAext(5!ifn -areturn*ZE0Thecis built progressively,Aribu%ofA`# eachU1add :naCalculhUUe/o%.K*= U 1[{}_Rrangev .size)], d-v=object0H.reshap>)# Memory-( approach. A mehungry w#lCto cYe$GwillMG allEM)Qhen cpPm into aX   @s. \ followed here is to sd the matrix of derivatives, by  # progressively adding the3 with respect to?Bsucc> variables. for (var,N_wrt_var) in zip3,3func_then_Is): G# Update@list  and associated=U4each element:-(0S_dictAe_value <;Ts.fla<0)s7id%)`r[var] =?# An array1rnumbers uncertainties is built from8#1'ul* result = numpy.vectorize(S _core.AffineScalarFunc)(Rrnominal ;[ LinearCombination)8s))NumPy matrices that con5are# better as uPif isinstance(",b1py.~x## =^c.view(*creturn$wrapped_I5 # Mx inverse def _a*s(arr, input_type1""" De?e`{7its"s.0SeeI d=iC_to_70() 1itsxdetailed semantic!lPPg.inv)$P# Thea Q. ItCssumP#<.g'Bsuch`other Nbs yiel#p!nds62subclass(d - 4 .z#mathematically `venienR work|$ceK6_ma!as$#x(u6# SIsw.$L{ 4-o8* inv = 7invI);.__doc__ = """\pVersion7q-like objecthat contain4 numbers with uncertainties. The result is a unumpy.matrix if  linalg.pinv would return aF/for the array of nom9U valus Analytical formulas are usedAOrig9documentation:l!%sP""" %3py.inv.__doc__ #" Mpseudo-inverse def __derivatives(arr, input_type, , rcond)1"""qDefines  o and itsKCWorkreal or complex Kc:1SeebdnieGfuncB_to__ ()f{detailed semantics. * =\),#? Cof a<xYH@. IpEassumed that:v?Bsuch`other ss yieldD_!nd{sif issubclass(.  i.view(.pz %I#Ahemaly convenient to work|$ceE_maty!as$#x(g)hF5 (4.12) fromDifferenti.PI_s"# Nonlinear Least Squares Problems Whose Variablet# Separate. Author(s): G. H. Golubb V. Pereyra. Source: SIAM{PJournqn Numer sis, Vol. 10, No. 2 (Apr., 1973),Bpp. 413-432Calso" http://mathoverflow.net/ques8s/25778/a-$-n--of-the--hortcuts. Allfollowing factors shC#beSs object@PA =I*DAP ={A*arr^+21@(.H)2k0eye.shape[0])-PA*3S *h1])-AP*T q *# Successive=?R8 in2##C )4@term:*) 8 #G_H =*fd `3_H*2_33 =,/3133391+term2+term3 #j Default rcond argument for the generalization of numpy.linalg.pinv: # # Most common modern case first: try: pinv_dev1= ( inspect.signature(k).parameters["3"].M) except AttributeError: # No_) before Python 3.3Atry: B# Inq 1.17+," is wrapped using a decorator which unfortunatelyPresults inbmetadata (}s\lost. However, weNcan still get atT@origQ func#__'__Ga4" (?hat7edoes).>_" =-!.s$._*as__[0]EF5notqin NumPy <C|1, 2.6+: Ewith_uncert =E_deriv_to__(2atives) def,(array_like,g=3)lareturn1l=)2 = "_core.set_doc("""OVers t`works  - objectsD'acontai3ber1zainties. .BThe 2a umatrix i9 would raF/v!omEvalusAnalyticalmulas are usedO 1docs%_""" %adoc__)E) #" Mqclass  CallableStdDevs1'''C8 standard deviD$s,Fsed to bcf. ProvidedHcompatibilityold code. Issues an}obsolescence warnbPupon \74New  must be created by pasn existing\ __new__(cls,  # 1`followprevents a copyAdFcDbe expensive, andunnecessary (M F@is jaejaroundO  {modified21.__%r__ = clx&H;__ (selfOadeprec) ('std_devs !sh2Ralledxr ' anymore: use .std_devs instead ofs().') return self class matrix(numpy. !):1# The nameRRthis 3is the s as NumPy's, which is why itEdoes not follow PEP 8.1"""Cequivalent to , but that behaves better whenG containsCbers with uncerFties9def __rmul__(s, other =4# !32 s an apparently restrictivebCdot() functio`at can`handle multiplica&Gof aDscalar anaing objects (arguments are given i is order). We go around Qlimit%W ifkreric.is(@(~1num,mfFelse^:a,2) important UAgetIA"""M inverse or pseudo-.am, n =tV.shap(inv if m == n b pinv)z0I =0oA.I.g(") &Q# !!!8:iRficial doc#e module. Maybg is(@becaD_array)E!do{W any #isa,they should b%#first onesOsuch methods?o@propertynominal_valuesL!N* *1allz2ele!of,Ev~ ECallableStdDevs(/0) u(r$, -S=NonepConstru"  [ Qfor us(...): \sGstandard devi{"s.(a%edRan beq@ted,!nk~3facQit isaa unumpy.matrix object instead of a numpy.matrix one. """ -if std_devs is None: # Obsolete, single tuple argument callANdeprecation('ul() should now be2ed with twoKEs.')J(nominal_values,J) = return uarray>b.view(O) #; def define_vectorized_funcs():s-D'&s ( versions4Is from uncertainties.\rh_core.VSome 3$have their name translated, so as to follow NumPy's`convenw (example: math.acos ->G{arccos)Dthis_module = sys.m @s[__1__]f#t does not always us ss!heD\T-cG= dict([2t!(f&, 'arc'+F[1:]zBfor ` in [''1Acosh 1sin%ta2Rh']])1newrFs = P.get(6,H# Th#@non_Twrapp# (available^;) are normally'in5)@Cthey-fcluded herekH5uncOmany_scalars_to 2"s]BC uREzip(_*, "):p1# !\Snewlyd;s (.cos, etc.!doD!beexactly lik#irpequivalM(N#X: cos(0) gives an @) an[7t a3Hfloat... (equality tests succe cthough = getattr(Q nData typethe resultD#o4@# Itmuch more i#to preserwAys that r1ber|;out5y. Thus, ", .isnan() cavgg a boolean d'( ob), which aeT toD$usB # boolean indexing. {} if function_name in umath_core.locally_cst_(s@# If by any chance aO returns,Sa particularCacase, teger instead of a number with uncertainty,Eside-effectspvectorize() would fix the resultingBdtype to in, which is not what wanted (a r, at leastNumPy around 2010 maybedecided aboutoutput data by lookinga;the%of first element only)else {'o1s': [object]}) Ssetattr(8this_module, unumpy6 !!!! ForJ ,it make senso optimize |m us%pequival\(? seFuabove) "d 1 onqnominal values?.C(< doc="""\ Vd versione.%s. Origy@docua: %s""" % mlb.__doc__) "**6)) __all__.append() define_d() """ Testsx2cod0Bies/O/__init__.py. These t>can be ruvQrough~#No"framework. (c)8P-2016Eric O. LEBIGOT (EOL). # 3rd-o"y qs: try:`importWpy except IYError%"sysys.exit() # There pno reas=o?ArfacLhLHOies .3 asS from Dies <Tfloat,_f=.Drc. L2Qs_cloCrrayPB2():M.aIntera34@clud matrix in=correlated_CPd cald-BmeantRarr =.arange(3)qnum = uG(3.14, 0.01#9a mPPpliedVariable Ts#AAever%Torderoperands|prod1 = arr*num22*arA`# Addial check@assert (prod1 =D= prod2).all() # Operations with arrays work (they are first handled by NumPy,D@thenthis module):r 1*2mT!should be calculable-assert not (3 1-@ny()@All elements mustF0ComparisDtoo:Usual behaviorq len(arr[arr > 1.5]) == 1)# W#@Vari objectsMufloat(1.5, 0.1)Z[!1[! <612The following canGted (special  abs() func`numpy.#+ "-1 lAdoescompletely%, becauses(0# i- wexp on ani of generalN, apparentlyZA 3> 0zEquivalentsAffineScalarFunc|p#try" v .a0, 0))k except (AttributeError, Typ xNB# In `<1.17,  8 is raised in RAsitu!. A1wasyQ considered a bug however\D o it was changed to aJ (see PR #12700Erepository2pasBelseA! EQion("B.unexpectedD5ed"vCthe mean, global and fic axisAarr_t2s =is.random((10, 3, 52= uu`E, B/100@arr.(=0).shape;(a[,1,5YRGc def test_matrix(U "M0ces-cnumberuncertainties"!# .x inversion6@ mixP }sregularQQPythozO%m R#[[f1), -3.1],E. 4[0,3i"]] m_nominal_value %(mP@TestI %$ a #mI= m.Dsg<`type(m0d_core.Ms multiplicp, both _13*m.2m*3 derivatives_close(x, y"Returns True^ iff the AffineScalarFunc objects x and y have derivatives that are close to each other (they must depend?!onpsame variables).A""" #wm? ;:1if set(x.A) !=y1return False # Not,all(numbers_c sy[var], q)u0forJ in  def test_inverse()"Tests osmatrix $8m = unumpy. ([[ufloat(10, 1), -3.1],S [0, 1r3, 0)]]m_nominal_valuesh 2(m)0# "Regular" , when uncertaintiesDnAaken# into account_90 = $.I3Theqion should j0yie Z withraassertgy.dtype == l(hIZmT .I elements@ con@s2 itusupport customAoperationsO?cesisinstance(,m+3" -[00])6\core.UChecknumerical :diagonal &)!be5[EAm (because we started,qa trianh &,1/8 j..m), "Wrong?1,  . 6#!conubetween~xgWbOx, x P3+2*xD~]{ E0 pr-t;m_doubleJ !.If"# Sitial& be recovered, including i4`ich de : Dominal_value?, m[0, 0].nominal_value)1assert numbers_close(m_double_inverse?std_devj+() e_arrayd3, m.# Partial test:BderivativeG#, >P1, 1]> ## Tests of covariances during the BEion:2here are correlations if both5next two 2 # not zerom;1[x]: *;1].*+8# Cbetween m and A should create a perfectC & *O ,  py.eye(m.shape[0])) defa_wrap_Cr_func()1'''umnumpy.-, with optal argumentsAvkeyword.` `# Func? that worksVD uncertainties in mat (ifEiv )".ucmatrix f_mat, *args, **kw %aQreturj@.I +Cs[0](['factor']2est l( p# This -0is tped: it9only be calledApure&#{Gany(isinstx3(v,N_core.UFloat) for vR.flatL2^ .uWrappedf=esfDGll rank rectangular&2rix\Im = P([[uf(10, 1), -3.1] 1_3, 0)*1L] Numeric%nd package (analyt) pseudo-0es:y must b#S same_1 r(m, 2, 2=10!m_1 = %J[#, G') F2E">$"0iono0ppinv_nul g.-q.matrix: m = unumpy.matrix([[ufloat(10, 1), -3.1], C[0, 1_3, 0)*1L1]) N# Numerical and package (analyt) pseudo-inverses: they must beGthe same:rcond = 1e-8 # Test of91 seargument to pinv(): m_ 0_nu A(m, S $p= core.- )assert arrays_close(a#, I## Example with a non-full rank rectangular vector = Q, 11]^ :", ]-isquare P0], []r def test_broadcast_funcs()1"""qmathema6 *tions that workBSNumPy1 ofBrnumbers!uncertainties. j x,0.2, 0.1! armF([x, 2*xJ lcos(arr)[1] =~ru.#&[1+GSomePdo no"arPame n!inHp module]@# intPy (acos insteadarccos, etc.c ! W$2a# The )q shouldPexist because it does*jhasattr(0, 't'&n'hOS__all__ variabl_r_$inC2% R_and_P_crearbcustom &"*a!.uT`([1, 200.12,arr[1].nominal_valuep2 %pstd_dev20.2t0# SOthing fob2cesy0matm.<nomat[0,' Vcomponent_extracQE!ng  s and standard de viations from an array" = unumpy.u([1, 2], [0.1, 0.2])-bssert -Call(8nominal_values(arr) == H)h;wstd_dev5 u# matrices, in addi, should have Q that~# are simplyNT (notc on_because theyXGuncertainties):6matCxa O(mat353tOtype:p def test_ _comparisons("Test of9bay andJ'x -\_1, 4]?Aaarr[0]*True, FalseR# For"1Dsconverted to 2u = [mat[0,QobsoleteH'HP func"s'm# The neweold calls1giv same results:;unusual syntax is here protect against automatic code# update+varr_obs*0.__<__(8c) # OVl:g. (c) 2010-2016 by Eric O. LEBIGOT (EOL) . ies import __author__%.Dcore1inv, pinv 00canX: 6s tF. __all__ = ['inv', 'a1'] PUtili! for NumPy1ays ceU`at conPbers with ". tpackage2E1) um help with the creation and manipulatof NumPy arrays!$trices of numbers with uncertainties; 2) generalizO3multipleYP funck s so that they also work [ 0cone|b. - A  can be built as follows: arr = unumpy.u([1, 2], [0.01, 0.002]) # (values,1) @M@directly through5,)bnks to's supportlarbitrary object,)([.ufloat(1),...])S/Ma are best created in one of two way7matam]/x(cd  Bby converting ^m4the_ class(arr) 2y behave like;py.!  2butfebetterfor some operf(such as ciQsion)b# The e or pseudo-P(for @ance6garccos is^"d,2iY!isgt0d a1W!infpstandarto@). ip`quanti 0 byY6se availablL!P docu x } ulger}R[ st @ (sev$e ation for this module). Thh requires the NumPy package. (c) 2009-2016 by Eric O. LEBIGOT (EOL) . Please send featurewests, bug repor or feedback to ttaddresssoftware is re[d under a dual license. (1) The BSD (2) Any other, as long it]obtained fromoriginal author.""" # Local`As: 10.com# *" i ulH4g =Bsub-Qp__all__Pset s at pydoc shows allMant functions: < = .C # "|numpy" makes .availabl;$%behavior is # copied here, for maximum compatibility.append('0') 1T?Puncerdbties.u-Qese t/can be run through#No"ing framework/10+d # Somxalready performed in_# (0cons a # matrix inversionBinstance).  y a0not3eatn. try:  except IWYError%1sys4sys.exit()sT]no reasonm1estVinterface , ufloat )#arrays_close defHRlist_*2e()"83 ofFPa squ8c!" @mat_H = [[1, 1], 20]]!#BT.inv(4) does calculatetae evenbA# th7R!a u!ofps (and a$CaB de same? He:1s ae2 = v.@ M2typ6ingJ+# ="asPasser  w>!),6 (j9$)) Auld ehh&@ wayV# with respectsF_< &)F @]) == V~`result^1have4be u that c"yhandle Rp, becauh3put^ [e # unce4rtainties: assert not isinstance(mat_list_inv, unumpy.matrix) 8 # Individual element checkXT[1,1], float)y%b == -1tQx = u4r(1, 0.1;y20mat([[x, x], [y, 0]])Y)ternal consistency: ulinalg.inv() must coincide with the#$ inverse, for square ?ces (.I is<ypseudo-5Knon-9P, but[ ()@Qnot).~arrays_close(Pmat),.I) def tes"()"Test of #";^0theO anda yield#same result onDUmat.IKpLB1e-4?D# Support9PoptiowQ arguj/isF "edf ^, 1e-15)4N]1y]]) # "Long"1rixOmat24, [1, 3+42*xHETallHIOmat11#?10)B2B8)) INSTALL.txt LICENSE MANIFEST.in README.rst setup.cfg py doc/Makefile /Sconf.(QindexIE_TOCmake.batH?e_guide!KtechKuser_static/default.cssRyeol.jpgfavicon.icoslogo.pn- templates/layout.html unce-py23/1to2__init__@backOcore{o_umath! )E _0lib/t__.py uncer tainties-py23/lib1to2/test_ .py uncer(fixes/__init__-fix_std_dev0s1uarray_umatrix7_float/ounumpy &OcoreH culinalg*~) N /7/7 /7/7)gh!B)E _ 7( - 017#7/B &"r*).egg-info/PKG-INFO SOURCES.txt#dependency_links, require$ top_levelI J [all] sphinx  nose [docs [optional]& [6"s]/: Metadata-Version: 2.1 Name: y!3.1.2 Summary: Transparent calculawjs withD on the quantiA involved (aka error propagFi); fasY of derivatives Home-page: http://-python-package.readthe+.io/ Author: Eric O. LEBIGOT (EOL)D-email: eric.lebigot@normalesup.org License: This software can be used under one offollowing two lBs: (1) The Revi9CBSD `. (2) Any other5, as longit is ob~qed fromo@orig:! a. Descri&: Overview = `:`uncertainties`` allows **calculations** such as (2 +/- 0.1)*2 = 4 +/- 0.2 to be **performed transparently**. MN more complex mathematical M express involving numbers with can alsevaluatedOdirectly. ]The ` `packagtakes the pain andity out**L'of(y Iz**Detailed in1s** about this be found on its `main|website`_jBasic exars3= .. code-block:: pythor(>>> fromies import ufloat1 :3x =$(2, 0.25)$ `2.0+/-* Vsquare = x**2 # T : 4q91.0g.nominal_}e%45pstd_devStandard devi  Ez i - x*x00.0\0Exa 0: corre n into accoun .u*isin(), etcPin(1+ -0.95892427466313845836621854632263 [print (2*x+1000).derivatives[x]AAutofG of + X2 q aunumpyrrray manipO Grandom_vars;0.ua9([1, 2], [0.1]7F b![1E0.1 /]"Dj.mean(m21.5p/11AW.cos( F[0.5403023058680841470984808 -0.416146836547"181859485365Mfeature, O- **_**: **no or littlqmodificQPexist= ** is needed. Similarly,SPRU_ (or3 Iq) shellpbe used**a powerfuwor** the handles quantities with uncertainties (``print`` statements are optional, which is convenient).* - **Correla:s** between expressionf c'ctly taken intoH account. Thus, ``x-x``1exa8 zero, for instance (mostFAimpl found on the web yield a non-Pa uncer%y[L #in  Al all mathematical oper **s supported, including <AfuncUQ fromAdard^_ module (sin,...). ComparisonJ!or0>``^ ==Zetc.)O tooMany **fast]arrays an@rice of numbers witht6arez**Extensiv* Ying**j7iesx(lTLaTeXwtpretty-TGMost_sy calcuHperformed **analyOly**DThisalso givesaess to**derivat** of any meya (theyused by error:apropagkAory,thus autolM8thi_m9qIl0 or upgrad=@ I#ru-availableQ`main6sito`_3 Z fContac  Please seni feature requests, bug red s,ifeedback** w `Eric O. LEBIGOT (EOL)`_0Verv histor} Mzchanges: - 3.1.2: Partial fixNumPy 1.17`unumpy.ulinalg.pinv()`I`: Varis built through a{0cov+Fbmatrix6thag have"p span m0ordof magnituderEnow  )ped moreurately (improved ``a`d_values()``K&Q_norm+functions). l - 3.0: Massive speedup for some operations involving large numbers of numbers with uncertainty, like ``sum(ufloat(1, 1)a_ in xrange(10&))`` (this is about 5,000 times faster than before).  - 2.4.8: Friendlier comple Python shells, etc.: internal func+ should not appear anymore (the user modules: ``lies``,.umath`` and numpy``). Parsee@shor (e.g. ``3.1(2)``) now worksinfinite values1-inf(inf4!; dmirrors kability to print suchP. Theticle Data Group roundArule`ppliedB5casj-724.2±26.2gives ``724r`+LaTeXG@mattC 5an @nomiPfixedG !.u.matrix``u ``.std_devs`` instead of  () consistencyfry (automatic conversionWcode added ^P.1to2 `7: Str 4for``(-)inf+/-... F5K?NaNH !4:)documentqlicense^allows itspmercial] 2: `NumPy 1.8,Cpati`_Z^1: In,b``ceilq``floor  ish p``isnan$q``truncdreturn'ofHsame type acorrespo`"``F(generally w'a|wa zero J``...+/-0wr: Exten?`upportU_2w'6ies= A1explicitly displayedXger 0K30newmats are understood byq_fromstLqAbbrevisR Z@(``nwtandardJdDQ (``s-r vailablev3.6: Full s_blimit M!ofSpower'ort!``}.pow()``. < - 2.3.5: Uncertainties and derivatives can now be NaN (not-a-number). Full support for $s with a zero uly;(``sqrt(ufloat(0, 0))``x_worksi limit cases of the power operator (``x**y``I: Functions wrappedpso thatRy accept;pinsteadsKC`have f'keyword arguments92(improved ``(f). Incompatible change:?5..., None>`shouldreplaced by_0...$/orEe[])``.?2: Creating array?bmatric  /J "1``uD1``uJxArequires two simpleCP(nominal valupstandar1via') Ha tuP This is consistentjCnew,Cr ``JinterfaceKe previouusage willF!edHsome time. Users are encouraged to updatetheir code,Dance throughp newly e idg/KGr`_,Owhich in addi<automaticallyverts ``.set_std_dev(v 'toN!L = vUP1: Nu^: 5 cxed more directly lik3, 0.1)``,`, "pi" _fromstr("3.0(1)(& o !O(6mm("z ~0: The h: obe gout anexplicitf.Z(``4``x0;). KFA.of a variaOd^ =``. As aksequence1zy is deprecated. -B 1.9.1: Support added for pickling subclasses of ``UFloat`` (= ``Variable``). -W2: AMunctionsWAhandWpcorrela matrices:BG ``"_"x()`` and'ed_values_norm+. (These new fmirror theHcovariance-la based)0P.posi_in_sigmas"7 isqnow namwg.std_score., so as to followx commonG am`convent (`standard M- `_). Obsolet?^were removed (frommain moduleNumberWithUncert``, ``num_with_uarray_u``,``nominal@7Mdevs8: Compatibility f Python 3.2.a?7.26 D2.3,Bb2.4, JN[2.5.1k1: New semantics: ``ufs("12.3(78)"-represents e+/-7.8 instead 8`V aiVNE,Ha generic Excep_when given an in'ct0str, like ``Jdoesp6: Test>pwhetherdobject is a nM:ainty should nowrbe done.@``isb(..., 6)``AffineScalarFunc``{`not imCPed by3ies!G *``anymore, but itsUalias<c5.5: The first possible license@ReviRBSD L"GPLv2, which"0makt easier} include this package in o0pro 05.4G``umath.modf&Pfrexp 40``  x ac a single( #) iU0 Ts some pot3al confusion abou01.1f(zero Py) bedifferent SBA"1.1(?1 on8last digit`5N`05 ``!P4 reYufloat``,  !``uarray`` and ``umatrix``, for ease of typing. 6 - 1.5: Added functions ``nominal_valueWpstd_devW5andG module9PunumpP(addiOal supportqNumPy_ sG@ces)M0.ulg`` (generaliza[GsomeC@from.B) Memory footprintOof numbers with uncertaintieso@divi<Hby 3[FL1 ``R_u`` is 5 times faster2EMain_{_{`` renamewp``float]consistency"``. !2Kxa the abbenefi shorter J4LKHpstandarPpicklS4 C#2:C!cobA?Putili manipulating  y' (,"s#7s``k 3:yR are now qtructedX``num ()which replacNQWithU'h. Thisimplifies class hierarchy by remov0,``W1`` 5 2+:A canbe entered ah("1.23+/-0.45")`` toou3: ``log(x, base'!isjH ed h.+> ink$toO<)``l@2: Voutput like 1, in orderhPavoid0fusmA3+-1k 3+(-1EE new)@wrap,aexposed, Pallow n-Python~+(e.g. Fortra C used through a such as SciPy) toOohandle7 I1: Mathematical4s (fcosine, etc.)#w .h;&they do not overrides,cmath``C anymore@0.12"in4``) '`` soUPto fo `PEP 8`_w1: ``origin_value`` renamed more appropriately as ``nominal_value``. - 1.0.9: ``correlations()_covariance_matrix@en .. _Python: http://docs.p.org/tutorial/interpreter.htmlEIFiBqreadtheUio/en/stable/>UNumPynumpy.scipy +Emath*Wjlibrary/%UPEP 8<8wwwdev/pepsZ-0008`error !agf theoren.wikipediaS/Prop1_of_uncertainty&Eric O. LEBIGOT (EOL): mailto:eric.lebigot@normalesupf FbPayPalAs://6aypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=4TK7KNDTEDT4SgPmain E2item6://Bies--package. Ncode updaterN"en/latest/indexQ#migr-from-version-1-to 2fX_tting,user_guide@prinW Keywords: M,?sy calcu,standard devi,derivatives,partial different0P Plat: UNKNOWN ClassifiDevelopment Status :: 5 - Produc!/S 8Intended Audience7M?ers,AEduc+UOtheri0!Sc/Research2aLicensPOSI A0vedCBSD  30Ope\ng System,OS Indep)nt/Programming Languago1+h?2.3242526272?3.1b/.22.3 Classifier: Programming Language :: Python 3.4 Classifie2526272ImplementatiJG.IPyPyEPTopic;AEducnScientific/Engineering,eMathematics;OPhys7oftware Develop;a*Librarie7 D_ModulI`UtilithProvides-Extra: tests >doc:all)a: optional