-
Notifications
You must be signed in to change notification settings - Fork 20
/
module_generator.py
3638 lines (3057 loc) · 142 KB
/
module_generator.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
from __future__ import division, print_function
import os
import sys
import six
import xpsi
def write(filename, module):
with open(filename, 'w') as mod:
_module = ''''''
for _line in module.splitlines():
if _module:
_module += '\n'
_module += _line.rstrip()
mod.write(_module)
nindent = '\n '
indent = ' '
import argparse
import re
class ArgumentParserCustom(argparse.ArgumentParser):
def convert_arg_line_to_args(self, arg_line):
if (re.match(r'^[\s]*#', arg_line) or # look for any number of whitespace characters up to a `#` character
re.match(r'^[\s]*$', arg_line)): # look for lines containing nothing or just whitespace
return []
else:
try:
_idx = arg_line.index('#')
except ValueError:
pass
else:
arg_line = arg_line[:_idx].rstrip()
if xpsi._verbose:
print(arg_line)
return [arg_line]
def add_argument(self, *args, **kwargs):
if kwargs.pop('destined_for_config_file', True) and args[0] != '-h':
_ = (args[0],
kwargs.get('default', None),
kwargs.get('nargs', 1) if kwargs.get('action') != 'store_true' else 0,
kwargs.pop('comment_line_above', None),
kwargs.pop('empty_lines_below', 0),
kwargs.pop('comment', False),
kwargs.pop('inline_comment', None),
kwargs.get('action', None))
try:
self._config_file_args
except AttributeError:
self._config_file_args = [_]
else:
self._config_file_args.append(_)
else:
_ = kwargs.pop('comment_line_above', None)
_ = kwargs.pop('empty_lines_below', 0)
_ = kwargs.pop('comment', False)
_ = kwargs.pop('inline_comment', None)
super(ArgumentParserCustom, self).add_argument(*args, **kwargs)
class GenerateConfigAction(argparse.Action):
def __init__(self, option_strings, dest, **kwargs):
super(GenerateConfigAction, self).__init__(option_strings, dest, nargs=0, **kwargs)
@staticmethod
def _typeset(arg, default, nargs, comment_line_above, empty_lines_below, comment, inline_comment, action, newline=True):
entry = '\n' if newline else ''
if comment_line_above is not None:
if comment_line_above == 'rule':
entry += '#' + '-'*78 + '#\n'
else:
_ = '## {} ##'.format(comment_line_above)
entry += '##' + '-' * (len(_) - 4) + '##\n' + _ + '\n##' + '-' * (len(_) - 4) + '##\n'
_ = ' ## {}'.format(inline_comment) if inline_comment is not None else ''
if not _ and isinstance(nargs, int) and nargs > 1:
_ = ' ## enter {} values below, one per empty line'.format(nargs)
elif not _ and not isinstance(nargs, int):
_ = ' ## enter code below, one statement per line'
if isinstance(default, list):
for i, _default in enumerate(default):
entry += '{5}{0}{1}{2}{3}{4}'.format('#' if comment else '',
'' if (i > 0 and nargs != 1) else arg,
'' if nargs != 1 else '=',
'' if (i == 0 and nargs != 1) else str(_default),
(_ if i == 0 else '') + ('\n{0}{1}'.format('#' if comment else '', str(_default)) if i == 0 and nargs != 1 else ''),
'\n' if i > 0 else '')
else:
entry += '{0}{1}{2}{3}{4}'.format('#' if comment else '',
arg,
'=' if nargs == 1 else '',
_ if nargs != 1 else (str(default) if default is not None else ''),
('\n' + str(default) if default is not None else '') if nargs != 1 else _)
if action == 'append':
entry += '\n#{0}='.format(arg)
if isinstance(nargs, int) and nargs > 1:
entry += '\n' * nargs
elif isinstance(nargs, str):
entry += '\n' * 3
entry += '\n' * empty_lines_below
return entry
def __call__(self, parser, namespace, values, option_string=None):
for _ in parser._config_file_args:
try:
config_file
except NameError:
config_file = self._typeset(*_, newline=False)
else:
config_file += self._typeset(*_)
with open('./generate.ini', 'w') as file:
file.write(config_file)
print('Configuration file generated.')
parser.exit()
parser = ArgumentParserCustom(
description='''
Script for automated generation of X-PSI model module set.
Usage: python %(prog)s [-h] @<generate.ini>
''',
fromfile_prefix_chars='@')
parser.add_argument('--generate-config-file', default=argparse.SUPPRESS, action=GenerateConfigAction, help='Generate the meta configuration file template.',
destined_for_config_file=False)
parser.add_argument('--telescope',
type=str,
action='append',
help='Telescope name, e.g., NICER. Use argument once per telescope name, and no whitespaces.',
comment_line_above='telescope instrument flags')
parser.add_argument('--instrument',
type=lambda x: str(x).replace(' ', '_').replace('-', '_'),
action='append',
help='Name of an instrument on-board a telescope, e.g., XTI. Can use one or more instrument names per telescope name, and no whitespaces.',
empty_lines_below=2)
parser.add_argument('--source',
type=str,
help='The name of the star, e.g., PSR J0740+6620.',
comment_line_above='target source flags')
parser.add_argument('--frequency',
type=float,
required=True,
help='The coordinate spin frequency of the star (Hz).',
empty_lines_below=2)
parser.add_argument('--model',
type=str,
help='A custom model name, e.g., ST-U + NSX-H, otherwise the model name is constructed from other arguments.',
comment_line_above='model flags',
comment=True)
parser.add_argument('--hot-region-model',
type=str,
action='append',
choices=['ST', 'CST', 'EST', 'PST', 'CDT', 'EDT', 'PDT'],
required=True,
help='The name of the hot-region model, e.g., ST. Maximum of two argument uses.')
parser.add_argument('--antipodal-reflection-symmetry',
action='store_true',
help='Are the two hot regions related via antipodal reflection symmetry? E.g., ST-S.',
comment=True)
parser.add_argument('--break-hot-region-exchange-degeneracy-with',
type=str,
default='super_colatitude',
help='Hot region parameter name to break hot-region exchange degeneracy with when there are two hot-regions of the same type that are not antipodally reflection-symmetric, e.g., ST+ST (ST-U). An example is e.g., "super_temperature".',
comment=True)
def str_to_bool(x):
if x == 'False':
return False
elif x == 'True':
return True
raise ValueError('Invalid argument where boolean ``True`` or ``False`` is required.')
parser.add_argument('--is-antiphased',
type=str_to_bool,
action='append',
help='Specify whether the hot regions are anti-phased w.r.t to Earth.')
parser.add_argument('--prefix',
type=str,
action='append',
help='Specify the prefixes for hot region parameter naming.')
parser.add_argument('--hot-atmosphere-model',
type=str,
help='Name of atmosphere model within hot regions, e.g., blackbody or NSX-H.')
parser.add_argument('--hot-atmosphere-load',
action='store_true',
help='Does a numeric atmosphere table need to be loaded from disk for the hot regions?',
comment=True)
parser.add_argument('--elsewhere-atmosphere-model',
type=str,
help='Name of atmosphere model elsewhere, e.g., blackbody or NSX-H.')
parser.add_argument('--elsewhere-atmosphere-load',
action='store_true',
help='Does a numeric atmosphere table need to be loaded from disk for elsewhere?',
comment=True)
parser.add_argument('--attenuation-model',
type=str,
help='Name of interstellar attenuation model, e.g., tbnew.',
empty_lines_below=2)
parser.add_argument('--background-model',
action='store_true',
help='Include an incident background component?',
comment=True)
parser.add_argument('--background-shared-instance',
action='store_true',
help='Do all instruments share the same background model instance?')
parser.add_argument('--background-shared-class',
action='store_true',
help='Do all instrument models share a background class?')
parser.add_argument('--background-parameters',
type=lambda x: ( str(x).replace(' ', '_') ).replace('-', '_'),
nargs='*',
default=['powerlaw_index', 'powerlaw_normalization'],
help='Background model parameter names.',
comment=True,
inline_comment='enter one name per line below',
empty_lines_below=2)
parser.add_argument('--print-MPI-rank',
action='store_true',
help='Print MPI rank from main module?',
comment_line_above='miscellaneous flags',
empty_lines_below=2)
parser.add_argument('--config-path',
type=str,
help='If main module is imported, use this argument to specify the relative or absolute path to the configuration file.',
comment_line_above='write flags')
parser.add_argument('--module-directory-path',
type=str,
help='Absolute path to directory to write module files to.')
parser.add_argument('--main-module',
type=str,
default='main',
help='Name of the main module.')
parser.add_argument('--custom-signal-module',
type=str,
default='CustomSignal',
help='Name of the module containing the CustomSignal subclass.')
parser.add_argument('--custom-instrument-module',
type=str,
default='CustomInstrument',
help='Name of the module containing the CustomInstrument subclass.')
parser.add_argument('--custom-photosphere-module',
type=str,
default='CustomPhotosphere',
help='Name of the module containing the CustomPhotosphere subclass.')
parser.add_argument('--custom-interstellar-module',
type=str,
default='CustomInterstellar',
help='Name of the module containing the CustomInterstellar subclass.')
parser.add_argument('--custom-prior-module',
type=str,
default='CustomPrior',
help='Name of the module containing the CustomPrior subclass.')
parser.add_argument('--custom-background-module',
type=str,
default='CustomBackground',
help='Name of the module containing the CustomBackground subclass(es).')
if __name__ == '__main__':
if xpsi._verbose:
print('Parsing configuration file...')
args, _ = parser.parse_known_args()
if xpsi._verbose:
print('Configuration file parsed.')
else:
if xpsi._verbose:
print('Parsing configuration file...')
args, _ = parser.parse_known_args(['@generate.ini'])
if xpsi._verbose:
print('Configuration file parsed.')
if len(args.hot_region_model) > 2:
raise ValueError('A maximum of two hot regions are permitted for module autogeneration.')
_telescopes = args.telescope[0]
for _x in args.telescope[1:]:
_telescopes += ' x {}'.format(_x)
if args.model is None:
if len(args.hot_region_model) == 2:
if args.hot_region_model[0] == args.hot_region_model[1]:
if args.antipodal_reflection_symmetry:
_tmp = '{}-S'.format(args.hot_region_model[0])
else:
_tmp = '{}-U'.format(args.hot_region_model[0])
else:
if args.antipodal_reflection_symmetry:
raise ValueError('Hot region models are not identical, so antipodal reflection symmetry cannot be imposed.')
_tmp = '{}+{}'.format(args.hot_region_model[0],
args.hot_region_model[1])
else:
_tmp = args.hot_region_model[0]
args.model = '{} + {}'.format(_tmp,
args.hot_atmosphere_model)
if args.elsewhere_atmosphere_model is not None:
args.model += ' + {}'.format(args.elsewhere_atmosphere_model)
module = (
'''""" Main module for {} {} <- X-PSI {} {}"""'''.format(_telescopes,
args.source,
xpsi.__version__,
args.model)
)
_telescopes = args.telescope[0]
for _x in args.telescope[1:]:
_telescopes += ' & {}'.format(_x)
module += (
'''
from __future__ import print_function, division
import os
import six
import argparse
import re
class ArgumentParserCustom(argparse.ArgumentParser):
def convert_arg_line_to_args(self, arg_line):
if (re.match(r'^[\s]*#', arg_line) or # look for any number of whitespace characters up to a `#` character
re.match(r'^[\s]*$', arg_line)): # look for lines containing nothing or just whitespace
return []
else:
try:
_idx = arg_line.index('#')
except ValueError:
pass
else:
arg_line = arg_line[:_idx].rstrip()
if xpsi._verbose:
print(arg_line)
return [arg_line]
def add_argument(self, *args, **kwargs):
if kwargs.pop('destined_for_config_file', True) and args[0] != '-h':
_ = (args[0],
kwargs.get('default', None),
kwargs.get('nargs', 1) if kwargs.get('action') != 'store_true' else 0,
kwargs.pop('comment_line_above', None),
kwargs.pop('empty_lines_below', 0),
kwargs.pop('comment', False),
kwargs.pop('inline_comment', None),
kwargs.get('action', None))
try:
self._config_file_args
except AttributeError:
self._config_file_args = [_]
else:
self._config_file_args.append(_)
else:
_ = kwargs.pop('comment_line_above', None)
_ = kwargs.pop('empty_lines_below', 0)
_ = kwargs.pop('comment', False)
_ = kwargs.pop('inline_comment', None)
super(ArgumentParserCustom, self).add_argument(*args, **kwargs)
class CompileAction(argparse._StoreAction):
""" Compile arguments for dynamic evaluation. """
def __call__(self, parser, namespace, values, option_string=None):
if isinstance(values, list):
for i, value in enumerate(values):
values[i] = compile(value, '<string>', 'eval')
setattr(namespace, self.dest, values)
else:
setattr(namespace, self.dest, compile(values, '<string>', 'eval'))
class GenerateConfigAction(argparse.Action):
def __init__(self, option_strings, dest, **kwargs):
super(GenerateConfigAction, self).__init__(option_strings, dest, nargs=0, **kwargs)
@staticmethod
def _typeset(arg, default, nargs, comment_line_above, empty_lines_below, comment, inline_comment, action, newline=True):
entry = '\\n' if newline else ''
if comment_line_above is not None:
if comment_line_above == 'rule':
entry += '#' + '-'*78 + '#\\n'
else:
_ = '## {{}} ##'.format(comment_line_above)
entry += '##' + '-' * (len(_) - 4) + '##\\n' + _ + '\\n##' + '-' * (len(_) - 4) + '##\\n'
_ = ' ## {{}}'.format(inline_comment) if inline_comment is not None else ''
if not _ and isinstance(nargs, int) and nargs > 1:
_ = ' ## enter {{}} values below, one per empty line'.format(nargs)
elif not _ and not isinstance(nargs, int):
_ = ' ## enter code below, one statement per line'
if isinstance(default, list):
for i, _default in enumerate(default):
entry += '{{5}}{{0}}{{1}}{{2}}{{3}}{{4}}'.format('#' if comment else '',
'' if (i > 0 and nargs != 1) else arg,
'' if nargs != 1 else '=',
'' if (i == 0 and nargs != 1) else str(_default),
(_ if i == 0 else '') + ('\\n{{0}}{{1}}'.format('#' if comment else '', str(_default)) if i == 0 and nargs != 1 else ''),
'\\n' if i > 0 else '')
else:
entry += '{{0}}{{1}}{{2}}{{3}}{{4}}'.format('#' if comment else '',
arg,
'=' if nargs == 1 else '',
_ if nargs != 1 else (str(default) if default is not None else ''),
('\\n' + str(default) if default is not None else '') if nargs != 1 else _)
if action == 'append':
entry += '\\n#{{0}}='.format(arg)
if isinstance(nargs, int) and nargs > 1:
entry += '\\n' * nargs
elif isinstance(nargs, str):
entry += '\\n' * 3
entry += '\\n' * empty_lines_below
return entry
def __call__(self, parser, namespace, values, option_string=None):
for _ in parser._config_file_args:
try:
config_file
except NameError:
config_file = self._typeset(*_, newline=False)
else:
config_file += self._typeset(*_)
with open('{3}', 'w') as file:
file.write(config_file)
print('Configuration file generated.')
parser.exit()
class NullAction(argparse.Action):
""" Do not store value in namespace. """
def __call__(self, parser, namespace, values, option_string=None):
pass
parser = ArgumentParserCustom(
description="""
Main module for X-PSI {0} modelling of {1} {2} event data.
You can run this module as a script and launch a sampler, optionally
with a world of MPI processes.
Alternate usage: mpiexec -n 4 python -m mpi4py %(prog)s [-h] @<config.ini>
""",
fromfile_prefix_chars='@')
'''.format(args.model,
_telescopes,
args.source,
args.config_path)
)
module += (
'''\ndef str_to_bool(x):
if x == 'False':
return False
elif x == 'True':
return True
raise ValueError('Invalid argument where boolean ``True`` or ``False`` is required.')
'''
)
module += (
'''
parser.add_argument('--generate-config-file', default=argparse.SUPPRESS, action=GenerateConfigAction, help='Generate the configuration file template.',
destined_for_config_file=False)
'''
)
module += (
'''
parser.add_argument('--main-import-statements',
type=str,
nargs='*',
default=['from xpsi.global_imports import gravradius', 'import math'],
help='Custom import statements needed for main module. Each statement is executed with the ``exec(...)`` builtin function. Note that if you pass statements, the default statements are deleted unless you uncomment the defaults in the configuration file.',
comment=True,
comment_line_above='import statements needed for main module',
empty_lines_below=2,
inline_comment='e.g., from ... import ... as ...')
parser.add_argument('--main-global-statements',
type=str,
nargs='*',
help='Custom assignment statements to be evaluated on the global level in the main module. Each statement is executed with the ``exec(...)`` builtin function. Note that if you pass statements, the default statements are deleted unless you uncomment the defaults in the configuration file.',
comment=True,
comment_line_above='global statements needed for main module',
empty_lines_below=2,
inline_comment='e.g., global_variable = math.pi')
parser.add_argument('--prior-import-statements',
type=str,
nargs='*',
default=['from scipy.stats import truncnorm', 'import math'],
action=NullAction,
help='Custom import statements needed for evaluation of prior CDFs. Each statement is executed with the ``exec(...)`` builtin function. Note that if you pass statements, the default statements are deleted unless you uncomment the defaults in the configuration file.',
comment=True,
comment_line_above='import statements needed for prior',
empty_lines_below=2,
inline_comment='e.g., from ... import ... as ...')
parser.add_argument('--prior-global-statements',
type=str,
nargs='*',
action=NullAction,
help='Custom assignment statements to be evaluated on the global level that are useful, e.g., for evaluation of prior CDFs. Each statement is executed with the ``exec(...)`` builtin function. Note that if you pass statements, the default statements are deleted unless you uncomment the defaults in the configuration file.',
comment=True,
comment_line_above='global statements needed for prior',
empty_lines_below=2,
inline_comment='e.g., global_variable = math.pi')
'''
)
_path = 'Absolute or relative path to'
_bounds_default_notice = 'If no bounds are given (``None``), and no value is given (``None``), bounds default to the source code strict bounds.'
_value_notice = 'No value means the parameter is free, whilst a value means the parameter is fixed (and the prior may need to be modified manually). If you want the parameter to be derived from other parameters in a complex way, manual modification of the main module is necessary, but we support functions of one parameter in the configuration file.'
_derived_notice = 'If the parameter is derived from one other parameter, e.g., the temperature of a hot region is derived from the temperature of the other hot region, then the value needs to be written using the following template: lambda x: f(x), "parameter", "space". In this template: f(x) is a function of the parameter x from which the value is derived; "parameter" is the name of the parameter x as a string; and "space" is an object in the global namespace, with name written as a string, which is a (sub)space of parameters from which the current value of parameter x can be accessed via getitem magic using "parameter".'
_CDF_notice = 'Supply a function of one variable (the probability mass ``x``), in the form of an expression that can be evaluated with the ``eval(...)`` builtin function, i.e., scipy.stats.truncnorm(x, ...). Note that the prior default PDF is uniform (with compact support), so do not supply a CDF if a uniform prior is desired, or to be explicit, use: DEFAULT UNIFORM. You must use DEFAULT UNIFORM to overwrite a default CDF shown in the auto-generated configuration file, unless the parameter is fixed/derived in which case the prior flag is silently ignored. You can also use the flag more than once: the last usage must be an expression that will be dynamically evaluated using the ``eval(...)`` builtin and must return a float to set as the parameter value; the other usages can be helper statements executed with the ``exec(...)`` builtin, e.g., to set temporary local variables to make the code (and configuration file more readable).'
for instrument in args.instrument:
module += (
'''
parser.add_argument('--{0}-exposure-time',
type=float,
help='{0} exposure time in seconds.',
comment_line_above='{0} configuration flags')
parser.add_argument('--{0}-count-matrix-path', type=str, help='{1} {0} channel-phase count matrix. If the data is a spectrum (phase-averaged), then the file must contain a vector. This path is written to if the file does not exist by processing the event files.')
parser.add_argument('--{0}-count-matrix-type', type=str, default='double', help='{0} count matrix NumPy data type.',
comment=True)
parser.add_argument('--{0}-event-path', type=str, help='{1} {0} event list file.')
parser.add_argument('--{0}-number-phase-bins', type=int, help='Number of phases bins for binning {0} event list file.')
parser.add_argument('--{0}-event-file-channel-column', type=int, default=1, help='Channel column in {0} event list file.',
comment=True)
parser.add_argument('--{0}-event-file-phase-column', type=int, default=2, help='Phase column in {0} event list file.',
comment=True)
parser.add_argument('--{0}-event-file-skiprows', type=int, default=3, help='Number of top rows to skip when loading {0} event list file.',
comment=True)
parser.add_argument('--{0}-events-in-eV', action='store_true', help='{0} event list file lists events by energy in eV?',
comment=True)
parser.add_argument('--{0}-arf-path', type=str, help='{1} {0} ARF file.',
comment_line_above='rule')
parser.add_argument('--{0}-effective-area-scaling-factor', type=str, default='1.0',
help='Factor by which to scale the nominal effective area model, as a mathematical expression, e.g., a ratio of integers such as 51.0/52.0.',
comment=True)
parser.add_argument('--{0}-arf-skiprows', type=int, default=3,
help='Number of header rows to skip when loading ARF file.',
comment=True)
parser.add_argument('--{0}-arf-low-column', type=int, default=1,
help='Column (zero-indexed) containing the low energy edges in the ARF file.',
comment=True)
parser.add_argument('--{0}-arf-high-column', type=int, default=2,
help='Column (zero-indexed) containing the high energy edges in the ARF file.',
comment=True)
parser.add_argument('--{0}-arf-area-column', type=int, default=3,
help='Column (zero-indexed) containing the effective area in the ARF file.',
comment=True)
parser.add_argument('--{0}-rmf-path', type=str, help='{1} {0} RMF file.',
comment_line_above='rule')
parser.add_argument('--{0}-rmf-skiprows', type=int, default=3,
help='Number of header rows to skip when loading RMF file.',
comment=True)
parser.add_argument('--{0}-rmf-usecol', type=int, default=-1,
help='Column (zero-indexed) containing the flattened redistribution matrix elements in the RMF file.',
comment=True)
parser.add_argument('--{0}-channels-path', type=str, help='{1} {0} channel-energy mapping file.',
comment_line_above='rule')
parser.add_argument('--{0}-channel-energies-skiprows', type=int, default=0,
help='Number of header rows to skip when loading channel-energy mapping file.',
comment=True)
parser.add_argument('--{0}-channel-energies-low-column', type=int, default=0,
help='Column (zero-indexed) containing the low energy edges in the channel-energy mapping file.',
comment=True)
parser.add_argument('--{0}-input-bounds',
type=int,
nargs=2,
help='{0} bounding input energy intervals of instrument response submatrix for use with NumPy slice notation.',
comment_line_above='rule')
parser.add_argument('--{0}-channel-bounds',
type=int,
nargs=2,
help='{0} bounding channels of instrument response submatrix for use with NumPy slice notation.')
parser.add_argument('--{0}-energy-independent-effective-area-scaling-factor-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds for {0} energy-independent effective area scaling factor parameter. If no bounds are given (``None``), and no value is given (``None``), the parameter value is fixed at unity, and the instrument response model is locked to the nominal response model (unless a custom model is implemented).',
comment=True,
comment_line_above='rule')
parser.add_argument('--{0}-energy-independent-effective-area-scaling-factor-prior',
type=str,
nargs='*',
default=['truncnorm.ppf(x, -3.0, 3.0, loc=1.0, scale=0.1)'],
action=NullAction,
help='Prior inverse CDF of the energy-independent effective area scaling factor. {5}',
comment=True,
inline_comment='Normal distribution with std. dev. 10%, truncated at +/- 3 std. dev.')
parser.add_argument('--{0}-energy-independent-effective-area-scaling-factor-value',
type=str,
action=CompileAction,
help='Value for {0} energy-independent effective area scaling parameter. Either the name of an instrument to share the parameter with, as a string, or a float. {3} {4}',
comment=True,
empty_lines_below=2)
parser.add_argument('--{0}-phase-shift-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds for {0} phase-shift parameter. If no bounds are given (``None``), and no value is given (``None``), the parameter value is fixed at zero, and is therefore locked to the phase of the signal specified by the hot region phases. For one phase-resolving instrument, this default behaviour is advised, and additional phase-resolving instruments can in principle have a different fixed, derived, or free phase-shift parameter. For instruments that phase-average, the phase-shift can be arbitrarily fixed or derived, but not free because the likelihood is not a function of it.',
comment=True,
comment_line_above='rule')
parser.add_argument('--{0}-phase-shift-value',
type=str,
action=CompileAction,
help='Value for {0} phase-shift parameter. Either the name of an instrument to share the parameter with, as a string, or a float. {3} {4}',
comment=True,
empty_lines_below=2)
parser.add_argument('--{0}-background-prior-support-path', type=str, help='{1} {0} background prior support file. The channel-by-channel lower count-rate limits in the zeroth column, and the upper count-rate limits in the first column. The channels must already match the data.',
comment=True,
comment_line_above='rule')
parser.add_argument('--{0}-background-skiprows', type=int, default=0, help='Number of top rows to skip when loading {0} background file (prior support or spectrum file).',
comment=True)
parser.add_argument('--{0}-background-path', type=str, help='{1} {0} background spectrum file (for imaging telescope).',
comment=True)
parser.add_argument('--{0}-background-usecol', type=int, help='Column to use when loading {0} background spectrum file (for imaging telescope).',
comment=True)
parser.add_argument('--{0}-background-prior-support-half-width', type=float, help='{0} background prior support half-width (for imaging telescope). The half-width is in units of standard deviation of background count number per instrument channel.',
comment=True)
parser.add_argument('--{0}-background-exposure-time',
type=float,
help='{0} background exposure time in seconds (for imaging telescope).',
comment=True)
parser.add_argument('--{0}-background-scaling-factor',
type=str,
help='{0} background scaling factor, nominally the ratio of on-source CCD extraction area to background CCD extraction area (ideally on same CCD) for imaging telescope. Supply an expression for evaluation by the ``eval(...)`` builtin function.',
comment=True,
empty_lines_below=2)
'''.format(instrument.replace('_','-'),
_path,
_bounds_default_notice,
_value_notice,
_derived_notice,
_CDF_notice)
)
if args.background_model:
for i, _parameter in enumerate(args.background_parameters):
module += (
'''
parser.add_argument('--{0}-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of the ``{0}`` parameter. {1}',
comment=True,
comment_line_above='{4}')
parser.add_argument('--{0}-prior',
type=str,
nargs='*',
action=NullAction,
help='Prior inverse CDF of the ``{0}`` parameter. {3}',
comment=True)
parser.add_argument('--{0}-value',
type=str,
action=CompileAction,
default='{5}',
help='Value of the ``{0}`` parameter. {2}',
comment=True,
inline_comment='{6}',
empty_lines_below=2)
'''.format(_parameter.replace('_', '-'),
_bounds_default_notice,
_value_notice,
_CDF_notice,
'background flags' if i == 0 else 'rule',
str(1.0) if 'powerlaw_norm' in _parameter else None,
'to allow parameter to be free, uncomment and use: None' if 'powerlaw_norm' in _parameter else None)
)
module += (
'''
parser.add_argument('--attenuation-path', type=str, help='{0} attenuation file.',
comment_line_above='attenuation flags')
parser.add_argument('--attenuation-energy-column', type=int, default=0,
help='Column (zero-indexed) containing the energies in the attenuation file.',
comment=True)
parser.add_argument('--attenuation-column', type=int, default=1,
help='Column (zero-indexed) containing the attenuation factors in the attenuation file.',
comment=True)
parser.add_argument('--neutral-hydrogen-column-density-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of the neutral hydrogen column density parameter. {1}',
comment=True,
comment_line_above='rule')
parser.add_argument('--neural-hydrogen-column-density-prior',
type=str,
nargs='*',
action=NullAction,
help='Prior inverse CDF of ratio of interstellar neutral hydrogen column density to the fiducial density. {3}',
comment=True)
parser.add_argument('--neutral-hydrogen-column-density-value',
type=str,
action=CompileAction,
help='Value of the neutral hydrogen column density parameter. {2}',
comment=True,
empty_lines_below=2)
'''.format(_path,
_bounds_default_notice,
_value_notice,
_CDF_notice)
)
module += (
'''
parser.add_argument('--mass-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of gravitational mass (solar masses). {1}',
comment=True,
comment_line_above='spacetime flags')
parser.add_argument('--mass-prior',
type=str,
nargs='*',
action=NullAction,
help='Prior inverse CDF of gravitation mass (solar masses). {4}',
comment=True)
parser.add_argument('--mass-value',
type=str,
action=CompileAction,
help='Value of gravitational mass (solar masses). {2} {3}',
comment=True,
empty_lines_below=2)
parser.add_argument('--radius-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of coordinate equatorial radius (km). {1}',
comment=True,
comment_line_above='rule')
parser.add_argument('--radius-value',
type=str,
action=CompileAction,
help='Value of coordinate equatorial radius (km). {2} {3}',
comment=True,
empty_lines_below=2)
parser.add_argument('--cos-inclination-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of cosine of Earth colatitude (inclination) w.r.t to stellar rotation axis. {1}',
comment=True,
comment_line_above='rule')
parser.add_argument('--cos-inclination-prior',
type=str,
nargs='*',
action=NullAction,
help='Prior inverse CDF of cosine of Earth inclination to stellar spin axis. {4}',
comment=True)
parser.add_argument('--cos-inclination-value',
type=str,
action=CompileAction,
help='Value of cosine of Earth colatitude (inclination) w.r.t to stellar rotation axis. {2}',
comment=True,
empty_lines_below=2)
parser.add_argument('--distance-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of distance to source (kpc). {1}',
comment=True,
comment_line_above='rule')
parser.add_argument('--distance-prior',
type=str,
nargs='*',
action=NullAction,
help='Prior inverse CDF of distance to source (kpc). {4}',
comment=True)
parser.add_argument('--distance-value',
type=str,
action=CompileAction,
help='Value of distance to source (kpc). {2} {3}',
comment=True,
empty_lines_below=2)
'''.format(_path,
_bounds_default_notice,
_value_notice,
_derived_notice,
_CDF_notice)
)
for _h, _m in zip(args.prefix, args.hot_region_model)[:1 if (len(args.hot_region_model) == 1 or args.antipodal_reflection_symmetry) else 2]:
module += (
'''
parser.add_argument('--{0}-super-colatitude-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of hot region "{0}" super-member colatitude w.r.t stellar spin axis (radians). {1}',
comment_line_above='"{0}" hot region parameter flags',
comment=True)
parser.add_argument('--{0}-super-colatitude-value',
type=str,
action=CompileAction,
help='Value of hot region "{0}" super-member colatitude w.r.t stellar spin axis (radians). {2} {3}',
comment=True,
empty_lines_below=2)
parser.add_argument('--{0}-super-radius-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of hot region "{0}" super-member angular radius (radians). {1}',
comment=True,
comment_line_above='rule')
parser.add_argument('--{0}-super-radius-value',
type=str,
action=CompileAction,
help='Value of hot region "{0}" super-member angular radius (radians). {2} {3}',
comment=True,
empty_lines_below=2)
parser.add_argument('--{0}-super-temperature-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of hot region "{0}" super-member log10(temperature [K]). {1}',
comment=True,
comment_line_above='rule')
parser.add_argument('--{0}-super-temperature-prior',
type=str,
nargs='*',
action=NullAction,
help='Prior inverse CDF of hot-region {0} superseding region log10(temperature [K]). {4}',
comment=True)
parser.add_argument('--{0}-super-temperature-value',
type=str,
action=CompileAction,
help='Value of hot region "{0}" super-member log10(temperature [K]). {2} {3}',
comment=True,
empty_lines_below=2)
'''.format(_h,
_bounds_default_notice,
_value_notice,
_derived_notice,
_CDF_notice)
)
if _m in ['CST', 'EST', 'PST']:
module += (
'''
parser.add_argument('--{0}-omit-radius-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of hot region "{0}" omit-member angular radius (radians). {1}',
comment=True,
comment_line_above='rule')
parser.add_argument('--{0}-omit-radius-value',
type=str,
action=CompileAction,
help='Value of hot region "{0}" omit-member angular radius (radians). {2} {3}',
comment=True,
empty_lines_below=2)
'''.format(_h,
_bounds_default_notice,
_value_notice,
_derived_notice)
)
if _m in ['EST', 'PST']:
module += (
'''
parser.add_argument('--{0}-omit-colatitude-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of hot region "{0}" omit-member colatitude w.r.t stellar spin axis (radians). {1}',
comment=True,
comment_line_above='rule')
parser.add_argument('--{0}-omit-colatitude-value',
type=str,
action=CompileAction,
help='Value of hot region "{0}" omit-member colatitude w.r.t stellar spin axis (radians). {2} {3}',
comment=True,
empty_lines_below=2)
parser.add_argument('--{0}-omit-azimuth-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of hot region "{0}" omit-member azimuth relative to super-member (radians). {1}',
comment=True,
comment_line_above='rule')
parser.add_argument('--{0}-omit-azimuth-value',
type=str,
action=CompileAction,
help='Value of hot region "{0}" omit-member azimuth relative to super-member (radians). {2} {3}',
comment=True,
empty_lines_below=2)
'''.format(_h,
_bounds_default_notice,
_value_notice,
_derived_notice)
)
if _m in ['CDT', 'EDT', 'PDT']:
module += (
'''
parser.add_argument('--{0}-cede-radius-bounds',
type=str,
nargs=2,
action=CompileAction,
help='Bounds of hot region "{0}" cede-member angular radius (radians). {1}',
comment=True,