GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR module

Synthetic High-Resolution Spectroscopy Data Generator

This module generates synthetic high-resolution spectroscopic data for exoplanet observations. It simulates the complete observing process including: - Stellar spectra with proper normalization - Planetary atmospheric signatures - Telluric absorption - Instrumental effects and noise - Orbital motion and Doppler shifts

The main function synthetic_HR() orchestrates the entire simulation process.

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.compute_spc_at_given_pwv(fit_spc: ndarray, mask: ndarray, pwv: float, airmass: float) ndarray[source]

Compute telluric spectrum at given precipitable water vapor (PWV) value.

This function takes a precomputed grid of telluric spectra and interpolates to compute the telluric transmission at any given PWV and airmass using polynomial interpolation in logarithmic space.

Parameters:
  • fit_spc (np.ndarray) – Polynomial fit coefficients for PWV interpolation, shape (2, n_wavelengths) First row contains linear coefficients, second row contains constant terms

  • mask (np.ndarray) – Boolean mask for invalid wavelength regions where transmission is unreliable

  • pwv (float) – Precipitable water vapor value in mm

  • airmass (float) – Airmass value for scaling atmospheric absorption (1.0 at zenith)

Returns:

Telluric transmission spectrum at given PWV and airmass, values between 0-1 where 1 = no absorption, 0 = complete absorption

Return type:

np.ndarray

Notes

The interpolation is performed in log-space to handle the exponential nature of atmospheric absorption. Masked regions are set to 0 transmission.

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.gen_pwv(size: int, dt: float = 1, pace: float = 600000.0, s: float = 0.69598, scale: float = 3.0862) ndarray[source]

Generate realistic time series of precipitable water vapor (PWV) values.

Creates a PWV time series using an autoregressive AR(1) model with exponential transformation to ensure positive values. The model captures the temporal correlation typical of atmospheric water vapor variations.

Parameters:
  • size (int) – Number of PWV values to generate (time points)

  • dt (float, optional) – Time step between observations in seconds, by default 1

  • pace (float, optional) – PWV correlation timescale parameter in seconds, by default 6e5 (about 7 days) Controls how quickly PWV values decorrelate over time

  • s (float, optional) – Scale parameter for the random component, by default 0.69598 Controls the amplitude of PWV variations

  • scale (float, optional) – Final scaling factor to convert to physical PWV units, by default 3.0862 Typical scaling to get PWV values in mm

Returns:

Array of PWV values in mm, shape (size,) Values are always positive due to exponential transformation

Return type:

np.ndarray

Notes

The AR(1) model follows: X[t] = p*X[t-1] + eps[t] where p is the autocorrelation parameter and eps is white noise. The exponential transformation ensures realistic PWV statistics.

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.prepare_fit(path_default: str, include_0_1=False) tuple[ndarray, ndarray, ndarray][source]

Prepare polynomial fit for PWV interpolation of telluric spectra.

Loads precomputed telluric transmission grids and creates polynomial fits for interpolating transmission as a function of PWV. The interpolation is performed in logarithmic space for better numerical stability.

Parameters:
  • path_default (str) – Path to default directory containing telluric grid files Expected structure: path_default/GUIBRUSHR/Files/Telluric_grids/

  • include_0_1 (bool, optional) – Whether to include PWV values of 0.0 and 1.0 mm in the interpolation grid. If True, extends the PWV grid to include very dry conditions (0.0 mm) and modifies the 1.0 mm point for better sampling, by default False

Returns:

  • fit_spc: Polynomial fit coefficients for PWV interpolation, shape (2, n_wavelengths)

  • telluric_wl: Wavelength array for telluric grid in nm, shape (n_wavelengths,)

  • mask: Boolean mask marking invalid spectral regions, shape (n_PWV, n_wavelengths)

Return type:

tuple[np.ndarray, np.ndarray, np.ndarray]

Notes

The telluric grid covers PWV values with higher sampling at low PWV values where transmission varies most rapidly. The polynomial fit is linear in PWV vs log(transmission) space. The include_0_1 parameter allows extending the grid to include extreme dry conditions for specialized observations.

Raises:

FileNotFoundError – If telluric grid files are not found in the expected location

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.plot_spectra(n_orders_tot, n_imgs, path_synthetic, flux_order_image, wavelength, telluric_spectrum, telluric_spectrum_times_flux, star_spectrum, continuum_star, star_spectrum_normalized, spectrum, synthetic_model, error_synthetic, synthetic_plus_error_model)[source]

