ctools  2.0.0
 All Classes Namespaces Files Functions Variables Macros Pages
csmodelsois.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 # ==========================================================================
3 # Puts subset of sources in diffuse model cube
4 #
5 # Copyright (C) 2017-2022 Josh Cardenzana
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #
20 # ==========================================================================
21 import sys
22 import gammalib
23 import ctools
24 
25 
26 # ================= #
27 # csmodelsois class #
28 # ================= #
29 class csmodelsois(ctools.cscript):
30  """
31  Puts subset of sources in diffuse model cube
32 
33  The csmodelsois class puts a subset of sources in a model definition
34  XML file into a model cube and generates a new model definition XML file
35  in which the subset of sources is replaced by a model of type
36  DiffuseMapCube.
37  """
38 
39  # Constructor
40  def __init__(self, *argv):
41  """
42  Constructor
43 
44  Parameters
45  ----------
46  argv : list of parameters
47 
48  Raises
49  ------
50  TypeError
51  An invalid number of command line arguments was provided.
52  """
53  # Initialise application by calling the base class constructor
54  self._init_cscript(self.__class__.__name__, ctools.__version__, argv)
55 
56  # Initialize parameters
57  self._cubegen = ctools.ctmapcube()
58  self._models = gammalib.GModels()
59  self._cubemodels = gammalib.GModels()
60 
61  # Return
62  return
63 
64 
65  # Private methods
66  def _get_parameters(self):
67  """
68  Get parameters from parfile
69  """
70  # Query input parameters
71  self['inmodel'].filename()
72  self['soilist'].string()
73 
74  # Read input parameters
75  ptsrcsig = self['ptsrcsig'].real()
76 
77  # Get the cube centre coordinates
78  self._cubegen['coordsys'].string(self['coordsys'].string())
79  if self['coordsys'].string() == 'CEL':
80  self._cubegen['xref'].real(self['ra'].real())
81  self._cubegen['yref'].real(self['dec'].real())
82  else:
83  self._cubegen['xref'].real(self['glon'].real())
84  self._cubegen['yref'].real(self['glat'].real())
85 
86  # Get spatial binning parameters
87  self._cubegen['binsz'].real(self['binsz'].real())
88  self._cubegen['nxpix'].integer(self['nxpix'].integer())
89  self._cubegen['nypix'].integer(self['nypix'].integer())
90  self._cubegen['proj'].string(self['proj'].string())
91 
92  # Get the energy binning parameters
93  self._cubegen['ebinalg'].string(self['ebinalg'].string())
94  if self['ebinalg'].string() == 'FILE':
95  self._cubegen['ebinfile'].filename(self['ebinfile'].filename())
96  else:
97  self._cubegen['emin'].real(self['emin'].real())
98  self._cubegen['emax'].real(self['emax'].real())
99  self._cubegen['enumbins'].integer(self['enumbins'].integer())
100 
101  # Set point source significance
102  self._cubegen['ptsrcsig'].real(ptsrcsig)
103 
104  # Read optionally output cube filenames
105  if self._read_ahead():
106  self._cubegen['outcube'].filename(self['outcube'].filename())
107  self['outmodel'].query()
108 
109  # Write parameters into logger
110  self._log_parameters(gammalib.TERSE)
111 
112  return
113 
114  def _gen_cubemodel(self):
115  """
116  Generates a binned model from the model file using ctmapcube
117  """
118  # Get a list of sources we DONT want to put into the cube
119  sources = self['soilist'].string().split(',')
120 
121  # Load the model into a model container
122  if (self._models.size() == 0):
123  self._models = gammalib.GModels(self['inmodel'].filename())
124 
125  # Store a copy of the models
126  self._cubemodels = self._models.copy()
127 
128  # Loop through models and pull out all models not in the list
129  for model in self._models:
130 
131  # If model is not a sky model then continue
132  if model.classname() != 'GModelSky':
133  self._cubemodels.remove(model.name())
134 
135  # ... otherwise, if model is in list of sources the remove it
136  # from the container
137  elif model.name() in sources:
138  self._cubemodels.remove(model.name())
139 
140  # Log the number of models to be put into the cube
141  self._log_value(self['chatter'].integer(), 'Numner of cube models',
142  self._cubemodels.size())
143 
144  # Return
145  return
146 
147 
148  # Public methods
149  def process(self):
150  """
151  Implements the actual bulk of the script's tasks
152  """
153  # Get parameters
154  self._get_parameters()
155 
156  # Set the models to put into the cube
157  self._gen_cubemodel()
158 
159  # Only run if there still models to be filled into the cube
160  if not self._cubemodels.is_empty():
161 
162  # Log action
163  self._log_string(gammalib.NORMAL, 'Generating model cube')
164 
165  # Fill the cube models into the ctmapcube object
166  self._cubegen.models(self._cubemodels)
167 
168  # Run the map generating method
169  self._cubegen.run()
170 
171  else:
172  self._log_string(gammalib.NORMAL,
173  'List of models is empty, nothing will be done')
174 
175  # Return
176  return
177 
178  def save(self):
179  """
180  Save the cube and optionally the updated XML model file
181  """
182  # Save the generated cube if the cube and filename are not empty
183  if ((not self._cubegen.mapcube().cube().is_empty()) and
184  self['outcube'].is_valid()):
185 
186  # Save cube
187  self._cubegen.mapcube().save(self['outcube'].filename(),
188  self['clobber'].boolean())
189 
190  # Stamp cube
191  self._stamp(self['outcube'].filename())
192 
193  # If requested, save the updated list of models
194  if self['outmodel'].is_valid():
195 
196  # Generate a list of models that will be output to file
197  outmodels = gammalib.GModels(self._models)
198 
199  # Remove all models used in the generated cube
200  for model in self._cubemodels:
201  outmodels.remove(model.name())
202 
203  # Generate the actual cube model
204  spat = gammalib.GModelSpatialDiffuseCube(self['outcube'].filename())
205  spec = gammalib.GModelSpectralConst()
206  newmodel = gammalib.GModelSky(spat, spec)
207 
208  # Give the model a default name
209  newmodel.name(self.cubemodelname())
210 
211  # Now append the model to the list of output models
212  outmodels.append(newmodel)
213 
214  # Save the model list
215  outmodels.save(self['outmodel'].filename())
216 
217  # Return
218  return
219 
220  def mapcube(self):
221  """
222  Return the mapcube generated by the underlying 'ctmapcube' object
223  """
224  # Return
225  return self._cubegen.mapcube()
226 
227  def cubemodelname(self):
228  """
229  Return the name to be given to the cube model in the output XML file
230  """
231  # Return
232  return 'FixedSourcesCube'
233 
234  def models(self, models):
235  """
236  Set the models
237 
238  Parameters
239  -------
240  models : `~gammalib.GModels`
241  Model container
242  """
243  # Set models
244  self._models = models
245 
246  # Return
247  return
248 
249 
250 # ======================== #
251 # Main routine entry point #
252 # ======================== #
253 if __name__ == '__main__':
254 
255  # Create instance of application
256  app = csmodelsois(sys.argv)
257 
258  # Execute application
259  app.execute()