class xspec.ModelManager

Models container.

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


  • __call__ (the '()' operator)

  • __iadd__ (the '+=' operator)

  • __isub__ (the '-=' operator)

  • addPyMod

  • calcFlux

  • calcLumin

  • clear

  • eqwidth

  • initpackage

  • lmod

  • mdefine

  • setActive

  • setEnergies

  • setInactive

  • setPars

  • show

  • simpars

  • systematicSingleModel

  • setSystematicSingleModel

  • tclLoad


  • sources (get-only)

  • systematic

__call__(groupNum, modName='')

Get Model objects from the AllModels container.


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.


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.


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


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


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


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.


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')

Calculate the model flux for a given energy range.


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.


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


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.


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.


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.

identify(energy=None, delta=None, redshift=None, lineList=None, tplasma=None, emiss=None)

Identify spectral lines.

List possible lines in the specified energy range.

This function also returns the list of lines as a string.

Args (all are optional):

energy: The center of the energy range (energy +/- delta) to search.

This should be entered in keV unless working with plot x-axis settings in wavelength mode, in which case enter as wavelengths in Angstroms. [float]

delta: Specifies the spread of energies (energy +/- delta). [float]

redshift: [float]

lineList: The list of lines to be searched [string].

Options are 'bearden', 'mekal', and 'apec'.

tplasma: For 'apec' list only, temperature of the plasma in keV.


emiss: For 'apec' list only, minimum emissivity of lines to be

shown. [float]


# All values are optional, use keywords to enter values
# non-consecutively.  Unspecified values revert to the
# current defaults.

# Search the 'mekal' list between .4 and .6 keV
AllModels.identify(.5, .1, lineList='mekal')

# Search the 'apec' list with additional temperature and 
# minimum emissivity values, and save the results in string 's'.
s = AllModels.identify(1.0, .1, .0, 'apec', 5.0, 1.0e-18)

Initial defaults: energy = 1.0, delta = .01, redshift = 0.0, lineList = 'apec', tplasma = 1.0, emiss = 1.0e-19. These defaults will be modified by each new entry.

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.


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.


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.


Define a simple model using an arithmetic expression.


commandStr: The full mdefine expression string.

If this is blank or None, PyXspec will simply display the list of currently defined mdefine components.

Otherwise this should be a string of the form: <name> [<expression>[: [<type>] [<emin> <emax>]]] where:

<name> = the name of the model component

<expression> = a string of arithmetic expressions

defining the model.

<type> = type of the component (ie. add, mul, con)

<emin> <emax> = optional min and max energy values

for the model.

If the string is just "<name>", it will display information of the previously defined component with name = <name> (if any).

Doing "<name> :" will delete a previously defined component with name = <name>.

See the 'mdefine' command in the standard XSPEC manual for more information.


AllModels.mdefine('dplaw e**p1 + f*E**p2')
AllModels.mdefine('test1 exp(-a*e) : mul')
AllModels.mdefine('test2 a*e**2 ')
# Show all currently loaded mdefine components
# Delete component named 'test2'
AllModels.mdefine('test2 :')                          

Sets the model specified with modl_nm to active.


modl_nm: The name of the model to be activated.

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.


arg1: A string containing either:

"<range specifier> [<additional range specifiers>...]"

"<name of input ascii file>"

"extend" [This option also uses arg2]


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.


# Create an array of 1000 logarithmic-spaced bins, from .1 to 50. keV
AllModels.setEnergies(".1 50. 1000 log")
# Change it to 500 bins
# 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.

Sets the model specified by modl_nm to inactive.


modl_nm: The name of the model to be set to inactivate.

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.


# 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("phabs*pow", "firstMod", 1)
m2 = Model("gauss", "secondMod", 2)
setSystematicSingleModel(modelName, value)

Set a fractional systematic error for a specific model.

The AllModels.systematic attribute is for setting the default systematic error which applies to all models. Use this method to set a value that only applies to a specific model, overriding the default value. If the model is un-named, enter 'unnamed' for the modelName argument.


Show all or a subset of Xspec model parameters.


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.


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.


Get the systematic error setting for a specific model.

This will be the same as the default value stored in the AllModels.systematic attribute unless this model was given its own value with the setSystematicSingleModel method. To get the value of an un-named model, enter 'unnamed'.


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.


fullLibPath: The full local model library path and filename.

property 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)

property systematic

The fractional model systematic error.

This will be added in quadrature to the error on the data when evaluating chi-squared. This sets the default value that will be applied to all models. To override this setting for a specific model, use the setSystematicSingleModel method.