Generate comprehensive spectral plots for synthetic HR data analysis.

Creates multi-panel plots showing all components of the synthetic spectrum generation process for each order and image. Saves plots as PDF files.

Parameters:
  • n_orders_tot – Number of spectral orders

  • n_imgs – Number of images (time points)

  • path_synthetic – Path to save plot files

  • flux_order_image – Mean flux values per order and img

  • wavelength – Wavelength arrays

  • telluric_spectrum – Telluric absorption spectrum

  • telluric_spectrum_times_flux – Telluric spectrum scaled by flux

  • star_spectrum – Stellar spectrum

  • continuum_star – Stellar continuum

  • star_spectrum_normalized – Normalized stellar spectrum

  • spectrum – Planetary spectrum

  • synthetic_model – Complete synthetic model (no noise)

  • error_synthetic – Noise component

  • synthetic_plus_error_model – Final synthetic spectrum with noise

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.save_fits_file(data, output_path, transpose_axes=(1, 2, 0))[source]

Save a numpy array to a FITS file with optional axis transposition.

Parameters:
  • data – Numpy array to save

  • output_path – Path where to save the FITS file

  • transpose_axes – Tuple specifying axis order for transposition

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.find_continuum_points(wavelength, flux, n_segments=20, method='max')[source]

Find continuum points by dividing spectrum into segments.

This function divides the input spectrum into segments and finds representative continuum points in each segment using either the maximum value or a high percentile.

Parameters:
  • wavelength – Array of wavelength values

  • flux – Array of flux values

  • n_segments – Number of segments to divide spectrum into

  • method – Method for finding continuum (‘max’ or ‘percentile’)

Returns:

Array of wavelength points for continuum cont_flux: Array of flux values for continuum points

Return type:

cont_wave

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.fit_continuum(wavelength, flux, n_segments=20, method='spline', degree=3)[source]

Fit continuum to spectrum using various methods.

Parameters:
  • wavelength – Array of wavelength values

  • flux – Array of flux values

  • n_segments – Number of segments for finding continuum points

  • method – Fitting method (‘spline’, ‘polynomial’, ‘linear’)

  • degree – Polynomial degree or spline parameter

Returns:

Fitted continuum array cont_wave: Wavelength points used for fitting cont_flux: Flux points used for fitting

Return type:

continuum

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.normalize_spectrum(wavelength, flux, n_segments=20, method='spline', degree=3)[source]

Normalize spectrum by dividing by fitted continuum.

Parameters:
  • wavelength – Array of wavelength values

  • flux – Array of flux values

  • n_segments – Number of segments for continuum fitting

  • method – Continuum fitting method

  • degree – Polynomial degree for fitting

Returns:

Flux normalized by continuum continuum: Fitted continuum cont_points: Tuple of (wavelength, flux) points used for fitting

Return type:

normalized_flux

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.analyze_skycalc_file(filename)[source]

Analyze SkyCalc output file for airmass and validation errors.

This function parses the SkyCalc output to extract the airmass value and check for any parameter validation errors.

Parameters:

filename – Path to SkyCalc output file

Returns:

Dictionary containing:
  • airmass: Extracted airmass value or None

  • has_validation_error: Boolean indicating if validation error occurred

  • error_message: Error message string or None

Return type:

dict

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.calculate_airmass(ra, dec, observatory_lat, observatory_lon, observatory_height, obs_time_iso)[source]

Calculate airmass for astronomical observations.

Computes the airmass (secant of zenith angle) for a target at given coordinates observed from a specified location and time.

Parameters:
  • ra – Right ascension in degrees

  • dec – Declination in degrees

  • observatory_lat – Observatory latitude in degrees

  • observatory_lon – Observatory longitude in degrees

  • observatory_height – Observatory height in meters

  • obs_time_iso – Observation time in ISO format ‘YYYY-MM-DDTHH:mm:ss’

Returns:

Airmass value (secant of zenith angle)

Return type:

float

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.hjd_to_datetime_string(hjd)[source]

Convert Heliocentric Julian Date to formatted datetime string.

Parameters:

hjd – Heliocentric Julian Date

Returns:

Date string in format ‘YYYY-MM-DDTHH:MM:SS’

Return type:

str

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.date_string_to_hjd(date_str)[source]

