ModelManager

class xspec.ModelManager

Models container.

PyXspec automatically creates a single object of this class, named AllModels.

Methods

  • __call__ (the ‘()’ operator)
  • __iadd__ (the ‘+=’ operator)
  • __isub__ (the ‘-=’ operator)
  • addPyMod
  • calcFlux
  • calcLumin
  • clear
  • eqwidth
  • initpackage
  • lmod
  • setEnergies
  • setPars
  • show
  • simpars
  • tclLoad

Attributes

  • sources (get-only)
  • systematic
__call__(groupNum, modName='')

Get Model objects from the AllModels container.

Args:

groupNum: The data group number to which the Model object corresponds.

modName: Optional string containing the Model’s name (if any).

Returns the Model object.

__iadd__(modelInfo)

Define a new model and add it to the AllModels container.

This operation is equivalent to the Model class constructor, except that it does not return a Model object.

Args:
modelInfo:

A string containing the model expression (component names may be abbreviated). The model will be unnamed and assigned to source number = 1.

OR

If supplying a model name and a source number, this should be a tuple with:

modelInfo[0] = model expression string

modelInfo[1] = model name string

modelInfo[2] = source number

__isub__(modName)

Remove all copies of the given model from the AllModels container.

Args:
modName:
The name of the model to be removed, or an empty string if the model has no name. If set to “*”, this will behave like the clear() function and remove all models.
addPyMod(func, parInfo, compType, calcsErrors=False, spectrumDependent=False)

Add a user-defined Python model function to XSPEC’s models library.

This provides a way to add to XSPEC local models written in Python. It performs the same role as the combination of initpackage/lmod commands do for C/C++/Fortran local models. The first 3 arguments (func, parInfo, and compType) are mandatory.

Args:

func: The user-defined model function (Python type = ‘function’).

Function must define at least 3 arguments for energies, parameters, and flux.

A optional fourth argument may be added if your model calculates flux errors, and a fifth if your model requires that XSPEC pass it the spectrum number.

parInfo: A tuple of strings.

One string for each parameter your model requires. The format of these strings is identicalto what is placed in a ‘model.dat’ file (see Appendix C of the XSPEC manual).

compType: A string telling XSPEC the type of your model.

Currently allowed types: ‘add’, ‘mul’, ‘con’

calcsErrors: OPTIONAL bool flag.

If your model function also calculates model errors, set this to True.

spectrumDependent: OPTIONAL bool flag.

Set this to True only if your model function has an explicit dependence on the spectrum.
Example usage: A local additive model written in Python, named ‘myModel’,

which takes parameters named ‘par1’ and ‘par2’.

def myModel(engs, pars, flux):
   #    [... your model code, fill in
   #      flux array based on input
   #      engs and pars arrays ...]

myModelParInfo=("par1  "" 2.0  -10.0  -9.0  9.0  10.0  0.01",
                "par2  keV  1e-3 1e-5  1e-5  100. 200. .01" )

AllModels.addPyMod(myModel, myModelParInfo, 'add')
calcFlux(cmdStr)

Calculate the model flux for a given energy range.

Args:

cmdStr: string

Should contain the energy limit values and optional error specifiers. This follows the same syntax rules as the standard XSPEC ‘flux’ command.

The flux will be calculated for all loaded spectra, and the results will be stored in the Spectrum objects’ flux attribute. If no spectra are loaded, the flux will be stored in the Model objects’ flux attribute.

calcLumin(cmdStr)

Calculate the model luminosity for a given energy range and redshift.

Args:

cmdStr: string

Should contain the energy limit values and optional error specifiers. This follows the same syntax rules as the standard XSPEC ‘lumin’ command.

The lumin will be calculated for all loaded spectra, and the results will be stored in the Spectrum objects’ lumin attribute. If no spectra are loaded, the flux will be stored in the Model objects’ lumin attribute.

clear()

Remove all models.

eqwidth(component, rangeFrac=None, err=False, number=None, level=None)

