-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPObject.py
More file actions
2048 lines (1789 loc) · 79.3 KB
/
Copy pathPObject.py
File metadata and controls
2048 lines (1789 loc) · 79.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Python Implementation: PObject
##
# @file PObject.py
#
# @version 2.0.0
#
# @par Purpose
# PObject class and derived classes for PObjects toolbox package.
#
# @par Comments
#
# @par
# This is Python 3 code!
# Known Bugs: none
#
# @author W. Ekkehard Blanz <Ekkehard.Blanz@gmail.com> (C) 2018-2024
#
# Copyright
# Copyright (C) 2018-2022 W. Ekkehard Blanz
# See NOTICE.md and LICENSE.md files that come with this distribution
#
# File history:
#
# Date | Author | Modification
# ----------------+----------------+------------------------------------------
# Mon Feb 12 2018 | Ekkehard Blanz | created
# Thu Feb 15 2018 | Ekkehard Blanz | now PObject accepts PObject as parameter
# | | and operators return value-type if result
# | | is unitless
# Sat Feb 17 2018 | Ekkehard Blanz | added valueList() and floatList() and put
# | | constants in Const and its metaclass
# Tue Aug 28 2018 | Ekkehard Blanz | PObject constructor can now have prefixed
# | | unit argument
# Wed Aug 29 2018 | Ekkehard Blanz | added standardizedList()
# Wed Nov 21 2018 | Ekkehard Blanz | improved unit test and documentation
# Fri Dec 07 2018 | Ekkehard Blanz | can now add and subtract regular numbers
# | | from unitless PObjects
# Tue Jan 15 2019 | Ekkehard Blanz | added Temperature as PObject subclass
# Fri Jan 18 2019 | Ekkehard Blanz | added standard printing of different
# | | units to Energy and Temperature
# Mon Jan 21 2019 | Ekkehard Blanz | harmonized Energy and Temperature and
# | | removed their conversion properties in
# | | favor of a more robust printUnit
# Tue Feb 12 2019 | Ekkehard Blanz | added ImperialLengthMisfits
# Wed Feb 13 2019 | Ekkehard Blanz | vastly improved PObject documentation
# Thu Feb 14 2019 | Ekkehard Blanz | added useYards parameter
# Mon Feb 18 2019 | Ekkehard Blanz | added in-place arithmetic operators and
# | | fixed various bugs dealing with
# | | interaction with non PObjects
# Mon Mar 10 2019 | Ekkehard Blanz | fixed problem in multiplying and dividing
# | | derived classes
# Tue Mar 12 2019 | Ekkehard Blanz | fixed bug in standardizedList() and
# | | allowed comparisons with 0 directly
# Fri Jan 07 2022 | Ekkehard Blanz | added standardizedTuple property to
# | | PObject and provided setter for digits
# Mon Jan 10 2022 | Ekkehard Blanz | arithmetic operations no longer return
# | | unitless PObjects but plain numbers
# | | instead
# Mon Jan 10 2022 | Ekkehard Blanz | cleaned up code and added documentation
# | | for unitless and zero-valued PObjects
# Wed Feb 02 2022 | Ekkehard Blanz | added __bool__() method to PObject
# Fri Feb 18 2022 | Ekkehard Blanz | added copy() method to PObject
# Wed Apr 13 2022 | Ekkehard Blanz | separated Const from this file and made
# | | part of Physics package
# Mon Jul 18 2022 | Ekkehard Blanz | added __format__ method to PObject
# Sat Dec 07 2024 | Ekkehard Blanz | fixed bug in __rtruediv__
# Wed Dec 11 2024 | Ekkehard Blanz | added Time, Mass, and Length
# | | and moved Frequency From EE package
# Thu Dec 12 2024 | Ekkehard Blanz | made float() work on PObjects
# Tue Dec 17 2024 | Ekkehard Blanz | renamed package to PObjects
# | |
import math
import copy
import scipy
from PObjects import SI
def sqrt( value ):
"""!
@brief Provide a sqrt function that, other than the one provided by math,
can handle PObjects and negative arguments without raising an exception.
Instead of
@code
from math import sqrt
@endcode
use
@code
from PObjects import sqrt
@endcode
to take advantage of this function.
@param value radicant
@return square root of radicant
"""
return value**0.5
class PObject():
"""!
@brief Class representing any physical object consisting of value and unit.
Can serve as a base class to derive more specific object classes from, but
all SI units are fully implemented in this class. PObjects can be used like
any other numerical objects in Python, i.e. they can be added, subtracted,
multiplied, divided and compared. Obviously, only PObjects with the same
units can be added and subtracted, but PObjects with arbitrary units can be
multiplied and divided, multiplied with and divided by regular numbers, and
raised to a given power thereby yielding not only the SI base units m,
kg, s, A, K, mol and cd but also the derived SI units such as Hz, N, Pa, J,
W, C, V, F, Ω, S, Wb, T, H, and lx. For more details on this, see class
Unit of the module SI. When raising a PObject to a non-integer power, only
such operations are legal that yield valid combinations of SI units, i.e.
usually the only non-integer power that is legal and useful is 0.5, which
is also obtained by the sqrt function from this module. For instance, one
could compute
@code
from PObjects import PObject, sqrt
from math import pi
...
L = PObject( 5, "mH" )
C = PObject( 4.7, "pF" )
f = 1 / (2 * pi * sqrt( L * C ))
print( f )
@endcode
which would produce the string "1.03821 MHz".
The built-in functions min() and max() will also work on arrays of PObjects.
PObjects can be converted to strings and then yield human-readable results
with engineering notation and standard SI prefixes as shown above. Again
see the module SI for more details on this. There are both SI units and
prefixes (i.e. Ω and μ) that may not render correctly in cases where only
strict ASCII characters are allowed. The constructor of the PObject class
accepts a parameter strictAscii, which, when set to True, will instruct the
string conversion not to use these characters but use Ohm and u instead.
Since neither Ω nor μ can be typed on regular ASCII keyboards, PObjects
always accept Ohm and u as input in addition to Ω and μ.
It is worth noting that the values used to instantiate any PObject can be
ints, floats, or even complex numbers, the latter being of particular
interest in electrical engineering.
It is possible to instantiate a PObject without a unit or a "blank" unit
string; doing so is discouraged, but, following the philosophy that simpler
is better, any value resulting from an arithmetic operation resulting in a
unitless PObject will automatically be converted into a regular number (or a
complex number if the value was complex and the unit string blank). Only
other unitless PObjects or regular numbers can be added to or subtracted
from unitless PObjects.
At the expense of sounding like a general Python tutorial, it is worth
noting that PObjects are mutable objects - not immutable ones such as
integers or floats with the effect that variable names are just references
(pointers) to existing mutable PObjects. Therefore,
@code
x = PObject( 5, "kg" )
y = x
x *= 2
@endcode
will not only result in x obtaining the value of 10 kg but also y. To avoid
this (especially for C/C++ or Java programmers unexpected) behavior, use
@code
x = PObject( 5, "kg" )
y = x.copy()
x *= 2
@endcode
now only x will have a value of 10 kg and y still the value of 5 kg.
To make PObjects seamlessly work in regular code, the __float__ method has
been implemented, so that
@code
x = float( PObject( 0.005, "s" ) )
@endcode
is the same as
@code
x = PObject( 0.005, "s" ).value
@endcode
PObjects can have a value of 0 and any unit. This is because real
physical objects, such as voltages or currents, often can take on positive
and negative values and exhibit smooth transitions in between. Of course,
strictly mathematically speaking, the numerical representation of a
physical object consists of the product of its value and its unit, and if
the value is zero the product is zero too. The representation as PObject
with a value of 0 and its regular unit was kept for strictly practical
reasons so that currents undergoing zero-transitions still remain currents
and the voltage drop across a superconductor is still a voltage, albeit one
of 0 V. It is worth noting, however, that the comparison of
@code
PObject( 0, "V" ) == 0
@endcode
evaluates to True, and the following is True too for any unit
@code
not PObject( 0, "A" )
@endcode
However, there is a difference between zero-valued PObjects of different
units and the number 0 when used in arithmetic operations. Even a
zero-valued voltage PObject can only be added to or subtracted from other
voltage PObjects, not, say, a current PObject, not even a zero-valued one.
At the other hand, the number 0, by definition, can be added to or
subtracted from anything, including a PObject, without changing its value.
This becomes important when we have an existing function that, say, sums up
its arguments in an accumulator that it initialized to zero, and we want
to give it either a sequence of regular numbers or a sequence of PObjects
without making changes to the function code. Lastly, any number, including
zero, can be multiplied with any PObject without changing the PObject's
unit. At the other hand, multiplying e.g. a zero-valued voltage PObject
with any current PObject will result in a power PObject of 0 W and not in
any current or voltage PObject. So while potentially not holding up to
mathematical rigor, zero-valued PObjects are very useful and implemented
with strict consistency.
Without going into the ontology vs. epistemology discussion here, many
entities in physics and engineering are not known or cannot be known to an
arbitrary level of detail, i.e. to a precision better than a given number
of relevant digits. This class allows his number of digits to be specified,
which will also affect any PObjects that are derived from this
limited-precision object. The values of PObjects without digit limitation
are rendered as ordinary floating point numbers, whereby the Python string
format specification will always take precedence even if the internal digit
limitation was specified. It is important to know that by specifying the
'digits' parameter, only the string representation of the associated
PObject and its derivatives are affected - not the internal representation,
which is always a floating point number. Also, calculating inherent
uncertainties internally is beyond the scope of this class.
"""
@staticmethod
def valueList( polist ):
"""!
@brief Convert a list with PObjects into one with values in SI base
units only - the unit is not returned.
It is not checked whether all elements in the list have the same SI base
unit.
It is worth noting that valueList() is agnostic with respect to the
values of the PObjects in the list. That means that it can handle
PObjects with complex values, but it also means that the resulting list
may contain elements of different types.
@param polist list with PObject-derived objects
@return list with only values of all objects
"""
try:
return [item if item == 0 else item.value for item in polist]
except AttributeError as e:
raise ValueError( "elements in list need to be PObjects or 0" ) \
from e
@staticmethod
def floatList( polist ):
"""!
@brief Convert a list with PObjects into one with floats of values in
base SI units only - the unit is not returned.
It is not checked whether all elements in the list have the same SI base
unit. The difference to valueList is merely that all returned elements
are guaranteed to be floats, but passing a list with PObjects that are
complex will result in an exception.
The method is mostly used to pass lists of values of PObjects as arrays
to C library programs which do not understand PObjects.
@param polist list with PObject-derived objects
@return list with values of all objects converted to floats
"""
try:
return [0. if item == 0 else float( item.value ) for item in polist]
except AttributeError as e:
raise ValueError( "elements in list need to be PObjects or 0" ) \
from e
@staticmethod
def standardizedList( polist ):
"""!
@brief Convert a list of PObjects into one with standardized (i.e. not
necessarily base SI units) floats of values and return a tuple
with that list and the (potentially not SI base) unit for all of
them.
If a conversion of all elements of the list to the same standardized
unit is not possible, the values are converted to those with base SI
units. Of course, it only makes sense to convert objects to
standardized units if they have the same SI base unit. If not all
elements of the list have the same SI unit or are not PObjects, a
ValueError exception is raised.
@param polist list with PObject-derived objects
@return tuple with list of float values and unit for all of them
"""
minobj = min( polist )
if minobj == 0:
if max( polist ) == 0:
return ([0] * len( polist ), "")
maxobj = minobj
for element in polist:
if element != 0:
if not isinstance( element, PObject ):
raise ValueError( "elements in list need to be PObjects" )
if element.unit != minobj.unit:
raise ValueError( "all elements in list must have same "
"unit" )
element = abs( element )
if element < minobj:
minobj = element
elif element > maxobj:
maxobj = element
_, maxunit = SI.Prefix.standardizeTuple( (maxobj.value, maxobj.unit) )
if minobj != 0:
_, minunit = SI.Prefix.standardizeTuple( (minobj.value,
minobj.unit) )
if minunit != maxunit:
# convert all elements to base unit
return (PObject.floatList( polist ), minobj.unit)
vallist = []
for obj in polist:
if obj != 0:
val, unit = SI.Prefix.standardizeTuple( (obj.value, obj.unit) )
else:
val = 0
vallist.append( val )
return (vallist, unit)
def __init__( self, value, *args, **kwargs ):
"""!
@brief Constructor - use as
@code
PObject( valstring[, digits=<digits>][, strictAscii=<bool>] )
@endcode
or
@code
PObject( value[, unit][, digits=<digits>][, strictAscii=<bool>] )
@endcode
or
@code
PObject( valobj[, digits=<digits>][, strictAscii=<bool>] )
@endcode
digits and strictAscii are optional parameters in all cases. If unit
is not given, a unitless PObject will be created.
To allow more arguments in derived classes, the constructor can be
called with more than the required number of arguments, both with and
without keywords. All will be stored internally and made available for
the derived classes via the "protected" properties _args and _kwargs.
@param value string representing the physical object including
numerical value and potentially unit, the numerical value
of the physical object, or another instance of PObject
@param args currently only supported with one element which is then the
unit for the physical object either as a string or as an
instance of Unit (see SI.Unit)
@param kwargs can consist of digits=<digits> and/or strictAscii=<bool>
"""
if isinstance( value, str ):
# called with value-and-unit string
vlist = value.split( " " )
if len( vlist ) <= 2:
# only one unit item - may contain SI prefix and can
# be handled by SI.Prefix
(self.__value, unit) = SI.Prefix.fromString( value )
else:
# more than one unit item needs to be handled natively
# and cannot contain any SI prefix
self.__value = float( vlist[0] )
unit = " ".join( vlist[1:] )
self.__args = args
self.__kwargs = kwargs
elif isinstance( value, PObject ):
# called with another PObject-derived object
# value and unit are simply derived from it
self.__value = value.value
unit = value.unit
# args and kwargs are first also derived from it
self.__args = value._args
self.__kwargs = value._kwargs
# but supplied arguments override
try:
self.__kwargs["digits"] = kwargs["digits"]
except KeyError:
pass
try:
self.__kwargs["strictAscii"] = kwargs["strictAscii"]
except KeyError:
pass
try:
self.__kwargs["precision"] = kwargs["precision"]
except KeyError:
pass
elif isinstance( value, (int, float, complex) ):
# called with numerical value only, requires unit in args tuple or
# results in unitless PObject if nothing is given
if len( args ) < 1:
self.__value = value
unit = ""
elif str == type( args[0] ):
if len( args[0].split( " " ) ) == 1:
# unit is not composite string and can have prefix
(self.__value, unit) = SI.Prefix.fromString( str( value )
+ " "
+ args[0] )
else:
# unit is composite string and can not have prefixes
self.__value = value
unit = args[0]
elif SI.Unit == type( args[0] ):
# first argument is proper SI Unit
self.__value = value
unit = args[0]
else:
raise ValueError( "PObject not called with proper unit - "
"value = {0}, args[0] = {1}"
.format( value, args[0] ) )
if len( args ) > 1:
self.__args = args[1:]
else:
self.__args = ()
self.__kwargs = kwargs
else:
raise ValueError( "value argument is of type {0} "
"but must be string, number or PObject"
.format( type( value ) ) )
try:
self.__digits = self.__kwargs["digits"]
except KeyError:
self.__digits = 6
self.__kwargs["digits"] = self.digits
try:
self.__precision = self.__kwargs["precision"]
except KeyError:
self.__precision = 0
self.__kwargs["precision"] = self.precision
try:
self.__strictAscii = self.__kwargs["strictAscii"]
except KeyError:
self.__strictAscii = False
self.__kwargs["strictAscii"] = self.__strictAscii
if str == type( unit ):
self.__unit = SI.Unit( unit )
elif SI.Unit == type( unit ):
self.__unit = unit
else:
raise ValueError( "unit {0} must be string or SI.Unit object "
"but is {1}".format( unit, type( unit ) ) )
return
def __str__( self ):
"""!
@brief Return a pretty string representing the object.
@return string containing string representation of value and unit
"""
if float == type( self.__value ) and \
1 == len( str( self.__unit ).split( " " )) and \
-1 == str( self.__unit ).find( "**" ):
return SI.Prefix.toString( (self.__value, str( self.__unit )),
digits=self.__digits,
strictAscii=self.__strictAscii )
fstring = "{{0:.{0}g}} {{1}}".format( self.__digits )
return fstring.format( self.__value, self.__unit )
def __format__( self, formatSpec ):
"""!
@brief Return a pretty string representing the object with a given
format specification.
This method allows to override the built-in formatting, including the
(potentially) user-specified number of significant digits.
@param formatSpec Python format specifier
@return string containing string representation of value and unit
"""
if float == type( self.__value ) and \
1 == len( str( self.__unit ).split( " " )) and \
-1 == str( self.__unit ).find( "**" ):
return SI.Prefix.toString( (self.__value, str( self.__unit )),
formatSpec=formatSpec,
strictAscii=self.__strictAscii )
return format( self.__value, formatSpec ) + " " + str( self.__unit )
def __repr__( self ):
"""!
@brief Return string that when evaluated will re-create the object.
@return string that when evaluated will recreate the object
"""
return "{0}( {1}, {2} )".format( str( self.__class__ ),
repr( self.__value ),
repr( self.__unit ) )
def copy( self ):
"""!
@brief Make a (deep) copy of self.
This is a Python idiosyncrasy - similar to the copy() method in dicts.
"""
return copy.deepcopy( self )
def __add__( self, other ):
"""!
@brief Overload addition operator (self + other)
@param other other object to add to ourselves
@return Object of same class with result
"""
kwargs = self._kwargs
if not isinstance( other, PObject ):
if other == 0 or self.isUnitless:
resval = self.__value + other
else:
raise ValueError( "can only add 0 to any PObject or any "
"number to a unitless PObject" )
elif other.unit != self.unit:
raise ValueError( "only objects with identical units "
"can be added to each other" )
else:
resval = self.__value + other.value
kwargs["digits"] = max( self.__digits, other.digits )
if self.isUnitless:
return resval
return self.__class__( resval, self.__unit,
*self.__args, **kwargs )
def __radd__( self, other ):
"""!
@brief Overload addition operator (other + self)
@param other other object to add to ourselves
@return Object of same class with result
"""
return self.__add__( other )
def __iadd__( self, other ):
"""!
@brief Overload in-place addition operator (self += other)
@param other other object to add to ourselves
@return self now containing result
"""
if not isinstance( other, PObject ):
if other == 0 or self.isUnitless:
self.__value += other
else:
raise ValueError( "can only add 0 to any PObject or any "
"number to a unitless PObject" )
elif other.unit != self.unit:
raise ValueError( "only objects with identical units "
"can be added to each other" )
else:
self.__value += other.value
if self.isUnitless:
return self.__value
return self
def __sub__( self, other ):
"""!
@brief Overload subtraction operator (self - other)
@param other other object to subtract from ourselves
@return Object of same class with result
"""
kwargs = self.__kwargs
if not isinstance( other, PObject ):
if other == 0 or self.isUnitless:
resval = self.__value - other
else:
raise ValueError( "can only subtract 0 from any PObject "
"or any number from a unitless PObject" )
elif other.unit != self.unit:
raise ValueError( "only objects with identical units "
"can be subtracted from each other" )
else:
resval = self.__value - other.value
kwargs["digits"] = max( self.__digits, other.digits )
if self.isUnitless:
return resval
return self.__class__( resval, self.__unit,
*self.__args, **kwargs )
def __rsub__( self, other ):
"""!
@brief Overload subtraction operator (other - self)
@param other other object to subtract ourselves from
@return Object of same class with result
"""
kwargs = self.__kwargs
if not isinstance( other, PObject ):
if other == 0 or self.isUnitless:
resval = other - self.__value
else:
raise ValueError( "can only subtract any PObject from 0 or "
"a unitless PObject from any number" )
elif other.unit != self.unit:
raise ValueError( "only objects with identical units "
"can be subtracted from each other" )
else:
resval = other.value - self.__value
kwargs["digits"] = max( self.__digits, other.digits )
if self.isUnitless:
return resval
return self.__class__( resval, self.__unit,
*self.__args, **kwargs )
def __isub__( self, other ):
"""!
@brief Overload in-place subtraction operator (self -= other)
@param other other object to subtract from ourselves
@return self now containing result
"""
if not isinstance( other, PObject ):
if other == 0 or self.isUnitless:
self.__value -= other
else:
raise ValueError( "can only subtract 0 from any PObject or any "
"number from unitless PObject" )
elif other.unit != self.unit:
raise ValueError( "only objects with identical units "
"can be subtracted from each other" )
else:
self.__value -= other.value
if self.isUnitless:
return self.__value
return self
def __mul__( self, other ):
"""!
@brief Overload multiplication operator (self * other)
If self is a PObject-derived class and other is too, the result will not
be an object from the derived class but a proper PObject since the unit
no longer fits the derived class.
@param other other object to multiply ourselves with
@return Object of same class or PObject with result
"""
if isinstance( other, PObject ):
kwargs = self.__kwargs
kwargs["digits"] = max( self.__digits, other.digits )
res = PObject( self.__value * other.value,
self.__unit * other.unit,
*self.__args, **kwargs )
else:
res = self.__class__( self.__value * other, self.__unit,
*self.__args, **self.__kwargs )
if res.isUnitless:
return res.value
return res
def __imul__( self, other ):
"""!
@brief Overload in-place multiplication operator (self *= other)
If self is a PObject-derived class and other is too, the result will not
be an object from the derived class but a proper PObject since the unit
no longer fits the derived class.
@param other other object to multiply ourselves with
@return self or PObject with result
"""
if not isinstance( other, PObject ):
self.__value *= other
res = self
else:
res = PObject( self.__value * other.value,
self.__unit * other.unit,
*self.__args, **self.__kwargs )
if res.isUnitless:
return res.value
return res
def __rmul__( self, other ):
"""!
@brief Overload multiplication operator (other * self)
@param other other object to multiply ourselves with
@return PObject or derived objects with result
"""
if isinstance( other, PObject ):
raise ValueError( "We did not expect to get here" )
res = self.__class__( other * self.__value, self.__unit,
*self.__args, **self.__kwargs )
if res.isUnitless:
return res.value
return res
def __truediv__( self, other ):
"""!
@brief Overload division operator (self / other)
@param other other object to divide ourselves by
@return Object of same class or PObject with result
"""
if isinstance( other, PObject ):
kwargs = self.__kwargs
kwargs["digits"] = max( self.__digits, other.digits )
res = PObject( self.__value / other.value,
self.__unit / other.unit,
*self.__args, **kwargs )
else:
res = self.__class__( self.__value / other, self.__unit,
*self.__args, **self.__kwargs )
if res.isUnitless:
return res.value
return res
def __itruediv__( self, other ):
"""!
@brief Overload in-place addition operator (self /= other)
@param other other object to divide ourselves by
@return self or PObject with result
"""
if not isinstance( other, PObject ):
self.__value /= other
res = self
else:
res = PObject( self.__value / other.value,
self.__unit / other.unit,
*self.__args, **self.__kwargs )
if res.isUnitless:
return res.value
return res
def __rtruediv__( self, other ):
"""!
@brief Overload division operator (other / self)
@param other other object to divide by ourselves
@return PObject with result
"""
if isinstance( other, PObject ):
raise ValueError( "We did not expect to get here" )
res = PObject( other / self.__value,
1 / self.__unit,
*self.__args, **self.__kwargs )
if res.isUnitless:
return res.value
return res
def __pow__( self, other ):
"""!
@brief Overload raise to the power operator (self**other)
@param other other object to which power to raise ourselves to
@return always a PObject - not one of the derived objects
"""
if other == 0:
return 1
if isinstance( other, PObject ):
if other.isUnitless:
other = other.value
else:
raise ValueError( "Cannot raise any object to the power "
"of a PObject with non-blank unit" )
res = PObject( self.__value**other, self.__unit**other,
*self.__args, **self.__kwargs )
if res.isUnitless:
return res.value
return res
def __abs__( self ):
"""!
@brief Overload absolute value operator (abs( self ))
@return Object of same class with result
"""
res = self.__class__( abs( self.__value ), self.__unit,
*self.__args, **self.__kwargs )
if res.isUnitless:
return res.value
return res
def __neg__( self ):
"""!
@brief Overload negative sign operator (-self)
@return Object of same class with result
"""
res = self.__class__( -self.__value, self.__unit,
*self.__args, **self.__kwargs )
if res.isUnitless:
return res.value
return res
def __lt__( self, other ):
"""!
@brief Overload < operator (self < other)
@param other other object to compare ourselves to
"""
if not isinstance( other, PObject ):
if not (self.isUnitless or other == 0):
raise ValueError( "can only compare like objects" )
return self.__value < other
if self.unit != other.unit:
raise ValueError( "can only compare objects with like units" )
return self.__value < other.value
def __le__( self, other ):
"""!
@brief Overload <= operator (self <= other)
@param other other object to compare ourselves to
@return boolean value as result
"""
if not isinstance( other, PObject ):
if not (self.isUnitless or other == 0):
raise ValueError( "can only compare like objects" )
return self.__value <= other
if self.unit != other.unit:
raise ValueError( "can only compare objects with like units" )
return self.__value <= other.value
def __gt__( self, other ):
"""!
@brief Overload > operator (self > other)
@param other other object to compare ourselves to
@return boolean value as result
"""
if not isinstance( other, PObject ):
if not (self.isUnitless or other == 0):
raise ValueError( "can only compare like objects" )
return self.__value > other
if self.unit != other.unit:
raise ValueError( "can only compare objects with like units" )
return self.__value > other.value
def __ge__( self, other ):
"""!
@brief Overload >= operator (self >= other)
@param other other object to compare ourselves to
@return boolean value as result
"""
if not isinstance( other, PObject ):
if not (self.isUnitless or other == 0):
raise ValueError( "can only compare like objects" )
return self.__value >= other
if self.unit != other.unit:
raise ValueError( "can only compare objects with like units" )
return self.__value >= other.value
def __eq__( self, other ):
"""!
@brief Overload == operator (self == other)
@param other other object to compare ourselves to
@return boolean value as result
"""
if not isinstance( other, PObject ):
if not (self.isUnitless or other == 0):
return False
return self.__value == other
return self.__value == other.value and self.__unit == other.unit
def __ne__( self, other ):
"""!
@brief Overload != operator (self != other)
@param other other object to compare ourselves to
@return boolean value as result
"""
if not isinstance( other, PObject ):
if not (self.isUnitless or other == 0):
return True
return self.value != other
return self.__value != other.value or self.__unit != other.unit
def __bool__( self ):
"""!
@brief Obtain truth value of the object, which is the truth value of its
value.
"""
return bool( self.__value )
def __float__(self):
"""!
@brief Make float work on PObjects.
"""
return float( self.__value )
@property
def value( self ):
"""!
@brief Obtain the value of a PObject.
"""
return self.__value
@property
def unit( self ):
"""!
@brief Obtain the SI.Unit of a PObject as (base) SI.Unit.
"""
return self.__unit
@property
def standardizedTuple( self ):
"""!
@brief Obtain a standardized tuple of value and standard (i.e. not
necessarily base) SI unit.
"""
return SI.Prefix.standardizeTuple( (self.__value, self.__unit) )
@property
def isUnitless( self ):
"""!
@brief Test whether object is unitless.
"""
return self.__unit.isUnitless
@property
def digits( self ):
"""!
@brief Obtain the digits of a PObject.
"""
return self.__digits
@digits.setter
def digits( self, value ):
"""!
@brief Set the digits of a PObject.
"""
self.__digits = value
return
@property
def precision( self ):
"""!
@brief Obtain the precision of a PObject (mostly for Constants).
"""
return self.__precision
@property
def _strictAscii( self ):
"""!
@brief Obtain the strictAscii property of a PObject.
"""
return self.__strictAscii
@property
def _args( self ):
"""!
@brief Obtain non-keyword arguments we were called with
"""
return self.__args
@property
def _kwargs( self ):
"""!
@brief Obtain keyword arguments we were called with