scieee AI-readable full text Open interactive document viewer

SPEX X-ray spectral fitting package

Kaastra, J. S.; Raassen, A. J. J.; de Plaa, J.; Gu, Liyi

Abstract

SPEX is a software package for fitting astrophysical X-ray spectra. It has been developed since the 1970s at SRON Netherlands Institute for Space Research. SPEX is an interactive command-line program for the computation of emergent spectra of optically thin plasmas such as stellar coronal loop structures, supernova remnants (also including transient ionization effects), photo-ionized plasmas, and optically thick plasmas. These model spectra can be fitted to measured X-ray spectra from various X-ray observatories, like XMM-Newton and Chandra. SPEX has been optimized for high-resolution X-ray spectroscopy, which makes it especially suitable for analyzing grating and micro-calorimeter spectra.

Full text

SPEX Help Center Documentation Release 3.08.02 J. de Plaa, J. Kaastra, L. Gu, the SPEX Development Team Oct 10, 2025 CONTENTS 1 Getting started 1 1.1 How to install SPEX ......................................... 1 1.2 How to run SPEX .......................................... 4 1.3 How to convert spectra to SPEX format ............................... 10 1.4 Install the SPEX Python interface .................................. 13 1.5 Dependencies ............................................. 15 1.6 Compile SPEX from source ..................................... 15 1.7 Use SPEX through Docker ...................................... 18 1.8 How to install SPEX using Anaconda ................................ 20 1.9 Optimize for speed .......................................... 22 2 Analysis threads 25 2.1 Fitting a CCD spectrum ....................................... 25 2.2 Modeling particle background .................................... 36 2.3 Fitting interstellar dust absorption .................................. 42 2.4 Import UV/Optical data ....................................... 47 2.5 PION setup for AGN warm absorber ................................. 48 2.6 PION setup for emission and absorption features in AGN ...................... 56 2.7 Fitting two different spectra simultaneously ............................. 68 2.8 How to use the SPEX user model .................................. 82 2.9 SPEX solution of the relativistic disk reflection ........................... 85 2.10 SPEX evaluation of APEC model .................................. 86 3 Command overview 89 3.1 Command syntax ........................................... 89 3.2 Plotting reference ...........................................156 4 Spectral models 171 4.1 Overview of spectral components ..................................171 4.2 Optimizing model performance ...................................240 5 Additional tools 245 5.1 Trafo .................................................245 5.2 Stepcontour ..............................................250 5.3 Xabsinput ...............................................251 5.4 Hydro driver .............................................252 5.5 Rgsvprof ...............................................253 5.6 RGS_fluxcombine ..........................................254 5.7 RGS_fmat ..............................................256 5.8 Uvtospex ...............................................257 5.9 Calling SPEX from Fortran .....................................257 5.10 Linid .................................................259 6 Python Interface 261 6.1 Basic commands ...........................................261 i 6.2 Analysis threads & other tricks ....................................299 6.3 Advanced class descriptions .....................................304 7 Help & troubleshooting 331 7.1 Commandline help ..........................................331 7.2 Solving SPEX problems .......................................332 7.3 Find known issues ..........................................334 7.4 Report issues .............................................334 8 SPEX Theory 335 8.1 SPEX Atomic Code & Tables ....................................335 8.2 SPEX 2 notation of atomic transitions ................................349 8.3 Modelling and fitting .........................................356 8.4 Optimal definition of respons matrices ...............................361 8.5 Definition of the micro-turbulent velocity in SPEX .........................366 9 Exercises 369 9.1 Powerlaw ...............................................369 9.2 Powerlaw with a Gaussian line ....................................370 9.3 Statistics, binning and more .....................................370 9.4 Stellar Spectra ............................................371 9.5 Supernova remnants .........................................372 9.6 Relativistic lines ...........................................372 9.7 AGN winds ..............................................373 10 Changelog 375 10.1 Version 3.01.00 ............................................376 10.2 Version 3.02.00 ............................................376 10.3 Version 3.03.00 ............................................376 10.4 Version 3.04.00 ............................................377 10.5 Version 3.05.00 ............................................377 10.6 Version 3.06.00 ............................................378 10.7 Version 3.06.01 ............................................379 10.8 Version 3.07.00 ............................................379 10.9 Version 3.07.01 ............................................380 10.10 Version 3.07.02 ............................................380 10.11 Version 3.07.03 ............................................381 10.12 Version 3.08.00 ............................................381 10.13 Version 3.08.01 ............................................382 10.14 Version 3.08.02 ............................................382 11 Credits 383 11.1 Software ...............................................383 11.2 Plasma model .............................................383 11.3 SPEX models .............................................384 11.4 Documentation ............................................384 Python Module Index 385 ii CHAPTER ONE GETTING STARTED 1.1 How to install SPEX 1.1.1 Download The current SPEX version 3.08.02 was released on 2025-10-10. SPEX install files can be downloaded from our Zenodo page. 1.1.2 Linux Unpack the tar file in the destination directory (for example /usr/local/): tar xvfz spex-3.08.02-Linux-Intel.tar.gz The tar file will create a directory called SPEX-3.08.02-Linux in which the program will be installed. Set the environment variable SPEX90 to the installation directory (for example /usr/local/SPEX-3.08.02-Linux): export SPEX90=/usr/local/SPEX-3.08.02-Linux (bash shell) setenv SPEX90 /usr/local/SPEX-3.08.02-Linux (C-type shell) Source the script provided by the distribution: source $SPEX90/spexdist.sh (bash shell) source $SPEX90/spexdist.csh (C-type shell) Remove the tar file: rm SPEX-3.08.02-Linux-Intel.tar.gz Note: In some cases the csh script fails because either PATH, LD_LIBRARY_PATH or PYTHONPATH are not defined. This can be temporarily fixed by defining an empty variable using setenv, for example: setenv PATH "" and run the script again. This will be fixed in the next SPEX release. 1 SPEX Help Center Documentation, Release 3.08.02 1.1.3 Mac OS We provide a SPEX binary version for Mac OS that has been built on Intel processors as an install package. Although this Intel build works mostly on Apple Silicon processors, we recommend to follow the How to install SPEX using Anaconda (page 20) instead on Apple Silicon machines as this is a native build on that platform. Note: This version of SPEX has been compiled using XQuartz 2.8.0, so please upgrade XQuartz to a version >=2.8.0. Administrator install (Intel) If you have administrator rights on your Mac, this option is the easiest one. Download the PKG file from Zenodo (SPEX-3.08.02-Apple-Intel.pkg or SPEX-3.08.02-Apple-Silicon.pkg for M1/M2/M3 processors), open it in Mac OS and follow the instructions on the screen. MacOS may complain about not being able to verify the developer of the software. Please close this dialog and go to the MacOS System Preferences >> Security & Privacy. In that dialog, you are offered to open the SPEX package anyway. Accept the offer and make sure the SPEX package is unblocked. Now, you can open the SPEX PKG installer again and proceed with the installation. Non-administrator install (Intel) Unpack the tar file in the destination directory (for example /usr/local/): tar xvfz spex-3.08.02-Apple-Intel.tar.gz The tar file will create a directory called SPEX-3.08.02-Darwin in which the program will be installed. Set the environment variable SPEX90 to the installation directory (for example /usr/local/SPEX-3.08.02-Darwin): export SPEX90=/usr/local/SPEX-3.08.02-Darwin (bash shell) setenv SPEX90 /usr/local/SPEX-3.08.02-Darwin (C-type shell) Source the script provided by the distribution: source $SPEX90/spexdist.sh (bash shell) source $SPEX90/spexdist.csh (C-type shell) Remove the tar file: rm SPEX-3.08.02-Apple-Intel.tar.gz Note: In some cases the csh script fails because either PATH, DYLD_LIBRARY_PATH or PYTHONPATH are not defined. This can be temporarily fixed by defining an empty variable using setenv, for example: setenv PATH "" and run the script again. This will be fixed in the next SPEX release. 2 Chapter 1. Getting started SPEX Help Center Documentation, Release 3.08.02 1.1.4 Windows 10/11 SPEX can be installed in Windows 11 using the linux subsystem in Windows (WSL2). SPEX can run in an Ubuntu Linux environment that can be installed through the Microsoft Store. How to install Ubuntu in Windows 11 Since November 2022, WSL2 should support graphics output from Ubuntu, so a separate X-server should no longer be necessary. Section 5 of the tutorial above shows some examples of running graphical programs. It should not be necessary to run all of those, but they can be helpful to test your installation. After installing the X11 apps using the command sudo apt install x11-apps, you should be able to continue with the SPEX installation below. Install SPEX in the Ubuntu environment The steps below describe how to install a SPEX version tailored to Ubuntu 22.04. If you are planning to use Anaconda in this Ubuntu WSL2 environment, then we would recommend to install SPEX through Anaconda directly. See How to install SPEX using Anaconda (page 20) for details. 1. On the Ubuntu terminal, first install the OpenBlas library: apt-get install libopenblas-base 2. Download spex-3.08.02-Ubuntu-WSL.tar.gz from Zenodo. Unpack the tar file in the destination directory (for example /usr/local/): tar xvfz spex-3.08.02-Ubuntu-WSL.tar.gz The tar file will create a directory called SPEX-3.08.02-Linux in which the program will be installed. 3. Set the environment variable SPEX90 to the installation directory (for example /usr/local/SPEX-3.08.02Linux): export SPEX90=/usr/local/SPEX-3.08.02-Linux (bash shell) setenv SPEX90 /usr/local/SPEX-3.08.02-Linux (C-type shell) 4. Source the script provided by the distribution: source $SPEX90/spexdist.sh (bash shell) source $SPEX90/spexdist.csh (C-type shell) 5. Remove the tar file: rm spex-3.08.02-Ubuntu-WSL.tar.gz 6. Set the DISPLAY variable in ~/.bashrc: echo "export DISPLAY=localhost:0.0" >> ~/.bashrc . ~/.bashrc 7. Run SPEX: spex If you get an error about a missing library when running SPEX, please run the following command: sudo apt-get install libopenblas-base libreadline8 libncurses5 x11-common libx11-6␣ ˓→gfortran The command above makes sure that all the packages that SPEX needs are installed. The latest Ubuntu build also contains the python interface. To use it, make sure to install: sudo apt-get install python3-numpy python3-matplotlib python3-future python3-astropy 1.1. How to install SPEX 3 SPEX Help Center Documentation, Release 3.08.02 1.2 How to run SPEX SPEX is a spectral fitting program used to fit high-resolution X-ray spectra. The code contains several simple and detailed models that are able to deal with the radiative processes observed in the X-ray band. Because SPEX has a command-line interface, a first-time user should get familiar with the syntax of the commands to be able to work with it. This chapter provides some basic commands and threads to fit X-ray spectra. 1.2.1 The SPEX data format The data files containing the spectrum of the source and the response need to be in the correct format. In the SPEX installation, we provide a program called Trafo (page 245) to convert OGIP standard fits files into SPEX format (see How to convert spectra to SPEX format (page 10) for an explanation of how to use trafo). In this chapter, we assume that you already have spectra in SPEX format. If not, you can find example files in the SPEX Exercises (page 369) section. Each exercise contains a .spo and .res file that can be downloaded. SPEX needs two files per spectrum: •<filename>.spo – This file contains the countrate per energy bin for the source (𝐷𝑖), as well as the background countrate and the errors (𝜎𝑖). •<filename>.res – This file contains the instrumental response: the energy redistribution and effective area (𝑅𝑖𝑗 𝐴𝑗). In order to calculate the observed model spectrum, SPEX uses this integral equation to account for the imperfections caused by the instrument: 𝐷(𝑐) = ∫︁𝑅(𝑐, 𝐸)𝐴(𝐸)𝑆(𝐸)𝑑𝐸 (1.1) 𝐷𝑖= 𝑛 ∑︁ 𝑗=1 𝑅𝑖𝑗𝐴𝑗𝑆𝑗 The .res and .spo files are so-called FITS files. This is a data format widely used in Astronomy. FITS files can contain images as well as data tables. The software package FTOOLS provided by NASA contains a large number of tools to manipulate FITS files. If you are interested, then you can launch flaunch to see which tools are available. For more information about the SPEX spectrum and response format see Optimal definition of respons matrices (page 361). 1.2.2 Loading spectra into SPEX The SPEX program is started by entering spex in a linux terminal window. In the following sections we describe one run of the program. To start SPEX do this: user@linux:~> spex Welcome user to SPEX version 3.00.00 SPEX> First, we have to load the data files. This is done using the data command (Data: read response file and spectrum (page 113)). It is a general thing in SPEX that filename extensions are not typed explicitly when issuing a command. If you have a file called filename.spo and filename.res then you type: SPEX> data filename filename The responsefile (.res) is entered first and then the file containing the spectrum (.spo). You can avoid confusion by giving the same filename to both .res and .spo files. Remember that the order of the words in the commands is very important! To save you from typing a lot, many commands can be abbreviated by typing just the first few characters. For example, da is equivalent to dat and data. 4 Chapter 1. Getting started SPEX Help Center Documentation, Release 3.08.02 1.2.3 Plotting the data If the data command was successful, we can now have a look at the spectra. SPEX offers a lot of different plot commands (see Plot: Plotting data and models (page 137)). Using default settings, the easiest way of plotting a spectrum is as follows: SPEX> plot dev xs SPEX> plot type data SPEX> plot The sequence above opens a PGPLOT window (plot dev xs) and tells SPEX that we want to plot the spectral data (plot type data). This will create a linear-linear plot in keV units. The plot can be tailored to your wishes. Below is an example to change the plot to a linear-linear plot in Å and add a title to the plot: SPEX> plot x lin SPEX> plot y lin SPEX> plot ux a SPEX> plot uy a SPEX> plot rx 8.:35. SPEX> plot ry 0.:0.05 SPEX> plot set 1 SPEX> plot cap ut text "This is my plot" SPEX> plot cap lt disp false SPEX> plot cap id disp false SPEX> plot To make sure the axes are linear, we give the commands (plot x lin and plot y lin) and change the axes to unit Å (plot ux a and plot uy a). The commands plot rx 8.:35. and plot ry 0.:0.05 change the ranges on the x and y axes, respectively. Then the color of the data, background spectrum and model are set. The last commands beginning with plot cap remove some standard titles and other text around the plot. After you define the plot like in the example above, you can plot it with a single plot command. The y-axis in this plot is in counts s−1−1. Ångstrom is not the only unit used in high-energy astrophysics. Usually, the energy of the photons is expressed in keV. In SPEX you can use keV by writing kinstead of ain all commands. For example, plot ux k to use keV for the x-axis. An overview of possible units is provided in Plot axis units and scales (page 162). 1.2.4 Ignoring and rebinning High-resolution X-ray spectra from Chandra and XMM-Newton are usually oversampled (e.g. the energy bins are much smaller than the spectral resolution) and contain a lot more channels then is useful. Therefore, it is necessary to remove wavelength intervals which contain bad data and rebin your spectrum. The SPEX command to ignore parts of the spectrum is called ignore (Ignore: ignoring part of the spectrum (page 125)) and the command to rebin is called bin (Bin: rebin the spectrum (page 110)). In the next example we bin the spectrum over the 8–35 Å range with a factor of 5 and ignore the rest of the spectrum: ign 0:8 unit a ign 35:100 unit a bin 8:35 5 unit a The words unit a tells SPEX that the ranges (for example 8.0:35.0) are given in Å. If you work with more than one spectrum (from more than one instrument), you can add an extra instrument statement: ign ins 1:2 0:8 unit a ign ins 1:2 35:100 unit a bin ins 1:2 8:35 5 unit a 1.2. How to run SPEX 5 SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) Backscal: 1.00000000E+00 No BACKFILE keyword found Corrscal: 1.00000000E+00 No CORRFILE keyword found No RESPFILE keyword found No ANCRFILE keyword found 1.3.5 Bad channels and grouping Depending on the instrument used, there is a chance that the spectrum contains bad channels. This is especially true for grating spectra. Sometimes the background spectrum can have a different number of bad channels than the source spectrum. It is therefore important that a particular bad channel in either of the two spectra is ignored. In this example, there are no bad channels, so either yes or no will do. Checking data quality and grouping ... Ogip files have quality flags. Quality 0 means okay Your spectrum file has 0 bins with bad quality Your background file has 0 bins with bad quality Your combined file has 0 bins with bad quality Shall we ignore bad channels? (y/n) [no]:y If grppha has been used on the spectrum, trafo will also ask whether the spectra should be binned according to the groups defined in the PHA file. Important note: We do not recommend the use of grppha for binning spectra. For spectra with Poisson statistics (most X-ray spectra), it is much better to use C-statistics and use an optimal binning algorithm in SPEX based on the spectral resolution of the instrument. 1.3.6 Read response and effective area files In the next step, the response matrix is read. Sometimes, the response matrices start at channel 0, which can be somewhat confusing. Especially when some arrays start at channel 0 and others at channel 1. If both data sets start at zero, it is best to shift the channel numbers with 1 unit. For most instruments this is fine, however, there are situations when this does not apply. In that case, please check your energy grid by loading a delta line component in SPEX and check the energy of the line manually. Then, compare the output with a delta line defined in XSPEC. Determining background subtracted spectra ... No response matrix file specified in pha-file. Enter filename response matrix to be read: PN.rmf Reading response matrix ... Warning, ebounds data started at channel 0 Warning, response data started at channel 0 Possible response conflict; check xspec/spex with delta line! Enter shift to response array (1 recommended, but some cases may be 0):1 No effective area file specified in pha-file. Sometimes, also an effective area file needs to be provided separately: Read nevertheless an effective area file? (y/n) [no]: y Enter filename arf-file to be read: PN.arf Reading effective area ... Determining zero response data ... Total number of channels with zero response: 373 Original number of data channels : 4096 Channels after passing mask and omitting zero response channels: 3723 (continues on next page) 12 Chapter 1. Getting started SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) Rebinning data where necessary ... Rebinning response where necessary ... old number of response elements: 435950 new number of response elements: 435950 old number of response groups : 1481 new number of response groups : 1481 Correcting for effective area ... Determine number of components ... Found 1 components Enter any shift in bins (0 recommended): 0 order will not be swapped ... If there are bins with zero response, then they are excluded from the resulting file. Also here a shift in bins can be set, but the recommended value is 0. 1.3.7 Writing res and spo files The final step is writing the spectra in SPEX format. The file names should be provided without an extension. The .spo and .res extension will be added automatically. Enter filename spectrum to be saved (without .spo): PN Enter filename response to be saved (without .res): PN Final number of response elements: 435950 The PN.spo and PN.res file have been saved in the current directory. 1.4 Install the SPEX Python interface The SPEX python interface depends on a quite specific python environment. Using conda, you can create this environment pretty quickly. Please make sure you have (mini)conda installed and initialized on your machine before you continue. 1.4.1 Binary installation The easiest option to install the Python interface for SPEX is by downloading the SPEX binary version for your platform. See and follow the instruction in How to install SPEX (page 1). Once the standard SPEX environment is set up using the spexdist.sh or spexdist.csh files, it is time to build the conda environment. This can be done using the spex.yml file provided in the SPEX directory. Please enter the following command: (base) unix:~/SPEX> conda env create -f $SPEX90/python/spex.yml This creates the spex-3.08 conda environment for you. This step should only be done once. Note: If you installed SPEX through the Mac package installer, then spex.yml is not located in a writeable directory. Please copy spex.yml first to your home directory (cp /opt/spex/python/spex.yml ~/) and then create the conda environment like: conda env create -f ~/spex.yml. If successful, you can from now on activate the environment with the command: (base) unix:~/SPEX> conda activate spex-3.08 1.4. Install the SPEX Python interface 13 SPEX Help Center Documentation, Release 3.08.02 And from now on, you can use the python interface in SPEX: (spex-3.08) unix:~/SPEX> python Python 3.11.6 |Anaconda, Inc. Type "help", "copyright", "credits" or "license" for more information. >>> from pyspex.spex import Session >>> s=Session() Welcome user to SPEX version 3.08.02 NEW in this version of SPEX: 07-10-2025 Added plot component functionality 07-10-2025 Added atbl model to load Xspec table models 07-10-2025 Added magnetism module for pion 07-10-2025 Added ebit model for laboratory astrophysics 07-10-2025 Improvement of partial covering factor 07-10-2025 Update of quick calculation mode Setting the number of threads to 4 for optimal performance. Currently using SPEXACT version 2.07.00. Type `help var calc`for details. >>> If you need other python packages for your project, you can install them through conda in your new spex-3.08 environment. 1.4.2 Compile Python interface for SPEX If you do not want to use conda, you can also compile the Python interfaces for SPEX. This can be done either through a compile script called compile.py or manually with CMake by adding the option -DPYTHON=3. 1.4.3 Integration into iPython and Jupyter Notebook Next to the dependencies installed in the conda environment spex-3.08, the Python interface also depends on the SPEX environment variables set with the spexdist.(c)sh files. So before running iPython or Jupyter notebook, it is necessary to source the SPEX environment (also make sure the conda spex-3.08 environment is activated): (spex-3.08) unix:~> source /opt/spex/spexdist.sh (replace /opt/spex in this path with the location of SPEX on your machine, or $SPEX90 if this variable is already set). It may be that iPython and Jupyter are not yet installed in your conda environment. If not, please install them using the command: (spex-3.08) unix:~> conda install jupyter_client ipykernel With iPython and Jupyter notebook, it can be helpful to install the spex conda environment explicitly for your project: (spex-3.08) unix:~> ipython kernel install --user --name=spex-3.08 In your Jupyter notebook, you can now select spex-3.08 from the drop-down menu if you are creating a new project. The spex-3.08 conda environment should now be linked to your Jupyter project. 14 Chapter 1. Getting started SPEX Help Center Documentation, Release 3.08.02 1.5 Dependencies PYSPEX depends on the numpy,astropy, and matplotlib python modules. The current numpy versions should include the f2py program that is necessary to create the Fortran to python interface. Since Python 2 is no longer maintained, we do not actively support the Python 2 application of PYSPEX anymore. 1.6 Compile SPEX from source Table of Contents: •Getting started •Library dependencies •MacOS instructions •General compilation instructions •Optional features •Create install packages 1.6.1 Getting started The SPEX source code can be compiled using the multi-platform Cmake build system. See http://www.cmake.org/ for more information and downloads, or check the package manager of your Linux distribution. The SPEX install needs CMake version 3.0 or higher. Since SPEX is programmed mostly in Fortran 90, it is recommended to use a recent Fortran compiler. SPEX has been tested with GFortran (version 4 and above) and the Intel Fortran Compiler. This Zenodo contains a tar.bz2 file containing the source code of SPEX: spex-3.08.02-Source.tar.bz2. Unpack it in a convenient directory: unix:~/Software> tar xvfj spex-3.08.02-Source.tar.bz2 In the top-level directory, a script called compile.py is available to guide the user through the compilation process. Please read the section about library dependencies first and install what is needed. Otherwise, the script will tell you what is missing. To run the script call: unix:~/Software/spex> python compile.py Please note that the compile script requires Python 3 to be installed. 1.6.2 Library dependencies SPEX depends on a few external libraries to function. For some of those, the library source code has been included in the SPEX source code package. By default, CMake will look for system libraries to link to. If they are not there, then the version in the source package will be used. The following libraries and packages are required to compile SPEX: •CMake •X11 •Readline •CFITSIO (*) 1.5. Dependencies 15 SPEX Help Center Documentation, Release 3.08.02 •BLAS (*) •LAPACK (*) •PGPLOT (*) (*) The SPEX source tree also contains the library if necessary. All these libraries are commonly available in Linux distributions, so please read the documentation of your distribution to find out how to install these libraries. Please note that some distributions require you to also install the ‘development’ package of a library to be able to use them during compilation. In the Debian repository, for example, the development package of readline is called ‘libreadline-dev’. Below, we list some library-specific comments that can be helpful in case of problems. Readline Note for Mac OSX users: The OSX readline library is NOT compatible with the GNU readline library. You need to compile your own readline library from source or find a GNU readline library elsewhere on your system to link to. Compilation may work in, for example, a MacPorts environment, although this has not been tested. The official Mac version of SPEX statically links to a compiled version of readline downloaded from: https://tiswww.case.edu/php/chet/readline/rltop.html CFITSIO The cmake program will be able to find system versions of CFITSIO automatically. If CFITSIO is not installed, please install it using a package manager or compile it yourself. In case cmake cannot find the CFITSIO library, then add the flag -DCFITSIO_ROOT_DIR=/usr/local to the cmake command (in this example, CFITSIO was compiled using --prefix=/usr/local and the library is found in /usr/local/lib/libcfitsio.so. Make sure to provide the path where your libcfitsio library is installed). BLAS and LAPACK Some of the SPEX models depend heavily on the BLAS and LAPACK linear algebra packages. The default routines are available in the SPEX source tree, but compiling those will not provide the best performance. The performance improves substantially if an optimized BLAS or LAPACK library is used. There are two tested options: •Intel Math Kernel Library (MKL) •OpenBLAS When compiling with the Intel Fortran compiler, using MKL is quite obvious. To link the MKL library, add the following option to the cmake command: cmake . -DMKL=YES If MKL is not set, cmake will look for other options, like OpenBLAS, if they are installed on your machine. If nothing is found, the non-optimized code in the SPEX source tree is used. On Mac, CMake could find the MacOS Accelerator framework. 16 Chapter 1. Getting started SPEX Help Center Documentation, Release 3.08.02 1.6.3 MacOS instructions The compilation of SPEX on MacOS is slightly more demanding. SPEX can run natively on MacOS (without ports), but then it needs a few pre-installed programs: •Xcode (Through the App store) •CMake •XQuartz •GNU readline Compile and install readline with ‘clang’ and install in /usr/local. •Fortran compiler. For example GCC/GFORTRAN. 1.6.4 General Compilation Instructions When all library dependencies are installed, the compilation process can begin. Execute cmake in the root directory of the SPEX source tree, where CMakeLists.txt is located (mind the dot): unix:~/Software/SPEX-3.08.02-Source> cmake . If no errors occured and all libraries were found, then type ‘make’: unix:~/Software/SPEX-3.08.02-Source> make When the program needs to be installed system wide, then execute: unix:~/Software/SPEX-3.08.02-Source> sudo make install The program will be installed to /opt/spex by default. Usually, administrator rights are necessary to copy the files to the right location. Before you can run SPEX, the environment needs to be set. This can be done with the source command: source /opt/spex/spexdist.sh (bash shell) source /opt/spex/spexdist.csh (C-type shell) In case you used another prefix for the SPEX installation directory, you can find spexdist.sh or spexdist.csh in the prefix directory that you set. To load the SPEX environment automatically, add the relevant source line to your ~/.cshrc or ~/.bashrc file. 1.6.5 Optional features There are several options that can be passed to CMake to influence the build process through the -D operator. Of course, all options can be combined in a single cmake call. See the cmake documentation and the CMakeLists.txt file for details. Compiler selection Select a different fortran compiler: unix:~/Software/SPEX-3.08.02-Source> cmake . -DCMAKE_Fortran_COMPILER=ifort 1.6. Compile SPEX from source 17 SPEX Help Center Documentation, Release 3.08.02 Install prefix Install SPEX at a different location in the ‘make install’ step: unix:~/Software/SPEX-3.08.02-Source> cmake . -DCMAKE_INSTALL_PREFIX=/home/user/ ˓→software Force use of SPEX libraries The use of the SPEX libraries in the source tree can be forced: unix:~/Software/SPEX-3.08.02-Source> cmake . -DPGPLOT=YES The command above will compile the pgplot library from the SPEX source tree. See the CMakeLists.txt file for more options. 1.7 Use SPEX through Docker SPEX is written mostly in Fortran 90 and depends on a few system libraries. This makes it difficult to provide a few binary versions that will continue to run on multiple platforms over many years. Therefore, we have also created a Docker image for SPEX that can be run on the Docker platform, which is available for Linux, Mac OS and Windows. 1.7.1 Step 1: Download and install Docker on your computer To run a Docker image, please install Docker on your computer. See the Docker website for details and look for the Docker Engine community edition. Once you have downloaded and installed Docker, you can continue with this tutorial. 1.7.2 Step 2: Download the SPEX docker image from Zenodo The SPEX Docker image is available on this Zenodo page as a tar.gz file. Please download the file called spex- [version]-Docker.tar.gz, for example: spex-3.08.02-Docker.tar.gz Or, alternatively, you can pull the image from Docker hub with the command: docker pull spexxray/ spex:latest. 1.7.3 Step 3: Import the SPEX image into Docker Before you can run the docker file, it should be imported into the docker system. This can be done on the command line: user@linux:~> docker load -i spex-3.08.02-docker.tar.gz The image will be named spexxray/spex with the tag 3.08.02 and can be found with the command: user@linux:~> docker images REPOSITORY TAG IMAGE ID CREATED SIZE spexxray/spex 3.08.02 0a0a0a0a0a0 1 minute ago 996MB 18 Chapter 1. Getting started SPEX Help Center Documentation, Release 3.08.02 1.7.4 Step 4: Run SPEX on Docker Using the docker run command, the image can be executed and SPEX can be run in a so-called container. To enjoy all the capabilities of SPEX, two things need to be arranged in the docker run command: access to local directories and a graphical X11 connection. To arrange this, additional flags need to be specified on the command line. 1.7.5 Mounting local directories to the container If you would like to mount your own home directory into the SPEX container such that you can use some spo and res files there or save the output files, then you need the following flags: -e LOCAL_USER_ID=`id -u $USER` -v /home/myusername:/home/user The first flag arranges that the user in the container will have the same user ID as you. This will allow you to read and write to your home directory from within the container. The second flag arranges that your true local home directory called /home/myusername is mounted to /home/user inside the SPEX container. MAC users: Please note that on OSX your home directory is in /Users/myusername. 1.7.6 Arranging the X11 connection To make sure PGPLOT can connect to the X11 server on the host, we need to make a few connections from the container to the host machine. This is done with the following flags: -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix The first flag sets the DISPLAY variable inside the container to the DISPLAY variable of the host machine. The second flag mounts the X11 temporary directory of the host to the same directory inside the container. MAC users: To use X11 on Mac, you need to install XQuartz (or a similar X11 server) and set it to ‘Allow connections from network clients’ in the XQuartz settings. In addition, the X server should be set to allow incoming connections from localhost on the command line: user@macos:~> xhost +127.0.0.1 Then the DISPLAY variable on the docker run line should be set to host.docker.internal:0 1.7.7 The complete docker run command The full run commands for docker now look like below, where -w means that the container will start in working directory /home/user. For Linux: docker run -it \ -e DISPLAY=$DISPLAY \ -e LOCAL_USER_ID=`id -u $USER`\ -v /tmp/.X11-unix:/tmp/.X11-unix \ -v /home/myusername:/home/user \ -w /home/user \ spexxray/spex:3.08.02 For Mac: 1.7. Use SPEX through Docker 19 SPEX Help Center Documentation, Release 3.08.02 docker run -it \ -e DISPLAY=host.docker.internal:0 \ -e LOCAL_USER_ID=`id -u $USER`\ -v /tmp/.X11-unix:/tmp/.X11-unix \ -v /Users/myusername:/home/user \ -w /home/user \ spexxray/spex:3.08.02 The docker run command above will provide you with a prompt that will allow you to run spex: user@linux:~> docker run -it -e DISPLAY=$DISPLAY -e LOCAL_USER_ID=`id -u $USER`\ -v /tmp/.X11-unix:/tmp/.X11-unix -v /home/myusername:/home/user -w /home/user \ spexxray/spex:3.08.02 Welcome to the SPEX Docker Container! Just type 'spex'to start the program. user@0922f2e4ff85:~> In this environment, you can just run spex or trafo: user@0922f2e4ff85:~> spex Welcome user to SPEX version 3.08.02 NEW in this version of SPEX: 07-10-2025 Added plot component functionality 07-10-2025 Added atbl model to load Xspec table models 07-10-2025 Added magnetism module for pion 07-10-2025 Added ebit model for laboratory astrophysics 07-10-2025 Improvement of partial covering factor 07-10-2025 Update of quick calculation mode Setting the number of threads to 4 for optimal performance. Currently using SPEXACT version 2.07.00. Type `help var calc`for details. SPEX> 1.8 How to install SPEX using Anaconda SPEX is now also available through Anaconda for Linux and MacOS. The instructions below assume that you have a working version of Anaconda on your system (otherwise see Anaconda download or Miniconda, which installs the minimum needed). 1.8.1 SPEX status at Anaconda 1.8.2 Create a conda environment for SPEX (optional, but recommended) To make sure that SPEX keeps having access to its dependencies, it is best to install it in its own environment. This way, the number of potential conflicts with other packages remains minimal. Currently, SPEX is available for Python 3.10, 3.11 and 3.12, so please choose a version that matches your needs. A conda environment can be created with the command below: 20 Chapter 1. Getting started SPEX Help Center Documentation, Release 3.08.02 (base) user@linux:~> conda create -n spex python=3.12 Replace the version number in the flag python=3.12 with the Python version you need. Once the environment is created and the minimal packages are installed, the environment can be activated: (base) user@linux:~> conda activate spex (spex) user@linux:~> You now have a minimal environment to install SPEX into. 1.8.3 Install SPEX using conda Installing SPEX in a conda environment is as simple as: (spex) user@linux:~> conda install -c spexxray spex Conda will automatically install the dependencies of SPEX. It is possible that you need to re-initialize the conda environment to make SPEX run directly from the command line: (spex) user@linux:~> conda deactivate (base) user@linux:~> conda activate spex (spex) user@linux:~> spex Welcome user to SPEX version 3.08.02 07-10-2025 Added plot component functionality 07-10-2025 Added atbl model to load Xspec table models 07-10-2025 Added magnetism module for pion 07-10-2025 Added ebit model for laboratory astrophysics 07-10-2025 Improvement of partial covering factor 07-10-2025 Update of quick calculation mode Setting the number of threads to 4 for optimal performance. Currently using SPEXACT version 2.07.00. Type `help var calc`for details. SPEX> quit Thank you for using SPEX You probably want to install more packages in this environment for your purposes, like Jupyterlab or other scientific packages. This can be done using the conda install command as well. On an Apple Mac, it is necessary to install an Xserver, like XQuartz. 1.8.4 Running SPEX in conda Every time that you want to use SPEX in a new terminal, you have to activate the spex environment: (base) user@linux:~> conda activate spex (spex) user@linux:~> After this command also the python interface of SPEX should be automatically initialized: (spex) user@linux:~> python >>> from pyspex.spex import Session >>> s=Session() 1.8. How to install SPEX using Anaconda 21 SPEX Help Center Documentation, Release 3.08.02 28 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 2.1.6 Select good data and bin the spectrum Before we start fitting, we can make sure that only trustworthy data is fitted. For MOS1, for example, we know that the calibration is valid for the energy range between roughly 0.3 keV and 10 keV. To fit only the good spectral interval, we need to ignore the parts at low and high energies. This is done using the ignore command. In addition, we can bin the spectrum. To automatically rebin to the recommended (optimal) bin size, one can use the obin command. This command bins the spectrum optimally based on the instrument resolution and statistics. SPEX> ignore 0:0.3 unit kev SPEX> ignore 10:100 unit kev SPEX> obin 0.3:10 unit kev SPEX> plot 2.1.7 Define the model Next we can define the model that we want to fit. In this case, we are looking at a MOS spectrum of a galaxy cluster. The simplest model that we can try is a single temperature spectrum absorbed by gas in the ISM. We also add a redshift component reds (Reds: redshift model (page 224)) to shift the energy of the model spectrum with the right amount: SPEX> com reds You have defined 1 component. SPEX> com hot You have defined 2 components. (continues on next page) 2.1. Fitting a CCD spectrum 29 SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) SPEX> com cie You have defined 3 components. The hot model (Hot: collisional ionisation equilibrium absorption model (page 204)) is actually a gas in equilibrium in absorption, which is a fair representation of the neutral gas phase of the ISM. Later we will put the temperature of this component to 5×10−4keV to emulate a neutral plasma. The cie model (Cie: collisional ionisation equilibrium model (page 177)) represents a single temperature plasma in collisional ionisation equilibrium, which is commonly used for clusters. Then the components need to be related to each other, which means you need to specify how the multiplicative models should be applied to the additive models. The multiplicative components should be listed in order from the source to the observer (see also Comp: create, delete and relate spectral components (page 111)): SPEX> com rel 3 1,2 This means that the emitted CIE component (#3) will be first redshifted by component #1 and then absorbed by component #2. If you have multiple additive components, this should be done for each one. It is possible to supply a range of components. SPEX> calc SPEX> plot Calculating and plotting the model unsurprisingly results in a curve that is not near to the data. 30 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 2.1.8 Initial guess of parameters To help the spectral fitting process, it is good to provide initial guesses for the model parameters. This way, the spectral fit starts already with a model that is in the right direction. As a more experienced user, you usually have a rough idea what the parameters should be by looking at the raw spectrum. For this cluster, for example, the redshift is around 0.05, the absorption column is small, and the temperature of the cluster is around 3 keV. We can set the guess parameters as follows: SPEX> par 1 1 z v 0.05 SPEX> par 1 1 z s t SPEX> par 1 2 t v 8E-6 SPEX> par 1 2 t s f SPEX> par 1 2 nh v 1E-4 SPEX> par 1 3 norm v 1000. SPEX> par 1 3 t v 3.0 SPEX> ca SPEX> pl As we can see from the image, the first guess of the model is already in the right direction. In this example, we assume that the exact redshift is unknown. However, if you do have an accurate measurement of the distance, it is wise to set that distance in SPEX (Distance: set the source distance (page 115)): SPEX> dist 0.05 z The command above sets the distance to 0.05 z and makes sure that the luminosities are correctly calculated. Note that this distance change also affects the values of the normalisation of the models! So, we increase the normalisation to keep the model reasonably close to the data: 2.1. Fitting a CCD spectrum 31 SPEX Help Center Documentation, Release 3.08.02 SPEX> par 1 3 norm v 1E+8 2.1.9 Fit the model We are now ready to fit the spectrum. To see the fitting steps, we can give the command fit print 1. This needs to be set only once per session. A subsequent fit command (Fit: spectral fitting (page 120)) starts to optimize the parameters: SPEX> fit print 1 SPEX> fit 42102.6 5 5.000E-02 1.000E-04 1.000E+08 3.00 2461.87 10 5.404E-02 9.087E-05 2.021E+08 2.04 428.533 15 5.439E-02 1.041E-04 2.412E+08 2.31 414.925 20 5.437E-02 9.425E-05 2.429E+08 2.37 414.651 25 5.426E-02 9.229E-05 2.428E+08 2.37 414.532 30 5.408E-02 9.269E-05 2.428E+08 2.37 414.525 35 5.412E-02 9.281E-05 2.428E+08 2.37 414.524 42 5.411E-02 9.270E-05 2.428E+08 2.37 414.524 48 5.411E-02 9.265E-05 2.428E+08 2.37 -------------------------------------------------------------------------------------- ˓→------------ sect comp mod acro parameter with unit value status minimum maximum␣ ˓→lsec lcom lpar 1 1 reds z Redshift 5.4108180E-02 thawn -1.0 1.00E+10 1 1 reds flag Flag: cosmo=0, vel=1 0.000000 frozen 0.0 1.0 1 2 hot nh X-Column (1E28/m**2) 9.2653019E-05 thawn 0.0 1.00E+20 1 2 hot t Temperature (keV) 1.9999999E-04 frozen 2.00E-04 1.00E+03 1 2 hot rt T(balance) / T(spec) 1.000000 frozen 1.00E-04 1.00E+04 1 2 hot fcov Covering fraction 1.000000 frozen 0.0 1.0 1 2 hot v RMS Velocity (km/s) 100.0000 frozen 0.0 3.00E+05 1 2 hot rms RMS blend (km/s) 0.000000 frozen 0.0 1.00E+05 1 2 hot dv Vel. separ. (km/s) 100.0000 frozen 0.0 1.00E+05 1 2 hot zv Average vel. (km/s) 0.000000 frozen -1.00E+05 1.00E+05 1 2 hot ref Reference atom 1.000000 frozen 1.0 30. 1 2 hot 01 Abundance H 1.000000 frozen 0.0 1.00E+10 1 2 hot 02 Abundance He 1.000000 frozen 0.0 1.00E+10 1 2 hot 03 Abundance Li 1.000000 frozen 0.0 1.00E+10 1 2 hot 04 Abundance Be 1.000000 frozen 0.0 1.00E+10 1 2 hot 05 Abundance B 1.000000 frozen 0.0 1.00E+10 1 2 hot 06 Abundance C 1.000000 frozen 0.0 1.00E+10 1 2 hot 07 Abundance N 1.000000 frozen 0.0 1.00E+10 1 2 hot 08 Abundance O 1.000000 frozen 0.0 1.00E+10 1 2 hot 09 Abundance F 1.000000 frozen 0.0 1.00E+10 1 2 hot 10 Abundance Ne 1.000000 frozen 0.0 1.00E+10 1 2 hot 11 Abundance Na 1.000000 frozen 0.0 1.00E+10 1 2 hot 12 Abundance Mg 1.000000 frozen 0.0 1.00E+10 1 2 hot 13 Abundance Al 1.000000 frozen 0.0 1.00E+10 1 2 hot 14 Abundance Si 1.000000 frozen 0.0 1.00E+10 1 2 hot 15 Abundance P 1.000000 frozen 0.0 1.00E+10 1 2 hot 16 Abundance S 1.000000 frozen 0.0 1.00E+10 1 2 hot 17 Abundance Cl 1.000000 frozen 0.0 1.00E+10 1 2 hot 18 Abundance Ar 1.000000 frozen 0.0 1.00E+10 1 2 hot 19 Abundance K 1.000000 frozen 0.0 1.00E+10 1 2 hot 20 Abundance Ca 1.000000 frozen 0.0 1.00E+10 (continues on next page) 32 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) 1 2 hot 21 Abundance Sc 1.000000 frozen 0.0 1.00E+10 1 2 hot 22 Abundance Ti 1.000000 frozen 0.0 1.00E+10 1 2 hot 23 Abundance V 1.000000 frozen 0.0 1.00E+10 1 2 hot 24 Abundance Cr 1.000000 frozen 0.0 1.00E+10 1 2 hot 25 Abundance Mn 1.000000 frozen 0.0 1.00E+10 1 2 hot 26 Abundance Fe 1.000000 frozen 0.0 1.00E+10 1 2 hot 27 Abundance Co 1.000000 frozen 0.0 1.00E+10 1 2 hot 28 Abundance Ni 1.000000 frozen 0.0 1.00E+10 1 2 hot 29 Abundance Cu 1.000000 frozen 0.0 1.00E+10 1 2 hot 30 Abundance Zn 1.000000 frozen 0.0 1.00E+10 1 2 hot file File electr.distrib. 1 3 cie norm ne nX V (1E64/m**3) 2.4279381E+08 thawn 0.0 1.00E+20 1 3 cie t Temperature (keV) 2.372914 thawn 5.00E-04 1.00E+03 1 3 cie sig Sigma 0.000000 frozen 0.0 1.00E+04 1 3 cie sup Sigma up 0.000000 frozen 0.0 1.00E+04 1 3 cie logt T grid (lin/log) 1.000000 frozen 0.0 1.0 1 3 cie ed El dens (1E20/m**3) 9.9999998E-15 frozen 1.00E-22 1.00E+10 1 3 cie it Ion temp (keV) 1.000000 frozen 1.00E-04 1.00E+07 1 3 cie rt T(balance) / T(spec) 1.000000 frozen 1.00E-04 1.00E+04 1 3 cie vrms RMS Velocity (km/s) 0.000000 frozen 0.0 3.00E+05 1 3 cie ref Reference atom 1.000000 frozen 1.0 30. 1 3 cie 01 Abundance H 1.000000 frozen 0.0 1.00E+10 1 3 cie 02 Abundance He 1.000000 frozen 0.0 1.00E+10 1 3 cie 03 Abundance Li 1.000000 frozen 0.0 1.00E+10 1 3 cie 04 Abundance Be 1.000000 frozen 0.0 1.00E+10 1 3 cie 05 Abundance B 1.000000 frozen 0.0 1.00E+10 1 3 cie 06 Abundance C 1.000000 frozen 0.0 1.00E+10 1 3 cie 07 Abundance N 1.000000 frozen 0.0 1.00E+10 1 3 cie 08 Abundance O 1.000000 frozen 0.0 1.00E+10 1 3 cie 09 Abundance F 1.000000 frozen 0.0 1.00E+10 1 3 cie 10 Abundance Ne 1.000000 frozen 0.0 1.00E+10 1 3 cie 11 Abundance Na 1.000000 frozen 0.0 1.00E+10 1 3 cie 12 Abundance Mg 1.000000 frozen 0.0 1.00E+10 1 3 cie 13 Abundance Al 1.000000 frozen 0.0 1.00E+10 1 3 cie 14 Abundance Si 1.000000 frozen 0.0 1.00E+10 1 3 cie 15 Abundance P 1.000000 frozen 0.0 1.00E+10 1 3 cie 16 Abundance S 1.000000 frozen 0.0 1.00E+10 1 3 cie 17 Abundance Cl 1.000000 frozen 0.0 1.00E+10 1 3 cie 18 Abundance Ar 1.000000 frozen 0.0 1.00E+10 1 3 cie 19 Abundance K 1.000000 frozen 0.0 1.00E+10 1 3 cie 20 Abundance Ca 1.000000 frozen 0.0 1.00E+10 1 3 cie 21 Abundance Sc 1.000000 frozen 0.0 1.00E+10 1 3 cie 22 Abundance Ti 1.000000 frozen 0.0 1.00E+10 1 3 cie 23 Abundance V 1.000000 frozen 0.0 1.00E+10 1 3 cie 24 Abundance Cr 1.000000 frozen 0.0 1.00E+10 1 3 cie 25 Abundance Mn 1.000000 frozen 0.0 1.00E+10 1 3 cie 26 Abundance Fe 1.000000 frozen 0.0 1.00E+10 1 3 cie 27 Abundance Co 1.000000 frozen 0.0 1.00E+10 1 3 cie 28 Abundance Ni 1.000000 frozen 0.0 1.00E+10 1 3 cie 29 Abundance Cu 1.000000 frozen 0.0 1.00E+10 1 3 cie 30 Abundance Zn 1.000000 frozen 0.0 1.00E+10 1 3 cie file File electr.distrib. 1 3 cie x1 T1/T0 1.000000 frozen 1.0 1.00E+10 1 3 cie y1 N1/N0 0.000000 frozen 0.0 1.00E+10 (continues on next page) 2.1. Fitting a CCD spectrum 33 SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) Instrument 1 region 1 has norm 1.00000E+00 and is frozen -------------------------------------------------------------------------------- Fluxes and restframe luminosities between 2.0000 and 10.000 keV sect comp mod photon flux energy flux nr of photons luminosity (phot/m**2/s) (W/m**2) (photons/s) (W) 1 3 cie 4.13667 2.229383E-15 2.655905E+51 1.422295E+36 -------------------------------------------------------------------------------- Fit method : Classical Levenberg-Marquardt Fit statistic : C-statistic C-statistic : 414.52 Expected C-stat : 247.13 +/- 21.92 Chi-squared value : 528.16 Degrees of freedom: 239 W-statistic : 0.00 At the end of the optimization step, SPEX prints out an overview of the fit parameters and the fit statistics. Here we can see that the fit improved, but there is still room for improvement. 34 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 2.1.10 Fitting abundances Although the C-statistics are not too bad, there are still residuals in the spectrum, especially around the strongest spectral lines. This is because the metal abundances in the gas are still fixed to 1.0. We can let the abundances vary in the optimization by setting them to thawn: SPEX> par 1 3 08 s t SPEX> par 1 3 12 s t SPEX> par 1 3 14 s t SPEX> par 1 3 16 s t SPEX> par 1 3 18 s t SPEX> par 1 3 20 s t SPEX> par 1 3 26 s t SPEX> par 1 3 28 s t SPEX> fit The optimization leads to an even better fit: Fit method : Classical Levenberg-Marquardt Fit statistic : C-statistic C-statistic : 266.80 Expected C-stat : 247.12 +/- 21.91 Chi-squared value : 366.77 Degrees of freedom: 231 W-statistic : 0.00 2.1. Fitting a CCD spectrum 35 SPEX Help Center Documentation, Release 3.08.02 2.1.11 Calculating errors When we have the best fit, we can calculate the errors (Error: Calculate the errors of the fitted parameters (page 119)). This has to be done per parameter. Below we calculate, for example, the error on the best fit temperature: SPEX> error 1 3 t parameter C-stat Delta Delta value value parameter C-stat ---------------------------------------------------- 2.33348 267.68 -2.246547E-02 0.89 2.31101 270.23 -4.493093E-02 3.44 2.33348 267.68 -2.246547E-02 0.89 2.33247 267.69 -2.346587E-02 0.90 2.32425 268.52 -3.169394E-02 1.73 2.32836 268.05 -2.758002E-02 1.26 2.33042 267.87 -2.552295E-02 1.07 2.33127 267.79 -2.466774E-02 1.00 2.37841 267.71 2.246547E-02 0.92 2.40087 270.28 4.493093E-02 3.49 2.37841 267.71 2.246547E-02 0.92 2.37914 267.77 2.319646E-02 0.98 2.37940 267.78 2.345586E-02 0.99 2.37974 267.81 2.379751E-02 1.02 Parameter 1 3 t : 2.3559 Errors: -2.46677E-02 , 2.37975E-02 The error command reports the best fit value for the temperature and the lower and upper 1 sigma (68%) confidence level. Usually, the error calculation stage is the end point of a spectral analysis. In this example, we can quit SPEX now: SPEX> quit Thank you for using SPEX! 2.2 Modeling particle background 2.2.1 Goal Time dependent particle backgrounds in X-ray spectra are very difficult to correctly subtract, especially for extended sources. Many times, a quiescent particle background remains present in the spectrum after flare filtering. In this example, we show how to model the quiescent soft-proton contribution in a spectrum extracted from an annulus around the core of a cluster of galaxies. The difficulty here is that the effective area for soft protons is very different from the effective area for X-rays. Please note that the example provided is not necessarily scientifically correct. The goal of this example is to show a general method to deal with these kind of problems in SPEX. The choice of models probably needs to be different in other cases. 36 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 2.2.2 SPEX solution The basic problem we have to solve here, is that we need a number of model components that are folded through the mirror effective area (the cosmic X-rays) and a few components describing the particle background, which are not folded through the ARF. In SPEX, this can be solved using sectors (Sectors and regions (page 357)). Sectors are essentially model groups representing different areas or different components on the sky. In this case, we will create two sectors: one for the cosmic X-rays and one for the particle background. The second sector should not be folded through the ARF. To achieve this, we have to create a special spectrum and response file with trafo (Trafo (page 245)) in which we define the sectors. Fig. 1: Schematic representation of the sectors and regions in this example. We load two spectra with trafo and we define two sectors (left). The exact model components are later defined in SPEX. The models for sectors 1 and 2 are folded through the response matrix separately. The result of the folding is added and applied to the first spectrum (region 1 on the right) only. Running trafo In this trafo run, we will actually load the same spectrum twice. One for every sector. Here we use a MOS1 spectrum extracted from an annulus between 6 and 9 arcmin from the cluster core. The background spectrum was extracted using the XMM Extended Source Analysis Software by Snowden & Kuntz. After starting trafo we have to tell it that we want to transform two spectra in two sectors: Program trafo: transform data to SPEX 2.0 format This is version 1.02, of trafo Are your data in OGIP format : type=1 Old (Version 1.10 and below) SPEX format: type=2 Enter the type: 1 Enter the number of spectra you want to transform: 2 Enter the maximum number of response groups per energy per spectrum: 1000000 Enter the number of sectors you want to create: 2 The region number respresents the spectral data that we will fit. Because we want to add the cosmic X-ray spectrum and the particle background spectrum, we want both sectors to point to region 1. First, we enter the spectra for the first sector. We only show the most relevant input/output lines here. Enter the sector and region number: 1 1 How should the matrix be partioned? Option 1: keep as provided (1 component, no re-arrangements) (continues on next page) 2.2. Modeling particle background 37 SPEX Help Center Documentation, Release 3.08.02 2.3.6 Defining the broadband model We are studying the interstellar dust along the line of sight of a bright low-mass X-ray binary located near the Galactic bulge (distance 6.1 kpc). Setting the distance of the source SPEX> distance 6.1 kpc Distances assuming H0 = 70.0 km/s/Mpc, Omega_m = 0.300 Omega_Lambda = 0.700 Omega_r␣ ˓→= 0.000 Sector m A.U. ly pc kpc Mpc redshift cz ␣ ˓→age(yr) -------------------------------------------------------------------------------------- ˓→-------- 1 1.882E+20 1.258E+09 1.990E+04 6100.0000 6.1000 6.100E-03 0.0000 0.4␣ ˓→1.990E+04 -------------------------------------------------------------------------------------- ˓→-------- Setting the SED Set the intrinsic spectral-energy-distribution (SED) of the low-mass X-ray binary. For a typical X-ray binary, the SED between 0.1 and 10 keV is described by two components (Mitsuda et al. 1984): a thermal component, e.g. a black-body (Bb: blackbody model (page 176)), and a non-thermal component, e.g. a power-law (Pow: power law model (page 222)): SPEX> com pow You have defined 1 component. SPEX> par 1 1 norm value 30 SPEX> par 1 1 gamm value 1.1 SPEX> com bb You have defined 2 components. SPEX> par 1 2 norm value 3.e-7 SPEX> par 1 2 t value 0.8 Setting the Galactic cold neutral absorption SPEX> com hot You have defined 3 components. SPEX> par 1 3 nh value 1.9e-2 SPEX> par 1 3 t value 8e-6 SPEX> par 1 3 t status frozen 2.3.7 Defining the dust absorption Here we introduce the amol components (Amol: interstellar dust absorption model (page 172)) to characterise the interstellar dust extinction. In this example we add four arbitrary dust compounds: a-olivine (index=4230, MgFeSiO4), a-quartz (index=2234, SiO2), c-forsterite (index=3230, Mg2SiO4), and a-enstatite (index=3231, MgSiO3). The full list of all compounds is reported in Table Compounds list (page 172) and Table Additional compounds list (page 173) in the Amol: interstellar dust absorption model (page 172) section of the manual. 44 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 Setting the interstellar dust models Defining amol with the initial guess for the column densities of the dust compounds: SPEX> com amol You have defined 4 components. SPEX> par 1 4 i1 value 4230 SPEX> par 1 4 i2 value 2234 SPEX> par 1 4 i3 value 3230 SPEX> par 1 4 i4 value 3231 SPEX> par 1 4 n1 value 1e-7 SPEX> par 1 4 n2 value 1e-7 SPEX> par 1 4 n3 value 1e-7 SPEX> par 1 4 n4 value 1e-7 SPEX> par 1 4 n1 status thawn SPEX> par 1 4 n2 status thawn SPEX> par 1 4 n3 status thawn SPEX> par 1 4 n4 status thawn Warning: It is necessary to change and let free to vary the relative abundances of the cold gas elements (Hot: collisional ionisation equilibrium absorption model (page 204) in this case) which are also contained in the dust compounds. In this example, the dust models contain oxygen (08), magnesium (12), silicon (14) and iron (26). We let them to vary within a limited range according to the depletion intervals defined by Whittet et al. (2002) and Jenkins et al. (2009). SPEX> par 1 3 08 value 0.7 SPEX> par 1 3 12 value 0.10 SPEX> par 1 3 14 value 0.10 SPEX> par 1 3 26 value 0.05 SPEX> par 1 3 08 range 0.4 1 SPEX> par 1 3 12 range 0 0.4 SPEX> par 1 3 14 range 0 0.4 SPEX> par 1 3 26 range 0 0.2 SPEX> par 1 3 08 status thawn SPEX> par 1 3 12 status thawn SPEX> par 1 3 14 status thawn SPEX> par 1 3 26 status thawn Setting the component relations Adding the multiplicative components hot and amol to the broad-band model: SPEX> com rel 1:2 4,3 SPEX> model show -------------------------------------------------------------------------------- Number of sectors : 1 Sector: 1 Number of model components: 4 Nr. 1: pow [4,3 ] Nr. 2: bb [4,3 ] Nr. 3: hot Nr. 4: amol 2.3. Fitting interstellar dust absorption 45 SPEX Help Center Documentation, Release 3.08.02 2.3.8 Fitting We fit the model to the data and print the free parameters: SPEX> calc SPEX> fit print 1 SPEX> fit SPEX> fit SPEX> plot SPEX> par show free -------------------------------------------------------------------------------------- ˓→------------ sect comp mod acro parameter with unit value status minimum maximum␣ ˓→lsec lcom lpar 1 1 pow norm Norm (1E44 ph/s/keV) 23.14066 thawn 0.0 1.00E+20 1 1 pow gamm Photon index 0.9320605 thawn -10. 10. 1 2 bb norm Area (1E16 m**2) 3.5883755E-07 thawn 0.0 1.00E+20 1 2 bb t Temperature (keV) 0.7793768 thawn 1.00E-04 1.00E+03 1 3 hot nh X-Column (1E28/m**2) 2.0304110E-02 thawn 0.0 1.00E+20 1 3 hot 08 Abundance O 0.5010648 thawn 0.40 1.0 1 3 hot 12 Abundance Mg 0.1016048 thawn 0.0 0.40 1 3 hot 14 Abundance Si 0.1060375 thawn 0.0 0.40 1 3 hot 26 Abundance Fe 0.000000 thawn 0.0 0.20 1 4 amol n1 Column 1 (1E28/m**2) 5.6286910E-07 thawn 0.0 1.00E+20 1 4 amol n2 Column 1 (1E28/m**2) 1.1466740E-07 thawn 0.0 1.00E+20 1 4 amol n3 Column 1 (1E28/m**2) 1.3037014E-07 thawn 0.0 1.00E+20 1 4 amol n4 Column 1 (1E28/m**2) 9.8849377E-08 thawn 0.0 1.00E+20 Instrument 1 region 1 has norm 1.00000E+00 and is frozen Instrument 1 region 2 has norm 1.00000E+00 and is frozen -------------------------------------------------------------------------------- Fluxes and restframe luminosities between 2.0000 and 10.000 keV sect comp mod photon flux energy flux nr of photons luminosity (phot/m**2/s) (W/m**2) (photons/s) (W) 1 1 pow 7877.93 6.754451E-12 4.125361E+45 3.331746E+30 1 2 bb 3030.35 1.681985E-12 1.818740E+45 9.538203E+29 -------------------------------------------------------------------------------- Fit method : Classical Levenberg-Marquardt Fit statistic : C-statistic C-statistic : 2388.02 Expected C-stat : 2402.60 +/- 69.35 Chi-squared value : 2406.15 Degrees of freedom: 2388 W-statistic : 0.00 46 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 2.3.9 Final remarks This is the end of this analysis thread. If you want, you can save the parameters and quit SPEX: SPEX> par write parameters SPEX> log out fit_result SPEX> par show SPEX> log close output SPEX> quit Thank you for using SPEX! 2.4 Import UV/Optical data For some applications it would be helpful to include non-X-ray data into the spectral fit. For example, this can be an optical/UV spectrum that the user wants to fit simultaneously with the X-ray spectrum using the models of SPEX. For some instruments, namely the photometric filters of XMM-Newton’s OM and Swift’s UVOT, the data products are available in the same format as the X-ray data (i.e. the OGIP-standard PHA and response files). Therefore, for OM and UVOT filters, the user is recommended to convert the PHA and response files to SPEX format using TRAFO as normally done for the X-ray data. Information about the instrumental response files of OM and UVOT filters can be found here: https://www.cosmos.esa.int/web/xmm-newton/om-response-files https://swift.gsfc.nasa.gov/proposals/swift_responses.html However, for some other instruments the user may not know, or have access, to the counts and instrumental response 2.4. Import UV/Optical data 47 SPEX Help Center Documentation, Release 3.08.02 information. For example, the user obtained optical/UV fluxes from NED or a table in a paper. In such cases the user is recommended to first use the FTOOLS program called ftflx2xsp to convert their data to the OGIP-standard PHA and response files. The webpage of ftflx2xsp provides all the instructions with some useful examples: https://heasarc.gsfc.nasa.gov/lheasoft/ftools/headas/ftflx2xsp.html This program reads a text file containing the spectrum with the specified units, and creates the corresponding PHA and RSP files. These files can be then converted to SPEX format using TRAFO as usual. The SPEX equivalent of ftflx2xsp is Uvtospex (page 257). Please follow the link to find a brief manual for this tool. It creates a SPEX format spectrum and response matrix based on the fluxes as function of wavelength stored in a text file. The instrument resolution is needed in units of km/s (FWHM). Note: There are some OM response matrices around that do not conform to the OGIP standard. The extension of the response matrix is then called ‘SPECTRESP MATRIX’ instead of the standard ‘SPECRESP MATRIX’. trafo and ogip2spex will exit with an error when this name error is encountered. This can be solved by renaming the extension to ‘SPECRESP MATRIX’ in the rmf file. This can be done, for example, by using the HEASOFT task fv. 2.5 PION setup for AGN warm absorber By: Junjie Mao, Missagh Mehdipour, and Jelle Kaastra 2.5.1 Goal Setup the PION model for the warm absorber in a nearby Seyfert 1 galaxy observed with Chandra HRC/LETGS. Note: A simulated spectrum was used because this thread merely intends to show the setup of the PION model. 2.5.2 Preparation To follow this thread, you need to download the example files here: chl.spo and chl.res. 2.5.3 Start SPEX Start SPEX in a linux terminal window: user@linux:~> spex Welcome user to SPEX version 3.05.00 SPEX> 48 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 2.5.4 Load data A command file tailored for this thread to load data is available here data.com user@linux:~> cat data.com # Simulated data #--------------- # HRC/LETGS DATA data chl chl bin inst 1 reg 1 0:10000 2 unit ang ignore inst 1 reg 1 0:1.5 unit ang ignore inst 1 reg 1 60:1000 unit ang Load the above command file into SPEX: SPEX> log exe data 2.5.5 Plot data A command file tailored for this thread to plot the data is available here plot.com user@linux:~> cat plot.com # plot setting plot dev xw plot type data plot x lin plot ux a plot rx 1.5:60 plot y lin plot uy fa plot ry 0:20 plot set 1 plot mo lw 3 plot fill disp f plot back disp f plot cap id disp f plot cap ut disp f plot cap lt disp f plot Load the above command file into SPEX: SPEX> log exe plot 2.5.6 Define model components and component relations (step-by-step) Here we are looking at the warm absorber in a nearby (z = 0.07) Seyfert 1 galaxy. 2.5. PION setup for AGN warm absorber 49 SPEX Help Center Documentation, Release 3.08.02 Set the distance of the source SPEX> dist 0.07 z Distances assuming H0 = 70.0 km/s/Mpc, Omega_m = 0.300 Omega_Lambda = 0.700 Omega_r␣ ˓→= 0.000 Sector m A.U. ly pc kpc Mpc redshift cz ␣ ˓→age(yr) -------------------------------------------------------------------------------------- ˓→-------- 1 9.740E+24 6.511E+13 1.030E+09 3.157E+08 3.157E+05 315.6554 0.0700 20985.5 9. ˓→302E+08 -------------------------------------------------------------------------------------- ˓→-------- SPEX> com reds You have defined 1 component. SPEX> par 1 1 z val 0.07 50 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 Set the redshift component SPEX> com reds You have defined 1 component. SPEX> par 1 1 z val 0.07 Set the galactic absorption SPEX> com hot You have defined 2 components. SPEX> par 1 2 nh val 2.0e-4 SPEX> par 1 2 t val 8E-6 SPEX> par 1 2 t s f SPEX> par 1 2 nh s f Set the SED Set the intrinsic spectral-energy-distribution (SED) of the AGN above the Lyman limit along our line-of-sight. For a typical Seyfert 1 galaxy, the SED has three components (Mehdipour et al. 2015): •A Comptonized disk component (Comt: comptonisation model (page 190)) for optical to soft X-rays data, •A power-law component (Pow: power law model (page 222)) for X-ray data, •A neutral reflection component (Refl: reflection model (page 224)) for hard X-rays data. Usually, the reflection component has an exponential cut-off energy (300 keV here). SPEX> com comt You have defined 3 components. SPEX> par 1 3 norm val 3.E12 SPEX> par 1 3 norm s f SPEX> par 1 3 t0 val 5e-4 SPEX> par 1 3 t0 s f SPEX> par 1 3 t1 val 0.15 SPEX> par 1 3 t1 s f SPEX> par 1 3 tau val 20 SPEX> par 1 3 tau s f SPEX> com pow You have defined 4 components. SPEX> par 1 4 norm val 1.E+09 SPEX> par 1 4 norm s t SPEX> par 1 4 gamm val 1.7 SPEX> par 1 4 gamm s t SPEX> com refl You have defined 5 components. SPEX> par 1 5 norm couple 1 4 norm SPEX> par 1 5 gamm couple 1 4 gamm SPEX> par 1 5 ecut val 300 SPEX> par 1 5 ecut s f SPEX> par 1 5 pow:fgr v 0 SPEX> par 1 5 scal val 1. SPEX> par 1 5 scal s f 2.5. PION setup for AGN warm absorber 51 SPEX Help Center Documentation, Release 3.08.02 Apply an exponential cut-off to the power-law Apply exponential cut-off to the power-law component of the SED both below the Lyman limit and above the high-energy cut-off. Note: The ecut parameter in the refl component applies to itself only. SPEX> com etau You have defined 6 components. SPEX> par 1 6 a val -1 SPEX> par 1 6 a s f SPEX> par 1 6 tau val 1.3605E-2 SPEX> par 1 6 tau s f SPEX> com etau You have defined 7 components. SPEX> par 1 7 a val 1 SPEX> par 1 7 a s f SPEX> par 1 7 tau val 3.3333E-3 SPEX> par 1 7 tau s f Set the PION (absorption) components Here we introduce three PION components (Pion: SPEX photoionised plasma model (page 216)). The parameters of the PION components are restricted to improve the efficiency of a realistic fitting process. fcov=1 refers to the PION component fully covers the line-of-sight. omeg=1.E-7 refers to a negligible solid angle (Ω) subtended by the PION component with respect to the nucleus (omeg = Ω/4𝜋). Note: The third pion component is a spare one with fcov=0 and omeg=0. This is practical when analyzing real data without any prior knowledge of the number of PION components required. Note: To see the density effect of the absorption features, it is necessary to set a non-zero omeg value. SPEX> com pion You have defined 8 components. ** Pion model: take care about proper COM REL use: check manual! SPEX> com pion You have defined 9 components. ** Pion model: take care about proper COM REL use: check manual! SPEX> com pion You have defined 10 components. ** Pion model: take care about proper COM REL use: check manual! SPEX> par 1 8:10 nh range 1.E-7:1.E1 SPEX> par 1 8:10 xil range -5:5 SPEX> par 1 8:10 omeg range 0:1 SPEX> par 1 8 nh val 5.E-03 SPEX> par 1 8 xil val 2.7 SPEX> par 1 8 zv val -500 SPEX> par 1 8 zv s t SPEX> par 1 8 v val 100 SPEX> par 1 8 v s t SPEX> par 1 8 omeg val 1.E-7 SPEX> par 1 9 nh val 2.E-03 (continues on next page) 52 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) SPEX> par 1 9 xil val 1.6 SPEX> par 1 9 zv val -100 SPEX> par 1 9 zv s t SPEX> par 1 9 v val 50 SPEX> par 1 9 v s t SPEX> par 1 9 omeg val 1.E-7 SPEX> par 1 10 nh val 1.E-7 SPEX> par 1 10 xil val 0 SPEX> par 1 10 fcov val 0 SPEX> par 1 10 omega val 0 Set component relation along our line of sight Set the component relation for the intrinsic AGN SED above the Lyman limit along our line-of-sight. Note: Photons from both the Comptonized disk and power-law components are screened by the warm absorber components at the redshift of the target, as well as the galactic absorption before reaching the detector. Photons from the neutral reflection component is assumed not to be screened by the warm absorber for simplicity. It is still redshifted and requires the galactic absorption. SPEX> com rel 3 8,9,10,1,2 SPEX> com rel 4 6,7,8,9,10,1,2 SPEX> com rel 5 1,2 Set the component relation for the PION components Assuming that the warm absorber components closer to the central engine are defined first (with a smaller component index), photons transmitted from the inner PION components (with a nonzero omeg value) are screened by all the outer PION components at the redshift of the target, as well as the galactic absorption before reaching the detector: SPEX> com rel 8 9,10,1,2 SPEX> com rel 9 10,1,2 SPEX> com rel 10 1,2 2.5. PION setup for AGN warm absorber 53 SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) SPEX> par 1 3 tau val 20 SPEX> par 1 3 tau s f SPEX> com pow You have defined 4 components. SPEX> par 1 4 norm val 1.E+09 SPEX> par 1 4 norm s t SPEX> par 1 4 gamm val 1.7 SPEX> par 1 4 gamm s t SPEX> com refl You have defined 5 components. SPEX> par 1 5 norm couple 1 4 norm SPEX> par 1 5 gamm couple 1 4 gamm SPEX> par 1 5 ecut val 300 SPEX> par 1 5 ecut s f SPEX> par 1 5 pow:fgr v 0 SPEX> par 1 5 scal val 1. SPEX> par 1 5 scal s f (B) Apply exponential cut-off to the power-law component of the SED both below the Lyman limit and above the high-energy cut-off. Note: The ecut parameter in the refl component applies to itself only. SPEX> com etau You have defined 6 components. SPEX> par 1 6 a val -1 SPEX> par 1 6 a s f SPEX> par 1 6 tau val 1.3605E-2 SPEX> par 1 6 tau s f SPEX> com etau You have defined 7 components. SPEX> par 1 7 a val 1 SPEX> par 1 7 a s f SPEX> par 1 7 tau val 3.3333E-3 SPEX> par 1 7 tau s f (C) Set the PION (obscuring wind) components. Here we introduce two PION components for the obscuring wind (Kaastra et al. 2014). The parameters of the PION components are restricted to improve the efficiency of a realistic fitting process. Note: The second pion component is a spare one with fcov=0 and omeg=0. This is practical when analyzing real data without any prior knowledge of the number of PION components required. SPEX> com pion You have defined 8 components. ** Pion model: take care about proper COM REL use: check manual! SPEX> com pion You have defined 9 components. ** Pion model: take care about proper COM REL use: check manual! SPEX> par 1 8:9 nh range 1.E-7:1.E1 SPEX> par 1 8:9 xil range -5:5 SPEX> par 1 8 nh val 5.E-02 SPEX> par 1 8 xil val 0.0 (continues on next page) 60 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) SPEX> par 1 8 zv val -3000 SPEX> par 1 8 zv s t SPEX> par 1 8 v val 1100 SPEX> par 1 8 v s t SPEX> par 1 9 nh val 1.E-7 SPEX> par 1 9 nh s f SPEX> par 1 9 xil val 0 SPEX> par 1 9 xil s f SPEX> par 1 9 fcov val 0 SPEX> par 1 9 omega val 0 (D) Set the PION (warm absorber) components. Here we introduce three PION components for the X-ray warm absorber. omeg=1.E-7 refers to a negligible solid angle (Ω) subtended by the PION component with respect to the nucleus (omeg = Ω/4𝜋). Note: To see the density effect of the absorption features, it is necessary to set a non-zero omeg value. SPEX> com pion You have defined 10 components. ** Pion model: take care about proper COM REL use: check manual! SPEX> com pion You have defined 11 components. ** Pion model: take care about proper COM REL use: check manual! SPEX> com pion You have defined 12 components. ** Pion model: take care about proper COM REL use: check manual! SPEX> par 1 10:12 nh range 1.E-7:1.E1 SPEX> par 1 10:12 xil range -5:5 SPEX> par 1 10:12 omeg range 0:1 SPEX> par 1 10 nh val 5.E-03 SPEX> par 1 10 xil val 2.7 SPEX> par 1 10 zv val -500 SPEX> par 1 10 zv s t SPEX> par 1 10 v val 100 SPEX> par 1 10 v s t SPEX> par 1 10 omeg val 1.E-7 SPEX> par 1 11 nh val 2.E-03 SPEX> par 1 11 xil val 1.6 SPEX> par 1 11 zv val -100 SPEX> par 1 11 zv s t SPEX> par 1 11 v val 50 SPEX> par 1 11 v s t SPEX> par 1 11 omeg val 1.E-7 SPEX> par 1 12 nh val 1.E-7 SPEX> par 1 12 xil val 0 SPEX> par 1 12 fcov val 0 SPEX> par 1 12 omega val 0 (E) Set the component relation for line-of-sight #1. Note: Photons from both the Comptonized disk and power-law components are screened by the obscuring wind and warm absorber components at the redshift of the target, as well as the galactic absorption before reaching the detector. Photons from the neutral reflection component is assumed not to be screened by the obscuring wind and warm absorber for simplicity. It is still redshifted and requires the galactic absorption. 2.6. PION setup for emission and absorption features in AGN 61 SPEX Help Center Documentation, Release 3.08.02 SPEX> com rel 3 8,9,10,11,12,1,2 SPEX> com rel 4 6,7,8,9,10,11,12,1,2 SPEX> com rel 5 1,2 (F) Set the component relation for the PION components. Assuming that the obscuring wind and warm absorber components closer to the central engine are defined first (with a smaller component index), photons transmitted from the inner PION components (with a nonzero omeg value) are screened by all the outer PION components at the redshift of the target, as well as the galactic absorption before reaching the detector. SPEX> com rel 8 9,10,11,12,1,2 SPEX> com rel 9 10,11,12,1,2 SPEX> com rel 10 11,12,1,2 SPEX> com rel 11 12,1,2 SPEX> com rel 12 1,2 Set the components and component relations for line-of-sights #2 and #3 (A) Set the AGN SED above the Lyman limit along line-of-sights #2a and #3a. Note: Here we assume that the photoionizing SED for the X-ray broad emission PION component(s) is set to be the same as that for the obscuring wind and warm absorber. This simplification assumes that the X-ray broad-line region respond to the photoionizing SED instantaneously. Because the X-ray broad-line region is typically a few lightdays away from the central engine and it has a relatively high density. On the other hand, the photoionizing SED for the X-ray narrow emission PION component(s) is set to a long-term averaged SED. This simplification assumes that the X-ray narrow-line region is in a steady state, i.e. it varies slightly around a mean value corresponding to the mean flux level over time. Because the X-ray narrow-line region is typically a few parsecs away from the central engine and it has a relatively low density. Readers are referred to Silva et al. 2016 for a detailed spectral timing study. SPEX> com comt You have defined 13 components. SPEX> par 1 13 norm:type couple 1 3 norm:type SPEX> com pow You have defined 14 components. SPEX> par 1 14 norm:lum couple 1 4 norm:lum SPEX> com comt You have defined 15 components. SPEX> par 1 15 norm val 1.E12 SPEX> par 1 15 norm s f SPEX> par 1 15 t0 val 3.E-4 SPEX> par 1 15 t0 s f SPEX> par 1 15 t1 val 0.125 SPEX> par 1 15 t1 s f SPEX> par 1 15 tau val 20 SPEX> par 1 15 tau s f SPEX> com pow You have defined 16 components. SPEX> par 1 16 norm val 6.E9 SPEX> par 1 16 norm s f SPEX> par 1 16 gamm val 1.6 SPEX> par 1 16 gamm s f (B) Apply exponential cut-off to the above AGN SEDs at all energies because these photons do not reach us (dashed gray lines in Figure 1). 62 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 SPEX> com etau You have defined 17 components. SPEX> par 1 17 tau val 1.E3 SPEX> par 1 17 tau s f SPEX> par 1 17 a val 0 SPEX> par 1 17 a s f (C) Set the PION (emission) components. Here we introduce three PION components. The parameters of the PION components are restricted to improve the efficiency of a realistic fitting process. fcov=0 for the emission PION components. Note: The first pion component refers to the X-ray broad-line region. The second pion component refers to the X-ray narrow-line region. The third pion component is a spare one with fcov=0 and omeg=0. This is practical when analyzing real data without any prior knowledge of the number of PION components required. SPEX> com pion You have defined 18 components. ** Pion model: take care about proper COM REL use: check manual! SPEX> com pion You have defined 19 components. ** Pion model: take care about proper COM REL use: check manual! SPEX> com pion You have defined 20 components. ** Pion model: take care about proper COM REL use: check manual! SPEX> par 1 16:18 nh range 1.E-7:1.E1 SPEX> par 1 16:18 xil range -5:5 SPEX> par 1 16:18 omeg range 0:1 SPEX> par 1 16 nh val 8.E-02 SPEX> par 1 16 xil val 0.8 SPEX> par 1 16 zv val 0 SPEX> par 1 16 zv s f SPEX> par 1 16 v val 100 SPEX> par 1 16 v s f SPEX> par 1 16 omeg val 3.E-2 SPEX> par 1 16 omeg s t SPEX> par 1 17 nh val 5.E-02 SPEX> par 1 17 xil val 2.3 SPEX> par 1 17 zv val 0 SPEX> par 1 17 zv s f SPEX> par 1 17 v val 240 SPEX> par 1 17 v s t SPEX> par 1 17 omeg val 5.E-2 SPEX> par 1 17 omeg s t SPEX> par 1 18 nh val 1.E-7 SPEX> par 1 18 nh s f SPEX> par 1 18 xil val 0 SPEX> par 1 18 xil s f SPEX> par 1 18 fcov val 0 SPEX> par 1 18 omeg val 0 (D) Set the broadening due to macroscopic motion for the PION (emission) components. Note: The vparameter in PION components refer to the microscopic (i.e. turbulent) motion. The macroscopic motion refers to the rotation around the black hole. For the X-ray broad emission lines, the macroscopic motion dominates the broadening. For the X-ray narrow emission lines, the microscopic and macroscopic motion are often 2.6. PION setup for emission and absorption features in AGN 63 SPEX Help Center Documentation, Release 3.08.02 degenerate (Mao et al. 2018). The second and third vgau components are spare. SPEX> com vgau You have defined 21 components. par 1 21 sig val 7.E3 par 1 21 sig s t SPEX> com vgau You have defined 22 components. SPEX> com vgau You have defined 23 components. (E) Set the component relation for line-of-sights #2a and #3a. Note: Photons from both the Comptonized disk and power-law (with exponential lowand high-energy cut-offs) components are the photoionizing source of the PION emission components at the redshift of the target. While (reflected/reprocessed) photons from the PION emission components reach us. SPEX> com rel 13 18,1,17 SPEX> com rel 14 6,7,18,1,17 SPEX> com rel 15 19,20,1,17 SPEX> com rel 16 6,7,19,20,1,17 (F) Set the component relation for the PION (emission) components. Note: Here we assume that the obscuring wind is outside the X-ray broad-line region and it screens photons emitted from the X-ray broad-line region before it reaches us. On the other hand, since the obscuring wind is closer to the central engine than the X-ray narrow-line region, photons emitted from the X-ray narrow-line region are not screened by the obscuring wind. SPEX> com rel 18 21,8,9,1,2,26 SPEX> com rel 19 22,1,2,26 SPEX> com rel 20 23,1,2,26 (G) Set the component relation for the AGN SED below the Lyman limit (optical/UV) along line-of-sight #1. SPEX> com rel 24 30,1,31,27 SPEX> com rel 25 6,7,30,1,31,27 SPEX> com rel 28 1 SPEX> com rel 29 1 2.6.7 Check settings and calculate We check the setting of the component relation: SPEX> model show -------------------------------------------------------------------------------- Number of sectors : 1 Sector: 1 Number of model components: 31 Nr. 1: reds Nr. 2: hot Nr. 3: comt[8,9,10,11,12,1,2,26 ] Nr. 4: pow [6,7,8,9,10,11,12,1,2,26 ] Nr. 5: refl[1,2,26 ] (continues on next page) 64 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) Nr. 6: etau Nr. 7: etau Nr. 8: pion[9,10,11,12,1,2,26 ] Nr. 9: pion[10,11,12,1,2,26 ] Nr. 10: pion[11,12,1,2,26 ] Nr. 11: pion[12,1,2,26 ] Nr. 12: pion[1,2,26 ] Nr. 13: comt[18,1,17 ] Nr. 14: pow [6,7,18,1,17 ] Nr. 15: comt[19,20,1,17 ] Nr. 16: pow [6,7,19,20,1,17 ] Nr. 17: etau Nr. 18: pion[21,8,9,1,2,26 ] Nr. 19: pion[22,1,2,26 ] Nr. 20: pion[23,1,2,26 ] Nr. 21: vgau Nr. 22: vgau Nr. 23: vgau Nr. 24: comt[30,1,31,27 ] Nr. 25: pow [6,7,30,1,31,27 ] Nr. 26: etau Nr. 27: etau Nr. 28: file[1 ] Nr. 29: file[1 ] Nr. 30: ebv Nr. 31: ebv We check the setting of the free parameters and calculate the 1–1000 Ryd ionizing luminosity: SPEX> elim 1.E0:1.E3 ryd SPEX> calc SPEX> plot SPEX> par show free -------------------------------------------------------------------------------------- ˓→------------ sect comp mod acro parameter with unit value status minimum maximum␣ ˓→lsec lcom lpar 1 3 comt norm Norm (1E44 ph/s/keV) 3.0000001E+12 thawn 0.0 1.00E+20 1 3 comt t0 Wien temp (keV) 5.0000002E-04 thawn 1.00E-05 1.00E+10 1 3 comt t1 Plasma temp (keV) 0.1500000 thawn 1.00E-05 1.00E+10 1 3 comt tau Optical depth 20.00000 thawn 1.00E-03 1.00E+03 1 4 pow norm Norm (1E44 ph/s/keV) 1.0000000E+09 thawn 0.0 1.00E+20 1 4 pow gamm Photon index 1.700000 thawn -10. 10. 1 8 pion nh X-Column (1E28/m**2) 5.0000001E-02 thawn 1.00E-07 10. 1 8 pion xil Log xi (1E-9 Wm) 0.000000 thawn -5.0 5.0 1 8 pion v RMS Velocity (km/s) 1100.000 thawn 0.0 3.00E+05 1 8 pion zv Average vel. (km/s) -3000.000 thawn -1.00E+05 1.00E+05 (continues on next page) 2.6. PION setup for emission and absorption features in AGN 65 SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) 1 10 pion nh X-Column (1E28/m**2) 4.9999999E-03 thawn 1.00E-07 10. 1 10 pion xil Log xi (1E-9 Wm) 2.700000 thawn -5.0 5.0 1 10 pion v RMS Velocity (km/s) 100.0000 thawn 0.0 3.00E+05 1 10 pion zv Average vel. (km/s) -500.0000 thawn -1.00E+05 1.00E+05 1 11 pion nh X-Column (1E28/m**2) 2.0000001E-03 thawn 1.00E-07 10. 1 11 pion xil Log xi (1E-9 Wm) 1.600000 thawn -5.0 5.0 1 11 pion v RMS Velocity (km/s) 50.00000 thawn 0.0 3.00E+05 1 11 pion zv Average vel. (km/s) -100.0000 thawn -1.00E+05 1.00E+05 1 18 pion nh X-Column (1E28/m**2) 7.9999998E-02 thawn 1.00E-07 10. 1 18 pion xil Log xi (1E-9 Wm) 0.8000000 thawn -5.0 5.0 1 18 pion omeg Scaling factor emis. 2.9999999E-02 thawn 0.0 1.0 1 19 pion nh X-Column (1E28/m**2) 5.0000001E-02 thawn 1.00E-07 10. 1 19 pion xil Log xi (1E-9 Wm) 2.300000 thawn -5.0 5.0 1 19 pion v RMS Velocity (km/s) 240.0000 thawn 0.0 3.00E+05 1 19 pion omeg Scaling factor emis. 9.9999998E-03 thawn 0.0 1.0 1 21 vgau sig Sigma (km/s) 7000.000 thawn 0.0 3.00E+05 1 28 file norm Flux scale factor 0.3000000 thawn 0.0 1.00E+20 1 29 file norm Flux scale factor 0.4000000 thawn 0.0 1.00E+20 1 30 ebv ebv E(B-V) (mag) 0.1000000 thawn 0.0 1.00E+20 1 31 ebv ebv E(B-V) (mag) 0.1200000 thawn 0.0 1.00E+20 Instrument 1 region 1 has norm 1.00000E+00 and is frozen Instrument 2 region 1 has norm 1.00000E+00 and is frozen Instrument 3 region 1 has norm 1.00000E+00 and is frozen Instrument 4 region 1 has norm 1.00000E+00 and is frozen Instrument 5 region 1 has norm 1.00000E+00 and is frozen Instrument 6 region 1 has norm 1.00000E+00 and is frozen Instrument 7 region 1 has norm 1.00000E+00 and is frozen Instrument 8 region 1 has norm 1.00000E+00 and is frozen -------------------------------------------------------------------------------- Fluxes and restframe luminosities between 1.36057E-02 and 13.606 keV (continues on next page) 66 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) sect comp mod photon flux energy flux nr of photons luminosity (phot/m**2/s) (W/m**2) (photons/s) (W) 1 3 comt 7.891731E-04 1.775058E-19 1.447225E+54 7.988903E+36 1 4 pow 38.8452 3.366349E-14 2.869709E+54 1.021578E+38 1 5 refl 5.98573 7.190706E-15 6.284845E+51 7.467510E+36 1 8 pion 0.00000 0.00000 0.00000 0.00000 1 9 pion 0.00000 0.00000 0.00000 0.00000 1 10 pion 1.755872E-08 5.460370E-24 2.240611E+44 1.101832E+28 1 11 pion 7.849879E-10 9.871699E-26 3.169252E+45 7.940836E+27 1 12 pion 0.00000 0.00000 0.00000 0.00000 1 13 comt 1213.94 6.701157E-15 1.447225E+54 7.988903E+36 1 14 pow 1657.30 8.033095E-14 2.869709E+54 1.021578E+38 1 15 comt 0.00000 0.00000 1.106767E+53 5.268881E+35 1 16 pow 0.00000 0.00000 1.296679E+55 6.397146E+38 1 18 pion 2.157629E-03 5.832195E-19 1.541392E+54 9.503085E+36 1 19 pion 3.30138 4.647512E-16 5.174083E+52 1.025305E+36 1 20 pion 0.00000 0.00000 0.00000 0.00000 1 24 comt 0.501314 1.089752E-18 1.447225E+54 7.988903E+36 1 25 pow 0.193548 4.207327E-19 2.869709E+54 1.021578E+38 1 28 file 0.00000 0.00000 0.00000 0.00000 1 29 file 0.00000 0.00000 0.00000 0.00000 Fit method : Classical Levenberg-Marquardt Fit statistic : C-statistic C-statistic : 1215.69 Expected C-stat : 1212.71 +/- 49.26 Chi-squared value : 1221.23 Degrees of freedom: 0 W-statistic : 0.00 Contributions of instruments and regions: Ins Reg Bins C-stat Exp C-stat Rms C-stat chi**2 W-stat 1 1 996 1007.73 996.70 44.66 1012.35 0.00 2 1 210 197.87 210.01 20.49 198.61 0.00 3 1 1 3.06 1.00 1.41 3.22 0.00 4 1 1 0.01 1.00 1.41 0.01 0.00 5 1 1 0.31 1.00 1.41 0.32 0.00 6 1 1 0.20 1.00 1.41 0.20 0.00 7 1 1 4.62 1.00 1.41 4.67 0.00 8 1 1 1.89 1.00 1.41 1.87 0.00 2.6.8 Final remarks This is the end of this analysis thread. If you want, you can quit SPEX now: SPEX> quit Thank you for using SPEX! Below, we provide a useful command file. 2.6. PION setup for emission and absorption features in AGN 67 SPEX Help Center Documentation, Release 3.08.02 Define model components and component relations (running scripts) calc.com is the command file tailored for this thread. Load the above command file into SPEX: user@linux:~> spex Welcome user to SPEX version 3.05.00 SPEX> log exe calc 2.7 Fitting two different spectra simultaneously Suppose one wants to fit two observed spectra from different sources (or areas on the sky) simultaneously with two different models, but with certain parameters coupled to each other. This is possible with SPEX! In this thread, we will guide you through the necessary steps to make this work. 68 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 2.7.1 Goal Suppose we have two point sources absorbed by the same molecular cloud in front of them. The elemental abundances in the cloud appear to be non-solar, but are assumed to be constant trough the cloud. Let’s say, we want to fit both sources, while we couple the abundance in the absorber. This requires us to load two different spectra and apply two different source models to them, while constraining some parameters between the models. 2.7.2 Sectors and regions Before we begin, it is good to understand the SPEX definitions of ‘sectors’ and ‘regions’. These SPEX concepts are very useful when creating more complicated fitting setups, but are often considered to be confusing. In this context, it is also useful to know the definition of ‘instruments’, because this is very close to the definition of ‘region’. Sectors are used in SPEX to create multiple separate models, for example to model two different sources or areas of an extended source. Key is that this is a division in model space. Each sector is assigned an integer number such that each model can be identified. Regions are used in SPEX to distinguish different observed spectra, for example observed spectra from different sources or spectra extracted from different extraction regions on the detector. Key is that this is a division in data space. Each observed spectrum is assigned its own integer number to be identified. Regions are usually defined when the spectra and response are combined into one .spo and .res file. Instruments are another division in data space. Spectra from each .spo and .res file combination that are read in, 2.7. Fitting two different spectra simultaneously 69 SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) 2 1 hot 10 Abundance Ne 1.000000 frozen 0.0 1.00E+10 2 1 hot 11 Abundance Na 1.000000 frozen 0.0 1.00E+10 2 1 hot 12 Abundance Mg 1.000000 frozen 0.0 1.00E+10 2 1 hot 13 Abundance Al 1.000000 frozen 0.0 1.00E+10 2 1 hot 14 Abundance Si 1.000000 frozen 0.0 1.00E+10 2 1 hot 15 Abundance P 1.000000 frozen 0.0 1.00E+10 2 1 hot 16 Abundance S 1.000000 frozen 0.0 1.00E+10 2 1 hot 17 Abundance Cl 1.000000 frozen 0.0 1.00E+10 2 1 hot 18 Abundance Ar 1.000000 frozen 0.0 1.00E+10 2 1 hot 19 Abundance K 1.000000 frozen 0.0 1.00E+10 2 1 hot 20 Abundance Ca 1.000000 frozen 0.0 1.00E+10 2 1 hot 21 Abundance Sc 1.000000 frozen 0.0 1.00E+10 2 1 hot 22 Abundance Ti 1.000000 frozen 0.0 1.00E+10 2 1 hot 23 Abundance V 1.000000 frozen 0.0 1.00E+10 2 1 hot 24 Abundance Cr 1.000000 frozen 0.0 1.00E+10 2 1 hot 25 Abundance Mn 1.000000 frozen 0.0 1.00E+10 2 1 hot 26 Abundance Fe 1.000000 frozen 0.0 1.00E+10 2 1 hot 27 Abundance Co 1.000000 frozen 0.0 1.00E+10 2 1 hot 28 Abundance Ni 1.000000 frozen 0.0 1.00E+10 2 1 hot 29 Abundance Cu 1.000000 frozen 0.0 1.00E+10 2 1 hot 30 Abundance Zn 1.000000 frozen 0.0 1.00E+10 2 1 hot file File electr.distrib. 2 2 pow norm Norm (1E44 ph/s/keV) 1.000000 thawn 0.0 1.00E+20 2 2 pow gamm Photon index 2.000000 thawn -10. 10. 2 2 pow dgam Photon index break 0.000000 frozen -10. 10. 2 2 pow e0 Break energy (keV) 1.0000000E+10 frozen 0.0 1.00E+20 2 2 pow b Break strength 0.000000 frozen 0.0 10. 2 2 pow type Type of norm 0.000000 frozen 0.0 1.0 2 2 pow elow Low flux limit (keV) 2.000000 frozen 1.00E-20 1.00E+10 2 2 pow eupp Upp flux limit (keV) 10.00000 frozen 1.00E-20 1.00E+10 2 2 pow lum Luminosity (1E30 W) 2.5786482E-02 frozen 0.0 1.00E+20 Instrument 1 region 1 has norm 1.00000E+00 and is frozen Instrument 1 region 2 has norm 1.00000E+00 and is frozen -------------------------------------------------------------------------------- Fluxes and restframe luminosities between 2.0000 and 10.000 keV sect comp mod photon flux energy flux nr of photons luminosity (phot/m**2/s) (W/m**2) (photons/s) (W) 1 2 pow 2.963082E-03 2.752802E-18 4.000000E+43 2.578606E+28 2 2 pow 2.963082E-03 2.752802E-18 4.000000E+43 2.578606E+28 -------------------------------------------------------------------------------- Fit method : Classical Levenberg-Marquardt Fit statistic : C-statistic C-statistic : 2929139.50 Expected C-stat : 64.11 +/- 16.31 Chi-squared value : 158042.30 Degrees of freedom: 0 W-statistic : 0.00 Obviously, the initial model parameters are quite far off. We also need to fix the hot model to a low temperature to mimic neutral gas: 76 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 2.7. Fitting two different spectra simultaneously 77 SPEX Help Center Documentation, Release 3.08.02 SPEX> par 1 1 t v 2E-4 SPEX> par 2 1 t v 2E-4 SPEX> par 1 1 t stat f SPEX> par 2 1 t stat f SPEX> par 1 1 nh v 1E-3 SPEX> par 2 1 nh v 1E-3 SPEX> par 1 2 norm v 1000 SPEX> par 2 2 norm v 1000 SPEX> calc SPEX> plot Now, the model spectrum is much closer to the best solution, so we can attempt a fit: SPEX> fit which provides the following best fit parameters: SPEX> par show free -------------------------------------------------------------------------------------- ˓→------------ sect comp mod acro parameter with unit value status minimum maximum␣ ˓→lsec lcom lpar 1 1 hot nh X-Column (1E28/m**2) 2.1649615E-04 thawn 0.0 1.00E+20 1 2 pow norm Norm (1E44 ph/s/keV) 2507.844 thawn 0.0 1.00E+20 (continues on next page) 78 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) 1 2 pow gamm Photon index 1.496156 thawn -10. 10. 2 1 hot nh X-Column (1E28/m**2) 1.5288954E-04 thawn 0.0 1.00E+20 2 2 pow norm Norm (1E44 ph/s/keV) 1878.148 thawn 0.0 1.00E+20 2 2 pow gamm Photon index 2.292902 thawn -10. 10. Instrument 1 region 1 has norm 1.00000E+00 and is frozen Instrument 1 region 2 has norm 1.00000E+00 and is frozen -------------------------------------------------------------------------------- Fluxes and restframe luminosities between 2.0000 and 10.000 keV sect comp mod photon flux energy flux nr of photons luminosity (phot/m**2/s) (W/m**2) (photons/s) (W) 1 2 pow 156.468 1.123012E-13 1.971041E+47 1.413442E+32 2 2 pow 41.1973 2.504328E-14 5.188680E+46 3.152038E+31 -------------------------------------------------------------------------------- Fit method : Classical Levenberg-Marquardt Fit statistic : C-statistic C-statistic : 1334.89 Expected C-stat : 1306.19 +/- 49.94 Chi-squared value : 1240.11 Degrees of freedom: 1272 W-statistic : 0.00 And plot: This fit already looks acceptable, but let’s assume that we want to test if the oxygen abundance in the absorber is consistent with solar. To do this, we can couple the oxygen abundances in the two hot models to each other: SPEX> par 2 1 08 couple 1 1 08 SPEX> par 1 1 08 s t SPEX> fit SPEX> par show free -------------------------------------------------------------------------------------- ˓→------------ sect comp mod acro parameter with unit value status minimum maximum␣ ˓→lsec lcom lpar 1 1 hot nh X-Column (1E28/m**2) 2.1453765E-04 thawn 0.0 1.00E+20 1 1 hot 08 Abundance O 1.083166 thawn 0.0 1.00E+10 1 2 pow norm Norm (1E44 ph/s/keV) 2509.920 thawn 0.0 1.00E+20 1 2 pow gamm Photon index 1.496786 thawn -10. 10. 2 1 hot nh X-Column (1E28/m**2) 1.5155401E-04 thawn 0.0 1.00E+20 2 1 hot 08 Abundance O 1.083166 frozen 0.0 1.00E+10 ␣ ˓→1 1 08 2 2 pow norm Norm (1E44 ph/s/keV) 1879.305 thawn 0.0 1.00E+20 (continues on next page) 2.7. Fitting two different spectra simultaneously 79 SPEX Help Center Documentation, Release 3.08.02 80 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) 2 2 pow gamm Photon index 2.293384 thawn -10. 10. Instrument 1 region 1 has norm 1.00000E+00 and is frozen Instrument 1 region 2 has norm 1.00000E+00 and is frozen -------------------------------------------------------------------------------- Fluxes and restframe luminosities between 2.0000 and 10.000 keV sect comp mod photon flux energy flux nr of photons luminosity (phot/m**2/s) (W/m**2) (photons/s) (W) 1 2 pow 156.456 1.122785E-13 1.970944E+47 1.413182E+32 2 2 pow 41.1969 2.504092E-14 5.188782E+46 3.151799E+31 -------------------------------------------------------------------------------- Fit method : Classical Levenberg-Marquardt Fit statistic : C-statistic C-statistic : 1334.81 Expected C-stat : 1306.19 +/- 49.94 Chi-squared value : 1239.62 Degrees of freedom: 1273 W-statistic : 0.00 The example above shows that we can couple parameters across sectors to each other and fit them. Although this may not be a realistic science case, it shows how fitting two different spectra simultaneously can be done and how parameters of different models can be coupled to each other. By the way, the oxygen abundance in this example did not turn out to be significantly different from solar when one calculates the error on oxygen: SPEX> error 1 1 08 parameter C-stat Delta Delta value value parameter C-stat ---------------------------------------------------- 0.838682 1335.33 -0.244484 0.52 0.594198 1336.85 -0.488968 2.03 0.838682 1335.33 -0.244484 0.52 0.761005 1335.70 -0.322161 0.89 0.739144 1335.82 -0.344022 1.01 0.741589 1335.81 -0.341577 0.99 1.32765 1335.17 0.244484 0.36 1.57213 1336.28 0.488968 1.46 1.41755 1335.50 0.334387 0.69 1.48019 1335.78 0.397026 0.97 1.48650 1335.82 0.403330 1.00 Parameter 1 1 08 : 1.0832 Errors: -0.34158 , 0.40333 2.7. Fitting two different spectra simultaneously 81 SPEX Help Center Documentation, Release 3.08.02 2.8 How to use the SPEX user model Some users would like to add their own models to the SPEX program, similar to the local model option in Xspec. Since the developers of SPEX do not have the man power to implement all possible models out there in a SPEX variety, we have devised a quick way of running external models in SPEX. SPEX contains two user models user (User: User defined model (page 234)) and musr (Musr: User defined multiplicative model (page 211)) for additive and multiplicative models respectively. These model components communicate with the external model through an input and output file containing the model parameters, the energy grid and the calculated spectrum. By creating a program that reads in the input parameters and energy grid, calculates the spectrum, and writes the result to an output file in the right format, users have a very flexible way of using any model in SPEX. Since this setup offers many possibilities, we can only show a few examples of how these user model components can be used. We have prepared a helper library for Python and Fortran. 2.8.1 Python The Python helper library for the user model is part of the pyspextools package. A general example of how to user the Python interface to the user model can be found here. As a more specific example we also provide a method to calculate APEC models and import them to SPEX using the Python interface. 2.8.2 Fortran Using the Fortran module moduser, we list a number of example user models below: Use any Xspec model in SPEX The most general way to incorporate Xspec models in SPEX is to call Xspec itself directly by a SPEX user model executable. Here we provide a fortran+tcl example to use an Xspec built-in comptt model. The program comptt-xspec.f90 can be modified to calculate different models. It requires the following files: •Xspec as provided in HEASARC web site. •Module moduser.f90 from our Github site. •Example program comptt-xspec.f90 as provided on our Github page. Modify the commtt-xspec program (optional) The key part of the model can be found in line 18-21 of comptt-xspec.f90. There, the TCL script sets up the model in Xspec. If you need another model than comptt, then change the model name and modify the number of parameters accordingly! 82 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 Compile the executable The program can be compiled in a few simple steps: linux:~/lmodel>gfortran -g-c-o moduser.o moduser.f90 linux:~/lmodel>gfortran -g-c-o comptt-xspec.o comptt-xspec.f90 linux:~/lmodel>gfortran -g-o comptt-xspec comptt-xspec.o moduser.o Use the Xspec model in SPEX Here are the SPEX commands to calculate the Xspec-version comptt model. If you are using a different Xspec model, please adapt the number of parameters to the number of parameters in the Xspec model: SPEX>com user SPEX>par 1exec av ./comptt-xspec SPEX>par 1npar v 6 # The number of parameter needed by the Xspec model SPEX>par 1p01 v 0 ... SPEX>calc Use local Xspec model ismabs in SPEX In this example, we include the Xspec local model called ismabs (Gatuzz et al., 2015) into a SPEX user model executable. The local model consists of a FITS file with atomic data, a ismabs.f90 Fortran file, and a parameter definition file called lmodel_ismabs.dat where the parameters of the model are defined. Since the local model is written in Fortran 90, the easiest way to use it in a SPEX user model is to write a Fortran 90 program that will be the interface between SPEX and the model. In this case, we need the following files and libraries: •The cfitsio library should be installed on the system. •Module moduser.f90 from our Github site. •Example program loc-xspec.f90 as provided by our Github site. •The ismabs local model files as provided on the XSPEC web site. Write a small user program The moduser.f90 file is a library with user callable functions to make it easy to write a user model. This file does not need any editing. The user should only edit the example program loc-xspec.f90 and sometimes also the local XSPEC model, which will be explained later. The example program loc-xspec.f90 looks like this: program locxspec use moduser implicit none integer :: i ! Get input and output filenames call getfilenames(fin,fout,ier) ! Read input file call readprm(trim(fin)) (continues on next page) 2.8. How to use the SPEX user model 83 SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) ! Allocate output arrays call allopar() ! Call local XSPEC model call ismabs(ipar%eg,ipar%neg,ipar%par,1,opar%sener) ! Do not use wener values for now do i=1,opar%neg opar%wener(i)=0.0 enddo ! Write result to output file call writespc(fout) ! Clean up memory call deallpar() end program Explanation of the called routines getfilenames(fin,fout,ier) is a routine to read the file names from the command line. The format of the files and the order on the command line is defined by the user model in SPEX. This routine returns the file names the program needs to read the input parameters and write the result. readprm(trim(fin)) is the routine that reads the input parameters and the input energy grid. It allocates and fills the structure ipar with the needed numbers. allopar() allocates the memory for the output arrays based on the input file. ismabs(ipar%eg,ipar%neg,ipar%par,1,opar%sener) is the actual call of the XSPEC local model. The parameters from the ipar structure contain the input parameters and the opar structure contains the output spectrum. For other local models than ismabs, simply change the name of the routine on this line. writespc(fout) writes the resulting spectrum to the output file. deallpar() deallocates all the allocated variables from the moduser module. Compile the executable In principle, the source files can now be compiled into an executable that the SPEX user model can use. Make sure you have all the necessary files in one directory (see above) and execute the following commands in a terminal: linux:~/lmodel>gfortran -g-c-o moduser.o moduser.f90 linux:~/lmodel>gfortran -g-c-o ismabs.o ismabs.f90 linux:~/lmodel>gfortran -g-c-o loc-xspec.o loc-xspec.f90 linux:~/lmodel>gfortran -g-o loc-xspec loc-xspec.o ismabs.o moduser.o In the last step, it will be clear whether the executable has access to all the necessary functions. In this case, the ismabs model needs cfitsio to read the fits file with atomic data. It also needs a few XSPEC internal functions to read the path for the FITS file. The cfitsio library can be easily linked by adding -lcfitsio to the last command in the sequence above. For the internal Xspec calls, we need to adapt ismabs.f90 slightly. The few calls to the XSPEC routines can be removed and with a slight modification we can also make sure it finds the fits file. This step needs a little programming experience to do it right. Always keep a backup of the original routine. When you are done, repeat the following commands to create the executable: 84 Chapter 2. Analysis threads SPEX Help Center Documentation, Release 3.08.02 linux:~/lmodel>gfortran -g-c-o ismabs.o ismabs.f90 linux:~/lmodel>gfortran -g-o loc-xspec loc-xspec.o ismabs.o moduser.o-L/path/to/cfitsio -lcfitsio The ’-L/path/to/cfitsio’ is optional. You may need to adapt it in case the compiler cannot find libcfitsio.so in the library path. In this flag, you can specify the correct path to libcfitsio.so. Use the Xspec local model in SPEX Start SPEX in a directory where the loc-xspec executable that we just made is located. Since the ismabs model is a multiplicative model, we need to load the musr component. In the example below, we show how a power-law model is absorbed by ismabs in SPEX: SPEX>com po SPEX>com musr SPEX>com rel 1 2 # Link the new loc-xspec executable to the musr component SPEX>par 12exec av ./loc-xspec # The number of parameters is found in ’local_ismabs.dat’, supplied by the Xspec model SPEX>par 12npar v 31 The file local_ismabs.dat also describes the parameters and their limits in order. It is advisable to write a SPEX command file to set the parameters and their ranges to their default values. The order of the parameters should be the same in the musr model and in the local_ismabs.dat file. If the bookkeeping is right, you should be able to issue a calculate command in SPEX and show the absorbed power law in a plot. 2.9 SPEX solution of the relativistic disk reflection By: Liyi Gu Here two sets of disk reflection setups are compared: XILLVER convolved with a SPEITH line profile, and RELXILL. 2.9.1 Setup of xillver*spei The table model based on the X-ray reflection code XILLVER can be incorporated in SPEX through atbl (Atbl: Additive table model (page 175)): SPEX> com atbl SPEX> par 1 1 file av /directory/to/xillver/xillverCp_v3.6.fits SPEX> calc The relativistic line profile can be obtained by applying the convolution model SPEITH: SPEX> com spei SPEX> par 1 2 i couple 1 1 incl SPEX> com rel 1 2 In this way, the inclination of the SPEI component is coupled to that of the XILLVER model, and the relativistic kernel SPEI has been applied to the XILLVER spectrum. 2.9. SPEX solution of the relativistic disk reflection 85 SPEX Help Center Documentation, Release 3.08.02 Output types The possible output types are listed below. Depending on the specific spectral model, not all types are allowed for each spectral component. The keyword in front of each item is the one that should be used for the appropriate syntax. Most options give output as a table with several columns. They are labeled here below with T1 after the keyword. A few options provide only a list of parameters. They are labeled below with T0 after the keyword. General plas (T0): basic plasma properties like temperatures, densities, sound speed, etc. (Output table properties (page ??)) abun (T1): elemental abundances and average charge per element. (Output table properties (page ??)) Ionisation balance & rates, timescales icon (T1): ion concentrations, both with respect to Hydrogen and the relevant elemental abundance. (Output table properties (page ??)) rion (T1): ionization rates per atomic subshell, specified according to the different contributing processes. (Output table properties (page ??)) rate (T1): total ionization, recombination and charge-transfer rates specified per ion. (Output table properties (page ??)) time (T1): recombination time scale per ion according to Bottorf et al. (2000) definition, and relative ion concentrations. Note that the recombination time scale depends upon the hydrogen density, so do not forget to set the relevant density in the model. (Output table properties (page ??)) Energy level populations and processes contributing to it pop (T1): the occupation numbers as well as upwards/downwards loss and gain rates to all quantum levels included. (Output table properties (page ??)) lev (T1): the contributions to the population of the energy levels by various processes: positive for gain, negative for loss (Output table properties (page ??)) elex (T1): the collisional excitation and de-excitation rates for each level, due to collisions with electrons. (Output table properties (page ??)) prex (T1): the collisional excitation and de-excitation rates for each level, due to collisions with protons. (Output table properties (page ??)) rad (T1): the radiative transition rates from each level. (Output table properties (page ??)) two (T1): the two-photon emission transition rates from each level. (Output table properties (page ??)) 92 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 rec (T1): the populating contributions from radiative, dielectronic and charge exchange recombination, as well as inner-shell ionisation (Output table properties (page ??)) Emitted spectrum with continuum and line emission contributions grid (T1): the energy and wavelength grid used in the last evaluation of the spectrum. (Output table properties (page ??)) con (T1): the free-free, free-bound, two-photon and total continuum spectrum, for the last plasma layer of the model. (Output table properties (page ??)) tcon (T1): the free-free, free-bound, two-photon and total continuum spectrum, added for all plasma layers of the model. (Output table properties (page ??)) ccon (T1): list of the ions that contribute to the free-free, free-bound and two-photon continuum emission, for the last plasma layer of the model. (Output table properties (page ??)) tcco (T1): list of the ions that contribute to the free-free, free-bound and two-photon continuum emission, combined for all plasma layers of the model. clin (T1): the continuum, line and total spectrum for each energy bin for the last plasma layer of the model. (Output table properties (page ??)) tcl (T1): the continuum, line and total spectrum for each energy bin added for all plasma layers of the model. (Output table properties (page ??)) line (T1): emission line energies, fluxes, identifications and various other line properties for each line contributing to the spectrum, for the last plasma layer of the model. (Output table properties (page ??)) tlin (T1): emission line energies, fluxes, identifications and various other line properties for each line contributing to the spectrum, combined for all plasma layers of the model. (Output table properties (page ??)) Absorbed spectrum with continuum and line contributions tral (T1): absorption line properties (energies, equivalent widths, optical depths, etc) are listed for the hot, pion, slab, xabs and warm models. (Output table properties for the lines (page ??)) trac (T1): absorption edge properties (energies, equivalent widths. optical depths, etc) are listed for the hot, pion, slab, xabs and warm models. (Output table properties for the lines (page ??)) col (T1): the ionic column densities for the hot, pion, slab, xabs and warm models (Output table properties for the lines (page ??)) wcol (T1): similar to the col option, but in addition the effective ionization parameters and temperatures of the warm model only. warm (T1): the column densities and ionisation parameters of the warm model 3.1. Command syntax 93 SPEX Help Center Documentation, Release 3.08.02 Energy balance for photoionized plasmas only heat (T0): heating and cooling rates for various processes (Output table properties (page ??)) ebal (T1): the energy balance contributions of each layer (only for photoionized plasmas). (Output table properties (page ??)) Non-equilibrium ionisation, supernova remnant and cluster models nei (T1): the history of ionisation parameter and temperature in NEI calculations. (Output table properties (page ??)) snr (T0): hydrodynamical and other properties of the supernova remnant (only for supernova remnant models such as Sedov, Chevalier etc.). (Output table properties (page ??)) clus (T1): the hydrodynamical parameters of the cluster as a function of radius. clup (T1): projected radial profile (photon and energy flux) within specified energy bands, as a function of projected radius. Differential emission measure models dem (T1): the emission measure distribution (for the pdem model) (Output table properties (page ??)) Output devices The following output options are currently implemented: ter: output to the screen of the terminal file: output to an ascii-file; the file name has to beprovided by the user, without exttension (.asc will be appended) fits: output to a file in fits-format; the full file name has to be provided by the user, including any extensions, if desired. Selection, sorting and formatting of the data The data can be sorted according to any column of the table, and the user can make selections of which data to display in the output. Further, for ascii-type of output, more formatting options of the data are possible. The information on sorting, selection and formatting should be provided by the user, in an ascii-file. The user then provides the name of this ascii-file after the “key” word in the command (see the syntax below). Note that this file must be in the directory where you run SPEX, or you should add the relevant path to the file in the name that you provide to SPEX. The file is read each time that you issue the output-option, so if you would like to investigate more output options for the same model, you can use separate files for each item, e.g. a file myplas.dat for the plasma output, and myline.dat for the emission line properties. The selection file contains a number of lines with on each line one and only one instruction for the selection, sorting and formatting. Each line hast to start with one of the words sel,sor or for for selection, sorting and formatting respectively. The order od these lines is arbitrary. After the first keyword the acronym for the relevant column should be given, followed, if relevant, by the numerical range. We specify this in more detail below: 94 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 sel: the user can make up to 10 selections simultaneously. After the sel word, the acronym of the relevant column should be given, followed by two numbers: the minimum and maximum value of the entry in this column that should be used for the selection; all entries with column values below this minimum and above this maximum will be omitted from the final output. If the user wants only one value, for example only atomic number 26, then simply use this number for both the minimum and maximum value. See also the example below. Selection only works for columns with logical, integer or real numbers; you cannot make selection on ascii-columns, but for almost all ascii-type columns, there is an equivalent numerical column that can be used for selection. sor: the user can sort on any column. Only one sorting instruction is allowed. Like for the selection option, only non-ascii columns can be used for sorting. for: for ascii-type of output (both on the terminal and on an ascii-file), the number of significant digits to be displayed can be changed by the user. In general the standard settings are fine, but this option allows to show more, less or no digits at all. It is explained best in the example below. Example: We use here the “line” output option on the terminal for sector 1, component 1. We issue the following command for SPEX: asc ter 1 1 line key mysel.dat And the file mysel.dat (in the current working directory) contains the following text lines: sel iz 26 26 sel jz 16 18 sel ener 0.5 2.0 sor watt for flux 1 for wave 15 for ion 0 What you will see then on your screen is the following: •only lines with atomic number 26 (the acronym for that is “iz”) •only lines with ionistion stage between 16-18 (i.e., Fe XVI to Fe XVIII) •only lines with energy between 0.5 and 2.0 keV •the lines are sorted according to their energy flux (as contained in the column labeled “watt”) •the column flux is displayed with only 1 significant digit behind the period, i.e. you get a number like 2.3E+32, rather than the default for this column of 2.349E+32 •the column with the wavelength (acronym “wave”) will display with 15 signifcant digits, rather than the default 6 digits for this column. •the column with acronym “ion” representing the ion number will not be displayed at all (width 0). See the relevant subsection of Output types (page 92) for the column acronyms to be used in the file for the selection, sorting and formatting of the data. 3.1. Command syntax 95 SPEX Help Center Documentation, Release 3.08.02 Syntax The following syntax rules apply for ascii output: ascdump terminal #i1 #i2 #a : Dump the output for sky sector #i1 and component #i2 to the terminal screen; the type of output is described by the parameter #a which is listed in the table above. ascdump terminal #i1 #i2 #a1 key #a2 : As above, but argument #a2 that follows the mandatory word “key” is the name of a the file setting the sorting, selection and formatting of the columns ascdump file #a1 #i1 #i2 #a2 : As above, but output written to an ascii file with its name given by the parameter #a1. The suffix “.asc” will be appended automatically to this filename. ascdump file #a1 #i1 #i2 #a2 key #a3 : As above, but argument #a3 that follows the mandatory word “key” is the name of a the file setting the sorting, selection and formatting of the columns ascdump fits #a1 #i1 #i2 #a2 : As above, but output written to a fits-format file with its name given by the parameter #a1. Contrary to the file option, no suffix is appended to this filename. ascdump fits #a1 #i1 #i2 #a2 key #a3 : As above, but argument #a3 that follows the mandatory word “key” is the name of a the file setting the sorting, selection and formatting of the columns Warning: Any existing files with the same name will be overwritten. Examples ascdump terminal 3 2 icon : dumps the ion concentrations of component 2 of sky sector 3 to the terminal screen. ascdump file mydump 3 2 icon : dumps the ion concentrations of component 2 of sky sector 3 to an ascii-file named mydump.asc. ascdump fits mydump.fits 3 2 icon : dumps the ion concentrations of component 2 of sky sector 3 to a fits-file named mydump.fits. ascdump terminal 3 2 line key mysel.sel : dumps the emission line properties of component 2 of sky sector 3 to the terminal screen, using selections, sorting and formatting options as described in the file mysel.sel 3.1.4 Ascdump output table properties This section contains the output table properties for the various ascdump commands. 96 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Plas Table 3: Output for option: plas Type Digits Acronym Description Units D 6 te Electron temperature keV D 6 tion Ion temperature keV D 6 tiba kT (ionisation balance) keV D 6 vmic 𝑏=√2𝜎𝑣km/s D 6 cs Sound speed km/s D 6 eden Electron density /m**3 D 6 hden Hydrogen density /m**3 D 6 eide Electron+Ion density /m**3 D 6 rho Mass density kg/m**3 D 6 ed Electron/Hydrogen density D 6 eid (Electron+Ion)/Hydrogen density D 6 denm Mass density / (n𝐻*m𝑝) D 6 epla Plasma frequency energy keV Abun Table 4: Output for option: abun Type Digits Acronym Description Units I 2 iz Z nuclear charge A 2 elem Element name D 4 abus Abundance Solar D 4 abua Abundance Absolute D 4 char Average charge Icon Table 5: Output for option: icon Type Digits Acronym Description Units I 2 iz Z nuclear charge I 2 jz Ionisation stage A 2 elem Element name A 6 stag Ionisation stage I 2 ii ii Iso-electronic sequence I 3 ion Ion number D 4 crel Concentration (relative) D 4 cabs Concentration (absolute) 3.1. Command syntax 97 SPEX Help Center Documentation, Release 3.08.02 Rion Table 6: Output for option: rion Type Digits Acronym Description Units I 2 iz Z nuclear charge I 2 jz Ionisation stage I 2 is Shell number within ion I 2 ii ii Iso-electronic sequence I 3 ion Ion number I 4 ind Shell number A 2 elem Element name A 6 stag Ionisation stage A 5 shel Shell name D 4 pion Photo-ionisation /s/ion D 4 cion Compton-ionisation /s/ion D 4 eion Electron impact ionisation /s/ion D 4 phea Photo ionisation heating W/ion D 4 chea Compton ionisation heating W/ion D 4 ecoo Electron impact ionisation cooling W/ion Rate Table 7: Output for option: rate Type Digits Acronym Description Units I 2 iz Z nuclear charge I 2 jz Ionisation stage I 2 ii ii Iso-electronic sequence I 3 ion Ion number A 2 elem Element name A 6 stag Ionisation stage D 4 rion Total ionisation rate /s/ion D 4 rrec Total Recombination rate /s/ion D 4 rcxi CX ionisation rate /s/ion D 4 rcxr CX recombination rate /s/ion Time Table 8: Output for option: time Type Digits Acronym Description Units I 2 iz Z nuclear charge I 2 jz Ionisation stage I 2 ii ii Iso-electronic sequence I 3 ion Ion number A 2 elem Element name A 6 stag Ionisation stage D 4 trec Recombination time (s) D 4 crel Concentration (relative) 98 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Pop Table 9: Output for option: pop Type Digits Acronym Description Units I 2 iz Z nuclear charge I 2 jz Ionisation stage A 2 elem Element name A 6 stag Ionisation stage I 2 ii ii Iso-electronic sequence I 3 ion Ion number I 5 il level number A 32 lev Configuration and term D 8 ener Energy keV D 6 occ Population D 4 rocc Population / LTE population D 4 gcas Gain Cascades from above (/s) D 3 gexc Gain Excitation from below (/s) D 3 ldow Loss Downwards (/s) D 3 lupp Loss Upwards (/s) D 3 arr Gain from Radiative recombination (/s) D 3 adr Gain from Dielectronic recombin. (/s) D 3 aii Gain from Inner-shell ionisation (/s) D 3 acx Gain from Charge Exchange (CX) (/s) Lev Table 10: Output for option: lev Type Digits Acronym Description Units I 2 iz Z nuclear charge I 2 jz Ionisation stage I 2 ii ii Iso-electronic sequence I 3 ion Ion number A 2 elem Element name A 6 stag Ionisation stage I 5 il lower level I 5 iu upper level D 8 elow Lower level energy keV D 8 eupp Upper level energy keV D 8 de Energy difference keV D 6 eex Electron excitation (/s) D 6 edex Electron de-excitation (/s) D 6 pex Proton excitation (/s) D 6 pdex Proton de-excitation (/s) D 6 rdec Radiative decay (/s) D 6 2p Two photon emission (/s) D 6 rabs Radiative absorption (/s) D 6 rrec Radiative recombination (/s) D 6 drec Dielectronic recombination (/s) D 6 fluo Fluorescence (/s) D 6 cx Charge exchange (/s) D 6 sum Total (/s) A 32 llev Lower configuration + term A 32 ulev Upper configuration + term 3.1. Command syntax 99 SPEX Help Center Documentation, Release 3.08.02 Elex Table 11: Output for option: elex Type Digits Acronym Description Units I 2 iz Z nuclear charge I 2 jz Ionisation stage I 2 ii ii Iso-electronic sequence I 3 ion Ion number A 2 elem Element name A 6 stag Ionisation stage I 5 il lower level I 5 iu upper level A 65 tran Transition D 6 eexc Excitation Energy keV D 4 ups Upsilon D 4 gbar gbar D 4 rexc Excitation rate /s/ion D 4 rdex Deexcitation rate /s/ion Prex Table 12: Output for option: prex Type Digits Acronym Description Units I 2 iz Z nuclear charge I 2 jz Ionisation stage I 2 ii ii Iso-electronic sequence I 3 ion Ion number A 2 elem Element name A 6 stag Ionisation stage I 5 il lower level I 5 iu upper level A 65 tran Transition D 6 eexc Excitation Energy keV D 4 ups Upsilon D 4 gbar gbar D 4 rexc Excitation rate /s/ion D 4 rdex Deexcitation rate /s/ion 100 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Rad Table 13: Output for option: rad Type Digits Acronym Description Units I 2 iz Z nuclear charge I 2 jz Ionisation stage A 2 elem Element name A 6 stag Ionisation stage I 2 ii ii Iso-electronic sequence I 3 ion Ion number I 5 il lower level I 5 iu upper level A 65 tran Transition D 6 ener Energy keV D 6 wav Wavelength Ang D 4 fosc Oscillator strength D 4 a Transition probability /s D 4 arad Total radiative loss probability /s D 6 atot Total decay probability /s D 4 br Branching ratio Two Table 14: Output for option: two Type Digits Acronym Description Units I 2 iz Z nuclear charge I 2 jz Ionisation stage A 2 elem Element name A 6 stag Ionisation stage I 2 ii ii Iso-electronic sequence I 3 ion Ion number I 5 il lower level I 5 iu upper level A 65 tran Transition D 6 ener Energy keV D 6 wav Wavelength Ang D 4 fosc Oscillator strength D 4 a Transition probability /s D 4 arad Total radiative loss probability /s D 6 atot Total decay probability /s D 4 br Branching ratio 3.1. Command syntax 101 SPEX Help Center Documentation, Release 3.08.02 Ebal Table 28: Output for option: ebal Type Digits Acronym Description Units I 4 step Step I 3 i i I 3 itcx CX iter D 3 hden H density /m**3 D 3 eden el density /m**3 D 3 nenh n D 3 te kT electron keV D 3 delt Delta D 3 heat Total heating W/m**3 D 3 cool Total cooling W/m**3 D 15 hcom Heating Compton scattering W/m**3 D 15 hff Heating free-free absorption W/m**3 D 15 hphe Heating photo-electrons W/m**3 D 15 hci Heating Compton ionisation W/m**3 D 15 haug Heating Auger electrons W/m**3 D 15 hcol Heating collis. de-excitation W/m**3 D 15 hex Heating external source W/m**3 D 15 ccom Cooling inverse Compton scatter. W/m**3 D 15 ccoi Cooling electron ionisation W/m**3 D 15 crec Cooling radiative recombination W/m**3 D 15 cffe Cooling free-free emission W/m**3 D 15 ccol Cooling collisional excitation W/m**3 D 15 cdr Cooling dielectronic recombin. W/m**3 D 15 cadi Cooling adiabatic expansion W/m**3 Nei Table 29: Output for option: nei Type Digits Acronym Description Units D 4 uhis U = integral (ne t) s/m**3 D 4 this kT keV Snr Table 30: Output for option: snr Type Digits Acronym Description Units D 6 age Age year D 6 rs Shock radius pc D 6 nh ISM Hydrogen density cm**-3 D 6 eexp Explosion energy 1E43 J D 6 mesh Shocked ejected mass Solar units D 6 mesw swept-up ISM mass Solar units D 6 s ISM density gradient s D 6 n ejecta density gradient n D 6 alfa Hamiltons alpha parameter D 6 nu Hamiltons nu parameter continues on next page 108 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Table 30 – continued from previous page Type Digits Acronym Description Units D 6 ts Shock temperature keV D 6 tej Av. temp. shocked ejecta keV D 6 tism Av. temp. shocked ISM keV D 6 u Ionisation parameter 1E20 s/m**3 D 6 uej Av. ionis. shocked ejecta 1E20 s/m**3 D 6 uism Av. ionis. shocked ISM 1E20 s/m**3 D 6 yej Em. measure shocked ejecta 1E64 /m**3 D 6 yism Em. measure shocked ISM 1E64 /m**3 D 6 rej Av. radius shocked ejecta pc D 6 rism Av. radius shocked ISM pc D 6 aej Av. plasma age shocked ejecta year D 6 aism Av. plasma age shocked ISM year D 6 vej Av. gas velocity shocked ejecta km/s D 6 vism Av. gas velocity shocked ISM km/s D 6 vs Shock velocity km/s D 6 rrs Reverse shock radius pc D 6 rcd Contact discontinuity radius pc D 6 cmax Maximum distance clumps pc D 6 nenh Ratio electron/Hydrogen density D 6 dist Distance kpc Clus Table 31: Output for option: clus Type Digits Acronym Description Units I 3 ir Bin number D 6 r1 Lower radius m D 6 r2 Upper radius m D 6 dr Bin width m D 6 rw Mean radius m D 6 hw Density Hydrogen profile /m**3 D 6 tw Temperature profile keV D 6 pw Pressure profile Pa D 6 yw Emission measure profile /m**3 D 6 sw Turbulent velocity profile km/s D 6 zw Outflow velocity profile km/s D 6 abu Relative abundance 3.1. Command syntax 109 SPEX Help Center Documentation, Release 3.08.02 Clup Table 32: Output for option: clup Type Digits Acronym Description Units I 8 ir Projected bin number D 6 r1 Lower radius m D 6 r2 Upper radius m D 6 dr Bin width m D 6 rw Mean radius m D 6 spro Radial photon flux profile ph/m**2/s D 6 ppro Power profile W/m**2 D 6 scum Cumulative Radial profile ph/s D 6 pcum Cumulative Power profile W Dem Table 33: Output for option: dem Type Digits Acronym Description Units D 4 t Temperature keV D 4 y Em. measure 1E64 m**-3 3.1.5 Bin: rebin the spectrum Overview This command rebins the data (thus both the spectrum file and the response file) in a manner as described in Section Data: read response file and spectrum (page 113). The range to be rebinned can be specified either as a channel range (no units required) or in either any of the following units: keV, eV, Rydberg, Joule, Hertz, Å, nanometer, with the following abbreviations: kev, ev, ryd, j, hz, ang, nm. Note: Usually, the ignore command and the bin command are used around the same time. The safest order is to ignore parts of the spectrum first and then re-bin it. If the bin command is done first and then parts of the spectrum are ignored using a different energy range, then bins at the edges of the energy range could end up being reduced in width. Syntax The following syntax rules apply: bin #r #i : This is the simplest syntax allowed. One needs to give the range, #r, over at least the input data channels one wants to rebin. If one wants to rebin the whole input file the range must be at least the whole range over data channels (but a greater number is also allowed). #i is then the factor by which the data will be rebinned. bin [instrument #i1] [region #i2] #r #i : Here one can also specify the instrument and region to be used in the binning. This syntax is necessary if multiple instruments or regions are used in the data input. bin [instrument #i1] [region #i2] #r #i [unit #a] : In addition to the above here one can also specify the units in which the binning range is given. The units can be eV, Å, or any of the other units specified above. 110 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Examples bin 1:10000 10 : Rebins the input data channel 1:10000 by a factor of 10. bin instrument 1 1:10000 10 : Rebins the data from the first instrument as above. bin 1:40 10 unit a : Rebins the input data between 1 and 40 Å by a factor of 10. 3.1.6 Calculate: evaluate the spectrum Overview This command evaluates the current model spectrum. When one or more instruments are present, it also calculates the model folded through the instrument. Whenever the user has modified the model or its parameters manually, and wants to plot the spectrum or display model parameters like the flux in a given energy band, this command should be executed first (otherwise the spectrum is not updated). On the other hand, if a spectral fit is done (by typing the fit command) the spectrum will be updated automatically and the calculate command needs not to be given. Syntax The following syntax rules apply: calc : Evaluates the spectral model. Examples calc : Evaluates the spectral model. 3.1.7 Comp: create, delete and relate spectral components Overview In fitting or evaluating a spectrum, one needs to build up a model made out of at least 1 component. This set of commands can create a new component in the model, as well as delete any component. Usually we distinguish two types of spectral components in SPEX. The additive components correspond to emission components, such as a power law, a Gaussian emission line, a collisional ionization equilibrium (CIE) component, etc. The second class (dubbed here multiplicative components for ease) consists of operations to be applied to the additive components. Examples are truly multiplicative operations, such as the Galactic absorption, where the model spectrum of any additive component should be multiplied by the transmission of the absorbing interstellar medium, warm absorbers etc. Other operations contained in this class are redshifts, convolutions with certain velocity profiles, etc. The user needs to define in SPEX which multiplicative component should be applied to which additive components, and in which order. The order is important as operations are not always communative. This setting is also done with this component command. If multiple sectors are present in the spectral model or response matrix (see Section Sectors and regions (page ??)) then one has to specify the spectral components and their relation for each sector. The possible components to the model are listed and described in Section Spectral models (page ??). Note that the order that you define the components is not important. However, for each sector, the components are numbered starting from 1, and these numbers should be used when relating the multiplicative components to the additive components. 3.1. Command syntax 111 SPEX Help Center Documentation, Release 3.08.02 If you want to see the model components and the way they are related, type “model show”. Warning: If in any of the commands as listed above you omit the sector number or sector number range, the operation will be done for all sectors that are present. For example, having 3 sectors, the “comp pow” command will define a power law component for each of the three sectors. If you only want to define/delete/relate the component for one sector, you should specify the sector number(s). In the very common case that you have only one sector you can always omit the sector numbers. Warning: After deleting a component, all components are re-numbered! So if you have components 1,2,3 for example as pow, cie, gaus, and you type “comp del 2”, you are left with 1=pow, 2=gaus. Syntax The following syntax rules apply: comp [#i:] #a : Creates a component #a as part of the model for the (optional) sector range #i: comp delete [#i1:] #i2: : Deletes the components with number from range #i2: for sector range (optional) #i1. See also the warning above comp relation [#i1:] #i2: #i3,...,#in : Apply multiplicative components #i3, ..., #in (numbers) in this order, to the additive components given in the range #i2: of sectors in the range #i1 (optional). Note that the multiplicative components must be separated by a “,” Examples comp pow : Creates a power-law component for modeling the spectrum for all sectors that are present. comp 2 pow : Same as above, but now the component is created for sector 2. comp 4:6 pow : Create the power law for sectors 4, 5 and 6 com abs : Creates a Morrison & McCammon absorption component. comp delete 2 : Deletes the second created component. For example, if you have 1 = pow, 2 = cie and 3 = gaus, this command delets the cie component and renumbers 1 = pow, 2 = gaus comp del 1:2 : In the example above, this will delete the pow and cie components and renumbers now 1 = gaus comp del 4:6 2 : If the above three component model (pow, cie, gaus) would be defined for 8 sectors (numbered 1–8), then this command deletes the cie component (nr. 2) for sectors 4–6 only. comp rel 1 2 : Apply component 2 to component 1. For example, if you have defined before with “comp pow” and “comp “abs” a power law and galactic absorption, the this command tells you to apply component 2 (abs) to component 1 (pow). comp rel 1 5,3,4 : Taking component 1 a power law (pow), component 3 a redshift operation (reds), component 4 galactic absorption (abs) and component 5 a warm absorber (warm), this command has the effect that the power law spectrum is multiplied first by the transmission of the warm absorber (5=warm), then redshifted (3=reds) and finally multiplied by the transmission of our galaxy (4=abs). Note that the order is always from the source to the observer! comp rel 1:2 5,3,4 : Taking component 1 a power law (pow), component 2 a gaussian line (gaus), and 3–5 as above, this model applies multiplicative components 5, 3 and 4 (in that orer) to the emission spectra of both component 1 (pow) and 2 (cie). comp rel 7:8 1:2 5,3,4 : As above, but only for sectors 7 and 8 (if those are defined). comp rel 3 0 : Remove all relations from component 3. 112 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 3.1.8 Data: read response file and spectrum Overview In order to fit an observed spectrum, SPEX needs a spectral data file and a response matrix. These data are stored in FITS format, tailored for SPEX (see section Response formats (page ??)). The data files need not necessarily be located in the same directory, one can also give a pathname plus filename in this command. Warning: Filenames should be entered in the data command without their extension. For the files response.res and spectrum.spo, the data command would look like: data response spectrum. Syntax The following syntax rules apply: data #a1 #a2 : Read response matrix #a1 and spectrum #a2 data delete instrument #i : Remove instrument #i from the data set data merge sum #i: : Merge instruments in range #i: to a single spectrum and response matrix, by adding the data and matrices data merge aver #i: : Merge instruments in range #i: to a single spectrum and response matrix, by averaging the data and matrices data save #i #a [overwrite] : Save data #a from instrument #i with the option to overwrite the existent file. SPEX automatically tags the .spo extension to the given file name. No response file is saved. data show : Shows the data input given, as well as the count (rates) for source and background, the energy range for which there is data the response groups and data channels. Also the integration time and the standard plotting options are given. Examples data mosresp mosspec : read a spectral response file named mosresp.res and the corresponding spectral file mosspec.spo. Hint, although 2 different names are used here for ease of understanding, it is eased if the spectrum and response file have the same name, with the appropriate extension. data delete instrument 1 : delete the first instrument data merge aver 3:5 : merge instruments 3–5 into a single new instrument 3 (replacing the old instrument 3), by averaging the spectra. Spectra 3–5 could be spectra taken with the same instrument at different epochs. data merge sum 1:2 : add spectra of instruments 1–2 into a single new instrument 1 (replacing the old instrument 1), by adding the spectra. Useful for example in combining XMM-Newton MOS1 and MOS2 spectra. data save 1 mydata : Saves the data from instrument 1 in the working directory under the filename of mydata.spo data /mydir/data/mosresp /mydir/data/mosspec : read the spectrum and response from the directory /mydir/data/ 3.1.9 DEM: differential emission measure analysis Overview SPEX offers the opportunity to do a differential emission measure analysis. This is an effective way to model multitemperature plasmas in the case of continuous temperature distributions or a large number of discrete temperature components. The spectral model can only have one additive component: the DEM component that corresponds to a multitemperature structure. There are no restrictions to the number of multiplicative components. For a description of 3.1. Command syntax 113 SPEX Help Center Documentation, Release 3.08.02 the DEM analysis method see document SRON/SPEX/TRPB05 (in the documentation for version 1.0 of SPEX), Mewe et al. (1994),Mewe et al. (1995) and Kaastra et al. (1996). SPEX has 5 different dem analysis methods implemented, as listed shortly below. We refer to the above papers for more details. 1. reg – Regularization method (minimizes second order derivative of the DEM; advantage: produces error bars; disadvantage: needs fine-tuning with a regularization parameter and can produce negative emission measures. 2. clean – Clean method: uses the clean method that is widely used in radio astronomy. Useful for “spiky emission measure distributions. 3. poly – Polynomial method: approximates the DEM by a polynomial in the log 𝑇−log 𝑌plane, where 𝑌is the emission measure. Works well if the DEM is smooth. 4. mult – Multi-temperature method: tries to fit the DEM to the sum of Gaussian components as a function of log 𝑇. Good for discrete and slightly broadened components, but may not always converge. 5. gene – Genetic algorithm: using a genetic algorithm try to find the best solution. Advantage: rather robust for avoiding local subminima.Disadvantage: may require a lot of cpu time, and each run produces slightly different results (due to randomization). In practice to use the DEM methods the user should do the following steps: 1. Read and prepare the spectral data that should be analysed 2. Define the dem model with the “comp dem” command 3. Define any multiplicative models (absorption, redshifts, etc.) that should be applied to the additive model 4. Define the parameters of the dem model: number of temperature bins, temperature range, abundances etc. 5. Give the “dem lib” command to create a library of isothermal spectra. 6. Do the dem method of choice (each one of the five methods outlined above) 7. For different abundances or parameters of any of the spectral components, first the “dem lib” command must be re-issued! Syntax The following syntax rules apply: dem lib : Create the basic DEM library of isothermal spectra dem reg auto : Do DEM analysis using the regularization method, using an automatic search of the optimum regularization parameter. It determines the regularisation parameter 𝑅in such a way that 𝜒2(𝑅) = 𝜒2(0)[1 + 𝑠√︀2/(𝑛−𝑛T]where the scaling factor 𝑠= 1,𝑛is the number of spectral bins in the data set and 𝑛Tis the number of temperature components in the DEM library. dem reg auto #r : As above, but for the scaling factor 𝑠set to #r. dem reg #r : Do DEM analysis using the regularization method, using a fixed regularization parameter 𝑅=#r. dem chireg #r1:#r2 #i : Do a grid search over the regularization parameter 𝑅, with #i steps and 𝑅 distributed logarithmically between #r1 and #r2. Useful to scan the 𝜒2(𝑅)curve whenever it is complicated and to see how much “penalty’ (negative DEM values) there are for each value of 𝑅. dem clean : Do DEM analysis using the clean method dem poly #i : Do DEM analysis using the polynomial method, where #i is the degree of the polynomial dem mult #i : Do DEM analysis using the multi-temperature method, where #i is the number of broad components dem gene #i1 #i2 : Do DEM analysis using the genetic algorithm, using a population size given by #i1 (maximum value 1024) and #i2 is the number of generations (no limit, in practice after ∼100 generations not much change in the solution. Experiment with these numbers for your practical case. 114 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 dem read #a : Read a DEM distribution from a file named #a which automatically gets the extension “.dem”. It is an ascii file with at least two columns, the first column is the temperature in keV and the second column the differential emission measure, in units of 1064 m:math:^{-3} keV:math:^{-1}. The maximum number of data points in this file is 8192. Temperature should be in increasing order. The data will be interpolated to match the temperature grid defined in the dem model (which is set by the user). dem save #a : Save the DEM to a file #a with extension “.dem”. The same format as above is used for the file. A third column has the corresponding error bars on the DEM as determined by the DEM method used (not always relevant or well defined, exept for the regularization method). dem smooth #r : Smoothes a DEM previously determined by any DEM method using a block filter/ Here #r is the full width of the filter expressed in 10 log 𝑇. Note that this smoothing will in principle worsen the 𝜒2of the solution, but it is sometimes useful to “wash out” some residual noise in the DEM distribution, preserving total emission measure. Examples dem lib : create the DEM library dem reg auto : use the automatic regularization method dem reg 10. : use a regularization parameter of 𝑅= 10 in the regularization method dem chireg 1.e-5:1.e5 11 : do a grid search using 11 regularisation parameters 𝑅given by 10−5,10−4, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 104,105. dem clean : use the clean method dem poly 7 : use a 7th degree polynomial method dem gene 512 128 : use the genetic algorithm with a population of 512 and 128 generations dem save mydem : save the current dem on a file named mydem.dem dem read modeldem : read the dem from a file named modeldem.dem dem smooth 0.3 : smooth the DEM to a temperature width of 0.3 in 10 log 𝑇(approximately a factor of 2 in temperature range). Recommended citation: Mewe et al. (1995). 3.1.10 Distance: set the source distance Overview One of the main principles of SPEX is that spectral models are in principle calculated at the location of the X-ray source. Once the spectrum has been evaluated, the flux received at Earth can be calculated. In order to do that, the distance of the source must be set. SPEX allows for the simultaneous analysis of multiple sky sectors. In each sector, a different spectral model might be set up, including a different distance. For example, a foreground object that coincides partially with the primary X-ray source has a different distance value. The user can specify the distance in a number of different units. Allowed distance units are shown in the table below. 3.1. Command syntax 115 SPEX Help Center Documentation, Release 3.08.02 Table 34: SPEX distance units Abbrevation Unit spex internal SPEX units of 1022 m (this is the default) m meter au Astronomical Unit, 1.49597892 1011 m ly lightyear, 9.46073047 1015 m pc parsec, 3.085678 1016 m kpc kpc, kiloparsec, 3.085678 1019 m mpc Mpc, Megaparsec, 3.085678 1022 m z redshift units for the given cosmological parameters cz recession velocity in km/s for the given cosmological parameters The default unit of 1022 m is internally used in all calculations in SPEX. The reason is that with this scaling all calculations ranging from solar flares to clusters of galaxies can be done with single precision arithmetic, without causing underflow or overflow. For the last two units (z and cz), it is necessary to specify a cosmological model. Currently this model is simply described by H0,Ω𝑚(matter density), ΩΛ(cosmological constant related density), and Ω𝑟(radiation density). At startup, the values are: H0: 70 km/s/Mpc , Ω𝑚: 0.3 , ΩΛ: 0.7 , Ω𝑟: 0.0 i.e. a flat model with cosmological constant. However, the user can specify other values of the cosmological parameters. Note that the distance is in this case the luminosity distance. Note that the previous defaults for SPEX (H0= 50,𝑞0= 0.5) can be obtained by putting H0= 50,Ω𝑚= 1, ΩΛ= 0 and Ω𝑟= 0. Warning: When H0or any of the Ωis changed, the luminosity distance will not change, but the equivalent redshift of the source is adjusted. For example, setting the distance first to z=1 with the default H0=70 km/s/Mpc results into a distance of 2.039 1026 m. When H0is then changed to 100 km/s/Mpc, the distance is still 2.168 1026 m, but the redshift is adjusted to 1.3342. Warning: In the output also the light travel time is given. This should not be confused with the (luminosity) distance in light years, which is simply calculated from the luminosity distance in m! Syntax The following syntax rules apply to setting the distance: distance [sector #i:] #r [#a] : set the distance to the value #r in the unit #a. This optional distance unit may be omittted. In that case it is assumed that the distance unit is the default SPEX unit of 1022 m. The distance is set for the sky sector range #i:. When the optional sector range is omitted, the distance is set for all sectors. distance show : displays the distance in various units for all sectors. distance h0 #r : sets the Hubble constant H0to the value #r. distance om #r : sets the Ω𝑚parameter to the value #r. distance ol #r : sets the ΩΛparameter to the value #r. distance or #r : sets the Ω𝑟parameter to the value #r. 116 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Examples distance 2 : sets the distance to 2 default units, i.e. to 2E22 m. distance 12.0 pc : sets the distance for all sectors to 12 pc. distance sector 3 0.03 z : sets the distance for sector 3 to a redshift of 0.03. distance sector 2 : 4 50 ly : sets the distance for sectors 2-4 to 50 lightyear. distance h0 50. : sets the Hubble constant to 50 km/s/Mpc. distance om 0.27 : sets the matter density parameter Ω𝑚to 0.27 distance show : displays the distances for all sectors, see the example below for the output format. SPEX> di 100 mpc Distances assuming H0 = 70.0 km/s/Mpc, Omega_m = 0.300 Omega_Lambda = 0.700 Omega_r␣ ˓→= 0.000 Sector m A.U. ly pc kpc Mpc redshift cz ␣ ˓→age(yr) -------------------------------------------------------------------------------------- ˓→-------- 1 3.086E+24 2.063E+13 3.262E+08 1.000E+08 1.000E+05 100.0000 0.0229 6878.7␣ ˓→3.152E+08 -------------------------------------------------------------------------------------- ˓→-------- 3.1.11 Egrid: define model energy grids Overview SPEX operates essentially in two modes: with an observational data set (read using the data commands), or without data, i.e. theoretical model spectra. In the first case, the energy grid needed to evaluate the spectra is taken directly from the data set. In the second case, the user can choose his own energy grid. The energy grid can be a linear grid, a logarithmic grid or an arbitrary grid read from an ascii-file. It is also possible to save the current energy grid, whatever that may be. In case of a linear or logarithmic grid, the lower and upper limit, as well as the number of bins or the step size must be given. The following units can be used for the energy or wavelength: keV (the default), eV, Ryd, J, Hz, Å, nm. When the energy grid is read or written from an ascii-file, the file must have the extension “.egr”, and contains the bin boundaries in keV, starting from the lower limit of the first bin and ending with the upper limit for the last bin. Thus, the file has 1 entry more than the number of bins! In general, the energy grid must be increasing in energy and it is not allowed that two neighbouring boundaries have the same value. Finally, the default energy grid at startup of SPEX is a logarithmic grid between 0.001 and 100 keV, with 8192 energy bins. Warning: When a dataset is already loaded, the egrid command overwrites the model grid set by the response matrix. This can cause problems when convolving the model spectrum with the matrix. Therefore, if you need a special energy grid (for instance, extended energy range needed for photoionisation models such as pion), first issue the egrid command, and after that read your data files. 3.1. Command syntax 117 SPEX Help Center Documentation, Release 3.08.02 fit statistic cstat : Use the C-statistic for all instruments for the minimisation. This is the default at start-up. fit statistic wstat : Use the W-statistic for all instruments for the minimisation. fit statistic chi2 #i1: #i2: : Change to the 𝜒2statistic for the instrument (range) #i1: and region (range) #i2: for the minimisation. fit statistic cstat #i1: #i2: : Change to the C-statistic for the instrument (range) #i1: and region (range) #i2: for the minimisation. This is the default at start-up. fit statistic wstat #i1: #i2: : Change to the W-statistic for the instrument (range) #i1: and region (range) #i2: for the minimisation. fit method classical : Use the classical Levenberg-Marquardt minimisation as the fitting method. fit method simplex : Use simplex minimisation as the fitting method. fit method anneal : Use simulated annealing minimisation as the fitting method. fit ann rt #r : Change the temperature reduction factor. Default value is 0.85. fit ann t #r : Change the start temperature. Default value: 5. fit ann eps #r : Change the convergence criterion 𝜖. If the final function values from the last 4 temperatures differ from the corresponding value at the current temperature by less than 𝜖and the final function value at the current temperature differs from the current optimal function value by less than 𝜖, execution terminates. Default value is 0.10. fit ann vm #r : The step length vector. On input it should encompass the region of interest given the starting value X. For point X(I), the next trial point is selected is from X(I) - VM(I) to X(I) + VM(I). Since VM is adjusted so that about half of all points are accepted, the input value is not very important (i.e. if the value is off, the algorithm adjusts VM to the correct value). Default value: 1. fit ann ns #i : Number of cycles. After 𝑛𝑠 *𝑛function evaluations, where 𝑛is the number of free parameters, each element of the vector VM is adjusted so that approximately half of all function evaluations are accepted. The vector VM controls the relative step size for the free parameters. Default value for 𝑛𝑠 is 20. fit ann max #i : The maximum number of function evaluations. If during iteration more than this maximum nunber of evaluations is used, the process terminates with an error message (not converged). Default value: 100000. fit ann print #r : Controls the printing of details of th simulated annealing process during the fit. Allowed values 0 to 3. Only relevant for debugging your problem, may give a lot of output depending on its value. Default value: 0 (no printing). This is overruled by the fit print ... command, which for the simulated annealing method prints every new set of parameters and plots its spectrum if a new minimum is found. Examples fit : Performs a spectral fit. At the end the list of best fit parameters is printed, and if there is a plot this will be updated. fit print 1 : If followed by the above fit command, the intermediate fit results are printed to the screen, and the plot of spectrum, model or residuals is updated (provided a plot is selected). fit iter 10 : Stop the after 10 iterations or earlier if convergence is reached before ten iterations are completed. fit iter 0 : Stop fitting only after full convergence (default). fit weight model : Instead of using the data for the statistical weights in the fit, use the current model. fit weight data : Use the data instead for the statistical weights in the fit. fit method clas : Use the classical Leveberg-Marquardt method to find minima. fit ann rt 0.5 : changes the temperature reduction factor for simulated annealing to 0.5. fit statistic chi2 : Switch from C-statistics to 𝜒2(for all instruments and regions). fit statistic cstat : Switch back to C-statistics. fit statistic chi2 2 3:4 : Switch to 𝜒2statistics for instrument 2, regions 3 to 4. 124 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 3.1.15 Ibal: set type of ionisation balance Overview For the plasma models, different ionisation balance calculations are possible. Currently, the default set is Urdampilleta et al. (2017) The Table below lists the possible options. Table 36: Ionisation balance modes Abbrevation Reference reset default (=u17) ar85 Arnaud & Rothenflug (1985) ar92 Arnaud & Raymond (1992) for Fe, Arnaud & Rothenflug (1985) for the other elements bryans09 Bryans et al. (2009) u17 Urdampilleta et al. (2017) (default) Syntax The following syntax rules apply: ibal #a : Set the ionisation balance to set #a with #a in the table above. ibal show : Show the currently active ionisation balance. Examples ibal reset : Take the standard ionisation balance ibal ar85 : Take the Arnaud & Rothenflug ionisation balance 3.1.16 Ignore: ignoring part of the spectrum Overview If one wants to ignore part of a data set in fitting the input model, as well as in plotting this command should be used. The spectral range one wants to ignore can be specified as a range in data channels or a range in wavelength or energy. Note that the first number in the range must always be smaller or equal to the second number given. If multiple instruments are used, one must specify the instrument as well. If the data set contains multiple regions, one must specify the region as well. So per instrument/region one needs to specify which range to ignore. The standard unit chosen for the range of data to ignore is data channels. To undo ignore, see the use command (Use: reuse part of the spectrum (page 150)). The range to be ignored can be specified either as a channel range (no units required) or in either any of the following units: keV, eV, Rydberg, Joule, Hertz, Å, nanometer, with the following abbrevations: kev, ev, ryd, j, hz, ang, nm. 3.1. Command syntax 125 SPEX Help Center Documentation, Release 3.08.02 Syntax The following syntax rules apply: ignore [instrument #i1] [region #i2] #r : Ignore a certain range #r given in data channels of instrument #i1 and region #i2. The instrument and region need to be specified if there are more than 1 data sets in one instrument data set or if there are more than 1 data set from different instruments. ignore [instrument #i1] [region #i2] #r unit #a : Same as the above, but now one also specifies the unites #a in which the range #r of data points to be ignored are given. The units can be either Å (ang) or (k)eV. Examples ignore 1000:1500 : Ignores data channels 1000 till 1500. ignore region 1 1000:1500 : Ignore data channels 1000 till 1500 for region 1. ignore instrument 1 region 1 1000:1500 : Ignores the data channels 1000 till 1500 of region 1 from the first instrument. ignore instrument 1 region 1 1:8 unit ang : Same as the above example, but now the range is specified in units of Å instead of in data channels. ignore 1:8 unit ang : Ignores the data from 1 to 8 Å, only works if there is only one instrument and one region included in the data sets. 3.1.17 Ion: select ions for the plasma models Overview For the plasma models, it is possible to include or exclude specific groups of ions from the line calculations. This is helpful if a better physical understanding of the (atomic) physics behind the spectrum is requested. In addition, there is an option to mute particular lines in the spectrum for specific analysis purposes. There are two main reasons why the user may use this option: computational speed and educational reasons. Computational speed The first reason is accelerating the calculations. For complex spectral models, the computational time may be long due to the large number of ions and transitions that need to be taken into account, in particular for the line calculations. By reducing the number of ions in the calculation, or using a maximum principal quantum number, or other reductions, allow to make the calculations faster by simply skipping the line emission from those transitions. Note that obviously this leads to less accurate spectra as compared to the full calculation. Technically, it is done by using the “ions ignore ...” or “ions use ...” commands (for getting rid of, or including line emission from specific ions), or the “ions nmax ...” or “ions lmax ...” commands, to reduce the maximum principal quantum number 𝑛and the maximum orbital quantum number 𝑙, respectively. Also, by using the “ions new ...”, “ions qc ...”, and “ions old ...” commands one may switch between the default (new) spex calculations, the quick-cie mode, and the (old) mekal calculations. See Optimizing model performance (page 240) for more details. A minor note must be made here: when excluding a single ion, the calculations becomes less accurate, because level populations of ions depend also on how many ionisations or recombinations occur from levels of neighbouring ions. By ignoring an ion, it also cannot contribute to its neighbours. Currently these settings only affect the line emission; in the calculation of the ionisation balance as well as the continuum always all ions are taken into account (unless of course the abundance is put to zero). 126 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Diagnostics & education The second reason to include or exclude ions is for diagnostic or educational reasons. It may be of interest to know how the spectrum of a single ion looks, or how the total spectrum would look without an ion. For such cases, SPEX has the “ions mute ...” or its inverse “ions unmute ...” commands. Contrary to the use/ignore commands, with this command the full spectrum is calculated, and only at the last step the contribution of the ion is muted or unmuted. Also, contrary to the use/ignore commands, this option works on the full spectrum (continuum and lines, both in emission and absorption). Finally, take care when combining the use/ignore with the mute/unmute commands. Whenever you ignore an ion, it will not be calculated and in those cases the mute or unmute commands are not effective. Finally, when you use the mute/unmute commands, it will also affect the ascii output for a few important output options, like the “line” and “tra” options for line emission or absorption. Warning: When using the pion model with this option, you will get a different solution, because it affects the heating and cooling rates, and thus the ionisation balance (equilibrium temperature). Exception is when you use the tmod=1 option for pion, which forces the temperature to be equal to what you prescribe through parameter tinp. For diagnosing the heating/cooling contributions of ions or elements, it is therefore recommended to run first the model with all ions, make an ascii-output of the plasma parameters, take the temperature from there as the “tinp” parameter, and set tmod=1. You can play then with the mute/unmute command. Quicklook A new quicklook mode is introduced in SPEX 3.0. This mode can greatly reduce computation time by excluding the atomic levels of outer shells that barely affect the obtained spectrum. The maximum quantum numbers 𝑛and 𝑙of Hydrogen-like ions are provided in the table below. The quicklook mode is enabled by the command: SPEX> ions ql To undo the quicklook mode, just type ions use all. Warning: This mode will not work for CX model, since electron captured by charge exchange usually populate the outer shells. Table 37: Preset maximum 𝑛and 𝑙for quicklook mode (H-like) Ion max. 𝑛max. 𝑙Ion max. 𝑛max. 𝑙Ion max. 𝑛max. 𝑙 C VI 16 3 N VII 16 3 O VIII 16 5 F IX 2 1 Ne X 16 4 Na XI 9 2 Mg XII 16 4 Al XIII 9 2 Si XIV 16 4 P XV 5 1 S XVI 16 4 Cl XVII 4 1 Ar XVIII 13 2 K XIX 4 1 Ca XX 9 2 Sc XXI 2 1 Ti XXII 4 1 V XXIII 2 1 Cr XXIV 5 1 Mn XXV 4 1 Fe XXVI 16 4 Co XXVII 2 1 Ni XXVIII 8 2 Cu XXIX 2 1 Zn XXX 2 1 Note: the quicklook mode is different from the quick CIE mode set by ions qc or var calc qc. 3.1. Command syntax 127 SPEX Help Center Documentation, Release 3.08.02 QC mode QC, or the quick cie mode, is introduced in SPEX v3.08 for a quick evalulation of CIE-family models, including CIE,dem,pdem,wdem,cf, and clus. This mode can be turned on and off for individual ions or elements. Note: ion qc is only valid when the system flag var calc is set to new or qc. Ewlim An alternative, tunable method to reduce the computation time is the ewlim mode. For a grid of temperatures and non-equilibrium ionisation or recombination parameters, for each spectral line in SPEX the maximum equivalent width 𝑊has been computed. The equivalent width is here the line intensity divided by the continuum intensity for the same model. From this, we compute for each line 𝑄=𝑊/𝐸 with E the energy of the line. This is a measure of the relative intensity of the line for a given spectral resolution. Further, for each line we register the maximum principal quantum number 𝑛. The user now can select a critical value for 𝑄𝑐(or actually, the 10log of this quantity). Now for each principal quantum number, we check whether there is any line with 𝑄>𝑄𝑐. If so, all lines with this principal quantum number are retained, but if none of thelines is tronger than the threshold, we will discard lines from that pricipal quantum number. In this way we determine the maximum principal quantum number for each ion, given the value for 𝑄𝑐. Higher values for 𝑄𝑐means less lines, because more lines will be deemed to be too weak. A performance test shows that a speed gain of a factor of 2-3 gan be reached with this method. It is in particular useful for error searches on parameter values. Try experimenting with this. Warning: it is advised, after obtaining a best fit with some setting of ewlim, to set the parameter ewlim to -25 (including all lines), issue a calculate command, and compare the cstat value of this model with the cstat value of your fit. Dicide if this is good enough for your purpose. Mute lines A new feature since version 3.06.01 is the line mute command. In some cases, when users what to study a particular line, they want to remove the line from the spectrum to replace it, for example, with a delta line or Gaussian. The ions mute line command allows to mute up to 10 spectral lines identified from the asc ter line output. Please note that this command only works for SPEXACT v3 (var calc new). When SPEXACT v3 is enabled, the ascdump line command (Ascdump: ascii output of plasma and spectral properties (page 91)) will show a line list with line id numbers: 1 O VIII 1s 2S1/2 - 2p 2P1/2 0. ˓→6534939 18.97252 1.418E+42 1.689E-06 3.957E-04 2 O VIII 1s 2S1/2 - 2s 2S1/2 0. ˓→6535030 18.97225 1.011E+39 1.419E-12 3.957E-04 3 O VIII 1s 2S1/2 - 2p 2P3/2 0. ˓→6536802 18.96711 2.834E+42 1.691E-06 3.958E-04 In the example of O VIII above, the line id is listed as an integer in the first column before O VIII. To not show the O VIII Lya lines in the spectrum, they can be muted with the command: SPEX> ions mute line 1 ion 8 8 SPEX> ions mute line 3 ion 8 8 Where the number behind line is the line id, and the numbers behind ion are the atomic number and ionisation stage, respectively. If necessary, the lines can be unmuted with the ions unmute line command which has a very similar syntax. 128 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Syntax The following syntax rules apply: ions show : Display the list of ions currently taken into account ions ewlim #r : use only the strongest lines using criterion #r. useful numbers for the X-ray range are typically the range between -4 and 4; the minimum and maximum allowed values are -25 and 7. A higher value means faster computation but less accurate spectra. ions use all : Use all possible ions in the calculation of the line spectrum. This is the default at startup of the program. ions use iso #i: : Use ions of the iso-electronic sequences indicated by #i: in the line spectrum ions use z #i: : Use ions with the atomic numbers indicated by #i: in the line spectrum ions use ion #i1 #i2: : Use ions with the atomic number indicated by #i1 and ionisation stage indicated by #i2: in the line spectrum ions ignore all : Ignore all possible ions in the calculation of the line spectrum ions ignore iso #i: : Ignore ions of the iso-electronic sequences indicated by #i: in the line spectrum ions ignore z #i: : Ignore ions with the atomic numbers indicated by #i: in the line spectrum ions ignore ion #i1 #i2: : Ignore ions with the atomic number indicated by #i1 and ionisation stage indicated by #i2: in the line spectrum ions unmute all : Display the contributions of all possible ions in the final spectrum. This is the default at startup of the program. ions unmute iso #i: : Display ions of the iso-electronic sequences indicated by #i: in the spectrum ions unmute z #i: : Display ions with the atomic numbers indicated by #i: in the spectrum ions unmute ion #i1 #i2: : Display ions with the atomic number indicated by #i1 and ionisation stage indicated by #i2: in the spectrum ions mute all : Ignore all possible ions in the display of the spectrum; will create a zero emission or transmission spectrum! Most useful when followed immieditately by a “ions unmute ...” command ions mute iso #i: : Do not display ions of the iso-electronic sequences indicated by #i: in the spectrum ions ignore z #i: : Do not display ions with the atomic numbers indicated by #i: in the spectrum ions ignore ion #i1 #i2: : Do not display ions with the atomic number indicated by #i1 and ionisation stage indicated by #i2: in the spectrum ions nmax all #i: : Set maximum 𝑛for all ions ions nmax iso #i1: #i2 : Set maximum 𝑛to #i2 for isoelectronic sequence indicated by #i1 ions nmax z #i1: #i2 : Set maximum 𝑛to #i2 for atomic number indicated by #i1 ions nmax ion #i1 #i2: #i3 : Set maximum 𝑛to #i3 for atomic number indicated by #i1 and ionisation stage indicated by #i2. ions lmax all #i: : Set maximum 𝑙for all ions ions lmax iso #i1: #i2 : Set maximum 𝑙to #i2 for isoelectronic sequence indicated by #i1 ions lmax z #i1: #i2 : Set maximum 𝑙to #i2 for atomic number indicated by #i1 ions lmax ion #i1 #i2: #i3 : Set maximum 𝑙to #i3 for atomic number indicated by #i1 and ionisation stage indicated by #i2. ions old all : Force the old calculation for all ions ions old iso #i1: : Force the old calculation for the isoelectronic sequence indicated by #i1 ions old z #i1: : Force the old calculation for atomic number indicated by #i1 ions old ion #i1 #i2: : Force the old calculation for atomic number indicated by #i1 and ionisation stage indicated by #i2. ions qc all : Force the quick-cie calculation for all ions ions qc iso #i1: : Force the quick-cie calculation for the isoelectronic sequence indicated by #i1 ions qc z #i1: : Force the quick-cie calculation for atomic number indicated by #i1 ions qc ion #i1 #i2: : Force the quick-cie calculation for atomic number indicated by #i1 and ionisation stage indicated by #i2. 3.1. Command syntax 129 SPEX Help Center Documentation, Release 3.08.02 ions new all : Force the new calculation for all ions ions new iso #i1: : Force the new calculation for the isoelectronic sequence indicated by #i1 ions new z #i1: : Force the new calculation for atomic number indicated by #i1 ions new ion #i1 #i2: : Force the new calculation for atomic number indicated by #i1 and ionisation stage indicated by #i2. ions mute line #i1 ion #i2 #i3 : Mute a line with id #i1 for element #i2 at ionisation stage #i3. ions unmute line #i1 ion #i2 #i3 : Unmute a line with id #i1 for element #i2 at ionisation stage #i3. Examples ions ignore all : Do not take any line calculation into account ions use iso 3 : Use ions from the 𝑍= 3 (Li) iso-electronic sequence ions use iso 1:2 : Use ions from the H-like and He-like isoelectronic sequences ions ignore z 26 : Ignore all iron (𝑍= 26) ions ions use ion 6 5:6 : Use C V to C VI ions mute ion 8 7 : does eliminate the O VII continuum and lines from the displayed spectrum ions unmute iso 2 : shows the emission from all He-like ions (again). ions show : Display the list of ions that are used ions ql : Quicklook mode on ions ewlim 1.2 : Select strongest lines using the cut-off value 1.2 ions old ion 6 6 : Use old calculation for C VI ions qc ion 6 5 : Use quick-cie calculation for C V ions nmax ion 26 25 5 : Set maximum principal quantum number for Fe XXV to 𝑛= 5. ions lmax ion 26 25 3 : Set maximum angular momentum quantum number for Fe XXV to ℓ= 3. ions mute line 1 ion 8 8 : Mute line id 1 for O VIII. ions unmute line 1 ion 8 8 : Unmute line id 1 for O VIII. 3.1.18 Log: Making and using command files Overview In many circumstances a user of SPEX wants to repeat his analysis for a different set of parameters. For example, after having analysed the spectrum of source A, a similar spectral model and analysis could be tried on source B. In order to facilitate such analysis, SPEX offers the opportunity to save the commands that were used in a session to an ascii-file. This ascii-file in turn can then be read by SPEX to execute the same list of commands again, or the file may be edited by hand. The command files can be nested. Thus, at any line of the command file the user can invoke the execution of another command file, which is executed completely before execution with the current command file is resumed. Using nested command files may help to keep complex analyses manageable, and allow the user easy modification of the commands. In order to facilitate the readability of the command files, the user can put comment lines in the command files. Comment lines are recognized by the first character, that must be #. Also blank lines are allowed in the command file, in order to enhance (human) readability. 130 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Saving commands to file After the command log save #a is given on the SPEX command line (#a is the file name), all the following commands entered by the user (NOT the ones before) are stored on the command file until the log close out command is given. Exceptions are the commands read from a nested command file (it is not necessary to save these commands, since they are already in the nested command file). Also, help calls and the command to open the file (“log save #a”) are not stored. All commands are expanded to the full keywords before they are saved in the file. However, for execution this is not important, since the interpreter can read both abbrevated and full keywords. Saving the commands to the command file can be stopped by giving the command log close save. The file with the saved commands is closed and remains at the specified path. SPEX will automatically append the extension “.com” to the filename. Saving output to file It is also possible to store all the output that is printed on the screen to a file. This is usefull for long sessions or for computer systems with a limited screen buffer. The output saved this way could be inspected later by (other programs of) the user. It is also useful if SPEX is run in a kind of batch-mode. The command to save the output is log out #a, where #a should be the filename without extension. SPEX will automatically append the extension “.out” to the filename. Executing commands from file ASCII files with the .com extension containing SPEX commands can be executed in SPEX using the command log execute #a, where #a stands for the file name without the “.com” extension. When a command file is read and the end of file is reached, the text “Normal end of command file encountered” is printed on the screen, and execution of the calling command file is resumed, or if the command file was opened from the terminal, control is passed over to the terminal again. For example, the user may have a command file named run which does his entire analysis. This command file might start with the line log exe mydata that will run the command file mydata that contains all information regarding to the data sets read, further data selection or binning etc. This could be followed by a second line in run like “log exe mymodel” that runs the command file mymodel which could contain the set-up for the spectral model and/or parameters. Also, often used plot settings (e.g. stacking of different plot types) could easily placed in separate command files. Syntax The following syntax rules apply for command files: log exe #a : Execute the commands from the file #a. The suffix “.com” will be automatically appended to this filename. log save #a [overwrite] [append] : Store all subsequent commands on the file #a. The suffix “.com” will be automatically appended to this filename. The optional argument “overwrite” will allow to overwrite an already existing file with the same name. The argument “append” indicates that if the file already exists, the new commands will be appended at the end of this file. log close save : Close the current command file where commands are stored. No further commands will be written to this file. log out #a [overwrite] [append] : Store all subsequent screen output on the file #a. The suffix “.out” will be automatically appended to this filename. The optional argument “overwrite” will allow to overwrite an already existing file with the same name. The argument “append” indicates that if the file already exists, the new output will be appended at the end of this file. log close output : Close the current ascii file where screen output is stored. No further output will be written to this file. 3.1. Command syntax 131 SPEX Help Center Documentation, Release 3.08.02 Examples log save myrun : writes all subsequent commands to a new file named “myrun.com”. However, in case the file already exists, nothing is written but the user gets a warning instead. log save myrun append : as above, but appends it to an existing file log save myrun overwrite : as above, but now overwrites without warning any already existing file with the same name. log close save : close the file where commands are stored. log exe myrun : executes the commands in file myrun.com. log output myrun : writes all subsequent output to file myrun.out. log close output : closes the file above. 3.1.19 Menu: Menu settings Overview When command lines are typed, it frequently happens that often the first keywords are identical for several subsequent lines. This may happen for example when a plot is edited. SPEX offers a shortcut to this by using the menu command. Syntax The following syntax rules apply: menu none : Quit the current menu text settings (i.e., return to the default spex prompt). menu text #a : For all following commands, the text string #a will be appended automatically before the following commands. Examples menu text plot : All following commants will get the “plot” keyword put in front of them. So if the next commant would be “plot dev xs” it is sufficient to type “dev xs” instead. menu none : Return to the normal SPEX prompt. menu text "par 1 2" : All following commands wil get the “par 1 2” keywords put in front of them. The next command could be “t val 4.”, which will be expanded to the full “par 1 2 t val 4.” to set the temperature of sector 1, component 2 to 4 keV. Note that here the text has three keywords (par, 1, 2) and hence it has to be put between “”, to indicate that it is a single text string. If there is only one keyword, these “” are not necessary. 3.1.20 Model: show the current spectral model Overview This commands prints the current spectral model, for each sector, to the screen. The model is the set of spectral components that is used, including all additive and multiplicative components. For all additive components, it shows in which order the multiplicative components are applied to the additive (emitted) components. See Comp: create, delete and relate spectral components (page 111) for more details. 132 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Syntax The following syntax rules apply: model show : Prints the model for all sectors to the screen. model show #i : Prints the model for sector #i to the screen. Examples model show 2 : Prints the model for the second sector 3.1.21 Multiply: scaling of the response matrix Overview This command multiplies (a component of) the response matrix by a constant. Warning: If this command is repeated for the same component then the original response matrix is changed by the multiplication of the constants. For example, after multiplying the response matrix by a factor of 2, the original matrix is recovered by multiplying the intermediate result by 0.5. Warning: The instrument number must be given in this command even if you use only a single instrument. Syntax The following syntax rules apply: multiply #i1 [component #i2] #r : Multiplies the response matrix of component #i2 of instrument #i1 by a constant #r. Examples multiply 1 3.5 : Multiplies the response matrix from instrument 1 by a factor of 3.5. multiply 1 component 2 3.5 : Multiplies the second component of instrument 1 by the constant 3.5. 3.1.22 Obin: optimal rebinning of the data Overview This command rebins (a part of) the data (thus both the spectrum and the response) to the optimal bin size given the statistics of the source as well as the instrumental resolution. This is recommended to do in all cases, in order to avoid oversampling of the data. The theory and algorithms used for this rebinning are described in detail in Optimal definition of respons matrices (page 361). A simple cartoon of this is: binning to 1/3 of the FWHM, but the factor of 1/3 depends weakly upon the local count rate at the given energy and the number of resolution elements. The better the statistics, the smaller the bin size. 3.1. Command syntax 133 SPEX Help Center Documentation, Release 3.08.02 the string will be placed at “coord”, if #r = 1.0 the right hand of #a will be placed at “coord”. Other values can be used but are less useful. plot string new #r1 #r2 #a : Plot a new string with text as specified in #a at x=#r1 and y = #r2. See Plot text (page 158) for more details about text strings. Also do not forget to put #a between “” if it consists of more than one word (i.e., if it contains spaces). plot string del #i: : Delete string numbers specified by the range #i from the plot. plot string #i: disp #l : If true (default), display the strings specified by the range #i:. plot string #i: text #a : Change the text of strings #i: to #a plot string #i1: col #i2 : Set the colours of strings #i1: to #i2 plot string #i1: back #i2 : Set the background colour for the strings #i1: to the value #i2. plot string #i1: lw #i2 : Set the line weight of strings #i1: to #i2. plot string #i: fh #r : Set the font height of strings #i to #r. plot string #i1: font #i2 : Set the font style of strings #i1 to #i2. plot string #i: x #r : Set the x position of strings #i: to #r. plot string #i: y #r : Set the y position of string #i: to #r. plot string #i: angle #r : Set the angle of strings #i: to #r. plot string #i: fjust #r : Controls justification of the strings #i: parallel to the specified edge of the viewport. If #r = 0.0, the left hand of the strings will be placed at the position specified by “x y” above; if #r = 0.5, the center of the strings will be placed at “x y”, if #r = 1.0 the right hand of #i: will be placed at “x y”. Other values can be used but are less useful. plot string #i: box #l : If #l is true, plot a box around the text strings #i:. The default value is false (no box). plot string #i1: box lt #i2 : Set the line style of the box around the strings #i1: to the value #i2. plot string #i1: box lw #i2 : As above, but for the line weight specified by #i2. plot string #i1: box col #i2 : As above, but for the colour index for the box specified by #i2. plot set #i: : Selects data set numbers as specified by #i:. Afterwards most plot commands will only affect data sets #i: plot set all : Selects all data sets that are present. All subsequent plot commands will be executed for all data sets. plot line disp #l : If #l is true, plots a connecting line through the data points, (default is false). plot line col #i : Set the colour of the connecting line to #i. plot line lt #i : Set the line style of the connecting line to #i. plot line lw #i : Set the line weight of the connecting line to #i. plot line his #l : If #l is true, plot the connecting line in histogram format (default is true). plot elin disp #l : If #l is true, plots a connecting line through the end points of the error bars, (default depends upon the plot type). plot elin col #i : Set the colour of the connecting line through the end points of the error bars to #i. plot elin lt #i : Set the line style of the connecting line through the end points of the error bars to #i. plot elin lw #i : Set the line weight of the connecting line through the end points of the error bars to #i. plot elin his #l : If #l is true, plot the connecting line through the end points of the error bars in histogram format (default is true). plot model disp #l : If #l is true, plot the current model corresponding to the relevant data set (default is true). plot model col #i : Set the colour of the model to number #i. plot model lt #i : Set the line style of the model to number #i. plot model lw #i : Set the line weight of the model to number #i. plot model his #l : If #l is true, plot the model in histogram format (default is true). plot back disp #l : If #l is true, plot the subtracted background (default is true). plot back col #i : Set the colour of the subtracted background to number #i. plot back lt #i : Set the line style of the subtracted background to number #i. plot back lw #i : Set the line weight of the subtracted background to number #i. plot back his #l : If true, plot the subtracted background in histogram format (default is true). 140 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 plot fill disp #l : If #l is true, fill the curve below the model with the colour specified by the next command or the default colour. plot fill col #i : Change the filling colour to #i. plot fill lt #i : Change the line type of the filling lines to #i. plot fill lw #i : Change the line weight of the filling lines to #i. plot fill style #i : Change the style of the filling lines to the value #i. Here #i has values between 1–4, with the following meaning: 1 = solid filling (default), 2 = outline, 3 = hatched, 4 = cross-hatched. plot fill angle #r : Set the angle for the filling lines for hatched filling. Default is 45 degrees. plot fill sep #r : Set the distance between the filling lines for hatched filling. The unit spacing is 1 % of the smaller of the height or width of the viewing surface. This should not be zero. plot fill phase #r : The phase between the hatch lines that fill the area. plot data disp #l : If #l is true, display the data. plot data errx #l : If #l is true, display the error bars in the x-direction. plot data erry #l : If #l is true, display the error bars in the y-direction. plot data col #i : Give the data colour index #i. plot data lt #i : Give the data line style #i. plot data lw #i : Give the data line weight #i. plot data fh #r : Give the symbols for the data font height #r. plot data symbol #i : Plot the data with symbol number #i. For symbol numbers, see Plot symbols (page 162). plot adum #a [overwrite] [append] : Dump the data and model in the plot in an ascii file with filename #a. The extension “.qdp” will automatically be appended. Note that the data will be written as they are, i.e. if you have a logarithmic x-axis or y-axis, the logs of the plotted quantities will be written. If you want to replot your data later with for example the qdp package, take care that you plot the data in SPEX on a lin-lin frame before you execute the “plot adum” command. Also note that the data will be written in the units that were specified in the plot (energy, wavelength or whatever is applicable). The output format is described in Plot asciidump file format (page 166). If the optional “append” keyword is present, the data will be appended to any existing file with the name #a; if the optional “overwrite” keyword is present, any pre-existing file with the name #a will be overwritten by the new data. plot ion new #i1 #i2 #r : Plot the transition identifier per ion. Specify #i1 and #i2 to select element and ionization state, for instance, to plot Fe XXV, #i1 and #i2 are set to 26 and 25. It is optional to define the redshift of the transitions with respect to their restframe energies by #r. The current implementation includes all isoelectronic sequences from H-like down to B-like ions. It only contains K-shell transitions in the Rydberg series. | plot ion del : Delete the last transition identifier. | plot com #i : Plot each additive model component separately for all components in sector #i. The command should be immediately followed by a calc command to re-evaluate the model, and then a plot command to display the individual components (shown in green) in the current window. plot com works under both plot type data and plot type model modes. If multiplicative components are present, they are applied to the additive components in the plot. Use plot com 0 to disable the component plot. Warning: plot com cannot be applied yet to the pion model. Warning: plot com should be best used for the final plot. It is not recommended to use plot com during a spectral fitting. 3.1. Command syntax 141 SPEX Help Center Documentation, Release 3.08.02 Examples plot device xs : Open the graphic device xs (xserver). plot device ps myplot.ps : Select a postscript device connected to the file name myplot.ps plot type data : Plot the data on the selected graphics device(s) plot ux angstrom : Set the x-axis plot units to Å plot uy angstrom : Set the y-axis plot units to Counts/s/Å plot frame new : Open a new frame in the selected graphics device(s) plot frame 2 : Go to the 2nd frame, all plot commands will now only affect frame 2 plot type chi : Plot the residuals in frame 2 plot uy rel : Set the y-axis plot units in frame 2 to (Observed - Model)/Model plot view default f : Set the default viewport keyword to false so that new user viewport values can be specified for frame 2 plot view y 0.2:0.8 : Set the y viewport limits of frame 2 from 0.2 to 0.8 of the full device window plot cap id disp f : Do not display the id caption of frame 2 plot cap ut disp f : Do not display the upper top caption of frame 2 plot cap lt disp f : Do not display the lower top caption of frame 2 plot ux a : Set the x-axis plot units of frame 2 to Å plot ux 21.602 ang : Plot the x-axis as velocity in km−1relative to a wavelength of 21.602 Å. plot ry -1:1 : Set the y-axis plot range of frame 2 to between a lower limit of -1 and an upper limit of 1 plot frame 1 : Go to frame 1 plot view default f : Set the default viewport keyword to false so that new user viewport values can be specified for frame 1 plot view x 0.25:0.75 : Set the x viewport limits of frame 1 from 0.25 to 0.75 of the full device window plot de cps filename.ps : Open a colour postscript graphics device and write the output file to filename.ps plot ion new 26 25 0.1 : Plot the positions of the K-shell atomic transitions for Fe XXV with a redshift of 0.1 on the current device plot ion del : Delete the last ion from the plot plot com 1 : Plot separately all additive components from sector 1. This command should be immediately followed by a calc and a plot command to execute. | plot com 0 : Remove the component plot. | plot : Redraw the plot on all frames and devices. | plot close 2 : Close device number 2, which is the postscript device in this case 3.1.25 Quit: finish the program The quit option exits the execution of SPEX, closes the open plot-devices and scratch files (if any) and, if requested outputs the cpu-time statistics. Syntax The following syntax rule applies: quit : quit the program as described above. 142 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 3.1.26 Rbin: optimal rebinning of the data and response, including saving Overview This command rebins (a part of) the data (thus both the spectrum and the response) to the optimal bin size given the statistics of the source as well as the instrumental resolution. This is recommended to do in all cases, in order to avoid oversampling of the data. The theory and algorithms used for this rebinning are described in detail in Optimal definition of respons matrices (page 361). It does essentially the same as the obin command as far as binning of the data channels is concerned, but in addition it also optimally bins the model energy grid. All prescriptions for this are given in the paper of Kaastra and Bleeker (2016). In addition, it stores the newly binned spectrum and response, with a different name, in the same directory where the original data are. If the original data rea named data.spo and data.res, the new names will be databin0.spo and databin0.res. It is highly recommended to apply the binning to the full data set, and to do one instrument at a time, to reduce the use of memory, especially in cases with very large matrices. In those cases, the compression may take several minutes. Further, it is best practice to quit spex after the creation of the reduced dataset, and to load the reduced data in a new session. If you want to see the difference, you can load the original and the binned data as two separate instruments in spex, apply a simple model and see the differences in a plot. Syntax The following syntax rules apply: rbin #i1: : Simplest command allowed. #i1: is the range in data channels over which the binning needs to take place. rbin #r1: #i: unit #a : The same command as above, except that now the ranges over which the data is to be binned (#r1:) are specified in units (#a) different from data channels. These units can be eV, keV, Å, as well as in units of Rydberg (ryd), Joules (j), Hertz (hz) and nanometers (nm). rbin [instrument #i1:] [region #i2:] #i3: : Here #i3: is the same as #i1: in the first command. However, here one can specify the instrument range #i1: and the region range #i2: as well, so that the binning is done only for one given data set. rbin [instrument #i1:] [region #i2:] #r1: [unit #a] : This command is the same as the above, except that here one can specify the range over which the binning should occur in the units specified by #a. These units can be eV, Å, keV, as well as in units of Rydberg (ryd), Joules (j), Hertz (hz) and nanometers (nm). Examples rbin 1:10000 : Optimally bins the data channels 1:10000. 3.1.27 Sector: creating, copying and deleting of a sector Overview This allows one to create, delete, copy, and show the number of sectors, used for the analysis of the data. Sectors are designed to allow modeling of different sources of radiation with its own spectral model. This way, common components can be fit simultaneously, while the observed spectra are of a different origin. One can create a sector for another (unresolved) source in the spectrum, for modeling particle background, or for spectra extracted in a different time interval for a time variable source. See for more details about sectors and regions in the Section Sectors and regions (page 357). 3.1. Command syntax 143 SPEX Help Center Documentation, Release 3.08.02 For doing spectral fitting of data sets, the sectors need to be specified in the response matrix of the data: the response file should tell which sector number corresponds to a given part of the matrix. The sector command features also a spectral dump mode (adump) that writes the model spectrum to an ascii file, formatted such that it is suited for the SPEX file model. The first line of the output file is an integer showing the number of bins, and the following lines show the energy bin centroid and the luminosity in 1044 ph/s/keV. Syntax The following syntax rules apply: sector new : Creates a new sector, which can have its own model. sector show : Gives the number of sectors that are currently used. sector copy #i : Copies the model for sector #i to a new sector. sector delete #i : Deletes sector #i. sector adump #i #a overwrite : Writes the model spectrum of sector number #i to an ASCII file with name #a. Examples sector new : Creates a new sector. sector copy 2 : Creates a new sector, with the same spectral model as used in sector 2. This can be useful if the spectra of the different sectors are very similar in composition. sector delete 3 : Deletes sector number 3. sector adump 1 model.txt : Dumps the spectrum in sector 1 to model.txt 3.1.28 Shiftplot: shift the plotted spectrum for display purposes Overview This command shifts the observed spectrum as well as the model spectrum by adding a constant or by multiplying a constant, as far as plots are concerned. The true data files do not change, so the shift is only for representational purposes. There are basically two options, indicated by the mode variable plotshift: For plotshift=1, a constant shift is added to the plotted spectrum of a given part of the data, for plotshift=2 the plotted spectrum is multiplied by the constant shift. The multiplicative constant shift (plotshift=2) is generally preferred for log-log plots, while for linear plots a constant additive shift (plotshift=1) is preferred. Warning: In the case of addition (plotshift=1), the addition constant is given in counts/s. This thus leads to a different (energy-dependent) constant being added to the plotted spectrum if the units are not in counts/s. For the multiplicative case this is of course not the case. 144 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Syntax The following syntax rules apply: shiftplot #i #r : #i indicates whether a constant should be added (#i=1) or multiplied (#i=2) to the spectrum and model. #r is then the constant to be added or multiplied by. shiftplot [instrument #i1:] [region #i2:] #i3 #r : Shift the plot using a factor #r. Here #i3 (= plotshift) determines whether the constant is added (plotshift=1) or multiplied (plotshift=2). The optional instrument range #i1: can be used to select a single instrument or range of instruments for which the shift needs to be applied, and the optional region range #i2: the region for these instruments. Examples shiftplot 1 2.0 : Adds 2 counts/s to the plotted spectrum. Since no instrument or region is specified, this applies for all spectra. shiftplot 2 10.0 : Multiplies the plotted spectrum by a factor of 10.0 shiftplot instrument 1 region 2 1 2 : Adds 2 counts/s to the plotted spectrum for the data from instrument 1 and region 2. shiftplot region 2:3 1 2 : Adds 2 counts/s to the plotted spectrum for the data for all instruments and regions 2−3. 3.1.29 Simulate: Simulation of data Overview This command is used for spectral simulations. The user should start with a spectral model and a spectral data set (both matrix and spectrum). After giving the “simulate” command, the observed spectrum will be replaced by the simulated spectrum in SPEX. Note that the original spectrum file (with the .spo extension) is not overwritten by this command, so no fear to destroy your input data! Different options exist and several parameters can be set: •Instrument, region: the instrument(s) and region(s) for which the simulation should be done (i.e., if you have more instruments you can do the simulation only for one or a few instruments). •time: set the exposure time 𝑡(s) of the source spectrum as well as the background error scale factor 𝑓𝑏. This last option allows you to see what happens if for example the background would have a ten times higher accuracy (for 𝑓𝑏= 0.1). •syserr: add a systematic error to both the source and background spectrum. An alternative way to introduce systematic errors is of course to use the syserr command (Syserr: systematic errors (page 148)). Take care not to set the systematic errors twice, and remember that rebinning your spectrum later will reduce the systematic errors, as these will be added in quadrature to the statistical errors. So first rebin and then add systematics! •noise: either randomize your data or just calculate the expected values. •bnoise: randomize your background model (generally not recommended to do). •seed: set the random seed either to a specific number or generate it from the system clock. By default, SPEX initializes the random number generator based on the system clock, but through this command a specific seed can be set. The command will show the seeds used for the maximum number of expected threads. Please note that by default, only the first instrument and region are being simulated. If you want to simulate all instruments and regions, then this can be arranged by the commands: SPEX>simulate instrument 1:2 SPEX>simulate region 1:2 3.1. Command syntax 145 SPEX Help Center Documentation, Release 3.08.02 Warning: A response matrix and spectrum of the region and the instrument you want to simulate are necessary, because SPEX needs the response matrix as well as the background to be subtracted for the simulations. Warning: When you include systematic errors in the simulation (by putting the “syserr” to non-zero values), you cannot use anymore Poissonian statistics hence the C-stat for fitting, but you have to use the “fit meth chi” to use Gaussian errors and 𝜒2-fitting, with all thr disadvantages of that. Warning: When you use bnoise=true, your subtracted background (the scaled background from the background region) will be randomized, and the pure C-stat cannot be used; the W-stat can be used as alternative but has serious drawbacks and is not recommended to be used). Warning: (obsolete) If your background is taken from the same observation as your source, and you multiply the original exposure time with a factor of 𝑆, you should put 𝑓𝑏to 𝑆−0.5, reflecting the fact that with increasing source statistics the background statistics also improves. This is the case for an imaging observation wherea part of the image is used to determine the background. If instead you use a deep field to subtract the background, then the exposure time of your background will probably not change and you can safely put 𝑓𝑏= 1 for any exposure time 𝑡. Warning: (obsolete) If your subtracted background (one of the columns in the .spo file) is derived from a low statistics Poissonian variable (for example a measured count rate with few counts per channel), then scaling the background is slightly inaccurate as it takes the observed instead of expected number of background counts as the starting point for the simulation. Syntax Note that only the “simulate” keyword followed by a number (the exposure time will do the actual simulation. All other syntax rules just set some parameters. The following syntax rules apply: simulate #r : Does the simulation, with #r the exposure time 𝑡in seconds. simulate instrument #i1 : Specify the instrument (range) to be used in the simulation. Default values are 1 (just the first instrument). simulate region #i1 : Specify the region (range) to be used in the simulation. Default values are 1 (just the first region). For simulating everything you have, you can put this range to a large value: the simulation will simply ignore non-existent regions. If you use complex settings, like only region 3 for instrument 1 and region 2 for instrument 2, you may have to run the simulation separately for each entity. simulate syserr #r1 #r2 : Specify the systematic errors as a fraction of the source and background spectrum, respectively; both should be specified together. Default values are 0. simulate noise #l : If #l is true, Poissonian noise will be added (this is the default). simulate bnoise #l : If #l is false, no Poissonian noise will be added to the model background (this is the default). simulate seed #i : Set random seed to a particular number. simulate seed random : Set random seed randomly based on system clock. 146 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Examples simulate 10000. : This simulates a new spectrum/dataset with 10 000 s exposure time. simulate noise f : Set simulation flag to simulate without Poissonian noise. The nominal error bars will still plotted. simulate syserr 0.1 0.2 : Set simulation for a systematic error of 10 % of the source spectrum and 20 % of the subtracted background spectrum added in quadrature. simulate instrument 2:4 : Set simulation for a spectrum for instruments 2–4 only simulate region 2 : Set simulation for only region 2 (of every instrument involved simulate seed 2 : Set random number seed to 2. 3.1.30 Step: Grid search for spectral fits Overview A grid search can be performed of 𝜒2versus 1, 2, 3 or 4 parameters. The minimum, maximum and number of steps for each parameter may be adjusted. Steps may be linear or logarithmic. For each set of parameters, a spectral fit is made, using the last spectral fit executed before this command as the starting point. For each step, the parameters and 𝜒2are displayed. This option is useful in case of doubt about the position of the best fit in the parameter space, or in cases where the usual error search is complicated. Further it can be useful incases of complicated correlations between parameters. Warning: Take care to do a spectral fit first! Warning: Beware of the cpu-time if you have a fine grid or many dimensions! Because the step terminal output can be quite long and cause issues in some cases, we suppress the terminal output when an output file is requested. If you want to follow the progress of the steps, you can open a new terminal and use the tail -f command. In your SPEX terminal, you give the step file command: SPEX>step file pargrid While this is running, open a new terminal window and change to your working directory. Now you can give the tail -f command and follow the progress: unix:~> tail -f pargrid.stp Syntax The following syntax rules apply: step dimension #i : Define the number of axes for the search (between 1–4). step axis #i1 parameter [[#i2] #i3] #a range #r1:#r2 n #i4 : Set for axis #i1, optional sector #i2, optional component #i3 and parameter with name #a the range to the number specified by #r1 and #r2, with a number of steps 𝑛given by #i4. If 𝑛 > 0, a linear mesh between #r1 and #r2 will be taken, for 𝑛 < 0, a logarithmic grid will be taken. step : Do the step search. Take care to do first the “step dimension” command, followed by as many “step axis” commands as you entered the number of dimensions. 3.1. Command syntax 147 SPEX Help Center Documentation, Release 3.08.02 step file example : Do the step search and also write the results to an .stp file used by the stepcontour program (see Stepcontour (page 250)). Warning: The step file command will overwrite existing .stp files with the same name by default. Examples Below we give a worked out example for a CIE model where we took as free parameters the normalization “norm”, temperature “t”, Si abundance “14” and Fe abundance “26”. To do a 3-dimensional grid search on the temperature (logarithmic between 0.1 and 10 keV with 21 steps), Fe abundace (linear between 0.0 and 1.0 with 11 steps) and Si abundance (linear between 0.0 and 2.0 with 5 steps, i.e. values 0.0, 0.4, 0.8, 1.2, 1.6 and 2.0) the following commands should be issued: fit : Do not forget to do first a fit. step dimension 3 : We will do a three-dimensional grid search step axis 1 parameter 1 1 t range 0.1:10.0 n -21 : The logarithmic grid for the first axis, temperature; note the −before the 21! step axis 2 par 26 range 0:1 n 11 : The grid for axis 2, Fe abundance. step axis 3 par 14 range 0:2 n 5 : Idem for the 3rd axis, Silicon. step : Now do the grid search. Output is in the form of ascii data on your screen (and/or output file if you opened one). step file example : Grid search with output to your screen and .stp output file for use with the stepcontour task. 3.1.31 Syserr: systematic errors Overview This command calculates a new error, adding the systematic error of the source and the background to the Poissonian error in quadrature. One must specify both the systematic error as a fraction of the source spectrum as well as of the subtracted background spectrum. The total of these fractions can either be less or greater than 1. Warning: This command mixes two fundamentally different types of errors: statistical (random fluctuations) and systematic (offset). The resulting uncertainties are unjustly treated as being statistical, which can lead to wrong results when the systematic offsets are substantial. Syserr should therefore be used with extreme caution. Warning: One should first rebin the data, before running syserr. Run syserr however before fitting the data or finding errors on the fit. Warning: Running syserr multiple times will increase the error every time. If the input to syserr is wrong one should restart SPEX and rerun syserr with the correct values to calculate the total error correctly. 148 Chapter 3. Command overview SPEX Help Center Documentation, Release 3.08.02 Syntax The following syntax rules apply: syserr #i: #r1 #r2 : The shortest version of this command. #i: is the range in data channels for which the systematic error is to be calculated and added (in quadrature) to the Poissonian error. #r1 is then the the relative systematic error due to the source and #r2 the relative systematic error due to the background. syserr [instrument #i1:] [region #i2:] #i3: #r1 #r2 : In this syntax one can also specify the instrument and the region one wants to calculate the combined error for. Both can be ranges as well. #i3: has the same role as #i: in the above command, and #r1 and #r2 are the same as above. syserr [instrument #i1:] [region #i2:] #i3: #r1 #r2 [unit #a] : Exact same command as above, except that now the data range (#i3:) for which the errors are to be calculated are given in units different than data channels. These units can be Å (ang), eV (ev), keV (kev), Rydbergs (ryd), Joules (j), Hertz (hz) and nanometers (nm). This is the most general command. Examples syserr 1:100000 0.3 0.5 : Calculates the combined Poissonian and systematic error for data channels 1:100000, where the fraction of the systematic error of the source is 0.3 and the background is 0.5. syserr 0:2000 0.3 0.5 unit ev : The same as the above command, expect that now the error calculation is performed between 0 and 2000 eV instead of data channels. syserr instrument 2 region 1 0:2000 0.3 0.5 unit ev : The same as the above command, but now the error calculation is only performed for the data set from the second instrument and the first region thereof. 3.1.32 System: call system executables Overview Sometimes it can be handy if SPEX interacts with the computer system, for example if you run it in command mode. You might want to check the existence of certain file, or run other programs to produce output for you, and depending on that output you want to continue SPEX. Therefore there is an option to execute any shell type commands on your machine, using the fortran “call system” subroutine. Another useful goody is the possibility to stop SPEX automatically if you find some condition to occur; this might be useful for example if you have a program running that calls SPEX, and depending on the outcome of SPEX you might want to terminate the execution. This is achieved in SPEX by testing for the existence of a file with a given filename; if the file exists, SPEX stops immediately execution and terminates; if the file does not exist, SPEX continues normally. Syntax The following syntax rules apply: system exe #a : execute the command #a on your UNIX/linux shell. system stop #a : stop SPEX if the file #a exists. 3.1. Command syntax 149 SPEX Help Center Documentation, Release 3.08.02 Finally, our runs with Cloudy are done using the following default settings (apart from the SED and abundances that are entered by the user): •Hydrogen density small, i.e. 1014 m−3(108cm−3) •Column density small, i.e. 1020 m−2(1016 cm−2) •Use the “iterate to convergence” command of Cloudy •Values of log 𝜉between −8.5and +6.5with steps of 0.1 Note that, depending on the computer used, this program may run for several hours. During execution it should display the present value of log 𝜉and the electron temperature in eV for each step of log 𝜉between −8.5and +6.5. This number should update regularly. If it does not, then it is possible that the calculation is stuck. This usually happens if the used model cannot calculate the lowest values for 𝜉. If so, you may want to change the log 𝜉range. This can be done by providing the flag -r at the command line when xabsinput is started. If you do that, make sure that when you use the xabs model in SPEX, you adjust the lower and upper limit of the xil parameter as well to the limits given to xabsinput. This way one can avoid possible problems when xil is out of the calculated range. Warning: We note that up to and including version 13.03 of Cloudy, 𝐿i𝑜𝑛 in the definition of 𝜉was actually the total bolometric ionising luminosity. However, from the upcoming version 13.04 of Cloudy this is corrected in the Cloudy code to be consistent with the commonly used definition, where 𝐿i𝑜𝑛 ranges between 1 to 1000 Ryd. Thus, we recommend using the xabsinput program with Cloudy version 13.04. 5.4 Hydro driver Some users run complex and computationally expensive hydrodynamical simulations, and want to be able to calculate the corresponding X-ray spectrum. Without having to implement these hydro-codes into it is now possible to do this. For that purpose we offer the Fortran90 subroutine hydro_driver.f90. Basically, it does the following: 1. It reads the needed parameters as subroutine arguments. 2. It does a few sanity checks (ion concentrations should be non-negative, and the total H+H column density must be 1. 3. It then creates a file called “spexicon.dat” containing the ion concentrations. 4. It also creates a file called “spexgrid.egr” containing the energy grid. 5. It then creates a file called “spexdriver.com” that contains the commands to run in batch mode. 6. This file is executed, and creates a file “spexoutput.asc” containing the emitted spectrum. 7. SPEX terminates. 8. The subroutine reads the file “spexoutput.asc” and puts the spectrum in the appropriate output array of the subroutine. The input arguments of the subroutine are as follows: hden : The Hydrogen density in units of 1020 m−3. Real number. t: The electron temperature in keV. Real number. it : The ion temperature in keV, used for line broadening. Real number. vmic : The microturbulence velocity, in km s−1, used for line broadening. Real number. volume : The emitting volume, in units of 1024 m3. Real number. con(31,30) : Array with ion concentrations relative to hydrogen (number densities). The abundances of the metals should be taken into account in this; thus, for example, for cosmic abundances, oxygen has a number density of about 0.001 per hydrogen atom, hence the sum of all oxygen ion concentrations should then be 0.001. The array con(jz,iz) contains for each element (labeled with atomic number 𝑖𝑧, H=1, He=2 etc.) the 252 Chapter 5. Additional tools SPEX Help Center Documentation, Release 3.08.02 concentration; 𝑗𝑧 indicates the ionisation stage (1=I=neutral, 2=II=singly ionized, etc.; do not forget to include the bare nucleus as the last one. Array elements with 𝑗𝑧 > 𝑖𝑧 + 1 will be ignored. Note that as things are normalised to hydrogen, 𝑐𝑜𝑛(1,1) + 𝑐𝑜𝑛(2,1) = 1 is obligatory! Real array. neg : Number of energy bins. Integer number. eg(0:neg) : Energy bin boundaries in keV; the boundaries of the first bin are stored in eg(0) and eg(1); the second bin in eg(1) and eg(2); etc. Real array. The output arguments of the subroutine are as follows: spec(neg) : The emitted spectrum in units of 1044 photons/s/keV. Divide this number by 4𝜋𝑑2with 𝑑the source distance to get the flux at Earth. Real array. 5.5 Rgsvprof In SPEX, the lpro component (see Lpro: spatial broadening model (page 210)) can be used to fold the spectrum with a user defined broadening profile. This is particularly useful for the analysis of extended sources with grating spectrometers, like RGS aboard XMM-Newton. The rgsvprof program creates an input file (usually called vprof.dat) for the lpro component from a MOS1 detector image. The program will ask for the following input: •MOS1 detector image. In order to obtain a profile along the dispersion direction of RGS within the same field of view, the program asks for a MOS1 image of the source in detector coordinates (DETX,DETY) created by, for example, the XMM-Newton SAS task evselect. Rgsvprof does not require a particular resolution for the image, but a resolution of about 1/3 of the XMM-Newton PSF, i.e. 4′′, is recommended. It is recommended to extract an image using events with energies falling in the RGS band: ∼0.3-2.0 keV. •Cross-dispersion selection region. If the RGS spectrum is extracted from a certain area in the cross-dispersion direction, then provide the lower and upper boundary here in arcminutes with respect to the centre of the field of view. The full RGS strip corresponds to a range between -2.5 and 2.5 arcminutes. •Source width in the dispersion direction. This parameter determines the boundaries of the resulting profile in wavelength space. Rgsvprof asks for the width of the source in arcmin centred on the peak of the emission. Choose this width to be somewhat larger than the actual width of the source to be sure that the brightest parts are included in the profile. A width of >10 arcmin is typically enough, but a larger width will increase the size of the vprof.dat file and increase processing times. •Output file name. The name of the output file (usually vprof.dat). Note that rgsvprof does not overwrite files that already exist. Rgsvprof creates an ASCII file with two columns. The left column consists of the grid of wavelengths that the profile is based upon and the right column gives the normalised cumulative profile over this range starting with 0 and ending at 1. The profile will be centred on the peak of the emission. Note: The cross-dispersion axis in RGS is parallel to the DETX coordinate axis in MOS1 and has the same direction. This is particularly helpful when one extracts spatial regions in the cross-dispersion direction of RGS. Warning: This program works best for bright extended sources, where the background contribution is negligible. For sources with a low surface brightness, in principle a background subtracted image should be used. This program, however, cannot deal with negative values in the MOS1 image. 5.5. Rgsvprof 253 SPEX Help Center Documentation, Release 3.08.02 Warning: This program does not take into account vignetting and chip gaps. For offset observations or very extended sources, this may start to play a role. 5.5.1 Theory The wavelength scale corresponding to the angular width of the source in RGS can be calculated using the dispersion equation defined in e.g. Peterson et al. (2004): 𝑚𝜆 =𝑑(cos𝛽−cos𝛼), where 𝑚is the spectral order, 𝜆the wavelength, 𝑑the grating spacing, 𝛼the incidence angle of a photon, and 𝛽the diffracted angle. The wavelength shift ∆𝜆due to an offset angle ∆𝜃relative to the telescope boresight can be derived by differentiating the equation above with respect to 𝜃=𝐹 𝐿(𝛼−𝛼0), where 𝐹is the distance between the gratings (RGA) and the camera (RFC), 𝐿the focal length of the telescope, and 𝛼0the incidence angle corresponding to the telescope boresight. The resulting relation for ∆𝜆is: ∆𝜆=𝑑𝐿 𝑚𝐹 sin(𝛼0)∆𝜃. We then use the following numbers from den Herder et al. (2001):𝑑is 1/645.6 mm, 𝐿is 7.5 m, 𝐹is 6.7 m, and 𝛼0is 1.5762∘to calculate the typical conversion factor from ∆𝜃in arcmin: ∆𝜆= 0.1387 ∆𝜃 Note that the value in Peterson et al. (2004) is not correct, because the factor 𝐿 𝐹was not applied. The value in the above equation is used in rgsvprof to convert the spatial profile from arcminute scales to wavelength scales. 5.6 RGS_fluxcombine Program RGS_fluxcombine combines fluxed spectra, created by the XMM-Newton SAS task rgsfluxer. It has two options: 1. Option 1: combine RGS spectra of the same detector and spectral order. 2. Option 2: combine spectra of RGS1, RGS2 and first and second order of both (4 spectra) into one spectrum. This is not a trivial task, due to the presence of bad pixels, CCD gaps etc, that for each individual spectrum can be slightly different, for instance because of the use of the multi-pointing mode (MPM) of the RGS, so that the same bad pixel falls at a different wavelength for each individual spectrum, or due to the transient nature of some bad pixels/columns. We discuss both options separately. In general, if you have RGS data for multiple epochs of a source, you may have to run this program first four times with option 1 (RGS1 and 2, orders 1 and 2), and then run it ones with option 2 to get a single stacked RGS spectrum. Warning: You must run the SAS task rgsfluxer with 3600 wavelength bins between 4–40 Å. Thus, do not use the former 𝛽-bins! Also, do not change these wavelength limits or number of bins. The program needs an input file, basically telling it how many spectra should be combined, followed by one line for each spectrum (fixed format, in fortran (F9.2,1X,A) for option 1), containing the exposure time in s (unfortunately not contained in the output of rgsfluxer, but you can get it from the spectral files) and the name of the relevant output file of rgsfluxer. For option 2 there are two additional numbers, namely the RGS (1 or 2 for RGS1 and RGS2), and the spectral order (1 or 2 for first and second spectral order), in such a way that the format is (I1,1X,I1,1X,F11.2,1X,A). 254 Chapter 5. Additional tools SPEX Help Center Documentation, Release 3.08.02 5.6.1 Option 1: combining RGS spectra of the same detector and spectral order It is important to realise that when data of a time-variable source are combined, artifacts due to missing data (bad pixels) will arise. This can be simply illustrated by an example. Suppose that source X is observed twice with RGS, with exactly the same exposure time, the first time with 100 counts/bin, the second time with 20 counts/bin. Suppose that at wavelength bin 𝑗the first observation has a bad pixel, hence no counts, while the second observation has no bad pixel at bin 𝑗. The averaged spectrum will have (100+20)/2=60 counts per bin, except for bin 𝑗where the average value is (0+20)/2=10. Now since both exposure times are the same, the model will predict 60 counts for all bins (as required), except for bin 𝑗where it will predict 30 counts (the pixel is dead for half of the exposure). Thus, the model has 30 counts while the data have only 10 counts. An innocent observeer might therefore think there is an absorption line at bin 𝑗taking awat 20 counts, but it is obvious that that is not true. For this reason, when we combine spectra, we will weigh with the exposure time for all “normal” bins, but when in some of the datasets there is a bad pixel 𝑗, we will use a different procedure. In that case, we look to the neighbouring pixels, and assume that the spectral shape in this local neighbourhoud remains the same. From the neighbours with complete data we can estimate how much flux the spectra with good data contribute to the total flux, and we use this fraction to estimate with what factor we should scale the flux measured at pixel 𝑗in these good data sets, to obtain the best estimate of the flux at pixel 𝑗for the total spectrum. This procedure gives reliable results as long as the spectral shape does not change locally; as there is less exposure at pixel 𝑗, only the error bar on the flux will be larger. When there is reason to suspect that the bad pixel is at the location of a spectral line that changes in equivalent width, this procedure cannot be applied! To alleviate this problem, the user has to enter a minimum exposure fraction. If this value is zero, for spectra with constant shape the best result is obtained. On the other hand, if this value is 1, only bins will be included that have no bad pixel in any of the observations that are combined. Advantage in that case is that there is no bias in the stacked spectrum, but a disadvantage may be that a significant part of the spectrum may be lost near important diagnostic lines (in particular for the multi-pointing mode). Due to the binning and randomisation procedures within the SAS task rgsfluxer, it is still possible that despite careful screening on bad pixels, a few bad pixels remain in the fluxed spectrum, often adjacent or close to discarded pixels. For this reason, the present program checks for any bins that are more than 3𝜎below their right or left neighbouring bin (taking the statistical errors in both into account). Typically, the algorithm finds a few additional bad pixels in an individual observation that is discarded for combination. The program further allows to apply two other corrections (both are done in the same step). The first correction is an effective area correction. In very high signal to noise data, there are broadband flux differences between RGS1 and RGS2 and first and second order spectra, in some parts of the spectrum, at the few percent level. A simpel model has been produced to correct for this, in the sense that when RGS1 and RGS2 are combined, the true spectrum is assumed to be the average of both. The correction is based on the monitoring campaign on Mrk 509, taken in 2009, and is found to be consistent with a large data set of Mrk 421 spectra that are present in the archive. Local continuum fits to spectral bands that are poor of lines yield in general 𝜒2values that are too low. This is an artifact of the SAS procedures related to the rebinning of the data. Data have to be binned from the detector pixel grid to the fixed wavelength grid that we use in our analysis. The bin boundaries of both grids do not match. As a consequence of this process, the natural Poissonian fluctuations on the spectrum as a function of detector pixel are distributed over the wavelength bin coinciding most with the detector pixel and its neighbours. In addition, there is a small smoothing effect caused by pointing fluctuations of the satellite. Due to this tempering of the Poissonian fluctuations, 𝑐ℎ𝑖2values will be lower for a “perfect” spectral fit. We have quantified the effect by fitting a linear model 𝐹𝜆=𝑎+𝑏𝜆 to fluxed spectra in relatively line-poor spectral regions, in 1 Å wide bins in the 7–10, 17–18 and 35–38 Å ranges. The median reduced 𝜒2is 0.72, with a 67 % confidence range between 0.65 and 0.79. The rebinning process conserves the number of counts, hence the nominal error bars (square root of the number of counts) are properly determined. The lower reduced 𝜒2is caused by the smoothing effect on the data. For correct inferences about the spectrum, such a bias in 𝜒2is not appropriate. As we cannot change the observed flux values, we opt to multiply the nominal errors on the fluxes by √︀(0.72) = 0.85, in order to get get acceptable fits for ideal data and models. 5.6. RGS_fluxcombine 255 SPEX Help Center Documentation, Release 3.08.02 5.6.2 Option 2: combine spectra of RGS1, RGS2 and first and second order of both (4 spectra) into one spectrum This procedure is similar to option 1, but with some differences. No corrections for effective area or binning bias are allowed here, as this should be taken into account in the steps that use option 1. In case there is only one observation, the present program can also be run with only one spectrum for option 1, to get the efective area and binning corrections in. Further, the spectra are not combined according to exposure time (that should be in general almost the same for RGS1 and RGS2), but according to signal to noise ratio at each bin. Reason is that ofteh the second order spectra have poorer statistics than the first order spectra, hence they should be weighted less in the combined spectra. Spectra created with rgsfluxcombine can only be fitted using 𝜒2statistics. C-statistics will produce wrong values. 5.7 RGS_fmat Program RGS_fmat produces a response matrix for a fluxed spectrum created by the XMM-Newton SAS task rgsfluxer. The user should provide an FITS file that is the output of the rgsfluxer program. That program must be run with 3600 equidistant wavelength bins between 4 and 40 Å. The program takes this fluxed spectrum, and creates a response matrix with effective area 1 m2for each wavelength, and a redistribution function normalised to unity for each wavelength. This redistribution function is slightly different for RGS1 and RGS2, and also different for the second order spectra. Hence, the user must provide RGS_fmat the information about which RGS and spectral order is used. In addition, it is also possible to make a single response matrix for combined RGS1 and RGS2 data, first and second order. In this case, first the program RGS_fluxcombine must have been run with option=2. That program then creates the rgsfluxer-compatible file, with the addition of four extra columns, containing for each wavelength the relative weight of the different instrument/order to the total spectrum. These weights are used to weigh the redistribution functions in the combined spectra. The redistribution function has been parametrised as the sum of three (first order) or 4 (second order) Gaussians, with wavelength-dependent width and relative normalisations. These parametrisations have been obtained by fitting the “true” redistribution function as it is in SAS in 2014 after having re-investigated the RGS line-spread-function by the RGS consortium. The model energy grid used for the matrix has a uniform spacing of 1/9th of the instrumental FWHM, approxinmated here simply by 0.06/|𝑚|, where 𝑚is the spectral order. The matrix is fully -compatible, in the sense that it also uses the derivatives of the matrix with respect to energy to get the most accurate results. There is no way back from this to OGIP-typs spectra! Warning: The redistribution function is limited to ±1 Å around the central wavelength. For most continuum and absorption line spectra this is sufficient. In a few rare cases of very bright emission line sources, the user is advised to compare the resulting fit with a direct fit using the original SAS response matrices and spectral files. The matrix is much smaller: the combined RGS matrix has a size of 8.2 Mbyte. This should be compared to the total size of the four matrices in OGIP format, which is over 200 Mbyte. 256 Chapter 5. Additional tools SPEX Help Center Documentation, Release 3.08.02 5.8 Uvtospex Many optical/UV spectra are delivered without a response matrix. Hubble COS spectra, for example, are delivered as data/error points on a wavelength grid. To include these spectra in a SPEX fit, a response matrix with a given spectral resolution should be created. Uvtospex is a tool to transform such optical spectra into SPEX format. Note: Some UV/optical instruments do provide response matrices, for example XMM-Newton OM and Swift UVOT. Please see this thread to import Import UV/Optical data (page 47). To create a spectrum in SPEX format from UV/Optical grating data, the spectrum needs to be stored in a text file with three columns. The uvtospex program shows the format when opening: Your input spectral file should have 3 columns: Column 1: wavelength in Angstrom Column 2: flux in ergs/cm^2/s/Angstrom Column 3: flux error in same units Enter input file name spectrum: cos.txt The program first asks for the ascii file name containing the spectrum. Then the output file name of the spo file needs to be provided: Enter file name output spectrum (with .spo): cos.spo To be able to create a response matrix for the spectrum, the spectral resolution of the instrument needs to be known. Uvtospex asks for the resolution in units of km/s (FWHM): Enter spectral resolution (km/s): It is assumed that this resolution in km/s is constant over the entire spectral range. Finally, the name of the output response file should be entered: Enter file name output response (with .res): The result should be a .res and .spo file containing the UV spectrum that can be read into SPEX. 5.9 Calling SPEX from Fortran 5.9.1 Goal Sometimes you may want to combine SPEX with some of your own code. For instance, you may have a hydrodynamical code calculating the evolution of a cluster of galaxies or a supernova remnant, and you want SPEX to calculate the corresponding spectrum. Or you need to make realistic simulations for a large sample of sources or a broad range of parameters. In that case it can be useful to call SPEX from a fortran program. 5.8. Uvtospex 257 SPEX Help Center Documentation, Release 3.08.02 5.9.2 Solution The basic flow of the solution is as follows: •Start your fortran program and calculate whatever is needed •create a command file for SPEX •call SPEX through a system call •read the output of SPEX •continue with your program To explain how you can do this, we give below a sample Fortran 90 program. The program first creates a command file called spex.com that contains the input for the run with SPEX. In your case, you can replace the “/opt/spex/bin/spex” to whatever path is appropriate for you to call SPEX. The “<<STOP” is essential for linux to tell when the input stream is finished. In the command file, it tells how to read the pn spectrum of a cluster of galaxies with roughly metallicity 0.3, temperature 2 keV, redshift 0.01 and Galactic foreground absorption of 1024 m−2. It ignores data at the lowest and highest energies, sets the initial model and parameters for SPEX. It will then perform a fit with SPEX. Next we tell SPEX to open an output file named “spex.out”, that will contain the results of the next part of the SPEX run, an error search on the temperature. Note also that we have set-up the plotting device to “null”, to speed up the calculation (but implying that you do not get to see the fit itself, so use with care). After the error run, we stop SPEX, first by writing the “quit” command for SPEX and then the end of input signal “STOP” for linux. Next we simply close the command file spex.com. The fortran program then continues by making spex.com executable, and then by executing that file, thereby doing the run with SPEX. When SPEX is finished, fortran takes over control again and reads the spex.out file created by SPEX. The program grabs any info it needs from that file (here the errors on the temperature) and then closes the file. As a last step, the intermediate outputfile “spex.out” is deleted, as we do not need it longer. real nh,z,t character*128 s z = 0.01 !redshift 0.01 nh = 1e-4 !1E20 cm**-2 absorption column density (SPEX uses units of 1E28 m**-2) t = 2 !temperature 2 keV open(unit=12,file='spex.com',status='replace') !open a spex command file called␣ ˓→spex.com write (12,'("/usr/local/bin/spex <<STOP")') !call spex write (12,'("abu lodders")') !set abunances to Lodders scale write (s,'("dis ",f6.4," z")') z write (12,'(a)') trim(s) !write the distance write (12,'("data pn pn)') !read some spex data set: pn.res &␣ ˓→pn.spo write (12,'("ign in 1 r 1 1:60")') !ignore first 60 channels write (12,'("ign in 1 12:10000 u kev")') !ignore E>12 keV region write (12,'("com cie")') !define a CIE component write (12,'("com reds")') !define a redshift component write (12,'("com abs")') !define galactic absorption write (12,'("com rel 1 2,3")') !couple the components write (s,'("par 1 2 z v ",f6.4)') z write (12,'(a)') trim(s) !set the redshift write (s,'("par 1 3 nh v ",1pe12.3)') nh write (12,'(a)') trim(s) !set the galactic absorption write (12,'("par 1 3 nh s f")') !freeze NH write (12,'("par 1 1 06:28 v 0.3")') !set abundances of C to Ni to 0.3␣ (continues on next page) 258 Chapter 5. Additional tools SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) ˓→time solar write (s,'("par 1 1 t v ",f5.2)') t write (12,'(a)') trim(s) !set the temperature write (12,'("fit meth cstat")') !use C-statistics for fitting write (12,'("plot dev null")') !no visible plots write (12,'("plot type data")') !plot type data write (12,'("fit prin 1")') !show each fitting step write (12,'("fit")') !do a fit write (12,'("err dchi 1.")') !for error search, do Delta chi**2␣ ˓→= 1 write (12,'("log out spex o")') !open a file for the SPEX output !file will be called "spex.out" !the option "o" means overwrite write (12,'("err 1 1 t")') !do an error search on T write (12,'("quit")') !done with the spex run, so quit write (12,'("STOP")') !last command needed to close the␣ ˓→command file close (12) !close the file spex.com and save call system("chmod +x spex.com") !make file spex.com executable call system("spex.com") !execute the file spex.com open (unit=12,file='spex.out',status='old') !open the outputfile spex.out do k = 1,100000 !loop over all the lines in this␣ ˓→file read (12,'(a)',end=20) s !read the text of the line; put it␣ ˓→in string s if (s(2:11).eq."Parameter:") then !search for the line with text␣ ˓→Parameter: read (s(34:),*) e1,e2 !read from this line the errors on T err = 0.5 * (-e1 + e2) !calculate average pos and neg error !..... do further all you wish endif enddo !close loop over lines file spex.out 20 close(12) !close spex.out call system("rm spex.out") !remove the file spex.out end 5.10 Linid Linid is a utility for displaying spectral line lists without starting a full SPEX session. It can operate in two modes. In the first mode, it returns detailed information on the strongest transitions for a user-specified element and ionization stage. In the second mode, it lists all transitions within a user-defined energy interval. For each transition, the tool provides the element, charge state, Rydberg state, empirical identifier, energy, wavelength, and transition probability. Note: The current implementation includes all isoelectronic sequences from H-like down to B-like ions. It only contains K-shell transitions in the Rydberg series. For a complete list, please run a SPEX session. 5.10. Linid 259 SPEX Help Center Documentation, Release 3.08.02 5.10.1 Example The first example is to list the Ne X Rydberg lines: Atomic number and spectroscopic charge (e.g., 8 8 for O VIII), or E and dE in keV (1. ˓→0 0.1): 10 10 Next, to display all the recorded transitions in the 0.1 keV range around a central energy of 6.6 keV: Atomic number and spectroscopic charge (e.g., 8 8 for O VIII), or E and dE in keV (1. ˓→0 0.1): 6.6 0.1 260 Chapter 5. Additional tools CHAPTER SIX PYTHON INTERFACE Welcome to the documentation of PYSPEX, the Python interface to SPEX. Since version 3.06.00 we provide a Python interface layer to the SPEX program. This documentation section explains how to use this interface, which is an alternative for the standard command-line interface of SPEX. Note: As an alternative to some auxilliary programs of SPEX (e.g. trafo), we offer a separate Python package called pyspextools. Please see the Pyspextools documentation for more information. 6.1 Basic commands 6.1.1 Basic usage of PYSPEX The PYSPEX python module offers a python interface to the SPEX program. This means that you can use SPEX directly either in interactive python mode and in python scripts. In this short tutorial, we assume you are using PYSPEX in interactive mode. The structure of PYSPEX is chosen such that for many SPEX commands, there is an equivalent class in PYSPEX. These classes contain the functions that copy the functionality of the SPEX command, and if applicable, the classes contain also the output parameters of the SPEX command. This makes it easy to incorporate the SPEX results inside your own program. In addition to the classes, you can also simply send a SPEX command-line command using the command function (see Section below). Start a PYSPEX session For this example PYSPEX session in python, we use the interactive mode of python. We simply start python from the Linux command line (making sure that the environment is set using a spexdist script located in the SPEX install directory): linux:~> source spex/spexdist.sh linux:~> python Python 2.7.13 Type "help","copyright","credits" or "license" for more information. >>> If the PYTHONPATH variable is correctly set, we should now be able to import spex from pyspex: >>> from pyspex import spex From here, we can start a SPEX session easily: 261 SPEX Help Center Documentation, Release 3.08.02 >>> s.simulate(1E+5, inst='1:3', bnoise=True, seed=42) Model related commands A SPEX model is organised in sectors and components. Sectors are groups of components that model a particular source of radiation. Below, the basic commands for building the model and change its parameters are listed. Abundance The solar abundance table used is set in SPEX using the abundance command. In PYSPEX, this is abbreviated to abun. The desired abundance table should be loaded by providing the abbreviation for the table (abunset): Session.abun(abunset) Set the abundance table in SPEX. The abunset parameter is one of ‘reset’, ‘ag’, ‘allen’, ‘asplund’, ‘ra’, ‘grevesse’, ‘gs’, ‘lodders’, and ‘solar’. Parameters abunset (str) – String representing the abundance set used in SPEX. Returns Object containing the abundance class. Return type pyspex.model.Abundance (page 314) The possible abundance tables are: •reset: Lodders et al. (2009) •allen: Allen (1973) •ra: Ross & Aller (1976) •grevesse: Grevesse et al. (1992) •gs: Grevesse & Sauval (1998) •lodders: Lodders proto-Solar (2003) •solar: Lodders Solar Photospheric (2003) •ag: Anders & Grevesse (1989) •asplund: Asplund et al. (2009) The abun command returns an object with the abundance information, which can optionally be assigned to a parameter and be accessed through Python. See the advanced class descriptions for details. For example: >>> a=s.abun('asplund') >>> dir(a) ['__doc__','__init__','__module__','get','index','list','ref','set','update'] 268 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 Abundance show To show the current abundance table, use the abun_show method: Session.abun_show() Show the current ionisation balance. Returns Reference to the used ionisation balance. Return type str The method returns the reference as a text string: >>> ab =s.abun_show() Lodders et al. (2009) >>> print(ab) Lodders et al. (2009) Aerror Calculate the uncertainties for several parameters of a model component due to the uncertainties in the atomic data. Session.aerror(isect,icomp,name,shell=0) Command to calculate the uncertainty in a model parameter due to the uncertainties in the atomic data. Parameters •isect (int) – Sector number of the component. •icomp (int) – Component number. •name (str) – Parameter name. •shell (int) – Shell number for calculation (L-shell = 1, K-shell = 2) Returns The atomic uncertainty for the selected parameter. Return type float Example: >>> aerr =s.aerror(1,1,'norm') >>> aerr =s.aerror(1,1,'26',shell=1) Calculate Once the model sectors and components are set-up and the parameters are set, the model spectrum can be calculated using the SPEX calculate command. For convenience, this command has been abbreviated to calc in PYSPEX. Session.calc() Calculate the current model. Example: >>> s.calc() 6.1. Basic commands 269 SPEX Help Center Documentation, Release 3.08.02 Components Spectral components, like power laws, thermal and absorption models are loaded using the SPEX comp command. Since the command is often typed simply as com in practice, the PYSPEX command is also com: Session.com(name,isect=1) Add model component. Parameters •name (str) – Name of the model component, for example ‘reds’, ‘hot’, ‘cie’, etc. •isect (int) – Sector number to add component to (default is sector 1). The command adds a component by default to sector 1. If the component should be added to a different sector, then please use the optional isect parameter to specify the target sector. For example: >>> s.com('cie') >>> s.com('po', isect=2) See the SPEX reference manual for a list of spectral components. Component delete Deleting a component from the model is done using the sector and component number of the component. Session.com_del(isect,icomp) Delete component from model. Parameters •isect (int) – Sector number of the component to delete. •icomp (int) – Component number to delete. For example: >>> s.com_del(1,1) The command above deletes the first component in sector number 1. Component relate The relation between the additive and multiplicative components is set with a com rel command in SPEX. In PYSPEX this is: Session.com_rel(isect,icomp,rel) Relate model components. Parameters •isect (int) – Sector number of the component to relate. •icomp (int) – Component number to relate. •rel (numpy.ndarray) – Array containing the multiplicative component numbers counted from the source to the observer. The relations are set per component (so no ranges, unfortunately) and the related multiplicative models should be entered (in the right order) using a numpy array. For example: 270 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 >>> s.com('reds') >>> s.com('hot') >>> s.com('cie') >>> s.com_rel(1,3, numpy.array([1,2])) Distance To calculate fluxes and luminosities, SPEX needs an assumed distance of the source. In SPEX this is done with the distance command. In PYSPEX this is abbreviated to dist for convenience. The distance can be set with the dist command: Session.dist(isect,dist,unit) Set the distance in SPEX. Parameters •isect (int) – Sector number. •dist (float) – Distance value. •unit (str) – The unit of the distance value, for example: ‘m’, ‘au’, ‘ly’, ‘pc’, ‘kpc’, ‘mpc’, ‘z’, ‘cz’ where isect is the sector number, dist the distance (float) and unit the unit of the distance that is put in. The function returns an object containing the distance in all available units. Examples: >>> d=s.dist(1,0.5,'z')# Redshift of z=0.5 >>> d=s.dist(1,2.0,'kpc')# Distance of 2 kiloparsec >>> dir(d) ['__doc__','__init__','__module__','age','au','cz','get','h0','kpc','ly','m ˓→','mpc','omega_l','omega_m','omega_r','pc','set','set_cosmo','z'] If you do not want to set the distance, but just get the current parameters, the dist_get command can be used: Session.dist_get(isect) Get the current distances in SPEX. Parameters isect (int) – Sector number. Like the dist command, this method returns an object with the distances in all available units. Cosmology Next to the distance, the cosmology used by SPEX can also be specified. In SPEX all parameters should be provided through seperate lines, but in PYSPEX this has been combined in one command: Session.dist_cosmo(h0,omega_m,omega_l,omega_r) Set the cosmology for the distance calculation. Parameters •h0 (float) – Hubble constant (km/s/Mpc). •omega_m (float) – Omega matter. •omega_l (float) – Omega lambda. •omega_r (float) – Omega R. 6.1. Basic commands 271 SPEX Help Center Documentation, Release 3.08.02 The commands needs values for the Hubble constant h0 (70 km/s/Mpc), Omega Matter omega_m (0.3), Omega Lambda omega_l (0.7) and Omega R omega_r (0.0). For example: >>> s.dist_cosmo(75,0.33,0.67,0.0) (The command will write the distances 4 times to the terminal since in the background all SPEX commands are executed separately...) Energy grid The model energy grid can be manipulated with the SPEX egrid command. In PYSPEX, this command has been splitted into two varieties: Session.egrid(elow,ehigh,nbins,unit,log) Egrid command when the number of desired bins is known. Parameters •elow (float) – Lowest energy/wavelength for energy grid. •ehigh (float) – Highest energy/wavelength for energy grid. •nbins (int) – Number of bins for energy grid. •unit (str) – Unit of the energy/wavelength range, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’ •log (bool) – Make the energy grid logarithmic (True or False) Session.egrid_step(elow,ehigh,step,unit,log) Egrid command when the stepsize for the grid is known. Parameters •elow (float) – Lowest energy/wavelength for energy grid. •ehigh (float) – Highest energy/wavelength for energy grid. •step (float) – Step size for the energy grid. •unit (str) – Unit of the energy/wavelength range, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’ •log (bool) – Make the energy grid logarithmic (True or False) For the first method, egrid, the number of spectral bins nbins is known, while for egrid_step the step size (step) is an input value. The lowest and highest energy of the grid needs to be provided using the elow and ehigh input values. The unit is a text string and the grid can be logarithmic if the log parameter is set to True. Examples: >>> s.egrid(0.1,10.,9990,'kev',True) >>> s.egrid_step(0.1,10.,0.01,'kev',False) 272 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 Reading & saving grids Grids can also be save and read from a text file. The two methods below save and read a .egr file, respectively: Session.egrid_save(savefile) Save energy grid to file. Parameters savefile (str) – Filename to save the energy grid to (including .egr extension) Session.egrid_read(readfile) Read energy grid from file. Parameters readfile (str) – Filename to read the energy grid from (including .egr extension) The savefile or readfile parameter should provide the method with the filename to save or read, including the .egr extension! If necessary, the full path to the file can be included. Examples: >>> s.egrid_save('mygrid.egr') >>> s.egrid_read('mygrid.egr') Get & set custom grids If the grid needs to be transfered from or to Python memory, then the get and set methods can be used: Session.egrid_get() Get the energy grid and return the grid as an object. Returns An Egrid object from pyspex. Return type pyspex.model.Egrid (page 315) Session.egrid_set(ebounds) Provide a grid to SPEX by providing a numpy array with the bin boundaries. Please note that the length of this array is the number of bins + 1! Parameters ebounds (numpy.ndarray) – Array containing the energy boundaries of the new energy grid. The get routine returns a Python object with the egrid arrays. The set routine requires an ebounds numpy array containing the energies of the bin boundaries. Note that the number of elements of this array would be of length n + 1, where n is the number of bins in the array. Examples: >>> grid =s.egrid_get() >>> ebounds =0.1 +0.01 *numpy.arange(9991, dtype=float) >>> s.egrid_set(ebounds) 6.1. Basic commands 273 SPEX Help Center Documentation, Release 3.08.02 Flux & Luminosity For each component, the fluxes and luminosities are calculated using the set distance and energy boundaries. These energy limits for the flux and luminosity can be set using the elim command: Session.elim(elow,ehigh,unit) Set the energy limits for flux output. Parameters •elow (float) – Lowest energy/wavelength for energy interval. •ehigh (float) – Highest energy/wavelength for energy interval. •unit (str) – Unit of the energy/wavelength interval, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’. where elow is the lower boundary of the flux and ehigh the higher boundary. The unit determines the units of the input values, for example ‘kev’ for keV. Examples: >>> s.elim(13.6E-3,13.6,'kev') Get flux The fluxes and luminosities calculated in SPEX can be extracted using the flux_get method. Session.flux_get(isect,icomp) Get the fluxes and luminosities for component icomp in sector isect. Parameters •isect (int) – Sector number of the component to obtain the flux from. •icomp (int) – Component number to obtain the flux from. Return flux A Flux object from pyspex. Rtype flux pyspex.model.Flux The values are returned in a python object so that they can be accessed easily: >>> flx =s.flux_get(1,1) >>> print flx.enerflux 1.51011622912e-18 For the details about the contents of the object, see the advanced class description of the Fluxes class. Ionisation balance There are several ionisation balances available in SPEX. The Urdampilleta ionisation balance is the current default set. The ionisation balance can be set using the ibal method: Session.ibal(ref ) Set the ionisation balance. Parameters ref (str) – Abbreviation of the reference to the ionisation balance. 274 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 The ref is the short text string describing the paper reference for the ionisation balance: •ar92: Arnaud & Raymond (1992) for Fe, Arnaud & Rothenflug (1985) for other elements. •ar85: Arnaud & Rothenflug (1985). •oldbryans: Old Bryans et al. data (NOT recommended). •bryans09: Bryans et al. (2009). •u17: Urdampilleta et al. (2017). Examples: >>> s.ibal('u17') Show To show the current ionisation balance, the ibal_show method can be used: Session.ibal_show() Show the current ionisation balance. Returns Reference to the used ionisation balance. Return type str This method returns the reference of the ionisation balance as a string. Example: >>> ib =s.ibal_show() Urdampilleta et al. (2017) Ion selection In original SPEX models that use the SPEX atomic data, ions can be turned on or off, or can be calculated using the old SPEX version 2 or the new SPEX version 3. In addition, the maximum principle quantum number (nmax) and the maximum angular momentum (lmax) can be set. The functions have been created such that each function selects the ions either by atomic number, iso-electronic sequence or ion. Session.ions_all(par,value) Set parameter for all values. Parameters •par (str) – Parameter name to set, e.g.: ‘use’, ‘new’, ‘nmax’, ‘lmax’. •value (bool or int) – Value to set. Session.ions_iso(iso,par,value) Set parameter for an iso-electronic sequence. Parameters •iso (int) – Iso-electronic sequence number •par (str) – Parameter name to set, e.g.: ‘use’, ‘new’, ‘nmax’, ‘lmax’. •value (bool or int) – Value to set. 6.1. Basic commands 275 SPEX Help Center Documentation, Release 3.08.02 Session.ions_z(z,par,value) Set parameter for an atom. Parameters •z(int) – Atomic number of the element. •par (str) – Parameter name to set, e.g.: ‘use’, ‘new’, ‘nmax’, ‘lmax’. •value (bool or int) – Value to set. Session.ions_ion(z,i,par,value) Set parameter for a specific ion. Parameters •z(int) – Atomic number of the element. •i(int) – Ionisation stage (in astrophysical notation, e.g. 1, 2, 3, etc.) •par (str) – Parameter name to set, e.g.: ‘use’, ‘new’, ‘nmax’, ‘lmax’. •value (bool or int) – Value to set. Show The ion selections can be shown by calling the ions_show function below: Session.ions_show() Show the ions in use and with which parameters. Line selection Up to 10 specific lines can be ‘muted’ using the ions_line function below: Session.ions_line(z,i,lid,add) Mutes or unmutes a spectral line from an emission spectrum. Parameters •z(int) – Atomic number of the element. •i(int) – Ionisation stage (in astrophysical notation, e.g. 1, 2, 3, etc.) •lid – Line ID number (see ascdump_line for the line ID number). •add – If False, the line is not added to the spectrum. True will add the line to the spectrum again. Setting parameters Model parameters in SPEX are set using the par command. Since this command has subcommands, there are a number of methods to cover most of the functionality in PYSPEX. The most basic function is to set a parameter value and determine whether it should be free in the fit or thawn. These functions have been combined into one: Session.par(isect,icomp,name,value,thawn=False) Set parameter value and status. Parameters •isect (int) – Sector number of the parameter. •icomp (int) – Component number of the parameter. •name (str) – Parameter name. 276 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 •value (float) – New value of the parameter. •thawn (bool) – (Optional) Should the parameter be free (True) or frozen (False). Session.par_text(isect,icomp,name,value) Set text type parameter value. Parameters •isect (int) – Sector number of the parameter. •icomp (int) – Component number of the parameter. •name (str) – Parameter name. •value (str) – New value of the parameter. The par method is used for setting numerical values. It needs the sector number (isect), component number (icomp) and the name of the parameter (name) to set. Optionally, the parameter can be set free by setting thawn to True. For text values, like filenames of model input files, the par_text method is used. The usage is very similar to the par method, but just with the difference a text string is passed instead of a value. Text parameters cannot be free parameters as well. Examples: >>> s.par(1,1,'norm',1E+8, thawn=True) >>> s.par_text(1,1,'file','dist.dat') Fix & Free parameters Many times, we want to fix and free parameters without changing the values. For this purpose, two convenience functions have been created: Session.par_fix(isect,icomp,name) Fix a model parameter during the fit. Parameters •isect (int) – Sector number of the parameter. •icomp (int) – Component number of the parameter. •name (str) – Parameter name. Session.par_free(isect,icomp,name) Free a model parameter during the fit. Parameters •isect (int) – Sector number of the parameter. •icomp (int) – Component number of the parameter. •name (str) – Parameter name. par_fix and par_free fix and free the parameter with name (name) in sector (isect) and component (icomp). Examples: >>> s.par_free(1,1,'26') >>> s.par_fix(1,1,'t') 6.1. Basic commands 277 SPEX Help Center Documentation, Release 3.08.02 Genetic algorithm Session.dem_gene(pop,gen) Do DEM analysis using the genetic algorithm, using a population size given by pop (maximum value 1024) and gen is the number of generations (no limit, in practice after about 100 generations not much change in the solution. Experiment with these numbers for your practical case). Parameters •pop (int) – Population size •gen (int) – Number of generations Return mult_table Table containing the best temperature components and their emission measure. Rtype mult_table astropy.table.QTable Return chisq Best fit 𝜒2. Rtype chisq float For example: >>> (chisq, penalty) =s.dem_gene(512,80) DEM smooth Session.dem_smooth(width) Smoothes a DEM previously determined by any DEM method using a block filter/ Here width is the full width of the filter expressed in 10 log 𝑇. Note that this smoothing will in principle worsen the 𝜒2of the solution, but it is sometimes useful to “wash out” some residual noise in the DEM distribution, preserving total emission measure. Parameters width (float) – The full width of the filter expressed in 10 log 𝑇. For example: >>> s.dem_smooth(0.5) Get the DEM distribution in python Session.dem_get() Get the best-fit DEM distribution. Return table Table with the DEM distribution Rtype table astropy.table.QTable For example: >>> table =s.dem_get() >>> print(table) The output table has the columns temperature (kT), differential emission measure (DY) and the error on the emission measure (DY_Err), if available. 284 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 Plot the DEM distribution Session.dem_plot(xlog=False,ylog=False) Plot the DEM distribution. Parameters •xlog (bool) – Make the X-axis logarithmic. •ylog (bool) – Make the Y-axis logarithmic. For example: >>> s.dem_plot() Reading the DEM distribution from file Session.dem_read(file) Read a DEM distribution from a file named #a which automatically gets the extension .dem. It is an ascii file with at least two columns, the first column is the temperature in keV and the second column the differential emission measure, in units of 1064𝑚−3𝑘𝑒𝑉 −1. The maximum number of data points in this file is 8192. Temperature should be in increasing order. The data will be interpolated to match the temperature grid defined in the dem model (which is set by the user). Parameters file (str) – Filename without .dem extension. For example: >>> s.dem_read('mydem') Writing the DEM distribution to file Session.dem_write(file) Save the DEM to a file file with extension “.dem”. The same format as above is used for the file. A third column has the corresponding error bars on the DEM as determined by the DEM method used (not always relevant or well defined, exept for the regularization method). Parameters file (str) – Filename without .dem extension. For example: >>> s.dem_write('mydem') Plasma model parameters There are a number of settings for the SPEX plasma models that can be changed by the user. In SPEX these are done using the var command. The var commands have been implemented in pyspex through the methods below. The current settings can be obtained using the Var class (page 321) which is referenced in the SPEX session as s.mod_var. 6.1. Basic commands 285 SPEX Help Center Documentation, Release 3.08.02 Free-bound accuracy Session.var_gacc(value) Set the free-bound emission accuracy. Parameters value (float) – Free-bound emission accuracy. Example: >>> s.var_gacc(1.0E-2) Line emission contributions Session.var_line(ltype,status) Set a line emission contribution on or off. Parameters •ltype (str) – Line emission contribution (‘ex’, ‘px’, ‘rr’, ‘dr’, ‘ds’, ‘ii’, ‘reset’) •status (bool) – Boolean indicator whether contribution is on (True) or off (False). Example: >>> s.var_line('ex',False) Doppler broadening Session.var_doppler(value) Doppler broadening. Parameters value (int) – Doppler broadening type. Example: >>> s.var_doppler(1) SPEXACT version 3 calculations Session.var_calc(status) Perform SPEXACT 3 line calculations. Parameters status (int) – Use SPEXACT 2 (0), Quick SPEXACT 3 (1), or SPEXACT 3 (2) Example: >>> s.var_calc(True) 286 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 Occupation numbers starting values Session.var_occstart(otype) At which occupation level to start. Parameters otype (str) – Occupation level (‘ground’, ‘boltz’, ‘last’) Example: >>> s.var_occstart('ground') SPEXACT version 2 settings (MEKAL) Session.var_mekal(utype,status) Switch old Mekal updates on/off. Parameters •utype (str) – Update type (‘wav’, ‘fe17’, ‘update’, ‘all’) •status (bool) – On (True) or off (False) Examples: >>> s.var_mekal('wav',False) >>> s.var_mekal('fe17',False) Multi-Maxwellians for the ionisation balance Session.var_ibalmaxw(status) Switch the Multi-Maxwellians for the ionisation balance on/off (True/False). Parameters status (bool) – On (True) or off (False) Example: >>> s.var_ibalmaxw(False) SPEXACT version 3 cooling Session.var_newcoolexc(status) Cooling by collisional excitation by Stofanova (SPEXACT 3) on/off (True/False). Parameters status (bool) – On (True) or off (False) Example: >>> s.var_newcoolexc(False) And for the cooling by di-electronic recombination: Session.var_newcooldr(status) Cooling by dielectronic recombination (SPEXACT 3) on/off (True/False). Parameters status (bool) – On (True) or off (False) 6.1. Basic commands 287 SPEX Help Center Documentation, Release 3.08.02 Example: >>> s.var_newcooldr(False) Charge exchange recombination and ionization Set the origin of the charge exchange recombination and ionization rates. Session.var_cxcon(value) Set charge exchange recombination and ionization rates according to either 1 = Arnaud & Rothenflug (1985) or 2 = Kingdon & Ferland (1996). Default is 2. Parameters value (int) – Recombination and ionisation rateset. 1 = Arnaud & Rothenflug, 2 = Kingdon & Ferland. Example: >>> s.var_cxcon(1) Ascdump commands The SPEX ascdump command is designed to return internal model parameters in SPEX through terminal output, an ASCII file or a FITS file. With pyspex we can return these numbers in a python object, making them directly available in your script as an Astropy table. An overview of the different ascdump outputs and an explanation about the acronyms in the output table can be found in the section Ascdump: ascii output of plasma and spectral properties (page 91). The ascdump command Session.ascdump(isect,icomp,atype) Generic ascdump method to obtain the various numeric outputs of the spectral models. (see https: //spex-xray.github.io/spex-help/reference/commands/ascdump.html for more information). Parameters •isect (int) – Sector number of the component. •icomp (int) – Component number. •atype (str) – Ascdump type Example: >>> s.com('cie') >>> asc =s.ascdump(1,1,'plas') number of layer lines : 4156 0 No selection file used >>> print(asc.table) te tion tiba vmic cs eden ␣ ˓→hden eide rho ed eid denm epla keV keV keV km / s km / s 1 / m3 1 /␣ ˓→m3 1 / m3 kg / m3 keV ------------ ------------ ------------ ------------ ------------ ------------ -------- ˓→---- ------------ ------------ ------------ ------------ ------------ ------------ 1.000000E+00 1.000000E+00 1.000000E+00 0.000000E+00 5.072631E+02 1.204480E+06 1. ˓→000000E+06 2.302763E+06 2.389693E-21 1.204480E+00 2.302763E+00 1.428711E+00 4. ˓→075277E-14 288 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 Optimization commands Once the data have been read in and the model has been set, the model parameters can be optimized to fit the data. The methods in this section are used for the optimization and determination of the uncertainties in the fit. Fit The SPEX command to fit is simply fit and this has been implemented as fit in PYSPEX as well: Session.fit(niter=100) Fit command. Parameters niter (int) – (Optional) Maximum number of iterations. This method can be called without any arguments. Optionally, the number of iteration steps can be given, but this is only useful in some particular cases. When done fitting, the values of the fit statistics can be found in the object s.opt_fit. See the Fit() class for details. Examples: >>> s.fit() >>> s.fit(niter=50) Fit results The resulting C-statistics/Chi-square value and degrees of freedom can be obtained with separate commands: Session.fit_cstat() Get the current C-statistics from the model. Returns Tuple containing the C-stat value and the degrees of freedom. Return type tuple Session.fit_chisq() Get the current Chi2-statistics from the model. Returns Tuple containing the 𝜒2value and the degrees of freedom. Return type tuple These commands return a tuple with the latest statistics value and the degrees of freedom. Examples: >>> cstat =s.fit_cstat() >>> print(cstat) (2979.7792968, 3000) >>> chisq =s.fit_chisq() >>> print(chisq) (2997.3247823, 3000) 6.1. Basic commands 289 SPEX Help Center Documentation, Release 3.08.02 Fit statistics Although C-statistics is recommended for Poisson distributed data like X-ray spectra, sometimes it may be better to switch to chi^2 statistics. This can be done using the fit_stat method: Session.fit_stat(stat) Set the fit statistics. Parameters stat (str) – Fit statistics, for example: ‘csta’, ‘chi2’, ‘wsta’ The statistics (stat) can be either csta (C-statistics), chi2 (Chi-square statistics), or wsta (W-statistics). The W-statistics is added to SPEX for reference, but is not recommended for use in analysis. Example: >>> s.fit_stat('chi2') If you have more instruments or regions which require a different fit statistic (optical or UV spectra for example), then it is possible to set a different statistic for specific regions with the fit_stat_inst command: Session.fit_stat_inst(stat,inst,reg) Set the fit statistics for a particular instrument and region. Parameters •stat (str) – Fit statistics, for example: ‘csta’, ‘chi2’, ‘wsta’ •inst (int) – Instrument number. •reg (int) – Region number. One needs to specify the instrument and region number for which the new statistics apply. Example: >>> s.fit_stat_inst('chi2',2,1) Fit method Next to the default Levenberg-Marquardt algorithm, SPEX also offers Simplex and Simulated annealing methods (see Fit: spectral fitting (page 120)). The method can be selected using the following command: Session.fit_method(method) Set the fit statistics for a particular instrument and region. Parameters method – Fit method: classical, simplex or anneal The simulated annealing method has a number of parameters that can be altered. This can be done using the fit_set_ann method: Session.fit_set_ann(param,value) Set the simulating annealing method parameters. Parameters •param (str) – Type of annealing parameter (rt, t, eps, vm, ns, max, or print). •value (float) – Value of the parameter (will be converted to the nearest int if necessary). The current parameters can also be found in the s.opt_fit object. See Fitting spectra (page 323) for more information. Examples: 290 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 >>> s.fit_method('ann') >>> s.fit_set_ann('rt',0.85) Fit verbosity The intermediate results from the fit iterations can be shown in the terminal (and in a pgplot window). In PYSPEX, this feature is on by default. If you want to turn it off, then call Session.fit_print(status) Set the fit output verbosity. Default is true. Parameters status (bool) – Fit output verbosity setting. with False as status. The intermediate steps will not be printed anymore. Example: >>> s.fit_print(False) Error The command for calculating errors on fitted parameters is error and has a direct equivalent in PYSPEX: Session.error(isect,icomp,name,dchi=None) Calculate the error for a parameter (name) in sector (isect) and component (icomp). Parameters •isect (int) – Sector number of the component to calculate the error for. •icomp (int) – Component number to calculate the error for. •name (str) – Parameter name to calculate the error for. •dchi (float) – (Optional) ∆𝜒2value to optimize for (Default: 1.0, 68% errors) Returns An Error object from pyspex. Return type pyspex.optimize.Error (page 324) The method calculates the lower and upper error value for the parameter with name name in sector isect and component icomp. Optionally, the target delta-c-stat value can be set. By default, dchi is set to 1.0, which results in 68% (1 sigma) errors. The error command returns an object with the results of the error calculation. See the Error() class definition elsewhere in this manual. Examples: >>> err_si =s.error(1,1,'14') >>> err_fe =s.error(1,1,'26',dchi=2.71) >>> print(err_fe.value, err_fe.lerr, err_fe.uerr) 1.023902 -0.119324 0.109223 6.1. Basic commands 291 SPEX Help Center Documentation, Release 3.08.02 Plot commands Next to the PGPLOT plotting system of SPEX, the python interface can also be used for plotting. In this section, we provide a list of commands for plotting spectral models, the effective area and spectral data (including residuals). Plot spectral model The SPEX plot type ‘model’ plots the model spectrum as a function of energy or wavelength. In PYSPEX there is a function to obtain the same plot using matplotlib: Session.plot_model(xlog=False,ylog=False,wave=False,title='SPEX Model Spectrum', show=True) Plot the spectral model. Parameters •xlog (bool) – (Optional) Set the X-axis to be logarithmic. •ylog (bool) – (Optional) Set the Y-axis to be logarithmic. •wave (bool) – (Optional) Plot in wavelength (Angstrom) •title (str) – (Optional) Set the title of the plot. •show (bool) – (Optional) Show the plot (True) or return the plot object (False). Returns Plot object and optionally the matplotlib plt object. Return type pyspex.plot.PlotModel (page 325), matplotlib.pyplot This function plots the model spectrum as a function of energy (keV) by default. If the wave=True parameter is set, then the spectrum will be plotted as a function of wavelength (). The axis can be made logarithmic by setting xlog=True and ylog=True for the x and y axis, respectively. Warning: Due to a bug in pyspex 3.06.01, the unit on the y axis is not photons/s/m**2/keV, but photons/s/m**2. So it shows the spectra without dividing by the bin width. This issue will be fixed in pyspex 3.07.00. Examples: >>> s.plot_model() >>> s.plot_model(xlog=True, ylog=True) >>> s.plot_model(wave=True) Obtain the raw plot data It is possible to get the raw plot data through the pyspex interface. The plot_model command can return an object containing the plot data organised by model sector. Per sector, the data is available in two formats: an Astropy QTable and individual numpy arrays. The data object pl can be returned as follows: >>> pl =s.plot_model() >>> data =pl.sector[0].tabmodel Please be reminded that Python starts counting at 0, while SPEX starts counting at 1, so sector[0] in Python corresponds to sector 1 in SPEX. The table tabmodel contains the following columns: 292 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 •X_ctr: The central value of the X-axis bin (in energy or wavelength) •X_upp: The value of the upper bin edge of the X-axis bin (in energy or wavelength) •Model: The model value for that bin. Since tabmodel is an Astropy QTable the units of the values are included in the table data and all the features of a QTable can be used. Some examples to try: >>> pl =s.plot_model() >>> data =pl.sector[0].tabmodel >>> x=data['X_ctr']# extract a column from the table >>> print(data['Model'].unit) # see the unit of the Model column >>> print(data) # Print the table nicely formatted See Model spectrum plots (page 325) for a description of the individual numpy arrays available within the sector object. Plot data The SPEX data plot type plots the observed spectrum, the folded model and background spectrum. In PYSPEX, this is done with one command called plot_data: Session.plot_data(xlog=False,ylog=False,wave=False,title='SPEX',show=True) Plot the observed spectrum with the convolved model for all instruments. Parameters •xlog (bool) – (Optional) Set the X-axis to be logarithmic. •ylog (bool) – (Optional) Set the Y-axis to be logarithmic. •title (str) – (Optional) Set the title of the plot. •show (bool) – (Optional) Show the plot (True) or return the plot object (False). Returns Plot object and optionally the matplotlib plt object. Return type pyspex.plot.PlotData (page 326), matplotlib.pyplot This function plots the observed spectra in black, the convolved model in red, and the background spectrum as a dashed blue line. The axis can be made logarithmic by setting xlog=True and ylog=True for the x and y axis, respectively. With the parameter wave=True, the data and model will be plotted versus wavelength (). Warning: Due to a bug in pyspex 3.06.01, the unit on the y axis is not counts/s/keV, but counts/s. So it shows the spectra without dividing by the bin width. This issue will be fixed in pyspex 3.07.00. Examples: >>> s.plot_data() >>> s.plot_data(xlog=True, ylog=True) >>> s.plot_data(wave=True) 6.1. Basic commands 293 SPEX Help Center Documentation, Release 3.08.02 Getting numbers from a Quantity object If we only want the number itself, then it can be obtained by adding .value after the parameter like this: >>> print(flx.enerlum.value) 1.8976663101053723e+27 We can also get the unit from the object in a similar way: >>> print(flx.enerlum.unit) W Converting the units One of the reasons for using Astropy Quantities is that they are easily converted to other units. For example, many astronomers would like to know the luminosity in erg/s instead of W, because they are used to the CGS system. To get our luminosity in CGS units, the only thing we need to do is: >>> print(flx.enerlum.cgs) 1.8976663101053722e+34 erg / s Just appending .cgs at the end of the variable name is enough to return a converted number. As we can see, the unit is erg/s now, which we would expect. More examples about how to use Astropy units and how to use them in calculations can be found in the Astropy units documentation. Astropy Tables When we continue our example of the previous section, we can get the plot data for a plot of the CIE model as follows from PYSPEX: >>> (pl, plt) =s.plot_model(show=False) >>> print(pl.sector[0].tabmodel) X_ctr X_upp Model keV keV ph / (keV m2 s) --------------------- --------------------- ------------------ 0.0010007031872137865 0.0010014063744275728 149.9039074938181 0.0010021105505858743 0.001002814726744176 149.66520271469315 ... ... ... 99.78943871942874 99.85956006837118 0.0 99.9297800341856 100.0 0.0 Length = 8192 rows Because the spectral models are organised by sector, we need to get the data for the first sector. In Python indices start at 0, so we select sector[0] to get the tabmodel table for sector 1. When we print the table, it clearly consists of three columns with the names X_ctr,X_upp and Model. Each column also has a unit associated to it, so these columns are effectively Astropy Quantities. Suppose that we are interested in the Model column, then we can extract that from the table quite easily. For convenience, we first make a reference to the table in a separate variable: >>> table =pl.sector[0].tabmodel >>> print(table['Model']) [149.90390749 149.66520271 149.42688589 ... 0. 0. 0. ] ph / (keV m2 s) 300 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 The table['Model']array has the same properties as a well known numpy array and can be manipulated using the same functions. More examples and information about Astropy QTables can be found in the Astropy Tables documentation. Plotting Quantities and QTables Since Astropy Quantities and QTables have a slightly different structure than regular numpy arrays, matplotlib cannot handle these arrays by default. Luckily, the compatibility can be added easily by importing and running the following at the start of your python session or script: from astropy.visualization import quantity_support quantity_support() If you do not want to have Quantity support throughout your script, you can also add it locally before the plot commands: with quantity_support(): plt.plot(table['X_ctr'], table['Model'], '-r') 6.2.3 Multiprocessing with PYSPEX As described in Session class structure (page 304), a PYSPEX session can only be started once, at least per process or thread. This can be an annoying limitation if you want to run several SPEX sessions at once. This problem can be partly circumvented by using the multiprocessing module of Python. This module is able to run functions in parallel with different input parameters. So, if you have a problem that requires you to run SPEX multiple times with a very similar setup, but different input parameters, then this thread may be helpful to you. The following script calculates the spectrum emitted by a CIE plasma for four different temperatures. This is just a simple example. This particular problem can be calculated more efficiently in a different way, but this shows the potential of the multiprocessing module if you need to do more complicated calculations. First, we show the full script: #!/usr/bin/env python from multiprocessing import Pool from pyspex.spex import Session # Define the function that calls pyspex # and does the calculation and/or # analysis that you want def ciecalc(kt): # Start the SPEX session s=Session() # Load a CIE model and choose # the SPEXACT version 3 database s.com('cie') s.var_calc(True) # Set the temperature of the plasma s.par(1,1,'t',kt[0]) # Calculate the model (continues on next page) 6.2. Analysis threads & other tricks 301 SPEX Help Center Documentation, Release 3.08.02 (continued from previous page) s.calc() # Save the output spectral model # to a FITS file (pl, plt) =s.plot_model(show=False) pl.sector[0].tabmodel.write('cie_{0}.fits'.format(kt[0]), format='fits', overwrite=True) # Close this SPEX session gently s.__del__() # The function below is executed when this # script is executed from the terminal: if __name__ == "__main__": # Maximum number of processes to # create at once nproc =2 # The temperatures for which to # calculate the CIE spectrum kt =(0.5,1.0,2.0,4.0) # Pack the input parameters into one # iterable variable arg =zip(kt) # Create a new pool of processes (nproc) pool =Pool(processes=nproc, maxtasksperchild=1) # Call the ciecalc function with each argument pool.map(ciecalc, arg) # Close the pool pool.close() pool.join() Next, we will discuss the details of each part of this script. Needed Python modules For this script, PYSPEX is obviously needed and is imported as usual. The other module is multiprocessing. Pool, which will handle the multiprocessing for us (see also Python multiprocessing): from multiprocessing import Pool from pyspex.spex import Session 302 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 The ciecalc function The function ciecalc is our worker function here. This means that this function will start a PYSPEX session, executes a number of SPEX commands (based on the input arguments), and produces a result. In this case, we add one CIE component, set a temperature read from the function input arguments, and calculate the spectrum. In the last step, we get the calculated spectrum from a model plot and save it to FITS format. The temperature value is included in the output filename. It is important here to have the start of the PYSPEX session s=Session() inside the function. Remember that you can only have one Session per process, so this needs to be defined in each process separately to make PYSPEX run in parallel. In this example, we just vary the temperature in each calculation, but this can be expanded to more variables or options. There are multiple ways of approaching this: 1. You create a worker function with multiple arguments (see starmap). 2. You pack the variables in an object such that you can pass that object to the function. This object could be a Python list or dictionary, or a custom object that you define. The function should be able to read the variables and instructions from the input object. 3. You pass a filename of a SPEX .com file or other configuration file at each iteration. Make sure to call the s.__del__() at the very end of your function to close SPEX gently at the end. This will delete all the *.dum files as well. Set up multiprocessing The nproc variable specifies the number of processes to run at the same time. Choose this parameter wisely based on the number of processors and amount of RAM memory in your computer. Also keep in mind that one PYSPEX session may also use multiple processors at the same time. Warning: Please take care that you do not set nproc too high. A PYSPEX run can use between 1 and 4 GB of RAM memory. If you do not have a lot of RAM, then these processes can make your system extremely slow or even crash. It may be helpful to limit the number of cores used for each process. This can be done by setting the environment variable OMP_NUM_THREADS. For example, if you have a computer with 16 cores and 32 GB of RAM memory, the optimal setting would be nproc=4 and export OMP_NUM_THREADS=4. Or: import os os.environ["OMP_NUM_THREADS"]="4" Having 4 processes which can use 4 cores each gives you 16 cores at maximum, which is exactly the processor specification. Assuming that each of the 4 processes uses 4 GB of memory at maximum, the total memory usage of 16GB should fit easily on the available RAM memory chips. The line that creates the pool of processes (pool = Pool(processes=nproc, maxtasksperchild=1)) needs a very important option. The maxtasksperchild=1 option tells the pool that each function needs to be performed in a separate process. This ensures that the s = Session() command is only given once in each process. The pool.map(ciecalc, arg) line divides the tasks over the different processes and passes the arguments (arg) to the ciecalc function. The arg variable needs to contain an iterable list or array. The zip function can help to create a multi-dimensional array with input arguments if necessary. See also the starmap function to pass multiple arguments to the worker function. The pool.close() and pool.join() functions make sure that the processes are properly closed and that their output is merged (if applicable). The script above can be saved as pyspexmp.py and executed from the command line: 6.2. Analysis threads & other tricks 303 SPEX Help Center Documentation, Release 3.08.02 python pyspexmp.py You should see multiple welcome messages from SPEX on your screen indicating that multiple instances of SPEX are running. Final thoughts The method above is especially suitable for repeating long and more complicated PYSPEX sessions. Since the SPEX is restarted each time a process starts, you will lose a couple of seconds. Therefore, this is only efficient if the runtime of one iteration is much longer than a couple of seconds. The multiprocessing module has many more options which may serve your needs. As long as you have only one SPEX session per process, everything should run well. 6.3 Advanced class descriptions 6.3.1 Session class structure The PYSPEX session class is the top-level class for PYSPEX and the most important class managing user interaction. When the class is initialized, a SPEX session is started for the duration of the Python session. All subsequent commands communicate with this SPEX session in the background. The start of a SPEX session is managed by the __init__ method. At the same time, objects are created to contain much of the internal SPEX data that pyspex can access. These objects are instances of the Data, Model, Optimization, Ascdump and Log classes that are explained later in this Chapter. class pyspex.spex.Session(*args,**kwargs) This class contains all the classes and commands that are available in a pySPEX session. __init__() Function to initialize the PYSPEX session. It starts an instance of SPEX in the background. Furthermore, it initializes a set of objects containing information about the loaded data, model values, optimization and logs. Variables •version (str) – The SPEX version number •dataset (data.Data (page 305)) – Class containing the data information •mod_abundance (model.Abundance (page 314)) – Model class for the abundance setting •mod_distance (model.Distance (page 315)) – Model class containing distance tools •mod_egrid (model.Egrid (page 315)) – Model class for the definition of energy grids •mod_flux (model.Fluxes (page 316)) – Model class containing flux and luminosity information •mod_ibal (model.Ibal (page 317)) – Model class for the ionisation balance setting •mod_ions (model.Ions (page 318)) – Model class for setting the used ions •mod_var (model.Var (page 321)) – Model class for plasma model settings •mod_dem (model.Dem (page 321)) – Model class for DEM modeling •mod_spectrum (model.Spectrum (page 320)) – Model class containing commands to extract model results from SPEX •mod (model.Model (page 309)) – Model class containing sectors, components and parameters. •opt_fit (optimize.Fit (page 323)) – Initialize the Fit class for spectral fitting •asc (ascdump.Ascdump (page 329)) – Class for the Ascdump output 304 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 •logs (log.Log (page 329)) – Class for Log saving and execution During the SPEX session, the object variables can be used to obtain values from the SPEX session in the background. Please note that for most of these there are existing PYSPEX commands to retrieve the information safely. Descriptions of the classes behind the object variables in __init__ can be found by clicking the link behind the variable. Warning: You can only start one PYSPEX session during a python session. Unfortunately, the Fortran to Python interface that we use cannot handle multiple sessions properly. Session class commands The Session class also contains the main PYSPEX commands listed in Basic PYSPEX commands (page 262). 6.3.2 Data class structure Spectral & response data class pyspex.data.Data Main data class used to set and get observed data. Variables •ninst (int) – Number of instruments loaded. •inst (list of objects) – Python list of instrument objects. delete(ins) Delete instrument with number ins. Parameters ins (int) – Instrument number to delete. load(resfile,spofile) Add a new set of spectrum and response file to the dataset. Provide the full filename including extension! Parameters •resfile (str) – SPEX response file name (including .res extension). •spofile (str) – SPEX spectrum file name (including .spo extension). Return type int save(ins,spofile,overwrite=False) Save a spectrum to a .spo file. Parameters •ins (int) – Instrument number to save. •spofile (str) – Output filename for SPEX output file (including .spo extension). •overwrite (bool) – (Optional) Overwrite an existing .spo file with the same name. update() Update the number of instruments. class pyspex.data.Instrument Properties of an instrument. Variables •nsector (int) – Number of sectors in instrument. 6.3. Advanced class descriptions 305 SPEX Help Center Documentation, Release 3.08.02 •nregion – Number of data regions in response. •nreg (int) – Number of regions in data. •ncomp (int) – Number of response components. •index (int) – Index number of this instrument. •sponame (str) – Filename of .spo file. •resname (str) – Filename of .res file •reg (list of objects) – List of regions for this instrument. update(iins) Update the instrument information. Parameters iins (int) – Instrument number to update. class pyspex.data.Region Properties of one region. Variables •index (int) – Region number. •emin (float) – Min data energy range (keV). •emax (float) – Max data energy range (keV). •srccount (float) – Net source counts. •srccerr (float) – Net source count error. •bkgcount (float) – Subtracted background counts. •bkgcerr (float) – Error subtracted background counts. •srcrate (float) – Net source count rate (counts/s). •srcrerr (float) – Net source count rate error (counts/s). •bkgrate (float) – Background count rate subtracted. •bkgrerr (float) – Error background count rate subtracted. •mbkgrate (float) – Model background count rate. •tintmin (float) – Minimum integration time per channel. •tintmax (float) – Maximum integration time per channel. •tintaver (float) – Average integration time per channel. update(iins,ireg) Update the region properties. Parameters •iins (int) – Instrument number. •ireg (int) – Region number to update. 306 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 Spectral binning and data selection class pyspex.data.Bins Class containing the binning methods. bin(inst,reg,elow,ehigh,factor,unit=None) Bin the spectrum using a fixed factor. Parameters •inst (int) – Instrument number. •reg (int) – Region number. •elow (float) – Start point of energy/channel interval. •ehigh (float) – End point of energy/channel interval. •factor (int) – Binning factor •unit (str) – Unit of the energy/channel range, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’ ignore(inst,reg,elow,ehigh,unit=None) Ignore the bins given by the energy/channel range. Parameters •inst (int) – Instrument number. •reg (int) – Region number. •elow (float) – Start point of energy/channel interval. •ehigh (float) – End point of energy/channel interval. •unit (str) – Unit of the energy/channel range, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’ obin(inst,reg,elow,ehigh,unit=None) Bin the spectrum optimally given the instrument resolution and statistics. Parameters •inst (int) – Instrument number. •reg (int) – Region number. •elow (float) – Start point of energy/channel interval. •ehigh (float) – End point of energy/channel interval. •unit (str) – Unit of the energy/channel range, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’ rbin(inst,reg,elow,ehigh,unit=None) Bin the spectrum and the response optimally given the instrument resolution and statistics. Parameters •inst (int) – Instrument number. •reg (int) – Region number. •elow (float) – Start point of energy/channel interval. •ehigh (float) – End point of energy/channel interval. •unit (str) – Unit of the energy/channel range, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’ reset(inst,reg) Reset the binning and use status to use all with the original binning. Parameters •inst (int) – Instrument number. •reg (int) – Region number. syserr(inst,reg,elow,ehigh,src,bkg,unit=None) Add an additional error to the source and background spectrum. Parameters •inst (int) – Instrument number. •reg (int) – Region number. •elow (float) – Start point of energy/channel interval. •ehigh (float) – End point of energy/channel interval. 6.3. Advanced class descriptions 307 SPEX Help Center Documentation, Release 3.08.02 •src (float) – Error value to be quadratically added to the current error bar of the source spectrum. •bkg (float) – Error value to be quadratically added to the current error bar of the background spectrum. •unit (str) – Unit of the energy/channel range, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’ use(inst,reg,elow,ehigh,unit=None) Use the bins given by the energy/channel range. Parameters •inst (int) – Instrument number. •reg (int) – Region number. •elow (float) – Start point of energy/channel interval. •ehigh (float) – End point of energy/channel interval. •unit (str) – Unit of the energy/channel range, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’ vbin(inst,reg,elow,ehigh,factor,snr,unit=None) Bin the spectrum using a variable bin size, given a minimum bin factor and a minimum signal to noise ratio. Parameters •inst (int) – Instrument number. •reg (int) – Region number. •elow (float) – Start point of energy/channel interval. •ehigh (float) – End point of energy/channel interval. •factor (int) – Minimal binning factor •snr (float) – Minimal signal to noise for a data point after binning. •unit (str) – Unit of the energy/channel range, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’ Simulate spectra class pyspex.data.Simulate Class to simulate spectra. set_bnoise(status) Add Poisson noise to the background spectrum (status is True or False). Parameters status (bool) – Add Poisson noise to the simulated background spectrum. set_instrument(irange) Define the range of instruments to simulate. Parameters irange (str) – Instrument range to simulate (default all) set_noise(status) Add Poisson noise to the source spectrum (status is True or False). Parameters status (bool) – Add Poisson noise to the simulated source spectrum. set_random() Set the random seed to a random number (default). set_random_seed(seed) Set the random seed to an integer value. Parameters seed (int) – Set the random seed for the simulation. 308 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 set_region(rrange) Define the range of regions to simulate. Parameters rrange (str) – Region range to simulate (default all) set_syserr(src,bkg) Add a systematic error to the source spectrum (src) and to the background spectrum (bkg). Parameters •src (float) – Add a systematic error to the source spectrum. •bkg (float) – Add a systematic error to the background spectrum. simulate(extime,inst=None,reg=None,ssys=None,bsys=None,noise=None,bnoise=None, seed=None) Simulate a spectrum for exposure time extime and optionally with a number of options. Parameters •extime (float) – Exposure time to simulate. •inst (str) – (Optional) Instrument range to simulate (default all) •reg (str) – (Optional) Region range to simulate (default all) •ssys (float) – (Optional) Add a systematic error to the source spectrum (Default 0). •bsys (float) – (Optional) Add a systematic error to the background spectrum (Default 0). •noise (bool) – (Optional) Add Poisson noise to the simulated source spectrum (Default True). •bnoise (bool) – (Optional) Add Poisson noise to the simulated background spectrum (Default False). •seed (int) – (Optional) Set the random seed for the simulation (Default: system clock). simulate_exposure(extime) Simulate the spectrum for the provided exposure time. Parameters extime (float) – Exposure time to simulate. 6.3.3 Model class structures Model class pyspex.model.Model Top class containing the entire model, containing all sectors and components. Variables •nsector (int) – Number of sectors in this model •sect (list) – List of sector objects comp_delete(isect,icomp) Delete component from sector. Parameters •isect (int) – Sector number of the component to delete. •icomp (int) – Component number to delete. comp_new(name,isect=1) Add new component to the model. By default in sector 1. Parameters •name (str) – Name of the model component, for example ‘reds’, ‘hot’, ‘cie’, etc. •isect (int) – Sector number to add component to (default is sector 1). 6.3. Advanced class descriptions 309 SPEX Help Center Documentation, Release 3.08.02 •energy_upper (astropy.units.quantity.Quantity) – Upper boundaries of bins (Energy, keV) •energy_width (astropy.units.quantity.Quantity) – Widths of bins (Energy, keV) get() Get the current energy grid from SPEX. grid(ebounds) Provide a grid to SPEX by providing a numpy array with the bin boundaries. Please note that the length of this array is the number of bins + 1! Parameters ebounds (numpy.ndarray) – Array containing the energy boundaries of the new energy grid (keV). read(readfile) Read the energy grid from a file named readfile (extension: .egr). Parameters readfile (str) – Filename to read the energy grid from (including .egr extension) save(savefile) Save the energy grid to a file named savefile (extension: .egr). Parameters savefile (str) – Filename to save the energy grid to (including .egr extension) set(elow,ehigh,nbins,unit,log) Set egrid using limits and number of bins. Parameters •elow (float) – Lowest energy/wavelength for energy grid. •ehigh (float) – Highest energy/wavelength for energy grid. •nbins (int) – Number of bins for energy grid. •unit (str) – Unit of the energy/wavelength range, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’ •log (bool) – Make the energy grid logarithmic (True or False) set_step(elow,ehigh,step,unit,log) Set egrid using limits and step size. Parameters •elow (float) – Lowest energy/wavelength for energy grid. •ehigh (float) – Highest energy/wavelength for energy grid. •step (float) – Step size for the energy grid. •unit (str) – Unit of the energy/wavelength range, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’ •log (bool) – Make the energy grid logarithmic (True or False) Fluxes and luminosities class pyspex.model.Fluxes This class is used to calculate fluxes and luminosities of spectra in a spectral band. Variables •sector (int) – Sector number of flux calculation •component (int) – Component number of flux calculation •photflux (astropy.units.quantity.Quantity) – Photon flux (phot/m**2/s) •enerflux (astropy.units.quantity.Quantity) – Energy flux (W/m**2) 316 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 •photlum (astropy.units.quantity.Quantity) – Photon luminosity (photons/s) •enerlum (astropy.units.quantity.Quantity) – Energy luminosity (W) •elimflux (astropy.units.quantity.Quantity) – Flux energy limits (keV) calc(isect,icomp) Calculate and get flux and luminosity from SPEX for a given sector and component number. Parameters •isect (int) – Sector number of the component to calculate. •icomp (int) – Component number to calculate. elim(elow,ehigh,unit) Set the energy limits for the flux and luminosity calculation. Parameters •elow (float) – Lowest energy/wavelength for energy interval. •ehigh (float) – Highest energy/wavelength for energy interval. •unit (str) – Unit of the energy/wavelength interval, for example: ‘kev’, ‘ev’, ‘ryd’, ‘j’, ‘hz’, ‘ang’, ‘nm’. elimflux Flux energy limits (keV) get(isect,icomp) Get the flux and luminosity from SPEX for a given sector and component number. Parameters •isect (int) – Sector number of the component to obtain the flux from. •icomp (int) – Component number to obtain the flux from. Ionisation balance class pyspex.model.Ibal This class manages the SPEX ionisation balance setting. Variables •index (int) – Index number for list of ionisation balance sets. •ref (str) – Reference to the current ionisation balance. •list (tuple) – List of available ionisation balance data. get() Get the current Abundance setting (reference). set(ibal) Set the abundance in SPEX to another set. Parameters ibal (str) – Abbreviation of the reference to the ionisation balance. update() Update the abundance setting in pyspex. 6.3. Advanced class descriptions 317 SPEX Help Center Documentation, Release 3.08.02 Ion selection class pyspex.model.Ions Class to manage the ions taken into account in the model calculation. Variables •nz (int) – Total number of atoms considered. •atoms (list) – List of atoms (with information about each ion). ignore_all() Ignore all ions. ignore_ion(z,i) Ignore this ion. Parameters •z(int) – Atomic number •i(int) – Ion number ignore_iso(iso) Ignore this iso-electronic sequence. Parameters iso (int) – Iso-electronic sequence. ignore_z(z) Ignore all ions of this element. Parameters z(int) – Atomic number lmax_all(lmax) Set all ions to maximum angular momentum lmax. Parameters lmax (int) – Maximum angular momentum to use. lmax_ion(z,i,lmax) Set this ion to maximum angular momentum lmax. Parameters •z(int) – Atomic number •i(int) – Ion number •lmax (int) – Maximum angular momentum to use. lmax_iso(iso,lmax) Set this iso-electronic sequence to maximum angular momentum lmax. Parameters •iso (int) – Iso-electronic sequence. •lmax (int) – Maximum angular momentum to use. lmax_z(z,lmax) Set all ions of this element to maximum angular momentum lmax. Parameters •z(int) – Atomic number •lmax (int) – Maximum angular momentum to use. new_all() Use new calculations for all ions. new_ion(z,i) Use new calculations for this ion. Parameters •z(int) – Atomic number •i(int) – Ion number 318 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 new_iso(iso) Use new calculations for this iso-electronic sequence. Parameters iso (int) – Iso-electronic sequence. new_z(z) Use new calculations for all ions of this element. Parameters z(int) – Atomic number nmax_all(nmax) Set all ions to maximum quantum number nmax. Parameters nmax (int) – Maximum principle quantum number to use. nmax_ion(z,i,nmax) Set this ion to maximum quantum number nmax. Parameters •z(int) – Atomic number •i(int) – Ion number •nmax (int) – Maximum principle quantum number to use. nmax_iso(iso,nmax) Set this iso-electronic sequence to maximum quantum number nmax. Parameters •iso (int) – Iso-electronic sequence. •nmax (int) – Maximum principle quantum number to use. nmax_z(z,nmax) Set all ions of this element to maximum quantum number nmax. Parameters •z(int) – Atomic number •nmax (int) – Maximum principle quantum number to use. old_all() Use old calculations for all ions. old_ion(z,i) Use old calculations for this ion. Parameters •z(int) – Atomic number •i(int) – Ion number old_iso(iso) Use old calculations for this iso-electronic sequence. Parameters iso (int) – Iso-electronic sequence. old_z(z) Use old calculations for all ions of this element. Parameters z(int) – Atomic number qc_all() Use qc calculations for all ions. qc_ion(z,i) Use qc calculations for this ion. Parameters •z(int) – Atomic number •i(int) – Ion number 6.3. Advanced class descriptions 319 SPEX Help Center Documentation, Release 3.08.02 qc_iso(iso) Use qc calculations for this iso-electronic sequence. Parameters iso (int) – Iso-electronic sequence. qc_z(z) Use qc calculations for all ions of this element. Parameters z(int) – Atomic number show() Show the settings for the ions. update() Update the properties of all atoms. use_all() Use all ions. use_ion(z,i) Use this ion. Parameters •z(int) – Atomic number •i(int) – Ion number use_iso(iso) Use this iso-electronic sequence. Parameters iso (int) – Iso-electronic sequence. use_z(z) Use all ions of this element. Parameters z(int) – Atomic number Model spectra class pyspex.model.Spectrum This class obtains and stores the model spectrum from SPEX. Variables •nbins (int) – Number of bins •energy (astropy.units.quantity.Quantity) – Centroids of bins (Energy, keV) •energy_upper (astropy.units.quantity.Quantity) – Upper boundaries of bins (Energy, keV) •energy_width (astropy.units.quantity.Quantity) – Widths of bins (Energy, keV) •spectrum (astropy.units.quantity.Quantity) – Spectrum of bins (in ph/s/m**2/bin at observatory) •luminosity (astropy.units.quantity.Quantity) – Spectrum of bins (in 10^44 ph/s/keV at source distance) •table (astropy.table.QTable) – Astropy QTable containing spectrum. get(isect) Get the model spectra from SPEX for sector number isect. 320 Chapter 6. Python Interface SPEX Help Center Documentation, Release 3.08.02 DEM Modeling class pyspex.model.Dem SPEX DEM modeling interface. Variables •nr (int) – Number of temperature bins. •tw (astropy.quantity.Quantity) – Temperature bins in keV. •yw (astropy.quantity.Quantity) – Differential emission measure as a function of temperature (in 10^64 m**3 / keV). •ywerr (astropy.quantity.Quantity) – Error on the differential emission measure as a function of temperature (in 10^64 m**3 / keV). •chisq (float) – Chi^2 value for the DEM fit. •dempen (float) – Dem penalty, number of bins that are less or equal to 0. •table (astropy.table.QTable) – Astropy QTable containing DEM model. Plasma parameters class pyspex.model.Var Various settings for the plasma models. Variables •gacc (float) – Free-bound accuracy •line_ex (bool) – Electron excitation included •line_px (bool) – Proton excitation included •line_rr (bool) – Radiative recombination included •line_dr (bool) – Di-electronic recombination included •line_ds (bool) – Di-electronic satellites included •line_ii (bool) – Inner shell ionisation included •doppler (int) – Doppler broadening •newcalc (bool) – SPEXACT 3 calculations (False: SPEXACT 2) •occstart (int) – Occupation calculations •mekal_wav (bool) – Wavelength corrections according to the work of Phillips et al. (1999) •mekal_fe17 (bool) – The strongest Fe XVII lines by Doron & Behar (2002). •mekal_update (book) – Several minor corrections •ibalmaxw (bool) – Multi-Maxwellians for the ionisation balance •newcoolexc (bool) – Cooling by collisional excitation by Stofanova (SPEXACT 3) •newcooldr (bool) – Cooling by dielectronic recombination (SPEXACT 3) reset_gacc() Reset the free-bound emission accuracy. 6.3. Advanced class descriptions 321 [Document text truncated for crawler view.]