# The `pyspectral` API

## Blackbody radiation

Planck radiation equation.

pyspectral.blackbody.blackbody(wavel, temp)

  Derive the Planck radiation as a function of wavelength.

  SI units. blackbody(wavelength, temperature) wavel = Wavelength or a sequence of wavelengths (m) temp = Temperature (scalar) or a sequence of temperatures (K)

  Output: The spectral radiance per meter (not micron!)

    Unit = W/m^2 sr^-1 m^-1

pyspectral.blackbody.blackbody_rad2temp(wavelength, radiance)

  Derive brightness temperatures from radiance using the inverse Planck function.

  Parameters:

    - wavelength – The wavelength to use, in SI units (metre).

    - radiance – The radiance to derive temperatures from, in SI units (W/m^2 sr^-1). Scalar or arrays are accepted.

  Returns:

    The derived temperature in Kelvin.

pyspectral.blackbody.blackbody_wn(wavenumber, temp)

  Derive the Planck radiation as a function of wavenumber.

  SI units. blackbody_wn(wavnum, temperature) wavenumber = A wavenumber (scalar) or a sequence of wave numbers (m-1) temp = A temperatfure (scalar) or a sequence of temperatures (K)

  Output: The spectral radiance in Watts per square meter per steradian

    per m-1: Unit = W/m^2 sr^-1 (m^-1)^-1 = W/m sr^-1

    Converting from SI units to mW/m^2 sr^-1 (cm^-1)^-1: 1.0 W/m^2 sr^-1 (m^-1)^-1 = 1.0e5 mW/m^2 sr^-1 (cm^-1)^-1

pyspectral.blackbody.blackbody_wn_rad2temp(wavenumber, radiance)

  Derive brightness temperatures from radiance using the inverse Planck function.

  Parameters:

    - wavenumber – The wavenumber to use, in SI units (1/metre).

    - radiance – The radiance to derive temperatures from, in SI units (W/m^2 sr^-1). Scalar or arrays are accepted.

  Returns:

    The derived temperature in Kelvin.

pyspectral.blackbody.planck(wave, temperature, wavelength=True)

  Derive the Planck radiation as a function of wavelength or wavenumber.

  SI units. _planck(wave, temperature, wavelength=True) wave = Wavelength/wavenumber or a sequence of wavelengths/wavenumbers (m or m^-1) temp = Temperature (scalar) or a sequence of temperatures (K)

  Output: Wavelength space: The spectral radiance per meter (not micron!)

    Unit = W/m^2 sr^-1 m^-1

    Wavenumber space: The spectral radiance in Watts per square meter per steradian per m-1: Unit = W/m^2 sr^-1 (m^-1)^-1 = W/m sr^-1

    Converting from SI units to mW/m^2 sr^-1 (cm^-1)^-1: 1.0 W/m^2 sr^-1 (m^-1)^-1 = 1.0e5 mW/m^2 sr^-1 (cm^-1)^-1

## Spectral responses

Reading the spectral responses in the internal pyspectral hdf5 format.

class pyspectral.rsr_reader.RSRDict(instrument: str)

  Bases: `dict`

  Helper dict-like class to handle multiple names for band keys.

  get(key, default=None)

    Get value either directly or fallback to pre-configured ‘standard’ names.

class pyspectral.rsr_reader.RSRResponseDict

  Bases: `TypedDict`

  Dictionary of Relative Spectral Response information.

  central_wavelength: float
  response: ndarray[tuple[Any, ...], dtype[float32]]
  wavelength: ndarray[tuple[Any, ...], dtype[float32]]

class pyspectral.rsr_reader.RelativeSpectralResponse(platform_name: str | None = None, instrument: str | None = None, filename: str | Path | None = None)

  Bases: `_RSRDataBase`

  Container for the relative spectral response functions for various satellite imagers.

  convert()

    Convert spectral response functions from wavelength to wavenumber.

  get_bandname_from_wavelength(wavelength, epsilon=0.1, multiple_bands=False)

    Get the band name from the wavelength.

  integral(band_name)

    Calculate the integral of the spectral response function for each detector.