Convert date string to Heliocentric Julian Date.

Supports both ‘YYYYMMDD’ and ‘YYYY-MM-DD’ formats.

Parameters:

date_str – Date string in format ‘YYYYMMDD’ or ‘YYYY-MM-DD’

Returns:

Heliocentric Julian Date

Return type:

float

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.find_nearest_hjd(hjd0, period, target_date)[source]

Find the nearest HJD to a target date given reference HJD and period.

This function finds the closest transit time to a specified date using the ephemeris defined by hjd0 and period.

Parameters:
  • hjd0 – Reference Heliocentric Julian Date (epoch)

  • period – Orbital period in days

  • target_date – Target date string in format ‘YYYYMMDD’

Returns:

Dictionary containing:
  • hjd: Nearest HJD to target date

  • date: Formatted date string of nearest HJD

  • n_periods: Number of periods from hjd0

  • time_diff_hours: Time difference in hours from target

  • target_date: Original target date string

  • target_hjd: Target date converted to HJD

Return type:

dict

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.synthetic_HR(path_default: str, target_obj, path_target: str, rad_mode: str, instrument_obj, string_nights: str, model_CC: str, order_sel: str, tell_rm_method: str, path_stellar_spectrum: str = '', atmospheric_params: dict | None = None, almanac_params: dict | None = None, pwv_params: dict | None = None, discontinuous: bool = False, save_plots: bool = False, eccentricity: bool = False, noise_factor: float = 0.5, gain: float = 1.0, include_0_1: bool = False, seed: int = 42, error_type: str = 'Synthetic error') None[source]

Generate comprehensive synthetic high-resolution spectroscopic data for exoplanet observations.

This function orchestrates the complete simulation pipeline for high-resolution exoplanet spectroscopy, modeling all physical processes that affect the observed spectra. The simulation includes:

Physical Components: - Planetary atmospheric signatures with Doppler shifts due to orbital motion - Stellar spectra with proper continuum normalization and radial velocity variations - Telluric absorption computed using SkyCalc atmospheric models - Instrumental effects (spectral resolution, noise characteristics) - Time-variable atmospheric conditions (PWV, airmass)

Output Products: - Aligned spectral matrices compatible with standard analysis pipelines - Individual spectral components for diagnostic purposes - Comprehensive diagnostic plots showing all simulation steps - Realistic noise models preserving instrument characteristics

