ctools  2.0.0
 All Classes Namespaces Files Functions Variables Macros Pages
ioutils.py
Go to the documentation of this file.
1 # ==========================================================================
2 # Utility functions for input and output
3 #
4 # Copyright (C) 2016-2017 Juergen Knoedlseder
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 #
19 # ==========================================================================
20 import csv
21 import sys
22 import gammalib
23 
24 
25 # ========================= #
26 # Write one row of CSV file #
27 # ========================= #
28 def write_csv_row(outfile, row, colnames, colvalues):
29  """
30  Write one row into CSV file
31 
32  Parameters
33  ----------
34  outfile : str
35  Output file name
36  row : int
37  Row number
38  colnames : list of str
39  Column names
40  colvalues : list of float
41  Column values
42  """
43  # If this is the first row then open a new file and write the header
44  if row == 0:
45  f = open(outfile, 'w')
46  writer = csv.DictWriter(f, colnames)
47  headers = {}
48  for colname in colnames:
49  headers[colname] = colname
50  writer.writerow(headers)
51 
52  # ... otherwise append to an existing file
53  else:
54  f = open(outfile, 'a')
55 
56  # Write out row
57  writer = csv.DictWriter(f, colnames)
58  writer.writerow(colvalues)
59 
60  # Close file
61  f.close()
62 
63  # Return
64  return
65 
66 
67 # ================ #
68 # Read pull values #
69 # ================ #
70 def read_pull_values(filename, parname):
71  """
72  Read pull values from pull distribution ASCII file
73 
74  Parameters
75  ----------
76  filename : str
77  Pull distribution ASCII file
78  parname : str
79  Parameter
80 
81  Returns
82  -------
83  values : list of float
84  List of pull values
85 
86  Raises
87  ------
88  NameError
89  """
90  # Initialise list of values
91  values = []
92 
93  # Open reader
94  reader = csv.reader(open(filename, 'r'), delimiter=',')
95 
96  # Read rows
97  first = True
98  index = -1
99  for row in reader:
100 
101  # Get column index if first row
102  if first:
103  try:
104  index = row.index(parname)
105  except:
106  print('ERROR: Parameter "'+parname+'" not found in list:')
107  for p in row:
108  print(' "'+p+'"')
109  raise NameError(parname)
110 
111  # Handle data rows
112  else:
113  values.append(float(row[index]))
114 
115  # Flag that first row has been passed
116  first = False
117 
118  # Return values
119  return values
120 
121 
122 # ============================================ #
123 # Get arguments and options from argument list #
124 # ============================================ #
125 def get_args_options(options, usage):
126  """
127  Get arguments and options from argument list
128 
129  Parameters
130  ----------
131  options : list of dict
132  List of possible options and default values
133  usage : str
134  Usage string to be shown in case of a problem
135 
136  Returns
137  -------
138  args, options : tuple of list and list of dict
139  Arguments and updated list of options
140  """
141  # Initialise list of arguments
142  args = []
143 
144  # If there are no command line arguments then show usage string and
145  # exit
146  if len(sys.argv) < 1:
147  print('Usage: %s' % usage)
148  sys.exit()
149 
150  # First possible option is element 1
151  i = 1
152 
153  # Loop over all arguments
154  while i < len(sys.argv):
155 
156  # Initialise that no option was found
157  option_found = False
158 
159  # Search for options
160  for option in options:
161 
162  # Do we have an option
163  if sys.argv[i] == option['option']:
164 
165  # If an option has been found then check if there is a
166  # following parameter and extract that parameter as a
167  # string. Quit in case that an exception occurs.
168  if len(sys.argv) > i+1:
169  i += 1
170  try:
171  option['value'] = str(sys.argv[i])
172  except:
173  print('Usage: %s' % usage)
174  sys.exit()
175 
176  # ... there is no following parameter, hence write out usage
177  # and quite
178  else:
179  print('Usage: %s' % usage)
180  sys.exit()
181 
182  # We can break now as every option should only occur once
183  option_found = True
184  break
185 
186  # If no option was found then add the argument to list of arguments
187  if not option_found:
188  args.append(sys.argv[i])
189 
190  # Next item
191  i += 1
192 
193  # Return arguments and options
194  return args, options
195 
196 
197 # =========================================== #
198 # Append model parameter column to FITS table #
199 # =========================================== #
200 def append_result_column(table, results, name, unit, key):
201  """
202  Append result column to FITS table
203 
204  Parameters
205  ----------
206  table : `~gammalib.GFitsTable`
207  FITS table
208  results : list of dict
209  Parameter values
210  name : str
211  Column name
212  unit : str
213  Column unit
214  key : str
215  Result key
216  """
217  # Determine number of rows in FITS table
218  nrows = len(results)
219 
220  # Allocate double precision column and set units
221  col = gammalib.GFitsTableDoubleCol(name, nrows)
222  col.unit(unit)
223 
224  # Fill results in columns
225  for i, result in enumerate(results):
226  col[i] = result[key]
227 
228  # Append column to table
229  table.append(col)
230 
231  # Return
232  return
233 
234 
235 # =========================================== #
236 # Append model parameter column to FITS table #
237 # =========================================== #
238 def append_model_par_column(table, model, results):
239  """
240  Append model parameter column to FITS table
241 
242  Parameters
243  ----------
244  table : `~gammalib.GFitsTable`
245  FITS table
246  model : `~gammalib.GModel`
247  Model
248  results : list of dict
249  Parameter values
250  """
251  # Determine number of rows in FITS table
252  nrows = len(results)
253 
254  # Loop over all parameters in model
255  for par in model:
256 
257  # Append parameter column only if model parameter is free
258  if par.is_free():
259 
260  # Set column names
261  name = par.name()
262  e_name = 'e_'+par.name()
263 
264  # Allocate double precision columns and set units
265  col = gammalib.GFitsTableDoubleCol(name, nrows)
266  e_col = gammalib.GFitsTableDoubleCol(e_name, nrows)
267  col.unit(par.unit())
268  e_col.unit(par.unit())
269 
270  # Fill results in columns
271  for i, result in enumerate(results):
272  col[i] = result['values'][name]
273  e_col[i] = result['values'][e_name]
274 
275  # Append columns to table
276  table.append(col)
277  table.append(e_col)
278 
279  # Return
280  return
def read_pull_values
Definition: ioutils.py:70
def append_result_column
Definition: ioutils.py:200
def write_csv_row
Definition: ioutils.py:28
def append_model_par_column
Definition: ioutils.py:238
def get_args_options
Definition: ioutils.py:125