pyspectral.rsr_reader.check_and_download(dest_dir: str | Path | None = None, dry_run: bool = False) → None

  Do a check for the version and attempt downloading only if needed.

Base class for reading raw instrument spectral responses.

class pyspectral.raw_reader.InstrumentRSR(bandname, platform_name, bandnames=None)

  Bases: `object`

  Base class for the raw (agency dependent) instrument response functions.

## Solar irradiance

Read solar irradiances and calculate solar flux.

Module to read solar irradiance spectra and calculate the solar flux over various instrument bands given their relative spectral response functions

class pyspectral.solar.SolarIrradianceSpectrum(filename=PosixPath('/usr/lib/python3/dist-packages/pyspectral/data/e490_00a.dat'), **options)

  Bases: `object`

  Total Top of Atmosphere (TOA) Solar Irradiance Spectrum.

  Wavelength is in units of microns (10^-6 m). The spectral Irradiance in the file TOTAL_IRRADIANCE_SPECTRUM_2000ASTM is in units of W/m^2/micron

  convert2wavenumber()

    Convert from wavelengths to wavenumber.

    Units:

      Wavelength: micro meters (1e-6 m) Wavenumber: cm-1

  inband_solarflux(rsr, scale=1.0, **options)

    Get the in band solar flux.

    Derive the in-band integrated solar flux for a given instrument relative spectral response valid for an earth-sun distance of one AU.

    This is the total solar flux in the band in units of W/m^2.

  inband_solarirradiance(rsr, scale=1.0, **options)

    Get the in band solar irradiance.

    Derive the in-band spectral solar irradiance for a given instrument relative spectral response valid for an earth-sun distance of one AU.

    This is the total solar flux in the band convolved with the spectral response function in units of W/m^2/micron.

  interpolate(**options)

    Interpolate Irradiance to a specified evenly spaced resolution/grid.

    This is necessary to make integration and folding (with a channel relative spectral response) straightforward.

    dlambda = wavelength interval in microns start = Start of the wavelength interval (left/lower) end = End of the wavelength interval (right/upper end) options: dlambda: Delta wavelength used when interpolating/resampling ival_wavelength: Tuple. The start and end interval in wavelength space, defining where to integrate/convolute the spectral response curve on the spectral irradiance data.

  plot(plotname=None, **options)

    Plot the data.

  solar_constant()

    Calculate the solar constant.

## Near-Infrared reflectance

Derive NIR reflectances of a a band in the 3-4 micron window region.

Derive the Near-Infrared reflectance of a given band in the solar and thermal range (usually the 3.7-3.9 micron band) using a thermal atmospheric window channel (usually around 11-12 microns).

class pyspectral.near_infrared_reflectance.Calculator(platform_name, instrument, band, detector='det-1', wavespace='wavelength', solar_flux=None, sunz_threshold=85.0, masking_limit=85.0)

  Bases: `RadTbConverter`

  A thermal near-infrared (~3.7 micron) band reflectance calculator.

  Given the relative spectral response of the NIR band, the solar zenith angle, and the brightness temperatures of the NIR and the Thermal bands, derive the solar reflectance for the NIR band removing the thermal (terrestrial) part. The in-band solar flux over the NIR band is optional. If not provided, it will be calculated here!

  The relfectance calculated is without units and should be between 0 and 1.

  derive_rad39_corr(bt11, bt13, method='rosenfeld')

    Derive the CO2 correction to be applied to the 3.9 channel.

    Derive the 3.9 radiance correction factor to account for the attenuation of the emitted 3.9 radiance by CO2 absorption. Requires the 11 micron window band and the 13.4 CO2 absorption band, as e.g. available on SEVIRI. Currently only supports the Rosenfeld method

  emissive_part_3x(tb=True)

    Get the emissive part of the 3.x band.

  reflectance_from_tbs(sun_zenith, tb_near_ir, tb_thermal, **kwargs)

    Derive reflectances from Tb’s in the 3.x band.

    The relfectance calculated is without units and should be between 0 and 1.

    Inputs:

    > sun_zenith: Sun zenith angle for every pixel - in degrees

    > tb_near_ir: The 3.7 (or 3.9 or equivalent) IR Tb’s at every pixel

    >   (Kelvin)

    > tb_thermal: The 10.8 (or 11 or 12 or equivalent) IR Tb’s at every

    >   pixel (Kelvin)

    > tb_ir_co2: The 13.4 micron channel (or similar - co2 absorption band)

    >   brightness temperatures at every pixel. If None, no CO2 absorption correction will be applied.

