forked from sherpa/sherpa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_astro_ui_plot.py
1101 lines (843 loc) · 30.7 KB
/
test_astro_ui_plot.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) 2019, 2020 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.
#
"""
Basic tests of the plot functionality in sherpa.astro.ui.
It is based on sherpa/ui/tests/test_ui_plot.py, but focusses on the
new routines, and "astro-specific" (currently PHA only) capabilities
that are in the astro layer.
There is very-limited checking that the plots are displaying the
correct data; it is more a check that the routines can be called.
"""
import logging
import numpy as np
from sherpa.astro import ui
from sherpa.astro.plot import ARFPlot, BkgDataPlot, ModelHistogram, \
SourcePlot
from sherpa.utils.err import IdentifierErr
from sherpa.utils.testing import requires_data, requires_fits, \
requires_plotting, requires_pylab, requires_xspec
import pytest
_data_chan = np.linspace(1, 10, 10, dtype=np.int8)
_data_counts = np.asarray([0, 1, 2, 3, 4, 0, 1, 2, 3, 4],
dtype=np.int8)
_data_bkg = np.asarray([1, 0, 0, 1, 0, 0, 2, 0, 0, 1],
dtype=np.int8)
_arf = np.asarray([0.8, 0.8, 0.9, 1.0, 1.1, 1.1, 0.7, 0.6, 0.6, 0.6])
# using a "perfect" RMF, in that there's a one-to-one mapping
# from channel to energy
#
_energies = np.linspace(0.5, 1.5, 11)
# How much longer is the background exposure compared to the source
# exposure; chose a non-integer value to make it more obvious when
# it is being applied (e.g. compared to the scaling ratios applied
# to the backscal values).
#
_bexpscale = 2.5
def example_pha_data():
"""Create an example data set."""
etime = 1201.0
d = ui.DataPHA('example', _data_chan.copy(),
_data_counts.copy(),
exposure=etime,
backscal=0.1)
a = ui.create_arf(_energies[:-1].copy(),
_energies[1:].copy(),
specresp=_arf.copy(),
exposure=etime)
r = ui.create_rmf(_energies[:-1].copy(),
_energies[1:].copy(),
e_min=_energies[:-1].copy(),
e_max=_energies[1:].copy(),
startchan=1,
fname=None)
d.set_arf(a)
d.set_rmf(r)
return d
def example_pha_with_bkg_data():
"""Create an example data set with background
There is no response for the background.
"""
d = example_pha_data()
b = ui.DataPHA('example-bkg', _data_chan.copy(),
_data_bkg.copy(),
exposure=1201.0 * _bexpscale,
backscal=0.4)
d.set_background(b)
return d
def example_model():
"""Create an example model."""
ui.create_model_component('const1d', 'cpt')
cpt = ui.get_model_component('cpt')
cpt.c0 = 1.02e2
return cpt
def example_bkg_model():
"""Create an example background model."""
ui.create_model_component('powlaw1d', 'bcpt')
bcpt = ui.get_model_component('bcpt')
bcpt.gamma = 0.0 # use a flat model to make it easy to evaluate
bcpt.ampl = 1e-1
return bcpt
def setup_example(idval):
"""Set up a simple dataset for use in the tests.
A *very basic* ARF is used, along with an ideal RMF. The
way this is created means the analysis is in channel space
by default.
Parameters
----------
idval : None, int, str
The dataset identifier.
See Also
--------
setup_example_bkg
"""
d = example_pha_data()
m = example_model()
if idval is None:
ui.set_data(d)
ui.set_source(m)
else:
ui.set_data(idval, d)
ui.set_source(idval, m)
def setup_example_bkg(idval):
"""Set up a simple dataset + background for use in the tests.
Parameters
----------
idval : None, int, str
The dataset identifier.
See Also
--------
setup_example, setup_example_bkg_model
"""
d = example_pha_with_bkg_data()
m = example_model()
if idval is None:
ui.set_data(d)
ui.set_source(m)
else:
ui.set_data(idval, d)
ui.set_source(idval, m)
def setup_example_bkg_model(idval):
"""Set up a simple dataset + background for use in the tests.
This includes a model for the background, unlike
setup-example_bkg.
Parameters
----------
idval : None, int, str
The dataset identifier.
See Also
--------
setup_example_bkg
"""
d = example_pha_with_bkg_data()
m = example_model()
bm = example_bkg_model()
if idval is None:
ui.set_data(d)
ui.set_source(m)
ui.set_bkg_model(bm)
else:
ui.set_data(idval, d)
ui.set_source(idval, m)
ui.set_bkg_model(idval, bm)
"""
Functions that could be tested:
plot_model
plot_source
plot_model_component
plot_source_component
plot_order
plot_bkg
plot_bkg_model
plot_bkg_resid
plot_bkg_ratio
plot_bkg_delchi
plot_bkg_chisqr
plot_bkg_fit
plot_bkg_source
plot_bkg_fit_ratio
plot_bkg_fit_resid
plot_bkg_fit_delchi
plot_arf
get_arf_plot X
get_bkg_chisqr_plot
get_bkg_delchi_plot
get_bkg_fit_plot X
get_bkg_model_plot X
get_bkg_plot X
get_bkg_ratio_plot
get_bkg_resid_plot X
get_bkg_source_plot
get_model_component_plot
get_model_plot X
get_order_plot
get_source_component_plot
get_source_plot X
"""
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_arf_plot(idval):
"""Basic testing of get_arf_plot
"""
setup_example(idval)
if idval is None:
ap = ui.get_arf_plot()
else:
ap = ui.get_arf_plot(idval)
assert isinstance(ap, ARFPlot)
assert ap.xlo == pytest.approx(_energies[:-1])
assert ap.xhi == pytest.approx(_energies[1:])
assert ap.y == pytest.approx(_arf)
assert ap.title == 'test-arf'
assert ap.xlabel == 'Energy (keV)'
# the y label depends on the backend (due to LaTeX)
# assert ap.ylabel == 'cm$^2$'
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_bkg_plot(idval):
"""Basic testing of get_bkg_plot
"""
setup_example_bkg(idval)
if idval is None:
bp = ui.get_bkg_plot()
else:
bp = ui.get_bkg_plot(idval)
assert isinstance(bp, BkgDataPlot)
assert bp.x == pytest.approx(_data_chan)
# normalise by exposure time and bin width, but bin width here
# is 1 (because it is being measured in channels).
#
yexp = _data_bkg / 1201.0 / _bexpscale
assert bp.y == pytest.approx(yexp)
assert bp.title == 'example-bkg'
assert bp.xlabel == 'Channel'
assert bp.ylabel == 'Counts/sec/channel'
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_bkg_plot_energy(idval):
"""Basic testing of get_bkg_plot: energy
"""
# The way I have set up the data means that set_analysis
# doesn't seem to change the setting for the background,
# which should be tracked down (Sep 2019) but not just now.
#
setup_example_bkg(idval)
if idval is None:
ui.set_analysis('energy')
ui.get_bkg().units = 'energy'
bp = ui.get_bkg_plot()
else:
ui.set_analysis(idval, 'energy')
ui.get_bkg(idval).units = 'energy'
bp = ui.get_bkg_plot(idval)
# TODO: is this a bug in the plotting code, or does it just
# indicate that the test hasn't set up the correct invariants
# (which may be true as the code above has to change the units
# setting of the background object)?
#
# I was expecting bp.x to return energy and not channel values
#
assert bp.x == pytest.approx(_data_chan)
# normalise by exposure time and bin width, but bin width here
# is 1 (because it is being measured in channels).
#
yexp = _data_bkg / 1201.0 / _bexpscale
assert bp.y == pytest.approx(yexp)
assert bp.title == 'example-bkg'
assert bp.xlabel == 'Energy (keV)'
assert bp.ylabel == 'Counts/sec/keV'
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
@pytest.mark.parametrize("gfunc", [ui.get_bkg_plot,
ui.get_bkg_model_plot,
ui.get_bkg_fit_plot])
def test_get_bkg_plot_no_bkg(idval, gfunc):
"""Basic testing of get_bkg_XXX_plot when there's no background
"""
setup_example(idval)
with pytest.raises(IdentifierErr):
if idval is None:
gfunc()
else:
gfunc(idval)
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_model_plot(idval):
"""Basic testing of get_model_plot
"""
setup_example(idval)
if idval is None:
mp = ui.get_model_plot()
else:
mp = ui.get_model_plot(idval)
assert isinstance(mp, ModelHistogram)
assert mp.xlo == pytest.approx(_data_chan)
assert mp.xhi == pytest.approx(_data_chan + 1)
# The model is a constant, but integrated across the energy bin,
# so the energy width is important here to get the normalization
# right. It should also be divided by the channel width, but in
# this case each bin has a channel width of 1.
#
yexp = _arf * 1.02e2 * (_energies[1:] - _energies[:-1])
assert mp.y == pytest.approx(yexp)
assert mp.title == 'Model'
assert mp.xlabel == 'Channel'
assert mp.ylabel == 'Counts/sec/channel'
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_model_plot_energy(idval):
"""Basic testing of get_model_plot: energy
"""
setup_example(idval)
if idval is None:
ui.set_analysis('energy')
mp = ui.get_model_plot()
else:
ui.set_analysis(idval, 'energy')
mp = ui.get_model_plot(idval)
assert mp.xlo == pytest.approx(_energies[:-1])
assert mp.xhi == pytest.approx(_energies[1:])
# This should be normalized by the bin width, but it is cancelled
# out by the fact that the model normalization has to be multiplied
# by the bin width (both in energy).
#
yexp = _arf * 1.02e2
assert mp.y == pytest.approx(yexp)
assert mp.title == 'Model'
assert mp.xlabel == 'Energy (keV)'
assert mp.ylabel == 'Counts/sec/keV'
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_source_plot_warning(caplog, idval):
"""Does get_source_plot create a warning about channel space?
This is a logged warning, not a UserWarning.
"""
setup_example(idval)
if idval is None:
ui.get_source_plot()
else:
ui.get_source_plot(idval)
emsg = 'Channel space is unappropriate for the PHA unfolded ' + \
'source model,\nusing energy.'
assert len(caplog.record_tuples) == 1
rec = caplog.record_tuples[0]
assert len(rec) == 3
loc, lvl, msg = rec
assert loc == 'sherpa.astro.plot'
assert lvl == logging.WARNING
assert msg == emsg
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_source_plot_energy(idval):
"""Basic testing of get_source_plot: energy
"""
setup_example(idval)
if idval is None:
ui.set_analysis('energy')
sp = ui.get_source_plot()
else:
ui.set_analysis(idval, 'energy')
sp = ui.get_source_plot(idval)
assert isinstance(sp, SourcePlot)
assert sp.xlo == pytest.approx(_energies[:-1])
assert sp.xhi == pytest.approx(_energies[1:])
yexp = 1.02e2 * np.ones(10)
assert sp.y == pytest.approx(yexp)
assert sp.title == 'Source Model of example'
assert sp.xlabel == 'Energy (keV)'
# y label depends on the backend
# assert sp.ylabel == 'f(E) Photons/sec/cm$^2$/keV'
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_bkg_model_plot(idval):
"""Basic testing of get_bkg_model_plot
"""
setup_example_bkg_model(idval)
if idval is None:
bp = ui.get_bkg_model_plot()
else:
bp = ui.get_bkg_model_plot(idval)
print(bp)
assert bp.xlo == pytest.approx(_data_chan)
assert bp.xhi == pytest.approx(_data_chan + 1)
# TODO: this is the same output as test_get_bkg_model_plot_energy,
# which doesn't make sense.
yexp = _arf / (_bexpscale * 100)
assert bp.y == pytest.approx(yexp)
assert bp.title == 'Model'
assert bp.xlabel == 'Channel'
assert bp.ylabel == 'Counts/sec/channel'
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_bkg_model_plot_energy(idval):
"""Basic testing of get_bkg_model_plot: energy
"""
# The way I have set up the data means that set_analysis
# doesn't seem to change the setting for the background,
# which should be tracked down (Sep 2019) but not just now.
#
setup_example_bkg_model(idval)
if idval is None:
ui.set_analysis('energy')
ui.get_bkg().units = 'energy'
bp = ui.get_bkg_model_plot()
else:
ui.set_analysis(idval, 'energy')
ui.get_bkg(idval).units = 'energy'
bp = ui.get_bkg_model_plot(idval)
# TODO: is this a bug in the plotting code, or does it just
# indicate that the test hasn't set up the correct invariants
# (which may be true as the code above has to change the units
# setting of the background object)?
#
# I was expecting bp.x to return energy and not channel values
#
assert bp.xlo == pytest.approx(_data_chan - 0.5)
assert bp.xhi == pytest.approx(_data_chan + 0.5)
# TODO: The factor of 100 comes from the bin width (0.1 keV), but
# why is there a scaling by _bexpscale?
yexp = _arf / (_bexpscale * 100)
assert bp.y == pytest.approx(yexp)
assert bp.title == 'Model'
assert bp.xlabel == 'Energy (keV)'
assert bp.ylabel == 'Counts/sec/keV'
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_bkg_resid_plot(idval):
"""Basic testing of get_bkg_resid_plot
"""
setup_example_bkg_model(idval)
if idval is None:
bp = ui.get_bkg_resid_plot()
else:
bp = ui.get_bkg_resid_plot(idval)
assert bp.x == pytest.approx(_data_chan)
# correct the counts by the bin width and exposure time
#
yexp = (_data_bkg * 100.0 / 1201.0 - _arf) / (_bexpscale * 100)
assert bp.y == pytest.approx(yexp)
assert bp.title == 'Residuals of example-bkg - Bkg Model'
assert bp.xlabel == 'Channel'
assert bp.ylabel == 'Counts/sec/channel'
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_bkg_resid_plot_energy(idval):
"""Basic testing of get_bkg_resid_plot: energy
"""
setup_example_bkg_model(idval)
if idval is None:
ui.set_analysis('energy')
ui.get_bkg().units = 'energy'
bp = ui.get_bkg_resid_plot()
else:
ui.set_analysis(idval, 'energy')
ui.get_bkg(idval).units = 'energy'
bp = ui.get_bkg_resid_plot(idval)
assert bp.x == pytest.approx(_data_chan)
# correct the counts by the bin width and exposure time
#
yexp = (_data_bkg * 100.0 / 1201.0 - _arf) / (_bexpscale * 100)
assert bp.y == pytest.approx(yexp)
assert bp.title == 'Residuals of example-bkg - Bkg Model'
assert bp.xlabel == 'Energy (keV)'
assert bp.ylabel == 'Counts/sec/keV'
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_bkg_fit_plot(idval):
"""Basic testing of get_bkg_fit_plot
"""
setup_example_bkg_model(idval)
if idval is None:
fp = ui.get_bkg_fit_plot()
else:
fp = ui.get_bkg_fit_plot(idval)
dp = fp.dataplot
mp = fp.modelplot
assert dp.title == 'example-bkg'
assert mp.title == 'Background Model Contribution'
for plot in [dp, mp]:
assert plot.xlabel == 'Channel'
assert plot.ylabel == 'Counts/sec/channel'
assert plot.x == pytest.approx(_data_chan)
yexp = _data_bkg / 1201.0 / _bexpscale
assert dp.y == pytest.approx(dp.y)
yexp = _arf / 100.0 / _bexpscale
assert mp.y == pytest.approx(yexp)
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
def test_get_bkg_fit_plot_energy(idval):
"""Basic testing of get_bkg_fit_plot: energy
"""
setup_example_bkg_model(idval)
if idval is None:
ui.set_analysis('energy')
ui.get_bkg().units = 'energy'
fp = ui.get_bkg_fit_plot()
else:
ui.set_analysis(idval, 'energy')
ui.get_bkg(idval).units = 'energy'
fp = ui.get_bkg_fit_plot(idval)
dp = fp.dataplot
mp = fp.modelplot
assert dp.title == 'example-bkg'
assert mp.title == 'Background Model Contribution'
for plot in [dp, mp]:
assert plot.xlabel == 'Energy (keV)'
assert plot.ylabel == 'Counts/sec/keV'
assert plot.x == pytest.approx(_data_chan)
yexp = _data_bkg / 1201.0 / _bexpscale
assert dp.y == pytest.approx(dp.y)
yexp = _arf / 100.0 / _bexpscale
assert mp.y == pytest.approx(yexp)
def check_bkg_fit(plotfunc):
"""Is the background fit displayed?
This only checks the plot object, not the plot "hardcopy" output
(e.g. the pixel display/PNG output).
"""
dplot = ui._session._bkgdataplot
mplot = ui._session._bkgmodelplot
# check the "source" plots are not set
for plot in [ui._session._dataplot, ui._session._modelplot]:
assert plot.x is None
assert plot.y is None
xlabel = 'Channel' if plotfunc == ui.plot_bkg_fit else ''
# check plot basics
for plot in [dplot, mplot]:
assert plot.xlabel == xlabel
assert plot.ylabel == 'Counts/sec/channel'
assert plot.x == pytest.approx(_data_chan)
assert dplot.title == 'example-bkg'
assert mplot.title == 'Background Model Contribution'
yexp = _data_bkg / 1201.0 / _bexpscale
assert dplot.y == pytest.approx(yexp)
yexp = _arf / (_bexpscale * 100)
assert mplot.y == pytest.approx(yexp)
def check_bkg_resid(plotfunc):
"""Is the background residual displayed?
This only checks the plot object, not the plot "hardcopy" output
(e.g. the pixel display/PNG output).
There is limited checks of the actual values, since the
assumption is that this test is just to check the plots were
constructed from its components, and that other tests above
will have checked that the components work.
"""
# check the "other" background plots are not set
plot = None
for pf, pd in [(ui.plot_bkg_fit_delchi, ui._session._bkgdelchiplot),
(ui.plot_bkg_fit_ratio, ui._session._bkgratioplot),
(ui.plot_bkg_fit_resid, ui._session._bkgresidplot)]:
if pf == plotfunc:
assert plot is None # a precaution
plot = pd
continue
else:
assert pd.x is None
assert pd.y is None
# very limited checks
#
assert plot.xlabel == 'Channel'
assert plot.ylabel != '' # depends on the plot type
assert plot.title == ''
assert plot.x == pytest.approx(_data_chan)
assert plot.y is not None
# the way the data and model are constructed, all residual values
# should be negative, and the ratio values positive (or zero).
#
if plotfunc == ui.plot_bkg_fit_ratio:
assert np.all(plot.y >= 0)
else:
assert np.all(plot.y < 0)
@requires_plotting
@pytest.mark.usefixtures("clean_astro_ui")
@pytest.mark.parametrize("idval", [None, 1, "one", 23])
@pytest.mark.parametrize("plotfunc,checkfuncs",
[(ui.plot_bkg_fit, [check_bkg_fit]),
(ui.plot_bkg_fit_delchi, [check_bkg_fit, check_bkg_resid]),
(ui.plot_bkg_fit_ratio, [check_bkg_fit, check_bkg_resid]),
(ui.plot_bkg_fit_resid, [check_bkg_fit, check_bkg_resid])])
def test_bkg_plot_xxx(idval, plotfunc, checkfuncs):
"""Test background plotting - channel space"""
setup_example_bkg_model(idval)
if idval is None:
plotfunc()
else:
plotfunc(idval)
# The X label of the plots may depend on whether there are 1
# or two plots. The following isn't ideal but let's see how
# it goes.
#
for checkfunc in checkfuncs:
checkfunc(plotfunc)
# The following tests were added in a separate PR to those above, and
# rather than try to work out whether they do the same thing, they
# have been left separate.
#
@pytest.fixture
def basic_pha1(make_data_path):
"""Create a basic PHA-1 data set/setup"""
ui.set_default_id('tst')
ui.load_pha(make_data_path('3c273.pi'))
ui.subtract()
ui.notice(0.5, 7)
ui.set_source(ui.powlaw1d.pl)
pl = ui.get_model_component('pl')
pl.gamma = 1.93
pl.ampl = 1.74e-4
@pytest.fixture
def basic_img(make_data_path):
"""Create a basic image data set/setup"""
ui.set_default_id(2)
ui.load_image(make_data_path('img.fits'))
ui.set_source(ui.gauss2d.gmdl)
ui.guess()
_basic_plotfuncs = [ui.plot_data,
ui.plot_bkg,
ui.plot_model,
ui.plot_source,
ui.plot_resid,
ui.plot_delchi,
ui.plot_ratio,
ui.plot_fit,
ui.plot_fit_delchi,
ui.plot_fit_resid,
ui.plot_arf,
ui.plot_chisqr]
@requires_plotting
@requires_fits
@requires_data
def test_pha1_plot_function(clean_astro_ui, basic_pha1):
# can we call plot; do not try to be exhaustive
ui.plot("data", "bkg", "fit", "arf")
@requires_plotting
@requires_fits
@requires_data
@pytest.mark.parametrize("plotfunc", _basic_plotfuncs)
def test_pha1_plot(clean_astro_ui, basic_pha1, plotfunc):
plotfunc()
@requires_plotting
@requires_fits
@requires_data
@pytest.mark.parametrize("plotfunc", [ui.plot_model_component,
ui.plot_source_component])
def test_pha1_plot_component(clean_astro_ui, basic_pha1, plotfunc):
plotfunc("pl")
@requires_plotting
@requires_fits
@requires_data
@pytest.mark.parametrize("plotfunc", [ui.int_unc, ui.int_proj])
def test_pha1_int_plot(clean_astro_ui, basic_pha1, plotfunc):
plotfunc('pl.gamma')
@requires_plotting
@requires_fits
@requires_data
@pytest.mark.parametrize("plotfunc", [ui.reg_unc, ui.reg_proj])
def test_pha1_reg_plot(clean_astro_ui, basic_pha1, plotfunc):
plotfunc('pl.gamma', 'pl.ampl')
_img_plotfuncs = [ui.contour_data,
ui.contour_fit,
ui.contour_fit_resid,
ui.contour_model,
ui.contour_ratio,
ui.contour_resid,
ui.contour_source ]
@requires_plotting
@requires_fits
@requires_data
def test_img_contour_function(clean_astro_ui, basic_img):
# can we call contour; do not try to be exhaustive
ui.contour("data", "model", "source", "fit")
@requires_plotting
@requires_fits
@requires_data
@pytest.mark.parametrize("plotfunc", _img_plotfuncs)
def test_img_contour(clean_astro_ui, basic_img, plotfunc):
plotfunc()
# Add in some pylab-specific tests to change default values
#
@requires_pylab
@requires_fits
@requires_data
def test_pha1_plot_data_options(clean_astro_ui, basic_pha1):
"""Test that the options have changed things, where easy to do so"""
from matplotlib import pyplot as plt
prefs = ui.get_data_plot_prefs()
# check the preference are as expected for the boolean cases
assert not prefs['xerrorbars']
assert prefs['yerrorbars']
assert not prefs['xlog']
assert not prefs['ylog']
prefs['xerrorbars'] = True
prefs['yerrorbars'] = False
prefs['xlog'] = True
prefs['ylog'] = True
prefs['color'] = 'orange'
prefs['linecolor'] = 'brown'
prefs['linestyle'] = '-.'
prefs['marker'] = 's'
prefs['markerfacecolor'] = 'cyan'
prefs['markersize'] = 10
ui.plot_data()
ax = plt.gca()
assert ax.get_xscale() == 'log'
assert ax.get_yscale() == 'log'
assert ax.get_xlabel() == 'Energy (keV)'
assert ax.get_ylabel() == 'Counts/sec/keV'
# It is not clear whether an 'exact' check on the value, as
# provided by pytest.approx, makes sense, or whether a "softer"
# check - e.g. just check whether it is less- or greater- than a
# value - should be used. It depends on how often matplotlib
# tweaks the axis settings and how sensitive it is to
# platform/backend differences. Let's see how pytest.approx works
#
xmin, xmax = ax.get_xlim()
assert xmin == pytest.approx(0.40110954270367555)
assert xmax == pytest.approx(11.495805054836712)
ymin, ymax = ax.get_ylim()
assert ymin == pytest.approx(7.644069935298475e-05)
assert ymax == pytest.approx(0.017031102671151491)
assert len(ax.lines) == 1
line = ax.lines[0]
# Apparently color wins out over linecolor
assert line.get_color() == 'orange'
assert line.get_linestyle() == '-.'
assert line.get_marker() == 's'
assert line.get_markerfacecolor() == 'cyan'
assert line.get_markersize() == pytest.approx(10.0)
# assume error bars handled by a collection; test a subset
# of values
#
assert len(ax.collections) == 1
coll = ax.collections[0]
assert len(coll.get_segments()) == 42
assert coll.get_linestyles() == [(None, None)]
# looks like the color has been converted to individual channels
# - e.g. floating-point values for R, G, B, and alpha.
#
colors = coll.get_color()
assert len(colors) == 1
assert len(colors[0]) == 4
r, g, b, a = colors[0]
assert r == pytest.approx(1)
assert g == pytest.approx(0.64705882)
assert b == pytest.approx(0)
assert a == pytest.approx(1)
@requires_pylab
@requires_fits
@requires_data
def test_pha1_plot_model_options(clean_astro_ui, basic_pha1):
"""Test that the options have changed things, where easy to do so
In matplotlib 3.1 the plot_model call causes a MatplotlibDeprecationWarning
to be created:
Passing the drawstyle with the linestyle as a single string is deprecated since Matplotlib 3.1 and support will be removed in 3.3; please pass the drawstyle separately using the drawstyle keyword argument to Line2D or set_drawstyle() method (or ds/set_ds()).
This warning is hidden by the test suite (sherpa/conftest.py) so that
it doesn't cause the tests to fail. Note that a number of other tests
in this module also cause this warning to be displayed.
"""
from matplotlib import pyplot as plt
# Note that for PHA data sets, the mode is drawn as a histogram,
# so get_model_plot_prefs doesn't actually work. We need to change
# the histogram prefs instead. See issue
# https://github.com/sherpa/sherpa/issues/672
#
# prefs = ui.get_model_plot_prefs()
prefs = ui.get_model_plot().histo_prefs
# check the preference are as expected for the boolean cases
assert not prefs['xlog']
assert not prefs['ylog']
# Only change the X axis here
prefs['xlog'] = True
prefs['color'] = 'green'
prefs['linecolor'] = 'red'
prefs['linestyle'] = 'dashed'