Calculate the equivalent width of a model component.

Please see the Standard XSPEC Manual for a discussion on how the eqwidth of a component is calculated.

Args:
component:
An integer specifying the model component number for which to calculate the eqwidth (left-most component is 1). If the component belongs to a NAMED model, then this must be a string of the form “<modelName>:<compNumber>”.

rangeFrac: Determines the energy range for the continuum calculation.

Range will be from E(1-<rangeFrac>) to E(1+<rangeFrac>) where E is the location of the peak of the photon spectrum. The initial default rangeFrac is 0.05. Setting this will change the future default value.

err: Bool flag.

If set to True, errors will be estimated on the equivalent width calculation. This will also require the setting of the “number” and “level” arguments.

number: Only set this if err = True.

This determines the number of sets of randomized parameter values to draw to make the error estimation. [int]

level: Only set this if err = True.

The error algorithm will order the equivalent widths of the number sets of parameter values, and the central level percent will determine the error range. [float]

The results of the most recent eqwidth calculation are stored as attributes of the currently loaded Spectrum objects.

initpackage(packageName, modDescrFile, dirPath=None, udmget=False)

Initialize a package of local models.

Use this method to compile your local model source code and build a library, which can then be loaded into XSPEC with the lmod method.

Args:

packageName: The name of the model package [string].

The name should be all lower-case and contain NO numerals or spaces. The local models library file will be based upon this name, and this is also the name you will use when loading the library with the lmod method.

modDescrFile: Name of your local model description file [string].

This file is typically named ‘lmodel.dat’, but you’re free to name it something else.

dirPath: Optional directory path to your local models [string].

This may be an absolute or relative path. If you don’t enter this argument, XSPEC will look in the directory given by the LOCAL_MODEL_DIRECTORY in your Xspec.init start-up file.

udmget: Optional bool flag.

Set this True only when your models need to call XSPEC’s udmget function. Udmget is a function for allocating dynamic memory in Fortran routines, and is no longer used within XSPEC itself. If this flag is set to ‘True’, initpackage will copy the necessary files and build the udmget function within your local models directory.
lmod(packageName, dirPath=None)

Load a local models library.

Args:

packageName: The name of the model package to be loaded.

This is the same name that is the first argument in the initpackage command.

dirPath: An optional string argument.

This should specify the (absolute or relative) path to the local model directory. If this argument is not entered, XSPEC will look in the directory given by the LOCAL_MODEL_DIRECTORY in the Xspec.init start-up file.
setEnergies(arg1, arg2=None)

Specify new energy binning for model fluxes.

Supply an energy binning array to be used in model evalutations in place of the associated response energies, or add an extension to the response energies.

Args:

arg1: A string containing either:

“<range specifier> [<additional range specifiers>...]”

“<name of input ascii file>”

“extend” [This option also uses arg2]

“reset”

where the first <range specifier> ::= <lowE> <highE> <nBins> log|lin

<additional range specifier> ::= <highE> <nBins> log|lin

This uses the same syntax as standard XSPEC’s ‘energies’ command. Values can be delimited by spaces or commas.

arg2: String only needed when arg1 is “extend”.

This requires an extension specifier string of the form: “low|high <energy> <nBins> log|lin”

All energies are in keV. Multiple ranges may be specified to allow for varied binning in different segments of the array, but note that no gaps are allowed in the overall array. Therefore only the first range specifier accepts a <lowE> parameter. Additional ranges will automatically begin at the <highE> value of the previous range.

With the “extend” option, the specifier string supplied to arg2 will extend the existing response energy array by an additional <nBins> to the new <energy>, in either the high or low direction.

Once an energy array is specified, it will apply to all models and will be used in place of any response energy array (from actual or dummy responses) for calculating and binning the model flux. It will also apply to any models that are created after it is specified. To turn off this behavior and return all models back to using their response energies, set arg1 to “reset”.