pyspectral.near_infrared_reflectance.get_as_array(variable)

  Return variable as a Dask or Numpy array.

  Variable may be a scalar, a list or a Numpy/Dask array.

## Rayleigh scattering

> Atmospheric correction of shortwave imager bands in the wavelength range 400 to 800 nm.

> class pyspectral.rayleigh.Rayleigh(platform_name, sensor, **kwargs)

>   Bases: `RayleighConfigBaseClass`

>   Container for the atmospheric correction of satellite imager bands.

>   This class removes background contributions of Rayleigh scattering of molecules and Mie scattering and absorption by aerosols.

>   get_reflectance(sun_zenith, sat_zenith, azidiff, band_name_or_wavelength, redband=None)

>     Get the reflectance from the three sun-sat angles.

>   static reduce_rayleigh_highzenith(zenith, rayref, thresh_zen, maxzen, strength)

>     Reduce the Rayleigh correction amount at high zenith angles.

>     This linearly scales the Rayleigh reflectance, rayref, for solar or satellite zenith angles, zenith, above a threshold angle, thresh_zen. Between thresh_zen and maxzen the Rayleigh reflectance will be linearly scaled, from one at thresh_zen to zero at maxzen.

> class pyspectral.rayleigh.RayleighConfigBaseClass(aerosol_type, atm_type='us-standard')

>   Bases: `object`

>   A base class for the Atmospheric correction, handling the configuration and LUT download.

>   property lutfiles_version_uptodate

>     Tell whether LUT file is up to date or not.

> pyspectral.rayleigh.check_and_download(dry_run=False, aerosol_types=None)

>   Download atm correction LUT tables if they are not up-to-date already.

>   Do a check for the version of the atmospheric correction LUTs and attempt downloading only if needed.

> pyspectral.rayleigh.get_reflectance_lut_from_file(lut_filename)

>   Get reflectance LUT.

>   Read the Look-Up Tables from file with reflectances as a function of wavelength, satellite zenith secant, azimuth difference angle, and sun zenith secant.

> pyspectral.rayleigh.normalize_sensor(platform_name: str, sensor: str) → str

>   Check sensor belongs to platform and is consistently named.

## Utils

Utility functions.

pyspectral.utils.AEROSOL_TYPES = ['antarctic_aerosol', 'continental_average_aerosol', 'continental_clean_aerosol', 'continental_polluted_aerosol', 'desert_aerosol', 'marine_clean_aerosol', 'marine_polluted_aerosol', 'marine_tropical_aerosol', 'rayleigh_only', 'rural_aerosol', 'urban_aerosol']

  Aerosol types available as downloadable LUTs for rayleigh correction

class pyspectral.utils.NullHandler(level=0)

  Bases: `Handler`

  Empty handler.

  emit(record)

    Record a message.

pyspectral.utils.are_instruments_identical(name1, name2)

  Given two instrument names check if they are both describing the same instrument.

  Takes care of the case of AVHRR where the internal pyspectral naming (following WMO Oscar) is is with a slash as in “avhrr/1”, but where a naming using a dash instead is equally accepted, as in “avhrr-1”.

pyspectral.utils.bytes2string(var)

  Decode a bytes variable and return a string.

pyspectral.utils.check_and_adjust_instrument_name(platform_name, instrument)

  Check instrument name and try fix if inconsistent.

  It checks against the possible listed instrument names for each platform. It also makes an adjustment replacing names like avhrr/1 with avhrr1, removing the “/”.

pyspectral.utils.convert2hdf5(ClassIn, platform_name, bandnames, scale=1e-06, detectors=None)

  Retrieve original RSR data and convert to internal hdf5 format.

  scale is the number which has to be multiplied to the wavelength data in order to get it in the SI unit meter

