/
functions.py
3450 lines (2570 loc) · 97.5 KB
/
functions.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 atexit
import csv
import ctypes.util
import importlib
import os
import platform
import re
import sys
import urllib.parse
import warnings
from collections.abc import Iterable
from itertools import product
from math import isnan
from numbers import Integral
from os import mkdir
from os.path import abspath as _os_path_abspath
from os.path import dirname as _os_path_dirname
from os.path import expanduser as _os_path_expanduser
from os.path import expandvars as _os_path_expandvars
from os.path import join as _os_path_join
from os.path import relpath as _os_path_relpath
from urllib.parse import urlparse
import cfdm
import netCDF4
import numpy as np
from dask import config as _config
from dask.base import is_dask_collection
from dask.utils import parse_bytes
from psutil import virtual_memory
from . import __cfa_version__, __file__, __version__
from .constants import (
CONSTANTS,
OperandBoundsCombination,
_stash2standard_name,
)
from .docstring import _docstring_substitution_definitions
# Instruction to close /proc/mem at exit.
def _close_proc_meminfo():
try:
_meminfo_file.close()
except Exception:
pass
atexit.register(_close_proc_meminfo)
# --------------------------------------------------------------------
# Inherit classes from cfdm
# --------------------------------------------------------------------
class Constant(cfdm.Constant):
def __docstring_substitutions__(self):
return _docstring_substitution_definitions
def __docstring_package_depth__(self):
return 0
def __repr__(self):
"""Called by the `repr` built-in function."""
return super().__repr__().replace("<", "<CF ", 1)
class DeprecationError(Exception):
pass
KWARGS_MESSAGE_MAP = {
"relaxed_identity": "Use keywords 'strict' or 'relaxed' instead.",
"axes": "Use keyword 'axis' instead.",
"traceback": "Use keyword 'verbose' instead.",
"exact": "Use 're.compile' objects instead.",
"i": (
"Use keyword 'inplace' instead. Note that when inplace=True, "
"None is returned."
),
"info": (
"Use keyword 'verbose' instead. Note the informational levels "
"have been remapped: V = I + 1 maps info=I to verbose=V inputs, "
"excluding I >= 3 which maps to V = -1 (and V = 0 disables messages)"
),
}
if platform.system() == "Linux":
# ----------------------------------------------------------------
# GNU/LINUX
# ----------------------------------------------------------------
# Opening /proc/meminfo once per PE here rather than in
# _free_memory each time it is called works with MPI on
# Debian-based systems, which otherwise throw an error that there
# is no such file or directory when run on multiple PEs.
# ----------------------------------------------------------------
_meminfo_fields = set(("SReclaimable:", "Cached:", "Buffers:", "MemFree:"))
_meminfo_file = open("/proc/meminfo", "r", 1)
def _free_memory():
"""The amount of available physical memory on GNU/Linux.
This amount includes any memory which is still allocated but is no
longer required.
:Returns:
`float`
The amount of available physical memory in bytes.
**Examples**
>>> _free_memory()
96496240.0
"""
# https://github.com/giampaolo/psutil/blob/master/psutil/_pslinux.py
# ----------------------------------------------------------------
# The available physical memory is the sum of the values of
# the 'SReclaimable', 'Cached', 'Buffers' and 'MemFree'
# entries in the /proc/meminfo file
# (http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/Documentation/filesystems/proc.txt).
# ----------------------------------------------------------------
free_KiB = 0.0
n = 0
# with open('/proc/meminfo', 'r', 1) as _meminfo_file:
# Seeking the beginning of the file /proc/meminfo regenerates
# the information contained in it.
_meminfo_file.seek(0)
for line in _meminfo_file:
field_size = line.split()
if field_size[0] in _meminfo_fields:
free_KiB += float(field_size[1])
n += 1
if n > 3:
break
free_bytes = free_KiB * 1024
return free_bytes
else:
# ----------------------------------------------------------------
# NOT GNU/LINUX
# ----------------------------------------------------------------
def _free_memory():
"""The amount of available physical memory.
:Returns:
`float`
The amount of available physical memory in bytes.
**Examples**
>>> _free_memory()
96496240.0
"""
return float(virtual_memory().available)
def configuration(
atol=None,
rtol=None,
tempdir=None,
chunksize=None,
log_level=None,
regrid_logging=None,
relaxed_identities=None,
bounds_combination_mode=None,
of_fraction=None,
collapse_parallel_mode=None,
free_memory_factor=None,
):
"""View or set any number of constants in the project-wide
configuration.
The full list of global constants that can be set in any
combination are:
* `atol`
* `rtol`
* `tempdir`
* `chunksize`
* `log_level`
* `regrid_logging`
* `relaxed_identities`
* `bounds_combination_mode`
These are all constants that apply throughout cf, except for in
specific functions only if overridden by the corresponding keyword
argument to that function.
The value of `None`, either taken by default or supplied as a
value, will result in the constant in question not being changed
from the current value. That is, it will have no effect.
Note that setting a constant using this function is equivalent to
setting it by means of a specific function of the same name,
e.g. via `cf.atol`, but in this case multiple constants can be set
at once.
.. versionadded:: 3.6.0
.. seealso:: `atol`, `rtol`, `tempdir`, `chunksize`,
`total_memory`, `log_level`, `regrid_logging`,
`relaxed_identities`, `bounds_combination_mode`
:Parameters:
atol: `float` or `Constant`, optional
The new value of absolute tolerance. The default is to not
change the current value.
rtol: `float` or `Constant`, optional
The new value of relative tolerance. The default is to not
change the current value.
tempdir: `str` or `Constant`, optional
The new directory for temporary files. Tilde expansion (an
initial component of ``~`` or ``~user`` is replaced by
that *user*'s home directory) and environment variable
expansion (substrings of the form ``$name`` or ``${name}``
are replaced by the value of environment variable *name*)
are applied to the new directory name.
The default is to not change the directory.
chunksize: `float` or `Constant`, optional
The new chunksize in bytes. The default is to not change
the current behaviour.
bounds_combination_mode: `str` or `Constant`, optional
Determine how to deal with cell bounds in binary
operations. See `cf.bounds_combination_mode` for details.
log_level: `str` or `int` or `Constant`, optional
The new value of the minimal log severity level. This can
be specified either as a string equal (ignoring case) to
the named set of log levels or identifier ``'DISABLE'``,
or an integer code corresponding to each of these, namely:
* ``'DISABLE'`` (``0``);
* ``'WARNING'`` (``1``);
* ``'INFO'`` (``2``);
* ``'DETAIL'`` (``3``);
* ``'DEBUG'`` (``-1``).
regrid_logging: `bool` or `Constant`, optional
The new value (either True to enable logging or False to
disable it). The default is to not change the current
behaviour.
relaxed_identities: `bool` or `Constant`, optional
The new value; if True, use "relaxed" mode when getting a
construct identity. The default is to not change the
current value.
of_fraction: `float` or `Constant`, optional
Deprecated at version 3.14.0 and is no longer
available.
collapse_parallel_mode: `int` or `Constant`, optional
Deprecated at version 3.14.0 and is no longer
available.
free_memory_factor: `float` or `Constant`, optional
Deprecated at version 3.14.0 and is no longer
available.
:Returns:
`Configuration`
The dictionary-like object containing the names and values
of the project-wide constants prior to the change, or the
current names and values if no new values are specified.
**Examples**
>>> cf.configuration() # view full global configuration of constants
{'rtol': 2.220446049250313e-16,
'atol': 2.220446049250313e-16,
'tempdir': '/tmp',
'regrid_logging': False,
'relaxed_identities': False,
'log_level': 'WARNING',
'bounds_combination_mode': 'AND',
'chunksize': 82873466.88000001}
>>> cf.chunksize(7.5e7) # any change to one constant...
82873466.88000001
>>> cf.configuration()['chunksize'] # ...is reflected in the configuration
75000000.0
>>> cf.configuration(tempdir='/usr/tmp', log_level='INFO') # set items
{'rtol': 2.220446049250313e-16,
'atol': 2.220446049250313e-16,
'tempdir': '/tmp',
'regrid_logging': False,
'relaxed_identities': False,
'log_level': 'WARNING',
'bounds_combination_mode': 'AND',
'chunksize': 75000000.0}
>>> cf.configuration() # the items set have been updated accordingly
{'rtol': 2.220446049250313e-16,
'atol': 2.220446049250313e-16,
'tempdir': '/usr/tmp',
'regrid_logging': False,
'relaxed_identities': False,
'log_level': 'INFO',
'bounds_combination_mode': 'AND',
'chunksize': 75000000.0}
Use as a context manager:
>>> print(cf.configuration())
{'rtol': 2.220446049250313e-16,
'atol': 2.220446049250313e-16,
'tempdir': '/usr/tmp',
'regrid_logging': False,
'relaxed_identities': False,
'log_level': 'INFO',
'bounds_combination_mode': 'AND',
'chunksize': 75000000.0}
>>> with cf.configuration(atol=9, rtol=10):
... print(cf.configuration())
...
{'rtol': 9.0,
'atol': 10.0,
'tempdir': '/usr/tmp',
'regrid_logging': False,
'relaxed_identities': False,
'log_level': 'INFO',
'bounds_combination_mode': 'AND',
'chunksize': 75000000.0}
>>> print(cf.configuration())
{'rtol': 2.220446049250313e-16,
'atol': 2.220446049250313e-16,
'tempdir': '/usr/tmp',
'regrid_logging': False,
'relaxed_identities': False,
'log_level': 'INFO',
'bounds_combination_mode': 'AND',
'chunksize': 75000000.0}
"""
if of_fraction is not None:
# TODODASKAPI
_DEPRECATION_ERROR_FUNCTION_KWARGS(
"configuration",
kwargs={"of_fraction": None},
version="3.14.0",
removed_at="5.0.0",
) # pragma: no cover
if collapse_parallel_mode is not None:
# TODODASKAPI
_DEPRECATION_ERROR_FUNCTION_KWARGS(
"configuration",
kwargs={"collapse_parallel_mode": None},
version="3.14.0",
removed_at="5.0.0",
) # pragma: no cover
return _configuration(
Configuration,
new_atol=atol,
new_rtol=rtol,
new_tempdir=tempdir,
new_chunksize=chunksize,
new_log_level=log_level,
new_regrid_logging=regrid_logging,
new_relaxed_identities=relaxed_identities,
bounds_combination_mode=bounds_combination_mode,
)
def _configuration(_Configuration, **kwargs):
"""Internal helper function to provide the logic for
`cf.configuration`.
We delegate from the user-facing `cf.configuration` for two main reasons:
1) to avoid a name clash there between the keyword arguments and the
functions which they each call (e.g. `atol` and `cf.atol`) which
would otherwise necessitate aliasing every such function name; and
2) because the user-facing function must have the appropriate keywords
explicitly listed, but the very similar logic applied for each keyword
can be consolidated by iterating over the full dictionary of input kwargs.
:Parameters:
_Configuration: class
The `Configuration` class to be returned.
:Returns:
`Configuration`
The names and values of the project-wide constants prior
to the change, or the current names and values if no new
values are specified.
"""
old = {name.lower(): val for name, val in CONSTANTS.items()}
old.pop("total_memory", None)
# Filter out 'None' kwargs from configuration() defaults. Note that this
# does not filter out '0' or 'True' values, which is important as the user
# might be trying to set those, as opposed to None emerging as default.
kwargs = {name: val for name, val in kwargs.items() if val is not None}
# Note values are the functions not the keyword arguments of same name:
reset_mapping = {
"new_atol": atol,
"new_rtol": rtol,
"new_tempdir": tempdir,
"new_chunksize": chunksize,
"new_log_level": log_level,
"new_regrid_logging": regrid_logging,
"new_relaxed_identities": relaxed_identities,
"bounds_combination_mode": bounds_combination_mode,
}
old_values = {}
try:
# Run the corresponding func for all input kwargs
for setting_alias, new_value in kwargs.items():
reset_mapping[setting_alias](new_value)
setting = setting_alias.replace("new_", "", 1)
old_values[setting_alias] = old[setting]
except ValueError:
# Reset any constants that were changed prior to the exception
for setting_alias, old_value in old_values.items():
reset_mapping[setting_alias](old_value)
# Raise the exception
raise
return _Configuration(**old)
# --------------------------------------------------------------------
# Inherit class from cfdm
# --------------------------------------------------------------------
class Configuration(cfdm.Configuration):
def __new__(cls, *args, **kwargs):
"""Must override this method in subclasses."""
instance = super().__new__(cls)
instance._func = configuration
return instance
def __docstring_substitutions__(self):
return _docstring_substitution_definitions
def __docstring_package_depth__(self):
return 0
def __repr__(self):
"""Called by the `repr` built-in function."""
return super().__repr__().replace("<", "<CF ", 1)
def free_memory():
"""The available physical memory.
:Returns:
`float`
The amount of free memory in bytes.
**Examples**
>>> import numpy
>>> print('Free memory =', cf.free_memory()/2**30, 'GiB')
Free memory = 88.2728042603 GiB
>>> a = numpy.arange(10**9)
>>> print('Free memory =', cf.free_memory()/2**30, 'GiB')
Free memory = 80.8082618713 GiB
>>> del a
>>> print('Free memory =', cf.free_memory()/2**30, 'GiB')
Free memory = 88.2727928162 GiB
"""
return _free_memory()
def FREE_MEMORY():
"""Alias for `cf.free_memory`."""
return free_memory()
_disable_logging = cfdm._disable_logging
# We can inherit the generic logic for the cf-python log_level()
# function as contained in _log_level, but can't inherit the
# user-facing log_level() from cfdm as it operates on cfdm's CONSTANTS
# dict. Define cf-python's own. This also means the log_level
# dostrings are independent which is important for providing
# module-specific documentation links and directives, etc.
_reset_log_emergence_level = cfdm._reset_log_emergence_level
_is_valid_log_level_int = cfdm._is_valid_log_level_int
# --------------------------------------------------------------------
# Functions inherited from cfdm
# --------------------------------------------------------------------
class ConstantAccess(cfdm.ConstantAccess):
_CONSTANTS = CONSTANTS
_Constant = Constant
def __docstring_substitutions__(self):
return _docstring_substitution_definitions
def __docstring_package_depth__(self):
return 0
class atol(ConstantAccess, cfdm.atol):
pass
class rtol(ConstantAccess, cfdm.rtol):
pass
class log_level(ConstantAccess, cfdm.log_level):
_is_valid_log_level_int = _is_valid_log_level_int
_reset_log_emergence_level = _reset_log_emergence_level
class regrid_logging(ConstantAccess):
"""Whether or not to enable `esmpy` regridding logging.
If it is logging is performed after every call to `esmpy`.
:Parameters:
arg: `bool` or `Constant`, optional
The new value (either `True` to enable logging or `False`
to disable it). The default is to not change the current
behaviour.
:Returns:
`Constant`
The value prior to the change, or the current value if no
new value was specified.
**Examples**
>>> cf.regrid_logging()
False
>>> cf.regrid_logging(True)
False
>>> cf.regrid_logging()
True
"""
_name = "REGRID_LOGGING"
def _parse(cls, arg):
"""Parse a new constant value.
.. versionaddedd:: 3.8.0
:Parameters:
cls:
This class.
arg:
The given new constant value.
:Returns:
A version of the new constant value suitable for insertion
into the `CONSTANTS` dictionary.
"""
return bool(arg)
class collapse_parallel_mode(ConstantAccess):
"""Which mode to use when collapse is run in parallel. There are
three possible modes:
Deprecated at version 3.14.0 and is no longer available.
0. This attempts to maximise parallelism, possibly at the expense
of extra communication. This is the default mode.
1. This minimises communication, possibly at the expense of the
degree of parallelism. If collapse is running slower than you
would expect, you can try changing to mode 1 to see if this
improves performance. This is only likely to work if the
output of collapse will be a sizeable array, not a single
point.
2. This is here for debugging purposes, but we would expect this
to maximise communication possibly at the expense of
parallelism. The use of this mode is, therefore, not
recommended.
:Parameters:
arg: `int` or `Constant`, optional
The new value (0, 1 or 2).
:Returns:
`Constant`
The value prior to the change, or the current value if no
new value was specified.
**Examples**
>>> cf.collapse_parallel_mode()
0
>>> cf.collapse_parallel_mode(1)
0
>>> cf.collapse_parallel_mode()
1
"""
_name = "COLLAPSE_PARALLEL_MODE"
def _parse(cls, arg):
"""Parse a new constant value.
Deprecated at version 3.14.0 and is no longer available.
.. versionaddedd:: 3.8.0
:Parameters:
cls:
This class.
arg:
The given new constant value.
:Returns:
A version of the new constant value suitable for insertion
into the `CONSTANTS` dictionary.
"""
# TODODASKAPI
_DEPRECATION_ERROR_FUNCTION(
"collapse_parallel_mode", version="3.14.0", removed_at="5.0.0"
) # pragma: no cover
class relaxed_identities(ConstantAccess):
"""Use 'relaxed' mode when getting a construct identity.
If set to True, sets ``relaxed=True`` as the default in calls to a
construct's `identity` method (e.g. `cf.Field.identity`).
This is used by construct arithmetic and field construct
aggregation.
:Parameters:
arg: `bool` or `Constant`, optional
:Returns:
`Constant`
The value prior to the change, or the current value if no
new value was specified.
**Examples**
>>> org = cf.relaxed_identities()
>>> org
False
>>> cf.relaxed_identities(True)
False
>>> cf.relaxed_identities()
True
>>> cf.relaxed_identities(org)
True
>>> cf.relaxed_identities()
False
"""
_name = "RELAXED_IDENTITIES"
def _parse(cls, arg):
"""Parse a new constant value.
.. versionaddedd:: 3.8.0
:Parameters:
cls:
This class.
arg:
The given new constant value.
:Returns:
A version of the new constant value suitable for insertion
into the `CONSTANTS` dictionary.
"""
return bool(arg)
class chunksize(ConstantAccess):
"""Set the default chunksize used by `dask` arrays.
If called without any arguments then the existing chunksize is
returned.
.. note:: Setting the chunk size will also change the `dask`
global configuration value ``'array.chunk-size'``. If
`chunksize` is used in a context manager then the `dask`
configuration value is only altered within that context.
Setting the chunk size directly from the `dask`
configuration API will affect subsequent data creation,
but will *not* change the value of `chunksize`.
:Parameters:
arg: number or `str` or `Constant`, optional
The chunksize in bytes. Any size accepted by
`dask.utils.parse_bytes` is accepted, for instance
``100``, ``'100'``, ``'1e6'``, ``'100 MB'``, ``'100M'``,
``'5kB'``, ``'5.4 kB'``, ``'1kiB'``, ``'1e6 kB'``, and
``'MB'`` are all valid sizes.
Note that if *arg* is a `float`, or a string that implies
a non-integral amount of bytes, then the integer part
(rounded down) will be used.
*Parameter example:*
A chunksize of 2 MiB may be specified as ``'2097152'``
or ``'2 MiB'``
*Parameter example:*
Chunksizes of ``'2678.9'`` and ``'2.6789 KB'`` are both
equivalent to ``2678``.
:Returns:
`Constant`
The value prior to the change, or the current value if no
new value was specified.
"""
_name = "CHUNKSIZE"
def _parse(cls, arg):
"""Parse a new constant value.
.. versionaddedd:: 3.8.0
:Parameters:
cls:
This class.
arg:
The given new constant value.
:Returns:
A version of the new constant value suitable for insertion
into the `CONSTANTS` dictionary.
"""
_config.set({"array.chunk-size": arg})
return parse_bytes(arg)
class tempdir(ConstantAccess):
"""The directory for internally generated temporary files.
When setting the directory, it is created if the specified path
does not exist.
:Parameters:
arg: `str`, optional
The new directory for temporary files. Tilde expansion (an
initial component of ``~`` or ``~user`` is replaced by
that *user*'s home directory) and environment variable
expansion (substrings of the form ``$name`` or ``${name}``
are replaced by the value of environment variable *name*)
are applied to the new directory name.
The default is to not change the directory.
:Returns:
`str`
The directory prior to the change, or the current
directory if no new value was specified.
**Examples**
>>> cf.tempdir()
'/tmp'
>>> old = cf.tempdir('/home/me/tmp')
>>> cf.tempdir(old)
'/home/me/tmp'
>>> cf.tempdir()
'/tmp'
"""
_name = "TEMPDIR"
def _parse(cls, arg):
"""Parse a new constant value.
.. versionaddedd:: 3.8.0
:Parameters:
cls:
This class.
arg:
The given new constant value.
:Returns:
A version of the new constant value suitable for insertion
into the `CONSTANTS` dictionary.
"""
arg = _os_path_expanduser(_os_path_expandvars(arg))
# Create the directory if it does not exist.
try:
mkdir(arg)
except OSError:
pass
return arg
class of_fraction(ConstantAccess):
"""The amount of concurrently open files above which files
containing data arrays may be automatically closed.
Deprecated at version 3.14.0 and is no longer available.
The amount is expressed as a fraction of the maximum possible
number of concurrently open files.
Note that closed files will be automatically reopened if
subsequently needed by a variable to access its data array.
.. seealso:: `cf.close_files`, `cf.close_one_file`,
`cf.open_files`, `cf.open_files_threshold_exceeded`
:Parameters:
arg: `float` or `Constant`, optional
The new fraction (between 0.0 and 1.0). The default is to
not change the current behaviour.
:Returns:
`Constant`
The value prior to the change, or the current value if no
new value was specified.
**Examples**
>>> cf.of_fraction()
0.5
>>> old = cf.of_fraction(0.33)
>>> cf.of_fraction(old)
0.33
>>> cf.of_fraction()
0.5
The fraction may be translated to an actual number of files as
follows:
>>> old = cf.of_fraction(0.75)
>>> import resource
>>> max_open_files = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
>>> threshold = int(max_open_files * cf.of_fraction())
>>> max_open_files, threshold
(1024, 768)
"""
_name = "OF_FRACTION"
def _parse(cls, arg):
"""Parse a new constant value.
Deprecated at version 3.14.0 and is no longer available.
.. versionaddedd:: 3.8.0
:Parameters:
cls:
This class.
arg:
The given new constant value.
:Returns:
A version of the new constant value suitable for insertion
into the `CONSTANTS` dictionary.
"""
# TODODASKAPI
_DEPRECATION_ERROR_FUNCTION(
"of_fraction", version="3.14.0", removed_at="5.0.0"
) # pragma: no cover
class free_memory_factor(ConstantAccess):
"""Set the fraction of memory kept free as a temporary workspace.
Deprecated at version 3.14.0 and is no longer available.
Users should set the free memory factor through cf.set_performance
so that the upper limit to the chunksize is recalculated
appropriately. The free memory factor must be a sensible value
between zero and one. If no arguments are passed the existing free
memory factor is returned.
:Parameters:
arg: `float` or `Constant`, optional
The fraction of memory kept free as a temporary workspace.
:Returns:
`Constant`
The value prior to the change, or the current value if no
new value was specified.
"""
_name = "FREE_MEMORY_FACTOR"
def _parse(cls, arg):
"""Parse a new constant value.
Deprecated at version 3.14.0 and is no longer available.
.. versionaddedd:: 3.8.0
:Parameters:
cls:
This class.
arg:
The given new constant value.
:Returns:
A version of the new constant value suitable for insertion
into the `CONSTANTS` dictionary.
"""
# TODODASKAPI
_DEPRECATION_ERROR_FUNCTION(
"free_memory_factor", version="3.14.0", removed_at="5.0.0"
) # pragma: no cover
class bounds_combination_mode(ConstantAccess):
"""Determine how to deal with cell bounds in binary operations.
The flag returned by ``cf.bounds_combination_mode()`` is used to
influence whether or not the result of a binary operation "op(x,
y)", such as ``x + y``, ``x -= y``, ``x << y``, etc., will contain
bounds, and if so how those bounds are calculated.
The result of op(x, y) may only contain bounds if
* ``x`` is a construct that may contain bounds, or
* ``x`` does not support the operation and ``y`` is a construct
that may contain bounds, e.g. ``2 + y``.