arg1 can also be the name of an ascii text file containing a custom energy array. To see the proper file format, and for more details in general about the ‘energies’ command, please see the standard XSPEC manual.

Examples:

# Create an array of 1000 logarithmic-spaced bins, from .1 to 50. keV
AllModels.setEnergies(".1 50. 1000 log")
# Change it to 500 bins
AllModels.setEnergies(",,500")
# Now restore original response energies, but with an extension of the
#   high end to 75.0 keV with 100 additional linear bins.
AllModels.setEnergies("extend","high,75.,100 lin")
# Return to using original response energies with no extensions.
AllModels.setEnergies("reset")
setPars(*args)
Change the value of multiple parameters from multiple
model objects with a single function call.

This is a quick way to change multiple parameter values at a time since only a SINGLE recalculation will be performed at the end. In contrast, when parameter values are changed through the individual parameter objects, the model is recalculated after EACH parameter change. (If all the parameters belong to a single model object, you can also use the Model.setPars() function.)

args: An arbitrary number model objects and parameter values.

The first argument must be model object, followed by one or more of its new parameter values. Additional groups of model objects and parameter values may follow.

The parameter values follow the same syntax rules as with the single Model.setPars() function. They can be listed singly (as floats or strings), or collected into tuple, list, or dictionary containers. Dictionaries must be used when parameters are not in consecutive order, in which case the parameter index number is the dictionary key.

Parameter indices are local to each model object. That is, they are always numbered from 1 to N where N is the number of parameters in the model object.

Examples:

# Assume we've already assigned a 3 parameter model to 2 data groups:
m1 = AllModels(1)
m2 = AllModels(2)
        
# Various ways of changing parameters in consecutive order.

# This changes pars 1-2 in m1 and 1-3 in m2:
AllModels.setPars(m1, .4, "1.3 -.01", m2, "5.3 ,,3.0e-4", 2.2, 1.9)
#   ...and these 2 examples do the exact same thing as above:
valList = [.4, "1.3 -.01"]
valTuple = ("5.3 ,,3.0e-4", 2.2, 1.9)
AllModels.setPars(m1, valList, m2, valTuple)
AllModels.setPars(m1, valList, m2,"5.3 ,,3.0e-4", [2.2, 1.9])

# Parameters in non-consecutive order, must use Python
#   dictionaries:

# Change parameter 2 in m1, parameter 1 and 3 in m2:
AllModels.setPars(m1, {2:8.3}, m2, {1:0.99, 3:"7.15 -.01"})
# ...same thing as above:
AllModels.setPars(m1, {2:8.3}, m2, 0.99, {3:"7.15 -.01"})

# Note that identical syntax is used for model objects belonging
# to different sources.  All of the above examples are still valid
# had we obtained m1 and m2 like this:
  
m1 = Model("wabs*pow", "firstMod", 1)
m2 = Model("gauss", "secondMod", 2)
show(parIDs=None)

Show all or a subset of Xspec model parameters.

Args:
parIDs:
An optional string specifying a range of parameters as with Xspec’s “show parameter” function. If no string is supplied, this will show all parameters in all models.
simpars()

Create a list of simulated parameter values.

Values are drawn from a multivariate normal distribution based on the covariance matrix from the last fit, or from Monte Carlo Markov chains if they are loaded. This method is identical to doing ‘tclout simpars’ in standard XSPEC.

Returns a tuple of the simulated parameter values.

tclLoad(fullLibPath)

Load a local model library by calling Tcl’s ‘load’ command.

This by-passes lmod (with its pkgIndex.tcl requirements) and allows the user to load a local model by directly calling Tcl’s lower level ‘load’ command. May also be useful for error diagnostics when lmod has failed.

Args:
fullLibPath: The full local model library path and filename.
sources

A dictionary containing the currently active <source number>:<model name> assignments.

If the model has no name, <model name> will be an empty string. (GET only)

systematic

The fractional model systematic error.

This will be added in quadrature to the error on the data when evaluating chi-squared. The default value is zero.