forked from cxcsds/ciao-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmk_runtool.header
2494 lines (1911 loc) · 83.8 KB
/
mk_runtool.header
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) 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2021, 2022, 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 2 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.
#
# TODO
#
# use try/finally and context generators to make sure resources,
# such as parameter files, are closed. This has been done in _run()
# but are there other areas where it could be done?
#
"""Summary
=======
This module allows users to run CIAO command-line tools with parameter files
by calling a function with the name of the tool: for example
dmcopy("in.fits", "out.fits", clobber=True)
print(dmstat(infile="img.fits", centroid=False, verbose=0))
If using an interactive Python session - such as IPython or Sherpa - the
output will be displayed on-screen, so you can just say
dmstat(infile="img.fits", centroid=False, verbose=0)
Parameters may also be set before running the tool using the syntax
toolname.paramname - e.g. the dmstat call above can be written as
dmstat.centroid = False
dmstat.median = True
dmstat("evt2.fits[bin sky=::1]")
or even
dmstat.centroid = False
dmstat.median = True
dmstat.infile = "evt2.fits[bin sky=::1]"
dmstat()
Once the tool has been run the parameters can be accessed; for instance
dmstat("simple.dat", median=True)
print(f"Median = {dmstat.out_median}")
or
acis_bkgrnd_lookup("evt2.fits")
match = acis_bkgrnd_lookup.outfile
print(f"Found file: {match}")
There is also support for those parameter files which have no associated
tools - e.g. lut, colors, or ardlib. So you can say
print(f"Location of LUT 'a' is {lut.a}")
but you cannot run these commands. Attempting to do so will result in
an error like
colors()
TypeError: 'CIAOParameter' object is not callable
Parameter handling
==================
Names
-----
In the summary, the full parameter names were given, but - as with the
command-line version - the names can be abbreviated to any unique
prefix. This means that the following can also be used:
print(dmstat("evt2.fits[bin sky=::1]", cen=False, med=True))
or
dmstat.cent = False
dmstat.med = True
dmstat.inf = "evt2.fits[bin sky=::1]"
dmstat()
The use of an invalid parameter name - both in <toolname>.<parname>
and in the argument list when calling the tool - will result in an
error. For example:
dmstat.niter = 10
AttributeError: There is no parameter for dmstat that matches 'niter'
dmstat.c = True
AttributeError: Multiple matches for dmstat parameter 'c', choose from:
centroid clip
When using abbreviations, be aware that some apparently valid names
will conflict with reserved Python keywords; one example is using "in"
for a parameter like "infile". This will result in a Syntax Error.
There is one note for the above: a few parameters can not be represented
as Python identifiers since they contain a '-' character (they are all
ardlib parameters). For these parameters, the name used in this
module has the '-' replaced with '_', so you would use
ardlib.AXAF_HRC_I_BADPIX_FILE
to refer to the AXAF_HRC-I_BADPIX_FILE parameter of ardlib.
Values
------
Please see the NOTE below for information on how this information is
slightly different for those tools written as shell scripts.
When the module is imported, each tool is set up so that its
parameters are set to the CIAO default values. Once the tool has run,
the settings are updated to match any changes the tool may have made
to the parameter settings (e.g. setting values such as outfile or
out_median).
When a parameter is set for a tool - e.g.
acis_process_events.infile = "evt2.fits"
then this setting ONLY applies to this routine; it does NOT write the
value to the on-disk parameter file for the tool (unless you use the
write_params method, as described below).
If a tool relies on any other parameter file - e.g. many of the
Chandra instrument tools will implicitly use the ardlib parameter file
- then these settings are obtained using that tools parameter file
(i.e. the file located in the PFILES environment variable), and NOT
from the settings for that tool or parameter file in this module.
Therefore setting
ardlib.AXAF_ACIS0_BADPIX_FILE = "bpix1.fits[ccd_id=0]"
will *NOT* change the on-disk ardlib parameter file, and hence this
setting will not be used by any tool that needs it. To save the
settings to disk, use the write_params method:
ardlib.write_params()
will write to the system ardlib.par file and either of
ardlib.write_params("store")
ardlib.write_params("store.par")
will write to the file store.par in the current working
directory.
The read_params() can be used to read in settings from a
parameter file - e.g.
ardlib.read_params()
ardlib.read_params("store.par")
Converting between Python and parameter types
---------------------------------------------
The parameter types have been converted into Python equivalents using
the following table:
Parameter type Python type
s string
f string
b bool
i int
r float
When using string or filename parameters, you do not need to add
quotes around the name if it contains a space - so you can say
inf = "evt2.fits[energy=500:2000,sky=region(src.reg)][bin sky=::1]"
dmcopy(inf, "img.fits")
There is some support for converting Python values to the correct
type - e.g. for a boolean parameter you can use one either
- True, 1, "yes", "true", "on", "1"
- False, 0, "no", "false", "off", "0"
bit it is **strongly suggested** that you use the correct Python type
(in this case either True or False) as the conversion of other types
is not guaranteed to work reliably or match the rules used by the CXC
parameter library.
Parameters can be set to None and the system will try to do the right
thing, but it is best to be explicit when possible.
Handling of stacks
------------------
There is limited support for using arrays when setting a parameter
that can accept a stack (see "ahelp stack" for background
information). String and file parameters may be set using an array,
in which case the value is automatically converted into a
comma-separated string.
There is no support for converting a parameter value from a stack into
an array; the stk.build() routine can be used for this.
It is planned to handle stacks that exceed the maximimum parameter
length by using a temporary file to contain the values when the tool
is run; the current behavior in this case should be to throw an error
that the expected and stored parameter values do not match.
An example of use is:
dmstat.punlearn()
dmstat.median = False
dmstat.centroid = False
dmstat(["file1.img", "file2.img"])
After the above, the dmstat.infile parameter will be set to the string
"file1.img,file2.img"
NOTE: special case for shell scripts
------------------------------------
There are several tools which are written as shell scripts that do not
support the <@@name.par> syntax for calling a CIAO tool (see the
'ahelp parameter' page for more information on this functionality). Care
should be taken to avoid running multiple copies of these tools at the
same time; if this is likely to happen use the new_pfiles_environment
context handler or the set_pfiles() routine to set up separate user
parameter directories.
The tools for which this is true are: axbary, dmgti, evalpos, fullgarf,
mean_energy_map, pileup_map, tgdetect, and wavdetect.
Displaying the current setting
------------------------------
The print command can be used to display the current parameter settings
of a tool; for instance
print(dmimgcalc)
Parameters for dmimgcalc:
Required parameters:
infile = Input file #1
infile2 = Input file #2
outfile = output file
operation = arithmetic operation
Optional parameters:
weight = 1 weight for first image
weight2 = 1 weight for second image
lookupTab = ${ASCDS_CALIB}/dmmerge_header_lookup.txt lookup table
clobber = False delete old output
verbose = 0 output verbosity
The tool also acts as a Python iterator, so you can loop through
the parameter names and values using code like the following:
for (pname, pval) in dmimgcalc:
print(f"{pname} = {pval}")
Resetting parameter values
--------------------------
The parameter values for a tool can be reset using the punlearn()
method - e.g.
dmstat.punlearn()
Parameter redirects
-------------------
There is limited support for setting a parameter value using the
"re-direct" functionality of the parameter library - e.g. values like
")sclmin", which mean use the value of the sclmin parameter of the
tool . Such re-directs can only be used to parameter values from the
same tool, so the value ")dmstat.centroid" is not permitted.
Excluded parameters
-------------------
The following parameters are not included for the tools:
- the mode parameter
- any parameter that can only be set to a single value is
ignored
Parameter constraints
---------------------
There is currently no access to the constraints on a parameter, namely
whether it has a lower- or upper-limit set, or is restricted to a set
of values.
How is the tool run?
====================
The tool is always run with the mode set to 'hl', so that there will
be no querying the user for arguments.
dmstat.punlearn()
print(dmstat("img.fits", centroid=False, median=True))
or
dmstat.punlearn()
dmstat.infile = "img.fits"
dmstat.cent = False
dmstat.med = True
print(dmstat())
If there was an error running the tool then an IOError will be raised,
otherwise the screen output of the tool will be returned (including
any output to STDERR, since it is possible for a CIAO tool to run
successfully and produce output on the STDERR channel).
To avoid problems with running multiple copies of a tool at the same
time, the tool is run using its own parameter file, supplied using the
"@@<filename>" form of the tool. This should be invisible to users of
this module. The location used for the temporary parameter file is
controlled by the ASCDS_WORK_PATH environment variable.
As noted above in the 'special case for shell scripts' section,
this method is not used for several tools. You may need to use
the new_pfiles_environment() context manager to automate the
creation of a new PFILES environment and directory for each run,
or the set_pfiles() routine to handle this case manually.
Detecting errors
================
An IOError is raised if the tool returns a non-zero exit
status. Unfortunately some CIAO tools still return a zero exit status
when they error out; for such cases it will appear as if the tool ran
successfully. The full screen output is included in the error, with
each line indented for readability at the IPython/Sherpa prompt.
As an example,
dmcopy("in.fits[cols x", "out.fits")
raises the error
IOError: An error occurred while running 'dmcopy':
Failed to open virtual file in.fits[cols x
# DMCOPY (CIAO 4.5): DM Parse error: unmatched [ or (: [cols x
The PFILES environment variable
===============================
When a tool is run, it is supplied with all the parameter values
so that there should be no problem with multiple versions of the
tool being run at the same time.
However, some tools make use of other parameter files - e.g. many of
the instrument tools such as mkinstmap or mkrmf - and these are
accessed using the standard CIAO parameter system. For standard CIAO
installations this means that the PFILES environment (see "ahelp
parameter" or https://cxc.harvard.edu/ciao/ahelp/parameter.html for
more information) is used.
The module provides a set_pfiles() routine which changes the location
of the user directory for parameter files. See 'help(set_pfiles)' for
more information on this. The get_pfiles() routine provides access to
the current settings.
If you are using any instrument-specific tools it is suggested that
you call set_pfiles() with a unique directory name, rather than with
no argument. The new_pfiles_environment() context manager can be used
to automate this, as it creates a temporary directory which is used to
store the parameter files which is then deleted on exit from the block.
An example of its use is
with new_pfiles_environment():
# The following tools are run with a PFILES directory
# that is automatically deleted at the end of the block
#
mki = make_tool("make_tool")
mki.clobber = True
mki.pixelgrid = "1:1024:1,1:1024:1"
mki.maskfile = "msk1.fits"
for ccd in [0,1,2,3]:
mki.obsfile = f"asphist{ccd}.fits[asphist]"
mki.detsubsys = f"ACIS-{ccd}"
for energy in [1,2,3,4,5]:
mki(monoenergy=energy,
out=f"imap{ccd}_e{energy}.fits")
See 'help(new_pfiles_environment)' for more information.
Using multiple versions of a tool
=================================
You can set up multiple "copies" of a tool using the make_tool
routine. This can be useful if you wish to set up common, but
different, parameter values for a tool. For instance to run the dmstat
tool with median set to False and True you could define two separate
versions dms1 and dms2 using
dms1 = make_tool("dmstat")
dms1.median = True
dms2 = make_tool("dmstat")
dms2.median = False
and then run them on files
dms1("src1.dat")
dms1("src2.dat")
dms2("src1.dat")
dms2("src2.dat")
The new_tmpdir() and new_pfiles_environment() context managers can
also be useful when running multiple tools.
Setting the HISTORY record of a file
====================================
The add_tool_history routine allows you to set the HISTORY record of
a file in a format that can be read by the dmhistory tool. This is
useful when writing your own scripts and you want to record the
parameter values used by the script to create any output files.
Verbose level
=============
If the CIAO verbose level is set to 2 then the command-line used to
run the tool is logged, as long as a logging instance has been created
using ciao_contrib.logger_wrapper.initialize_logger. As an example
from ciao_contrib.logger_wrapper import initialize_logger, set_verbosity
initialize_logger("myapp")
set_verbosity(2)
dmstat.punlearn()
dmstat("src1.dat[cols x]", median=True, centroid=True)
will create the additional screen output
Running tool dmstat using:
>>> dmstat "src1.dat[cols x]" median=yes
Note that the output only lists hidden parameters if they are not set
to their default value.
"""
import sys
import os
import stat
import operator
import subprocess
import time
import tempfile
import errno
import shutil
import glob
import re
from collections import namedtuple
from contextlib import contextmanager
# only used to check for floating-point equality
import numpy as np
import paramio as pio
import stk
import cxcdm
from ciao_contrib.logger_wrapper import initialize_module_logger
# This is to throw out any date-encoded parameter files which end in
# _YYYYMMDD.HH:MM:SS.par. I could be clever and specialize this
# (e.g. since we know the first digit of month must be 0 or 1) but
# leave that for now.
#
dtime = re.compile(r"_\d{8}\.\d{2}:\d{2}:\d{2}\.par$")
logger = initialize_module_logger("runtool")
v2 = logger.verbose2
v3 = logger.verbose3
v4 = logger.verbose4
v5 = logger.verbose5
ParValue = namedtuple("ParValue",
["name", "type", "help", "default"])
ParSet = namedtuple("ParSet",
["name", "type", "help", "default", "options"])
ParRange = namedtuple("ParRange",
["name", "type", "help", "default", "lo", "hi"])
class UnknownParamError(TypeError):
"""The parameter is not defined for this tool.
This is just to provide a slightly-more user friendly error
message than the standard Python error in this case.
"""
pass
def _from_python(type, value):
"""Return a string representation of value, where
type is the paramio "type" of the parameter
(e.g. one of "b", "i", "r", "s", "f").
A value of None for numeric types is converted to
INDEF and "" for strings/filenames.
"""
if type == "b":
if value is None:
raise ValueError("boolean values can not be set to None")
elif value:
return "yes"
else:
return "no"
elif type in "ir":
if value is None:
return "INDEF"
else:
return str(value)
elif value is None:
return ""
else:
return str(value)
def _to_python(type, value):
"""Return the Python representatiopn of the input value, which is
a string. The type value is the the paramio "type" of the
parameter (e.g. one of "b", "i", "r", "s", "f").
Values converted to None: INDEF for numeric types and "" for
strings.
Numeric types with a value of '' (or are all spaces) are converted to 0.
It looks like this is called assuming that value has been retrived
gvia one of the paramio routines, and so we don't have to deal
with all the cases we do in CIAOParameter._validate, but it has
been long enough since I wrote this that I can not guarantee it.
"""
if type == "b":
return value == "yes"
elif type == "i":
if value == "INDEF":
return None
elif str(value).strip() == "":
return 0
else:
return int(value)
elif type == "r":
if value == "INDEF":
return None
elif str(value).strip() == "":
return 0.0
else:
return float(value)
elif value == "":
return None
elif value is None:
raise ValueError("Did not expect to be sent None in _to_python")
else:
return str(value)
def _values_equal(ptype, val1, val2):
"""Decide whether two values are equal (or nearly equal) for the
given parameter type (e.g. one of 'b', 'i', 'r', 's', 'f').
val1 and val2 are assumed to be the output of _to_python(ptype, ...).
"""
if ptype != "r" or (val1 is None and val2 is None):
return val1 == val2
else:
return np.allclose([val1], [val2])
def _partial_match(matches, query, qtype="s"):
"""Returns the value from matches - an iterable - that has
query as its unique prefix. The query type is given
by qtype; it is normally expected to be 's' but can be other
values; note that prefix matching is only done if ptype is 's'.
Return values:
no match - None
one match - (value, True)
multiple matches - (matches, False)
"""
if query in matches:
return (query, True)
elif qtype != "s":
return None
else:
out = [v for v in matches if v.startswith(query)]
nout = len(out)
if nout == 0:
return None
elif nout == 1:
return (out[0], True)
else:
return (out, False)
def _time_delta(stime, etime):
"""Returns a "nice" string representing the time
difference between stime and etime (with etime > stime).
"""
dt = time.mktime(etime) - time.mktime(stime)
if dt < 1.0:
return "< 1 sec"
def myint(f):
return int(f + 0.5)
def stringify(val, unit):
out = f"{val} {unit}"
if val > 1:
out += "s"
return out
d = myint(dt // (24 * 3600))
dt2 = dt % (24 * 3600)
h = myint(dt2 // 3600)
dt3 = dt % 3600
m = myint(dt3 // 60)
s = myint(dt3 % 60)
if d > 0:
lbl = stringify(d, "day")
if h > 0:
lbl += f' {stringify(h, "hour")}'
elif h > 0:
lbl = stringify(h, "hour")
if m > 0:
lbl += f' {stringify(m, "minute")}'
elif m > 0:
lbl = stringify(m, "minute")
if s > 0:
lbl += f' {stringify(s, "second")}'
else:
lbl = stringify(s, "second")
return lbl
def _value_needs_quoting(val):
"""Returns True if the given value needs quoting when
used on the command-line as a parameter value.
"""
# TODO: are there other problem situations/characters?
#
sval = str(val)
for char in ' [(";':
if char in sval:
return True
return False
def _quote_value(val):
"""Given a string representing a parameter value, return the
string adding quotes if necessary."""
if _value_needs_quoting(val):
return f'"{val}"'
else:
return val
def _log_par_file_contents(parfile):
"Log the contents of the given parameter file"
if logger.getEffectiveVerbose() < 4:
return
v4("***** Start of parameter file")
with open(parfile, "r") as ofh:
for line in ofh.readlines():
v4(f"** {line.strip()}")
v4("***** End of parameter file")
class CIAOPrintableString(str):
"""Wraps strings for "nice" formatting.
This is intended for interactive use, such as IPython and
notebooks. Is it still needed?
"""
def __init__(self, string):
self.str = string
def __str__(self):
return self.str
def __repr__(self):
return self.str
def is_an_iterable(val):
"""Return True if this is an iterable but not a string.
This is a stop-gap routine to handle Python 2.7 to 3.5
conversion, since in 2.7 strings did not have an __iter__
method but they do now. Ideally the code would be rewritten
to avoid this logic.
Currently unclear what needs to be changed now we have dropped
Python 2.7 support, so leave in.
"""
return not isinstance(val, str) and hasattr(val, "__iter__")
# See
# http://stackoverflow.com/questions/2693883/dynamic-function-docstring
# for some work on adding individualized doc strings to
# class instances
#
# Could add __eq__/__neq__ methods, comparing parameter values
#
class CIAOParameter(object):
"""Simulate a CIAO parameter file. This class lets you set and get
parameter settings as if you were using the pset/pget command-line
tools, but using an attribute style - e.g.
print(f"The green color is {colors.green}")
ardlib.AXAF_ACIS0_BADPIX_FILE = "bpix.fits[ccd_id=0]"
To list all the parameters use the print() command, or convert to
a string; for example
print(geom)
txt = f"We have\n\n{geom}"
As with the command-line tools, the parameters can be specified
using any unique prefix of the name (case sensitive), so you can
say
ardlib.AXAF_ACIS0_B
to reder to the AXAF_AXIS0_BADPIX_FILE parameter. Using a
non-unique prefix will result in an error listing the possible
matches - so using ardlib.AXAF_ACIS0 will throw
AttributeError: Multiple matches for ardlib parameter 'AXAF_ACIS0', choose from:
AXAF_ACIS0_QE_FILE AXAF_ACIS0_QEU_FILE AXAF_ACIS0_BADPIX_FILE AXAF_ACIS0_CONTAM_FILE
and if there is no match - e.g. colors.bob - you see
AttributeError: There is no parameter for colors that matches 'bob'
The object is not callable (ie runnable); for that use the CIAOTool
subclass.
NOTES
=====
Setting a parameter value ONLY changes the object itself; it does
NOT change the on-disk parameter file. To write the values to disk
use the write_params() method.
Any '-' characters in a parameter name are converted to '_'
instead. At present this only occurs for several ardlib parameters.
There is limited support for stacks; you can set any file or
string parameter to an array which is converted to a
comma-separated set of values. Note that there is no check that
the parameter accepts stacks (since this is not encoded in the
parameter file). The stack module can be used to convert a
parameter value from the stack format into an attay
"""
def __init__(self, toolname, reqs, opts):
"""reqs is the list of the required parameters for
the tool, and opts is the list of optional parameters
(either may be []).
The reqs and opts arrays are list of named tuples; support
types are ParValue, ParSet, and ParRange.
"""
self._toolname = toolname
self._required = [p.name.replace('-', '_') for p in reqs]
self._optional = [p.name.replace('-', '_') for p in opts]
self._parnames = self._required + self._optional
z1 = list(zip(self._required, reqs))
z2 = list(zip(self._optional, opts))
self._store = dict(z1 + z2)
# we include names that are not mapped just to make it easier
z1 = list(zip(self._required,
[p.name for p in reqs]))
z2 = list(zip(self._optional,
[p.name for p in opts]))
self._orig_parnames = dict(z1 + z2)
self._defaults = {pname: self._store[pname].default
for pname in self._parnames}
# should only be accessed via _set/get_param_value
self._settings = {}
self._index = 0
self.punlearn()
def _get_param_value(self, pname):
"""Returns the parameter value. This should be used instead of
accessing self._settings directly, and should not be used by
external code, which should use the <object>.parname
interface.
pname must be the full parameter name.
"""
# at present do nothing extra
if pname not in self._parnames:
raise ValueError(f"Invalid parameter name: {pname}")
val = self._settings[pname]
return val
def _set_param_value(self, pname, nval):
"""Sets the parameter value. This should be used instead of
accessing self._settings directly, and should not be used by
external code, which should use the <object>.parname
interface.
pname must be the full parameter name and nval is assumed to
be of the correct type (although arrays are converted into
comma-separated lists here)
"""
# at present do nothing extra
if pname not in self._parnames:
raise ValueError(f"Invalid parameter name: {pname}")
if is_an_iterable(nval):
# should really enforce the type constraint for safety
# here
svals = [str(v) for v in nval]
self._settings[pname] = ",".join(svals)
else:
self._settings[pname] = nval
def __repr__(self):
return f"<CIAO parameter file: {self._toolname}>"
def _param_as_string(self, pname):
"Return a string representation of the parameter"
pi = self._store[pname]
pval = self._get_param_value(pname)
# need !s for value to keep booleans as True or False,
# otherwise gets converted to 0/1; is this a bug in Python 2.6.2?
# since "{0}".format(True) == "True"
# "{0:5}".format(True) == "1 "
# "{0!s:5}".format(True) == "True "
#
# QUS: do we want to do any manipulation of the data here?
# if pi.type == "f" and pval is None:
# pval = "INDEF"
if pi.type in "sf" and pval is None:
pval = ""
return f"{pname:>20} = {pval!s:<15} {pi.help}"
def __str__(self):
"""Return a multi-line output listing the parameter names and values"""
out = [f"Parameters for {self._toolname}:"]
if len(self._required) > 0:
out.extend(["", "Required parameters:"])
for pname in self._required:
out.append(self._param_as_string(pname))
if len(self._required) > 0:
out.extend(["", "Optional parameters:"])
for pname in self._optional:
out.append(self._param_as_string(pname))
return "\n".join(out)
# could say @property here, but since we use __setattr__
# it seems that we can (have to?) trap write access there
#
def toolname(self):
"""The name of the tool (or parameter file)"""
return self._toolname
def punlearn(self):
"""Reset the parameter values to their default settings"""
v5(f"Calling punlearn on tool {self._toolname}")
self._settings = self._defaults.copy()
def _expand_parname(self, pname):
"""Returns the parameter name that matches pname (using a
unique sub-string check); if there is no match or multiple
matches then an UnknownParamError is thrown.
The check is case sensitive.
"""
ans = _partial_match(self._parnames, pname)
if ans is None:
raise UnknownParamError(
f"There is no parameter for {self._toolname} that matches '{pname}'")
elif ans[1]:
return ans[0]
else:
choices = " ".join(ans[0])
raise UnknownParamError(
f"Multiple matches for {self._toolname} parameter '{pname}', choose from:\n {choices}")
def _validate(self, pname, val, store=True):
"""Check that val is a valid value for the parameter and
save it (if store is True). pname should be an exact parameter
name, and not a partial match. val may be a string redirect.
"""
v5(f"Entering _validate for name={pname} " +
f"val={val} (type={type(val)}) " +
f"store={store}")
pinfo = self._store[pname]
ptype = pinfo.type
# pstr is used for informational and error messages only
#
is_redirect = str(val).startswith(")")
if is_redirect:
pval = self._eval_redirect(val)
pstr = f"{val} -> {pval}"
else:
pval = val
pstr = str(val)
isiterable = is_an_iterable(pval)
if isiterable and ptype in "bir":
raise ValueError(f"The {self._toolname}.{pname} value can not be set to an array (sent {pstr})")
v5(f"Validating {self._toolname}.{pname} val={pstr} as ...")
if ptype == "b":
v5("... a boolean")
try:
porig = pval
pval = pval.lower()
if pval in ["no", "false", "off", "0"]:
pval = False
elif pval in ["yes", "true", "on", "1"]:
pval = True
else:
raise ValueError(f"The {self._toolname}.{pname} value should be a boolean, not '{porig}'")