Metadata-Version: 2.4
Name: qmost-xpca
Version: 1.0.4.dev0
Summary: 4MOST Redshift Module
Author-email: Jens-Kristian Krogager <jens-kristian.krogager@univ-lyon1.fr>
Keywords: 4MOST,4XP,Extra-galactic Analysis,Redshift
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: astropy
Requires-Dist: numpy
Requires-Dist: scipy
Requires-Dist: networkx
Requires-Dist: matplotlib
Requires-Dist: joblib
Requires-Dist: pyyaml
Requires-Dist: pytest
Provides-Extra: doc
Requires-Dist: setuptools_scm; extra == "doc"
Requires-Dist: sphinx; extra == "doc"
Requires-Dist: furo; extra == "doc"
Dynamic: license-file

# xPCA : Cross-correlation and PCA template fitting

Based on a prototype by JK Krogager, Aug 1st 2022
inspired by Glazebrook, Offer and Deeley 1998, ApJ 492, 98

The xPCA algorithm obtains spectroscopic redshift measurements and broad object classification
using an initial cross-correlation step to identify likely regions of redshift space
for various spectral templates. Each region of interest is subsequently analysed using a
principal component analysis. A redshift grid is defined around the 5 most significant peaks
from the cross-correlation function. At each point in redshift space, a PCA fit is obtained
which yields a Chi^2 value. The minimum of the Chi^2 as a function of redshift as well as the
decrease of the Chi^2 surface around the minimum are recorded for each solution.
All solutions for all template types are then ranked based on their minimum Chi^2 and the dip in Chi^2 (dChi^2). 
The highest ranked solutions are returned as the 5 most credible solutions.


## Installation

### Public version

The public versions of the code can be installed directly from pip:
    
    pip install qmost-xpca

Note the different name when installing from pip: `qmost-xpca`.

### Internal versions

Clone the code from the gitlab repository. This requires an account on the 4MOST GitLab server.
You can then install using pip:

    git clone git@gitlab.4most.eu:iwg8/xpca.git
    cd xpca
    python -m pip install .

You can also obtain development versions from the internal PyPI registry:

    QMOST_PYPI=https://gitlab.4most.eu/api/v4/projects/212/packages/pypi/simple
    pip install --extra-index-url $QMOST_PYPI qmost-xpca


## Running xPCA from the command line

The code is executed directly from the terminal by the following command:

    python -m xpca -h

This will show the help string for the command line options.

Currently the code accepts spectra in FITS format for:
 - individual 4MOST 'singlespec' files (default)
 - individual SDSS spectra (`--source=sdss`)
 - individual GAMA spectra (`--source=gama`)
 - individual 4MOST MEC files (`--source=mec`)
 - individual CSV files (`--source=csv`)

Note: For MEC files it's possible to use the `--start` and `--end` options
to indicate the first and last index of the MEC container to process.

You can also give a folder or a regex pattern to match.

### Output to the command line

If you process a single spectrum, the best-fit solutions will be written to the terminal as follows:

    ```
     --- Best solutions ---
    
               Redshift     Error    Template      FoM    Prob    DCHI2     CHI2   Flags
    zBest :     1.24911    0.00015   QSO-LOWZ      1.00   1.00    24900    34111   0
    z_2 :       1.25330    0.00017   QSO-MIDZ      0.96   0.96    23481    35019   0
    z_3 :       4.17048    0.00087   QSO           0.54   0.54    11815    45467   0
    z_4 :       0.56528    0.00011   QSO-LOWZ      0.46   0.46     9976    47840   0
    z_5 :      -0.04290    0.00018   QSO-LOWZ      0.38   0.38     8162    50014   0
    ```

In this case, the analyzed spectrum is indeed a simulated quasar at redshift z = 1.2497.


