forked from OpenMDAO/OpenMDAO
-
Notifications
You must be signed in to change notification settings - Fork 0
/
units.py
1179 lines (972 loc) · 33.1 KB
/
units.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
"""
Classes and functions to support unit conversion.
The module provides a basic set of predefined physical quantities
in its built-in library; however, it also supports generation of
personal libararies which can be saved and reused.
This module is based on the PhysicalQuantities module
in Scientific Python, by Konrad Hinsen. Modifications by
Justin Gray.
"""
import sys
import re
import os.path
from collections import OrderedDict
from configparser import RawConfigParser as ConfigParser
# pylint: disable=E0611, F0401
from math import floor, pi
import numpy as np
####################################
# Class Definitions
####################################
class NumberDict(OrderedDict):
"""
Dictionary storing numerical values.
An instance of this class acts like an array of numbers with
generalized (non-integer) indices. A value of zero is assumed
for undefined entries. NumberDict instances support addition
and subtraction with other NumberDict instances, and multiplication
and division by scalars.
"""
def __getitem__(self, item):
"""
Get the item, or 0.
Parameters
----------
item : key
key to get the item
Returns
-------
int
value of the given key
"""
try:
return dict.__getitem__(self, item)
except KeyError:
return 0
def __coerce__(self, other):
"""
Change other dict to NumberDicts.
Parameters
----------
other : dict
the dict instance to be coerced
Returns
-------
NumberDict
new NumberDict with keys/values from original
"""
if isinstance(other, dict):
other = NumberDict(other)
return self, other
def __add__(self, other):
"""
Add another NumberDict to myself.
Parameters
----------
other : NumberDict
the other NumberDict Instance
Returns
-------
NumberDict
new NumberDict with self+other values
"""
sum_dict = NumberDict()
for k, v in self.items():
sum_dict[k] = v
for k, v in other.items():
sum_dict[k] = sum_dict[k] + v
return sum_dict
def __sub__(self, other):
"""
Add another NumberDict from myself.
Parameters
----------
other : NumberDict
the other NumberDict Instance
Returns
-------
NumberDict
new NumberDict instance, with self-other values
"""
sum_dict = NumberDict()
for k, v in self.items():
sum_dict[k] = v
for k, v in other.items():
sum_dict[k] = sum_dict[k] - v
return sum_dict
def __rsub__(self, other):
"""
Add subtract myself from another NumberDict.
Parameters
----------
other : NumberDict
the other NumberDict Instance
Returns
-------
NumberDict
new NumberDict instance, with other-self values
"""
sum_dict = NumberDict()
for k, v in other.items():
sum_dict[k] = v
for k, v in self.items():
sum_dict[k] = sum_dict[k] - v
return sum_dict
def __mul__(self, other):
"""
Multiply myself by another NumberDict.
Parameters
----------
other : NumberDict
the other NumberDict Instance
Returns
-------
NumberDict
new NumberDict instance, with other*self values
"""
new = NumberDict()
for key, value in self.items():
new[key] = other * value
return new
__rmul__ = __mul__
def __div__(self, other):
"""
Divide myself by another NumberDict.
Parameters
----------
other : int
value to divide by
Returns
-------
NumberDict
new NumberDict instance, with self/other values
"""
new = NumberDict()
for key, value in self.items():
new[key] = value / other
return new
__truediv__ = __div__ # for python 3
def __repr__(self):
"""
Return a string deceleration of myself.
Parameters
----------
other : NumberDict
the other NumberDict Instance
Returns
-------
str
str representation for the creation of this NumberDict
"""
return repr(dict(self))
class PhysicalUnit(object):
"""
Physical unit.
A physical unit is defined by a name (possibly composite), a scaling
factor, and the exponentials of each of the SI base units that enter into
it. Units can be multiplied, divided, and raised to integer powers.
Parameters
----------
names : dict or str
A dictionary mapping each name component to its
associated integer power (e.g., C{{'m': 1, 's': -1}})
for M{m/s}). As a shorthand, a string may be passed
which is assigned an implicit power 1.
factor : float
A scaling factor.
powers : list of int
The integer powers for each of the nine base units.
offset : float
An additive offset to the base unit (used only for temperatures).
Attributes
----------
_names : dict or str
A dictionary mapping each name component to its
associated integer power (e.g., C{{'m': 1, 's': -1}})
for M{m/s}). As a shorthand, a string may be passed
which is assigned an implicit power 1.
_factor : float
A scaling factor.
_powers : list of int
The integer powers for each of the nine base units.
_offset : float
An additive offset to the base unit (used only for temperatures)
"""
def __init__(self, names, factor, powers, offset=0):
"""
Initialize all attributes.
"""
if isinstance(names, str):
self._names = NumberDict(((names, 1),))
else:
self._names = names
self._factor = float(factor)
self._offset = float(offset)
self._powers = powers
def __repr__(self):
"""
Get the string representation of this unit.
Returns
-------
str
str representation of how to instantiate this PhysicalUnit
"""
return 'PhysicalUnit(%s,%s,%s,%s)' % (self._names, self._factor,
self._powers, self._offset)
def __str__(self):
"""
Convert myself to string.
Returns
-------
str
str representation of a PhysicalUnit
"""
return '<PhysicalUnit ' + self.name() + '>'
def __lt__(self, other):
"""
Compare myself to other.
Parameters
----------
other : PhysicalUnit
The other physical unit to be compared to
Returns
-------
bool
self._factor < other._factor
"""
if self._powers != other._powers or self._offset != other._offset:
raise TypeError(f"Units '{self.name()}' and '{other.name()}' are incompatible.")
return self._factor < other._factor
def __gt__(self, other):
"""
Compare myself to other.
Parameters
----------
other : PhysicalUnit
The other physical unit to be compared to
Returns
-------
bool
self._factor > other._factor
"""
if self._powers != other._powers:
raise TypeError(f"Units '{self.name()}' and '{other.name()}' are incompatible.")
return self._factor > other._factor
def __eq__(self, other):
"""
Test for equality.
Parameters
----------
other : PhysicalUnit
The other physical unit to be compared to
Returns
-------
bool
true if _factor, _offset, and _powers all match
"""
return (self._factor == other._factor and
self._offset == other._offset and
self._powers == other._powers)
def __mul__(self, other):
"""
Multiply myself by other.
Parameters
----------
other : PhysicalUnit
The other physical unit to be compared to
Returns
-------
PhysicalUnit
new PhysicalUnit instance representing the product of two units
"""
if self._offset != 0 or (isinstance(other, PhysicalUnit) and
other._offset != 0):
raise TypeError(f"Can't multiply units: either '{self.name()}' or '{other.name()}' "
"has a non-zero offset.")
if isinstance(other, PhysicalUnit):
return PhysicalUnit(self._names + other._names,
self._factor * other._factor,
[a + b for a, b in zip(self._powers, other._powers)])
else:
return PhysicalUnit(self._names + {str(other): 1},
self._factor * other,
self._powers,
self._offset * other)
__rmul__ = __mul__
def __div__(self, other):
"""
Divide myself by other.
Parameters
----------
other : PhysicalUnit
The other physical unit to be operated on
Returns
-------
PhysicalUnit
new PhysicalUnit instance representing the self/other
"""
if self._offset != 0 or (isinstance(other, PhysicalUnit) and
other._offset != 0):
raise TypeError(f"Can't divide units: either '{self.name()}' or '{other.name()}' "
"has a non-zero offset.")
if isinstance(other, PhysicalUnit):
return PhysicalUnit(self._names - other._names,
self._factor / other._factor,
[a - b for (a, b) in zip(self._powers,
other._powers)])
else:
return PhysicalUnit(self._names + {str(other): -1},
self._factor / float(other), self._powers)
__truediv__ = __div__ # for python 3
def __rdiv__(self, other):
"""
Divide other by myself.
Parameters
----------
other : PhysicalUnit
The other physical unit to be operated on
Returns
-------
PhysicalUnit
new PhysicalUnit instance representing the other/self
"""
return PhysicalUnit({str(other): 1} - self._names,
float(other) / self._factor,
[-x for x in self._powers])
__rtruediv__ = __rdiv__
def __pow__(self, power):
"""
Raise myself to a power.
Parameters
----------
power : float or int
power to raise self by
Returns
-------
PhysicalUnit
new PhysicalUnit of self^power
"""
if self._offset != 0:
raise TypeError(f"Can't exponentiate unit '{self.name()}' because it "
"has a non-zero offset.")
if isinstance(power, int):
return PhysicalUnit(power * self._names, pow(self._factor, power),
[x * power for x in self._powers])
if isinstance(power, float):
inv_exp = 1. / power
rounded = int(floor(inv_exp + 0.5))
if abs(inv_exp - rounded) < 1.e-10:
if all([x % rounded == 0 for x in self._powers]):
f = self._factor**power
p = [x / rounded for x in self._powers]
if all([x % rounded == 0 for x in self._names.values()]):
names = self._names / rounded
else:
names = NumberDict()
if f != 1.:
names[str(f)] = 1
for x, name in zip(p, _UNIT_LIB.base_names):
names[name] = x
return PhysicalUnit(names, f, p)
raise TypeError(f"Can't exponentiate unit '{self.name()}': "
"only integer and inverse integer exponents are allowed.")
def in_base_units(self):
"""
Return the base unit equivalent of this unit.
Returns
-------
PhysicalUnit
The equivalent base unit.
"""
num = ''
denom = ''
for unit, power in zip(_UNIT_LIB.base_names, self._powers):
if power < 0:
denom = denom + '/' + unit
if power < -1:
denom = denom + '**' + str(-power)
elif power > 0:
num = num + '*' + unit
if power > 1:
num = num + '**' + str(power)
if len(num) == 0:
num = '1'
else:
num = num[1:]
return _find_unit(num + denom)
def conversion_tuple_to(self, other):
"""
Compute the tuple of (factor, offset) for conversion.
Parameters
----------
other : PhysicalUnit
Another unit.
Returns
-------
Tuple with two floats
The conversion factor and offset from this unit to another unit.
"""
if self._powers != other._powers:
raise TypeError(f"Units '{self.name()}' and '{other.name()}' are incompatible.")
# let (s1,d1) be the conversion tuple from 'self' to base units
# (ie. (x+d1)*s1 converts a value x from 'self' to base units,
# and (x/s1)-d1 converts x from base to 'self' units)
# and (s2,d2) be the conversion tuple from 'other' to base units
# then we want to compute the conversion tuple (S,D) from
# 'self' to 'other' such that (x+D)*S converts x from 'self'
# units to 'other' units
# the formula to convert x from 'self' to 'other' units via the
# base units is (by definition of the conversion tuples):
# ( ((x+d1)*s1) / s2 ) - d2
# = ( (x+d1) * s1/s2) - d2
# = ( (x+d1) * s1/s2 ) - (d2*s2/s1) * s1/s2
# = ( (x+d1) - (d1*s2/s1) ) * s1/s2
# = (x + d1 - d2*s2/s1) * s1/s2
# thus, D = d1 - d2*s2/s1 and S = s1/s2
factor = self._factor / other._factor
offset = self._offset - (other._offset * other._factor / self._factor)
return (factor, offset)
def is_compatible(self, other):
"""
Check for compatibility with another unit.
Parameters
----------
other : PhysicalUnit
Another unit.
Returns
-------
bool
Indicates if two units are compatible.
"""
return self._powers == other._powers
def is_dimensionless(self):
"""
Dimensionless PQ.
Returns
-------
bool
Indicates if this is dimensionless.
"""
return not any(self._powers)
def is_angle(self):
"""
Check if this PQ is an Angle.
Returns
-------
bool
Indicates if this an angle type.
"""
return (self._powers[_UNIT_LIB.base_types['angle']] == 1 and
sum(self._powers) == 1)
def set_name(self, name):
"""
Set the name.
Parameters
----------
name : str
The name.
"""
self._names = NumberDict()
self._names[name] = 1
def name(self):
"""
Compute the name of this unit.
Returns
-------
str
String representation of the unit.
"""
num = ''
denom = ''
for unit, power in self._names.items():
if power < 0:
denom = denom + '/' + unit
if power < -1:
denom = denom + '**' + str(-power)
elif power > 0:
num = num + '*' + unit
if power > 1:
num = num + '**' + str(power)
if len(num) == 0:
num = '1'
else:
num = num[1:]
return num + denom
####################################
# Module Functions
####################################
def _new_unit(name, factor, powers):
"""
Create new Unit.
Parameters
----------
name : str
The name of the new unit
factor : float
conversion factor to base units
powers : [int, ...]
power of base units
"""
_UNIT_LIB.unit_table[name] = PhysicalUnit(name, factor, powers)
def add_offset_unit(name, baseunit, factor, offset, comment=''):
"""
Adding Offset Unit.
Parameters
----------
name : str
The name of the unit.
baseunit : str or instance of PhysicalUnit
The unit upon which this offset unit is based.
factor : str
The scaling factor used to define the new unit w.r.t. base unit.
offset : float
Zero offset for new unit.
comment : str
Optional comment to describe unit.
"""
if isinstance(baseunit, str):
baseunit = _find_unit(baseunit)
# else, baseunit should be a instance of PhysicalUnit
# names, factor, powers, offset=0
unit = PhysicalUnit(baseunit._names, baseunit._factor * factor,
baseunit._powers, offset)
unit.set_name(name)
if name in _UNIT_LIB.unit_table:
if (_UNIT_LIB.unit_table[name]._factor != unit._factor or
_UNIT_LIB.unit_table[name]._powers != unit._powers):
raise KeyError(f"Unit '{name}' already defined with different factor or powers.")
_UNIT_LIB.unit_table[name] = unit
_UNIT_LIB.set('units', name, unit)
if comment:
_UNIT_LIB.help.append((name, comment, unit))
def add_unit(name, unit, comment=''):
"""
Adding Unit.
Parameters
----------
name : str
The name of the unit being added. For example: 'Hz'.
unit : str
Definition of the unit w.r.t. some other unit. For example: '1/s'.
comment : str
Optional comment to describe unit.
"""
if comment:
_UNIT_LIB.help.append((name, comment, unit))
if isinstance(unit, str):
unit = eval(unit, {'__builtins__': None, 'pi': pi}, # nosec: scope limited
_UNIT_LIB.unit_table)
unit.set_name(name)
if name in _UNIT_LIB.unit_table:
if (_UNIT_LIB.unit_table[name]._factor != unit._factor or
_UNIT_LIB.unit_table[name]._powers != unit._powers):
raise KeyError(f"Unit '{name}' already defined with different factor or powers.")
_UNIT_LIB.unit_table[name] = unit
_UNIT_LIB.set('units', name, unit)
_UNIT_LIB = ConfigParser()
def _do_nothing(string):
"""
Make the ConfigParser case sensitive.
Defines an optionxform for the units configparser that
does nothing, resulting in a case-sensitive parser.
Parameters
----------
string : str
The string to be transformed for the ConfigParser
Returns
-------
str
The same string that was given as a parameter.
"""
return string
_UNIT_LIB.optionxform = _do_nothing
def import_library(libfilepointer):
"""
Import a units library, replacing any existing definitions.
Parameters
----------
libfilepointer : file
New library file to work with.
Returns
-------
ConfigParser
Newly updated units library for the module.
"""
global _UNIT_LIB
global _UNIT_CACHE
_UNIT_CACHE = {}
_UNIT_LIB = ConfigParser()
_UNIT_LIB.optionxform = _do_nothing
# New in Python 3.2: read_file() replaces readfp().
if sys.version_info >= (3, 2):
_UNIT_LIB.read_file(libfilepointer)
else:
_UNIT_LIB.readfp(libfilepointer)
required_base_types = ['length', 'mass', 'time', 'temperature', 'angle']
_UNIT_LIB.base_names = list()
# used to is_angle() and other base type checking
_UNIT_LIB.base_types = dict()
_UNIT_LIB.unit_table = dict()
_UNIT_LIB.prefixes = dict()
_UNIT_LIB.help = list()
for prefix, factor in _UNIT_LIB.items('prefixes'):
factor, comma, comment = factor.partition(',')
_UNIT_LIB.prefixes[prefix] = float(factor)
base_list = [0] * len(_UNIT_LIB.items('base_units'))
for i, (unit_type, name) in enumerate(_UNIT_LIB.items('base_units')):
_UNIT_LIB.base_types[unit_type] = i
powers = list(base_list)
powers[i] = 1
# print '%20s'%unit_type, powers
# cant use add_unit because no base units exist yet
_new_unit(name, 1, powers)
_UNIT_LIB.base_names.append(name)
# test for required base types
missing = [utype for utype in required_base_types
if utype not in _UNIT_LIB.base_types]
if missing:
raise ValueError("Not all required base types were present in the config file. missing: "
f"{missing}, at least {required_base_types} required.")
_update_library(_UNIT_LIB)
return _UNIT_LIB
def update_library(filename):
"""
Update units in current library from `filename`.
Parameters
----------
filename : str or file
Source of units configuration data.
"""
if isinstance(filename, str):
inp = open(filename, 'rU')
else:
inp = filename
try:
cfg = ConfigParser()
cfg.optionxform = _do_nothing
# New in Python 3.2: read_file() replaces readfp().
if sys.version_info >= (3, 2):
cfg.read_file(inp)
else:
cfg.readfp(inp)
_update_library(cfg)
finally:
inp.close()
def _update_library(cfg):
"""
Update library from :class:`ConfigParser` `cfg`.
Parameters
----------
cfg : ConfigParser
ConfigParser loaded with unit_lib.ini data
"""
retry1 = set()
for name, unit in cfg.items('units'):
data = [item.strip() for item in unit.split(',')]
if len(data) == 2:
unit, comment = data
try:
add_unit(name, unit, comment)
except NameError:
retry1.add((name, unit, comment))
elif len(data) == 4:
factor, baseunit, offset, comment = data
try:
add_offset_unit(name, baseunit, float(factor), float(offset),
comment)
except NameError:
retry1.add((name, baseunit, float(factor), float(offset),
comment))
else:
raise ValueError(f"Unit '{name}' definition {unit} has invalid format.")
retry_count = 0
last_retry_count = -1
while last_retry_count != retry_count and retry1:
last_retry_count = retry_count
retry_count = 0
retry2 = retry1.copy()
for data in retry2:
if len(data) == 3:
name, unit, comment = data
try:
add_unit(name, unit, comment)
retry1.remove(data)
except NameError:
retry_count += 1
else:
try:
name, factor, baseunit, offset, comment = data
add_offset_unit(name, factor, baseunit, offset, comment)
retry1.remove(data)
except NameError:
retry_count += 1
if retry1:
raise ValueError('The following units were not defined because they'
' could not be resolved as a function of any other'
' defined units: %s.' % [x[0] for x in retry1])
_UNIT_CACHE = {}
def _is_unitless(units):
if units is None:
return True
unit_meta = _find_unit(units)
return unit_meta is not None and unit_meta.is_dimensionless()
def _find_unit(unit, error=False):
"""
Find unit helper function.
Parameters
----------
unit : str
str representing the desired unit
error : bool
If True, raise exception if unit isn't found.
Returns
-------
PhysicalUnit
The actual unit object
"""
# Special handling for 's' and 'h' in the unit string
def simplify_time_units(unit_str):
# Split the unit string by multiplication and division
units = re.split(r'(\*|/)', unit_str)
# Create a dictionary to keep track of unit powers
unit_powers = {}
current_operation = '*'
for u in units:
if u in ['*', '/']:
current_operation = u
else:
# Adjust the power according to the operation
power = 1 if current_operation == '*' else -1
if u in unit_powers:
unit_powers[u] += power
else:
unit_powers[u] = power
# Simplify 's' and 'h' if both are present
if 's' in unit_powers and 'h' in unit_powers:
min_power = min(abs(unit_powers['s']), abs(unit_powers['h']))
unit_powers['s'] -= min_power * (1 if unit_powers['s'] > 0 else -1)
unit_powers['h'] -= min_power * (1 if unit_powers['h'] > 0 else -1)
# Reconstruct the unit string
new_units = []
for u, power in unit_powers.items():
if power != 0:
# Add the unit and its power (if not 1)
new_units.append(f"{u}^{power}" if power != 1 else u)
# Join the units with multiplication
simplified_unit_str = "*".join(new_units)
# Replace powers of -1 with division
simplified_unit_str = re.sub(r'\^(-1)', '/', simplified_unit_str)
return simplified_unit_str
if isinstance(unit, str):
unit = simplify_time_units(unit)
# Deal with 'as' for attoseconds
reg1 = re.compile(r'\bas\b')
unit = re.sub(reg1, 'as_', unit)
name = unit.strip()
try:
unit = _UNIT_CACHE[name]
except KeyError:
try:
unit = eval(name, {'__builtins__': None}, # nosec: scope limited
_UNIT_LIB.unit_table)
except Exception:
# This unit might include prefixed units that aren't in the
# unit_table. We must parse them ALL and add them to the
# unit_table.
# First character of a unit is always alphabet or $.
# Remaining characters may include numbers.
regex = re.compile('[A-Z,a-z]{1}[A-Z,a-z,0-9]*')
unit_table = _UNIT_LIB.unit_table
prefixes = _UNIT_LIB.prefixes
for item in regex.findall(name):
item = re.sub(reg1, 'as_', item)
# check if this was a compound unit, so each
# substring might be a unit
try:
eval(item, {'__builtins__': None}, unit_table) # nosec: scope limited
except Exception: # maybe is a prefixed unit then
base_unit = item[1:].rstrip('_')
# check for single letter prefix before unit
if (item[0] in prefixes and base_unit in unit_table):
add_unit(item, prefixes[item[0]] * unit_table[base_unit])
# check for double letter prefix before unit
elif (item[0:2] in prefixes and item[2:] in unit_table):
add_unit(item, prefixes[item[0:2]] * unit_table[item[2:]])
# no prefixes found, unknown unit
else:
if error:
raise ValueError(f"The units '{name}' are invalid.")
return None
unit = eval(name, {'__builtins__': None}, unit_table) # nosec: scope limited
_UNIT_CACHE[name] = unit
else:
name = unit
if not isinstance(unit, PhysicalUnit):
if error:
raise ValueError(f"The units '{name}' are invalid.")
return None
return unit
def valid_units(unit):
"""
Return whether the given units are vaild.
Parameters
----------
unit : str
String representation of the units.
Returns
-------
bool
True for valid, False for invalid.
"""
return _find_unit(unit) is not None
def conversion_to_base_units(units):
"""
Get the offset and scaler to convert from given units to base units.
Parameters
----------
units : str
String representation of the units.
Returns