/
units.py
2615 lines (2087 loc) · 81.2 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
import ctypes
import ctypes.util
import operator
from numpy import array as numpy_array
from numpy import asanyarray as numpy_asanyarray
from numpy import dtype as numpy_dtype
from numpy import generic as numpy_generic
from numpy import ndarray as numpy_ndarray
from numpy import shape as numpy_shape
from numpy import size as numpy_size
# --------------------------------------------------------------------
# Aliases for ctypes
# --------------------------------------------------------------------
_sizeof_buffer = 257
_string_buffer = ctypes.create_string_buffer(_sizeof_buffer)
_c_char_p = ctypes.c_char_p
_c_int = ctypes.c_int
_c_uint = ctypes.c_uint
_c_float = ctypes.c_float
_c_double = ctypes.c_double
_c_size_t = ctypes.c_size_t
_c_void_p = ctypes.c_void_p
_pointer = ctypes.pointer
_POINTER = ctypes.POINTER
_ctypes_POINTER = {4: _POINTER(_c_float), 8: _POINTER(_c_double)}
# --------------------------------------------------------------------
# Load the Udunits-2 library and read the database
# --------------------------------------------------------------------
# if sys.platform == 'darwin':
# # This has been tested on Mac OSX 10.5.8 and 10.6.8
# _udunits = ctypes.CDLL('libudunits2.0.dylib')
# else:
# # Linux
# _udunits = ctypes.CDLL('libudunits2.so.0')
_libpath = ctypes.util.find_library("udunits2")
if _libpath is None:
raise FileNotFoundError(
"cfunits requires UNIDATA UDUNITS-2. Can't find the 'udunits2' "
"library."
)
_udunits = ctypes.CDLL(_libpath)
# Suppress "overrides prefixed-unit" messages. This also suppresses
# all other error messages - so watch out!
#
# Messages may be turned back on by calling the module function
# udunits_error_messages.
# ut_error_message_handler ut_set_error_message_handler(
# ut_error_message_handler handler);
_ut_set_error_message_handler = _udunits.ut_set_error_message_handler
_ut_set_error_message_handler.argtypes = (_c_void_p,)
_ut_set_error_message_handler.restype = _c_void_p
_ut_set_error_message_handler(_udunits.ut_ignore)
# Read the data base
# ut_system* ut_read_xml(const char* path);
_ut_read_xml = _udunits.ut_read_xml
_ut_read_xml.argtypes = (_c_char_p,)
_ut_read_xml.restype = _c_void_p
# print('units: before _udunits.ut_read_xml(',_unit_database,')')
_ut_system = _ut_read_xml(None)
# print('units: after _udunits.ut_read_xml(',_unit_database,')')
# Reinstate the reporting of error messages
# _ut_set_error_message_handler(_udunits.ut_write_to_stderr)
# --------------------------------------------------------------------
# Aliases for the UDUNITS-2 C API. See
# http://www.unidata.ucar.edu/software/udunits/udunits-2.0.4/udunits2lib.html
# for documentation.
# --------------------------------------------------------------------
# int ut_format(const ut_unit* const unit, char* buf, size_t size,
# unsigned opts);
_ut_format = _udunits.ut_format
_ut_format.argtypes = (_c_void_p, _c_char_p, _c_size_t, _c_uint)
_ut_format.restype = _c_int
# char* ut_trim(char* const string, const ut_encoding encoding);
_ut_trim = _udunits.ut_trim
# ut_encoding assumed to be int!:
_ut_trim.argtypes = (_c_char_p, _c_int)
_ut_trim.restype = _c_char_p
# ut_unit* ut_parse(const ut_system* const system,
# const char* const string, const ut_encoding encoding);
_ut_parse = _udunits.ut_parse
# ut_encoding assumed to be int!:
_ut_parse.argtypes = (_c_void_p, _c_char_p, _c_int)
_ut_parse.restype = _c_void_p
# int ut_compare(const ut_unit* const unit1, const ut_unit* const
# unit2);
_ut_compare = _udunits.ut_compare
_ut_compare.argtypes = (_c_void_p, _c_void_p)
_ut_compare.restype = _c_int
# int ut_are_convertible(const ut_unit* const unit1, const ut_unit*
# const unit2);
_ut_are_convertible = _udunits.ut_are_convertible
_ut_are_convertible.argtypes = (_c_void_p, _c_void_p)
_ut_are_convertible.restype = _c_int
# cv_converter* ut_get_converter(ut_unit* const from, ut_unit* const
# to);
_ut_get_converter = _udunits.ut_get_converter
_ut_get_converter.argtypes = (_c_void_p, _c_void_p)
_ut_get_converter.restype = _c_void_p
# ut_unit* ut_divide(const ut_unit* const numer, const ut_unit* const
# denom);
_ut_divide = _udunits.ut_divide
_ut_divide.argtypes = (_c_void_p, _c_void_p)
_ut_divide.restype = _c_void_p
# ut_unit* ut_get_name(const ut_unit* unit, ut_encoding encoding)
_ut_get_name = _udunits.ut_get_name
_ut_get_name.argtypes = (_c_void_p, _c_int) # ut_encoding assumed to be int!
_ut_get_name.restype = _c_char_p
# ut_unit* ut_offset(const ut_unit* const unit, const double offset);
_ut_offset = _udunits.ut_offset
_ut_offset.argtypes = (_c_void_p, _c_double)
_ut_offset.restype = _c_void_p
# ut_unit* ut_raise(const ut_unit* const unit, const int power);
_ut_raise = _udunits.ut_raise
_ut_raise.argtypes = (_c_void_p, _c_int)
_ut_raise.restype = _c_void_p
# ut_unit* ut_scale(const double factor, const ut_unit* const unit);
_ut_scale = _udunits.ut_scale
_ut_scale.argtypes = (_c_double, _c_void_p)
_ut_scale.restype = _c_void_p
# ut_unit* ut_multiply(const ut_unit* const unit1, const ut_unit*
# const unit2);
_ut_multiply = _udunits.ut_multiply
_ut_multiply.argtypes = (_c_void_p, _c_void_p)
_ut_multiply.restype = _c_void_p
# ut_unit* ut_log(const double base, const ut_unit* const reference);
_ut_log = _udunits.ut_log
_ut_log.argtypes = (_c_double, _c_void_p)
_ut_log.restype = _c_void_p
# ut_unit* ut_root(const ut_unit* const unit, const int root);
_ut_root = _udunits.ut_root
_ut_root.argtypes = (_c_void_p, _c_int)
_ut_root.restype = _c_void_p
# void ut_free_system(ut_system* system);
_ut_free = _udunits.ut_free
_ut_free.argypes = (_c_void_p,)
_ut_free.restype = None
# float* cv_convert_floats(const cv_converter* converter, const float*
# const in, const size_t count, float* out);
_cv_convert_floats = _udunits.cv_convert_floats
_cv_convert_floats.argtypes = (_c_void_p, _c_void_p, _c_size_t, _c_void_p)
_cv_convert_floats.restype = _c_void_p
# double* cv_convert_doubles(const cv_converter* converter, const
# double* const in, const size_t count,
# double* out);
_cv_convert_doubles = _udunits.cv_convert_doubles
_cv_convert_doubles.argtypes = (_c_void_p, _c_void_p, _c_size_t, _c_void_p)
_cv_convert_doubles.restype = _c_void_p
# double cv_convert_double(const cv_converter* converter, const double
# value);
_cv_convert_double = _udunits.cv_convert_double
_cv_convert_double.argtypes = (_c_void_p, _c_double)
_cv_convert_double.restype = _c_double
# void cv_free(cv_converter* const conv);
_cv_free = _udunits.cv_free
_cv_free.argtypes = (_c_void_p,)
_cv_free.restype = None
_UT_ASCII = 0
_UT_NAMES = 4
_UT_DEFINITION = 8
_cv_convert_array = {4: _cv_convert_floats, 8: _cv_convert_doubles}
# Some function definitions necessary for the following
# changes to the unit system.
_ut_get_unit_by_name = _udunits.ut_get_unit_by_name
_ut_get_unit_by_name.argtypes = (_c_void_p, _c_char_p)
_ut_get_unit_by_name.restype = _c_void_p
_ut_get_status = _udunits.ut_get_status
_ut_get_status.restype = _c_int
_ut_unmap_symbol_to_unit = _udunits.ut_unmap_symbol_to_unit
_ut_unmap_symbol_to_unit.argtypes = (_c_void_p, _c_char_p, _c_int)
_ut_unmap_symbol_to_unit.restype = _c_int
_ut_map_symbol_to_unit = _udunits.ut_map_symbol_to_unit
_ut_map_symbol_to_unit.argtypes = (_c_char_p, _c_int, _c_void_p)
_ut_map_symbol_to_unit.restype = _c_int
_ut_map_unit_to_symbol = _udunits.ut_map_unit_to_symbol
_ut_map_unit_to_symbol.argtypes = (_c_void_p, _c_char_p, _c_int)
_ut_map_unit_to_symbol.restype = _c_int
_ut_map_name_to_unit = _udunits.ut_map_name_to_unit
_ut_map_name_to_unit.argtypes = (_c_char_p, _c_int, _c_void_p)
_ut_map_name_to_unit.restype = _c_int
_ut_map_unit_to_name = _udunits.ut_map_unit_to_name
_ut_map_unit_to_name.argtypes = (_c_void_p, _c_char_p, _c_int)
_ut_map_unit_to_name.restype = _c_int
_ut_new_base_unit = _udunits.ut_new_base_unit
_ut_new_base_unit.argtypes = (_c_void_p,)
_ut_new_base_unit.restype = _c_void_p
# Change Sv mapping. Both sievert and sverdrup are just aliases,
# so no unit to symbol mapping needs to be changed.
# We don't need to remove rem, since it was constructed with
# the correct sievert mapping in place; because that mapping
# was only an alias, the unit now doesn't depend on the mapping
# persisting.
assert 0 == _ut_unmap_symbol_to_unit(_ut_system, _c_char_p(b"Sv"), _UT_ASCII)
assert 0 == _ut_map_symbol_to_unit(
_c_char_p(b"Sv"),
_UT_ASCII,
_ut_get_unit_by_name(_ut_system, _c_char_p(b"sverdrup")),
)
# Add new base unit calendar_year
calendar_year_unit = _ut_new_base_unit(_ut_system)
assert 0 == _ut_map_symbol_to_unit(
_c_char_p(b"cY"), _UT_ASCII, calendar_year_unit
)
assert 0 == _ut_map_unit_to_symbol(
calendar_year_unit, _c_char_p(b"cY"), _UT_ASCII
)
assert 0 == _ut_map_name_to_unit(
_c_char_p(b"calendar_year"), _UT_ASCII, calendar_year_unit
)
assert 0 == _ut_map_unit_to_name(
calendar_year_unit, _c_char_p(b"calendar_year"), _UT_ASCII
)
assert 0 == _ut_map_name_to_unit(
_c_char_p(b"calendar_years"), _UT_ASCII, calendar_year_unit
)
def add_unit_alias(definition, symbol, singular, plural):
"""Registers an alias for an existing unit or value."""
unit = _ut_parse(
_ut_system, _c_char_p(definition.encode("utf-8")), _UT_ASCII
)
if symbol is not None:
assert 0 == _ut_map_symbol_to_unit(
_c_char_p(symbol.encode("utf-8")), _UT_ASCII, unit
)
if singular is not None:
assert 0 == _ut_map_name_to_unit(
_c_char_p(singular.encode("utf-8")), _UT_ASCII, unit
)
if plural is not None:
assert 0 == _ut_map_name_to_unit(
_c_char_p(plural.encode("utf-8")), _UT_ASCII, unit
)
# Add various aliases useful for CF
add_unit_alias(
"1.e-3", "psu", "practical_salinity_unit", "practical_salinity_units"
)
add_unit_alias("calendar_year/12", "cM", "calendar_month", "calendar_months")
add_unit_alias("1", None, "level", "levels")
add_unit_alias("1", None, "layer", "layers")
add_unit_alias("1", None, "sigma_level", "sigma_levels")
add_unit_alias("1", "dB", "decibel", "debicels")
add_unit_alias("10 dB", None, "bel", "bels")
# _udunits.ut_get_unit_by_name(_udunits.ut_new_base_unit(_ut_system),
# _ut_system, 'calendar_year')
# --------------------------------------------------------------------
# Create a calendar year unit
# --------------------------------------------------------------------
# _udunits.ut_map_name_to_unit('calendar_year', _UT_ASCII,
# _udunits.ut_new_base_unit(_ut_system))
from cftime import _dateparse as cftime_dateparse
from cftime import datetime as cftime_datetime
_cached_ut_unit = {}
_cached_utime = {}
# --------------------------------------------------------------------
# Save some useful units
# --------------------------------------------------------------------
# A time ut_unit (equivalent to 'day', 'second', etc.)
_day_ut_unit = _ut_parse(_ut_system, _c_char_p(b"day"), _UT_ASCII)
_cached_ut_unit["days"] = _day_ut_unit
# A pressure ut_unit (equivalent to 'Pa', 'hPa', etc.)
_pressure_ut_unit = _ut_parse(_ut_system, _c_char_p(b"pascal"), _UT_ASCII)
_cached_ut_unit["pascal"] = _pressure_ut_unit
# A calendar time ut_unit (equivalent to 'cY', 'cM')
_calendartime_ut_unit = _ut_parse(
_ut_system, _c_char_p(b"calendar_year"), _UT_ASCII
)
_cached_ut_unit["calendar_year"] = _calendartime_ut_unit
# A dimensionless unit one (equivalent to '', '1', '2', etc.)
# _dimensionless_unit_one = _udunits.ut_get_dimensionless_unit_one(_ut_system)
# _cached_ut_unit[''] = _dimensionless_unit_one
# _cached_ut_unit['1'] = _dimensionless_unit_one
_dimensionless_unit_one = _ut_parse(_ut_system, _c_char_p(b"1"), _UT_ASCII)
_cached_ut_unit[""] = _dimensionless_unit_one
_cached_ut_unit["1"] = _dimensionless_unit_one
# --------------------------------------------------------------------
# Set the default calendar type according to the CF conventions
# --------------------------------------------------------------------
_default_calendar = "standard"
_canonical_calendar = {
"gregorian": "standard",
"standard": "standard",
"none": "standard",
"proleptic_gregorian": "proleptic_gregorian",
"360_day": "360_day",
"noleap": "365_day",
"365_day": "365_day",
"all_leap": "366_day",
"366_day": "366_day",
"julian": "julian",
}
_months_or_years = ("month", "months", "year", "years", "yr")
# # --------------------------------------------------------------------
# # Set month lengths in days for non-leap years (_days_in_month[0,1:])
# # and leap years (_days_in_month[1,1:])
# # --------------------------------------------------------------------
# _days_in_month = numpy_array(
# [[-99, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
# [-99, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]])
# --------------------------------------------------------------------
# Function to control Udunits error messages
# --------------------------------------------------------------------
def udunits_error_messages(flag):
"""Controls the printing of error messages from Udunits.
Error messages are turned off by default in Udunits.
:Parameters:
flag: `bool`
Set to True to print Udunits error messages and False to
not print Udunits error messages.
:Returns:
`None`
**Examples**
>>> udunits_error_messages(True)
>>> udunits_error_messages(False)
"""
if flag:
_ut_set_error_message_handler(_udunits.ut_write_to_stderr)
else:
_ut_set_error_message_handler(_udunits.ut_ignore)
# def _month_length(year, month, calendar, _days_in_month=_days_in_month):
# '''
#
# Find month lengths in days for each year/month pairing in the input
# numpy arrays 'year' and 'month', both of which must have the same
# shape. 'calendar' must be one of the standard CF calendar types.
#
# :Parameters:
#
#
# '''
# shape = month.shape
# if calendar in ('standard', 'gregorian'):
# leap = numpy_where(year % 4 == 0, 1, 0)
# leap = numpy_where((year > 1582) &
# (year % 100 == 0) & (year % 400 != 0),
# 0, leap)
# elif calendar == '360_day':
# days_in_month = numpy_empty(shape)
# days_in_month.fill(30)
# return days_in_month
#
# elif calendar in ('all_leap', '366_day'):
# leap = numpy_zeros(shape)
#
# elif calendar in ('no_leap', '365_day'):
# leap = numpy_ones(shape)
#
# elif calendar == 'proleptic_gregorian':
# leap = numpy_where(year % 4 == 0, 1, 0)
# leap = numpy_where((year % 100 == 0) & (year % 400 != 0),
# 0, leap)
#
# days_in_month = numpy_array([_days_in_month[l, m]
# for l, m in zip(leap.flat, month.flat)])
# days_in_month.resize(shape)
#
# return days_in_month
#
# def _proper_date(year, month, day, calendar, fix=False,
# _days_in_month=_days_in_month):
# '''
#
# Given equally shaped numpy arrays of 'year', 'month', 'day' adjust
# them *in place* to be proper dates. 'calendar' must be one of the
# standard CF calendar types.
#
# Excessive number of months are converted to years but excessive days
# are not converted to months nor years. If a day is illegal in the
# proper date then a ValueError is raised, unless 'fix' is True, in
# which case the day is lowered to the nearest legal date:
#
# 2000/26/1 -> 2002/3/1
#
# 2001/2/31 -> ValueError if 'fix' is False
# 2001/2/31 -> 2001/2/28 if 'fix' is True
# 2001/2/99 -> 2001/2/28 if 'fix' is True
#
# :Parameters:
#
# '''
# # y, month = divmod(month, 12)
# # year += y
#
# year += month // 12
# month[...] = month % 12
#
# mask = (month == 0)
# year[...] = numpy_where(mask, year-1, year)
# month[...] = numpy_where(mask, 12, month)
# del mask
#
# days_in_month = _month_length(year, month, calendar,
# _days_in_month=_days_in_month)
#
# if fix:
# day[...] = numpy_where(day > days_in_month, days_in_month, day)
# elif (day > days_in_month).any():
# raise ValueError("Illegal date(s) in %s calendar" % calendar)
#
# return year, month, day
# --------------------------------------------------------------------
# Constants, as defined by UDUNITS
# --------------------------------------------------------------------
_year_length = 365.242198781
_month_length = _year_length / 12
class Units:
"""Utilities for working with physical units.
Store, combine and compare physical units and convert numeric
values to different units.
Units are as defined in UNIDATA's Udunits-2 package, with a few
exceptions for greater consistency with the CF conventions namely
support for CF calendars and new units definitions.
**Modifications to the standard Udunits database**
Whilst a standard Udunits-2 database may be used, greater
consistency with CF is achieved by using a modified database. The
following units are either new to, modified from, or removed from
the standard Udunits-2 database (version 2.1.24):
======================= ====== ============ ==============
Unit name Symbol Definition Status
======================= ====== ============ ==============
practical_salinity_unit psu 1e-3 New unit
level 1 New unit
sigma_level 1 New unit
layer 1 New unit
decibel dB 1 New unit
bel 10 dB New unit
sverdrup Sv 1e6 m3 s-1 Added symbol
sievert J kg-1 Removed symbol
======================= ====== ============ ==============
Plural forms of the new units' names are allowed, such as
``practical_salinity_units``.
The modified database is in the *udunits* subdirectory of the
*etc* directory found in the same location as this module.
**Accessing units**
Units may be set, retrieved and deleted via the `units`
attribute. Its value is a string that can be recognized by
UNIDATA's Udunits-2 package, with the few exceptions given in the
CF conventions.
>>> u = Units('m s-1')
>>> u
<Units: m s-1>
>>> v = Units('days since 2004-3-1')
>>> v
<Units: days since 2004-3-1>
**Equality and equivalence of units**
There are methods for assessing whether two units are equivalent
or equal. Two units are equivalent if numeric values in one unit
are convertible to numeric values in the other unit (such as
``kilometres`` and ``metres``). Two units are equal if they are
equivalent and their conversion is a scale factor of 1 and an
offset of 0 (such as ``kilometres`` and ``1000 metres``). Note
that equivalence and equality are based on internally stored
binary representations of the units, rather than their string
representations.
>>> u = Units('m/s')
>>> v = Units('m s-1')
>>> w = Units('km.s-1')
>>> x = Units('0.001 kilometer.second-1')
>>> y = Units('gram')
>>> u.equivalent(v), u.equals(v), u == v
(True, True, True)
>>> u.equivalent(w), u.equals(w)
(True, False)
>>> u.equivalent(x), u.equals(x)
(True, True)
>>> u.equivalent(y), u.equals(y)
(False, False)
**Time and reference time units**
Time units may be given as durations of time (*time units*) or as
an amount of time since a reference time (*reference time units*):
>>> v = Units()
>>> v = Units('s')
>>> v = Units('day')
>>> v = Units('days since 1970-01-01')
>>> v = Units('seconds since 1992-10-8 15:15:42.5 -6:00')
.. note:: It is recommended that the units ``year`` and ``month``
be used with caution, as explained in the following
excerpt from the CF conventions: "The Udunits package
defines a year to be exactly 365.242198781 days (the
interval between 2 successive passages of the sun
through vernal equinox). It is not a calendar
year. Udunits includes the following definitions for
years: a common_year is 365 days, a leap_year is 366
days, a Julian_year is 365.25 days, and a Gregorian_year
is 365.2425 days. For similar reasons the unit
``month``, which is defined to be exactly year/12,
should also be used with caution."
**Calendar**
The date given in reference time units is associated with one of
the calendars recognized by the CF conventions and may be set with
the `calendar` attribute. However, as in the CF conventions, if
the calendar is not set then, for the purposes of calculation and
comparison, it defaults to the mixed Gregorian/Julian calendar as
defined by Udunits:
>>> u = Units('days since 2000-1-1')
>>> u.calendar
Traceback (most recent call last):
...
AttributeError: Units has no attribute 'calendar'
>>> v = Units('days since 2000-1-1', 'standard')
>>> v.calendar
'standard'
>>> v.equals(u)
True
**Arithmetic with units**
The following operators, operations and assignments are
overloaded:
Comparison operators:
``==, !=, >, >=, <, <=``
Binary arithmetic operations:
``+, -, *, /, //, pow(), **, %``
Unary arithmetic operations:
``-, +``
Augmented arithmetic assignments:
``+=, -=, *=, /=, //=, **=``
The comparison operations return a boolean and all other
operations return a new units object or modify the units object in
place.
>>> u = Units('m')
>>> u
<Units: m>
>>> v = u * 1000
>>> v
<Units: 1000 m>
>>> u == v
False
>>> u != v
True
>>> u **= 2
>>> u
<Units: m2>
It is also possible to create the logarithm of a unit
corresponding to the given logarithmic base:
>>> u = Units('seconds')
>>> u.log(10)
<Units: lg(re 1 s)>
**Modifying data for equivalent units**
Any numpy array or Python numeric type may be modified for
equivalent units using the `conform` static method.
>>> Units.conform(2, Units('km'), Units('m'))
2000.0
>>> import numpy
>>> a = numpy.arange(5.0)
>>> Units.conform(a, Units('minute'), Units('second'))
array([ 0., 60., 120., 180., 240.])
>>> a
array([0., 1., 2., 3., 4.])
If the *inplace* keyword is True, then a numpy array is modified
in place, without any copying overheads:
>>> Units.conform(
... a,
... Units('days since 2000-12-1'),
... Units('days since 2001-1-1'),
... inplace=True
... )
array([-31., -30., -29., -28., -27.])
>>> a
array([-31., -30., -29., -28., -27.])
"""
def __init__(
self,
units=None,
calendar=None,
formatted=False,
names=False,
definition=False,
_ut_unit=None,
):
"""Initialises the `Units` instance.
:Parameters:
units: `str` or `Units`, optional
Set the new units from this string.
calendar: `str`, optional
Set the calendar for reference time units.
formatted: `bool`, optional
Format the string representation of the units in a
standardized manner. See the `formatted` method.
names: `bool`, optional
Format the string representation of the units using names
instead of symbols. See the `formatted` method.
definition: `bool`, optional
Format the string representation of the units using basic
units. See the `formatted` method.
_ut_unit: `int`, optional
Set the new units from this Udunits binary unit
representation. This should be an integer returned by a
call to `ut_parse` function of Udunits. Ignored if *units*
is set.
"""
if isinstance(units, self.__class__):
self.__dict__ = units.__dict__
return
self._isvalid = True
self._reason_notvalid = ""
self._units = units
self._ut_unit = None
self._isreftime = False
self._calendar = calendar
self._canonical_calendar = None
self._utime = None
self._units_since_reftime = None
# Set the calendar
_calendar = None
if calendar is not None:
_calendar = _canonical_calendar.get(calendar.lower())
if _calendar is None:
self._new_reason_notvalid(f"Invalid calendar={calendar!r}")
self._isvalid = False
_calendar = calendar
if units is not None:
try:
units = units.strip()
except AttributeError:
self._isvalid = False
self._new_reason_notvalid(f"Bad units type: {type(units)}")
return
unit = None
if isinstance(units, str) and " since " in units:
# ----------------------------------------------------
# Set a reference time unit
# ----------------------------------------------------
# Set the calendar
if calendar is None:
_calendar = _default_calendar
else:
_calendar = _canonical_calendar.get(calendar.lower())
if _calendar is None:
_calendar = calendar
units_split = units.split(" since ")
unit = units_split[0].strip()
self._units_since_reftime = unit
ut_unit = _cached_ut_unit.get(unit, None)
if ut_unit is None:
ut_unit = _ut_parse(
_ut_system, _c_char_p(unit.encode("utf-8")), _UT_ASCII
)
if not ut_unit or not _ut_are_convertible(
ut_unit, _day_ut_unit
):
ut_unit = None
self._isvalid = False
else:
_cached_ut_unit[unit] = ut_unit
if (_calendar, units) in _cached_utime:
utime = _cached_utime[(_calendar, units)]
else:
unit_string = f"{unit} since {units_split[1].strip()}"
utime = _cached_utime.get((_calendar, unit_string))
if utime is None:
try:
d = cftime_dateparse(
unit_string, calendar=_calendar
)
except Exception as error:
self._new_reason_notvalid(str(error))
self._isvalid = False
else:
utime = cftime_datetime(
*d.timetuple()[:6], calendar=_calendar
)
_cached_utime[(_calendar, unit_string)] = utime
self._isreftime = True
self._calendar = calendar
self._canonical_calendar = _calendar
self._utime = utime
else:
# ----------------------------------------------------
# Set a unit other than a reference time unit
# ----------------------------------------------------
ut_unit = _cached_ut_unit.get(units, None)
if ut_unit is None:
ut_unit = _ut_parse(
_ut_system, _c_char_p(units.encode("utf-8")), _UT_ASCII
)
if not ut_unit:
ut_unit = None
self._isvalid = False
self._new_reason_notvalid(
f"Invalid units: {units!r}; Not recognised by "
"UDUNITS"
)
else:
_cached_ut_unit[units] = ut_unit
self._isreftime = False
self._calendar = None
self._canonial_calendar = None
self._utime = None
self._ut_unit = ut_unit
self._units = units
self._units_since_reftime = unit
if formatted or names or definition:
self._units = self.formatted(names, definition)
return
elif calendar:
# ---------------------------------------------------------
# Calendar is set, but units are not.
# ---------------------------------------------------------
self._units = None
self._ut_unit = None
self._isreftime = True
self._calendar = calendar
self._canonical_calendar = _canonical_calendar[calendar.lower()]
self._units_since_reftime = None
return
if _ut_unit is not None:
# ---------------------------------------------------------
# _ut_unit is set
# ---------------------------------------------------------
self._ut_unit = _ut_unit
self._isreftime = False
units = self.formatted(names, definition)
_cached_ut_unit[units] = _ut_unit
self._units = units
self._units_since_reftime = None
self._calendar = None
self._utime = None
return
# -------------------------------------------------------------
# Nothing has been set
# -------------------------------------------------------------
self._units = None
self._ut_unit = None
self._isreftime = False
self._calendar = None
self._canonical_calendar = None
self._utime = None
self._units_since_reftime = None
def __dask_tokenize__(self):
"""Return a value fully representative of the object."""
if self._isvalid:
return (Units, self._units, self._utime)
return (Units, self._units)
def __getstate__(self):
"""Called when pickling.
:Returns:
`dict`
A dictionary of the instance's attributes
**Examples**
>>> u = Units('days since 3-4-5', calendar='standard')
>>> u.__getstate__()
{'_units': 'days since 3-4-5',
'_calendar': 'standard'}
"""
return dict(
[
(attr, getattr(self, attr))
for attr in ("_units", "_calendar")
if hasattr(self, attr)
]
)
def __setstate__(self, odict):
"""Called when unpickling.
:Parameters:
odict: `dict`
The output from the instance's `__getstate__` method.
:Returns:
`None`
"""
units = None
if "_units" in odict:
units = odict["_units"]
calendar = None
if "_calendar" in odict:
calendar = odict["_calendar"]
self.__init__(units=units, calendar=calendar)
def __hash__(self):
"""Returns an integer representation of the `Units` object.
x.__hash__() is logically equivalent to hash(x)
"""
if not self._isreftime:
return hash(("Units", self._ut_unit))
# origin = self._utime.origin
origin = self._utime
return hash(
("Units", self._ut_unit, origin) # , self._utime.calendar)
)
def __repr__(self):
"""Returns a printable representation of the `Units` object.
x.__repr__() is logically equivalent to repr(x)
"""
return f"<{self.__class__.__name__}: {self}>"
def __str__(self):
"""Returns a string version of the `Units` object.
x.__str__() is logically equivalent to str(x)
"""
string = []
if self._units is not None:
if self._units == "":
string.append("''")
else:
string.append(str(self._units))
if self._calendar is not None:
string.append(f"{self._calendar}")
return " ".join(string)
def __deepcopy__(self, memo):
"""Used if copy.deepcopy is called on the variable."""
return self
def __bool__(self):
"""Truth value testing and the built-in operation ``bool``.
x.__bool__() is logically equivalent to x!=0
"""
return self._ut_unit is not None
def __eq__(self, other):
"""The rich comparison operator ``==``.
x.__eq__(y) is logically equivalent to x==y
"""
return self.equals(other)
def __ne__(self, other):
"""The rich comparison operator ``!=``.
x.__ne__(y) is logically equivalent to x!=y
"""
return not self.equals(other)
def __gt__(self, other):
"""The rich comparison operator ``>``.
x.__gt__(y) is logically equivalent to x>y