/
SpectrumLike.py
2972 lines (2072 loc) · 95.5 KB
/
SpectrumLike.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 print_function
from __future__ import division
from builtins import zip
from builtins import str
from builtins import range
from past.utils import old_div
import collections
import copy
from contextlib import contextmanager
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from astromodels import Model, PointSource
from astromodels import clone_model
from astromodels.core.parameter import Parameter
from astromodels.functions.priors import Uniform_prior
from astromodels.utils.valid_variable import is_valid_variable_name
from threeML.utils.spectrum.pha_spectrum import PHASpectrum
from threeML.config.config import threeML_config
from threeML.exceptions.custom_exceptions import custom_warnings, NegativeBackground
from threeML.io.plotting.light_curve_plots import channel_plot, disjoint_patch_plot
from threeML.io.rich_display import display
from threeML.plugin_prototype import PluginPrototype
from threeML.plugins.XYLike import XYLike
from threeML.utils.binner import Rebinner
from threeML.utils.spectrum.binned_spectrum import BinnedSpectrum, ChannelSet
from threeML.utils.string_utils import dash_separated_string_to_tuple
from threeML.utils.spectrum.pha_spectrum import PHASpectrum
from threeML.utils.statistics.stats_tools import Significance
from threeML.utils.spectrum.spectrum_likelihood import statistic_lookup
from threeML.io.plotting.data_residual_plot import ResidualPlot
NO_REBIN = 1e-99
__instrument_name = "General binned spectral data"
# This defines the known noise models for source and/or background spectra
_known_noise_models = ["poisson", "gaussian", "ideal", "modeled"]
class SpectrumLike(PluginPrototype):
def __init__(
self,
name,
observation,
background=None,
verbose=True,
background_exposure=None,
tstart=None,
tstop=None,
):
# type: (str, BinnedSpectrum, BinnedSpectrum, bool) -> None
"""
A plugin for generic spectral data, accepts an observed binned spectrum,
and a background binned spectrum or plugin with the background data.
In the case of a binned background spectrum, the background model is profiled
out and the appropriate profile-likelihood is used to fit the total spectrum. In this
case, caution must be used when there are zero background counts in bins as the
profiled background parameters (one per channel) will then have zero information from which to
constrain the background. It is recommended to bin the spectrum such that there is one background count
per channel.
If either an SpectrumLike or XYLike instance is provided as background, it is assumed that this is the
background data and the likelihood model from this plugin is used to simultaneously fit the background
and source.
:param name: the plugin name
:param observation: the observed spectrum
:param background: the background spectrum or a plugin from which the background will be modeled
:param background_exposure: (optional) adjust the background exposure of the modeled background data comes from and
XYLike plugin
:param verbose: turn on/off verbose logging
"""
# Just a toggle for verbosity
self._verbose = bool(verbose)
assert is_valid_variable_name(name), (
"Name %s is not a valid name for a plugin. You must use a name which is "
"a valid python identifier: no spaces, no operators (+,-,/,*), "
"it cannot start with a number, no special characters" % name
)
assert isinstance(
observation, BinnedSpectrum
), "The observed spectrum is not an instance of BinnedSpectrum"
# Precomputed observed (for speed)
self._observed_spectrum = observation # type: BinnedSpectrum
self._observed_counts = self._observed_spectrum.counts # type: np.ndarray
# initialize the background
background_parameters = self._background_setup(background, observation)
# unpack the parameters
(
self._background_spectrum,
self._background_plugin,
self._background_counts,
self._scaled_background_counts,
) = background_parameters
# Init everything else to None
self._like_model = None
self._rebinner = None
self._source_name = None
# probe the noise models and then setup the appropriate count errors
(
self._observation_noise_model,
self._background_noise_model,
) = self._probe_noise_models()
(
self._observed_count_errors,
self._back_count_errors,
) = self._count_errors_initialization()
# Initialize a mask that selects all the data.
# We will initially use the quality mask for the PHA file
# and set any quality greater than 0 to False. We want to save
# the native quality so that we can warn the user if they decide to
# select channels that were flagged as bad.
self._mask = np.asarray(np.ones(self._observed_spectrum.n_channels), np.bool)
# Now create the nuisance parameter for the effective area correction, which is fixed
# by default. This factor multiplies the model so that it can account for calibration uncertainties on the
# global effective area. By default it is limited to stay within 20%
self._nuisance_parameter = Parameter(
"cons_%s" % name,
1.0,
min_value=0.8,
max_value=1.2,
delta=0.05,
free=False,
desc="Effective area correction for %s" % name,
)
nuisance_parameters = collections.OrderedDict()
nuisance_parameters[self._nuisance_parameter.name] = self._nuisance_parameter
# if we have a background model we are going
# to link all those parameters to new nuisance parameters
if self._background_plugin is not None:
self._background_noise_model = "modeled"
for par_name, parameter in list(
self._background_plugin.likelihood_model.parameters.items()
):
# create a new parameters that is like the one from the background model
local_name = "bkg_%s_%s" % (par_name, name)
local_name = local_name.replace(".", "_")
nuisance_parameters[local_name] = parameter
# now get the background likelihood model
differential_flux, integral = self._get_diff_flux_and_integral(
self._background_plugin.likelihood_model
)
self._background_integral_flux = integral
super(SpectrumLike, self).__init__(name, nuisance_parameters)
if isinstance(self._background_plugin, XYLike):
if background_exposure is None:
custom_warnings.warn(
"An XYLike plugin is modeling the background but background_exposure is not set. "
"It is assumed the observation and background have the same exposure"
)
self._explict_background_exposure = self.exposure
else:
self._explicit_background_exposure = background_exposure
# The following vectors are the ones that will be really used for the computation. At the beginning they just
# point to the original ones, but if a rebinner is used and/or a mask is created through set_active_measurements,
# they will contain the rebinned and/or masked versions
self._current_observed_counts = self._observed_counts
self._current_observed_count_errors = self._observed_count_errors
self._current_background_counts = self._background_counts
self._current_scaled_background_counts = self._scaled_background_counts
self._current_back_count_errors = self._back_count_errors
# This will be used to keep track of how many syntethic datasets have been generated
self._n_synthetic_datasets = 0
if tstart is not None:
self._tstart = tstart
else:
self._tstart = observation.tstart
if tstop is not None:
self._tstop = tstop
else:
self._tstop = observation.tstop
# This is so far not a simulated data set
self._simulation_storage = None
# set the mask to the native quality
self._mask = self._observed_spectrum.quality.good
# Apply the mask
self._apply_mask_to_original_vectors()
# calculate all scalings between area and exposure
self._precalculations()
# now create a likelihood object for the call
# we pass the current object over as well
# the likelihood object is opaque to the class and
# keeps a pointer of the plugin inside so that the current
# counts, bkg, etc. are always up to date
# This way, when evaluating the likelihood,
# no checks are involved because the appropriate
# noise models are pre-selected
self._likelihood_evaluator = statistic_lookup[self.observation_noise_model][
self.background_noise_model
](self)
def _count_errors_initialization(self):
"""
compute the count errors for the observed and background spectra
:return: (observed_count_errors, background_count errors)
"""
# if there is not a background the dictionary
# will crash, so we need to do a small check
tmp_bkg_count_errors = None
if self._background_spectrum is not None:
tmp_bkg_count_errors = self._background_spectrum.count_errors
count_errors_lookup = {
"poisson": {
"poisson": (None, None),
"gaussian": (None, tmp_bkg_count_errors),
None: (None, None),
},
# gaussian source
"gaussian": {
"gaussian": (
self._observed_spectrum.count_errors,
tmp_bkg_count_errors,
),
None: (self._observed_spectrum.count_errors, None),
},
}
try:
error_tuple = count_errors_lookup[self._observation_noise_model][
self._background_noise_model
] # type: tuple
except (KeyError):
RuntimeError(
"The noise combination of source: %s, background: %s is not supported"
% (self._observation_noise_model, self._background_noise_model)
)
for errors, counts, name in zip(
error_tuple,
[self._observed_counts, self._background_counts],
["observed", "background"],
):
# if the errors are not None then we want to make sure they make sense
if errors is not None:
zero_idx = errors == 0 # type: np.ndarray
# check that zero error => zero counts
assert np.all(errors[zero_idx] == counts[zero_idx]), (
"Error in %s spectrum: if the error on the background is zero, "
"also the expected %s must be zero" % name
)
observed_count_errors, background_count_errors = error_tuple
return observed_count_errors, background_count_errors
def _probe_noise_models(self):
"""
probe the noise models
:return: (observation_noise_model, background_noise_model)
"""
observation_noise_model, background_noise_model = None, None
# Now auto-probe the statistic to use
if self._background_spectrum is not None:
if self._observed_spectrum.is_poisson:
self._observed_count_errors = None
self._observed_counts = self._observed_counts.astype(np.int64)
if self._background_spectrum.is_poisson:
observation_noise_model = "poisson"
background_noise_model = "poisson"
self._background_counts = self._background_counts.astype(np.int64)
assert np.all(
self._observed_counts >= 0
), "Error in PHA: negative counts!"
if not np.all(self._background_counts >= 0):
raise NegativeBackground(
"Error in background spectrum: negative counts!"
)
else:
observation_noise_model = "poisson"
background_noise_model = "gaussian"
if not np.all(self._background_counts >= 0):
raise NegativeBackground(
"Error in background spectrum: negative background!"
)
else:
if self._background_spectrum.is_poisson:
raise NotImplementedError(
"We currently do not support Gaussian observation and Poisson background"
)
else:
observation_noise_model = "gaussian"
background_noise_model = "gaussian"
if not np.all(self._background_counts >= 0):
raise NegativeBackground(
"Error in background spectrum: negative background!"
)
else:
# this is the case for no background
self._background_counts = None
self._back_count_errors = None
self._scaled_background_counts = None
if self._observed_spectrum.is_poisson:
self._observed_count_errors = None
self._observed_counts = self._observed_counts.astype(np.int64)
assert np.all(self._observed_counts >= 0), "Error in PHA: negative counts!"
assert np.all(
self._observed_counts >= 0
), "Error in PHA: negative counts!"
observation_noise_model = "poisson"
background_noise_model = None
else:
observation_noise_model = "gaussian"
background_noise_model = None
# Print the auto-probed noise models
if self._verbose:
if self._background_plugin is not None:
print(
"Background modeled from plugin: %s" % self._background_plugin.name
)
bkg_noise = self._background_plugin.observation_noise_model
else:
bkg_noise = background_noise_model
print("Auto-probed noise models:")
print("- observation: %s" % observation_noise_model)
print("- background: %s" % bkg_noise)
return observation_noise_model, background_noise_model
def _background_setup(self, background, observation):
"""
:param background: background arguments (spectrum or plugin)
:param observation: observed spectrum
:return: (background_spectrum, background_plugin, background_counts, scaled_background_counts)
"""
# this is only called during once during construction
# setup up defaults as none
background_plugin = None
background_spectrum = None
background_counts = None
scaled_background_counts = None
if background is not None:
# If this is a plugin created from a background
# we extract the observed spectrum (it should not have a background...
# it is a background)
# we are explicitly violating duck-typing
if isinstance(background, SpectrumLike) or isinstance(background, XYLike):
background_plugin = background
else:
# if the background is not a plugin then we need to make sure it is a spectrum
# and that the spectrum is the same size as the observation
assert isinstance(
background, BinnedSpectrum
), "The background spectrum is not an instance of BinnedSpectrum"
assert observation.n_channels == background.n_channels, (
"Data file and background file have different " "number of channels"
)
background_spectrum = background # type: BinnedSpectrum
background_counts = background_spectrum.counts # type: np.ndarray
# this assumes the observed spectrum is already set!
scaled_background_counts = self._get_expected_background_counts_scaled(
background_spectrum
) # type: np.ndarray
return (
background_spectrum,
background_plugin,
background_counts,
scaled_background_counts,
)
def _precalculations(self):
"""
pre calculate values for speed.
originally, the plugins were calculating these values on the fly, which was very slow
:return:
"""
# area scale factor between background and source
# and exposure ratio between background and source
if (self._background_spectrum is None) and (self._background_plugin is None):
# there is no background so the area scaling is unity
self._area_ratio = 1.0
self._exposure_ratio = 1.0
self._background_exposure = 1.0
self._background_scale_factor = None
else:
if self._background_plugin is not None:
if isinstance(self._background_plugin, SpectrumLike):
# use the background plugin's observed spectrum and exposure to scale the area and time
self._background_scale_factor = (
self._background_plugin.observed_spectrum.scale_factor
)
self._background_exposure = (
self._background_plugin.observed_spectrum.exposure
)
else:
# in this case, the XYLike data could come from anything, so area scaling is set to unity
# TODO: could this be wrong?
self._background_scale_factor = self._observed_spectrum.scale_factor
# if the background exposure is set in the constructor, then this will scale it, otherwise
# this will be unity
self._exposure_ratio = (
self._background_exposure
) = self._explict_background_exposure
else:
# this is the normal case with no background model, get the scale factor directly
self._background_scale_factor = self._background_spectrum.scale_factor
self._background_exposure = self._background_spectrum.exposure
self._area_ratio = old_div(
self._observed_spectrum.scale_factor, self._background_scale_factor
)
self._exposure_ratio = old_div(
self._observed_spectrum.exposure, self._background_exposure
)
self._total_scale_factor = self._area_ratio * self._exposure_ratio
# deal with background exposure and scale factor
# we run through this separately to
@property
def exposure(self):
"""
Exposure of the source spectrum
"""
return self._observed_spectrum.exposure
@property
def area_ratio(self):
"""
:return: ratio between source and background area
"""
assert (self._background_plugin is not None) or (
self._background_spectrum
) is not None, "No background exists!"
return self._area_ratio
@property
def exposure_ratio(self):
"""
:return: ratio between source and background exposure
"""
assert (self._background_plugin is not None) or (
self._background_spectrum
) is not None, "No background exists!"
return self._exposure_ratio
@property
def scale_factor(self):
"""
Ratio between the source and the background exposure and area
:return:
"""
# if (self._background_spectrum is None) and (self._background_plugin is None):
# return 1
#
# return self._observed_spectrum.exposure / self.background_exposure * self._observed_spectrum.scale_factor / self.background_scale_factor
assert (self._background_plugin is not None) or (
self._background_spectrum
) is not None, "No background exists!"
return self._total_scale_factor
@property
def background_exposure(self):
"""
Exposure of the background spectrum, if present
"""
return self._background_exposure
@property
def background_scale_factor(self):
"""
The background scale factor
:return:
"""
return self._background_scale_factor
@property
def background_spectrum(self):
assert (
self._background_spectrum is not None
), "This SpectrumLike instance has no background"
return self._background_spectrum
@property
def background_plugin(self):
return self._background_plugin
@property
def observed_spectrum(self):
return self._observed_spectrum
@classmethod
def _get_synthetic_plugin(cls, observation, background, source_function):
speclike_gen = cls("generator", observation, background, verbose=False)
pts = PointSource("fake", 0.0, 0.0, source_function)
model = Model(pts)
speclike_gen.set_model(model)
return speclike_gen
@staticmethod
def _build_fake_observation(
fake_data, channel_set, source_errors, source_sys_errors, is_poisson, **kwargs
):
"""
This is the fake observation builder for SpectrumLike which builds data
for a binned spectrum without dispersion. It must be overridden in child classes.
:param fake_data: series of values... they are ignored later
:param channel_set: a channel set
:param source_errors:
:param source_sys_errors:
:param is_poisson:
:return:
"""
observation = BinnedSpectrum(
fake_data,
exposure=1.0,
ebounds=channel_set.edges,
count_errors=source_errors,
sys_errors=source_sys_errors,
quality=None,
scale_factor=1.0,
is_poisson=is_poisson,
mission="fake_mission",
instrument="fake_instrument",
tstart=0.0,
tstop=1.0,
)
return observation
@classmethod
def from_background(cls, name, spectrum_like, verbose=True):
"""
Extract a SpectrumLike plugin from the background of another SpectrumLike (or subclass) instance
:param name: name of the extracted_plugin
:param spectrum_like: plugin with background to extract
:param verbose: if the plugin should be verbose
:return: SpectrumLike instance from the background
"""
background_only_spectrum = copy.deepcopy(spectrum_like.background_spectrum)
background_spectrum_like = SpectrumLike(
name, observation=background_only_spectrum, background=None, verbose=verbose
)
return background_spectrum_like
@classmethod
def from_function(
cls,
name,
source_function,
energy_min,
energy_max,
source_errors=None,
source_sys_errors=None,
background_function=None,
background_errors=None,
background_sys_errors=None,
**kwargs
):
"""
Construct a simulated spectrum from a given source function and (optional) background function. If source and/or background errors are not supplied, the likelihood is assumed to be Poisson.
:param name: simulkated data set name
:param source_function: astromodels function
:param energy_min: array of low energy bin edges
:param energy_max: array of high energy bin edges
:param source_errors: (optional) gaussian source errors
:param source_sys_errors: (optional) systematic source errors
:param background_function: (optional) astromodels background function
:param background_errors: (optional) gaussian background errors
:param background_sys_errors: (optional) background systematic errors
:return: simulated SpectrumLike plugin
"""
channel_set = ChannelSet.from_starts_and_stops(energy_min, energy_max)
# this is just for construction
fake_data = np.ones(len(energy_min))
if source_errors is None:
is_poisson = True
else:
assert len(source_errors) == len(
energy_min
), "source error array is not the same dimension as the energy array"
is_poisson = False
if source_sys_errors is not None:
assert len(source_sys_errors) == len(
energy_min
), "background systematic error array is not the same dimension as the energy array"
# call the class dependent observation builder
observation = cls._build_fake_observation(
fake_data,
channel_set,
source_errors,
source_sys_errors,
is_poisson,
**kwargs
)
if background_function is not None:
fake_background = np.ones(len(energy_min))
if background_errors is None:
is_poisson = True
else:
assert len(background_errors) == len(
energy_min
), "background error array is not the same dimension as the energy array"
is_poisson = False
if background_sys_errors is not None:
assert len(background_sys_errors) == len(
energy_min
), "background systematic error array is not the same dimension as the energy array"
tmp_background = BinnedSpectrum(
fake_background,
exposure=1.0,
ebounds=channel_set.edges,
count_errors=background_errors,
sys_errors=background_sys_errors,
quality=None,
scale_factor=1.0,
is_poisson=is_poisson,
mission="fake_mission",
instrument="fake_instrument",
tstart=0.0,
tstop=1.0,
)
# now we have to generate the background counts
# we treat the background as a simple observation with no
# other background
background_gen = SpectrumLike(
"generator", tmp_background, None, verbose=False
)
pts_background = PointSource(
"fake_background", 0.0, 0.0, background_function
)
background_model = Model(pts_background)
background_gen.set_model(background_model)
sim_background = background_gen.get_simulated_dataset("fake")
background = sim_background._observed_spectrum
else:
background = None
generator = cls._get_synthetic_plugin(
observation, background, source_function
) # type: SpectrumLike
return generator.get_simulated_dataset(name)
def assign_to_source(self, source_name):
"""
Assign these data to the given source (instead of to the sum of all sources, which is the default)
:param source_name: name of the source (must be contained in the likelihood model)
:return: none
"""
if self._like_model is not None:
assert source_name in self._like_model.sources, (
"Source %s is not contained in " "the likelihood model" % source_name
)
self._source_name = source_name
@property
def likelihood_model(self):
assert self._like_model is not None, (
"plugin %s does not have a likelihood model" % self._name
)
return self._like_model
def get_pha_files(self):
info = {}
# we want to pass copies so that
# the user doesn't grab the instance
# and try to modify things. protection
info["pha"] = copy.copy(self._observed_spectrum)
if self._background_spectrum is not None:
info["bak"] = copy.copy(self._background_spectrum)
return info
def set_active_measurements(self, *args, **kwargs):
"""
Set the measurements to be used during the analysis. Use as many ranges as you need, and you can specify
either energies or channels to be used.
NOTE to Xspec users: while XSpec uses integers and floats to distinguish between energies and channels
specifications, 3ML does not, as it would be error-prone when writing scripts. Read the following documentation
to know how to achieve the same functionality.
* Energy selections:
They are specified as 'emin-emax'. Energies are in keV. Example:
set_active_measurements('10-12.5','56.0-100.0')
which will set the energy range 10-12.5 keV and 56-100 keV to be
used in the analysis. Note that there is no difference in saying 10 or 10.0.
* Channel selections:
They are specified as 'c[channel min]-c[channel max]'. Example:
set_active_measurements('c10-c12','c56-c100')
This will set channels 10-12 and 56-100 as active channels to be used in the analysis
* Mixed channel and energy selections:
You can also specify mixed energy/channel selections, for example to go from 0.2 keV to channel 20 and from
channel 50 to 10 keV:
set_active_measurements('0.2-c10','c50-10')
* Use all measurements (i.e., reset to initial state):
Use 'all' to select all measurements, as in:
set_active_measurements('all')
Use 'reset' to return to native PHA quality from file, as in:
set_active_measurements('reset')
* Exclude measurements:
Excluding measurements work as selecting measurements, but with the "exclude" keyword set to the energies and/or
channels to be excluded. To exclude between channel 10 and 20 keV and 50 keV to channel 120 do:
set_active_measurements(exclude=["c10-20", "50-c120"])
* Select and exclude:
Call this method more than once if you need to select and exclude. For example, to select between 0.2 keV and
channel 10, but exclude channel 30-50 and energy , do:
set_active_measurements("0.2-c10",exclude=["c30-c50"])
* Using native PHA quality:
To simply add or exclude channels from the native PHA, one can use the use_quailty
option:
set_active_measurements("0.2-c10",exclude=["c30-c50"], use_quality=True)
This translates to including the channels from 0.2 keV - channel 10, exluding channels
30-50 and any channels flagged BAD in the PHA file will also be excluded.
:param args:
:param exclude: (list) exclude the provided channel/energy ranges
:param use_quality: (bool) use the native quality on the PHA file (default=False)
:return:
"""
# To implement this we will use an array of boolean index,
# which will filter
# out the non-used channels during the logLike
# Now build the new mask: values for which the mask is 0 will be masked
# We will build the high res mask even if we are
# already rebinned so that it can be saved
assert self._rebinner is None, (
"You cannot select active measurements if you have a rebinning active. "
"Remove it first with remove_rebinning"
)
if "use_quality" in kwargs:
use_quality = kwargs.pop("use_quality")
else:
use_quality = False
if use_quality:
# Start with quality mask. This means that channels
# marked good by quality will be used unless exluded in the arguments
# and channels marked bad by quality will be excluded unless included
# by the arguments
self._mask = self._observed_spectrum.qaulity.good
else:
# otherwise, we will start out with all channels deselected
# and turn the on/off by the arguments
self._mask = np.zeros(self._observed_spectrum.n_channels, dtype=bool)
if "all" in args:
# Just make sure than no further selections have been made.