Parameters:
  • path_default (str) – Root path to the GUIBRUSHR directory structure containing telluric grids, stellar models, and planetary atmosphere models

  • target_obj (Target) – Target object containing orbital parameters (period, K_p, mass, etc.), stellar properties, and observational constraints

  • path_target (str) – Base directory path for target-specific data and output files

  • rad_mode (str) – Radiation transfer mode - either ‘Transmission’ for transmission spectroscopy or ‘Emission’ for thermal emission observations

  • instrument_obj (Instrument) – Instrument configuration object containing spectral resolution, wavelength coverage, noise characteristics, and detector properties

  • string_nights (str) – Comma-separated string of observation night identifiers to simulate (e.g., “2023-01-15,2023-01-16,2023-01-17”)

  • model_CC (str) – Cross-correlation model identifier specifying which planetary atmosphere model to use (must exist in planetary model database)

  • order_sel (str) – Selected spectral order identifier for processing (instrument-specific)

  • tell_rm_method (str) – Telluric removal method identifier used for directory structure organization

  • path_stellar_spectrum (str, optional) – Path to custom stellar spectrum template file. If empty, uses default stellar model based on target parameters, by default “”

  • atmospheric_params (dict, optional) –

    Atmospheric modeling parameters, by default None

    Required keys:
    • ’airmass’ : float - Target airmass (0 for automatic calculation)

    • ’pwv’ : str or float - PWV function name or constant value

    • ’observatory’ : str - Observatory identifier for SkyCalc

    • ’wres_mul’ : float - Wavelength resolution multiplier

    For discontinuous=False mode:
    • ’pwv_func’ : str - PWV function name (‘constant’, ‘linear’, ‘sine’)

    • ’initial_x’ : float - Initial PWV function parameter

    • ’final_x’ : float - Final PWV function parameter

  • almanac_params (dict, optional) –

    Observational coordinate parameters, by default None

    Keys (with defaults):
    • ’ra’ : float - Right ascension in degrees (145.6013)

    • ’dec’ : float - Declination in degrees (-10.33297)

    • ’obs_lat’ : float - Observatory latitude in degrees (28.7539999)

    • ’obs_long’ : float - Observatory longitude in degrees (-17.88905555)

    • ’obs_alt’ : float - Observatory altitude in meters (2387.19999)

  • pwv_params (dict, optional) –

    PWV time series generation parameters, by default None

    Keys (with defaults):
    • ’dt’ : float - Time step in seconds (1)

    • ’pace’ : float - PWV correlation timescale in seconds (6e5)

    • ’s’ : float - PWV amplitude scale factor (0.69598)

    • ’scale’ : float - PWV units scale factor (3.0862)

    • ’tExp’ : float - Exposure time per frame in seconds (for discontinuous=False)

  • discontinuous (bool, optional) –

    PWV calculation mode, by default False

    If True: Calculate PWV independently for each observation using atmospheric_params If False: Generate continuous AR(1) PWV time series using pwv_params

  • eccentricity (bool, optional) – Whether to include orbital eccentricity effects in velocity calculations, by default False. If False, assumes circular orbit

  • save_plots (bool, optional) – Whether to generate and save diagnostic plots showing all spectral components and processing steps, by default False

  • noise_factor (float, optional) – Noise scaling factor applied to the synthetic noise model. The noise is calculated as sqrt(synthetic_model) * noise_factor * gaussian_matrix. Lower values reduce noise amplitude, higher values increase it. By default 0.5 (equivalent to the previous /2 factor)

  • gain (float, optional) – Gain factor applied to the synthetic model before noise addition. This parameter allows scaling of the overall signal amplitude. Values > 1 increase signal strength, values < 1 decrease it. By default 1.0 (no scaling)

  • include_0_1 (bool, optional) – Whether to include PWV values of 0.0 and 1.0 mm in the telluric interpolation grid. If True, extends the PWV grid to include very dry atmospheric conditions (0.0 mm) which may be relevant for high-altitude observatory sites or specialized atmospheric modeling scenarios, by default False

  • seed (int, optional) – Random seed for reproducible random number generation. Used for both PWV time series generation and synthetic noise creation. Setting a specific seed ensures identical results across multiple runs with the same parameters, by default 42

  • error_type (str, optional) – Type of error generation method to use. Options are: - “Error from reduction”: Use errors from actual data reduction pipeline - “Synthetic error”: Generate synthetic errors using noise model By default “Synthetic error”

Returns:

Results are saved as FITS files and plots in target-specific directories:

Main Outputs: - {night}_syn/aligned.fits - Final synthetic aligned spectral matrix - {night}_syn/synthetic_telluric/ - Individual spectral components

Diagnostic Files: - Telluric transmission spectra - Stellar spectra (raw and normalized) - Planetary absorption/emission signatures - Noise models and final synthetic spectra - PDF plots showing all processing steps (if save_plots=True)

Return type:

None

Raises:
  • FileNotFoundError – If required model files, telluric grids, or stellar spectra are not found

  • ValueError – If orbital parameters are invalid or atmospheric parameters are malformed

  • KeyError – If required parameters are missing from input dictionaries

Notes

The simulation follows this processing pipeline:

  1. Setup Phase: Load planetary and stellar models, initialize night objects

  2. Velocity Calculation: Compute Doppler shifts from orbital motion

  3. PWV Generation: Create time-variable atmospheric water vapor

  4. Spectral Synthesis: Generate all spectral components

  5. Noise Addition: Apply realistic instrument noise models

  6. Output Generation: Save FITS files and diagnostic plots

The output files are organized to be compatible with standard HR analysis pipelines used for real observations.

GUIBRUSHR.GUI.Input_Output_Panels.Input_Panels.TabPanels.FrameGenerationHRData.synthetic_HR.main()[source]

Main function for command-line execution of synthetic HR simulation.

Loads simulation parameters from a pickle file containing a single dictionary with all simulation parameters and executes the synthetic_HR function. Handles command-line arguments, error reporting, and cleanup.

Expected command line usage:

python3 synthetic_HR.py <pickle_path> <path_default>

Args (from command line):

pickle_path: Path to pickle file containing simulation parameters dictionary path_default: Working directory for simulation

Returns:

System exit code (0 for success, 1 for error)

Notes

The pickle file contains a single dictionary with all simulation parameters organized into logical groups (core framework, observation, physical model, and processing options).