-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy path__init__.py
More file actions
1092 lines (857 loc) · 37.8 KB
/
Copy path__init__.py
File metadata and controls
1092 lines (857 loc) · 37.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
>>> import phoebe
Available environment variables:
* PHOEBE_ENABLE_PLOTTING=TRUE/FALSE (whether to import plotting libraries with phoebe: defaults to True)
* PHOEBE_ENABLE_SYMPY=TRUE/FALSE (whether to attempt to import sympy for constraint algebra: defaults to True if sympy installed, otherwise False)
* PHOEBE_ENABLE_ONLINE_PASSBANDS=TRUE/FALSE (whether to query for online passbands and download on-the-fly: defaults to True)
* PHOEBE_PBDIR (directory to search for passbands, in addition to phoebe.list_passband_directories())
* PHOEBE_DOWNLOAD_PASSBAND_DEFAULTS_GZIPPED=TRUE/FALSE (whether to download gzipped version of passbands by default. Defaults to False. Note that gzipped files take longer to load and will increase time for import, but take significantly less disk-space.)
* PHOEBE_DOWNLOAD_PASSBAND_DEFAULTS_CONTENT (default content, comma separated for list. Defaults to 'all')
* PHOEBE_UPDATE_PASSBAND_IGNORE_VERSION=TRUE/FALSE (update passbands that need new content even if the online version is newer than the installed version. Defaults to False.)
* PHOEBE_ENABLE_MPI=TRUE/FALSE (whether to use internal parallelization: defaults to True if within mpirun, otherwise False, can override in python with phoebe.mpi.on() and phoebe.mpi.off())
* PHOEBE_MPI_NPROCS=INT (number of procs to spawn in mpi is enabled but not running within mpirun: defaults to 4, only applicable if not within mpirun and PHOEBE_ENABLE_MPI=TRUE or phoebe.mpi.on() called, can override in python by passing nprocs to phoebe.mpi.on() or by setting phoebe.mpi.nprocs)
* PHOEBE_MULTIPROC_NPROCS=INT (number of proces to use within multiprocessing. Multiprocessing is used for solver that support it and when sampling over a distribution in run_compute if MPI is not in use. Set to 0 to disable multiprocessing and force serial. Defaults to number of CPUs available.)
* PHOEBE_PBDIR (directory to search for passbands, in addition to phoebe.list_passband_directories())
* PHOEBE_DEVEL=TRUE/FALSE enable developer mode by default
"""
__version__ = '2.4.18.dev+release-2.5'
import os as _os
import sys as _sys
import inspect as _inspect
import multiprocessing as _multiprocessing
import atexit
import re
# People shouldn't import phoebe from the root directory or from root/phoebe:
_root_dir = _os.path.abspath(_os.path.split(_os.path.split(__file__)[0])[0])
if _os.getcwd() == _root_dir or _os.path.join(_root_dir, 'phoebe') in _os.getcwd():
# We have a clash of package name with the standard library: we implement an
# "io" module and also they do. This means that you can import Phoebe from its
# main source tree; then there is no difference between io from here and io
# from the standard library. Thus, if the user loads the package from here
# it will never work. Instead of letting Python raise the io clash (which
# is uniformative to the unexperienced user), we raise the importError here
# with a helpful error message
raise ImportError('\n\tYou cannot import Phoebe from inside its main source tree.\n')
def _env_variable_string_or_list(key, default):
value = _os.getenv(key, default)
if "," in value:
return value.split(",")
else:
return value
def _env_variable_int(key, default):
value = _os.getenv(key, default)
return int(value)
def _env_variable_int_or_none(key, default):
value = _os.getenv(key, default)
if value is None or isinstance(value, str) and value.lower()=='none':
return None
if isinstance(value, str):
value = float(value)
return int(value)
def _env_variable_bool(key, default):
value = _os.getenv(key, default)
if isinstance(value, bool):
return value
elif value.upper()=='TRUE':
return True
else:
return False
# If we try to load matplotlib.pyplot on a non-X system, it will fail
# unless 'Agg' is used before the import. All X-systems define the
# 'DISPLAY' environment variable, and all non-X-systems do not. We do make a
# distinction between windows and unix based system. Hence:
if _env_variable_bool('PHOEBE_ENABLE_PLOTTING', True):
try:
import matplotlib
except ImportError:
pass
# we'll catch this later in plotting and throw warnings as necessary
else:
if 'DISPLAY' not in _os.environ.keys() and _sys.platform not in ['win32','cygwin']:
matplotlib.use('Agg')
elif hasattr(_sys, 'real_prefix'):
# then we're likely in a virtualenv. Our best bet is to use the 'TkAgg'
# backend, but this will require python-tk to be installed on the system
try:
matplotlib.use('Agg')
except:
matplotlib.use('TkAgg')
import logging
_logger = logging.getLogger("PHOEBE")
_logger.addHandler(logging.NullHandler())
###############################################################################
######################### BEGIN MPI ##########################
###############################################################################
# detect if we're within mpirun and if so, place all non-zero-rank
# processors into a wait loop. This must happen before we start importing from
# phoebe so that those can have access to the _mpi object.
class MPI(object):
def __init__(self):
# this is a bit of a hack and will only work with openmpi, but environment
# variables seem to be the only way to detect whether the script was run
# via mpirun or not
evars = _os.environ.keys()
if 'OMPI_COMM_WORLD_SIZE' in evars or 'MV2_COMM_WORLD_SIZE' in evars or 'PMI_SIZE' in evars:
from mpi4py import MPI as mpi4py
self._within_mpirun = True
self._internal_mpi = True
self._comm = mpi4py.COMM_WORLD
self._myrank = self.comm.Get_rank()
self._nprocs = self.comm.Get_size()
if self._nprocs==1:
raise ImportError("need more than 1 processor to run with mpi")
self._enabled = _env_variable_bool("PHOEBE_ENABLE_MPI", True)
else:
self._within_mpirun = False
self._internal_mpi = False
self._comm = None
self._myrank = 0
self._nprocs = _env_variable_int("PHOEBE_MPI_NPROCS", 4)
self._enabled = _env_variable_bool("PHOEBE_ENABLE_MPI", False)
def __repr__(self):
return "<MPI mode={} myrank={} nprocs={}>".format(self.mode, self.myrank, self.nprocs)
@property
def mode(self):
if self.within_mpirun:
if self.enabled:
return "internal handling of mpi within mpirun"
else:
return "external handling of mpi by the user within mpirun"
else:
if self.enabled:
return "internal handling of mpi in spawned separate threads during run_compute"
else:
return "serial mode"
@property
def enabled(self):
return self._enabled
def on(self, nprocs=None):
if self.within_mpirun and not self.enabled:
raise ValueError("cannot enable mpi after disabling within mpirun.")
self._enabled = True
if nprocs is not None:
self.nprocs = nprocs
def off(self):
if self.within_mpirun and self.enabled and self.myrank == 0:
self.comm.bcast({'worker_command': 'release'}, root=0)
self._enabled = False
@property
def myrank(self):
return self._myrank
@property
def nprocs(self):
if not self.enabled and not self.within_mpirun:
return 1
else:
return self._nprocs
@nprocs.setter
def nprocs(self, nprocs):
if self.within_mpirun:
_logger.warning("ignoring setting nprocs while within mpirun, nprocs={}".format(self.nprocs))
else:
self._nprocs = nprocs
@property
def comm(self):
return self._comm
@property
def within_mpirun(self):
return self._within_mpirun
@property
def detach_cmd(self):
if self.within_mpirun:
raise ValueError("detach not available within mpirun")
# TODO: allow this as an option in the settings?
python = 'python3'
if self.enabled:
return 'mpiexec -np %d %s {}' % (self.nprocs, python)
else:
return '%s {}' % python
def shutdown_workers(self):
if self.within_mpirun and self.myrank == 0:
self.comm.bcast({'worker_command': 'shutdown'}, root=0)
self._enabled = False
# even though technically not true, we're now strictly serial and have no way of regaining the workers
self._within_mpirun = False
mpi = MPI()
# NOTE: logic for worker waiting for tasks below after phoebe imports
###############################################################################
########################## END MPI ###########################
###############################################################################
###############################################################################
######################### BEGIN SETTINGS ########################
###############################################################################
class Settings(object):
def __init__(self):
# Check to see whether in interactive mode
import __main__
# hasattr(__main__, '__file__') will be True if running a python script, but
# false if in a python or ipython interpreter.
# _sys.flags.interactive will be 1 if the -i flag is sent to python
# For now we'll set interactive_constraints to True by default, requiring it to
# explicitly be disabled.
# See #154 (https://github.com/phoebe-project/phoebe2/issues/154)
self._interactive_constraints = True
# We'll set interactive system checks to be off by default (new in 2.4)
self._interactive_checks = False
self._download_passband_defaults = {'content': _env_variable_string_or_list('PHOEBE_DOWNLOAD_PASSBAND_DEFAULTS_CONTENT', 'all'),
'gzipped': _env_variable_bool('PHOEBE_DOWNLOAD_PASSBAND_DEFAULTS_GZIPPED', False)}
self._update_passband_ignore_version = _env_variable_bool('PHOEBE_UPDATE_PASSBAND_IGNORE_VERSION', False)
self._multiprocessing_nprocs = _env_variable_int_or_none('PHOEBE_MULTIPROC_NPROCS', None)
self._progressbars = True
# And we'll require explicitly setting developer mode on
self._devel = _env_variable_bool('PHOEBE_DEVEL', False)
def __repr__(self):
return "<Settings interactive_checks={} interactive_constraints={}>".format(self.interactive_checks, self.interactive_constraints)
def reset(self):
self.__init__()
def interactive_on(self):
self.interactive_checks_on()
self.interactive_constraints_on()
def interactive_off(self, suppress_warning=False):
self.interactive_checks_off(suppress_warning=suppress_warning)
self.interactive_constraints_off(suppress_warning=suppress_warning)
def interactive_checks_on(self):
self._interactive_checks = True
def interactive_checks_off(self, suppress_warning=False):
if not suppress_warning:
_logger.warning("checks will not be run until 'run_checks' or 'run_compute' is called.")
self._interactive_checks = False
def interactive_constraints_on(self):
self._interactive_constraints = True
def interactive_constraints_off(self, suppress_warning=False):
if not suppress_warning:
_logger.warning("constraints will not be run until 'run_delayed_constraints' or 'run_compute' is called. This may result in inconsistent parameters if printing values before calling either of these methods.")
self._interactive_constraints = False
@property
def interactive_checks(self):
return self._interactive_checks
@property
def interactive_constraints(self):
return self._interactive_constraints
def devel_on(self):
self._devel = True
def devel_off(self):
self._devel = False
@property
def devel(self):
return self._devel
def set_download_passband_defaults(self, **kwargs):
"""
"""
for k,v in kwargs.items():
if k not in self._download_passband_defaults.keys():
raise KeyError("{} must be one of {}".format(self._download_passband_defaults.keys()))
if k=='content' and not (isinstance(v, str) or isinstance(v, list)):
raise TypeError("content must be of type string or list")
if k=='gzipped' and not (isinstance(v, bool)):
raise TypeError("gzipped must be of type bool")
self._download_passband_defaults[k] = v
def get_download_passband_defaults(self):
return self._download_passband_defaults
@property
def download_passband_defaults(self):
return self._download_passband_defaults
@property
def update_passband_ignore_version(self):
return self._update_passband_ignore_version
def update_passband_ignore_version_on(self):
self._update_passband_ignore_version = True
def update_passband_ignore_version_on(self):
self._update_passband_ignore_version = False
def multiprocessing_off(self):
self._multiprocessing_nprocs = 0
def multiprocessing_on(self):
self._multiprocessing_nprocs = None
def multiprocessing_set_nprocs(self, value):
if not isinstance(value, int):
return TypeError("must be integer")
if value > _multiprocessing.cpu_count():
return ValueError("only {} CPUs available".format(value))
elif value < 0:
return ValueError("nprocs must be >= 0")
self._multiprocessing_nprocs = value
@property
def multiprocessing_nprocs(self):
if self._multiprocessing_nprocs is None:
return _multiprocessing.cpu_count()
return self._multiprocessing_nprocs
def progressbars_on(self):
self._progressbars = True
def progressbars_off(self):
self._progressbars = False
@property
def progressbars(self):
return self._progressbars
conf = Settings()
###############################################################################
########################## END SETTINGS #########################
###############################################################################
# make packages available at top-level
from .dependencies.unitsiau2015 import u,c
from .dependencies.nparray import array, linspace, arange, logspace, geomspace, invspace
from .dependencies.distl import gaussian, gaussian_around, normal, boxcar, uniform, uniform_around, histogram_from_bins, histogram_from_data, mvgaussian, mvhistogram_from_data
from .atmospheres.passbands import install_passband, uninstall_passband, uninstall_all_passbands, download_passband, list_passband_online_history, update_passband_available, update_passband, update_all_passbands, list_all_update_passbands_available, list_online_passbands, list_installed_passbands, list_passbands, list_passband_directories, get_passband
from .parameters import hierarchy, component, compute, constraint, dataset, feature, figure, solver, server
from .frontend.bundle import Bundle
from .backend import backends as _backends
from .solverbackends import solverbackends as _solverbackends
from . import utils as _utils
from . import dynamics as dynamics
from . import distortions as distortions
from . import algorithms as algorithms
from . import features as features
import libphoebe
# Shortcut to building logger
def logger(*args, **kwargs):
"""
Return a basic logger via a log file and/or terminal.
Example 1: log only to the console, accepting levels "INFO" and above
```py
logger = logger()
```
Example 2: log only to the console, accepting levels "DEBUG" and above
```py
logger(clevel='DEBUG')
```
Example 3: log only to a file, accepting levels "DEBUG" and above
```py
logger(clevel=None,filename='mylog.log')
```
Example 4: log only to a file, accepting levels "INFO" and above
```py
logger(clevel=None,flevel='INFO',filename='mylog.log')
```
Example 5: log to the terminal (INFO and above) and file (DEBUG and above)
```py
logger(filename='mylog.log')
```
Arguments
----------
* `clevel` (string, optional): level to be logged to the console.
One of: "ERROR", "WARNING", "INFO", "DEBUG".
* `flevel` (string, optional): level to be logged to the file.
Must also provide `filename`. One of: "ERROR", "WARNING", "INFO", "DEBUG".
* `filename` (string, optional): path to the file to log at the `flevel` level.
* `style` (string, optional, default='default'): style to use for logging.
One of: "default", "minimal", "grandpa".
"""
if mpi.within_mpirun and mpi.myrank == 0:
# tell the workers to invoke the same logger
mpi.comm.bcast({'worker_command': 'logger', 'args': args, 'kwargs': kwargs}, root=0)
return _utils.get_basic_logger(*args, **kwargs)
if mpi.within_mpirun and mpi.enabled and mpi.myrank != 0:
while True:
packet = mpi.comm.bcast(None, root=0)
if packet.get('worker_command', False) == 'shutdown':
_logger.debug("rank:{}/{} message to shutdown".format(mpi.myrank, mpi.nprocs))
exit()
if packet.get('worker_command', False) == 'release':
_logger.debug("rank:{}/{} message to release".format(mpi.myrank, mpi.nprocs))
break
elif packet.get('worker_command', False) == 'logger':
_logger.debug("rank:{}/{} message to invoke logger".format(mpi.myrank, mpi.nprocs))
logger(*packet['args'], **packet['kwargs'])
elif hasattr(_backends, packet.get('backend', False)):
backend = getattr(_backends, packet.pop('backend'))()
backend._run_worker(packet)
elif hasattr(_solverbackends, packet.get('backend', False)):
backend = getattr(_solverbackends, packet.pop('backend'))()
backend._run_worker(packet)
else:
raise ValueError("could not recognize packet: {}".format(packet))
# Shortcuts to bundle classmethods
def open(*args, **kwargs):
return Bundle.open(*args, **kwargs)
open.__doc__ = Bundle.open.__doc__
def load(*args, **kwargs):
return Bundle.open(*args, **kwargs)
load.__doc__ = Bundle.open.__doc__
def from_legacy(*args, **kwargs):
return Bundle.from_legacy(*args, **kwargs)
from_legacy.__doc__ = Bundle.from_legacy.__doc__
def from_server(*args, **kwargs):
return Bundle.from_server(*args, **kwargs)
from_server.__doc__ = Bundle.from_server.__doc__
def default_star(*args, **kwargs):
return Bundle.default_star(*args, **kwargs)
default_star.__doc__ = Bundle.default_star.__doc__
def default_binary(*args, **kwargs):
return Bundle.default_binary(*args, **kwargs)
default_binary.__doc__ = Bundle.default_binary.__doc__
def default_contact_binary(*args, **kwargs):
return Bundle.default_contact_binary(*args, **kwargs)
default_contact_binary.__doc__ = Bundle.default_contact_binary.__doc__
# Shortcuts to settings
def reset_settings():
"""
Reset all configuration settings (interactivity, etc) but NOT MPI settings.
See also:
* <phoebe.interactive_on>
* <phoebe.interactive_off>
* <phoebe.interactive_constraints_on>
* <phoebe.interactive_constraints_off>
* <phoebe.interactive_checks_on>
* <phoebe.interactive_checks_off>
"""
conf.reset()
def interactive_on():
"""
Turn on both interactive constraints and interactive checks
See also:
* <phoebe.interactive_off>
* <phoebe.interactive_constraints_on>
* <phoebe.interactive_checks_on>
"""
conf.interactive_on()
def interactive_off():
"""
**USE WITH CAUTION**
Turn off both interactive constraints and interactive checks
See also:
* <phoebe.interactive_on>
* <phoebe.interactive_constraints_off>
* <phoebe.interactive_checks_off>
"""
conf.interactive_off()
def interactive_constraints_on():
"""
Turn interactive constraints on. When enabled, PHOEBE will update all
constraints whenever a <phoebe.parameters.Parameter> value is changed.
Although this adds to the run-time, it ensures that all values are updated
when accessed.
By default, interactive constraints are always on unless disabled.
See also:
* <phoebe.interactive_constraints_off>
"""
conf.interactive_constraints_on()
def interactive_constraints_off():
"""
**USE WITH CAUTION**
Turn interactive constraints off. When disabled, PHOEBE will **NOT** update
constraints whenever a <phoebe.parameters.Parameter> value is changed, but
will instead wait until needed (for example, by
<phoebe.frontend.bundle.Bundle.run_compute>). Accessing/printing the value
of a constrained Parameter, may be out-of-date when interactive constraints
is off.
By default, interactive constraints are always on unless disabled.
To update constraints manually, you can call
<phoebe.frontend.bundle.Bundle.run_delayed_constraints>.
See also:
* <phoebe.interactive_constraints_on>
"""
conf.interactive_constraints_off()
def interactive_checks_on():
"""
Turn interactive checks on. When enabled, PHOEBE will run system checks
(<phoebe.frontend.bundle.Bundle.run_checks>) after any
<phoebe.parameters.Parameter> value is changed and will log any issues
to the logger as a warning. In order to see these messages, you must
have a logger enabled with at least the "WARNING" level (see <phoebe.logger>).
Whether interactive checks is on or off, system checks will be run when
calling <phoebe.frontend.bundle.Bundle.run_compute> and will raise
an error if failing.
By default, interactive checks is OFF (in 2.4).
See also:
* <phoebe.interactive_checks_off>
"""
conf.interactive_checks_on()
def interactive_checks_off():
"""
Turn interactive checks off. When disabled, PHOEBE will **NOT** run system checks
(<phoebe.frontend.bundle.Bundle.run_checks>) after any
<phoebe.parameters.Parameter> value is changed and will **NOT** log any issues
to the logger as a warning.
Whether interactive checks is on or off, system checks will be run when
calling <phoebe.frontend.bundle.Bundle.run_compute> and will raise
an error if failing.
To manually run system checks at any time, you can call
<phoebe.frontend.bundle.Bundle.run_checks>.
By default, interactive checks is OFF (new in 2.4).
See also:
* <phoebe.interactive_checks_on>
"""
conf.interactive_checks_off()
def devel_on():
conf.devel_on()
def devel_off():
conf.devel_off()
def set_download_passband_defaults(**kwargs):
"""
Set default options to use for <phoebe.atmospheres.passbands.download_passband>.
These can also be set at import time via the following environment variables:
* PHOEBE_DOWNLOAD_PASSBAND_DEFAULTS_CONTENT (defaults to 'all')
* PHOEBE_DOWNLOAD_PASSBAND_DEFAULTS_GZIPPED (defaults to FALSE)
See also:
* <phoebe.get_download_passband_defaults>
* <phoebe.atmospheres.passbands.download_passband>
* <phoebe.atmospheres.passbands.update_passband>
* <phoebe.atmospheres.passbands.get_passband>
Arguments
------------
* `content` (string or list, optional): override the current value for
`content` in <phoebe.get_download_passband_defaults>.
* `gzipped` (bool, optional): override the current value for `gzipped`
in <phoebe.get_download_passband_defaults>.
"""
conf.set_download_passband_defaults(**kwargs)
def get_download_passband_defaults():
"""
Access default options to use for <phoebe.atmospheres.passbands.download_passband>.
See also:
* <phoebe.set_download_passband_defaults>
* <phoebe.atmospheres.passbands.download_passband>
* <phoebe.atmospheres.passbands.update_passband>
* <phoebe.atmospheres.passbands.get_passband>
Returns
---------
* dictionary of defaults, including `content` and `gzipped`.
"""
return conf.get_download_passband_defaults()
def update_passband_ignore_version_on():
"""
Turn ingoring passband versions when checking for necessary updates on.
<phoebe.frontend.bundle.Bundle.run_checks_compute> checks to see if any
additional content is required from the used passbands. If so, these will
be queried from the online tables if the timestamps match. Otherwise, an
error will be raised requiring manually calling <phoebe.atmospheres.passbands.update_passband>.
By enabling this, this version conflict will be ignored, preventing the need
to manually update the passbands.
This can also be set at import time via the following environment variables:
* PHOEBE_UPDATE_PASSBAND_IGNORE_VERSION (defaults to FALSE)
See also:
* <phoebe.update_passband_ignore_version_off>
"""
conf.update_passband_ignore_version_on()
def update_passband_ignore_version_off():
"""
Turn ingoring passband versions when checking for necessary updates off.
<phoebe.frontend.bundle.Bundle.run_checks_compute> checks to see if any
additional content is required from the used passbands. If so, these will
be queried from the online tables if the timestamps match. Otherwise, an
error will be raised requiring manually calling <phoebe.atmospheres.passbands.update_passband>.
This can also be set at import time via the following environment variables:
* PHOEBE_UPDATE_PASSBAND_IGNORE_VERSION (defaults to FALSE)
See also:
* <phoebe.update_passband_ignore_version_on>
"""
conf.update_passband_ignore_version_on()
# Shortcuts to MPI options
def mpi_on(nprocs=None):
"""
ENABLE PHOEBE to use MPI (parallelization).
Default case:
* If PHOEBE is run within an mpirun environment, MPI is ENABLED by default.
* If PHOEBE is not run within an mpirun environment, MPI is DISABLED by default.
When MPI is enabled, PHOEBE will do the following:
* if within mpirun: uses PHOEBE's built-in per-dataset or per-time
parallelization for <phoebe.frontend.bundle.Bundle.run_compute>
and per-model parallelization when possible for
<phoebe.frontend.bundle.Bundle.run_solver>.
* if not within mpirun (ie. in a serial python environment): will spawn a
separate thread at <phoebe.frontend.bundle.Bundle.run_compute>
and <phoebe.frontend.bundle.Bundle.run_solver>,
using `nprocs` processors. This separate thread will be detached
from the main thread if sending `detach=True` to
<phoebe.frontend.bundle.Bundle.run_compute> or
<phoebe.frontend.bundle.Bundle.run_solver>.
See also:
* <phoebe.mpi_off>
Arguments
----------
* `nprocs` (int, optional): number of processors. Only applicable if **NOT**
within mpirun (see above).
"""
mpi.on(nprocs=nprocs)
def mpi_off():
"""
Run PHOEBE in Serial Mode.
Default case:
* If PHOEBE is run within an mpirun environment, MPI is ENABLED by default.
* If PHOEBE is not run within an mpirun environment, MPI is DISABLED by default.
When MPI is disabled, PHOEBE will do the following:
* if within mpirun: PHOEBE will run equally on all processors. The user can
customize parallelization with access to `phoebe.mpi.nprocs`,
`phoebe.mpi.myrank`.
* if not within mpirun (ie. in a serial python environment): PHOEBE will
run on a single processor in serial-mode. Compute jobs can still
be detached from the main thread by sending `detach=True` to
<phoebe.frontend.bundle.Bundle.run_compute> or
<phoebe.frontend.bundle.Bundle.run_solver> but will still run
on a single processor.
See also:
* <phoebe.mpi_on>
"""
mpi.off()
def multiprocessing_on():
"""
Enable multiprocessing to use all CPUs available (this is the state by default).
MPI will always take preference over multiprocessing. See <phoebe.mpi_on>
and <phoebe.mpi_off>.
Multiprocessing is used by
<phoebe.frontend.bundle.Bundle.run_solver> (for some solvers) and
<phoebe.frontend.bundle.Bundle.run_compute> when `sample_from` is used.
See also:
* <phoebe.multiprocessing_off>
* <phoebe.multiprocessing_get_nprocs>
* <phoebe.multiprocessing_set_nprocs>
"""
conf.multiprocessing_on()
def multiprocessing_off():
"""
Disable multiprocessing and force serial mode (if MPI is also off: see
<phoebe.mpi_on> and <phoebe.mpi_off>).
See also:
* <phoebe.multiprocessing_on>
* <phoebe.multiprocessing_get_nprocs>
* <phoebe.multiprocessing_set_nprocs>
"""
conf.multiprocessing_off()
def multiprocessing_get_nprocs():
"""
Get the number of processors used within multiprocessing.
MPI will always take preference over multiprocessing. See <phoebe.mpi_on>
and <phoebe.mpi_off>.
Multiprocessing is used by
<phoebe.frontend.bundle.Bundle.run_solver> (for some solvers) and
<phoebe.frontend.bundle.Bundle.run_compute> when `sample_from` is used.
See also:
* <phoebe.multiprocessing_on>
* <phoebe.multiprocessing_off>
* <phoebe.multiprocessing_set_nprocs>
"""
return conf.multiprocessing_nprocs
def multiprocessing_set_nprocs(nprocs):
"""
Set a custom number of processors to use within multiprocessing.
MPI will always take preference over multiprocessing. See <phoebe.mpi_on>
and <phoebe.mpi_off>.
Multiprocessing is used by
<phoebe.frontend.bundle.Bundle.run_solver> (for some solvers) and
<phoebe.frontend.bundle.Bundle.run_compute> when `sample_from` is used.
See also:
* <phoebe.multiprocessing_on>
* <phoebe.multiprocessing_off>
* <phoebe.multiprocessing_get_nprocs>
"""
conf.multiprocessing_set_nprocs(nprocs)
def progressbars_on():
"""
Enable progressbars. Progressbars require `tqdm` to be installed
(will silently ignore if not installed).
See also:
* <phoebe.progressbars_off>
"""
conf.progressbars_on()
def progressbars_off():
"""
Disable progressbars. Progressbars require `tqdm` to be installed
(will silently ignore if not installed).
See also:
* <phoebe.progressbars_on>
"""
conf.progressbars_off()
# let's use magic to shutdown the workers when the user-script is complete
atexit.register(mpi.shutdown_workers)
# edit API docs for imported functions
def strip_docstring_refs(matchobj):
text = matchobj.group(0)
path = text[1:-1]
return path
def add_nparray_docstring(obj):
docsprefix = """This is an included dependency from [nparray 1.2.0](https://nparray.readthedocs.io/en/1.2.0/).\n\n===============================================================\n\n"""
docstring = docsprefix + "\n".join([l.lstrip() for l in obj.__doc__.split("\n")])
docstring = re.sub(r"(?P<name>\<[0-9a-zA-Z_\.]*\>)", strip_docstring_refs, docstring)
obj.__doc__ = docstring
add_nparray_docstring(array)
add_nparray_docstring(linspace)
add_nparray_docstring(arange)
add_nparray_docstring(logspace)
add_nparray_docstring(geomspace)
add_nparray_docstring(invspace)
def add_distl_docstring(obj):
docsprefix = """This is an included dependency from [distl](https://distl.readthedocs.io).\n\n===============================================================\n\n"""
docstring = docsprefix + "\n".join([l.lstrip() for l in obj.__doc__.split("\n")])
docstring = re.sub(r"(?P<name>\<[0-9a-zA-Z_\.]*\>)", strip_docstring_refs, docstring)
obj.__doc__ = docstring
add_distl_docstring(uniform)
add_distl_docstring(boxcar)
# add_distl_docstring(delta)
add_distl_docstring(gaussian)
add_distl_docstring(normal)
add_distl_docstring(histogram_from_bins)
add_distl_docstring(histogram_from_data)
add_distl_docstring(mvgaussian)
add_distl_docstring(mvhistogram_from_data)
add_distl_docstring(uniform_around)
add_distl_docstring(gaussian_around)
# expose available "kinds" per-context
def _get_phoebe_funcs(module, devel=False):
ignore = ['_empty_array', 'deepcopy', 'fnmatch',
'download_passband', 'list_installed_passbands', 'list_online_passbands', 'list_passbands', 'parameter_from_json', 'parse_json',
'send_if_client', 'update_if_client',
'_add_component', '_add_dataset', '_label_units_lims', '_run_compute',
'phase_mask_inds']
if not devel:
ignore += ['pulsation']
mod_split = module.__name__.split('.')
if mod_split[-1] in ['figure'] or (mod_split[-1] in ['solver'] and 'figure' not in mod_split):
ret = []
for sub_module in _inspect.getmembers(module):
if _inspect.ismodule(sub_module[1]):
ret += [sub_module[0]+"."+o for o in _get_phoebe_funcs(sub_module[1], devel=devel)]
return ret
return [o[0] for o in _inspect.getmembers(module) if _inspect.isfunction(o[1]) and o[0] not in ignore and o[0][0] != '_']
def list_available_components(devel=False):
"""
List all available 'kinds' for component from <phoebe.parameters.component>.
See also:
* <phoebe.list_available_features>
* <phoebe.list_available_datasets>
* <phoebe.list_available_computes>
* <phoebe.list_available_solvers>
* <phoebe.list_available_servers>
* <phoebe.list_available_figures>
Arguments
-----------
* `devel` (bool, default, optional=False): whether to include development-only
kinds. See <phoebe.devel_on>.
Returns
---------
* (list of strings)
"""
return _get_phoebe_funcs(component, devel=devel)
def list_available_features(devel=False):
"""
List all available 'kinds' for feature from <phoebe.parameters.feature>.
See also:
* <phoebe.list_available_components>
* <phoebe.list_available_datasets>
* <phoebe.list_available_computes>
* <phoebe.list_available_solvers>
* <phoebe.list_available_servers>
* <phoebe.list_available_figures>
Arguments
-----------
* `devel` (bool, default, optional=False): whether to include development-only
kinds. See <phoebe.devel_on>.
Returns
---------
* (list of strings)
"""
return list(feature._feature_classes.keys())
def list_available_datasets(devel=False):
"""
List all available 'kinds' for dataset from <phoebe.parameters.dataset>.
See also:
* <phoebe.list_available_components>
* <phoebe.list_available_features>
* <phoebe.list_available_computes>
* <phoebe.list_available_solvers>
* <phoebe.list_available_servers>
* <phoebe.list_available_figures>
Arguments
-----------
* `devel` (bool, default, optional=False): whether to include development-only
kinds. See <phoebe.devel_on>.
Returns
---------
* (list of strings)
"""
return _get_phoebe_funcs(dataset, devel=devel)
def list_available_figures(devel=False):
"""
List all available 'kinds' for figure from <phoebe.parameters.figure>.
See also:
* <phoebe.list_available_components>
* <phoebe.list_available_features>
* <phoebe.list_available_computes>
* <phoebe.list_available_solvers>
* <phoebe.list_available_servers>
Arguments
-----------
* `devel` (bool, default, optional=False): whether to include development-only
kinds. See <phoebe.devel_on>.
Returns
---------
* (list of strings)
"""
return _get_phoebe_funcs(figure, devel=devel)
def list_available_servers(devel=False):
"""