pyspectral.utils.convert2str(value)

  Convert a value to string.

  Parameters:

    value – Either a str, bytes or 1-element numpy array

pyspectral.utils.convert2wavenumber(rsr)

  Convert Spectral Responses from wavelength to wavenumber space.

  Take rsr data set with all channels and detectors for an instrument each with a set of wavelengths and normalised responses and convert to wavenumbers and responses

  Rsr:

    Relative Spectral Response function (all bands)

  Returns:

    retv: Relative Spectral Responses in wave number space :info: Dictionary with scale (to go convert to SI units) and unit

pyspectral.utils.debug_on()

  Turn debugging logging on.

pyspectral.utils.download_luts(aerosol_types=None, dry_run=False, aerosol_type=None)

  Download the luts from internet.

  See `pyspectral.rayleigh.check_and_download()` for a “smart” version of this process that only downloads the necessary files.

  Parameters:

    - aerosol_types (Iterable) – Aerosol types to download the LUTs for. Defaults to all aerosol types. See `AEROSOL_TYPES` for the full list.

    - dry_run (bool) – If True, don’t actually download files, only log what URLs would be downloaded. Defaults to False.

    - aerosol_type (str) – Deprecated.

pyspectral.utils.download_rsr(dest_dir: str | Path | None = None, dry_run: bool = False) → None

  Download the relative spectral response functions.

  Download the pre-compiled HDF5 formatted relative spectral response functions from the internet as tarballs, extracts them, then deletes the tarball.

  See `pyspectral.rsr_reader.check_and_download()` for a “smart” version of this process that only downloads the necessary files.

  Parameters:

    - dest_dir – Path to put the temporary tarball and extracted RSR files.

    - dry_run – If True, don’t actually download files, only log what URLs would be downloaded. Defaults to False.

pyspectral.utils.get_bandname_from_wavelength(sensor, wavelength, rsr, epsilon=0.1, multiple_bands=False)

  Get the bandname from h5 rsr provided the approximate wavelength.

pyspectral.utils.get_bounds_integrated_energy(rsp, wvl, ener_perc_lim=1)

  Compute wavelengths over which the integrated energy is greater than a threshold.

  This measure is typically used to assess out of band performance and to ensure that the spectral response function is not sensitive to specific absorption or emission features. On occasion, it is also used to define or measure the bandwidth of a sensor.

  The `ener_perc_lim` variable defines the threshold percentage of integrated energy. This function returns the minimum and maximum wavelengths over which the integrated energy is greater than (minimum) and less than (maximum) the threshold.

pyspectral.utils.get_central_wave(wav, resp, weight=1.0)

  Calculate the central wavelength or the central wavenumber.

  Calculate the central wavelength or the central wavenumber, depending on which parameters is input. On default the weighting funcion is f(lambda)=1.0, but it is possible to add a custom weight, e.g. f(lambda) = 1./lambda**4 for Rayleigh scattering calculations

pyspectral.utils.get_fullwidth_halfmax(rsp, wvl)

  Compute the full-width half maximum (bandwidth) for a given spectral response.

  Ths FWHM is defined as the wavelength range over which the SRF is greater than half of the maximum response. Often, this is referred to as the bandwidth of a channel.

pyspectral.utils.get_logger(name)

  Return logger with null handle.

pyspectral.utils.get_rayleigh_lut_dir(aerosol_type: str) → Path

  Get the rayleigh LUT directory for the specified aerosol type.

pyspectral.utils.get_wave_range(in_chan, threshold=0.15)

  Return central, min and max wavelength in an RSR greater than threshold.

  An RSR function will generally start near zero, increase to a maximum and then drop back to near zero. This function takes advantage of this to find the first and last points where the RSR is greater than a threshold. These points are then defined as the minimum and maximum wavelengths for a given channel, and can be used, for example, in Satpy reader YAML files.

pyspectral.utils.logging_off()

  Turn logging off.

pyspectral.utils.logging_on(level=30)

  Turn logging on.

