-
Notifications
You must be signed in to change notification settings - Fork 49
/
serialize.py
1537 lines (1217 loc) · 44.7 KB
/
serialize.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
#
# Copyright (C) 2015, 2016, 2019, 2021, 2023
# Smithsonian Astrophysical Observatory
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""Serialize the Sherpa session state.
This module is used by ``sherpa.astro.ui.utils`` and is not
intended for public use. The API and semantics of the
routines in this module are subject to change.
"""
import inspect
import logging
import os
import sys
from types import ModuleType
from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional, \
TextIO, TypedDict, Union
import numpy
from sherpa.astro.data import DataIMG, DataPHA, DataARF, DataRMF
from sherpa.astro import io
from sherpa.astro.io.wcs import WCS
if TYPE_CHECKING:
# Avoid an import cycle
from sherpa.astro.ui.utils import Session
xspec: Optional[ModuleType]
try:
from sherpa.astro import xspec
except ImportError:
xspec = None
from sherpa.data import Data, Data1D, Data1DInt, Data2D, Data2DInt
from sherpa.models.basic import UserModel
# from sherpa.models.parameter import Parameter
import sherpa.utils
from sherpa.utils.err import ArgumentErr
logger = logging.getLogger(__name__)
warning = logger.warning
string_types = (str, )
# Note: a lot of the serialization logic should probably be moved into
# the objects (or modules) being serialized.
#
OutType = TypedDict("OutType", {"imports": set[str], "main": list[str]})
IdType = Union[int, str]
MaybeIdType = Optional[IdType]
DataType = Union[Data1D, Data2D]
# Typing the state argument is awkward since it causes an import
# error, so for runtime we default to Any and only when run under a
# type checker do we use the actual type.
#
if TYPE_CHECKING:
SessionType = Session
else:
SessionType = Any
# The par parameter is hard to type as it's Union[Parameter,
# XSBaseParameter] but the latter is only defined if XSPEC support is
# enabled. One way around this is to create a Protocol for defining
# the parameter interface rather than have it be based on a class.
#
# For now we use Any to skip this, at the expense of not type checking
# the module propery
#
# ParameterType = Parameter
ParameterType = Any
def _output(out: OutType, msg: str, indent: int = 0) -> None:
"""Output the line"""
space = ' ' * (indent * 4)
out["main"].append(f"{space}{msg}")
def _output_nl(out: OutType) -> None:
"""Add a new-line."""
_output(out, "")
def _output_banner(out: OutType, msg: str) -> None:
"""Display the banner message.
Parameters
----------
out : dict
The output state
msg : str
The label to output.
"""
_output_nl(out)
_output(out, f"######### {msg}")
_output_nl(out)
def _get_out_pos(out: OutType) -> int:
"""Return the current position.
This is to make it easier to remove a banner call. The code
should be re-written so we only add text once we know we have
anything, but that is a relatively large change.
"""
return len(out["main"])
def _remove_banner(out: OutType, orig_pos: int) -> None:
"""Remove the banner message if no text has been added.
Parameters
----------
out : dict
The output state
orig_pos : int
The position after the banner was added.
"""
if _get_out_pos(out) != orig_pos:
return
out["main"].pop()
out["main"].pop()
out["main"].pop()
def _id_to_str(id: IdType) -> str:
"""Convert a data set identifier to a string value.
Parameters
----------
id : int or str
The data set identifier.
Returns
-------
out : str
A string representation of the identifier for use
in the Python serialization.
"""
if isinstance(id, string_types):
return f'"{id}"'
return str(id)
def _save_entries(out: OutType,
store: Mapping[str, Any],
tostatement: Callable[[str, Any], str]) -> None:
"""Iterate through entries in the store and serialize them.
Write out the key, value pairs in store in lexical order,
rather than rely on the ordering of the container (e.g.
whatever hash is used). The idea is to come up with a
repeatable ordering, primarily to make testing easier.
Parameters
----------
out : dict
The output state
store
A container with keys. The elements of the container are
passed to tostatement to create the string that is then
written to fh.
tostatement : func
A function which accepts two arguments, the key and value
from store, and returns a string. The reason for the name
is that it is expected that the returned string will be
a Python statement to restore this setting.
"""
keys = list(store)
keys.sort()
for key in keys:
cmd = tostatement(key, store[key])
_output(out, cmd)
def _save_response(out: OutType,
label: str,
respfile: str,
id: IdType,
rid: IdType,
bid: MaybeIdType = None) -> None:
"""Save the ARF or RMF
Parameters
----------
out : dict
The output state
label : str
Either ``arf`` or ``rmf``.
respfile : str
The name of the ARF or RMF.
id : id or str
The Sherpa data set identifier.
rid
The Sherpa response identifier for the data set.
bid
If not ``None`` then this indicates that this is the ARF for
a background dataset, and which such data set to use.
"""
id = _id_to_str(id)
rid = _id_to_str(rid)
cmd = f'load_{label}({id}, "{respfile}", resp_id={rid}'
if bid is not None:
cmd += f", bkg_id={_id_to_str(bid)}"
cmd += ")"
_output(out, cmd)
def _save_arf_response(out: OutType,
state: SessionType,
pha: DataPHA,
id: IdType,
rid: IdType,
bid: MaybeIdType = None) -> None:
"""Save the ARF.
Parameters
----------
out : dict
The output state
state
pha : DataPHA
The PHA object
id : id or str
The Sherpa data set identifier.
rid
The Sherpa response identifier for the data set.
bid
If not ``None`` then this indicates that this is the ARF for
a background dataset, and which such data set to use.
"""
arf, _ = pha.get_response(rid)
if arf is None:
return
if TYPE_CHECKING:
# We currently do not do much with arf, but add the type
# anyway.
assert isinstance(arf, DataARF)
_save_response(out, 'arf', arf.name, id, rid, bid=bid)
def _save_rmf_response(out: OutType,
state: SessionType,
pha: DataPHA,
id: IdType,
rid: IdType,
bid: MaybeIdType = None) -> None:
"""Save the RMF.
Parameters
----------
out : dict
The output state
state : Session
pha : DataPHA
The PHA object
id : id or str
The Sherpa data set identifier.
rid
The Sherpa response identifier for the data set.
bid
If not ``None`` then this indicates that this is the RMF for
a background dataset, and which such data set to use.
"""
_, rmf = pha.get_response(rid)
if rmf is None:
return
if TYPE_CHECKING:
# We currently do not do much with rmf, but add the type
# anyway.
assert isinstance(rmf, DataRMF)
_save_response(out, 'rmf', rmf.name, id, rid, bid=bid)
def _save_pha_array(out: OutType,
state: SessionType,
pha: DataPHA,
label: str,
id: IdType,
bid: MaybeIdType = None) -> None:
"""Save a grouping or quality array for a PHA data set.
Parameters
----------
out : dict
The output state
state
pha : DataPHA
The PHA object
label : "grouping" or "quality"
id : id or str
The Sherpa data set identifier.
bid
If not ``None`` then this indicates that the background dataset
is to be used.
"""
vals = getattr(pha, label)
if vals is None:
return
# The OGIP standard is for quality and grouping to be 2-byte
# integers -
# http://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/spectra/ogip_92_007/node7.html
# - then force that type here.
vals = vals.astype(numpy.int16)
lbl = 'Data' if bid is None else 'Background'
_output_banner(out, f"{lbl} {label} flags")
cmd = f"set_{label}({_id_to_str(id)}, " + \
"val=numpy.array(" + repr(vals.tolist()) + \
f", numpy.{vals.dtype})"
if bid is not None:
cmd += f", bkg_id={_id_to_str(bid)}"
cmd += ")"
_output(out, cmd)
def _save_pha_grouping(out: OutType,
state: SessionType,
pha: DataPHA,
id: IdType,
bid: MaybeIdType = None) -> None:
"""Save the grouping column values for a PHA data set.
Parameters
----------
out : dict
The output state
state
pha : DataPHA
The PHA object
id : id or str
The Sherpa data set identifier.
bid
If not ``None`` then this indicates that the background dataset
is to be used.
fh : None or file-like
If ``None``, the information is printed to standard output,
otherwise the information is added to the file handle.
"""
_save_pha_array(out, state, pha, "grouping", id, bid=bid)
def _save_pha_quality(out: OutType,
state: SessionType,
pha: DataPHA,
id: IdType,
bid: MaybeIdType = None) -> None:
"""Save the quality column values for a PHA data set.
Parameters
----------
out : dict
The output state
state
pha : DataPHA
The PHA object
id : id or str
The Sherpa data set identifier.
bid
If not ``None`` then this indicates that the background dataset
is to be used.
"""
_save_pha_array(out, state, pha, "quality", id, bid=bid)
def _add_filter(out: OutType,
data: DataType,
cmd_id: str) -> None:
"""Add any filter applied to the source."""
# We have mask being
# - True or an array of Trues
# => no filter is needed
#
# - False or an array of Falses
# => everything is filtered out
#
# - array of True and False
# => want to filter the data
#
# We only report a filter if it actually excludes some data. The
# following relies on numpy.all/any behaving the same when given
# boolval as [boolval], so we do not have to explicitly check if
# the mask is a boolean.
#
if numpy.all(data.mask):
return
extra = "2d" if len(data.get_dims()) == 2 else ""
if numpy.any(data.mask):
fvals = data.get_filter()
_output(out, f'notice{extra}_id({cmd_id}, "{fvals}")')
return
# All data has been ignored.
#
_output(out, f'ignore{extra}_id({cmd_id})')
def _add_bkg_filter(out: OutType,
bpha: DataPHA,
cmd_id: str,
bkg_id: int) -> None:
"""Add any filter applied to the background."""
if numpy.all(bpha.mask):
return
if numpy.any(bpha.mask):
# We need to clear any existing background filter set by
# the source.
#
_output(out, f'notice_id({cmd_id}, bkg_id={bkg_id})')
fvals = bpha.get_filter()
_output(out, f'notice_id({cmd_id}, "{fvals}", bkg_id={bkg_id})')
return
_output(out, f'ignore_id({cmd_id}, bkg_id={bkg_id})')
def _handle_filter(out: OutType,
state: SessionType,
data: DataType,
id: IdType) -> None:
"""Set any filter expressions for source and background
components for data set id.
It is expected that there is a dataset with the given id
in the Sherpa session object (state).
"""
_output_banner(out, "Filter Data")
orig_pos = _get_out_pos(out)
cmd_id = _id_to_str(id)
_add_filter(out, data, cmd_id)
# Since the state doesn't have type annotations, help the system out.
# Technically this is only true after the try call, not here.
#
if TYPE_CHECKING:
assert isinstance(data, DataPHA)
try:
bids = data.background_ids
except AttributeError:
# Not a PHA data set
_remove_banner(out, orig_pos)
return
# Only set the noticed range if the data set does not have
# the background subtracted. It might be useful to keep any
# noticed range the user may have previously set - if switching
# between fitting and subtracting the background - but that is
# probably beyond the use case of the serialization.
#
if data.subtracted:
_remove_banner(out, orig_pos)
return
# NOTE: have to clear out the source filter before applying the
# background one.
for bid in bids:
bpha = data.get_background(bid)
if TYPE_CHECKING:
assert isinstance(bpha, DataPHA)
_add_bkg_filter(out, bpha, cmd_id, bid)
_remove_banner(out, orig_pos)
def _save_dataset_settings_pha(out: OutType,
state: SessionType,
pha: DataType,
id: IdType) -> None:
"""What settings need to be set for DataPHA"""
if not isinstance(pha, DataPHA):
return
cmd_id = _id_to_str(id)
# Only store group flags and quality flags if they were changed
# from flags in the file.
#
if not pha._original_groups:
_save_pha_grouping(out, state, pha, id)
_save_pha_quality(out, state, pha, id)
if pha.grouped:
_output(out, f"group({cmd_id})")
# Add responses and ARFs, if any.
#
rids = pha.response_ids
if len(rids) > 0:
_output_banner(out, "Data Spectral Responses")
for rid in rids:
_save_arf_response(out, state, pha, id, rid)
_save_rmf_response(out, state, pha, id, rid)
# Check if this data set has associated backgrounds.
#
bids = pha.background_ids
if len(bids) > 0:
_output_banner(out, "Load Background Data Sets")
for bid in bids:
cmd_bkg_id = _id_to_str(bid)
bpha = pha.get_background(bid)
if TYPE_CHECKING:
assert isinstance(bpha, DataPHA)
bname = bpha.name
cmd = f'load_bkg({cmd_id}, "{bname}", bkg_id={cmd_bkg_id})'
_output(out, cmd)
# Only store group flags and quality flags if they were
# changed from flags in the file
#
if not bpha._original_groups:
_save_pha_grouping(out, state, bpha, id, bid=bid)
_save_pha_quality(out, state, bpha, id, bid=bid)
if bpha.grouped:
_output(out, f"group({cmd_id}, bkg_id={cmd_bkg_id})")
# Load background response, ARFs if any
rids = bpha.response_ids
if len(rids) > 0:
_output_banner(out, "Background Spectral Responses")
for rid in rids:
_save_arf_response(out, state, bpha, id, rid, bid=bid)
_save_rmf_response(out, state, bpha, id, rid, bid=bid)
# Set energy units if applicable
#
_output_banner(out, "Set Energy or Wave Units")
rate = "rate" if pha.rate else "counts"
cmd = f'set_analysis({cmd_id}, quantity="{pha.units}", ' + \
f'type="{rate}", factor={pha.plot_fac})'
_output(out, cmd)
if pha.subtracted:
_output(out, f"subtract({cmd_id})")
def _save_dataset_settings_2d(out: OutType,
state: SessionType,
data: DataType,
id: IdType) -> None:
"""What settings need to be set for Data2D/IMG?"""
if not isinstance(data, DataIMG):
return
_output_banner(out, "Set Image Coordinates")
_output(out, f"set_coord({_id_to_str(id)}, '{data.coord}')")
def _save_data(out: OutType, state: SessionType) -> None:
"""Save the data.
This can just be references to files, or serialization of
the data (or both).
Parameters
----------
out : dict
The output state
state
Notes
-----
This does not - at least at present - save data to one or
more files to be read in by the script. If any data needs
to be serialized it is included in the script.
"""
ids = state.list_data_ids()
if len(ids) == 0:
return
# Try to only output a banner if the section contains a
# command/setting.
#
_output_banner(out, "Load Data Sets")
cmd_id = ""
cmd_bkg_id = ""
for id in ids:
# But if id is a string, then quote as a string
# But what about the rest of any possible load_data() options;
# how do we replicate the optional keywords that were possibly
# used? Store them with data object?
cmd_id = _id_to_str(id)
data = state.get_data(id)
if TYPE_CHECKING:
# Assert an actual type rather than the base type of Data
assert isinstance(data, (Data1D, Data2D))
_save_dataset(out, state, data, id)
_save_dataset_settings_pha(out, state, data, id)
_save_dataset_settings_2d(out, state, data, id)
_handle_filter(out, state, data, id)
def _print_par(par: ParameterType) -> tuple[str, str]:
"""Convert a Sherpa parameter to a string.
Note that we have to be careful with XSParameter parameters,
to see if the hard limits need updating.
Parameters
----------
par : Parameter
The Sherpa parameter object to serialize.
Returns
-------
out_pars, out_link : (str, str)
A multi-line string serializing the contents of the
parameter and then any link setting.
"""
linkstr = ""
if par.link is not None:
linkstr = f"\nlink({par.fullname}, {par.link.fullname})\n"
unitstr = ""
if isinstance(par.units, string_types):
unitstr = f'"{par.units}"'
# Do we have to worry about XSPEC parameters which have changed their
# hard min/max ranges?
#
parstrs = []
try:
if par.hard_min_changed():
parstrs.append(f'{par.fullname}.hard_min = {repr(par.hard_min)}')
except AttributeError:
pass
try:
if par.hard_max_changed():
parstrs.append(f'{par.fullname}.hard_max = {repr(par.hard_max)}')
except AttributeError:
pass
parstrs.extend([f'{par.fullname}.default_val = {repr(par.default_val)}',
f'{par.fullname}.default_min = {repr(par.default_min)}',
f'{par.fullname}.default_max = {repr(par.default_max)}',
f'{par.fullname}.val = {repr(par.val)}',
f'{par.fullname}.min = {repr(par.min)}',
f'{par.fullname}.max = {repr(par.max)}',
f'{par.fullname}.units = {unitstr}',
f'{par.fullname}.frozen = {par.frozen}'])
parstr = '\n'.join(parstrs) + '\n'
return (parstr, linkstr)
def _save_statistic(out: OutType, state: SessionType) -> None:
"""Save the statistic settings.
Parameters
----------
out : dict
The output state
state
"""
_output_banner(out, "Set Statistic")
_output(out, f'set_stat("{state.get_stat_name()}")')
_output_nl(out)
def _save_fit_method(out: OutType, state: SessionType) -> None:
"""Save the fit method settings.
Parameters
----------
out : dict
The output state
state
"""
# Save fitting method
_output_banner(out, "Set Fitting Method")
_output(out, f'set_method("{state.get_method_name()}")')
_output_nl(out)
def tostatement(key, val):
# TODO: Using .format() returns more decimal places, which
# is probably what we want but is a change, so leave
# for now.
# return 'set_method_opt("{}", {})'.format(key, val)
return 'set_method_opt("%s", %s)' % (key, val)
_save_entries(out, state.get_method_opt(), tostatement)
_output_nl(out)
def _save_iter_method(out: OutType, state: SessionType) -> None:
"""Save the iterated-fit method settings, if any.
Parameters
----------
out : dict
The output state
state
"""
iname = state.get_iter_method_name()
if iname == 'none':
return
_output_banner(out, "Set Iterative Fitting Method")
cmd = f'set_iter_method("{iname}")'
_output(out, cmd)
_output_nl(out)
def tostatement(key, val):
# There was a discussion here about the use of
# str(val) vs val - the number of decimal places - but it
# turns out for the test we only output integer values
# so it makes no difference.
return f'set_iter_method_opt("{key}", {val})'
_save_entries(out, state.get_iter_method_opt(), tostatement)
_output_nl(out)
# Is there something in the standard libraries that does this?
def _reindent(code: str) -> str:
"""Try to remove leading spaces. Somewhat hacky."""
# Assume the first line is 'def func()'
nspaces = code.find('def')
if nspaces < 1:
return code
# minimal safety checks (e.g. if there was an indented
# comment line).
out = []
for line in code.split("\n"):
if line[:nspaces].isspace():
out.append(line[nspaces:])
else:
out.append(line)
return "\n".join(out)
# for user models, try to access the function definition via
# the inspect module and then re-create it in the script.
# An alternative would be to use the marshal module, and
# store the bytecode for the function in the code (or use
# pickle), but this is less readable and not guaranteed to
# be compatible with different major versions of Python.
# The idea is not to support all use case, but to try and
# support the simple use case.
#
# The user warnings are displayed for each user model,
# which could get annoying if there are many such models,
# but probably better to tell the user about each one
# than only the first.
#
def _handle_usermodel(out: OutType,
mod: UserModel,
modelname: str) -> None:
try:
pycode = inspect.getsource(mod.calc)
except IOError:
pycode = None
# in case getsource can return None, have check here
if pycode is None:
msg = "Unable to save Python code for user model " + \
f"'{modelname}' function {mod.calc.__name__}"
warning(msg)
_output(out, f'print("{msg}")')
_output(out, f"def {mod.calc.__name__}(*args):")
_output(out, "raise NotImplementedError('User model was "
"not saved by save_all().'", indent=1)
_output_nl(out)
return
msg = f"Found user model '{modelname}'; " + \
"please check it is saved correctly."
warning(msg)
# Ensure the message is also seen if the script is run.
_output(out, f'print("{msg}")')
_output(out, _reindent(pycode))
cmd = f'load_user_model({mod.calc.__name__}, "{modelname}")'
_output(out, cmd)
# Work out the add_user_pars call; this is explicit, i.e.
# it does not include logic to work out what arguments
# are not needed.
#
# Some of these values are over-written later on, but
# needed to set up the number of parameters, and good
# documentation (hopefully).
#
parnames = [p.name for p in mod.pars]
parvals = [p.default_val for p in mod.pars]
# parmins = [p.default_min for p in mod.pars]
# parmaxs = [p.default_max for p in mod.pars]
parmins = [p.min for p in mod.pars]
parmaxs = [p.max for p in mod.pars]
parunits = [p.units for p in mod.pars]
parfrozen = [p.frozen for p in mod.pars]
spaces = ' '
_output(out, f'add_user_pars("{modelname}",')
_output(out, f"{spaces}parnames={parnames},")
_output(out, f"{spaces}parvals={parvals},")
_output(out, f"{spaces}parmins={parmins},")
_output(out, f"{spaces}parmaxs={parmaxs},")
_output(out, f"{spaces}parunits={parunits},")
_output(out, f"{spaces}parfrozen={parfrozen}")
_output(out, f"{spaces})\n")
def _save_model_components(out: OutType, state: SessionType) -> bool:
"""Save the model components.
Parameters
----------
out : dict
The output state
state
Returns
-------
xspec_state : bool
True if any XSPEC models are found.
"""
found_xspec = False
# Try to be careful about the ordering of the components here.
#
all_model_components = state.list_model_components()
if len(all_model_components) == 0:
return found_xspec
all_model_components.reverse()
_output_banner(out, "Set Model Components and Parameters")
# If there are any links between parameters, store link commands here
# Then, *after* processing all models in the for loop below, send
# link commands to outfile -- *all* models need to be created before
# *any* links between parameters can be established.
linkstr = ""
for modval in all_model_components:
# get actual model instance from the name we are given
# then get model type, and name of this instance.
mod = eval(modval)
typename = mod.type
modelname = mod.name.split(".")[1]
if typename == "usermodel":
_handle_usermodel(out, mod, modelname)
elif typename == "psfmodel":
cmd = f'load_psf("{mod._name}", "{mod.kernel.name}")'
_output(out, cmd)
elif typename == "tablemodel":
cmd = f'load_table_model("{modelname}", "{mod.filename}")'
_output(out, cmd)
elif typename == "xstablemodel":
cmd = f'load_xstable_model("{modelname}", "{mod.filename}"'
if mod.etable:
cmd += ', etable=True'
cmd += ')'
_output(out, cmd)
found_xspec = True
else:
# Normal case: create an instance of the model.
cmd = f'create_model_component("{typename}", "{modelname}")'
_output(out, cmd)
# Is this an XSPEC model? We only care if it's the first
# one we find.
#
if not found_xspec and xspec is not None:
found_xspec = isinstance(mod, xspec.XSModel)
# QUS: should this be included in the above checks?
# @DougBurke doesn't think so, as the "normal
# case" above should probably be run , but there's
# no checks to verify this.
#
if typename == "convolutionkernel":
# Create general convolution kernel with load_conv
cmd = f'load_conv("{modelname}", "{mod.kernel.name}")'
_output(out, cmd)
if hasattr(mod, "integrate"):
cmd = f"{modelname}.integrate = {mod.integrate}"
_output(out, cmd)
_output_nl(out)
# Write out the parameters in the order they are stored in
# the model. The original version of the code iterated
# through mod.__dict__.values() and picked out Parameter
# values.
#
for par in mod.pars:
par_attributes, par_linkstr = _print_par(par)
_output(out, par_attributes)
linkstr = linkstr + par_linkstr
# If the model is a PSFModel, could have special
# attributes "size" and "center" -- if so, record them.
if typename == "psfmodel":
spacer = False
if hasattr(mod, "size") and mod.size is not None:
_output(out, f"{modelname}.size = {mod.size}")
spacer = True
if hasattr(mod, "center") and mod.center is not None:
_output(out, f"{modelname}.center = {mod.center}")
spacer = True
if spacer:
_output_nl(out)
# If there were any links made between parameters, send those
# link commands to outfile now; else, linkstr is just an empty string
_output(out, linkstr)
return found_xspec
def _save_psf_components(out: OutType, state: SessionType) -> None:
"""Save the PSF components.
This must be done after setting up the data and model components.
Parameters