### Command line options

  | Abb. | Option          | Type | Description |
  | ---- | --------------- | ---- | ----------- |
  | `-d` | `--debug`       |      | Activate debugging mode; save full output; add debug info to log |
  | `-V` | `--version`     |      | Show version and quit |
  |      | `--log`         | str  | Filename of the log file; (default = write log-stream to the terminal) |
  | `-o` | `--output`      | str  | Filename of the output catalog; (default = auto-generated using time stamp) |
  |      | `--full`        | str  | Filename of the full catalog (only with `--debug`, default = auto-generated using time stamp) |
  |      | `--start`       | int  | Index of targets to start the analysis |
  |      | `--end`         | int  | Index of targets to end the analysis |
  |      | `--mp`          | int  | Number of CPU cores to use for multi-threading (default = all) |
  | `-s` | `--source`      | str  | The source of the spectra, one of: singlespec, sdss, hrs, mec, gama, csv |
  | `-zp` |` --priors`     | str  | Catalog of photometric redshift priors (filename.fits) |
  |      | `--chunk`       | int  | Size of chunks when processing a MEC file in batch mode (default 10000) |
  | `-t` | `--tell`        |      | Filter telluric regions in the spectra (default: no telluric filtering) |
  | `-N` | `--N-best`      | int  | Number of redshift solutions to keep (default = 5) |
  |      | `--smooth-gal`  | float  | Smoothing factor for galaxy templates (gaussian kernel in pixels) |
  |      | `--smooth-star` | float  | Smoothing factor for stellar templates (gaussian kernel in pixels) |
  |      | `--smooth-qso`  | float  | Smoothing factor for quasar templates (gaussian kernel in pixels) |
  |      | `--deblend`     |      | Run xPCA in deblend mode: search for two solutions in the spectra |
  |      | `--l2`          | str  | Filename of the first pass redshift catalog from xpca. Only used with `--deblend` |
  |      | `--vac`         |      | Turn off the default air-to-vacuum conversion of wavelengths |
  |      | `--rules`       | str  | MEC rules to apply following logical expressions, ex: 'OBJ_FLAG < 2' |


### Masking of Telluric Regions

By default, no masking of telluric regions is performed, since all test spectra have been
corrected for telluric absorption features. However, the simulated spectra using the 4MOST ETC
includes the uncorrected absorption features and these regions should therefore be removed
when analysing such spectra. To include the telluric masking, run the command with the `-t` (or `--tell`) option.

    python -m xpca *filename.fits* -t

The telluric regions are hard-coded in the `xpca/config.py` file.


### Air vs Vacuum Wavelengths