pyspectral.utils.np2str(value)

  Convert an `numpy.bytes_` to str.

  Note: `numpy.string_` was deprecated in numpy 2.0 in favor of `numpy.bytes_`.

  Parameters:

    value (ndarray) – scalar or 1-element numpy array to convert

  Raises:

    ValueError – if value is array larger than 1-element or it is not of type numpy.bytes_ or it is not a numpy array

pyspectral.utils.sort_data(x_vals, y_vals)

  Sort the data so that x is monotonically increasing and contains no duplicates.

pyspectral.utils.use_map_blocks_on(argument_to_run_map_blocks_on)

  Use map blocks on a given argument.

  This decorator assumes only one of the arguments of the decorated function is chunked.

## Testing Utilities

Utilities for writing third-party tests that interact with Pyspectral.

The `pyspectral.testing` module provides functionality primarily for users of pyspectral to add to their own testing. By using these utilities you can avoid downloading pyspectral LUTs and other files that pyspectral may want to download. This should make your tests faster and require less disk space while also making your CI runners and pyspectral’s data host happier due to fewer (or no) downloads.

There are two levels of utilities. High-level utilities are most useful and typically mock a single component/interface of Pyspectral. Lower-level utilities are used by the higher-level utilities and generally only handle one part of the necessary changes to avoid Pyspectral downloads. For example, a low-level utility may set up the environment to create fake LUT files, but won’t set up the Pyspectral configuration to make Pyspectral use those files. Unless you are trying to optimize how and when the mocking is performed, it is recommended to use the high-level utilities.

### Pytest fixtures

Many of these utilities are context managers. If using these functions from pytest-based unit tests, it can be a good idea, although not required, to make a pytest fixture and pass pytest’s tmp_path to the utilities that require a directory. For example:

    @pytest.mark.fixture
    def fake_pyspectral(tmp_path):
        from pyspectral.testing import mock_pyspectral_downloads

        with mock_pyspectral_downloads(tmp_path=tmp_path):
            yield

This is especially useful for utilities like `forbid_pyspectral_downloads()` which can be set to run at the start of the pytest session and apply to all tests. See the individual function API documentation for examples.

### High-level utilities

- `mock_pyspectral_downloads()`

- `mock_tb_conversion()`

- `mock_rsr()`

- `mock_rayleigh()`

- `override_config()`

- `forbid_pyspectral_downloads()`

See the API documentation linked above for more information on how to use these functions.

### Lower-level utilities

- `init_tb_cache()`

- `mock_rsr_files()`

- `mock_rayleigh_luts()`

pyspectral.testing.create_pyspectral_config_file(config_path: Path, config_options: dict | None = None) → None

  Create an on-disk YAML file with the provided options.

  Parameters:

    - config_path – Path of the config file to create.

    - config_options – Configuration options to write to YAML file. If not provided then an empty dictionary is used.

pyspectral.testing.forbid_pyspectral_downloads()

  Raise exception if pyspectral tries to download LUTs from the internet.

  It is recommended to add this to your package’s tests’ root `conftest.py` as a session-level autouse fixture. For example:

      from pyspectral.testing import forbid_pyspectral_downloads

      @pytest.fixture(autouse=True, scope="session")
      def _forbid_pyspectral_downloads():
          with forbid_pyspectral_downloads():
              yield

  To avoid errors caused by this context manager, mocking or other fake data creation should be used to avoid pyspectral attempting a download. See the other context managers and functions in `pyspectral.testing` for available pyspectral-provided functionality.

  Note if you need some tests to not use this limitation (ex. tests that only run outside of CI) then the fixture can’t be session scoped. See pyspectral’s own `pyspectral/tests/conftest.py` for an example of using a pytest mark to control when tests are allowed to access downloads.

pyspectral.testing.init_tb_cache(tb2rad_dir: Path) → Iterator[None]

  Initialize RadTbConverter and Calculator cache directory.

  It will be filled when tests call the necessary methods of the effected classes.

