%
%
%
%
% Chapter 2
%
%
%
% 
% There are 17 figures in chapter 2. Each figure is labeled as \hypertarget{Fig2_#} and \label{Figure2_#}. They are not in order necessarily because some were added later. Here is a list of the figures:
%     Figure2_1: \caption{The Virtual Solar Observatory (VSO) main menu.}
%
%     Figure2_2: \caption{Search form generated after selecting the \textbf{Instrument / Source / Provider} box on the main VSO website. Hinode XRT data is provided by SAO.}
%
%     Figure2_3: \caption{VSO form describing the data available given the search parameters. The \textbf{CheckBox Tools} menu in the left column can be helpful when selecting a large amount of data.}
%
%Figure2_4: \caption{VSO Data request page.}
%
%Figure2_5: \caption{Hinode Science Data Center Europe Archive Search page. Search parameters relevant to XRT are highlighted green in this image.}
%
%Figure2_6: \caption{Example search results from the Hinode SDC Europe Archive.}
%
%Figure2_7: \caption{Lockheed Martin Solar \& Astrophysics Laboratory's Sungate website.}
%
%Figure2_8: \caption{LMSAL Solarsoft XRT catalog webpage.}
%
%Figure2_9: \caption{Effect of contamination layer, accumulating on the CCD between a bakeout and the next, on the XRT temperature response of Al\_mesh (black curves), C\_poly (red curves), and Be\_thin (blue curves). The solid lines are responses calculated for 2009-09-24, right after a CCD bakeout, and the dashed curves are calculated for 2009-10-15, i.e.\ three weeks later and just before the following bakeout. The comparison shows that in the regime of regular bakeouts, adopted since mid-2008, only the thinnest filter shows any detectable, though minimal,  change in response due to accumulation of contaminating material on the CCD between bakeouts.}
%
%Figure2_10: \caption{Examples displaying XRT data in IDL.}
%
%Figure2_11: \caption{Example of XRT temperature responses calculated for two different dates. The solid lines are responses calculated for 2007-03-01, before the first CCD bakeout, and the dashed curves are calculated for 2008-03-01, in the regime of regular bakeouts. The comparison shows how the sensitivity in the lower energy range, significantly decreased by the contamination material, has been recovered through CCD bakeout and maintained with regular CCD bakeouts.}
%
%Figure2_12: \caption{Example temperature output from \textbf{xrt\_teem.pro} using Al\_mesh and Al\_poly filters. The units have been changed from $\log$ K to Million K.}
%
%Figure2_13: \caption{Example emission measure output from \textbf{xrt\_teem.pro} using the Al\_mesh and Al\_poly filters.}
%
%Figure2_14: \caption{Example of XRT temperature responses calculated using the default spectrum for AIA and a standard XRT spectrum: the solid lines are the responses calculated for the standard XRT spectrum, and the dashed curves are calculated using the default spectrum for AIA. Both are calculated for the date 2011 August 21.}
%
%Figure2_15: \caption{An example Al\_mesh image taken on 5-August-2010 at 10:01UT. \emph{Left}: The prepped data without spot correction. \emph{Right}: The output image from the routine \textbf{xrt\_spotcor.pro}. The severity of the spots depends on wavelength with the Al\_mesh filter being most affected. Spot correction can be done from within \textbf{xrt\_prep.pro} and a spot map should be generated to locate affected pixels.}
%
%Figure2_16: \caption{Comparison of Ti\_poly images before and after light leak.}
%
%Figure2_17: \caption{Example output from \textbf{xrt\_deconvolve} with and without using a saturation mask.}
%
%Figure2_18: \caption{The total telescope throughput of the XRT for each of the nine X-Ray filter channels \emph{Figure 17 from \cite{Golub07}}.}
%

\hypertarget{chapter2}{}
\chapter{X-Ray Telescope Software Guide}
This chapter outlines how to analyze XRT data using software publicly available as part of SSWIDL (to add an instrument path to a SSWIDL tree, see \url{http://www.lmsal.com/solarsoft/}). This process involves obtaining, searching, reading, calibrating, coaligning and writing XRT data, as well as constructing Level 2 data products such as long-short composite images and various temperature analyses. 
%
%
%
% Quick Look at XRT DATA
%
%
%
\hypertarget{qlook}{}
\section{Browsing XRT Data}
There are several resources available for browsing XRT data, all of which can be accessed at the XRT webpage. \hyperlink{catalogs}{Table~\ref{xrtcat}} provides links to the resource along with a brief description of what is available there.

The XRT data Snapview webpage presents a visual representation of XRT data that includes pointing and filter information and links to the VSO website. The XRT Synoptic Gallery provides daily full-disk solar images and the XRT flare catalog details every flare observed by XRT and links to flare data (VSO website). The Level 0 MPEG movie archive provides MPEG movies of the XRT Level 0 data. Users can quickly check data availability and quality before accessing the archive. New tools and catalogs are always being developed and users are encouraged to visit the XRT webpage to find the latest data products available.

\begin{table}[h]
\hypertarget{catalogs}{}
\centering
\caption{\textbf{XRT Data Browsing Resources}}
\label{xrtcat}
\rowcolors{1}{}{gray!35}
\begin{tabular}{p{1.1in}p{.75\textwidth}}
\midrule
\T XRT website \B & \small \url{http://xrt.cfa.harvard.edu} \\
\T Helioviewer \B & \small \url{https://helioviewer.org/} \\
\T \mbox{XRT Synoptics} Gallery \B & {\small \url{http://solar.physics.montana.edu/HINODE/XRT/SCIA/latest_month.html}} \\ 
\T \mbox{XRT L0} MPEG  Archive \B & {\small{\url{http://solar.physics.montana.edu/HINODE/XRT/lev0_mma/}}} \\
\T \mbox{Hinode QL} Movie Archive \B & {\small{\url{http://hinode.nao.ac.jp/en/for-researchers/qlmovies/}}} \\
\T \mbox{XRT Flare} \mbox{Catalog} \B & {\small \url{http:/xrt.cfa.harvard.edu/flare_catalog/}} \\
\T \mbox{XRT Focus} \mbox{Catalog} \B & {\small{\url{http://xrt.cfa.harvard.edu/focus_catalog/}}} \\
\T Snapview \mbox{website} \B &  {\small \url{http://xrt.cfa.harvard.edu/missionops/snapview/snapview.html}} \\
\T XRT Picture of the Week \B & {\small \url{http://xrt.cfa.harvard.edu/xpow/}} \\
\end{tabular}
\end{table}
%
%
%
% OBTAINING XRT DATA
%
%
%
\hypertarget{obtaind}{}
\section {Obtaining XRT Data}\label{obtainingdata}
XRT data can be obtained from several outlets including the Darts/Hinode (ISAS, JAXA), the Virtual Solar Observatory (VSO), the Hinode Science Data Center Europe Archive, and the Lockheed Martin Solar \& Astrophysics Laboratory (LMSAL) Sungate website. 


%
%
%
%Hinode Darts
%
%
%
\subsection{Darts/Hinode}
The DARTS/Hinode website is at \url{https://darts.isas.jaxa.jp/solar/hinode/}. Here users can find data and information for all three Hinode instruments, including XRT. Data can be downloaded from this website. A very useful feature at this website is the \href{http://hinode.nao.ac.jp/en/gallery/latest/}{Hinode Latest Images}.


%
%
%
%VIRTUAL SOLAR OBSERVATORY
%
%
%
\subsection{Virtual Solar Observatory}

The VSO website, \hyperlink{Fig2_1}{Figure~\ref{Figure2_1}}, is at: \url{http://sdac.virtualsolar.org/cgi-bin/search} and allows users to search for solar data from several observatories. Users can select one or more ways to search for solar data by checking off the boxes they want and clicking the \textbf{Generate VSO Search Form} button located at the bottom of the screen. Currently, the VSO offers Level 1 XRT data as defined in \hyperlink{dataTypes}{Table~\ref{datatypes}}. 
%\setcounter{footnote}{0}
XRT data can be found in a variety of ways using this search form. If you are interested in searching XRT data based on the \textbf{Observable} option then you can check the \textbf{intensity} box after you click on the \textbf{Generate VSO Search Form} button.  The \textbf{Instrument/Source/Provider} box creates a form to search for data based on an instrument or data archive. The other categories of interest to XRT data users are \textbf{Spectral Range} (soft X-Rays [1 - 100\AA]), and \textbf{Nickname} (Soft X-Ray image). 

The direct way of finding XRT data is by searching by \textbf{Instrument/Source/Provider}. This creates a list of solar data currently a member of the VSO. The VSO generated search form is displayed in \hyperlink{Fig2_2}{Figure~\ref{Figure2_2}}. Once the time and instrument have been selected, choose the {\bf Search} button underneath the date. HINT: To change the date, change both years first, then both months, then both days. Otherwise the dates will automatically readjust.

Data for the dates of interest will appear in a form as seen in \hyperlink{Fig2_3}{Figure~\ref{Figure2_3}}. The left menu bar provides users with several ways to select the data. A user can select data by checking the box next to the desired entry or by using the \textbf{CheckBox Tools} menu where data can be selected above or below a selected box. Once all of the data has been selected click on the \textbf{Request Data} button in the left menu. \\
\indent Users are then directed to a page where they can select how to receive the data. Data can be downloaded via a URL or by creating a .tar file that will place the requested files in a staging area (see \hyperlink{Fig2_4}{Figure~\ref{Figure2_4}}). When selecting the tar file option, an email address may be required. 

\begin{figure}[H]
\hypertarget{Fig2_1}{}
\centering
\includegraphics[width=\textwidth]{VSO_MAIN_SCREEN.pdf}
\caption{The Virtual Solar Observatory (VSO) main menu.}
\label{Figure2_1}
\end{figure}
\newpage

\begin{figure}[H]
\hypertarget{Fig2_2}{}
\centering
\includegraphics[width=\textwidth]{date_instrument_select.pdf}
\caption{Search form generated after selecting the \textbf{Instrument / Source / Provider} box on the main VSO website. Hinode XRT data is provided by SAO.}
\label{Figure2_2}
\end{figure} 

\newpage

\begin{figure}[H]
\hypertarget{Fig2_3}{}
\centering
\includegraphics[width=\textwidth]{save_data_cart.pdf}
\caption{VSO form describing the data available given the search parameters. The \textbf{CheckBox Tools} menu in the left column can be helpful when selecting a large amount of data.}
\label{Figure2_3}
\end{figure}

\newpage

\begin{figure}[H]
\hypertarget{Fig2_4}{}
\centering
\includegraphics[width=\textwidth]{last_step.pdf}
\caption{VSO Data request page.}
\label{Figure2_4}
\end{figure}
%
%
%
% HINODE SCIENCE DATA CENTER EUROPE ARCHIVE
%
%
%
\subsection{Hinode Science Data Center Europe Archive}
The Archive Search page at the Hinode SDC Europe, \url{http://sdc.uio.no/search/}, has data from Hinode's three instruments (XRT, EIS, and SOT). The main page is shown in \hyperlink{Fig2_5}{Figure~\ref{Figure2_5}}. 

\hyperlink{Fig2_6}{Figure~\ref{Figure2_6}} shows a typical results page output,
which includes thumbnails (both a sample image from a dataset
and its field of view superimposed on a context synoptic image).
The `Action' column contains several icons for selection of 
data to download. Once data are selected, they can be retrieved
by clicking on the {\bf Retrieve} button at the bottom of the
page.  You will need to enter an email address to which the system 
will send a notification and instructions on how to download the
data once they are ready.

At the top of the webpage is a list of current instrument data in the archive. You can select XRT data here. In the \textbf{STATUS:} menu select `Level 0' data to get unprocessed data. Finally, you must provide a range of dates by entering the date(s) in the EPOCH\_START and EPOCH\_END fields. Once the desired parameter values have been selected click the \textbf{Search} button.

\begin{figure}[H]
\hypertarget{Fig2_5}{}
\centering
\includegraphics[width=\textwidth]{HinodeSDC_ArchiveSearch_uio_1.pdf}
\caption{Hinode Science Data Center Europe Archive Search page. Search parameters relevant to XRT are highlighted green in this image.}
\label{Figure2_5}
\end{figure}

\newpage

\begin{figure}[H]
\hypertarget{Fig2_6}{}
\centering
\includegraphics[width=\textwidth]{HinodeSDC_ArchiveSearch_uio_2.pdf}
\caption{Example search results from the Hinode SDC Europe Archive.}
\label{Figure2_6}
\end{figure} 

\newpage
%
%
%
% LOCKHEED MARTIN SOLAR AND ASTROPHYSICS LABORATORY SUNGATE WEBSITE	
%
%
%
\subsection{LMSAL Sungate Website}
Hinode XRT data may also be collected from the LMSAL Sungate webpage (\hyperlink{Fig2_7}{Figure~\ref{Figure2_7}}). \\ \url{http://www.lmsal.com/sungate/} 

There are multiple ways to search for XRT data. There is a direct link to the Hinode XRT catalog on this webpage as well as the Heliophysics Coverage Registry (HCR). Clicking the \textbf{Hinode XRT Archive} link will bring you to the search page shown in \hyperlink{Fig2_8}{Figure~\ref{Figure2_8}}.

The additional pages listed on the main page provide different  routes to the data; each page is equipped with explanations.
\begin{figure}[H]
\hypertarget{Fig2_7}{}
\centering
\includegraphics[width=\textwidth]{lmsal.pdf}
\caption{Lockheed Martin Solar \& Astrophysics Laboratory's Sungate website.}
\label{Figure2_7}
\end{figure}

\begin{figure}[H]
\hypertarget{Fig2_8}
\centering
\includegraphics[width=\textwidth]{pastedGraphic1.pdf}
\caption{LMSAL Solarsoft XRT catalog webpage.}
\label{Figure2_8}
\end{figure}

\newpage
%
%
%
% SEARCHING XRT DATA WITH THE XRT CATALOG
%
%
%
\hypertarget{searchxrt}{}
\section{Searching XRT Data with the XRT Catalog} \label{ssxrt}
The XRT catalog contains a subset of XRT FITS header keywords, (such
as field of view, filter positions, and image type), for every XRT
observation.  Using the catalog is a useful way to search data 
without downloading any of it. The catalog may be read and listed 
using the routine {\bf xrt\_cat.pro}.

In order to use this code, some ancillary XRT files are
necessary and can be installed by running {\bf sswdb\_upgrade} from
within SSWIDL and adding the {\bf hinode/xrt} branch of the SSWDB tree. 

\subsection{Using {\bf xrt\_cat.pro}}
This program returns XRT catalog records suitable for selecting 
data as a structure array. In the following example, the {\tt OFILES} 
keyword generates a list of files using the subroutine 
\textbf{xrt\_cat2files.pro}:  \\

%use mini page environment to keep these group of lines together and use verbatim so that you don't have to do special formatting on text.
\begin{minipage}{.9\textwidth}
\begin{verbatim}
IDL> t0=`2007-04-18T02:30:00'
IDL> t1=`2007-04-18T12:30:00'
IDL> xrt_cat, t0, t1, catx, ofiles
IDL> help, catx
    CATX    STRUCT   = ->  <Anonymous> Array[311]
IDL> help, ofiles
    OFILES   STRING   = Array[311]
    
Or it can be run with a specific search array for selecting data:
IDL> sa = ['ec_fw1_= Be_thin', 'ec_fw2_ = Open', 'naxis1 = 1024',]
IDL> xrt_cat, t0, t1, catx, ofiles, /level0, /url, /verbose, search_array=sa
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

There are several input and output keywords that can be set to provide additional information. 
\vspace{12pt}

\noindent Optional input keyword parameters: 
\begin{description}
\item {\tt SEARCH\_ARRAY}: (See {\bf struct\_where.pro}) Give 
a set of search parameters to further refine the data set.
\item {\tt \_EXTRA}: (Various possible types) Unknown parameters 
assumed to be in \\ PARAM=VALUE pairs (see {\bf struct\_where.pro}).
\item {\tt /QUICKLOOK}: (Boolean) If set, then return Quicklook data instead of Level 0 data. Overridden by {\tt /level0}.
\item {\tt /level0}: (Boolean) If set, then return Level 0 data. This is the default. Overrides \\ {\tt /QUICKLOOK}.
\item {\tt /level1}: (Boolean) If set, then returns Level 1 data URLs. If set, it forces {\tt /level0} and {\tt /URLS} to be set for the script to work, since it is really getting level0 URL links and replacing with the level1 version.
\item {\tt /URLS}: (Boolean) If set, then return {\tt OFILES} as 
URLs to a remote data server. (Default is to give local full paths.)
\item {\tt /REFRESH}: (Boolean) If set, then refresh the cache 
(i.e., re-read the catalog).
\item {\tt /TEMP}: (Boolean) If set, then use a temporary 
(i.e., offline/in-progress) catalog database.
\item {\tt /VERBOSE}: (Boolean) If set, print out extra information. 
Overrides {\tt /QUIET}. There are three levels of verbosity, in 
order of priority: (1) {\tt VERBOSE} displays all errors and 
messages. (2) {\tt  QUIET} suppresses all errors and messages. 
(3) No keyword displays all errors and some messages.
\item {\tt /QUIET}: (Boolean) If set, suppress messages.
\item {\tt /QSTOP}: (Boolean) For debugging.
\end{description}

\noindent Optional output keyword parameters: 
\begin{description}
\item {\tt OFILES}: (string array, [${\it N_{img}}$]) List of full 
path filenames for the Level 0 data matching the catalog. If 
{\tt /URL}, then instead returns data paths to a remote data 
server. This list is generated by a call to the program 
{\bf xrt\_cat2files.pro}. 
\item {\tt ERROR}: (scalar number) Returns the {\tt ERROR} keyword 
value from a call to\\ {\bf read\_genxcat.pro}.
\item {\tt QABORT}: (Boolean) Indicates that the program exited 
gracefully without completing. 
 \begin{description}
  \item 0: Program ran to completion.
  \item 1: Program aborted before completion.
 \end{description}
\end{description}
%
%
%
% SEARCH CRITERIA USED TO SELECT XRT DATA
%
%
%
\subsection{Search Criteria Used to Select XRT Data}
Further searching of XRT data can be done at the IDL command line using FITS keywords. All FITS values are in uninterpreted binary, with the exception that enumerated values are sometimes represented by string values instead of an integer. XRT follows with standard  FITS file naming conventions, available at \url{http://fits.gsfc.nasa.gov}. A complete list of Level 0 XRT header keywords is provided in \hyperlink{appendix}{Appendix A}. The following FITS file keywords may be of use. 
\begin{description}
\item {\tt EC\_IMTY\_}: Image type; input string values of `dark' or `normal'. 
\item {\tt EC\_FW1\_}: Filter Wheel 1 position; input string values of `Open', `Al\_poly', `C\_poly', \\ `Be\_thin', `Be\_med', `Al\_med'
\item  {\tt EC\_FW2\_}: Filter Wheel 2 position; input string values of `Open', `Al\_mesh', `Ti\_poly', `Gband',  `Al\_thick', `Be\_thick'
\item  {\tt EC\_VL\_}: Visible light shutter position; input string 
values of `open' or `closed'.
\item  {\tt NAXIS1}: General FITS keyword for pixel length in the  
{\it x}-direction; input integer value. XRT images are generally 
384$\times$384, 512$\times$512 or 1024$\times$1024; though any 
given area of the CCD can be read out. 
\item  {\tt NAXIS2}: General FITS keyword for pixel length in the 
{\it y}-direction; input integer value. 
\end{description}
\noindent Basic filter example:

{\tt IDL$>$ss=where(catx.ec\_imty\_ eq `normal' and catx.naxis1 eq 512)} \\

\noindent The following keywords are not useful for searching purposes, but are quite useful for interpretation purposes:
\begin{description}
\item {\tt EXPTIME} : This keyword represents the duration of the CCD
  exposure for normal images in seconds. {\tt EXPTIME} is useful for
  sorting long/short pairs.
\item ({\tt DATE\_OBS} + {\tt DATE\_END}) / 2: Performing this 
calculation best represents the UT time the exposure was taken. 
\end{description}
%
%
%
%READING XRT DATA
%
%
%
\section{Reading XRT Data}
\subsection{Using {\bf read\_xrt.pro}}
All XRT image headers and data can be read using the IDL routine {\bf read\_xrt.pro}, which calls the subroutine {\bf mreadfits.pro}. Because XRT images are of various sizes, {\bf read\_xrt.pro} can read header and data information for images of various sizes using the keyword {\tt /FORCE}. If the {\tt /FORCE} keyword is used to read image data of various sizes, the data array will be given the maximum required dimensions. Smaller images will be embedded in the lowest corner of the respective 2D slice, with zero values in the buffer pixels. These small images will retain their original {\tt NAXIS1} and {\tt NAXIS2} keywords; for example, if a 512$\times$512 image is embedded in a 2048$\times$2048 array, the {\tt NAXIS1} and {\tt NAXIS2} keywords for that image will read 512 and 512, respectively. Continuing with the example in \hyperlink{searchxrt}{Section~\ref{ssxrt}}. \\

%use mini page environment to keep these group of lines together and use verbatim so that you don't have to do special formatting on text.
\begin{minipage}{0.95\textwidth}
\noindent Basic call, to read headers and data:
\vspace{-6pt}
\begin{verbatim}
IDL> ss=where(catx.ec_imty_ eq `normal' and catx.naxis1 eq 2048)
IDL> read_xrt, ofiles[ss], index, data
IDL> help, ofiles[ss]
    <Expression>    STRING    = Array[5] 
IDL> help, index
    INDEX           STRUCT    = ->   <Anonymous>  Array[5]
IDL> help, data
    DATA            INT       = Array[2048, 2048, 5]}
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

\noindent Basic call, to read headers only:

{\tt IDL$>$ read\_xrt, ofiles, index} \\

\noindent To read headers and data for images of various sizes: 

{\tt IDL$>$ read\_xrt, ofiles, index, data, /force} \\

\noindent To suppress messages from mreadfits.pro: 

{\tt IDL$>$ read\_xrt, ofiles, index, data, /force, /quiet} \\

\noindent To display extra information:

{\tt IDL$>$ read\_xrt, ofiles, index, data, /force, /verbose} \\

\noindent The {\tt index.History} keyword is updated to reflect the origin file of the data:
\vspace{3pt}

    %use mini page environment to keep these group of lines together and use verbatim so that you don't have to do special formatting on text.
\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> print, index[0].History
    READ_XRT v2007-May-09: (22-May-2007 17:56:30)
    Read header only.
    Origin file: XRT20070418_111203.0.fits
\end{verbatim}
\end{minipage}
%
%
%
% CALIBRATING XRT DATA
%
%
%
\section{Calibrating XRT Data}
\hypertarget{xrtprep}{}
\subsection{Using \textbf{xrt\_prep.pro}}  \label{prepxrt} 
The routine \textbf{xrt\_prep.pro} is similar in nature to {\bf trace\_prep.pro}, {\bf eit\_prep.pro} and \\ {\bf sxt\_prep.pro}. The routine is intended to convert Level 0 data to Level 1 data. This process adds additional keywords to the Level 1 data FITS header.

It is important to note that if images of different sizes were read in using \textbf{read\_xrt.pro}, the values for the {\tt NAXIS1} and {\tt NAXIS2} keywords are preserved. The data output from \textbf{xrt\_prep.pro} defaults to 2*I for historical and memory conservation. Users are recommended to apply the {\tt /FLOAT} keyword always unless they are constrained by available memory. The calibrations applied by \textbf{xrt\_prep.pro} are discussed in the paper by \citet{Kobelski13}. \\

\noindent Basic call:

{\tt IDL$>$ xrt\_prep, input1, input2, index\_out, data\_out} \\  

\noindent Where {\tt input1} and {\tt input2} can take on one of two different values:\\

\noindent {\it Case 1}

Input 1: XRT FITS file list as a string scalar or array. 

Input 2: The data set number(s) to extract and process. \\

\noindent {\it Case 2}

Input 1: The index structure for the file list as a structure array. 

Input 2: The data array(s) as an integer array.\\

\noindent The basic calls for each case (\emph{example data from \hyperlink{searchxrt}{Section~\ref{ssxrt}}}): 
\vspace{6pt}

\begin{minipage}{0.95\textwidth}
\noindent {\it Case 1}: 
\vspace{-6pt}
    %use mini page environment to keep these group of lines together and use verbatim so that you don't have to do special formatting on text.
\begin{verbatim}
IDL> dset_arr = where(catx.ec_fw2_ eq `Ti_poly' and $
     catx.naxis1 eq 2048 and catx.ec_imty_ eq `normal')                      
IDL> xrt_prep, ofiles, dset_arr, index_out, data_out
IDL> help, ofiles
    OFILES     STRING   =    Array[311]
IDL> help, dset_arr
    DSET_ARR   LONG     =    Array[2]
IDL> help, index_out
    INDEX_OUT  STRUCT   =    -> <Anonymous> Array[2]
IDL> help, data_out
    DATA_OUT   INT      =    Array[2048, 2048, 2]
\end{verbatim} 
\end{minipage} \\
\vspace{12pt}

\begin{minipage}{0.95\textwidth}
\noindent {\it Case 2}: 
\vspace{-6pt}
\begin{verbatim}
IDL> read_xrt, ofiles[dset_arr], index, data 
IDL> xrt_prep, index, data, index_out, data_out, /float 
IDL> help, index
    INDEX      STRUCT   =    -> <Anonymous> Array[2]
IDL> help, data
    DATA       INT      =    Array[2048, 2048, 2]
IDL> help, index_out
    INDEX_OUT  STRUCT   =    -> <Anonymous> Array[2]
IDL> help, data_out
    DATA_OUT   FLOAT    =    Array[2048, 2048, 2]}
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

The routine will output the updated index structure of the input images as a structure array $[N_{img}]$ and processed output images as an integer array $[N_x, N_y, N_{img}]$. 

\noindent The executed steps (including possible options) are:
\begin{enumerate}
\item Read in raw FITS image(s) from a filelist or read in a datacube and structure.
\item Fill pixels of value = 0 (missing data) with a ``missing data value'' = -999.
\item Replace near-saturated pixels for values greater than some threshold \\ \mbox{(default: 2500 DN)}. 
\item Option to remove radiation-belt/cosmic-ray hits and streaks.
\item Calibrate for read-out signals.
\item  Locate missing pixels and replaces their values with a linear patch to improve \\ Fourier filter performance.
\item Remove the CCD bias (pedestal), and dark current (using the subroutine \\ {\bf xrt\_clean\_ro.pro} which also calibrates the read-out signals).
\item Remove vignetting.
\item Option to normalize each image for exposure time.
\item Option to compute map of calibration uncertainties.
\item Option to cosmetically correct for contamination spots or dust.
\item Output the corrected image(s) in an updated structure and data cube.
\item Option to coalign XRT data using \textbf{xrt\_read\_coaldb.pro}.
\end{enumerate}

\noindent Optional input keyword parameters: 
\begin{description}
\item {\tt /NORMALIZE}: (Boolean) Set to normalize output image to DN per sec. The data output will not default to floating point. Use the {\tt /FLOAT} keyword.
\item {\tt /FLOAT}: (Boolean) Set if you want to return floating point (default is I*2). Users are recommended to always apply the {\tt /FLOAT} keyword unless they are constrained by available memory.
\item {\tt CLEAN\_TYPE}: Type of Fourier cleaning to use
	(see subroutine \\ {\bf xrt\_fourier\_vacuum.pro} for details:
	\begin{description}
	\item[] 0 = prefilter on semi-fixed streaks, then remove remaining Fourier streaks, stars, and smudges [default].
         \item[] 1 = remove semi-fixed streaks only.
	\item[] 2 = remove Fourier streaks, stars, and smudges.
	\item[] 3 = no Fourier cleaning applied.
	\end{description}
\item {\tt BSUB\_TYPE}: Type of (model) background subtraction to use:
	\begin{description}
	\item[] 0 = remove Nyquist ringing and large-scale background ramp [default].
	\item[] 1 = remove Nyquist ringing only.
	\item [] 2 = remove large-scale background ``ramp'' only.
	\item[] 3 = no (model) background subtraction applied. 
	\item[] Note: {\tt DARK\_TYPE}=1 resets {\tt BSUB\_TYPE}=3.
	\end{description}
\item {\tt DARK\_TYPE}: Type of dark subtraction to use:
	\begin{description}
	\item[] 0 = if possible, use the model dark with median adjusted to median 
	of cleaned darks nearby in time [default]. Otherwise, shift to {\tt DARK\_TYPE}=2.
	\item[] 1 = if possible, use the median of cleaned darks nearby in time; otherwise, as in the above case, it will shift to {\tt DARK\_TYPE}=2.
	\item[] 2 = use model darks without median adjustment (this corresponds to the old default of the {\bf xrt\_prep.pro} version prior to `v2009-Jul-11').
	\item[] Note: {\tt DARK\_TYPE}=1 resets {\tt BSUB\_TYPE}=3.
	\end{description}
\item {\tt NSIGMA}: Number of standard deviations beyond which an FFT pixel is considered bad in the Fourier Star removal (see \textbf{xrt\_fourier\_vacuum.pro} for details.) The default is 4.5. It is not recommended to go below 4.0.

\item {\tt NMED}: Number of standard deviations above smoothed central minimal background to begin shielding (presumed) data from correction (see \textbf{xrt\_fourier\_vacuum.pro} for details). The default is 3.5. It is not recommended to go outside the range of 2.0 to 4.5.

\item {\tt /STOP\_BLEED}: (Boolean) Set if pixels corrected for saturation ``bloom/bleed" at the edge of saturated region(s) are to be retained. The default is to revert the pixels to their input values.

\item {\tt /DESPIKE\_DESPOT}: (Boolean or integer) 
Set = N ($1\le \mathrm{N} \le 3$) for N passes to remove radiation belt and cosmic-ray spikes. This method uses convolution and thresholding to remove spikes and may remove small real features. It automatically makes a cosmetic correction to contamination spots (spline-based). See  \textbf{xrt\_tup\_contam.pro} for an alternative, median-cap cosmetic correction. The default is not to remove spikes or spots. If set, it combines {\tt /ONLY\_DESPIKE} and {\tt /ONLY\_DESPOT} and overrides these too. These are considered cosmetic corrections and should not be used on data for quantitative analysis. 

\item {\tt /ONLY\_DESPIKE}: (Boolean or integer) Set = N ($1\le \mathrm{N} \le 3$) for N passes of removal radiation belt/cosmic-ray spikes. This method uses convolution and thresholding to remove spikes and may remove small real features and/or reduce the overall sharpness of the image. The default is not to removes spikes from data. This is considered a cosmetic correction and should not be used on data for quantitative analysis. 

\item {\tt /ONLY\_DESPOT}: (Boolean) Set to make a cosmetic correction to the contamination spots (spline-based). See \textbf{xrt\_tup\_contam.pro} for an alternative, median-cap cosmetic correction. The default is not to correct for spots. This is considered a cosmetic correction and affected pixels should not be used for quantitative analysis. 

\item {\tt SENS\_DESPIKE}: (Float scaler) This number controls the aggressiveness of the despiking routine. Values in the range 1.1 to 1.5 work well. Values less than 1.0 are rejected for the default. Default = 1.4. See \textbf{xrt\_despike2.pro} for more information.

\item {\tt SPOTTHRESH}: (Float scaler) $0\le$ {\tt SPOTTHRESH} $\le 1,$ or $-1.$ If value is between 0 and 1, the threshold fraction of a spotted binned pixel at which the binned pixel is treated as spotted [default=0.5]. Normally, the program only corrects spots if it determines they are sufficiently dark for speed. If = -1, force treatment of all spots regardless of how long it could take. 

\item {\tt GRADE\_TYPE}: (Integer) Type of grade\_map array to output. See {\tt /GRADE\_MAP} below, and {\bf xrt\_pixel\_grade.pro}.
	\begin{description}
	\item[] 0 = byte array containing coded grade of pixel indicating pixel affected by saturation, saturation bloom/bleed, contamination spot, dust, hot pixel, or dust growth. See \hyperlink{xrtcont}{Section~\ref{contamination}} for details about the effects of contamination on XRT data and implications for data analysis [default].
	\item[] 1 = double array, same as {\tt GRADE\_TYPE}=0 but with added encoding for the number of 1x1 pixels affected within each binned pixel (useful only for binned data).
	\item[]2 = do not return a grade array.
	\end{description}
	
\item {\tt COALIGN}: (Boolean or integer) Set to type of coalignment to apply to XRT data.
	\begin{description}
	\item[] 0 = [default]: use UFSS data.
	\item[] 1 = use UFSS data plus cross-correlation with AIA 335 \AA .
	\item[] 2 = No adjustment.
	\end{description}
	
\item {\tt /QUIET}: (Boolean) Set for no messages or errors. The default is some messages and all errors.

\item {\tt /VERBOSE}: (Boolean) Set for all messages, errors, and intermediate data listings. Suppresses {\tt /QUITE}.

\item {\tt /QSTOP}: (Boolean) For debugging.
\end{description}

\noindent Optional output:
\begin{description}
\item {\tt DATA\_OUT2}: (integer array, $[N_x, N_y, N_{img}]$ Processed output XRT images (data cube) like {\tt DATA\_OUT} but without cosmetic correction for contamination spots, dust, and dust growth. The default data type is I*2. See the {\tt /FLOAT} keyword. This will only return an array if any of the following keywords are used:  {\tt /ONLY\_DESPIKE}, {\tt /ONLY\_DESPOT}, or \\ {\tt /DESPIKE\_DESPOT}. 
\end{description} 

\begin{minipage}{0.95\textwidth}
\noindent The basic call for the optional output:
\vspace{-6pt}
\begin{verbatim}
IDL> xrt_prep, index, data, index_out, data_out, data_out2, $
    /float, /despike_despot
IDL> help, index
    INDEX      STRUCT   =    -> <Anonymous> Array[5]
IDL> help, data
    DATA       INT      =    Array[1024,1024,5]
IDL> help, index_out
    INDEX      STRUCT   =    -> <Anonymous> Array[5]
IDL> help, data_out
    DATA       FLOAT    =    Array[1024,1024,5]
IDL> help, data_out2
    DATA       FLOAT    =    Array[1024,1024,5]
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

\noindent Optional output keyword parameters: 
\begin{description}
\item {\tt MISS\_MAP}: (byte array, [${\it N_{x}, N_{y},N_{img}}$]) 
This is a 2D Boolean map of each image. 
	\begin{description}
	\item[] 0: mage pixel had data. 
	\item[] 1: Image pixel was missing data and was replaced with the image average.
	\end{description}

\item {\tt N\_MISS\_PIXELS}: (long array, [$N_{img}$]) Number of missing pixels found in each image.

\item {\tt GRADE\_MAP}: (byte array or double array if {\tt GRADE\_TYPE}=1, $[N_x, N_y, N_{img}]$) This is a 2D map of each image with a value given by the sum of:
	\begin{description}
	\item[] 0: Image pixel was okay.
	\item[] 1: Image pixel was saturated and was replaced with a constant.
	\item[] 2: Pixel was affected by saturation bloom/bleed. If {\tt STOP\_BLEED}=1 it was replaced by a local median.
	\item[] 4: Pixel was affected by a contamination spot.
	\item[] 8: Pixel was affected by a dust speck.
	\item[]16: Pixel was a hot pixel.
	\item[] 32: Pixel was a potential dust growth pixel.
	\end{description}
If {\tt GRADE\_TYPE}=1, a fraction is added encoding the number of $1\times1$ spot, dust, and hot pixels per binned pixel. Fractions are relevant only for spot, dust, and hot grades.

For each of these grade types, two digits to the right of the decimal place are reserved for the number of $1\times1$ pixels within the binned pixel which are of the given type. The digits are assigned in the same order as listed above. For example, a $4\times4$ binned pixel that has $1\times1$ pixels of which 8 are okay, 3 are spotted, 2 are dust, and 4 are hot has a grade that is $2+8+16=26,$ plus $0.030204,$ or $26.030204.$ (This is potentially useful for thresholding pixels by the degree of ``damage" - e.g., if only one $1\times1$ pixel in an $8\times8$ pixel is affected by a contamination spot, (i.e. only 1/64 spotted) the user may wish to treat it as okay for purposes of their further analysis. The grade map may be decoded into separate arrays (one map per grade type) using \textbf{xrt\_pixel\_grade.pro}.
\item{\tt N\_GRADE\_PIXELS}: (long array, [6,$N_{img}$]) Number of graded pixels of each type (saturation, bloom/bleed, spot, dust, and hot respectively) found in each image.
\item{\tt SPIKE\_MAP}: (byte array, $[N_x,N_y,N_{img}$]) This is a 2D Boolean map of each image:
    \begin{description}
    \item[] 0: Image was okay.
    \item[] 1: Image pixel was found to be a particle hit and replaced by the local average.
    \end{description}
\item{\tt N\_SPIKE\_PIXELS}: (long array, [$N_{ing}$]) Number of spike pixels found in each image.
\item {\tt RUN\_TIME}: (Float scalar) The run time in seconds for 
{\bf xrt\_prep.pro}.
\item {\tt QABORT}: (Boolean) Indicates that the program exited gracefully without completing.
\begin{description}
\item 0 = program ran to completion.
\item 1 = program aborted before completion.
\end{description} 
\item {\tt UNCERT\_MAP}: Returns an array of the photometric uncertainties within the XRT. These are non-statistical errors caused by JPEG compression, and uncertainties in vignetting, dark correction and filtering. No statistical/photometric errors are included. See the routine \textbf{xrt\_cvfact.pro} to add in the photon statistics.
\end{description}
%
%
%
% ROUTINES USED BY XRT_PREP.PRO
%
%
%
\subsection{Routines Used by  \textbf{xrt\_prep.pro}}
\subsubsection{xrt\_despike2.pro}
The despike module is used to smooth out cosmic ray hits. Generally, this is intended as a cosmetic fix, not as a scientific recalibration of the spiked pixels. However, unspiked pixels are not affected and the {\tt SPIKE\_MAP} can be used to identify the corrected pixels. Therefore, this keyword should be used cautiously when prepping display images, and possibly should not be used at all for quantitative data analysis. This routine replaces the older version of \textbf{xrt\_despike.pro}.

\subsubsection{xrt\_med\_dark.pro}
This program searches for full-frame darks in the XRT data archive, creates a full-frame median dark template and then generates an appropriate dark for the image being processed. Users can specify how many real darks are used to create a model dark and if a local archive does not exist the user can use \textbf{xrt\_search\_network.pro} to set the proper environment variables and retrieve the dark files to create the best possible dark correction. Users can create a single median dark based of the index of the data they want to process. \\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> dark = xrt_med_dark(index)
\end{verbatim}
\end{minipage} \\

This generates a single median dark that can be used for dark subtraction or baseline calibration. The output dark already has the Nyquist ringing removed but users have the option to recover the raw median dark with the ringing still included by adding it back via the commands: \\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> data_nonyq = no_nyquist(data,index)
IDL> dark_raw = dark + (data - data_nonyq)
\end{verbatim}
\end{minipage} \\

\subsubsection{xrt\_clean\_ro.pro}
The CCD camera has different bias voltages in odd and even pixel columns. As a result, XRT images show a prevalent sawtooth pattern in $x$ at the Nyquist frequency, with a peak-to-peak amplitude of $\approx 2.6$ DN. There is also a low-level large-scale ``ski-ramp" in $y$ with a shape which can be approximated by an exponential decrease (amplitude $\approx$ 4.3 DN, {\it e}-folding width $\approx 185$ pixels) and a weak linear increase on a base of $\approx 42$ DN, which is best seen in dark frames. 

The Fourier transform of an XRT dark shows many odd features, including ``streaks" (narrow ridges of power spanning all {\it y}; many are semi-fixed in location), 2D Voigt profiles, and truncated streaks. The latter two features are typically variable in $y$ position; all vary in amplitude. These features are present (though less clearly visible) in the Fourier transform of data as well. The routine \textbf{xrt\_clean\_ro.pro} addresses all of these issues while minimizing artifacts processing data creates.

The procedure removes the bias pattern Nyquist ringing (using {\bf no\_nyquist.pro}), the large-scale ramp (using {\bf lsback\_away.pro}), and the periodic features \\ (using \textbf{xrt\_fourier\_vacuum.pro}), in that order. The Fourier filtering can take a while on large images ($\approx.$15 seconds on a 2048$\times$2048 pixel image using a MacPro with dual 3GHz Xeon chips). Low frequencies on the transform are shielded from correction to avoid damaging the data; thus some low frequency read-out components will remain. Fourier patterns are not removed if a large part of the image ($45\% - 80\%$ depending on image size) is saturated. The basic call is as follows:  \\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> xrt_clean_ro, image_in, image_out, hist=hist
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

Sometimes, the the default parameters cause the routine to correct some parts of the transform which contain a non-negligible data component in the Fourier power. In these cases, the read-out signals can be over-corrected. This can cause sync ``ringing" around small, bright features in the corrected image. To reduce this, one can experiment with increasing the threshold for Fourier feature removal ({\tt NSIGMA} [default=4.5]) and/or decreasing level above background in Fourier space to begin data shielding ({\tt NMED} [default=3.5]). For example: \\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> xrt_clean_ro, image_in, image_out, hist=hist, nsigma=5.0, $
    nmed=3.0
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

\noindent It may also be useful to experiment with the form of the Fourier analysis by changing {\tt CLEAN\_TYPE}. For example:  \\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> xrt_clean_ro, image_in, image_out, hist=hist, clean_type=1, $
     nsigma=5.0, nmed=3.0
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

\noindent Filtering out cosmic ray hits (see {\tt /ONLY\_DESPIKE}) may also be helpful in such cases.  

The best available (default) dark subtraction method uses observed darks near
in time to the observations to optimally adjust the model dark's base level
({\tt DARK\_TYPE}=0).
After the high gain antenna failure January 2008, full-frame 1x1 binned darks
were rarely taken, for telemetry reasons.  The latest version of the software
uses the $512 \times 2048$ strip darks (which are taken regularly after 
August 2009) to emulate the full-frame 1x1 binned darks, and a note to 
that effect is placed in the history array.

Ordinarily, the program will search the users local copy of the XRT  data
archive to find and retrieve the required dark frames for the default
dark subtraction method.
Users without a local copy of the XRT archive have two options:
\begin{enumerate}
\item They may simply do nothing, in which case \textbf{xrt\_prep} will search for the dark files locally, and, not finding
them, will default to a pure model dark ({\tt DARK\_TYPE}=2).  This may
result in a slightly less accurate setting of the zero point in the
reduced data, but may be sufficient for many purposes.
\item They may permit \textbf{xrt\_prep} to copy the required 
darks from a remote data archive.  Before running \textbf{xrt\_prep}, the user must run a program called \textbf{xrt\_search\_network}
that will set up the required paths, permit remote copying, and make a (temporary) local archive for the darks needed.
\end{enumerate}

{\tt IDL$>$ xrt\_search\_network,/ENABLE } \\

\noindent When the \textbf{xrt\_prep} session is finished, the paths and permissions can be reset by: \\

{\tt IDL$>$ xrt\_search\_network,/DISABLE } \\

The user should be aware that remote coping is network speed dependent and that this routine will make a new directory tree in the current directory emulating the structure of the data archive needed.  The user may delete this tree after prepping, if desired.

\subsubsection{xrt\_pixel\_grade.pro}
This routine identifies the grade of an XRT pixel in an $N_x \times N_y$ array. It reports whether the pixel is affected by saturation, saturation bloom/bleed, contamination spots, dust/weakness (low QE), is ``hot", or is a contamination growth on a dust speck and optionally (for binned data) the fraction of the pixel so affected. Users can change the mode of the program by setting the keyword {\tt INTERPRET} = 1. This will interpret a grade array by generating an $N_x \times N_y \times 6$ array which gives the locations (and optionally, in the binned case when {\tt GRADE\_FRAC} = 1, the fractional contribution to the pixel) of saturation, bloom/bleed, contamination spot, dust/weakness, hot, or dust growth pixels.

\subsubsection{nono\_vignette.pro}
This routine removes the vignetting function from the XRT images. The vignetting function only includes the effects due to the physical obstruction by parts of the telescope and does not include any wavelength dependent effects of the reflectivity of the mirror. For a complete discussion of the vignetting function see~\citet{Kobelski13}.

\subsubsection{xrt\_unc\_rel.pro}
When a user wants to calculate the uncertainty of the XRT data based on the dark correction, Nyquist noise correction, Fourier filter correction, JPEG compression, and vignetting, \textbf{xrt\_prep} calls this function. This function does not take binning into account in the JPEG analysis yet and it recovers the relative uncertainty squared. The actual uncertainty can be recovered by applying the following formula. Let $u$ be the uncertainty, $u_r$ represent the relative uncertainty and $d$ be the prepped data,  then \[ u^2 \, = \, u_r^2 * d^2.\]
\textbf{xrt\_prep} applies this formula to generate the output uncertainty array. For further discussions about how the uncertainties in XRT data are calculated see the paper by~\citet{Kobelski13}. 

\subsubsection{get\_xrt\_expdur.pro}
If normalization of the data is requested in \textbf{xrt\_prep.pro} this function retrieves the exposure duration of the image. The measured exposure duration of the image is stored in the FITS header keyword {\tt E\_ETIM} for normal images and {\tt EXCCDEX} for dark images. These keywords will be updated when the data is normalized by \textbf{xrt\_prep} and it is recommended that users update these keywords when they renormalize the data by any factor.  

\subsubsection{xrt\_spotcor.pro}
This routine makes cosmetic correction for CCD spots and dust on XRT data. It achieves this by using thin-plate splines. It is called using the keywords {\tt /DESPIKE\_DESPOT} or \\ {\tt /ONLY\_DESPOT}. To use this routine, the image array must be composed of images of all the same size, binning, ccd location, and spot epoch. This routine does not work on Gband data. It also doesn't work well for $8 \times 8$ binned data but it does a reasonable job for lower binning levels.

The program assumes the timespan of the data in the cube is short enough that the evolution of the underlying structures is not important. It defines the spots which require correction based on the first image in each filter. Since the effect of the spots depends on the temperature of the underlying feature, their evolution over the timespan of the cube should be minimal for the spot correction to be optimal.

The correction is not photometric, though it should be reasonably good in most cases, provided the above guidelines are followed.  The latest versions (after the February 2014 update) include a cosmetic correction for dust on the CCD and the growth seen in the dust after bakeouts post light leak (May 2012). The latter dust growth pixels are added to the output spot array but are separately designated (grade = 32) in the grade maps produced by \textbf{xrt\_pixel\_grade.pro}. The model for the dust growth will likely improve over time. See \hyperlink{xrtcont}{Section~\ref{contamination}} for further discussions about cosmetic corrections to XRT data.
%
%
%
% CONTAMINATION 
%
%
%
\hypertarget{xrtcont}{}
\subsection{Contamination}\label{contamination}
Since launch, contaminating material has accumulated on the XRT
CCD and focal plane filters (FPFs), causing a decrease in sensitivity.
The effect of contamination is wavelength dependent, and the thickness 
of the contaminant deposited on the FPFs is different for each filter,
therefore contamination affects the response of each XRT filter 
differently (see \cite{2011SoPh..269..169N} and \cite{Narukage14}).

The accumulation of contaminant on the CCD has significantly affected the XRT filter responses, especially for observations carried out with the 
thinner filters for which the longer wavelength contribution, more absorbed by the contaminating material, is higher. Therefore, in order to recover as much as possible the initial 
sensitivity of the instrument, a CCD bakeout has been performed to evaporate the accumulated material. 

After each CCD bakeout, the contaminant layer on the XRT CCD gets thicker with time. Since the thickness of the layer impacts the temperature sensitivity of XRT, we routinely estimate the thickness by using Gband (and light leak) data. A repository of the layer thickness is distributed through SSW and updates happen about once every three weeks. Information regarding the contaminant thickness as a function of time is available online at \url{http://solar.physics.montana.edu/HINODE/XRT/xrt_contam/index.html}.

Users can determine when the latest update happened by updating their XRT branch of SolarSoft and checking the last entry of the file,\\ \$SSW/hinode/xrt/idl/response/contam/xrt\_contam\_on\_ccd.pdf. 


\subsubsection{Contaminant Spots on CCD}

After this first bakeout, spots have appeared in both X-Ray and 
Gband XRT images, and they have been interpreted as due to contaminant 
material congealed in beads on the CCD surface during the bakeout
process. A month-long bakeout has been performed soon after the 
first one, however it did not remove most of these spots.
To avoid formation of additional permanent contamination spots
the XRT team now performs CCD bakeouts on a regular schedule (at 
intervals of about 3 weeks), and this regime has proven successful 
in maintaining the CCD contamination layer thin enough to affect 
only minimally the filter responses (see \hyperlink{Fig2_9}{Figure~\ref{figure2_9}})
and to be removed efficiently 
by the bakeouts without formation of additional spots.
As of October 2009, the ratio of spot area to full CCD area is 
$\approx 5.2$\%.

\begin{figure}[H]
\hypertarget{Fig2_9}
\centering
\includegraphics[width=\textwidth]{tresp_CCDcont_effect.pdf}
\caption{Effect of contamination layer, accumulating 
on the CCD between a bakeout and the next, on the XRT temperature 
response of Al\_mesh (black curves), C\_poly (red curves), and Be\_thin (blue
curves). The solid lines are responses calculated for 2009-09-24, right
after a CCD bakeout, and the dashed curves are calculated for 2009-10-15,
i.e.\ three weeks later and just before the following bakeout. The
comparison shows that in the regime of regular bakeouts, adopted since
mid-2008, only the thinnest filter shows any detectable, though minimal, 
change in response due to accumulation of contaminating material on the 
CCD between bakeouts.}
\label{figure2_9}
\end{figure}

The {\bf xrt\_prep.pro} routine thoroughly described in the above \hyperlink{xrtprep}{Section~\ref{prepxrt}} provides a map of pixels affected 
by contamination spots, which should be excluded from analysis and has the option to cosmetically correct the data (see keyword parameters {\tt GRADE\_TYPE} and {\tt GRADE\_MAP}). 
In addition, there are two routines for cosmetic correction of the contamination spots available outside of \textbf{xrt\_prep.pro}. \textbf{xrt\_tup\_contam} replaces each contamination spot with the median of the pixels at the edge of each spot. \\

\noindent Basic call to get correct a datacube and indices: \\

{\tt IDL> xrt\_tup\_contam, ind\_in, dat\_in, ind\_out, \$ \\ dat\_out[,spotmaps=spotmaps]} \\

The optional keyword {\tt SPOTSMAPS} gets maps of which pixels were patched for each image. \\

\textbf{xrt\_spotcor} uses thin-plate splines to smoothly patch over a spot. \\

\noindent Basic call to get a corrected array of image: \\

{\tt IDL> xrt\_spotcor, index, data, index\_out, data\_out} \\

Call to get a corrected array of image, spot arrays (spotmap), get spot statistics \\ (numspots), and change spot threshold from default (=0): \\
	
{\tt IDL> xrt\_spotcor, index, data, index\_out, data\_out, numspots, \$ \\*
         spotmap, thresh=thresh} \\

The threshold allows the user to ``accept" (treat as non-spotted) 
low levels of spot contamination in binned pixels.  For example, one
would set {\tt THRESH}=1/16 if a single spot 1x1 pixel in a 4x4 binned pixel was
acceptable.
For \textbf{xrt\_spotcor} to work successfully, the data must be of the 
same size, binning level, CCD location, and cover a reasonably small
span of time. An example image processed with \textbf{xrt\_spotcor.pro} is given in \hyperlink{Fig2_15}{Figure~\ref{figure2_15}}. 


\begin{figure}[H]
\hypertarget{Fig2_15}
\centering
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{spotty_prepped_almesh.png}
\end{subfigure} \quad
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{spotty_spotcor_almesh.png}
\end{subfigure}
\caption{An example Al\_mesh image taken on 5-August-2010 at 10:01UT. \emph{Left}: The prepped data without spot correction. \emph{Right}: The output image from the routine \textbf{xrt\_spotcor.pro}. The severity of the spots depends on wavelength with the Al\_mesh filter being most affected. Spot correction can be done from within \textbf{xrt\_prep.pro} and a spot map should be generated to locate affected pixels.}
\label{figure2_15}
\end{figure}

The {\bf xrt\_tup\_contam} routine is faster, though providing more coarse correction,
in particular doing less well in cases where the spot lies over a region which has
strong intensity gradients.  
{\bf xrt\_spotcor}, is slower, but does a better job when there are significant 
gradients in intensity; it is the default spot corrector in \textbf{xrt\_prep}.   

We restate that at present no method is available for quantitative correction 
to restore in the affected pixels the capabilities for quantitative analysis.
Therefore, pixels affected by contamination spots should be excluded from
any quantitative analysis.  
%
%
%
% CONTAMINAT LAYER ON FOCAL PLANE FILTERS
%
%
%
\subsubsection{Contaminant Layer on Focal Plane Filters}

The contaminant layer deposited on the FPFs has different characteristics:
it was accumulated in the first few months from the start of the mission,
for each filter to an extent roughly proportional to their use,
and it apparently remained constant after mid-June 2007 when the operational
heaters were permanently turned on (and have stayed on until now, October 2009)
keeping the temperature of the FPFs high enough ($\approx 20^\circ$C)
to prevent further accumulation of contaminant.

The (wavelength dependent) effect of the layer of contamination on each of 
the FPFs on the temperature response is modeled and included in the 
instrument response (see \hyperlink{xrtresp}{Section~\ref{xrtfilter}} for further details).
The effect of this contaminant layer on the FPFs is very limited for 
most filters, though it is significant for observations carried out 
with the Al\_poly and (to a lesser extent) Al\_mesh filters.
%
%
%
% Light Leak 
%
%
%
\subsection{Light Leak Overview}

The XRT periodically sees an increase in visible stray light contamination, often referred as either \emph{stray light} or \emph{light leak}; summarized in \hyperlink{StrayLight}{Table~\ref{straylight}}. The leading idea for this increase is a pinhole in the telescopes entrance filter, which allows for some transmission when the visible light shutter is closed. This has lead to significant visible light contributions to X-Ray images in some of the thinner XRT X-Ray filters. \hyperlink{Fig2_16}{Figure~\ref{figure2_16}} shows equivalently-scaled Ti\_poly synoptic images taken before and after the first light leak; note the additional diffuse emission. 

Since the Beryllium images and the thicker Aluminum images remain unaffected, and the Al\_poly and Al\_mesh images are correctable, XRT still retains the ability to make images in a full range of temperatures, and to distinguish plasmas of different temperatures via all the standard analysis techniques.

After 14 June 2015 the T\_poly and C\_poly filters should not be used for quantitative analysis, although they might be useful as context images. The XRT Team eliminated the C\_poly and Ti\_poly filters from all future observation programs. G\_band images are still useful for calibration purposes and should be considered to be ``engineering data". The Al\_mesh and Al\_poly images are marginally affected, and may be used with care. Their largest component is estimated to be at the ~10 DN/s level, so the effect is negligible for active regions, but more important for dark features. The thicker filters are not significantly affected and may be used as before.

Users of XRT data are encouraged to visit the links provided in \hyperlink{StrayLight}{Table~\ref{straylight}} for a detailed analysis of the stray light for each affected filter and to determine whether a data set needs correcting.

\begin{table}[h]
\hypertarget{StrayLight}
\centering
\caption{\bf {Summary of Stray Light Events and Links to Analysis Webpages}}
\label{straylight}
%\rowcolors{1}{}{gray!35}
\begin{tabular}{p{.24in}m{6in}}
\midrule
\rowcolor{gray!35}
\multicolumn{2}{l}{2012-May-09, Phase 1}\\
\T & Gband intensity increased by a factor of 2. Significant visible light contributions to X-Rays in Ti\_poly and C\_poly and minor contributions to Al\_mesh.\\
\B & \url{http://solar.physics.montana.edu/takeda/xrt_straylight/xrt_sl_summary.html}\\
\rowcolor{gray!35}
\multicolumn{2}{l}{2015-June-14, Phase 2}\\
\T & Significant visible light contributions to X-Rays in Ti\_poly and C\_poly and minor contributions to Al\_mesh and Al\_poly.\\
\B & \url{http://solar.physics.montana.edu/takeda/xrt_sl2015/xrt15_sl2.html}\\
\rowcolor{gray!35}
\multicolumn{2}{l}{2017-May-27, Phase 3} \\
\T & Ti\_poly and C\_poly images used for calibration and engineering purposes. Correctible contributions to Al\_mesh and Al\_poly.\\
\B & \url{http://solar.physics.montana.edu/takeda/xrt_sl2017/xrt17_sl3.html}\\
\rowcolor{gray!35}
\multicolumn{2}{l}{2018-May-29, Phase 4} \\
\T& Minor increase in overall intensity. Correctible contributions to Al\_mesh and Al\_poly.\\
\B & \url{http://solar.physics.montana.edu/takeda/xrt_sl2018/xrt18_sl4.html}\\
\end{tabular}
\end{table}

%%%%% OLD TEXT
%
%On May 9th of 2012, XRT began observing an increase in visible light emission using the Gband optics by about a factor of 2. The leading idea for this increase is a pinhole in the telescope's entrance filter, which allows for some transmission when the visible light shutter is closed. This has led to significant visible light contributions to X-Ray images taken using the Ti\_poly and C\_poly filters and a minor contribution to the Al\_mesh filter. 
%
%After the light leak was uncovered, XRT began taking Gband images with the visible light shutter closed. These can be used to quantify the visible light contribution so that it can be subtracted from the X-Ray images. This code is currently under development, and until it is available, users should avoid using Ti\_poly and C\_poly data taken after 2012/05/09 for quantitative analyses. 

\begin{figure}[H]
\hypertarget{Fig2_16}{}
\includegraphics[width=\textwidth]{ti_poly_light_leak.png}
\caption{Comparison of Ti\_poly images before and after light leak.}
\label{figure2_16}
\end{figure}


\subsection{Light Leak Correction}
In March of 2022, software was added to the SSW pipeline to perform light leak corrections. The light leak correction is done by simply subtracting the light leak image (visible stray light component included in each X-ray filter pair) obtained during the Hinode satellite's eclipse season. This is performed with the following set of scripts available in SSWIDL:\\

\noindent
\textbf{xrt\_synleaksub.pro}: main program \\
\textbf{check\_sl\_phase.pro}: called from the main program \\
\textbf{get\_slcorfact\_raw.pro}: potentially called from the main program \\
\textbf{leak\_fits}: directory containing processed leak images \\

\noindent
The basic usage is as follows where out\_idx and out\_da will be the light leak corrected index and data array respectively:\\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}

IDL> file='./comp_XRT20200220_061539.6.fits'  ; sample XRT file (Al_mesh)
IDL> read_xrt, file, in_idx, in_da
IDL> xrt_synleaksub, in_idx, in_da, out_idx, out_da

\end{verbatim}
\end{minipage} \\

The light leak pattern and intensity differ with each filter and satellite pointing. Leak pattern and intensity of the same filter and pointing are roughly constant during each stray light phase, but vary by ~10 percent depending on the growth of the contamination layer on the CCD (that repeats gradual increase and jump down after CCD bakeouts. The image for the light leak correction should therefore be selected for the same filter, satellite pointing, stray light phase, and ideally be adjusted for the level of CCD contamination at the time of observation. However, as a practical matter, preparing the leak image for every possible pointing is hard to achieve, while we have good amount of light leak measurements at the disk center pointing. The full-disk composite images are therefore corrected most reliably for the light leak.

Intensity variation of the leak image due to the growth of CCD contamination layer is well determined for Ti\_poly during stray light phase 1 by using the intensity correlation between Ti\_poly and Al\_mesh images (cg. Takeda et al. 2016, SolPhys. 291, p.317). The resulting k-factor is obtained with the function GET\_SLCORFACT\_RAW.PRO, and the leak image subtraction has been already performed only for the Ti\_poly SCIA images at the phase 1 (as of March 2022).

%On June 14 of 2015, XRT experienced another increase in visible light emission. The cause is a change in the amount of visible light that is being transmitted to the detector, most likely due to a pinhole in one of the prefilters at the entrance aperture. Because of the differing characteristics of our various focal-plane filters, the increased visible light only affects a few of the passbands. In particular, the Ti-poly and C-poly images are strongly affected, as are the G-band (visible light) images. There is a measurable effect in Al\_mesh and Al-poly, but it's very small and is correctable.

%
%
%
% The effects of the light leak on contamination
%
%
%
%\section{The Effects of the Light Leak on Contamination}
%The light leaks have caused changes in the accumulation rate of contaminant after each light leak phase. At each of these epochs the XRT team is building a model to correct for the effects the light leaks are having on the contaminant accumulation. 

%
%
%
% DISPLAYING XRT DATA
%
%
%
\hypertarget{dispxrt}{}
\section{Displaying XRT Data} \label{displayingxrt}

XRT has a large dynamic range. To display the data using IDL, it is often useful to logarithmically scale the data. If viewing 
a 2048$\times$2048 image, which does not fit on most computer screens, it may be useful to rebin the image. The procedure below does pretty well with both raw and prepped images though you may have to change the gamma value of your display using \textbf{stretch.pro}. For example, display an image from the example started in \hyperlink{searchxrt}{Section~\ref{ssxrt}}. It is a $2048 \times 2048$ Ti\_poly image that was prepped and normalized. See \hyperlink{Fig2_10}{Figure~\ref{figure2_10}}.\\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> image=sigrange(data_out[*,*,0], frac=.9999, range=range)
IDL> if range[0] gt 0 then imin=alog10(range[0]) $
    else imin=alog10(0.1)
IDL> imax = alog10(range[1])
IDL> image=alog10(image > 10.0^imin)
IDL> image = image < imax
IDL> loadct, 3
IDL> stretch, 0, 255, 1.1
IDL> wdef, 0, 512
IDL> tvscl, rebin(image, 512, 512)
\end{verbatim}
\end{minipage} \\
\vspace{12pt}


\begin{minipage}{0.95\textwidth}
\noindent Alternatively, one could use \textbf{plot\_image.pro}: 
\vspace{-6pt}
\begin{verbatim}
IDL> plot_image, image
IDL> xdoc,`plot_image.pro'; for more information on plot_image.
\end{verbatim}
\end{minipage}

\begin{figure}[H]
\hypertarget{Fig2_10}{}
\centering
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{XRT20070418_111232_6.png}
\caption*{Logarithmic scale and \textbf{stretch.pro}} \end{subfigure} \quad
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{XRT_plot_image.png}
\caption*{Using \textbf{plot\_image.pro}}
\end{subfigure}
\caption{Examples displaying XRT data in IDL.}
\label{figure2_10}
\end{figure}
%
%
%
% COALIGNING XRT DATA
%
%
%
\section{Coaligning XRT Data}

The coalignment routine, \textbf{xrt\_read\_coaldb.pro}, is incorporated into \textbf{xrt\_prep.pro}. Users can determine what type of co-alignment calibration was performed by reading the image history keyword in the output image header after running \textbf{xrt\_prep}. 

\subsection{Using \textbf{xrt\_read\_coaldb.pro}}

The \textbf{xrt\_read\_coaldb.pro} routine updates XRT level-0 FITS header keywords to achieve better alignment. The alignment database is kept in the \$SSWDB tree and is updated weekly. Users will have to update the \$SSWDB/hinode/xrt/xrt\_msu\_coalign/ directory routinely to achieve the best alignment results. This routine does not alter XRT data and only updates the following index tags, or FITS keywords, typically used in coaligning images.
\begin{itemize} \itemsep1pt \parskip0pt \parsep0pt
  \item[] \tt{XCEN}
  \item[] \tt{YCEN}
   \item[] \tt{CRVAL1}
   \item[] \tt{CRVAL2}
   \item[] \tt{CRPIX1}
   \item[] \tt{CRPIX2}
   \item[] \tt{CDELT1}
  \item[] \tt{ CDELT2}
   \item[] \tt{CROTA1}
   \item[] \tt{CROTA2}
   \item[] \tt{HISTORY}
   \end{itemize}
This procedure assumes there has been no spatial modification to the data array (e.g., no shift, no rotation, and  no enlarge/shrink). If the data has been modified in one of these manners, you may need additional processing. If a user does not have access to the SSWDB database, they can download the database directly from the XRT Coalignment Database website: \\
   \url{http://ylstone.physics.montana.edu/yosimura/hinode/coalignment/}. \\
   Instructions for use are included at the webpage and it is also updated weekly. A paper detailing the generation of the alignment database is currently being prepared by Yoshimura and McKenzie.

The alignment routine has been included in the latest version of \textbf{xrt\_prep} (v2014-Oct-20) by using the {\tt /COALIGN} keyword. (See \hyperlink{xrtprep}{Section~\ref{prepxrt}}.) \\

%%%%%% Keiji's e-mail contents about database. 
%After careful calibration works, XRT team has started providing corrected
%parameters for coalignment through the SolarSoft.
%By using the IDL procedure \textbf{xrt\_read\_coaldb.pro}, you can correct the
%information in the level-0 XRT FITS headers, and get better coalignment
%results. Please note that the SSWDB is required for the correction,
%because the calibrated parameters are in the database under the SSWDB
%(\$SSWDB/hinode/xrt/xrt\_msu\_coalign/).  The database is updated weekly basis.
%
%The routine \textbf{xrt\_read\_coaldb.pro} does not change anything on images,
%but corrects some index tags (or FITS keywords) listed below.
%They are the information using in coalignment processes.
% XCEN
% YCEN
% CRVAL1
% CRVAL2
% CRPIX1
% CRPIX2
% CDELT1
% CDELT2
% CROTA1
% CROTA2
% HISTORY (add a new line)
%
%Since the routine \textbf{xrt\_read\_coaldb} has been implemented in {xrt\_prep},
%you don't need to use the routine directly/independently. That is to say the
%\tt{index\_out} from {xrt\_prep} should have corrected information.
%But, if you do want to correct \tt{index} from \textbf{read\_xrt} for some reason
%without \textbf{xrt\_prep}, you can get a corrected index \tt{cor\_index} by:

\noindent Basic Call: \\

{\tt IDL$>$  new\_index=xrt\_read\_coaldb(index)} \\

\noindent Inputs:
\begin{description}
\item {\tt INDEX}: (structure array) The XRT index structure. 
\end{description}

\noindent Outputs:
\begin{description}
\item {\tt  NEW\_INDEX}: (structure array) The updated XRT structure.
\end{description}

\noindent Optional Inputs:
\begin{description}
\item {\tt /AIA\_CC}: (Boolean) Set = 1 to utilize the calibration results from cross correlation between XRT thin-filter images and AIA 335 \AA\ images. It is expected that you can get better results with this option, especially in the coalignment with data from SDO. This option is not the default, since sometimes you get ``wrong'' results with it due to some failures in the cross correlation process.
\item {\tt BASE\_DIR}: (string) The directory where XRT coalignment databases (coaldb\_u, coaldb\_c) should be found. [Default: \$SSWDB/hinode/xrt/xrt\_msu\_coalign/].
\end{description}

\noindent Optional Outputs:
\begin{description}
\item {\tt DB\_VER}: (String) Version of the coalignment database.
\item {\tt CALIBRATION\_TYPE}: (Integer) Set to return the resources used for the calibration. In general, smaller numbers mean better results. see below:
  \begin{description}
  \item[] -1: No correction. Check if you have access to SSWDB on your system.
  \item[] 1: Cross correlation results (AIA and XRT). From the results of cross correlation between the XRT data and AIA 335A
      image observed close in time. You can use this resource type with {\tt /AIA\_CC} keyword.
  \item[] 2: Limb fitting results (G-band). If a full disk G-band solar image is available, it can improve the alignment by applying a limb fitting method.
       The correction using this method is robust.
  \item[] 3: UFSS data. The sun sensor on-board Hinode (UFSS) provides rather continuous output
       about Hinode's pointing information. We can utilize the information
       to get the XRT pointing with the correction of the offsets between
       the UFSS and XRT. This resource can cover most of the XRT data
       throughout the mission with good accuracy.
  \item[] 4: Limb fitting results (X-Ray).  Limb fitting method is also applicable to X-Ray full disk images, though
       the accuracy of the results is not as good as those from G-band limb
       fitting.
  \item[] 6: Other methods 
  \end{description}
\end{description}

Once you get the corrected information for coalignment, you can quickly
check the results by using the routine \textbf{plot\_map}. Below
is an example that demonstrates the coalignment results. Starting with an {\tt INDEX} structure and {\tt XRT\_DATA} array we apply the correction and compare it with an AIA image. See \hyperlink{coaldb}{Figure ~\ref{Fig_coaldb}}.

\begin{verbatim}
IDL> cor_index=xrt_read_coaldb(index)
IDL> new_xrt_data=rot(xrt_data,-cor_index.crota1,/cub)
IDL> cor_index.crota1=0 & cor_index.crota2=0
       ; where "xrt_data" is a single array of XRT data, and
       ; "cor_index" is a corrected index
       ; rotate XRT data and modify the tag of roll angle
IDL> index2map,cor_index,xrt_data, xrt_map
IDL> index2map,aia_index,aia_data, aia_map
       ; Prepare MAP structure
IDL> window,xs=512,ys=512 & mov=bytarr(512,512,2)
       ; Open window and prepare an array for movie
IDL> plot_map,xrt_map,/log & mov(*,*,0)=tvrd()
       ; display XRT image (log scale) and read it to the movie array
IDL> xr=!x.crange & yr=!y.crange
       ; Store x-,y-range of the plot to use the next plot
IDL> plot_map,aia_map,/log,xr=xr,yr=yr & mov(*,*,1)=tvrd()
IDL> stepper,mov
       ; play movie
\end{verbatim}

The routine also works for the better coalignment of a time series of
XRT images. Below is an example of making a dijittered movie:

\begin{verbatim}
 IDL> xrt_prep,old_index,old_data, new_index, new_data
       ; Prep to get corrected index and data
       ; Assuming all data have same x-,y-size and same binning
 IDL> delt_x = (new_index.xcen-new_index(0).xcen)/new_index.cdelt1
 IDL> delt_y = (new_index.ycen-new_index(0).ycen)/new_index.cdelt2
 IDL> shift_val = transpose([[delt_x],[delt_y]])
       ; Calculate offset values for each data referring to the first
       ; image in the sequence (i.e. new_data(*,*,0)).
 IDL> res_data = shift_img(new_data,shift_val)
       ; Shift images to correct their "jittering"
 IDL> stepper,res_data
       ; Watch the results to check
\end{verbatim}

More examples can be found at the XRT coalignment webpage at MSU: \\
\url{http://ylstone.physics.montana.edu/yosimura/hinode/coalignment/samples/}
  
\begin{figure}[ht!]
\hypertarget{coaldb}{}
\centering
\includegraphics[width=\textwidth]{coal_sample.png}
\caption{Sample coalignment between XRT and AIA images using \textbf{plot\_map}. XRT images are on the
left and AIA on the right. \emph{Upper Left}: XRT Map using level-0
FITS header information without correction. \emph{Lower Left}: Same data after the correction
done by xrt\_read\_coaldb.pro. The image location has changed relative to the $x$ and $y$ axes. The red contour in the right panel show the position of the flaring loop in XRT images.}
\label{Fig_coaldb}
\end{figure}

\subsection{Using \textbf{xrt\_jitter.pro}}
The routine {\bf xrt\_jitter.pro} applies a satellite jitter and 
orbital drift correction to a time series of XRT images by 
using the sun-sensor signals and information from coalignment
measurements taken regularly since February 2007. See \citet{Shimizu07} for details.

\noindent Basic call to align images of a time series to a reference image (the default being the first image): \\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> xrt_jitter, index, off
 \end{verbatim}
 \end{minipage} \\
 
\noindent The output {\tt OFF} is a float array, [2,$N_{ing}$] containing the shift values, in arc seconds, applied to the images in the E-W and N-S direction. For removing jitter and orbital variation, perform: \\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> data_ca = shift_img(data_x, off)
\end{verbatim}
\end{minipage} \\

\noindent Optional keywords: 
\begin{description}
\item {\tt REF}: Select the reference image frame [default = 0, using first image as reference].
\item {\tt XRT\_PIX}: Provides the offset values in units of XRT pixels instead of arc seconds.
\end{description}


%
%
%	
% MAKING COMPOSITE IMAGES WITH XRT DATA	
%
%
%
\section{Making Composite Images with XRT Data}
There are two routines available for making compositie images. The routine \\ \textbf{mk\_xrt\_composite.pro} combines a single long and 
short exposure pair of images to increase the dynamic range and to replace saturation with unsaturated data. \\

\noindent Basic call: \\

{\tt IDL$>$ mk\_xrt\_composite, l\_idx, l\_da, s\_idx, s\_da, c\_idx, c\_da} \\

\noindent Inputs: 
\begin{description}
\item {\tt L\_IDX}: (structure scalar) Long exposure index. 
\item{\tt L\_DA}: (2D number array) Long exposure data. 
\item {\tt S\_IDX}: (structure scalar) Short exposure index. 
\item {\tt S\_DA}: (2D number array) Short exposure data. 
\end{description}

\noindent Outputs: 
\begin{description}
\item {\tt C\_IDX}: (structure scalar) Composite index.
\item {\tt C\_DA}: (2D number array) Composite data.
\end{description}

\noindent Optional Keywords: 
\begin{description}
\item {\tt DESPIKE}: (Boolean or integer) Set if 1 pass of despiking is wanted, or set to 
1-3 for 1-3 passes of despike. [default, no despiking]
\item {\tt LSAT\_MAP}:  (Byte array) Set to a Boolean map of the location of saturated pixels 
to be replaced. Use this if the data have already been \textbf{xrt\_prepped} and the map 
was generated or if \textbf{xrt\_prep} is not to be used. Array must be same size as images 
to be composited. 1 represents the pixel is to be replaced.
\item {\tt /VERBOSE} (Boolean) If set, prints out extra messages.
\end{description}

\noindent The routine \textbf{xrt\_batch\_composite.pro} can be used to process 
multiple composite images and deposit them into an index structure array 
and data array consistent with \textbf{xrt\_prep.pro} outputs and the like. \\

\noindent Basic call: \\

{\tt IDL$>$ xrt\_batch\_composite,  l\_idx, l\_da, s\_idx, s\_da, index\_out, \$ 

data\_out} \\

\noindent Inputs are simply arrays of \textbf{mk\_xrt\_composite.pro} inputs with outputs of the same 
form. The keywords of \textbf{mk\_xrt\_composite.pro} are also supported. Note that {\tt LSAT\_MAP} 
must now be an array of Boolean maps. See header for additional information.

It has become customary to take three exposures and generate a composite image from them. The routine \textbf{mk\_xrt\_comp3.pro} will take a set of long, medium and short exposures and turn them into a composite image. \\

\noindent Basic call: \\

{\tt IDL$>$ mk\_xrt\_comp3, l\_idx, l\_da, m\_idx, m\_da, s\_idx, s\_da, c\_idx, c\_da} \\

\noindent Inputs:
\begin{description}
\item {\tt L\_IDX}: (structure scalar) Index for the long exposure.
\item {\tt L\_DA}: (2D number array, [$N_x,N_y$]) This is the 2D data array for the long exposure image. Can be either Level 0 or Level 1 data as long as it corresponds to {\tt L\_IDX}.
\item {\tt M\_IDX}: (structure scalar) Index for the medium exposure.
\item {\tt M\_DA}: (2D number array, [$N_x,N_y$]) This is the 2D data array for the medium exposure image. Can be either Level 0 or Level 1 data as long as it corresponds to {\tt L\_IDX}.
\item {\tt S\_IDX}: (structure scalar) Index for the short exposure.
\item {\tt S\_DA}: (2D number array, [$N_x,N_y$]) This is the 2D data array for the short exposure image. Can be either Level 0 or Level 1 data as long as it corresponds to {\tt L\_IDX}.
\end{description}

\noindent Optional Keywords:
\begin{description}
\item {\tt DESPIKE}: (Boolean or integer) Set if 1 pass of despike is wanted to remove radion-belt/cosmic-ray spikes, or set to 1-3 passes of despike [default is no despike].
\item {\tt LSAT\_MAP}: (byte array) Set to a Boolean map of the location of saturated pixels of the long exposure image. Use this if the data have already been prepped and the map was generated or if \textbf{xrt\_prep} is not to be used. Array must be the same size as images to be composited.
\item {\tt MSAT\_MAP}: (byte array) Set to a Boolean map of the saturated pixels of the medium exposure image.
\item {\tt /VERBOSE}: (Boolean) If set, print out extra messages.
\end{description}

\noindent Outputs:
\begin{description}
\item {\tt C\_IDX}: (structural scalar) This is the index of the composite image. It will have the same content as {\tt L\_IDL}.
\item {\tt C\_DA}: (2D number array,  [$N_x,N_y$]) This is the data array for the composite image.
\end{description}
%
%
%
% MAKING MOVIES WITH XRT DATA
%
%
%
\section{Making Movies with XRT Data}
Movies of XRT data can be made using a combination of IDL and 
software capable of stringing together a series of images, such 
as QuickTime Pro. 

First, display the data on the screen (see \hyperlink{dispxrt}{Section~\ref{displayingxrt}}). XRT movies are made by capturing images displayed on the 
monitor using the IDL function {\bf tvrd}, which works in similar 
fashion to a screen-shot function. For this reason, image quality 
is dependent on the resolution of your computer monitor. To avoid 
this problem, port images into the IDL Z-buffer and read them from there: \\

{\tt IDL $>$ set\_plot, `Z'} 

{\tt IDL $>$ device, set\_r = [512,512]} \\

\noindent After determining the size of the data array, a movie can be made using a simple for loop:\\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> help, data_out
    DATA_OUT            INT       = Array[512, 512, 64]
IDL> for i=0, 63 do begin &
IDL> tv, bytscl(alog(data_out[*,*,i])) &
IDL> xyouts, 0.03, 0.03, index[i].date_obs, /normal, size=2.0 &
IDL> opf = `Hinode_XRT'+trim(i,'(i3.3)')+`.png' &
IDL> print, `Saving image as: ', opf & 
IDL> write_png, opf, tvrd(), red, green, blue &
IDL> endfor
\end{verbatim}
\end{minipage}
\vspace{6pt}

\noindent Generate a movie using software capable of stringing together a sequence of images. 
%
%
%
% WRITING XRT DATA
%
%
%
\section{Writing XRT Data}
	\subsection{Using \textbf{write\_xrt.pro}}
This program will write Level 1 FITS files for the input data 
(unless the {\tt PATHS\_ONLY} switch is used). There will be one 
image per file. By default, the files will be written into the 
current working directory, but file-paths can be modified with keywords.\\

\noindent Examples: \\
\noindent Basic call, to write to a user-specified directory:

{\tt IDL$>$ write\_xrt,index\_out,data\_out,outdir=`/home/user/'} \\

\noindent Write Level 1 data-cube into the site XRT archive:

{\tt IDL$>$ write\_xrt, index\_out, data\_out, /archive}\\

\noindent Get the output filenames without writing the files:

{\tt IDL$>$ write\_xrt, index\_out, data\_out, /paths\_only, out\_paths}\\
 
\noindent Optional input keyword parameters: 
\begin{description}
\item {\tt /ARCHIVE}: (Boolean) If the {\tt /ARCHIVE} switch is used, 
then the standard archive path and standard filename format will be 
followed. This overrides {\tt OUTDIR} and {\tt OUTFILE}. If 
{\tt /ARCHIVE} is not used, then {\tt OUTDIR} and {\tt OUTFILE} are 
used if they are given. If {\tt OUTDIR} is not given, then the 
current working directory is used. If {\tt OUTFILE} is not given, 
then standard format filenames are used. The {\tt OUTDIR} and 
{\tt OUTFILE} keywords operate independently. If they are both 
given, then {\tt OUTDIR+OUTFILE} will be used.
\item {\tt OUTDIR}: (string scalar) Specifies the fully qualified 
output directory. Default = the current working directory. 
{\tt OUTDIR} overrides {\tt ONLINE}. 
\item {\tt OUTFILE}: (string array, [${\it N_{img}}$]) Specifies 
the output filenames. Default = follow the XRT filename standard 
for Level 1 FITS files: L1\_XRTyyymmdd\_hhmmss.s.fits
\item {\tt /PATHS\_ONLY}: (Boolean) If set, just return 
{\tt OUT\_PATHS} but don't write any files. 
\item {\tt /MAKE\_DIR}: (Boolean) If set, create implied directories 
if they do not exist. 
\item {\tt /VERBOSE}: (Boolean) If set, print out extra information. 
Overrides {\tt /QUIET}
\item {\tt /QUIET}: (Boolean) If set, suppress messages.
\item {\tt /QSTOP}: (Boolean) For debugging.
\end{description}
\noindent Optional output keyword parameters:
\begin{description}
\item{\tt OUT\_PATHS}: (string array, [${\it N_{img}}$]) List of 
implied/derived full file-paths for the output.
\item{\tt QABORT}: (Boolean) Indicates that the program exited 
gracefully without completing.
 \begin{description}
 \item 0: Program ran to completion. 
 \item 1: Program aborted before completion.
 \end{description}
\end{description}
%
%
%
% USING WRITE_PNG.PRO OR WRITE_BMP.PRO
%
%
%
\subsection{Using \textbf{write\_png.pro} or {\bf write\_bmp.pro}:}
Furthermore, IDL routines will write out lossless image files 
(such as BITMAP) and lossy images files (such as PNG):\\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> loadct, 3
IDL> tv, bytscl(alog(data_out[*,*,0])}
IDL> write_png, tvrd(), red, green, blue}, or
IDL> write_bmp, tvrd(), red, green, blue
\end{verbatim}
\end{minipage}

%
%
%
% INSTRUMENT RESPONSES AND INFERRING PHYSICAL QUANTITIES
%
%
%
\hypertarget{intresp}{}
\section{Instrument Responses and Inferring Physical \\ \mbox{Quantities}} \label{intresp1}

Proper analysis of XRT data requires understanding the physical units of the
relevant values and functions.

\begin{description}
\item[\textbullet] {\tt $\mathrm{d}_c$}: data value in an image pixel for a filter channel c. Units are \mbox{[DN $\mathrm{pix}^{-1}$]} (non-normalized) or \mbox{[DN $\mathrm{pix}^{-1} \mathrm{s}^{-1}$]} (exposure normalized).

XRT data values, such as are given in XRT data files and as returned by \textbf{xrt\_prep.pro}, are in units of [DN], for ``Data Numbers". This is a measurement of the total photon energy accumulated in the respective pixel across all photon wavelengths over the duration of the image exposure. (Note that, alternately, data values might be in units of \mbox{[DN $\mathrm{s}^{-1}$]} if the data has been normalized for the exposure duration, such as can be done with \textbf{xrt\_prep.pro}. If normalization was applied with \textbf{xrt\_prep.pro}, then there will be a sentence in the image {\tt INDEX.HISTORY} tag that starts ``XRT\_RENORMALIZE Normalized from...".) This measured energy corresponds to emission from a field-of-view determined by the pixel size and binning level.

\item[\textbullet] {\tt p}: pixel field-of-view size. Units are usually [arcsec]. 

The size of the field-of-view of an image pixel is given by the image keywords
{\tt CDELT1} or {\tt CDELT2} (length) and {\tt CUNIT1} or {\tt CUNIT2} (units), see~\hyperlink{appendix}{Appendix~\ref{append}} for a complete list. A full-resolution XRT
pixel (i.e., no binning) has the size 1.02860 arc-seconds x 1.02860 arc-seconds.
The binning (aka on-chip summing) level of the image is given by the image
{\tt CHIP\_SUM} tag, but the {\tt CDELT} and {\tt CUNIT} tags should be consistent
with that for any binning level.

\item[\textbullet] {\tt g\_port}: the camera gain; conversion factor from DN to N\_photoelectrons. Units
are \mbox{[\mbox{electron} $\mathrm{DN}^{-1}$].}

A data value in units of [DN] can be converted to the number of photoelectrons
read from the CCD for the corresponding pixel. (This is NOT the same as $\mathrm{N}_{\mathrm{e}}$ at
the Sun!) The conversion factor is given by the gain setting of the camera's
analog-to-digital converter and depends upon which CCD readout port was enabled.
Use the function \textbf{get\_xrt\_gain.pro} to get the gains for an array of images.
That routine has header documentation that explains its usage, and automatically
takes care of accounting for the correct readout port for each image.

\item[\textbullet] {\tt q}: photoexcitation conversion rate; conversion from N\_photoelectrons to
electron-volts. The value and units are 3.65 \mbox{[eV $\mathrm{electron}^{-1}$]}.

By using the conversion factors {\tt g\_port} and {\tt q}, one can convert data values from
units of [DN] to total integrated photon energy [eV].

XRT is a broadband instrument--- \hyperlink{Fig2_18}{Figure~\ref{Figure2_18}} illustrates that the effective areas of
the filter-channels (i.e., the instrumental spectral responses) are sensitive to
a wide range of photon wavelengths. As a consequence, large errors may be
introduced if one tries to directly convert data values from units of [eV] to
\mbox{[photon number]} by assuming any single particular value of photon wavelength.
The emitted solar spectrum simply has too many different atomic lines all
throughout this broad spectral range of the instrument. Furthermore, since XRT's
broadband response implies that individual lines are not distinguished, and
hence, spectroscopic analysis cannot be readily performed, electron densities,
Doppler velocities, and turbulence parameters cannot be directly inferred. So
what \emph{can} be done?  We discuss using XRT data to infer electron
temperatures and emission measures of the observed solar plasma. Finally, in a
roundabout way and doing careful analysis, it is possible to infer photon
numbers from the integrated photon energy per pixel that was discussed above.

\item[\textbullet] {\tt $R_c(\lambda)$}: instrument effective area (i.e., the spectral response) per
photon of wavelength $\lambda$ for a filter-channel $c$. Units are \mbox{[DN $\mathrm{cm}^2$ sr
$\mathrm{ph}^{-1}\ \mathrm{pix}^{-1}$]} or, optionally, \mbox{[electron $\mathrm{cm}^2$ sr $\mathrm{ph}^{-1}\ \mathrm{pix}^{-1}$]}.

The spectral response function $R_c(\lambda)$ indicates the detector signal (in
DN or, optionally, in number of CCD photoelectrons) produced by a photon of
given energy. It contains all of the information about the channel response as a
function of wavelength. \hyperlink{xrtresp}{Section~\ref{xrtfilter}} discusses how to obtain XRT's spectral
response functions (aka ``wavelength responses", as distinguished from the
``temperature responses"). \hyperlink{Fig2_11}{Figure~\ref{Figure2_11}} overlays the spectral response functions for
XRT's channels, both with and without the contamination layer for one epoch.

\item[\textbullet] {\tt $\mathrm{S}(\lambda, T)$}: solar spectrum emission model. Units are \mbox{[ph $\mathrm{cm}^3 \mathrm{s}^{-1} \mathrm{sr}^{-1} \AA^{-1}$]}.

\item[\textbullet] \textbf{\tt $\mathrm{F}_c(T)$}: instrument temperature response function, per emission measure, for a filter-channel $c$. Units are [DN $\mathrm{cm}^5 \mathrm{s}^{-1} \mathrm{pix}^{-1}$] or, optionally, \mbox{[electron $\mathrm{cm}^5 \mathrm{s}^{-1} \mathrm{pix}^{-1}$]}. Note that column emission measure has units of \mbox{[$\mathrm{cm}^{-5}$]}, so the units of the temperature response functions are, equivalently, \mbox{[DN $\mathrm{s}^{-1} \mathrm{pix}^{-1} \mathrm{EM}^{-1}$]}.

However, the user will usually only need to obtain the spectral responses in
order to then calculate the instrument temperature responses $\mathrm{F}_c(T)$. (That
process is also described in \hyperlink{xrtresp}{Section~\ref{xrtfilter}}) The temperature response function
indicates the detector signal that will be produced by unit emission measure of
plasma for a given temperature. 

The spectral responses (effective areas) are purely functions of the instrument.
But the temperature responses also depend upon some model of the solar emission
spectra corresponding to different plasma temperatures.  A spectral emission
model $\mathrm{S}(\lambda, T)$, such as one would get from ATOMDB/APEC or CHIANTI, is a
set of plasma emission spectra for a set of temperatures. It is determined by
information from all the assumptions (e.g., elemental abundances, ionization
equilibrium state, et cetera) that go into modeling the x-ray radiation from a
coronal plasma. The units are those of a photon intensity per column emission
measure per area of plasma emitting into a steradian of solid angle. The XRT
software will use an APEC solar model by default, but \hyperlink{xrtresp}{Section~\ref{xrtfilter}} describes how the
user can instead apply a solar model that they have independently obtained.

The temperature responses are related to the spectral responses and a solar
emission model in this way:

$$\mathrm{F}_c(T) = \int \mathrm{d}\lambda * \mathrm{S}(\lambda, T) * \mathrm{R}_c(\lambda).$$

Under common conditions and reasonable assumptions, it is possible to infer electron temperatures and emission measures for the observed plasma. 

Under the assumption that the emitting plasma along the line of sight is of a
uniform (or effectively uniform) temperature and emission measure, the technique
of filter-ratios may be applied (\hyperlink{teem}{Section~\ref{teem1}}) to infer the uniform temperature
$\mathrm{T}_0$ and corresponding emission measure $\mathrm{EM}|_{T_0}$ from measurements in two XRT
channels. The observation $\mathrm{d}_c$ in each channel satisfies this relation:

$$\mathrm{d}_c = \mathrm{F}_c(T_0) * \mathrm{EM}|_{T_0}.$$

Under the assumption that the emitting plasma along the line of sight is
composed of cells of thermalized plasma at various temperatures, each with
uniform (or effectively uniform) emission measure, DEMs over some temperature
range may be inferred. 

\item[\textbullet] {\tt DEM($T$)}: column differential emission measure as a function of temperature
$T$. Units are \mbox{[$\mathrm{cm}^{-5} \mathrm{K}^{-1}]$}.

See~\hyperlink{dem_iter}{Section~\ref{dem_iter1}}. for information about an XRT routine to calculate DEMs. DEMs are
related to the temperature responses $F_c(T)$ and data values $\mathrm{d}_c$ in this way:

$$\mathrm{d}_c = \int \mathrm{d}T * \mathrm{F}_c(T) * \mathrm{DEM}(T).$$

Do note, however, that an explanation of DEM analysis is well beyond the scope
of this Guide--- the software is provided for knowledgeable users who understand
the assumptions and pitfalls of that sort of analysis.

\item[\textbullet] {\tt $\epsilon_c(\lambda)$}: measured photon power as a function of photon wavelength.
Units are \mbox{[DN $\mathrm{s}^{-1} \mathrm{pix}^{-1}$]}. (The factors {\tt g\_port} and {\tt q}, described above, can
be used to directly convert this to \mbox{[eV $\mathrm{s}^{-1} \mathrm{pix}^{-1}$]}.)

\item[\textbullet] {\tt $\eta_c(\lambda)$}: measured photon number rate as a function of photon
wavelength. Units are \mbox{[ph $\mathrm{s}^{-1} \mathrm{pix}^{-1}$]}.

\item[\textbullet] {\tt $N_{ph}$}: total photon number rate corresponding to the XRT data value.
\end{description}

\begin{figure}[H]
\hypertarget{Fig2_18}{}
\centering
\includegraphics[width=\textwidth]{eff_area.pdf}
\caption{The total telescope throughput of the XRT for each of the nine X-Ray filter channels. \emph{Figure 17 from \cite{Golub07}}.}
\label{Figure2_18}
\end{figure}

We now return to the subject of inferring photon numbers from data values, which
represent an integrated photon energy (units of [DN] or [eV]). An observation in
a pixel is the total of all captured photon energies integrated over the solar
spectrum. However, one cannot specify the solar spectrum until one has a solar
emission model ($\mathrm{S}(\lambda, T)$, which is a signal per emission measure as a
function of wavelength) and a solution for (a) an emission measure EM at one
temperature $T_0$ or (b) a DEM($T$) over a range of temperatures. The relation
for the solar spectrum captured in the channel $c$ as a function of wavelength, $\epsilon_c(\lambda)$, is

\begin{enumerate}
\item[\textbf{(a)}] $\epsilon_c(\lambda) = \mathrm{d}\lambda * \mathrm{R}_c(\lambda) * \mathrm{S}(\lambda, T_0) * \mathrm{EM}|_{T_0}$, or
\item[\textbf{(b)}] $\epsilon_c(\lambda) = \mathrm{d}\lambda * \mathrm{R}_c(\lambda) \int \mathrm{d}T * \mathrm{S}(\lambda, T) * \mathrm{DEM}(T)$,
respectively.
\end{enumerate}
In either case, the net data value of the observation $\mathrm{d}_c$ may now be written as $\mathrm{d}_c = \sum_{\lambda}\epsilon_c(\lambda)$.


Once $\epsilon_c(\lambda)$ is expressed in units of \mbox{[eV $\mathrm{s}^{-1} \mathrm{pix}^{-1}$]} (applying the
conversion factors of {\tt g\_port} and {\tt q} as needed), the photon number as a function of photon wavelength is $\eta_c(\lambda) = \left( \frac{\lambda}{hc} \right) * \epsilon_c(\lambda)$, and the total captured photon number $\mathrm{N}_{\mathrm{ph}}$ in channel c is $\mathrm{N}_{\mathrm{ph}} = \sum_\lambda \eta_c.$

Note that, in order to calculate a solar spectrum and then photon number, one
relies on some solution for the emission measure or differential emission
measure, each of which may only be solved from XRT data alone only by making
several simplifying assumptions and avoiding the pitfalls of such analysis.
Furthermore, this brief overview has not even touched upon the delicacies of
proper error propagation. In short, deriving photon numbers from XRT data is not
simple nor straightforward--- the instrument has a \emph{very} broadband response
and was not designed specifically for inferring photon number. We recommend that
users avoid it unless they already have ample expertise in the subject.

%
%
%
% XRT FILTER RESPONSES
%
%
%
\hypertarget{xrtresp}{}
\subsection{Filter Responses} \label{xrtfilter}
This section describes the wavelength and temperature response
of the XRT filters and how to obtain temperatures using the filter ratio method. For a full discussion see ~\citet{2011SoPh..269..169N} and \citet{Narukage14}.

The routines providing the wavelength and temperature XRT responses are \hspace*{50pt} \linebreak \textbf{make\_xrt\_wave\_resp.pro} and \textbf{make\_xrt\_temp\_resp.pro} respectively. The output of \hspace*{15pt} \linebreak \textbf{make\_xrt\_wave\_resp.pro} containing the instrument response is used as input to \hspace*{20pt} \linebreak \textbf{make\_xrt\_temp\_resp.pro} to calculate the temperature responses. The routine \textbf{xrt\_teem.pro} will output the temperature and volume emission measure using the filter ratio method. 

We note that the updated software should also be used for the analysis of older data (i.e., data taken before the new calibrations were released), as the response functions at all times are better modeled, in particular taking into account the effects of contamination\footnote{Following the initial calibration, available at the beginning of the mission, the XRT team has released two significantly updated versions of the XRT calibration taking into account the effects of contamination, described in \hyperlink{xrtcont}{Section~\ref{contamination}}. The version released in September 2008 included an updated calibration able to adequately model the effects of the contamination on the CCD, while the most recent calibration, also takes into account the effect of the contamination layers on the focal plane filters.}.  

The routine \textbf{make\_xrt\_wave\_resp.pro} (v2012-March-16) produces the effective areas and spectral responses for a set of XRT X-Ray channels, 
taking into account the thickness of the CCD contamination layer. \\

\begin{minipage}{0.95\textwidth}
\noindent Basic call: 
\vspace{-6pt}
\begin{verbatim}
IDL> wave_resp = make_xrt_wave_resp(index=index, $
    contam_thick=contam_thick, contam_time=contam_time)
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

\noindent Optional input keyword parameters: 
\begin{description}
\item {\tt INDEX, CONTAM\_THICK, CONTAM\_TIME}: One, and only one,
	of these three input must be specified.
	{\tt INDEX} must be a standard XRT data ``index" array, 
	such as the one produced by \textbf{xrt\_prep.pro}. 
	{\tt CONTAM\_THICK} (scalar) input keyword may be used 
	to specify a single contamination layer thickness 
	(in Angstroms). 
	{\tt CONTAM\_TIME} input keyword must be in a time format
	that is recognizable by the SSWIDL program 
	\textbf{anytim2utc.pro}. This input keyword may be used to 
	specify a single ``mission time", which will be used 
	to specify a unique contamination thickness. 
\item {\tt CHN\_FILENAME}: (Input) A filename of the form 
	``xrt\_channels\_vNNNN.geny", where \\* NNNN is a 4-digit 
	version number. These files are the XRT channel 
	configuration files distributed by the XRT Team.  
	The default (i.e., if {\tt CHN\_FILENAME} is not used)
	is to get the latest, most correct file. The input may be a full or relative pathname. If it is a relative path name, the program will first look in \$SSW\_XRT/idl/response/channels/ and then look in the current working directory.
\item {\tt OUTFILE}: Writes the constructed wave response structure
	to the specified file (using \textbf{savegenx.pro});
\item {\tt /EL\_UNITS}: Sets the units of the spectral response (in the 
	{\tt SPEC\_RESP} array output) to \mbox{[el cm$^2$ sr ph$^{-1}$ pix$^{-1}$]}.
	Otherwise, the default is to produce the the response in units 
	of [DN cm$^2$ sr ph$^{-1}$ pix$^{-1}$].
\end{description}
 
The output structure contains data and information about the effective areas and spectral response functions for a set of XRT X-Ray channels. This output structure is the input to
{\bf make\_xrt\_temp\_resp.pro} that describes the instrument response. \\

\noindent Outputs:

\begin{description}
\item {\tt WAVE\_RESP}: This structure contains data and information about the effective areas and spectral response functions for a set of XRT X-Ray channels. This is the input that describes the instrument response.
\end{description}

\noindent Here is a listing and short description, of the fields of the {\tt xrt\_wave\_resp} structure: \\

\noindent  {\tt WAVE\_RESP \textbraceleft XRT\_wave\_resp\_vNNNN\textbraceright }:
\begin{description}
\item[-] {\tt TYPE}: [Default value = XRT\_wave\_resp.] This is the 
	generic name of the structure that contains the 
	wavelength response functions and information. 
	The version of the structure definition might evolve,
	but the TYPE should remain constant. This field should 
	NOT be changed.
\item[-]  {\tt WRS\_STR\_VERSION}: [Default value = XRT\_wave\_resp\_vNNNN,
	where NNNN is a 4-digit number.] This is the version 
	number of the xrt\_wave\_resp structure definition. 
	In addition to being recorded in this field, this is
	also the ``unique structure name" in the IDL sense. 
	This field should NOT be changed.
\item[-]  {\tt WRS\_STR\_DESCR}: This is a sentence or two that describes
	the purpose of this structure type. This field should NOT be changed.
\item[-]  {\tt NAME}: This is a name for these wavelength responses 
	for this channel and contamination thickness. 
	On creation, it inherits the name of the {\tt EFF\_AREA} 
	structure that was used to create it. This string 
	concisely identifies these dependent wavelength
	responses (although it may not be unique).
	This field MAY be changed, but the default is recommended.
\item[-]  {\tt CONFG}:  (structure scalar, \{XRT\_chn\_config\_ref\_vNNNN\}):
	This structure contains information about the instrument 
	components and the history of their role in the processing 
	that has been performed on this channel to produce
	this temperature response function. 
	Large arrays (such as the channel transmission function) 
	have been abridged, but there should be sufficient
	information in this structure to recover or reproduce 
	the corresponding full channel structure (of type 
	XRT\_chn\_config).
	The base set of channels is provided in the XRT 
	SSWIDL tree by a file with a pathname like this:\\
  	{\tt \$SSW\_XRT/idl/response/channels/xrt\_channels\_vNNNN.geny}.
	A listing of the \\ top-level fields of the 
	XRT\_chn\_config structure, and further details, can be 
	found in the routine header.
\item[-]  {\tt CONTAM}: (structure scalar, \{XRT\_contam\_ref\_vNNNN\}):
	This structure contains information about the particular 
	thickness of the CCD contamination layer (which affects 
	the response of the channel) and the history of its 
	processing.  Large arrays (such as the contaminations 
	transmission function) have been abridged, but there
	should be sufficient information in this structure to 
	recover or reproduce the corresponding full contamination 
	structure (of type XRT\_contam). More information 
	about the content of this XRT\_contam\_ref type of 
	structure may be found in the program header of 
	\textbf{make\_xrt\_ea.pro}.
	A listing of the fields of the XRT\_contam\_ref 
	structure, and further details, can be 
	found in the routine header.
\item[-]  {\tt EFFAR}:  (structure scalar, \{XRT\_eff\_area\_vNNNN\}):
	This structure contains information about the 
	channel's effective area and about the history of its
	processing. More information about the content of this
	XRT\_eff\_area type of structure may be found in 
	the program header of \textbf{make\_xrt\_ea.pro}.	
	A listing of the fields of the XRT\_eff\_area structure, 
	and further details, can be found in the routine header.
\item[-]  {\tt SPRSP}:  (structure scalar, \{XRT\_spec\_resp\_vNNNN\}):
	This structure contains information about the channel's 
	spectral response and about the history of its processing. 
	More information about the content of this XRT\_spec\_resp 
	type of structure may be found in the program header 
	of \textbf{make\_xrt\_sr.pro}.	
	A listing of the fields of the XRT\_spec\_resp structure, 
	and further details, can be found in the routine header.
\item[-]  {\tt HISTORY}: (string array, [3]):
	This text array is for XRT programs to record any 
	instance in which they have modified the content 
	of the XRT\_temp\_resp structure for this particular 
	channel. On creation, a line is added for the 
	creation of the XRT\_temp\_resp structure in 
	\textbf{make\_xrt\_temp\_resp.pro}.  An entry string 
	is composed of (a) a program name, (b) the program's 
	version/date, (c) colon separator, (d) Timestamp 
	(in parentheses) of when the program completed the 
	described action, and (e) a summation of what the 
	program created or modified in the XRT\_temp\_resp 
	structure. Values are inserted starting at the lowest 
	address of this array. Remaining unused addresses
	are filled with the empty string. Filled strings 
	should NOT be overwritten. Users should use the 
	{\tt COMMENTS} field to add their own notations to this 
	structure.
\item[-]  {\tt COMMENTS}: (string array, [5])  A tag for adding 
	notations regarding the temperature response described 
	for this XRT channel. Users and programs are
	encouraged to put content in the lower addresses, 
	and assign empty strings \{''\} to the higher, unused 
	addresses.
\end{description}

Once the instrument response as a function of wavelength is calculated
the routine \\* \textbf{make\_xrt\_temp\_resp.pro} can be used to derive the 
temperature responses of the XRT filters. \\

\begin{minipage}{0.95\textwidth}
\noindent Basic call:
\vspace{-6pt}
\begin{verbatim}
IDL> result = make_xrt_temp_resp(wave_resp, {[emiss\_model] OR
    [/apec_default] OR [/chianti_default]})
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

\noindent Input keyword parameters: 
\begin{description}
\item {\tt WAVE\_RESP}: Mandatory input structure containing the data
	and information about effective areas and spectral
	response functions for a set of XRT X-Ray channels.
	This structure array is the output of 
	{\bf make\_wave\_temp\_resp.pro}
\item {\tt EMISS\_MODEL, APEC\_DEFAULT, CHIANTI\_DEFAULT}: 
	One, and only one, of these three input must be specified.
	{\tt EMISS\_MODEL} (structure scalar, \\ \{XRT\_emiss\_model\_vNNNN\} 
	[Nchannels]) This structure contains data and information about
	a plasma emission model, as a function of wavelength and 
	temperature. This is the input that associates spectra with 
	temperatures, which allows one to ``convert" an instrument's 
	spectral response to a temperature response. For a complete description, see the program header for \textbf{make\_xrt\_emiss\_model.pro}. 
\item	{\tt APEC\_DEFAULT} : This input keyword switch may be used to
	indicate that the XRT default emission model from APED/APEC 
	should be utilized. (Some of the details of this model are 
	returned in the TRESP.EMISS substructure of the function output.)
	The default model assumes coronal abundances ~\citet{1992PhyS...46..202F}.
\item	{\tt CHIANTI\_DEFAULT}: This input keyword switch may be used to
	indicate that the XRT default emission model from CHIANTI 
	should be utilized. (Some of the details of this model are 
	returned in the TRESP.EMISS substructure of the function output.)
	The default model assumes coronal abundances ~\citet{1992PhyS...46..202F}.
\item {\tt OUTFILE}: Writes the constructed temperature response structure
	to the specified file (using savegenx.pro);
\item {\tt /EL\_UNITS}: Sets the units of the temperature response (in the 
	{\tt TEMP\_RESP} array output) to [el cm$^5$ s$^{-1}$ pix$^{-1}$].
	Otherwise, the default is to produce the the response in units 
	of [DN cm$^5$ s$^{-1}$ pix$^{-1}$].
\end{description}

\noindent Output: 
\begin{description}
\item {\tt RESULT}: Structure containing the data and information about the
	temperature response for each XRT X-Ray channel described by 
	the WAVE\_RESP input. A ``channel" is primarily specified by a 
	particular setting of the X-Ray analysis filters and a CCD
	contamination thickness.
	
	A full listing of the fields of the \textbf{XRT\_temp\_resp.pro} structure,
	with a detailed description, can be found in the routine header.
	Here below we include a brief description of only a subset of 
	the fields, and more information can be found in the header of \\
	\textbf{make\_xrt\_temp\_resp.pro}: 

	TRESP \{$<$Anonymous$>$\}
	\begin{description}
	\item {\tt TEMP}: (Float array, [$N_{temps}$s]) The abscissa of the 
		temperature response for this channel. The units are 
		provided in the TEMP\_RESP\_UNITS field. The actual 
		values may form a sequence of shorter length than 
		the length of the TEMP array. The LENGTH field 
		indicates the subarray of usable values, according 
		to TEMP[0:LENGTH-1]. Unused elements are set to 0.0.
	\item {\tt TEMP\_UNITS}: (string scalar) These are the units 
		of the TEMP values, and MUST be equal to `K' 
		(degrees Kelvin).
	\item {\tt TEMP\_RESP}: (Float array, [$N_{temps}$]) The temperature 
		response function for this channel, this value indicates
		the level of CCD signal that is produced in one CCD pixel, 
		in one second, by 1 cm$^{-5}$ (column) emission measure 
		of plasma at the corresponding temperature. The actual 
		values may form a sequence of shorter length than the 
		length of the TEMP\_RESP array. The LENGTH field 
		indicates the subarray of usable values, according to 
		TEMP\_RESP[0:LENGTH-1].  Unused elements are set to 0.0.
	\item {\tt TEMP\_RESP\_UNITS}: (string scalar)  Units of 
		the TEMP\_RESP values.  The default units are 
		\mbox{[DN cm$^5$ s$^{-1}$ pix$^{-1}$]}	because XRT data are 
		typically presented in DN. However, the /EL\_UNITS 
		keyword may be used to get TEMP\_RESP in units of 
		\mbox{[electron cm$^{5}$ s$^{-1}$ pix$^{-1}$]}.
	\item {\tt LENGTH}: (long scalar) 0 $<$ LENGTH $\le$ n\_elements(TEMP)
		Indicates sublength of the TEMP and TEMP\_RESP arrays 
		that contains valid values, starting at the zero-th 
		index. Only the range [0:LENGTH-1] of TEMP and TEMP\_RESP 
		will be utilized. Values outside this range may be 
		zeroed. This value is set equal to the corresponding 
		value in the EMISS\_MODEL input. This field should 
		NOT be changed.
	\item {\tt CONFG}: (structure scalar, \{XRT\_chn\_config\_ref\_vNNNN\})
		This structure contains information about the instrument 
		components and the history of their role in the processing 
		that has been performed on this channel to produce this 
		temperature response function. All of its values are 
		inherited from the corresponding ``CONFG" substructure 
		in WAVE\_RESP (see description above). Large arrays 
		(such as the channel transmission function) have been 
		abridged, but there should be sufficient information 
		in this structure to recover or reproduce the corresponding 
		full channel structure (of type ``XRT\_chn\_config").
	\item {\tt CONTAM}: (structure scalar, \{XRT\_contam\_ref\_vNNNN\})
		This structure contains information about the particular 
		thickness of the CCD contamination layer (which affects 
		the response of the channel) and the history of its role 
		in the processing that has been performed on this channel 
		to produce this temperature response function. All of its 
		values are inherited from the corresponding ``CONTAM" 
		substructure in WAVE\_RESP (see description above). 
		Large arrays (such as the contamination's transmission 
		function) have been abridged.
	\item {\tt EFFAR}: (structure scalar, \{XRT\_eff\_area\_ref\_vNNNN\})
		This structure contains information about the channel's 
		effective area and about the history of its role in the 
		processing that has been performed on this channel to 
		produce this temperature response function. Some of its 
		values are inherited from the corresponding ``EFFAR" 
		substructure in WAVE\_RESP (see description above). 
		Large arrays (such as the effective area function) 
		have been abridged.
	\item {\tt SPRSP}: (structure scalar, \{XRT\_spec\_resp\_ref\_vNNNN\})
		This structure contains information about the channel's 
		spectral response and about the history of its role in 
		the processing that has been performed on this channel to
		produce this temperature response function. Some of its 
		values are inherited from the corresponding ``SPRSP" 
		substructure in WAVE\_RESP (see description above). 
		Large arrays (such as the spectral response function) 
		have been abridged. 
	\item {\tt EMISS}:  (structure scalar, \{$<$Anonymous$>$\})
		This structure contains information about the plasma 
		emission model (input EMISS\_MODEL) and about the history 
		of its role in the processing that has been performed 
		to produce this temperature response function. Some of 
		its values are inherited from the EMISS\_MODEL input. 
		For a complete description, see the header 
		for \textbf{make\_xrt\_emiss\_model.pro}. 
		Large arrays (such as the model's spectra) have been 
		abridged, but there should be sufficient information in 
		this structure to recover or reproduce the corresponding
		full spectral response structure (of type ``XRT\_emiss\_model").
	\item {\tt HISTORY}: (string array, [3])
		This text array is for XRT programs to record any instance 
		in which they have modified the content of the 
		``XRT\_temp\_resp" structure for this particular channel.
	\item {\tt COMMENTS}: (string array, [5]) A tag for adding 
		notations regarding the temperature response described 
		for this XRT channel. Users and programs are encouraged 
		to put content in the lower addresses, and assign empty 
		strings \{''\} to the higher, unused addresses.
	\end{description}
\end{description}

\begin{minipage}{0.95\textwidth}
\noindent Example:
\vspace{-6pt}
\begin{verbatim}
IDL> wave_resp_mar07 = 
    make_xrt_wave_resp(contam_time=`2007-Mar-01 09:00:00')
IDL> temp_resp_mar07 = 
    make_xrt_temp_resp(wave_resp_mar07,/apec_default)
IDL> print,(temp_resp_mar07.history)(0)
    MAKE_XRT_TEMP_RESP v2008-Nov-21: (22-Jan-2010 19:44:11.07 UTC)
    Generated XRT_TEMP_RESP structure with name
    ``Al-mesh; XRT default emission model (APED/APEC 2007-May-17)"
IDL> help,(temp_resp_mar07.TEMP),(temp_resp_mar07.TEMP_RESP)
    <Expression>    FLOAT     = Array[50, 15]
    <Expression>    FLOAT     = Array[50, 15]
IDL> wave_resp_mar08 = 
    make_xrt_wave_resp(contam_time=`2008-Mar-01 09:00:00')
IDL> temp_resp_mar08 = 
    make_xrt_temp_resp(wave_resp_mar08,/apec_default)}
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

The XRT temperature responses produced by the above commands are shown in \hyperlink{Fig2_11}{Figure~\ref{Figure2_11}}.  \\

\begin{figure}[ht!]
\hypertarget{Fig2_11}{}
\centering
\includegraphics[width=\textwidth]{tresp_example.pdf}
\caption{Example of XRT temperature responses calculated for two different dates. The solid lines are responses calculated for 2007-03-01, before the first CCD bakeout, and the dashed curves are calculated for 2008-03-01, in the regime of regular bakeouts. The comparison shows how the sensitivity in the lower energy range, significantly decreased by the contamination material, has been recovered through CCD bakeout and maintained with regular CCD bakeouts.}
\label{Figure2_11}
\end{figure}
\newpage
%
%
%
% CALCULATING XRT FILTER RESPONSE WITH NON-STANDARD SPECTRA
%
%
%
\hypertarget{nonstd}{}
\subsection{Calculating XRT Filter Response with Non-Standard Spectra} \label{nonstd1}
You can calculate the XRT filter response using non-standard spectra by using the routine \textbf{make\_xrt\_emiss\_model.pro}; it puts a spectral emission model into a structure format that other XRT routines will expect. \\

%\subsection{Obtaining Physical Units}


\begin{minipage}{0.95\textwidth}
\noindent Basic call:
\vspace{-6pt}
\begin{verbatim}
IDL> emiss_model = make_xrt_emiss_model(model name, wave, temp, $
    spectrum, abund_model, ioneq_model, dens_model, $
    data_files = data_files)
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

\noindent Inputs: 
\begin{description}
\item {\tt MODELNAME}: (string scalar) This will be the name/ID given to this spectral model. 
\item {\tt WAVE}: (Float array, [$\mathrm{N}_{\lambda}$]) This is a 1D array of monotonically increasing wavelengths. Units are in angstroms. Must correlate to one dimension of the {\tt SPEC} array. See {\tt WLENGTH}.
\item {\tt TEMP}: (Float array, [$\mathrm{N}_{temperature}$]) This is a 1D array of monotonically increasing temperatures. Units are Kelvin. Must correlate to one dimension of the {\tt SPEC} array. See {\tt TLENGTH}.
\item {\tt SPEC}: (Float array, [$\mathrm{N}_{\lambda},\mathrm{N}_{temperature}$]) This is a 2D array of a spectral emission model. Units are $\mathrm{ph}\, \mathrm{cm}^3\,\mathrm{s}^{-1} \mathrm{sr}^{-1} \mathrm{\AA}^{-1}.$ This variable is dependent on {\tt WAVE} AND {\tt TEMP}. See {\tt WLENGTH} and {\tt TLENGTH}.
\item {\tt ABUND\_MODEL}: (string scalar) This is a brief description or reference for the abundance model that was used to calculate the spectra. 
\item {\tt IONEQ\_MODEL}: (string scalar) This is a brief description or reference for the ionization equilibrium model that was used to calculate the spectra.
\item {\tt DENS\_MODEL}: (string scalar) This is a brief description or reference for the density or emission measure model that was used to calcite the spectra.
\end{description}
\noindent Optional Inputs: 
\begin{description}
\item {\tt WLENGTH}: (long scalar, 0 $<$ {\tt WLENGTH} $\le$ n\_elements({\tt WAVE})) Indicates sub-length of {\tt WAVE} array that contains valid values, starting at the zeroth index. Only the range [0:{\tt WLENGTH} - 1] of {\tt WAVE} and of the corresponding dimension of {\tt SPEC} will be utilized. Values outside this range may be zeros. Default behavior is to set this value equal to the length of the {\tt WAVE} input array.
\item {\tt TLENGTH}: (long scalar, 0 $<$ {\tt TLENGTH} $\le$ n\_elements({\tt TEMP})) Indicates sub-length of {\tt TEMP} array that contains valid values, starting at the zeroth index. Only the range [0:{\tt TLENGTH }- 1] of {\tt TEMP} and of the corresponding dimension of {\tt SPEC} will be utilized. Values outside this range may be zeroed. Default behavior is to set this value equal to the length of the {\tt TEMP} input array.
\item {\tt DATA\_FILES}: (string scalar or array, [$\mathrm{N} \le 5$]) These are the source files for the emission model. It is up to the user whether they wish to provide them.
\item {\tt COMMENTS}:  (string scalar or array, [$\mathrm{N} \le 5$]) There is a field in the generated structure to store any relevant comments.
\item {\tt OUTFILE}: (string scalar) Write the constructed spectral emission model structure to the specified file using \textbf{savegenx.pro}. The extension ``.geny" will be automatically appended to the filename. See ``Return" output for structure description. 
\item {\tt /VERBOSE}: (Boolean) Print out extra information. Overrides {\tt /QUIET}.
\item {\tt /QUIET}: (Boolean) Suppress messages.
\item {\tt /QSTOP}: (Boolean) For debugging.
\end{description}

\begin{minipage}{0.95\textwidth}
\noindent Outputs a constructed spectral emission model structure. For example, \\
\vspace{-6pt}
\begin{verbatim}
TYPE    STRING    `XRT_emiss_model'
EMS_STR_VERSION:    STRING    (anonymous)
EMS_STR_DESCR:    STRING    `Solar spectral emission model
        in XRT-compatible format.'
NAME:    STRING    `XRT default (APED/APEC)'
WAVE:    FLOAT    Array[5000]
WAVE_UNITS:    STRING    `Angstroms'
TEMP:    FLOAT    Array[50]
TEMP_UNITS:    STRING    `K'
SPEC:    FLOAT    Array[5000,50]
SPEC_UNITS:    STRING    `ph cm^3 s^-1 sr^-1 A^-1'
WLENGTH:    LONG    5000
TLENGTH:    LONG    50
ABUND_MODEL:    STRING    `Photospheric abundances'
IONEQ_MODEL:    STRING    `Mazotta et al. (1998)'
DENS_MODEL:    STRING    `1e10 g cm^-3'
DATA_FILES:    STRING    Array[5]
HISTORY:    STRING    Array[3]
COMMENTS:    STRING    Array[5]
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

\noindent Here is an example using the default emission model for AIA. To learn more about the AIA routines see the SDO Data Analysis Guide at \url{https://www.lmsal.com/sdodocs/doc/dcur/SDOD0060.zip/zip/entry/index.html}. \\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> aia =aia_get_response(/emiss,/full)
IDL> help, aia, /str
** Structure <9000008>, 8 tags, length=501700960, 
    data length=496215788, refs=1:
   DATE            STRING    `20130107_193807'
   GENERAL         STRUCT    -> MS_129742904002 Array[1]
   LINES           STRUCT    -> MS_129742904003 Array[548515]
   CONT            STRUCT    -> MS_129742904004 Array[1]
   FIXES           STRING    Array[3]
   TOTAL           STRUCT    -> MS_129742904005 Array[1]
   NOTES           STRING    Array[1]
   VERSION         INT              4
\end{verbatim}
\end{minipage} \\

\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> modelname=`AIA default spectrum'
IDL> wave=aia.total.wave
IDL> temp=10.^(aia.total.logte)
IDL> spectrum = aia.total.emissivity
IDL> abund_model= aia.general.abundfile
IDL> ioneq_model = aia.general.ioneq_name
IDL> dens_model = aia.general.model_name + `,p='+ $
    trim(aia.general.model_pe,1)
IDL> emiss_model = make_xrt_emiss_model(modelname, wave, temp, $
    spectrum, abund_model, ioneq_model, dens_model, $
    data_files=data_files)
IDL> help, emiss_model, /str
** Structure <4806e08>, 18 tags, length=3673200, 
    data length=3673188, refs=1:
   TYPE            STRING    `XRT_EMISS_MODEL'
   EMS_STR_VERSION STRING    `<Anonymous>'
EMS_STR_DESCR STRING `Specifies a spectral emission model in X'...
   NAME            STRING    `AIA default spectrum'
   WAVE            FLOAT     Array[9001]
   WAVE_UNITS      STRING    `Angstroms'
   TEMP            FLOAT     Array[101]
   TEMP_UNITS      STRING    `K'
   SPEC            FLOAT     Array[9001, 101]
   SPEC_UNITS      STRING    `ph cm^3 s^-1 sr^-1 A^-1'
   WLENGTH         LONG              9001
   TLENGTH         LONG               101
ABUND_MODEL STRING `~/ssw/packages/chianti/dbase/abundance/s'...
IONEQ_MODEL STRING `~/ssw/packages/chianti/dbase/ioneq/chian'...
   DENS_MODEL      STRING    `Constant pressure,p=1E+15'
   DATA_FILES      STRING    Array[5]
   HISTORY         STRING    Array[3]
   COMMENTS        STRING    Array[5]
\end{verbatim}
\end{minipage} \\
\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> obs_date = `2011-08-21'
IDL> wresp_all = make_xrt_wave_resp(contam_time = obs_date)
IDL> help, wresp_all
WRESP_ALL       STRUCT    = -> XRT_WAVE_RESP_V0002 Array[15]
IDL> tresp_all = make_xrt_temp_resp(wresp_all, emiss_model)
\end{verbatim}
\end{minipage} \\
\begin{minipage}{0.95\textwidth}
\begin{verbatim}
IDL> help, tresp_all, /str
** Structure <4001c08>, 20 tags, length=5536, 
   data length=5468, refs=1:
   TYPE            STRING    `XRT_TEMP_RESP'
   TRS_STR_VERSION STRING    `<anonymous>'
TRS_STR_DESCR STRING `Provides temperature response function f'...
   NAME            STRING    `Al-mesh; AIA default spectrum'
   TEMP            FLOAT     Array[101]
   TEMP_UNITS      STRING    `K'
   TEMP_RESP       FLOAT     Array[101]
   TEMP_RESP_UNITS STRING    `DN cm^5 s^-1 pix^-1'
   LENGTH          LONG               101
   GAIN_USED       FLOAT          -1.00000
   WAVE_MIN        FLOAT           1.00000
   WAVE_MAX        FLOAT           400.000
   CONFG           STRUCT    -> XRT_CHN_CONFIG_REF_V0001 Array[1]
   CONTAM          STRUCT    -> XRT_CONTAM_REF_V0001 Array[1]
   FCONTAM         STRUCT    -> XRT_FILT_CONTAM_REF_V0001 Array[1]
   EFFAR           STRUCT    -> XRT_EFF_AREA_REF_V0001 Array[1]
   SPRSP           STRUCT    -> XRT_SPEC_RESP_REF_V0001 Array[1]
   EMISS           STRUCT    -> XRT_EMISS_MODEL_REF_V0001 Array[1]
   HISTORY         STRING    Array[3]
   COMMENTS        STRING    Array[5]
\end{verbatim}
\end{minipage} \\
\vspace{12pt}

The variable {\tt TRESP\_ALL} is a structure that contains the XRT response functions calculated with the default AIA spectrum. A comparison of XRT filter responses calculated with the default AIA spectrum and with the standard XRT spectrum are given in \hyperlink{Fig2_14}{Figure~\ref{Figure2_14}}.  

\begin{figure}[ht!]
\hypertarget{Fig2_14}{}
\centering
\includegraphics[width=\textwidth]{xrt_aia.png}
\caption{Example of XRT temperature responses calculated using the default spectrum for AIA and a standard XRT spectrum: the solid lines are the responses calculated for the standard XRT spectrum, and the dashed curves are calculated using the default spectrum for AIA. Both are calculated for the date 2011 August 21.}
\label{Figure2_14}
\end{figure}
%
%
%
% USING XRT_TEEM.PRO & XRT_TEEM_CH.pro
%
%
%
\hypertarget{teem}{}
\subsection{Using \textbf{xrt\_teem.pro} or \textbf{xrt\_teem\_ch.pro}} \label{teem1}

XRT has two routine to generate XRT coronal temperature images and differential emission measure images using filter ratios. They are called {\bf xrt\_teem.pro} and {\bf xrt\_teem\_ch.pro} (Chianti). The routines use the same methodology but the latter {\bf xrt\_teem\_ch.pro} has spectra created using several versions of Chianti. \\

\noindent Basic call: 

{\tt IDL $>$ xrt\_teem, index1, data1, index2, data2, te, em, et, ee} \\

\noindent Input Parameters: 
\begin{description}
\item {\tt INDEX1}: (Structure array) XRT index.
\item {\tt DATA1}: (2 or 3-dim float array, [x,y,n\_images]) XRT \textbf{non-normalized} level 1 data.
\item {\tt INDEX2}: (Structure array) XRT index.
\item {\tt DATA2}: (2 or 3-dim float array, [x,y,n\_images]) XRT \textbf{non-normalized} level 1 data. 
\end{description}

\noindent Optional Input keyword parameters: 
\begin{description}
\item {\tt CAL}: [default {\tt CAL} =2]
 \begin{description}If set, 
 \item 1= the coronal temperature is estimated based on the calibration in ~\citet{2011SoPh..269..169N} 
 \item 2 = the coronal temperature is estimated based on the calibration in ~\citet{Narukage14}. 
\end{description}
\item {\tt BIN}: (long) If set, data is binned using this value in spatial dimension. 
\item {\tt TE\_ERR\_THRESHOLD}: (Float) You can adjust the threshold ratio of the temperature error. (default is 0.1, i.e. 10\%.)
\item {\tt PHOTON\_NOISE\_THRESHOLD}: (Float) You can adjust the threshold ratio of photon noise to signal. (default is 0.1, i.e. 10\%)
\item {\tt /NO\_THRESHOLD}: (Boolean) If set, no threshold is set.
\item {\tt /INFO:} (Boolean) If set, information is shown.
\item {\tt LAMBDA\_SPECTRUM}: (Float array) wavelength for SPECTRUM in units of \AA.
\item {\tt TE\_SPECTRUM}: (Float array) temperature for SPECTRUM in units of [log K].
\item {\tt SPECTRUM}: (2-dim float array, [lambda,te]) photon number spectrum from solar plasma in units of [$\mathrm{cm}^3 \, \mathrm{s}^{-1} \, \mathrm{sr}^{-1}$].
We recommend that: 
\begin{itemize}
\item[-] The data point of the wavelength is from 1 to 400 [\AA] with 0.1 [\AA].
\item[-] The data point of temperature is from $10^{5.0}$ to $10^{8.0}$ [K] with $10^{0.05}$ [K] resolution. 
\end{itemize}
\item {\tt /APAC\_SPECTRUM:} (Boolean) If set, solar spectrum calculated with APAC database. (default is the solar spectrum calculated with CHIANTI database.)
\item {\tt EFF\_AREA:} (structure) You can use the output from \textbf{make\_xrt\_wave\_resp.pro}
\end{description}
\noindent Outputs:
\begin{description}
\item {\tt TE}: (2-dim float array, [$x,y$]) Derived temperature in log scale. [log K].
\item {\tt EM}: (2-dim float array, [$x,y$]) Derived volume emission measure in log scale [$\log \mathrm{cm}^{-3}$].
\item {\tt ET}: (2-dim float array, [$x,y$]) Error in temperature in log scale. [$\log \mathrm{K}$].
\item {\tt EE}: (2-dim float array, [$x,y$]) Error in the derived volume emission measure in log scale [$\log \mathrm{cm}^{-3}$].
\end{description}
For the following example, the filter ratio will be taken on Al\_mesh and Ti\_poly full disk images taken on 2007 Mar 01 at 06UT. The order of the images does not matter as long as the index,data combination is the same for each filter. The two images are \\ XRT20070301\_060214.6.fits and XRT20070301\_060310.1.fits. To display the images, an appropriate color table should be generated. \hyperlink{Fig2_12}{Figure~\ref{figure2_12}} is an example of the output of \textbf{xrt\_teem.pro} with different threshold values. \hyperlink{Fig2_13}{Figure~\ref{figure2_13}} is the corresponding volume emission measures. \\
\vspace{1in}

\begin{minipage}{0.95\textwidth}
\noindent Example:
\vspace{-6pt}
\begin{verbatim}
IDL> help, in, da
    IN           STRUCT    = -> <Anonymous> Array[2]
    DA            INT       = Array[2048, 2048, 2]
IDL> xrt_teem,in[0],da[*,*,0],in[1],da[*,*,1],te,em,et,ee,$
    /no_thresh
IDL> help,te
    TE              DOUBLE    = Array[2048, 2048]
IDL> help,em
    EM              DOUBLE    = Array[2048, 2048]
IDL> help,et
    ET              DOUBLE    = Array[2048, 2048]
IDL> help,ee
    EE              DOUBLE    = Array[2048, 2048]
IDL> te = 10.^(te)
IDL> te = te / 1000000. ; Convert to Million Kelvin
\end{verbatim}
\end{minipage}

\newpage

\begin{figure}[ht!]
\hypertarget{Fig2_12}{}
\centering
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{al_mesh.png}
\caption*{Al\_Mesh, 23 Nov 2011 at 20:48:13UT}
\end{subfigure} \quad
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{al_poly.png}
\caption*{Al\_Poly, 23 Nov 2011 at 20:48:19UT}
\end{subfigure}

\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{thres50almesh_alpoly.png}
\caption*{{\tt photon\_noise\_threshold}=0.5, {\tt te\_err\_threshold}=0.5}
\end{subfigure} \quad
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{nothreshalmesh_alpoly.png}
\caption*{Temperature output with {\tt /no\_thresh} keyword set.}
\end{subfigure}

\begin{subfigure}[t]{\textwidth} \centering
\begin{tikzpicture}
%The width is defined so that the proper scaling can be found based on the image size, scaling and unit conversions. 
% Changing the width/size/pixel resolution of the image will change where the ticks are located. 
\node[anchor=south west, inner sep=0] at (0,0){\includegraphics[width=5in]{tempbar1to2_5.png}};
\draw[black,ultra thick](3.2,-.1)--(3.2,.1);
\node[anchor=center] at (3.2,-.5){1.0};
\draw[black,ultra thick](5.3,-.1)--(5.3,.1);
\node[anchor=center] at (5.3,-.5){1.5};
\draw[black,ultra thick](7.4,-.1)--(7.4,.1);
\node[anchor=center] at (7.4,-.5){2.0};
\draw[black,ultra thick](9.5,-.1)--(9.5,.1);
\node[anchor=center] at (9.5,-.5){2.5};
\end{tikzpicture}
\caption*{Temperature: Million K}
\end{subfigure}
\caption{Example temperature output from \textbf{xrt\_teem.pro} using Al\_mesh and Al\_poly filters. The units have been changed from $\log$ K to Million K.}
\label{figure2_12}
\end{figure}

\begin{figure}[ht!]
\hypertarget{Fig2_13}{}
\centering
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{al_mesh.png}
\caption*{Al\_Mesh, 23 Nov 2011 at 20:48:13UT}
\end{subfigure} \quad
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{al_poly.png}
\caption*{Al\_Poly, 23 Nov 2011 at 20:48:19UT}
\end{subfigure}

\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{emthresh50almesh_alpoly.png}
\caption*{{\tt photon\_noise\_threshold}=0.5, {\tt te\_err\_threshold}=0.5}
\end{subfigure} \quad
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{emnothreshalmesh_alpoly.png}
\caption*{Temperature output with {\tt /no\_thresh} keyword set.}
\end{subfigure}

\begin{subfigure}[t]{\textwidth} \centering
\begin{tikzpicture}
%The width is defined so that the proper scaling can be found based on the image size, scaling and unit conversions. 
% Changing the width/size/pixel resolution of the image will change where the ticks are located. The image is 512x40pix
% with a resolution of 72pix/in. The image is scaled down to 5in. The bar begins at pixel 128 and ends at pixel 383 in
% the image. tikzpicture uses units of centimeters.
\node[anchor=south west, inner sep=0] at (0,0){\includegraphics[width=5in]{embar41_5to44_5.png}};
\draw[black,ultra thick](3.2,-.1)--(3.2,.1);
\node[anchor=center] at (3.2,-.5){41.5};
\draw[black,ultra thick](5.3,-.1)--(5.3,.1);
\node[anchor=center] at (5.3,-.5){42.5};
\draw[black,ultra thick](7.4,-.1)--(7.4,.1);
\node[anchor=center] at (7.4,-.5){43.5};
\draw[black,ultra thick](9.5,-.1)--(9.5,.1);
\node[anchor=center] at (9.5,-.5){44.5};
\end{tikzpicture}
\caption*{Emission Measure: $\log \, \mathrm{EM} \, (\mathrm{cm}^{-3})$}
\end{subfigure}
\caption{Example emission measure output from \textbf{xrt\_teem.pro} using the Al\_mesh and Al\_poly filters.}
\label{figure2_13}
\end{figure}

\noindent Basic call: 

{\tt IDL $>$ xrt\_teem\_ch, index1, data1, index2, data2, te, em, et, ee} \\

\noindent Input Parameters: 
\begin{description}
\item {\tt INDEX1}: (structure array) XRT index.
\item {\tt DATA1}: (2 or 3-dim float array, [x,y,n\_images]) XRT \textbf{non-normalized} level 1 data.
\item {\tt INDEX2}: (structure array) XRT index.
\item {\tt DATA2}: (2 or 3-dim float array, [x,y,n\_images]) XRT \textbf{non-normalized} level 1 data. 
\end{description}

\noindent Optional Input keyword parameters: 
\begin{description}
\item {\tt SPECTRUM\_FILE}:  (scalar string) Specify the name of the solar spectrum files (with path).
\item {CH\_VERSION}:  (scalar string of length 4). Specify the desired version of solar spectrum files calculated with CHIANTI (Densities: $10^9 [\mathrm{cm}^{-3}$]). By default, the routine will use the latest version of Chianti that is available. These files are stored in  \\ \mbox{\$SSW\_IDL/XRT/idl/response/spectrum\_files/}. As of this writing, mid-2017 A.D., the versions of Chianti that are available for use by this routine are:
\begin{itemize}
\item[] 0601 = Version 6.0.1
\item[] 0700 = Version 7.0.0
\item[] 0710 = Version 7.1.0
\item[] 0713 = Version 7.1.3
\item[] 0800 = Version 8.0.0
\item[] list = List all available versions of Chianti. This will cause the routine to exit before calculating the temperature. 
\end{itemize}
The ionization equilibrium: chianti.ioneq. The abundance: sun\_coronal\_1992\_feldman\_ext.    
\item HYBRID [Optional input] (boolean) Switch to use hybrid spectrum.
\item PHOTOSPHERIC [Optional input] (boolean) Switch to use photospheric spectrum.   
\item {\tt BIN}: (long) If set, data is binned using this value in spatial dimension. 
\item {\tt TRANGE}:  Same as \textbf{xrt\_teem.pro}.
\item {\tt /NO\_THRESHOLD}: (Boolean) If set, no threshold is set.
\item {\tt TE\_ERR\_THRESHOLD}: (float) You can adjust the threshold ratio of the temperature error. (default is 0.1, i.e. 10\%.)
\item {\tt PHOTON\_NOISE\_THRESHOLD}: (float) You can adjust the threshold ratio of photon noise to signal. (default is 0.1, i.e. 10\%)
\item {\tt MASK1} [Optional input] Same as \textbf{xrt\_teem.pro}.
\item {\tt MASK2} [Optional input] Same as \textbf{xrt\_teem.pro}.
\item {\tt EFF\_AREA}  same as \textbf{xrt\_teem.pro}. You can input the output (effective area) from \\ \textbf{make\_xrt\_wave\_resp.pro}.

We recommend that: 
\begin{itemize}
\item[-] The data point of the wavelength is from 1 to 400 [\AA] with 0.1 [\AA].
\item[-] The data point of temperature is from $10^{5.0}$ to $10^{8.0}$ [K] with $10^{0.05}$ [K] resolution. 
\end{itemize}
\item {\tt /APAC\_SPECTRUM:} (Boolean) If set, solar spectrum calculated with APAC database. (default is the solar spectrum calculated with CHIANTI database.)
\item {\tt EFF\_AREA:} (structure) You can use the output from \textbf{make\_xrt\_wave\_resp.pro}
\end{description}
\noindent Outputs:
\begin{description}
\item {\tt TE}: (2-dim float array, [$x,y$]) Derived temperature in log scale. [log K].
\item {\tt EM}: (2-dim float array, [$x,y$]) Derived volume emission measure in log scale [$\log \mathrm{cm}^{-3}$].
\item {\tt ET}: (2-dim float array, [$x,y$]) Error in temperature in log scale. [$\log \mathrm{K}$].
\item {\tt EE}: (2-dim float array, [$x,y$]) Error in the derived volume emission measure in log scale [$\log \mathrm{cm}^{-3}$].
\end{description}

%
%
%
% XRT_DEM_ITERATIVE2
%
%
%
\hypertarget{dem_iter}{}
\subsection{Using \textbf{xrt\_dem\_iterative2.pro}} \label{dem_iter1}
DEM estimation is a tricky business. This solver represents one algorithmic approach, and the default XRT temperature responses must necessarily make some assumptions (e.g., about the atomic physics, etc.). The XAG cannot possibly be a primer on DEM estimation, and the end-user is expected to know something about the topic. However, an effort has been made to keep the interface as straightforward and useful as possible. Furthermore, the temperature response codes (\textbf{calc\_xrt\_temp\_resp.pro} and associated routines) are designed to be modular, allowing end-users to ``roll their own''. \\

This routine estimates a DEM($T$) curve, given some observations $\mathrm{d}_c$ in channels $c$, and given the temperature response functions in every channel $F_c(T)$. These functions satisfy the equation: $$ \mathrm{d}_c = \int  \mathrm{DEM}(T) * \mathrm{F}_c(T)  \mathrm{d}T.  $$ The inversion is ill-posed and technically fraught with perils. This routine employs a forward-fitting approach: A DEM is guessed and folded through the $F_c(T)$ to generate ``model" observations. This process is iterated to reduce the chi-square between the actual and model observations. The DEM function is interpreted from some spline points, which are directly manipulated by the chi-square fitting routine \textbf{MPFIT.pro}. There are $N_c - 1$ splines, representing the degrees of freedom for $N_c$ observations. Note that the number of temperature bins requested for the DEM solution are usually greater than $N_c$.

To estimate errors on the DEM solution, this routine provides for Monte-Carlo iteration. On each iteration, the observations are varied normally by their sigma error, and then solved for a DEM. 
According to Monte Carlo theory, the distribution of these DEM solutions indicates the range of uncertainty in the DEM($T$) that corresponds to the unvaried observations. This routine only works on one pixel $\times\ \mathrm{N}_{\mathrm{channels}}$ at a time. This routine replaces \textbf{xrt\_dem\_iterative.pro}. \\

Basic Call:

\begin{verbatim}
XRT_DEM_ITERATIVE2, obs_index, obs_val, tresp, logT_out, dem_out
            [,obs_err=obs_err] [,base_obs=base_obs] [,mod_obs=mod_obs]
            [,chisq=chisq]     [,min_T=min_T]
            [,max_T=max_T]     [,dT=dT]             [,maxiter=maxiter]
            [,MC_iter=MC_iter] [,solv_factor=solv_factor]  [,/verbose]
            [,/quiet]          [,/qstop]              [,qabort=qabort]
\end{verbatim}

Inputs: 
\begin{description}
\item{{\tt OBS\_INDEX}}: (Structure or string array, [$N_{img}$]). This parameter identifies the XRT X-Ray channel for the corresponding element of the OBS\_VAL array. OBS\_INDEX may take one of two forms:

\begin{description}
\item[a] The ``index'' or ``catalog'' structure for the image from which this pixel OBS\_VALUE came from. 
\item[b] A string with the name of the XRT X-Ray channel or channel temperature response that corresponds to this OBS\_VALUE. Here are the possible names for the default XRT channel names:
                       `Al-mesh',  `Al-poly', `C-poly', `Ti-poly', `Be-thin', 
                         `Be-med, `Al-med', `Al-thick', `Be-thick',
                        `Al-poly/Al-mesh', `Al-poly/Ti-poly', 
                        `Al-poly/Al-thick', `Al-poly/Be-thick'
\end{description}

\item{{\tt OBS\_VAL}}: (Float array, [$N_{img}$]) This is the set of XRT data values seen in the X-Ray channels identified by OBS\_INDEX, respectively. Units = $\mathrm{DN}\ \mathrm{s}^{-1}\ \mathrm{pix}^{-1}$, where ``pix" means a one-arcsecond, full-resolution XRT pixel. 
         
\item{{\tt TRESP}}: (``temp\_resp" structure array, $N_{channels}$)
 This structure contains data and information
                   about the temperature responses for a set of XRT
               X-Ray channels. A ``channel" is primarily specified
               by a particular setting of the X-Ray analysis
                  filters and a CCD contamination thickness. This
                  structure is obtained using \textbf{make\_xrt\_wave\_resp.pro}
             and then \textbf{make\_xrt\_temp\_resp.pro}. More information
                   can be found in the headers of those programs
                 and in the XRT Analysis Guide located in the
                    Solarsoft directory, \\ \$SSW\_XRT/docs/XAG.pdf and at: \\
        \url{http://xrt.cfa.harvard.edu/resources/documents/XAG/XAG.pdf}.
\end{description}

Outputs:
\begin{description}
\item{{\tt LOGT\_OUT}}: (Float array, [$N_{temp}$]) The temperatures corresponding to the DEM solution. Units = log K. Runs from MIN\_T to MAX\_T with bin-width = DT.
\item{{\tt DEM\_OUT}}: (Float array, [$N_{temp}$, 1+MC\_ITER]) A DEM solution is a 1D array of length = $N_{temp}$. If Monte Carlo runs were performed, then the the 2nd dimension spans these runs. DEM\_OUT[$*$,0] is the solution for the original OBS\_VAL. DEM\_OUT[$*$,1:MC\_ITER] correspond to the solutions for the MC runs. Units = $\mathrm{cm}^{-5}\ \mathrm{K}^{-1}$. See Note \#3 for more about units.
\end{description}

Optional Inputs: 
\begin{description}
\item{{\tt OBS\_ERR}}:  (Float array, [$N_{img}$]) This input may provide the Gaussian one-sigma errors for the values in OBS\_VAL. The solver requires errors in order to calculate the least-squares. If the user does not provide these, then the default will be used. Default = (OBS\_VALUE $\times$ 0.03). (Min = 2 DN.)
\item{{\tt MIN\_T}}: (Float scalar) Input the low end of the DEM temp. range. Units = 'log K'. Default = 5.5. See Note \#2.
\item{{\tt MAX\_T}}: (Float scalar) Input the high end of the DEM temp. range. Units = 'log K'. Default = 8.0. See Note \#2.
\item{{\tt DT}}: (Float scalar) Input the bin-width of the DEM temp. range.  Units = 'log K'. Default = 0.1. See Note \#2.
\item{{\tt MAXITER}}: (Float scalar) This program works by iterating a least-squares search. This keyword may be used to specify the maximum number of iterations for each DEM solution. Default = 2000.
\item{{\tt MC\_ITER}}: (Float scalar) Use this keyword to cause the program to perform Monte Carlo runs. The value of MC\_ITER indicates how many runs. For each MC run, each of the OBS\_VAL values are modified from their original value by a  random normal amount using the respective OBS\_ERR as  a Gaussian sigma. Then, the DEM is solved again using  the new set of OBS\_VAL. See the descriptions of the output variables for how the results are reported. No MC runs are performed if this keyword is not used.
\item{{\tt SOLV\_FACTOR}}: (Float scalar) The least-squares solver is not completely  insensitive to the order of magnitude of the numbers  it is manipulating. SOLV\_FACTOR is used to normalize the inputs to move the solver into a ``sweet spot". The default choice is arbitrary but seems to work well (default = 1e21). Of course, the outputs are un-normalized at the end. It is recommended that users use the default.
\item{{\tt /VERBOSE}}: (Boolean) If set, print out extra information. Overrides ``/quiet" (see Note \#1).
\item{{\tt /QUIET}}: (Boolean) If set, suppress messages (see Note \#1).
\item{{\tt /QSTOP}}: (Boolean) For debugging.
\end{description}

Optional Outputs:
\begin{description}
\item{{\tt BASE\_OBS}}: (Float array, [$N_{img}$, 1+MC\_ITER]) These are the observations that a DEM solution  corresponds to. BASE\_OBS[$*$,0] = OBS\_VAL. BASE\_OBS[$*$,1:MC\_ITER] correspond to the observations produced by adding random OBS\_ERR noise to OBS\_VAL for each MC run. You may think of these as the ``actual" set of observations that each MC run was trying to solve the DEM for.
\item{{\tt MOD\_OBS}}: (Float array, [$N_{img}$, 1+MC\_ITER]) These are the model observations which are produced by the corresponding DEM solution. BASE\_OBS is the  actual set, and MOD\_OBS is how close the DEM can get to matching it.
\item{{\tt CHISQ}}: (Float array, [1+MC\_ITER]) These are the chi-square values for the DEM solutions.  CHISQ[$i$] = $\mathrm{total}(\mathrm{BASE}\_\mathrm{OBS}[*,i])-\mathrm{MOD}\_\mathrm{OBS}[*,i]/\mathrm{OBS}\_\mathrm{ERR}[*])^2$
\item{{\tt QABORT}}: (Boolean) Indicates that the program exited gracefully without completing. \\ (Might be useful for calling programs.)  
    \begin{description}
      \item 0: Program ran to completion.
      \item 1: Program aborted before completion.
    \end{description}
\end{description}


Simplest possible usage:

\begin{verbatim}
IDL> help, obs_index, obs_val
    OBS_INDEX       STRING    = Array[13]
    OBS_VAL         DOUBLE    = Array[13]
IDL> xrt_dem_iterative, obs_index, obs_val, tresp, logT_out, dem_out     
IDL> help, logT_out, dem_out
    LOGT_OUT        FLOAT     = Array[26]
    DEM_OUT         DOUBLE    = Array[26]
IDL> plot, logT_out, dem_out, psym=10, xtit='log T [log K]', $
         ytit='DEM [cm^-5 K^-1]'
\end{verbatim}

Provide errors (obs\_err) and perform 100 Monte Carlo runs:
 
\begin{verbatim} 
IDL> help, obs_index, obs_val, obs_err
OBS_INDEX       STRING    = Array[13]
OBS_VAL         DOUBLE    = Array[13]
OBS_ERR         DOUBLE    = Array[13]
IDL>xrt_dem_iterative, obs_index, obs_val, tresp, logT_out, dem_out, $
IDL>obs_err=obs_err, base_obs=base_obs, mod_obs=mod_obs, $
IDL>chisq=chisq, MC_iter=100
IDL>help, logT_out, dem_out
    LOGT_OUT        FLOAT     = Array[26]
    DEM_OUT         DOUBLE    = Array[26]
IDL>help, base_obs, mod_obs, chisq
    BASE_OBS        DOUBLE    = Array[13, 101]
    MOD_OBS         DOUBLE    = Array[13, 101]
    CHISQ           FLOAT     = Array[101]
\end{verbatim}

Notes:
\begin{description}
\item[1] There are three levels of verbosity.
  \begin{description}
  \item verbose is highest priority. All errors and messages are displayed.
  \item quiet is lower priority. No errors or messages are displayed.
  \item neither is lowest priority. All errors and some messages are displayed.
  \end{description}
\item[2] The user may specify the temperature bins over which the
 DEM will be solved. However, this solution temperature range 
          must lie within all of the T-ranges of the temperature 
          responses, to permit interpolations. (The default XRT responses
          run logT = 5.5 to 8.0.) Also, the solver requires that the 
         T-range be regular in `log T' units. Therefore, the solution 
          range is controlled with these three keywords: $\mathrm{MIN}_T$, $\mathrm{MAX}_T$, 
          and DT. Although these temperatures are all presented in 
          `log T', the underlying integrals are performed over `T'.
\item[3] A discussion of units. It is easier to understand these units in the larger context.
          For a spectral model S of the solar radiance, such as is returned by
          \textbf{get\_xrt\_spec\_genx}:  $$S(\lambda, T) \sim [\mathrm{ph\ cm}^3 \mathrm{s}^{-1} \mathrm{sr}^{-1} \AA^{-1}].$$
          For a spectral instrumental response R, such as \textbf{calc\_xrt\_spec\_resp.pro} 
          returns:
          $$\mathrm{R}(\lambda) \sim [\mathrm{DN\ cm}^2 \mathrm{sr\ ph}^{-1} \mathrm{pix}^{-1}],$$ which says something about
          how many DataNumbers are generated in the camera for a photon of a given wavelength.
          Then:
          $$\mathrm{S}(\lambda, T) * \mathrm{R}(\lambda) \sim [\mathrm{DN\ \AA}^{-1} \mathrm{s}^{-1} \mathrm{pix}^{-1} (\mathrm{cm}^{-5})^{-1}] \sim [\mathrm{DN\ \AA}^{-1} \mathrm{s}^{-1} \mathrm{pix}^{-1} \mathrm{EM}^{-1}],$$
           where EM $\sim \mathrm{cm}^{-5}$ is the line of sight, or column
          emission measure. For a channel's temperature response F($T$):
          $$\mathrm{F}_c(T) = \int \mathrm{S}(\lambda, T) * \mathrm{R}(\lambda) * \mathrm{d}(\lambda)
               \sim [\mathrm{DN\ s}^{-1} \mathrm{pix}^{-1} \mathrm{EM}^{-1}] $$
          Note that one must assume a spectral model of the solar radiance (per emission measure) in order to calculate a temperature response. This must combine an atomic physics model (such as from ATOMDB or CHIANTI) with assumptions about the nature of the solar plasma ($\mathrm{N}_e$, $\mathrm{T}_e$, P, abundances, etc.) along the line of sight.  
          
          Going just a bit further, for an EM at $T = T_0$, the signal d
          observed is
          $\mathrm{d}|_{T_0} = \mathrm{F}(T_0) * \mathrm{EM}|_{T_0} \sim [\mathrm{DN\ s}^{-1} \mathrm{pix}^{-1}$].
          For an emission measure continuously distributed over a range
          of temperatures T, one uses the differential emission measure:
          DEM($T$) $\sim \mathrm{cm}^{-5} \mathrm{K}^{-1}$.
          Now the net signal d is
          $$\mathrm{d} =\int \mathrm{F}_c(T) * \mathrm{DEM}(T) * \mathrm{d}T \sim [\mathrm{DN\ s}^{-1} \mathrm{pix}^{-1}].$$
                 
            Note that this program \textbf{xrt\_dem\_iterative.pro} just solves
          the equation:
            $$\mathrm{d}_c = \int \mathrm{DEM}(T) * \mathrm{F}_c(T) * \mathrm{d}T$$

          As long as the units are all consistent, it is less important
          what they are. So if the temperature response units were
          DN $\mathrm{cm}^5 \mathrm{s}^{-1} \mathrm{pix}^{-1}$, and the observations were in units of
          DN $\mathrm{s}^{-1} \mathrm{pix}^{-1}$, then DEM will still have units of $\mathrm{cm}^{-5} K^{-1}$.
          The moral of the story is that a combination of temperature
          responses and observations can be solved, given sufficient care
          about units and cross-calibrations.
\item[4] There is a program called \textbf{xrt\_dem2obs.pro}, which may be used
          to generate a set of XRT observations from a DEM($T$) curve.
          See that program for an explanation of its usage.

         We can use these faux observations to illustrate the usage of 
         the solver, since you can compare the ``real" original DEM 
          against the estimated DEM. Here is a simple tutorial using both 
          programs. First, create a simple DEM curve.
          \begin{verbatim}
         IDL> demt = findgen(26)*0.1 + 5.5 ;; Temps are logarithms.
         IDL> dem = demt * 0
          IDL> dem[15] = 1.3e22
          IDL> print, demt[15]
                7.00000
          IDL> wdef, 0, 1000
          IDL> plot, demt, dem, psym=10, /ytype, yr=[1e20,1e23]
	 \end{verbatim}
          Now generate the set of observations XRT would see.
\begin{verbatim}
          IDL> obs = xrt_dem2obs(demt, dem)
          IDL> help, obs                      ;; 14 XRT channels
          OBS             STRUCT    = -> <Anonymous> Array[14]
          IDL> help, obs[0], /st
  ** Structure <26648d4>, 3 tags, length=28, data length=28, refs=1:
             CHANNEL_NAME    STRING    'Al-mesh'
             OBS             FLOAT           8344.32
             OBS_UNITS       STRING    'DN s^-1 pix^-1'
\end{verbatim}
          Just to be clear, prepare input variables for the solver.
\begin{verbatim}
     IDL> obs_val = obs.obs
     IDL> obs_index = obs.channel_name
     IDL> help, obs_index, obs_val
     OBS_INDEX       STRING    = Array[14]
     OBS_VAL         DOUBLE    = Array[14]
\end{verbatim}
          Run the solver.
\begin{verbatim}
      IDL> xrt_dem_iterative, obs_index, obs_val, logT_out, dem_out
      IDL> help, logT_out, dem_out
      LOGT_OUT        FLOAT     = Array[26]
      DEM_OUT         DOUBLE    = Array[26]
\end{verbatim}
         Overplot the solution.
 \begin{verbatim}
          IDL> oplot, logT_out, dem_out, psym=10, linesty=2
\end{verbatim}
          As a follow-up exercise, re-run the solver for 10 Monte Carlo
          iterations and over plot the results.
\item[5]  When the OBS\_VAL values are smaller than the OBS\_ERR 
          uncertainties, there is a chance that the Monte Carlo
          random variations to the data set will generate a set 
         of all-zero observations. The program checks for this case,
         and returns a DEM function equal to zero.
\item[6] This routine deprecates and replaces the older routine
   \textbf{xrt\_dem\_iterative.pro}. The older routine is not
compatible with the most recent response routines.
          
          \end{description}
%
%
%
% XRT Point Spread Function
%
%
%
\section{The XRT Point-Spread Function}
A point spread function (PSF) was developed for the XRT based off of metrology data provided my the mirror manufacturer and on-orbit observations. The metrology data estimate the encircled energy profiles for two energies, 0.56 keV and 1.0 keV at best on-axis focus. The PSFs developed assume best on-axis performance and model scattering caused by the mirror. Other sources of scattering are not included in the model PSF. A complete discussion about the development of the PSF is provided in the Appendix of the paper, \citet{Afshari16}. 

The PSF provided can be used with your favorite deconvolution routine. The PSF's are distributed in SolarSoft as fits files in the same location where the deconvolution routine is stored. The algorithm used to deconvolve XRT data is based off the SDO/AIA deconvolution routine called \textbf{aia\_richardsonlucy\_deconvolve.pro}. The routine \textbf{xrt\_deconvolve.pro} is a wrapper for this program and processes the data prior to deconvolution.

The routine outputs the processed data and updated index structure. It process XRT images in the following ways:
\begin{enumerate}
\item For binned data the routine bins and renormalizes the PSF to be on the same plate scale as the images.
\item For small fields of view, the routine drops the image into a 2048x2048 zero array and extracts it after deconvolution.
\item The routines forces the input data to non-negative and less than 2500, the current saturation value of the data.
\end{enumerate}

\subsection{Using \textbf{xrt\_deconvolve.pro}}

\begin{verbatim}
IDL>xrt_deconvolve,in,da,new_in,new_da
\end{verbatim}


Optional input keyword parameters:

\begin{description}
\item {\tt /NITER}: The number of iterations to perform. The default is 5.
\item {\tt /PSF1KEV}: Use the 1keV PSF instead of the default 0.56 keV.
\item {\tt /QUIET}: Suppress all output.
\item {\tt /VERBOSE}: Output extra messages.
\end{description}

The routine does not take into account data saturated pixels or data spikes due to particle hits. These pixels can be excluded by multiplying the input image by a mask where the saturated pixels have value 0 and non-saturated pixels have value 1 in the mask. The mask can be created from either using the grade map output from \textbf{xrt\_prep.pro} or by flagging the pixels yourself. There will be a ring around the mask in the output image but the masked region is ignored by the deconvolution routine. \\

Basic call: 

\begin{verbatim}
IDL>mask=intarr(512,512)+1  ; data=512x512 float array.
IDL>mask[where(data ge 2500)]=0
IDL>xrt_deconvolve,index,mask*data,new_in,new_data
IDL>new_data[where(data ge 2500)]=2500
\end{verbatim} 

\begin{figure}[ht!]
\hypertarget{Fig2_deconvolve}{}
\centering
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{psf_001.png}
\caption*{Al\_Poly, 16 April 2013, 18:26:31 UT}
\end{subfigure} \quad
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{psf_002.png}
\caption*{Saturation Mask}
\end{subfigure}

\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{psf_003.png}
\caption*{Deconvolution Without Mask}
\end{subfigure} \quad
\begin{subfigure}[t]{0.45\textwidth}
\includegraphics[width=\textwidth]{psf_004.png}
\caption*{Deconvolution With Mask}
\end{subfigure}

\caption{Example output from \textbf{xrt\_deconvolve} with and without using a saturation mask.}
\label{figure2_17}
\end{figure}

%
%
%
% Known Issues
%
%
%
\section{Known Issues}\label{nissues}
\hypertarget{knissues}{}

\begin{description}
\item \textbf{XRT Grade Map} 

\hspace{1cm} {\it Symptom}: There is a minor bug in the grade map pertaining to the pixels that are affected by possible contamination growth. When processing a data cube, the grade map corresponding to the first image is correct. The subsequent grade map values for pixels affected by contamination growth are sometimes not correct. This issue will be dealt with in the next release of \textbf{xrt\_prep.pro}. 

\hspace{1cm} {\it Remedy}: If the grade map is needed, then it is recommended that the images are processed as individual calls to \textbf{xrt\_prep}.

\end{description}







