ioutils.py
7.21 KB
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
# ==========================================================================
# Utility functions for input and output
#
# Copyright (C) 2016-2017 Juergen Knoedlseder
#
# 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, see <http://www.gnu.org/licenses/>.
#
# ==========================================================================
import csv
import sys
import gammalib
#import ctools
# ========================= #
# Write one row of CSV file #
# ========================= #
def write_csv_row(outfile, row, colnames, colvalues):
"""
Write one row into CSV file
Parameters
----------
outfile : str
Output file name
row : int
Row number
colnames : list of str
Column names
colvalues : list of float
Column values
"""
# If this is the first row then open a new file and write the header
if row == 0:
f = open(outfile, 'w')
writer = csv.DictWriter(f, colnames)
headers = {}
for colname in colnames:
headers[colname] = colname
writer.writerow(headers)
# ... otherwise append to an existing file
else:
f = open(outfile, 'a')
# Write out row
writer = csv.DictWriter(f, colnames)
writer.writerow(colvalues)
# Close file
f.close()
# Return
return
# ================ #
# Read pull values #
# ================ #
def read_pull_values(filename, parname):
"""
Read pull values from pull distribution ASCII file
Parameters
----------
filename : str
Pull distribution ASCII file
parname : str
Parameter
Returns
-------
values : list of float
List of pull values
Raises
------
NameError
"""
# Initialise list of values
values = []
# Open reader
reader = csv.reader(open(filename, 'r'), delimiter=',')
# Read rows
first = True
index = -1
for row in reader:
# Get column index if first row
if first:
try:
index = row.index(parname)
except:
print('ERROR: Parameter "'+parname+'" not found in list:')
for p in row:
print(' "'+p+'"')
raise NameError(parname)
# Handle data rows
else:
values.append(float(row[index]))
# Flag that first row has been passed
first = False
# Return values
return values
# ============================================ #
# Get arguments and options from argument list #
# ============================================ #
def get_args_options(options, usage):
"""
Get arguments and options from argument list
Parameters
----------
options : list of dict
List of possible options and default values
usage : str
Usage string to be shown in case of a problem
Returns
-------
args, options : tuple of list and list of dict
Arguments and updated list of options
"""
# Initialise list of arguments
args = []
# If there are no command line arguments then show usage string and
# exit
if len(sys.argv) < 1:
print('Usage: %s' % usage)
sys.exit()
# First possible option is element 1
i = 1
# Loop over all arguments
while i < len(sys.argv):
# Initialise that no option was found
option_found = False
# Search for options
for option in options:
# Do we have an option
if sys.argv[i] == option['option']:
# If an option has been found then check if there is a
# following parameter and extract that parameter as a
# string. Quit in case that an exception occurs.
if len(sys.argv) > i+1:
i += 1
try:
option['value'] = str(sys.argv[i])
except:
print('Usage: %s' % usage)
sys.exit()
# ... there is no following parameter, hence write out usage
# and quite
else:
print('Usage: %s' % usage)
sys.exit()
# We can break now as every option should only occur once
option_found = True
break
# If no option was found then add the argument to list of arguments
if not option_found:
args.append(sys.argv[i])
# Next item
i += 1
# Return arguments and options
return args, options
# =========================================== #
# Append model parameter column to FITS table #
# =========================================== #
def append_result_column(table, results, name, unit, key):
"""
Append result column to FITS table
Parameters
----------
table : `~gammalib.GFitsTable`
FITS table
results : list of dict
Parameter values
name : str
Column name
unit : str
Column unit
key : str
Result key
"""
# Determine number of rows in FITS table
nrows = len(results)
# Allocate double precision column and set units
col = gammalib.GFitsTableDoubleCol(name, nrows)
col.unit(unit)
# Fill results in columns
for i, result in enumerate(results):
col[i] = result[key]
# Append column to table
table.append(col)
# Return
return
# =========================================== #
# Append model parameter column to FITS table #
# =========================================== #
def append_model_par_column(table, model, results):
"""
Append model parameter column to FITS table
Parameters
----------
table : `~gammalib.GFitsTable`
FITS table
model : `~gammalib.GModel`
Model
results : list of dict
Parameter values
"""
# Determine number of rows in FITS table
nrows = len(results)
# Loop over all parameters in model
for par in model:
# Append parameter column only if model parameter is free
if par.is_free():
# Set column names
name = par.name()
e_name = 'e_'+par.name()
# Allocate double precision columns and set units
col = gammalib.GFitsTableDoubleCol(name, nrows)
e_col = gammalib.GFitsTableDoubleCol(e_name, nrows)
col.unit(par.unit())
e_col.unit(par.unit())
# Fill results in columns
for i, result in enumerate(results):
col[i] = result['values'][name]
e_col[i] = result['values'][e_name]
# Append columns to table
table.append(col)
table.append(e_col)
# Return
return