pyspectral.testing.mock_pyspectral_downloads(*, tmp_path: Path | None = None, extra_config_options: dict | None = None, rsr_files_kwargs: dict | None = None) → Iterator[None]

  Mock pyspectral’s interfaces to avoid downloading files from the internet.

  This currently mocks and creates fakes versions of Rayleigh LUTs, RSR files, and the TB2Rad cache. It also overrides the pyspectral global configuration file to use these fake files. This function is an all-in-one version of the other high-level testing mocking utilities.

  Parameters:

    - tmp_path – Base directory to create fake files. If not provided or None, a directory will be created when the context manager is entered and deleted when exited. If provided, the directory and its contents will not be deleted.

    - extra_config_options – Extra pyspectral configuration settings to set in addition to those required for mocking to succeed.

    - rsr_files_kwargs – Keyword arguments to pass to `mock_rsr_files()`.

pyspectral.testing.mock_rayleigh(*, rayleigh_dir: Path | None = None, rsr_dir: Path | None = None, existing_version: bool | str = True, lut_data: dict | None = None, aerosol_types: Iterable[str] | None = None, atmospheres: Iterable[str] | None = None) → Iterator[None]

  Mock the Rayleigh interfaces to avoid LUT downloads.

  This high-level function overrides the pyspectral configuration and creates fake rayleigh LUT files using mock_rayleigh_luts.

  Parameters:

    - rayleigh_dir – Path where rayleigh LUTs should be created. If not specified then a temporary directory will be created and deleted on exit of the context manager.

    - rsr_dir – Path to store fake RSR files. If not specified then this is set to `rayleigh_dir`.

    - existing_version – How to prepare the fake LUT directory. This can be `True` (default) meaning the directory should be created as if they are the most up-to-date versions of the LUTs. If `False` then the version and LUT files are not created beforehand and will be created as downloads are requested. Downloads are mocked so no internet connection is accessed. If a string value is provided then that will be used as the version of the LUT files (ex. ‘v0.0.0’ to represent out-of-date files). Note that a “template” HDF5 will be created in the root of the rayleigh directory so it can be linked to in any later LUT creation instead of creating a new LUT file every time.

    - lut_data – Dictionary of numpy arrays to store to the HDF5 LUT file. Keys must include “azimuth_difference”, “reflectance”, “satellite_zenith_secant”, “sun_zenith_secant”, and “wavelengths”.

    - aerosol_types – List of aerosol types to create files for. Defaults to all supported types.

    - atmospheres – Atmospheres to create LUTs for. Defaults to all supported atmosphere types.

pyspectral.testing.mock_rayleigh_luts(rayleigh_dir: Path, *, existing_version: bool | str = True, lut_data: dict | None = None, aerosol_types: Iterable[str] | None = None, atmospheres: Iterable[str] | None = None) → Iterator[None]

  Mock the rayleigh LUT directories.

  Note this function does not mock the pyspectral global configuration necessary for the fake rayleigh LUTs to be used by pyspectral. You must either use `mock_rayleigh()` instead or use `override_config()` to override the configuration yourself and call `mock_rsr_files()` to mock the RSR files used by the Rayleigh class. The new configuration data must include `rayleigh_dir` passed to this function and `rsr_dir` passed to the `mock_rsr_files()` function.

  Parameters:

    - rayleigh_dir – Path where rayleigh LUTs should be created.

    - existing_version – How to prepare the fake LUT directory. This can be `True` (default) meaning the directory should be created as if they are the most up-to-date versions of the LUTs. If `False` then the version and LUT files are not created beforehand and will be created as downloads are requested. Downloads are mocked so no internet connection is accessed. If a string value is provided then that will be used as the version of the LUT files (ex. ‘v0.0.0’ to represent out-of-date files). Note that a “template” HDF5 will be created in the root of the rayleigh directory so it can be linked to in any later LUT creation instead of creating a new LUT file every time.

    - lut_data – Dictionary of numpy arrays to store to the HDF5 LUT file. Keys must include “azimuth_difference”, “reflectance”, “satellite_zenith_secant”, “sun_zenith_secant”, and “wavelengths”.

    - aerosol_types – List of aerosol types to create files for. Defaults to all supported types.

    - atmospheres – Atmospheres to create LUTs for. Defaults to all supported atmosphere types.

