forked from juanre/magnitude
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmagnitude.py
1139 lines (967 loc) · 33.6 KB
/
magnitude.py
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
# magnitude -- a module for computing with numbers with units.
#
# Version 0.9.5, June 2013
#
# Copyright (C) 2006-2013 Juan Reyero (http://juanreyero.com).
#
# Licensed under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the
# License.
#
# Home page: http://juanreyero.com/open/magnitude/
"""
A physical quantity is a number with a unit, like 10 km/h. Units can be any
of the SI units, plus a bunch of non-SI, bits, dollars, and any combination
of them. They can include the standard SI prefixes. Magnitude can operate
with physical quantities, parse their units, and print them. You don't have
to worry about unit consistency or conversions; everything is handled
transparently. By default output is done in basic SI units, but you can
specify any output unit, as long as it can be reduced to the basic units of
the physical quantity.
The basic units understood by the magnitude module are:
indicator meaning
--------- -------
$ dollar ('dollar' is also acceptable)
A ampere
b bit
cd candela
K degrees Kelvin
kg kilograms
m meters
mol amount of substance
s seconds
From these basic units you can derive many other units. The magnitude
package predefines these derived units:
Bq becquerel
C coulomb
c speed of light (m/s)
day
degC degree Celsius
dpi dots per inch
F farad
ft feet ("'" is also acceptable)
g gram
gravity acceleration due to gravity (m/s**2)
Gy gray
H henry
h hour
Hz Hertz
inch ('"' is also acceptable)
ips inches per second
J joule
kat katal
l liter
lightyear light year
lm lumen
lpi lines per inch
lux
min minute
N newton
ohm
Pa pascal
S siemens
Sv sievert
T tesla
V volt
W watt
Wb weber
year
B byte
Two magnitudes have no units, 'rad' (radian - unit of plane angle) and 'sr'
(steradian - unit of solid angle).
Any of the above units can be augmented with the following set of scale
prefixes:
letter scale name
------ ----- ----
y 1e-24 yocto
z 1e-21 zepto
a 1e-18 atto
f 1e-15 femto
p 1e-12 pico
n 1e-9 nano
u 1e-6 micro
m 1e-3 mili
c 1e-2 centi
d 1e-1 deci
k 1e3 kilo
Ki 2^10 Kibi
M 1e6 mega
Mi 2^20 Mebi
G 1e9 giga
Gi 2^30 Gibi
T 1e12 tera
Ti 2^40 Tebi
P 1e15 peta
Pi 2^50 Pebi
E 1e18 exa
Ei 2^60 Exbi
Z 1e21 zetta
Y 1e24 yotta
Exported symbols
----------------
- Magnitude [class] --- Numbers with units; math operations are overloaded
- mg(number, unit, ounit='') --- Construct a Magnitude
- ensmg(m, unit='') --- Tries to build a Magnitude out of something
- newmag(indicator, mag) --- Intern a new magnitude with its name
- MagnitudeError [class] --- Magnitude error handling
Defining new magnitudes
-----------------------
You can define new magnitudes by instantiating the Magnitude class. Suppose
you want to define pounds as a magnitude and associate with it the unit
'lb'. A pound is 0.45359237 kilograms, so we have
>>> lb = Magnitude(0.45359237, kg=1)
To make it recognized automatically you also have to introduce it to
the system:
>>> new_mag('lb', lb)
You can then use it as you would any other predefined physical quantity:
>>> me = mg(180, 'lb')
>>> print me.ounit('kg').toval()
81.6466266
The following online references provide more detail about physical units and
the SI system.
http://physics.nist.gov/cuu/Units/units.html
http://en.wikipedia.org/wiki/SI
http://www.gnu.org/software/units/units.html for units.dat
http://www.cip.physik.uni-muenchen.de/~tf/misc/etools.lisp
This code was very much inspired by
http://www.cs.utexas.edu/users/novak/units.html
and its associated paper,
http://www.cs.utexas.edu/users/novak/units95.html
Bits and bytes (2009-11-03)
---------------------------
A previous version of the library used "bit" for bit and "b" for byte,
leaving B for Bel. Following Michael Scheper's suggestion we follow
now IEEE 1541 and use "b" for bit and "B" for byte. If the need
arises I'll implement ad-hoc esupport for dB, but for the time being
there is none.
"""
import re, math
import types
# Base magnitude names and prefixes. The _mags dictionary, initialized
# at the end, will contain all the known magnitudes. Units are
# 9-element arrays, each element the exponent of the unit named by the
# Uname in the same position.
class MagnitudeError(Exception):
pass
_mags = {}
_unames = ['m', 's', 'K', 'kg', 'A', 'mol', 'cd', '$', 'b']
_prefix = {'y': 1e-24, # yocto
'z': 1e-21, # zepto
'a': 1e-18, # atto
'f': 1e-15, # femto
'p': 1e-12, # pico
'n': 1e-9, # nano
'u': 1e-6, # micro
'm': 1e-3, # mili
'c': 1e-2, # centi
'd': 1e-1, # deci
'k': 1e3, # kilo
'M': 1e6, # mega
'G': 1e9, # giga
'T': 1e12, # tera
'P': 1e15, # peta
'E': 1e18, # exa
'Z': 1e21, # zetta
'Y': 1e24, # yotta
# Binary prefixes, approved by the International
# Electrotechnical Comission in 1998. Since then, kb means
# 1000 bytes; for 1024 bytes use Kib (note the capital K in
# the binary version, and the lower case for the b of byte,
# see comment in byte definition below).
'Ki': 2 ** 10, # Kibi (<- kilo, 10^3)
'Mi': 2 ** 20, # Mebi (<- mega, 10^6)
'Gi': 2 ** 30, # Gibi (<- giga, 10^9)
'Ti': 2 ** 40, # Tebi (<- tera, 10^12)
'Pi': 2 ** 50, # Pebi (<- peta, 10^15)
'Ei': 2 ** 60 # Exbi (<- exa, 10^18)
}
###### Default print formatting options
_default_prn_format = "%.*f"
_prn_format = _default_prn_format
_prn_prec = 4
_prn_units = True
def reset_default_format():
"""Resets the default output format.
By default the output format is "%.*f", where * gets replaced by
the output precision.
"""
global _prn_format
_prn_format = _default_prn_format
def default_format(fmt=None):
"""Get or set the default ouptut format.
Include a fmt if and where you need to specify the output
precision. Defaults to %.*f, where the * stands for the
precision. Do nothing if fmt is None.
Returns: default format.
>>> print mg(2, 'm2').sqrt()
1.4142 m
>>> default_format("%.2f")
'%.2f'
>>> print mg(2, 'm2').sqrt()
1.41 m
>>> reset_default_format()
"""
global _prn_format
if fmt is not None:
_prn_format = fmt
return _prn_format
def output_precision(prec=None):
"""Get or set the output precision.
Package default is 4. Do nothing is prec is None.
Returns: default precision.
>>> default_format("%.*f")
'%.*f'
>>> print mg(2, 'm2').sqrt()
1.4142 m
>>> output_precision(6)
6
>>> print mg(2, 'm2').sqrt()
1.414214 m
>>> output_precision(4)
4
"""
global _prn_prec
if prec is not None:
_prn_prec = prec
return _prn_prec
def output_units(un=None):
"""Enable or disable the output of units when printing.
By default output of units is enabled. Do nothing if un is None.
When disabled (un is False) print of Magnitudes will produce only
numbers.
Return: True if output of units enabled, False otherwise.
>>> print mg(2, 'day')
2.0000 day
>>> output_units(False)
False
>>> print mg(2, 'day').ounit('s')
172800.0000
"""
global _prn_units
if un is not None:
_prn_units = un
return _prn_units
###### Resolution areas
def _res2num(res):
match = re.search(r'(\d+)x(\d+)', res)
if match:
return int(match.group(1)), int(match.group(2))
if (res[0] == '[') and (res[-1] == ']'):
return (int(res[1:-1]), int(res[1:-1]))
def _isres(res):
return (len(res) > 2) and (res[0] == '[') and (res[-1] == ']')
def _res2m2(res):
"""Convert resolution string to square meters.
Bracketed resolutions are used in the printing industry, to
denote the area of a pixel. Can be like [300x1200] or like [600]
(=[600x600]), meaning the area of square pixels of size 1"/300 x
1"/1200 and 1"/600 x 1"/600. The square brackes are intended to
show that we are talking about areas. This function converts them
to square meters.
>>> _res2m2("[600x600]")
1.792111111111111e-09
>>> _res2m2("[600]")
1.792111111111111e-09
>>> _res2m2("[150x300]")
1.4336888888888889e-08
"""
hr, vr = _res2num(res)
return 0.0254 * 0.0254 / (vr * hr)
# Definition of the magnitude type. Includes operator overloads.
def _numberp(n): ## Python has to have a decent way to do this!
return (isinstance(n, types.ComplexType) or
isinstance(n, types.FloatType) or
isinstance(n, types.IntType) or
isinstance(n, types.LongType))
class Magnitude():
def __init__(self, val, m=0, s=0, K=0, kg=0, A=0, mol=0, cd=0, dollar=0,
b=0):
self.val = val
self.unit = [m, s, K, kg, A, mol, cd, dollar, b]
self.out_unit = None
self.out_factor = None
self.oprec = None
self.oformat = None
def copy(self, with_format=False):
"""Builds and returns a copy of a magnitude.
The copy includes value and units. If with_format is set to
True the default output unit, output factor, output precision
and output format are also copied.
>>> a = mg(1000/3., 'mm')
>>> print a.output_prec(2)
333.33 mm
>>> print a.copy()
0.3333 m
>>> print a.copy(with_format=True)
333.33 mm
"""
cp = Magnitude(self.val, *self.unit)
if with_format:
cp.out_unit = self.out_unit
cp.out_factor = self.out_factor
cp.oprec = self.oprec
cp.oformat = self.oformat
return cp
def toval(self, ounit=''):
"""Returns the numeric value of a magnitude.
The value is given in ounit or in the Magnitude's default
output unit.
>>> v = mg(100, 'km/h')
>>> v.toval()
100.0
>>> v.toval(ounit='m/s')
27.77777777777778
"""
m = self.copy()
if not ounit:
ounit = self.out_unit
if ounit:
out_factor = self.sunit2mag(ounit)
m._div_by(out_factor)
return m.val
def __str__(self):
oformat = self.oformat
oprec = self.oprec
if oprec is None:
oprec = _prn_prec
if oformat is None:
oformat = _prn_format
if self.out_unit:
m = self.copy()
m._div_by(self.out_factor)
if '*' in oformat: # requires the precision arg
st = oformat % (oprec, m.val)
else:
st = oformat % (m.val)
if _prn_units:
return st + ' ' + self.out_unit.strip()
return st
if '*' in oformat:
st = oformat % (oprec, self.val)
else:
st = oformat % (self.val)
if not _prn_units:
return st
u = self.unit
num = ' ' # numerator
for i in range(len(_unames)):
if u[i] == 1:
num = num + _unames[i] + ' '
elif u[i] > 0:
num = num + _unames[i] + str(u[i]) + ' '
den = '' # denominator
for i in range(len(_unames)):
if u[i] == -1:
den = den + _unames[i] + ' '
elif u[i] < 0:
den = den + _unames[i] + str(-u[i]) + ' '
if den:
if num == ' ':
num += '1 '
st += (num + '/ ' + den)
elif num != ' ':
st += num
return st.strip()
def term2mag(self, s):
"""Converts a string with units to a Magnitude.
Can't divide: use with the numerator and the denominator
separately (hence the "term"). Returns the Magnitude that the
string represents. Units are separated by spaces, powers are
integers following the unit name.
Cannot parse fractional units. Cannot parse multi-digit
exponents.
>>> a = mg(1, '')
>>> print a.term2mag('V2 A')
1.0000 m4 kg2 / s6 A
>>> print a.term2mag('kft year') # kilo-feet year
9618551037.0820 m s
"""
m = Magnitude(1.0)
units = re.split(r'\s', s)
for u in units:
if re.search(r'[^\s]', u):
exp = 1
if re.search(r'\d$', u):
exp = int(u[-1])
u = u[0:-1]
if _mags.has_key(u):
u = _mags[u].copy()
elif ((len(u)>=3) and _prefix.has_key(u[0:2]) and
_mags.has_key(u[2:])):
pr = _prefix[u[0:2]]
u = _mags[u[2:]].copy(); u.val = pr * u.val
elif ((len(u)>=2) and _prefix.has_key(u[0]) and
_mags.has_key(u[1:])):
pr = _prefix[u[0]]
u = _mags[u[1:]].copy(); u.val = pr * u.val
elif _isres(u):
u = Magnitude(_res2m2(u), m=2)
elif u == '':
u = Magnitude(1.0)
else:
raise MagnitudeError("Don't know about unit %s" % u)
for i in range(exp):
m._mult_by(u)
return m
def sunit2mag(self, unit=''):
"""Convert a units string to a Magnitude.
Uses term2mag to convert a string with units, possibly
including a / to separate a numerator and a denominator, to a
Magnitude.
>>> a = mg(1, '')
>>> a.sunit2mag('m/s').toval()
1.0
>>> a.sunit2mag('km/h').toval()
0.2777777777777778
>>> print a.sunit2mag('W h')
3600.0000 m2 kg / s2
>>> print a.sunit2mag('W h').ounit('J')
3600.0000 J
>>> print a.sunit2mag('m2 kg / s3 Pa')
1.0000 m3 / s
>>> print a.sunit2mag('m2 kg/s3').ounit('W')
1.0000 W
"""
m = Magnitude(1.0)
if unit:
q = re.split(r'/', unit)
if re.search(r'[^\s]', q[0]):
m._mult_by(self.term2mag(q[0]))
if (len(q) == 2) and re.search(r'[^\s]', q[1]):
m._div_by(self.term2mag(q[1]))
return m
def dimensionless(self):
"""True if the magnitude's dimension exponents are all zero.
>>> mg(2, 'K').dimensionless()
False
>>> mg(2, 'rad').dimensionless()
True
"""
return self.unit == [0] * 9
def dimension(self):
"""Return the dimension of the unit in internal (array) format.
>>> mg(2, 'J').dimension()
[2, -2, 0, 1, 0, 0, 0, 0, 0]
"""
return self.unit[:]
def has_dimension(self, u):
"""Returns true if the dimension of the magnitude matches u:
>>> s = mg(120, 'km/h') * (2, 'day')
>>> s.has_dimension('m')
True
>>> print s.ounit('cm')
576000000.0000 cm
"""
o = self.sunit2mag(u)
return (self.unit == o.unit)
def _mult_by(self, m):
self.val *= m.val
for i in range(len(self.unit)):
self.unit[i] = self.unit[i] + m.unit[i]
self.out_unit = None
def _div_by(self, m):
self.val /= m.val
for i in range(len(self.unit)):
self.unit[i] = self.unit[i] - m.unit[i]
self.out_unit = None
def ounit(self, unit):
"""Set the preferred unit for output, returning the Magnitude.
>>> a = mg(1, 'kg m2 / s2')
>>> print a
1.0000 kg m2 / s2
>>> print a.ounit('J')
1.0000 J
>>> print a
1.0000 J
"""
self.out_unit = unit
self.out_factor = self.sunit2mag(unit)
if self.out_factor.unit != self.unit:
raise MagnitudeError("Inconsistent Magnitude units: %s, %s" %
(self.out_factor.unit, self.unit))
return self
def to_base_units(self):
"""Forgets about the output unit and goes back to base units:
>>> a = mg(10, 'km')
>>> print a
10.0000 km
>>> print a.to_base_units()
10000.0000 m
"""
self.out_unit = None
self.out_factor = None
return self
def output_prec(self, prec):
"""Set the output precision for the Magnitude.
If not set, the the module's default will be used, set and
queried with output_precision(prec).
>>> a = mg(5, 'm3') ** (1/3.) # Careful with precedence of **
>>> print a
1.7100 m
>>> print a.output_prec(1)
1.7 m
"""
self.oprec = prec
return self
def output_format(self, oformat):
"""Set the output format for the Magnitude.
If not set, the module's default will be used, set and queried
with default_format(fmt). Default value is "%.*f". The star
will be replaced by the expected output precision.
>>> a = mg(5, 'm2').sqrt()
>>> print a
2.2361 m
>>> print a.output_format("%03d")
002 m
"""
self.oformat = oformat
return self
def __coerce__(self, m):
"""Force tuples or numbers into Magnitude."""
if not isinstance(m, Magnitude):
if type(m) == tuple:
if len(m) == 2:
r = Magnitude(m[0])
r._mult_by(self.sunit2mag(m[1]))
return self, r
elif len(m) == 1:
return self, Magnitude(m[0])
else:
return None
elif _numberp(m):
return self, Magnitude(m)
else:
return None
else:
return self, m
def __add__(self, m):
"""Add Magnitude instances.
>>> print mg(10, 'm') + (20, 'km') + (30, 'lightyear')
283821914177444000.0000 m
"""
if m.unit != self.unit:
raise MagnitudeError("Incompatible units: %s and %s" %
(m.unit, self.unit))
r = self.copy()
r.val += m.val
return r
def __radd__(self, m):
"""Add Magnitude instances. See __add__. """
return self.__add__(m)
def __iadd__(self, m):
"""Add Magnitude instances. See __add__. """
if m.unit != self.unit:
raise MagnitudeError("Incompatible units: %s and %s" %
(m.unit, self.unit))
self.val += m.val
return self
def __sub__(self, m):
"""Substract Magnitude instances.
>>> print mg(20, 'm/s') - (1, 'km/h')
19.7222 m / s
"""
if m.unit != self.unit:
raise MagnitudeError("Incompatible units: %s and %s" %
(m.unit, self.unit))
r = self.copy()
r.val -= m.val
return r
def __rsub__(self, m):
"""Substract Magnitude instances. See __sub__."""
return m.__sub__(self)
def __isub__(self, m):
"""Substract Magnitude instances. See __sub__."""
if m.unit != self.unit:
raise MagnitudeError("Incompatible units: %s and %s" %
(m.unit, self.unit))
self.val -= m.val
return self
def __mul__(self, m):
"""Multiply Magnitude instances.
>>> print mg(10, 'm/s') * (10, 's')
100.0000 m
"""
r = self.copy()
r._mult_by(m)
return r
def __rmul__(self, m):
"""Multiply Magnitude instances. See __mul__."""
r = self.copy()
r._mult_by(m)
return r
def __imul__(self, m):
"""Multiply Magnitude instances. See __mul__."""
self._mult_by(m)
return self
def __div__(self, m):
"""Divide Magnitude instances.
>>> print mg(100, 'V') / (10, 'kohm')
0.0100 A
"""
r = self.copy()
r._div_by(m)
return r
def __truediv__(self, m):
"""Divide Magnitude instances when "from __future__ import division"
is in effect.
>>> print mg(100, 'V') / (1, 'kohm')
0.1000 A
"""
r = self.copy()
r._div_by(m)
return r
def __rdiv__(self, m):
"""Divide Magnitude instances. See __div__."""
r = self.copy()
m._div_by(r)
return m
def __rtruediv__(self, m):
"""Divide Magnitude instances. See __div__."""
r = self.copy()
m._div_by(r)
return m
def __idiv__(self, m):
"""Divide Magnitude instances. See __div__."""
self._div_by(m)
return self
def __itruediv__(self, m):
"""Divide Magnitude instances. See __div__."""
self._div_by(m)
return self
def __mod__(self, n):
"""Modulus of a Magnitude by a number or a Magnitude.
Unit is that of the left hand side operator.
>>> print mg(10, 'm/s') % 3
1.0000 m / s
>>> print mg(10, 'm/s') % (3, 'W')
1.0000 m / s
"""
r = self.copy()
r.val = r.val % ensmg(n).toval()
return r
def __imod__(self, n):
"""Modulus of a Magnitude by a number or a Magnitude. See __mod__."""
self.val %= n.val
for i in range(len(self.unit)):
self.unit[i] = self.unit[i] - n.unit[i]
self.out_unit = None
return self
def __floordiv__(self, m):
"""Floordiv of two Magnitude instances.
>>> print mg(10, 'm/s') // (3, 's')
3.0000 m / s2
>>> print mg(-10, 'm/s') // (3, 'm')
-4.0000 1 / s
"""
r = self.copy()
r._div_by(m)
r.val = math.floor(r.val)
return r
def __ifloordiv__(self, m):
"""Floordiv of two Magnitude instances. See __floordiv__."""
self._div_by(m)
self.val = math.floor(self.val)
return self
def __divmod__(self, m):
"""Floordiv and remainder of two Magnitude instances.
>>> [ str(i) for i in divmod(mg(10, 'm/s'), (3, 's')) ]
['3.0000 m / s2', '1.0000 m / s']
"""
return (self.__floordiv__(m), self.__mod__(m))
def __rdivmod__(self, m):
"""Floordiv and remainder of two Magnitude instances. See __divmod___"""
return (m.__floordiv__(self), m.__mod__(self))
def __pow__(self, n, modulo=None):
"""Return a Magnitude to the power n.
If modulo is present return the result modulo it.
>>> print mg(10, 'm/s') ** 2
100.0000 m2 / s2
>>> print pow(mg(10, 'km/h'), mg(2)) # Exponent cannot have dimension
7.7160 m2 / s2
>>> print pow(mg(10, 'm/s'), 2, 3)
1.0000 m2 / s2
"""
r = self.copy()
if modulo and (r.val == math.floor(r.val)): # it's an integer
# might have been converted to float during creation,
# modulo only works when all are int
r.val = int(r.val)
if isinstance(n, Magnitude): # happens when called as a ** n
if not n.dimensionless():
raise MagnitudeError("Cannot use a dimensional number as"
"exponent, %s" % (n))
n = n.val
r.val = pow(r.val, n, modulo)
for i in range(len(r.unit)):
r.unit[i] *= n
return r
def __ipow__(self, n):
"""Power of a Magnitude. See __pow___."""
if not n.dimensionless():
raise MagnitudeError("Cannot use a dimensional number as"
"exponent, %s" % (n))
n = n.val
self.val = pow(self.val, n)
for i in range(len(self.unit)):
self.unit[i] *= n
return self
def __neg__(self):
"""Multiply by -1 the value of the Magnitude."""
r = self.copy()
r.val = -r.val
return r
def __pos__(self):
"""Unary plus operator. """
return self.copy()
def __abs__(self):
"""Absolute value of a Magnitude.
>>> print abs(mg(-10, 'm'))
10.0000 m
"""
r = self.copy()
r.val = abs(r.val)
return r
def __cmp__(self, m):
"""Compare two Magnitude instances with the same dimensions.
>>> print mg(10, 'm/s') > (11, 'km/h')
True
>>> print mg(1, 'km') == (1000, 'm')
True
"""
if m.unit != self.unit:
raise MagnitudeError("Incompatible units in comparison: %s and %s" %
(m.unit, self.unit))
return cmp(self.val, m.val)
def __int__(self):
"""Return the value of a Magnitude coerced to integer.
Note that this will happen to the value in the default output unit:
>>> print int(mg(10.5, 'm/s'))
10
>>> print int(mg(10.5, 'm/s').ounit('km/h'))
37
"""
return int(self.toval())
def __long__(self):
"""Return the value of a Magnitude coerced to long. See __int__."""
return long(self.toval())
def __float__(self):
"""Return the value of a Magnitude coerced to float. See __int__."""
return float(self.toval())
def ceiling(self):
"""Ceiling of a Magnitude's value in canonical units.
>>> print mg(10.2, 'm/s').ceiling()
11.0000 m / s
>>> print mg(3.6, 'm/s').ounit('km/h').ceiling()
4.0000 m / s
>>> print mg(50.3, 'km/h').ceiling()
14.0000 m / s
"""
r = self.copy(with_format=False)
r.val = math.ceil(r.val)
return r
def floor(self):
"""Floor of a Magnitude's value in canonical units.
>>> print mg(10.2, 'm/s').floor()
10.0000 m / s
>>> print mg(3.6, 'm/s').ounit('km/h').floor()
3.0000 m / s
>>> print mg(50.3, 'km/h').floor()
13.0000 m / s
"""
r = self.copy()
r.val = math.floor(r.val)
return r
def round(self):
"""Round a Magnitude's value in canonical units.
>>> print mg(10.2, 'm/s').round()
10.0000 m / s
>>> print mg(3.6, 'm/s').ounit('km/h').round()
4.0000 m / s
>>> print mg(50.3, 'km/h').round()
14.0000 m / s
"""
r = self.copy()
r.val = round(r.val)
return r
def to_bits(self):
return Magnitude(math.ceil(math.log(self.val) / math.log(2.0)),
b=1)
def sqrt(self):
"""Square root of a magnitude.
>>> print mg(4, 'm2/s2').sqrt()
2.0000 m / s
>>> print mg(2, 'm/s').sqrt()
1.4142 m0.5 / s0.5
"""
return self ** 0.5
# Some helper functions
def mg(v, unit='', ounit=''):
"""Builds a Magnitude from a number and a units string. Specify
the preferred output unit with ounit (by default equals to unit).
If ounit and unit have different dimensionalities unit will be
used.
>>> print mg(10, 'm/s')
10.0000 m/s
>>> a = mg(10, 'm/s', 'km/h')
>>> print a
36.0000 km/h
>>> a = mg(10, 'm/s', 'kg/m')
>>> print a
10.0000 m/s
>>> a = mg(1, 'B')
>>> print a
1.0000 B
>>> print a.ounit('b')
8.0000 b
>>> a = mg(1024, 'B')
>>> print a.ounit('b')
8192.0000 b
>>> print a.ounit('KiB')
1.0000 KiB
"""
m = Magnitude(v)
if unit:
u = m.sunit2mag(unit)
m._mult_by(u)
if not ounit or not mg(1, unit).has_dimension(ounit):
ounit = unit
return m.ounit(ounit)
def ensmg(m, unit=''):
"""Converts something to a Magnitude.
>>> print ensmg(10, 'Hz')
10.0000 Hz
>>> print ensmg(ensmg(1000, 'Hz'))
1000.0000 Hz
>>> a = (4, 'mol')
>>> print ensmg(a)
4.0000 mol