Since 4MOST data are delivered in air wavelengths, xpca converts the wavelengths to the vacuum reference frame
by using the refractive index of the atmosphere as given by Ciddor 1996 (http://doi.org/10.1364/AO.35.001566). 
If the input spectra have already been corrected to the vacuum reference frame, then the user should run
xpca with the `--vac` command line option.


### Photometric redshift priors
You can run xpca with the command line option `-zp` to pass a FITS table
with photometric prior data per target. The table must contain a column `OBJ_NME`
matching the object name in the spectra. There are three possibilities
to provide redshift priors:

1. `REDSHIFT_ESTIMATE` and `REDSHIFT_ERROR`
    This is following the 4FS target catalog format and will create a
    Gaussian prior with the given redshift and standard deviation.

2. `ZPHOT_MU_i`, `ZPHOT_SIG_i`, `ZPHOT_AMP_i` for i in {1, 2, 3}
    This is following the MACOL format defining up to three Gaussian components
    of the redshift prior. Not all three components have to be defined, but all three parameters
    for each component has to be defined (MU, SIG, and AMP). Note that the prior is not normalized
    afterwards, so proper normalization should be ensured by the AMP parameters.

3. `Z` and `Z_PDF`
    A full posterior redshift probability density distribution
    from a photometric redshift analysis. `Z` and `Z_PDF` must be arrays of equal length
    in this case. The applied prior will be interpolated between these points.

By default, if multiple definitions are given for a single target,
the priors will be assigned in order 3, 2, 1. That is, `Z` and `Z_PDF` will be given priority,
subsequently the multiple gaussians will be used, and lastly, the single gaussian prior will be used.

If a target is not found in the redshift prior catalog, then no prior will be used
and a warning will be raised in the log.

The best-fit redshift using the photometric redshift prior is given in the output catalog
as the column `z_PZ` with its associated columns suffixed by `_PZ`.


## Examples

### 4MOST singlespec files
Process all files matching a given pattern in a directory:

    python -m xpca 'folder/*_LJ1.fits' --log folder_all.log

This will generate an output table with a date and time stamp:
`QMOST_XPCA_20230517T0846_L2.fits`

To change the name of the output table, use the `--output (-o)` option.

If run for a single target, the code also prints the output to terminal.
The output is also saved in a FITS table. 

To run on all (*.csv) files in a given folder:

    python -m xpca path/to/folder --source csv


### 4MOST MEC files
Process the first 500 spectra of a 4MOST MEC file using the `--source` (or `-s`) option:

    python -m xpca MEC_LJ11.fits -s mec --end 500 


**MEC Rules:**
You can apply filtering of the MEC files to only analyse certain rows based on the values in the
FIBINFO table. An example would be to only process targets with SNR > 3:

    python -m xpca MEC_LJ14.fits -s mec --rules 'SNR_4L1 > 3'

For a full set of columns in the FIBINFO table, see the description of the 4MOST L1 data model
or inspect the FIBMETATAB extension of the MEC file.


### SDSS individual files
Process all SDSS files matching a given pattern in a directory using the  `--source` (or `-s`) option:

    python -m xpca 'folder/spec-*.fits' --log sdss_test.log --source sdss


### Generic CSV files
xPCA can read in spectra in a generic comma-separate file (CSV) with three mandatory columns for
wavelength, flux and flux uncertainty. These can be specified using the following column names that
must be specified in the first line of the CSV file:

| Quantity   | Valid Names                                             |
|------------|---------------------------------------------------------|
| Wavelength | 'wave', 'wl', 'lambda', 'wavelength', 'loglam'          |
| Flux       | 'flux_density', 'flux', 'flam', 'flambda'               |
| Flux Error | 'error', 'err', 'flux_error', 'err_flux', 'ivar', 'var' |

Appropriate conversions, such as log(lambda) -> lambda or inverse variance -> standard deviation, are automatically applied. Since no meta data is encoded in the CSV file, the output only contains the filename as a reference (in the `PROV` column).


### Debugging mode
If run with the `--debug` option, the full output is returned in a separate file
following the same date and time stamp, e.g.:
`QMOST_XPCA_20230517T0846_DEBUG.fits` (for the output filename given above).

This FITS table includes the full cross-correlation function
and the chi^2 solutions for all identified peaks and for all templates.
To change the name of the debug-table, use the `--full` option.

Example:

    python -m xpca test_file.fits --debug --full debug_output.fits


**WARNING:** Do not use the full debugging mode for more than one spectrum at a time!
The additional memory needed to store the full solutions might crash your system.



## Running xPCA within the 4MOST data flow

The algorithm can be run as part of the 4MOST dataflow under the data processing center (4DPC) using either the 'L1 backend module (QZC)' implemented as the `FeedbackModule` in `backend.py`, or as part of the extragalactic pipeline (4XP-Z) using the `run` function implemented in `main.py`.

Both module implementations are configured to process all available stacking levels of joined MEC files of the low resolution spectrographs (`_LJ*.fits`). The output behaviour differs slightly between the QZC and 4XP-Z implementations:

 - The QZC module updates the given MEC file which is being processed and writes to the `FIBMETATAB` columns: QZC_Z, QZC_ZERR, QZC_ZPRB, QZC_ZTPL, and QZC_ZWRN. In the process of doing this, the module writes temporary output tables which are deleted at the end of a successful run.

 - The 4XP-Z module instead writes all output to separate files (one per MEC file analysed). These individual output files are subsequently combined into a single table, if the data processing passed successfully.

All runtime parameters are defined by the module implementations. Telluric masking is not needed, as the 4MOST spectra will be corrected by the L1 data reduction pipeline.


### FeedbackModule optional arguments

- `mp=96` : Number of CPU cores in Multiprocessing
    By default, all available CPU cores are used for the multiprocessing; However, a test of the runtime for varying number of CPU cores shows that above 96 cores (out of 160 available on 4DPC), there is no gain in runtime. Hence, the `mp` option is set to 96 for both the `QZC` and `4XP-Z` modules running on 4DPC.

    The test was carried out on 4DPC processing a full MEC file (25,727 spectra) for varying number of cores (from 16 to 160). We also tested on a smaller subset of 1000 spectra. The conclusion is that the overheads of multi-threading, output collection and shared PCA templates in memory for each thread leads to a maximum number of efficient cores (`mp=96`). Above this number, there is no gain in processing speed. For comparison, this benchmark test obtained a total processing time of 2400 seconds for 25,727 spectra, corresponding to the number of individual spectra expected for a single night (excluding stacked spectra).

- `mec_rules="OBJ_FLAG & 1 != 0"` : Processing rules to filter out rows of the MEC table
    The QZC backend module will only run on rows where the `mec_rules` evaluate to true. Note that if a rule is given which doesn't parse correctly, it will be ignored and default to processing *all rows*. 

    Example:  `mec_rules="(OBJ_FLAG > 0) & (FIB_USE == 1)"`