pyspectral.testing.mock_rsr(*, rsr_dir: Path | None = None, rsr_data_version: str | None = 'v1.4.1', download_from_internet: bool = False, central_wavelengths: dict[str, float] | None = None, side_effect: Any = '__unset__', return_value: Any = '__unset__') → Iterator[Mock]

  Mock the RelativeSpectralResponse class to avoid download of RSR files.

  This is the high-level function that uses mock_rsr_files to do the work of creating fake RSR files and mocking the necessary parts of pyspectral. Additionally, this function overrides the global pyspectral config file to allow the fake RSR files to be used.

  Parameters:

    - rsr_dir – Path to store fake RSR files. If not provided then a temporary directory is used and deleted on exit of the context manager.

    - rsr_data_version – Version number to use for the created fake RSR files. By default, the newest/active version number will be used. See `mock_rsr_files()` for more details.

    - download_from_internet – Set pyspectral configuration value to allow or disallow downloads to occur. Defaults to False and relies on mocking to make the files seem like they exist. If `True` then downloads may be attempted if `rsr_data_version` is out of date or `None`.

    - central_wavelengths – Dictionary mapping a channel name to a central wavelength floating point number. This is used to generate more realistic data in the created fake RSR files. This has no effect if `side_effect` or `return_value` are specified.

    - side_effect – Force the mocking of the data coming from the fake files.to use this callback or exception class. This is a low-level option and typically does not need to be specified. This has no effect if `return_value` is specified.

    - return_value – Force the mocking of the data coming from the fake file to be exactly this value. This is a low-level option and typically does not need to be specified. This value takes priority over `side_effect` and `central_wavelengths`.

pyspectral.testing.mock_rsr_files(rsr_dir: Path, *, rsr_data_version: str | None = 'v1.4.1', central_wavelengths: dict[str, float] | None = None, side_effect: Any = '__unset__', return_value: Any = '__unset__') → Iterator[Mock]

  Mock the RelativeSpectralResponse class and create fake RSR files to avoid downloads.

  This function does not override the pyspectral global configuration and as such the modifications applied by this function do not completely mock all access to RSR files. You must either use the higher-level mock_rsr function instead or override the configuration yourself using override_config and set `rsr_dir` to the path passed to this function.

  Parameters:

    - rsr_dir – Path to store fake RSR files.

    - rsr_data_version – Version number to use for the created fake RSR files. By default, the newest/active version number will be used. If `None` then no version file is written and no directory created. Note setting to `None` will trigger downloads to occur if no further mocking is done. This should only be used to test that downloads do happen when needed. This does not prevent the mocking (see `side_effect` and `return_value`) from making pyspectral think it has the downloads.

    - central_wavelengths – Dictionary mapping a channel name to a central wavelength floating point number. This is used to generate more realistic data in the created fake RSR files. This has no effect if `side_effect` or `return_value` are specified.

    - side_effect – Force the mocking of the data coming from the fake files.to use this callback or exception class. This is a low-level option and typically does not need to be specified. This has no effect if `return_value` is specified.

    - return_value – Force the mocking of the data coming from the fake file to be exactly this value. This is a low-level option and typically does not need to be specified. This value takes priority over `side_effect` and `central_wavelengths`.

pyspectral.testing.mock_tb_conversion(*, tb2rad_dir: Path | None = None, rsr_dir: Path | None = None, **rsr_files_kwargs) → Iterator[Mock]

  Mock pyspectral to avoid downloads and caching for Calculator and RadTbConverter classes.

  Parameters:

    - tb2rad_dir – Path to store Tb to radiance LUT data. If not provided a temporary one will be used and deleted on exit of the context manager.

    - rsr_dir – Path to store fake RSR files. If not provided then the `tb2rad_dir` will be used.

    - rsr_files_kwargs – Keyword arguments to pass to `mock_rsr_files()`.

pyspectral.testing.override_config(config_options: dict | None = None, config_path: Path | None = None) → Iterator[Path]

  Override builtin config with temporary on-disk YAML file.