API Documentation

pysilsub.observers

Colorimetric observer model based on CIEPO06 and CIES026.

Translated from…

Checked against:

exception pysilsub.observers.ObserverError

Generic Python-exception-derived object.

Raised programmatically by Observer class methods when arguments are incorrectly specified or when they do not agree with values of other.

class pysilsub.observers.ColorimetricObserver
__init__(age=32, field_size=10, penumbral_cones=False)
Parameters:
  • age (int | float) –

  • field_size (int | float) –

  • penumbral_cones (bool) –

adjust_lms(age, field_size)

Adjust LMS spectral sensetivities for age and field size.

Parameters:
  • age (int) – Observer age.

  • field_size (int) – Field size of the stimulus.

Returns:

lms_bar_norm – Adjusted LMS spectral sensitivites.

Return type:

pd.DataFrame

adjust_melanopsin()

Adjust melanopsin action spectrum for observer age.

After CIE:, we use a different lens density spectrum.

Returns:

new_mel – Melanopic action spectrum adjusted for age.

Return type:

np.array

adjust_rhodopsin()

Adjust rhodopsin action spectrum for observer age.

After CIE:, we use a different lens density spectrum.

Returns:

new_rod – Rhodopic action spectrum adjusted for age.

Return type:

np.array

add_penumbral_cones()

Include spectral sensitivities for penumbral cones.

Penumbral cones are cones that lie in the shadow of retinal blood vessels and have altered spectral sensitivity functions due to prefiltering of light by hemoglobin.

Return type:

None.

pysilsub.devices

Software model for multiprimary stimulation devices.

exception pysilsub.devices.StimulationDeviceError

Generic Python-exception-derived object.

Raised programmatically by StimulationDevice methods when arguments do not agree with internal parameters and those used to instantiate the class.

class pysilsub.devices.StimulationDevice

Generic class for calibrated multiprimary stimultion device.

Includes methods to visualise and predict data for a calibrated multiprimary system.

__init__(calibration, calibration_wavelengths, primary_resolutions, primary_colors, observer='CIE_standard_observer', name=None, config=None)

Instantiate class with specified parameters.

Parameters:
  • calibration (str or pd.DataFrame) – DataFrame or path to CSV file with spectral measurements to characterise the output of the device. Column headers must be wavelengths and each row a spectrum. Additional columns are needed to identify the Primary/Setting. For example, 380, 381, …, 780, Primary, Setting. See here for further info. See also cls.load_calibration_file()

  • calibration_wavelengths (sequence of int) – [start, stop, step] of wavelength range, e.g., [380, 781, 1] for 380 to 780 in 1 nm bins. The default is None, in which case the wavelength range is determined from the calibration spds.

  • primary_resolutions (sequence of int) – Resolution depth of primaries, i.e., the number of steps available for specifying the intensity of each primary. This is a list of integers to allow for systems where primaries may have different resolution depths. The number of elements must equal the number of device primaries.

  • primary_colors (sequence of str or rgb) – Sequence of valid color names for the primaries. Must be in matplotlib.colors.cnames. Alternatively, pass a sequence of RGB values.

  • observer (str or pysilsub.observer.Observer) – Colorimetric observer model. The default is “CIE_standard_observer” , in which case defaults to the CIE standard colorimetric observer model (age=32, field_size=10), but can pass a custom observer model.

  • name (str, optional) – Name of the device or stimulation system, e.g., 8-bit BCGAR photostimulator. The default name is Stimulation Device.

  • config (dict, optional) – Additional information from the config file. The default is None.

Return type:

None

classmethod from_json(config_json)

Construct class from preformatted json config file.

See pysilsub.config for further details.

Parameters:

config_json (str) – json file with configuration parameters for StimulationDevice.

Returns:

pysilsub.StimulationDevice

Return type:

class

classmethod from_package_data(example)

Construct class from example package data.

For further details:

show_package_data(verbose=True)
Parameters:

example (str) –

Currently the following options are available:

  • ’STLAB_York’

  • ’STLAB_Oxford’

  • ’BCGAR’

  • ’VirtualSky’

Return type:

StimulationDevice

Example

device = StimulationDevice.from_package_example('BCGAR')

Returns:

pysilsub.StimulationDevice

Return type:

class

Parameters:

example (str) –

classmethod show_package_data(verbose=False)

Show details of example data in the package distribution.

Parameters:

verbose (bool, optional) – Print detailed information if True. The default is False.

Returns:

Available package data

Return type:

list

classmethod load_calibration_file(calibration_fpath)

Load calibration file into pandas DataFrame.

First row must contain column headers Primary and Setting and numbers to describe the wavelength sampling (e.g., Primary, Setting, 380, 381, …, 780). All remaining rows row should contain a spectral measurement and the corresponding values for Primary and Setting to identify the measurement.

Parameters:

calibration_fpath (str) – Path to CSV file with correct format (see above).

Returns:

calibration – DataFrame with Multi-Index.

Return type:

pd.DataFrame

plot_gamut(ax=None, show_1931_horseshoe=True, show_CIE170_2_horseshoe=True, **kwargs)

Plot the gamut of the stimulation device.

Parameters:
  • ax (plt.Axes, optional) – Axes on which to plot. The default is None.

  • show_1931_horseshoe (bool, optional) – Whether to show the CIE1931 chromaticity horseshoe. The default is True.

  • show_CIE170_2_horseshoe (bool, optional) – Whether to show the CIE170_2 chromaticity horseshoe. The default is True.

Returns:

ax

Return type:

matplotlib.axes.Axes

plot_calibration_spds(ax=None, norm=False, **kwargs)

Plot the spectral power distributions for the stimulation device.

Returns:

ax

Return type:

matplotlib.axes.Axes

Parameters:
  • ax (Optional[Axes]) –

  • norm (bool) –

plot_calibration_spds_and_gamut(spd_kwargs=None, gamut_kwargs=None)

Plot calibration SPDs alongside gamut on CIE chromaticity horseshoe.

Returns:

fig – The figure.

Return type:

plt.Figure

Parameters:
  • spd_kwargs (Optional[dict]) –

  • gamut_kwargs (Optional[dict]) –

predict_primary_spd(primary, primary_input, name=0)

Predict output for a single device primary at a given setting.

This is the basis for all predictions.

Parameters:
  • primary (int) – Device primary.

  • primary_input (int or float) – Requested input for device primary. Must be float (>=0.0|<=1.0) or int (>=0|<=max resolution).

  • name (int or str, optional) – A name for the spectrum. The default is 0.

Raises:

ValueError – If requested value of primary_input exceeds resolution.

Returns:

Predicted spd for primary / primary_input.

Return type:

pd.Series

predict_multiprimary_spd(multiprimary_input, name=0, nosum=False)

Predict spectral power distribution for requested primary inputs.

Predict the SPD output of the stimulation device for a given list of primary inputs. Assumes linear summation of primaries.

Parameters:
  • multiprimary_input (list of int or float) – Rquested inputs for the device primaries. List of length self.nprimaries consisting of either float (>=0.0|<=1.0) or int (>=0|<=max resolution).

  • name (int or str, optional) – A name for the spectrum, e.g. ‘Background’. The default is 0.

  • nosum (bool, optional) – Whether to sum the primary components of the spectrum.

Raises:

ValueError – If the number of elements in settings is greater than the number of device primaries. If the elements in settings are not exclusively int or float.

Returns:

Predicted spectra or spectrum for given device settings.

Return type:

pd.DataFrame if nosum=True else pd.Series

calculate_aopic_irradiances()

Calculate aopic irradiances from calibration spds.

Using the CIE026 spectral sensetivities, calculate alpha-opic irradiances (S, M, L, R, I) for every spectrum in self.calibration.

Returns:

Alphaopic irradiances.

Return type:

pd.DataFrame

calculate_lux()

Using the CIE1924 photopic luminosity function, calculate lux for every spectrum in self.calibration.

Returns:

Lux values.

Return type:

pd.DataFrame

predict_multiprimary_aopic(multiprimary_input, name=0)

Predict a-opic irradiances of device for requested primary inputs.

Parameters:
  • multiprimary_input (list of int or float) – Rquested inputs for the device primaries. List of length self.nprimaries consisting of either float (>=0.0|<=1.0) or int (>=0|<=max resolution).

  • name (int or str, optional) – A name for the output, e.g. ‘Background’. The default is 0.

Returns:

aopic – Predicted a-opic irradiances for given device settings.

Return type:

pd.DataFrame

find_settings_xyY(xy, luminance, tolerance=1e-06, plot_solution=False, verbose=True)

Find device settings for a spectrum with requested xyY values.

Parameters:
  • xy (sequence of float) – Requested chromaticity coordinates (xy).

  • luminance (float) – Requested luminance.

  • tolerance (float, optional) – Acceptable precision for result.

  • plot_solution (bool, optional) – Set to True to plot the solution. The default is False.

  • verbose (bool, optional) – Set to True to print status messages. The default is False.

Raises:

ValueError if len(xy) != 2

Returns:

result – The result of the optimisation procedure, with result.x as the settings that will produce the spectrum.

Return type:

OptimizeResult

do_gamma(fit='polynomial', force_origin=False, poly_order=7)

Make a gamma table from reverse polynomial or beta cdf curve fits.

For each primary, calculate the unweigthed sum of the spectral calibration measurements (output) at each setting (input). A reverse curve fit on these data gives the new input values required for linearisation.

Parameters:
  • fit (str, optional) – ‘polynomial’ or ‘beta_cdf’. The default is ‘polynomial’.

  • save_plots_to (str, optional) – Folder to save plots in. The default is None.

  • force_origin (bool) –

  • poly_order (int) –

Return type:

None.

plot_gamma(save_plots_to=None, show_corrected=False)

Plot gamma results for each primary.

Parameters:
  • save_plots_to (str, optional) – Path to folder where plots should be saved. The default is None.

  • show_corrected (bool, optional) – Whether to show gamma corrected predicted values in the plots. The default is False.

Return type:

None.

gamma_lookup(primary, primary_input)

Look up the gamma corrected value for a primary input.

Parameters:
  • primary (int) – Device primary.

  • primary_input (int or float) – Requested input for device primary. Must be float (>=0.0|<=1.0) or int (>=0|<=max resolution).

Returns:

Gamma corrected primary input value.

Return type:

int

gamma_correct(multiprimary_input)

Return the gamma corrected values for multiprimary device input.

Parameters:

multiprimary_input (Sequence of int or float) – Rquested inputs for the device primaries. List of length self.nprimaries consisting of either float (>=0.0|<=1.0) or int (>=0|<=max resolution).

Returns:

Gamma corrected multiprimary input values.

Return type:

list

s2w(settings)

Convert settings to weights.

Parameters:

settings (Sequence of int) – List of length self.nprimaries containing device settings ranging from 0 to max-resolution for each primary.

Returns:

List of primary weights.

Return type:

list of float

w2s(weights)

Convert weights to settings.

Parameters:

weights (Sequence of float) – List of length self.nprimaries containing primary input weights, ranging from 0. to 1., for each primary.

Returns:

List of primary settings.

Return type:

list of int

pysilsub.problems

Definine, solve and visualise silent substitution problems for a given observer and multiprimary stimulation device.

exception pysilsub.problems.SilSubProblemError

Bases: Exception

Generic Python-exception-derived object.

Raised programmatically by SilentSubstitutionProblem methods when arguments are incorrectly specified or when they do not agree with values of other .

class pysilsub.problems.SilentSubstitutionProblem

Bases: StimulationDevice

Class to perform silent substitution with a stimulation device.

The class inherits from pysilsub.device.StimulationDevice and is extended with properties and methods to define and solve a silent substitution problem. After instantiating, set the properties to define a problem and then use the solver methods to find a solution:

import pysilsub

# EXAMPLE: 1
# Using all channels at half-power as the background spectrum,
# use linear algebra to find a solution that gives 20 % S-cone
# contrast while ignoring rods and silencing M-cones, L-cones
# and melanopsin.
ssp = pysilsub.problems.from_package_data('STLAB_York')
ssp.ignore = ['rh']
ssp.target = ['sc']
ssp.silence = ['mc', 'lc', 'mel']
ssp.background = [.5] * ssp.nprimaries
ssp.target_contrast = .2
solution = ssp.linalg_solve()
fig = ssp.plot_ss_result(solution)

# EXAMPLE: 2
# Without specifying a background spectrum, use numerical
# optimisation to find a pair of spectra which maximise
# melanopsin contrast while ignoring rods and silencing the
# cones.
ssp = pysilsub.problems.from_package_data('STLAB_York')
ssp.ignore = ['rh']
ssp.target = ['mel']
ssp.silence = ['sc', 'mc', 'lc']
ssp.background = None
ssp.target_contrast = None
solution = ssp.optim_solve()
fig = ssp.plot_ss_result(solution.x)
__init__(calibration, calibration_wavelengths, primary_resolutions, primary_colors, observer='CIE_standard_observer', name=None, config=None)

Instantiate class with specified parameters.

Parameters:
  • calibration (str or pd.DataFrame) –

    DataFrame or path to CSV file with spectral measurements to characterise the output of the device. Column headers must be wavelengths and each row a spectrum. Additional columns are needed to identify the Primary/Setting. For example, 380, 381, …, 780, Primary, Setting. See here for further info. See also cls.load_calibration_file()

  • calibration_wavelengths (sequence of int) – [start, stop, step] of wavelength range, e.g., [380, 781, 1] for 380 to 780 in 1 nm bins. The default is None, in which case the wavelength range is determined from the calibration spds.

  • primary_resolutions (sequence of int) – Resolution depth of primaries, i.e., the number of steps available for specifying the intensity of each primary. This is a list of integers to allow for systems where primaries may have different resolution depths. The number of elements must equal the number of device primaries.

  • primary_colors (sequence of str or rgb) –

    Sequence of valid color names for the primaries. Must be in matplotlib.colors.cnames. Alternatively, pass a sequence of RGB values.

  • observer (str or pysilsub.observer.Observer, optional) –

  • observer – Colorimetric observer model. The default is “CIE_standard_observer” , in which case defaults to the CIE standard colorimetric observer model (age=32, field_size=10).

  • name (str, optional) – Name of the device or stimulation system, e.g., 8-bit BCGAR photostimulator. The default name is Stimulation Device.

  • config (dict, optional) – Additional information from the config file. The default is None.

Return type:

None

property background

Set a background spectrum for the silent substitution stimulus.

Setting the background property internally conditions the silent substitution problem.

  • linalg_solve(...) only works when a background is specified.

  • optim_solve(...) optimises the background and modulation spectrum if no background is specified, otherwise it only optimises the modulation spectrum.

For example, to use all channels at half power as the background spectrum:

ssp.background = [.5] * ssp.nprimaries
Raises:

SilSubProblemError if requested but not specified.

Returns:

background – Primary inputs of the background spectrum.

Return type:

Sequence of float or int

property bounds: List[Tuple[float, float]]

Define input bounds for each primary.

The bounds property ensures that solutions are within gamut. Bounds should be defined as a list of tuples of length self.nprimaries, where each tuple consists of a min-max pair of floats (>=0.|<=1.) defining the lower and upper bounds for each channel. Bounds are set automatically in the __init__ as follows:

self._bounds = [(0., 1.,)] * self.nprimaries

If, after creating a problem you want to constrain solutions to avoid the lower and upper extremes of the input ranges (for example) you could pass something like:

ssp.bounds = [(.05, .95,)] * ssp.nprimaries

It is also possible to set different bounds for each primary. This may be useful if you want to pin a problematic primary so that its value is constrained during optimisation:

new_bounds = ssp.bounds
new_bounds[4] = (.49, .51,)  # Constrain the 4th primary
ssp.bounds = new_bounds
Raises:

SilSubProblemError if requested but not specified.

Returns:

bounds – Input bounds for each primary.

Return type:

List of float pairs

property ignore: list[str] | list[None]

Photoreceptor(s) to be ignored.

Setting the ignore property internally conditions the silent substitution problem such that the specified photoreceptor(s) will be ignored by the solvers (enabling them to find more contrast on the targeted photoreceptors). For example, one may choose to ignore rods when working in the photopic range (>300 cd/m2) as they are often assumed to be saturated and incapable of signalling at these light levels:

ssp.ignore = ['rh']

One may also choose to ignore both rods and melanopsin:

ssp.ignore = ['rh', 'mel']

Or both rods and the non-functional cone of a dichromat:

ssp.ignore = ['rh', 'lc']

In the event that you don’t want to ignore any photoreceptors, you must still pass:

ssp.ignore = [None]

Setting the ignore property is an essential step for conditioning a silent substitution problem.

Raises:

SilSubProblemError if ignore not specified.

Returns:

ignore – Photoreceptors to be ignored.

Return type:

[None] or list of str

property silence: list[str]

Photoreceptor(s) to be (nominally) silenced.

Setting the silence property internally conditions the silent substitution problem such that contrast on the target photoreceptors will be minimized. For example:

ssp.silence = ['sc', 'mc', 'lc']

Would aim to silence the cone photoreceptors.

Setting the silence property is an essential step for conditioning a silent substitution problem.

Raises:

SilSubProblemError if requested but not specified.

Returns:

silence – Photoreceptor(s) to be silenced.

Return type:

list of str

property target: list[str]

Photoreceptor(s) to target.

Setting the target property internally conditions the silent substitution problem so the solvers know which photoreceptor(s) should be targeted with contrast. For example, to target melanopsin:

ssp.target = ['mel']

It is also possible to target multiple photoreceptors:

ssp.target = ['sc', 'mc', 'lc']

Setting the target property is an essential step for conditioning a silent substitution problem.

Raises:

SilSubProblemError if requested but not specified.

Returns:

target – Photoreceptors to target.

Return type:

list of str

property target_contrast: numpy.ndarray[Any, numpy.dtype[numpy._typing._generic_alias.ScalarType]] | str

Target contrast to aim for on targeted photoreceptor(s).

Setting the target_contrast property conditions the silent substitution problem so the solvers know what target contrast to aim for:

ssp.target_contrast = .5

This would aim for 50% contrast on the targeted photoreceptor(s). If modulating multiple photoreceptors in different directions and / or with different contrasts, target_contrast should be a sequence of values (if you specify multiple receptors to targeted and pass a float then it is assumed target_contrast should be the same for each photoreceptor):

ssp.ignore = ['rh']
ssp.silence = ['sc', 'mel']
ssp.target = ['mc', 'lc']
ssp.target_contrast = [-.5, .5]

The above example defines a problem that will ignore rods, silence S-cones and melanopsin, and aim for 50% negative contrast on M-cones and 50% positive contrast on L-cones, relative to the background spectrum.

Note

Setting target_contrast is required for linalg_solve().

When using .optim_solve(), target_contrast can be set to ‘max’ or ‘min’, in which case the optimizer will aim to maximize or minimize contrast on the targeted photoreceptors.

Raises:

SilSubProblemError if requested but not specified.

Returns:

target_contrast – Contrast to aim for on photoreceptor(s) being targeted.

Return type:

NDArray or str

print_problem()

Print the current problem definition.

Return type:

None

initial_guess_x0()

Return an initial guess of the primary inputs for optimization.

Returns:

Initial guess for optimization.

Return type:

NDArray

aopic_calculator(x0)

Calculate alphaopic irradiances for candidate solution.

Parameters:

x0 (Sequence of float) – Primary input weights.

Returns:

  • bg_aopic (pd.Series) – Alphaopic irradiances for the background spectrum.

  • mod_aopic (pd.Series) – Alphaopic irradiances for the modulation spectrum.

Return type:

tuple[pandas.core.series.Series, pandas.core.series.Series]

print_photoreceptor_contrasts(x0, contrast_statistic='simple')

Print photoreceptor contrasts for a given solution.

Parameters:
  • x0 (Sequence[float]) –

  • contrast_statistic (str) –

get_photoreceptor_contrasts(x0, contrast_statistic='simple')

Return contrasts for ignored, silenced and targeted photoreceptors.

Parameters:
  • x0 (Sequence of float) – Primary input weights.

  • contrast_statistic (str) – The contrast statistic to return, either ‘simple’, ‘weber’, or ‘michelson’.

Returns:

Photoreceptor contrasts.

Return type:

pd.Series

objective_function(x0)

Calculate contrast error on targeted photoreceptor(s).

This happens in accordance with the problem definition.

Parameters:

x0 (Sequence of float) – Primary input weights.

Returns:

Contrast error on targeted photoreceptor(s).

Return type:

float

silencing_constraint(x0)

Calculate contrast error for silenced photoreceptor(s).

Parameters:

x0 (Sequence of float) – Primary input weights.

Returns:

Contrast error on silenced photoreceptor(s).

Return type:

float

optim_solve(x0=None, global_search=False, **kwargs)

Use optimisation to solve the current silent substitution problem.

This method is good for finding maximum available contrast. It uses SciPy’s minimize function with the SLSQP (sequential quadratic least squares programming) solver.

If self.background has not been set, both the background and the modulation spectrum are optimised.

If self.target_contrast has been set to np.inf or -np.inf, the optimser will aim to maximise or minimize contrast, respectively, otherwise it will aim to converge on the target contrast.

Parameters:
  • global_search (bool, optional) – Whether to perform a global search with scipy’s basinhopping algorithm.

  • x0 (Optional[Sequence[float]]) –

Returns:

result – The result of the optimization.

Return type:

scipy.optimize.OptimizeResult

linalg_solve()

Use linear algebra to solve the current silent substitution problem.

Inverse method is applied when the matrix is square (i.e., when the number of primaries is equal to the number of photoreceptors), alternatively the Moore-Penrose pseudo-inverse.

Raises:
  • SilSubProblemError – If self.background or self.target_contrast are not specified.

  • ValueError – If the solution is outside self.bounds.

Returns:

solution – Primary weights for the modulation spectrum.

Return type:

pd.Series

get_solution_spds(solution)

Get predicted spds for solution.

Parameters:

solution (array_like) – The solution returned by one of the solvers.

Returns:

  • bg_spd (pd.Series) – Chromaticity coordinates of background spectrum.

  • mod_spd (pd.Series) – Chromaticity coordinates of modulation spectrum.

plot_solution_spds(solution, ax=None, **kwargs)

Plot the solution spds.

Parameters:
  • solution (array_like) – The solution returned by one of the solvers.

  • ax (plt.Axes, optional) – Axes on which to plot. The default is None.

  • **kwargs (dict) – Passed to pd.Series.plot().

Returns:

ax – Axes on which the data are plotted.

Return type:

plt.Axes

get_solution_xy(solution)

Get xy chromaticity coordinates for solution spectra.

Parameters:

solution (array_like) – The solution returned by one of the solvers.

Returns:

  • bg_xy (TYPE) – Chromaticity coordinates of background spectrum.

  • mod_xy (TYPE) – Chromaticity coordinates of modulation spectrum.

plot_solution_xy(solution, ax=None, **kwargs)

Plot solution chromaticity coordinates on CIE horseshoe.

Parameters:
  • solution (array_like) – The solution returned by one of the solvers.

  • ax (plt.Axes, optional) – Axes on which to plot. The default is None.

  • **kwargs (dict) – Passed to pd.Series.scatter().

Returns:

ax – Axes on which the data are plotted.

Return type:

plt.Axes

plot_solution_aopic(solution, ax=None, **kwargs)

Plot barchart of alphaopic irradiances .

Parameters:
  • solution (array_like) – The solution returned by one of the solvers.

  • ax (plt.Axes, optional) – Axes on which to plot. The default is None.

  • **kwargs (dict) – Passed to DataFrame.bar.plot().

Returns:

ax – Axes on which the data are plotted.

Return type:

plt.Axes

plot_solution(solution)

Plot solution spds, xy chromaticities and alphaopic irradiances.

Parameters:

solution (array_like) – The solution returned by one of the solvers.

Returns:

fig

Return type:

plt.Figure

print_solution(solution)

Print device input settings for background and modulation.

Parameters:

solution (array_like) – The solution returned by one of the solvers.

Return type:

None.

make_contrast_modulation(frequency, sampling_frequency, target_contrasts, phase=0, duration=1)

Make a sinusoidal contrast modulation.

Parameters:
  • frequency (int | float) – Modulation frequency in Hz.

  • sampling_frequency (int) – Sampling frequency of the modulation. This should not exceed the temporal resolution (spectral switching time) of the stimulation device.

  • target_contrast (list(float)) – Peak contrast of the modulation for targeted photoreceptor(s).

  • phase (int | float, optional) – Phase offset. The default is 0. Use np.pi

  • duration (int | float, optional) – Duration of the modulation. The default is 1.

  • target_contrasts (list[float]) –

Returns:

solutions – Solution for each time point in the modulation.

Return type:

list

plot_contrast_modulation(solutions, ax=None, **kwargs)

Plot photoreceptor contrast over time for a list of solutions.

Parameters:
  • solutions (list) – List of solutions returned by one of the solvers (one for each timepoint in the modulation).

  • ax (Optional[Axes]) –

Returns:

fig – The plot.

Return type:

plt.Figure

animate_solutions(solutions, save_to=None)

Something here.

Parameters:
  • solutions (TYPE) – DESCRIPTION.

  • save_to (TYPE, optional) – DESCRIPTION. The default is None.

Returns:

DESCRIPTION.

Return type:

TYPE

pysilsub.colorfuncs

Tools for navigating between colorspaces.

Many have been translated from MATLAB’s Psychtoolbox/PsychColormetric

pysilsub.colorfuncs.xyY_to_XYZ(xyY)

Compute tristimulus values from chromaticity and luminance.

Parameters:

xyY (Sequence of float) – Array of values representing chromaticity (xy) and luminance (Y).

Returns:

XYZ – Tristimulus values.

Return type:

pd.Series

pysilsub.colorfuncs.XYZ_to_xyY(XYZ)

Compute chromaticity and luminance from tristimulus values.

Parameters:

XYZ (Sequence of float) – Tristimulus values.

Returns:

xyY – Chromaticity coordinates (xy) and luminance (Y).

Return type:

pd.Series

pysilsub.colorfuncs.XYZ_to_LMS(XYZ)

Compute cone excitation (LMS) coordinates from tristimulus values.

Parameters:

XYZ (Sequence of float) – Tristimulus values.

Returns:

LMS coordinates.

Return type:

pd.Series

pysilsub.colorfuncs.LMS_to_XYZ(LMS)

Compute tristimulus values from cone excitation (LMS) coordinates.

Parameters:

LMS (Sequence of float) – LMS (cone excitation) coordinates.

Returns:

Tristimulus values.

Return type:

pd.Series

pysilsub.colorfuncs.xyY_to_LMS(xyY)

Compute cone excitation (LMS) coordinates from chromaticity and luminance.

Parameters:

xyY (Sequence of float) – Array of values representing chromaticity (xy) and luminance (Y).

Returns:

LMS coordinates.

Return type:

pd.Series

pysilsub.colorfuncs.LMS_to_xyY(LMS)

Compute xyY coordinates from LMS values.

Parameters:

LMS (Sequence of float) – LMS (cone excitation) coordinates.

Returns:

Array of values representing chromaticity (xy) and luminance (Y).

Return type:

pd.Series

pysilsub.colorfuncs.spd_to_XYZ(spd, binwidth=1)

Convert a spectrum to an XYZ point.

Parameters:
  • spd (np.array or pd.Series) – Spectral power distribution in calibrated units..

  • binwidth (int, optional) – Bin width of the spd in nanometers. The default is 1.

Returns:

Tristimulus values.

Return type:

pd.Series

pysilsub.colorfuncs.spd_to_lux(spd, binwidth=1)

Convert a spectrum to luminance (lux).

Parameters:
  • spd (np.array or pd.Series) – Spectral power distribution in calibrated units.

  • binwidth (int, optional) – Bin width of the spd in nanometers. The default is 1.

Returns:

Luminance.

Return type:

float

pysilsub.colorfuncs.spd_to_xyY(spd, binwidth=1)

Compute xyY coordinates from spectral power distribution.

Parameters:
  • spd (np.array or pd.Series) – Spectral power distribution in calibrated units.

  • binwidth (int) –

Returns:

xyY.

Return type:

pd.Series

pysilsub.colorfuncs.xy_luminance_to_xyY(xy, luminance)

Return xyY from xy and luminance.

Parameters:
  • xy (Sequence of float) – xy chromaticity coordinates.

  • luminance (float) – Luminance in lux or cd/m2.

Returns:

xyY.

Return type:

pd.Series

pysilsub.CIE

Convenience functions for accessing CIE standards.

Obtained from http://www.cvrl.org/

pysilsub.CIE.get_CIE_2006_10_deg_CMF(binwidth=1)

Get the CIE 2006 XYZ 10-deg physiologically relevant color matching functions.

Parameters:

binwidth (int) – Desired width of the wavelength bins in nanometers. The default is 1.

Returns:

cmf – CIE 2006 XYZ 10-deg physiologically relevant CMFs.

Return type:

pd.DataFrame

pysilsub.CIE.get_CIE_1931_2_deg_CMF(binwidth=1)

Get the CIE 1931 XYZ 2-deg color matching functions.

Parameters:

binwidth (int) – Desired width of the wavelength bins in nanometers. The default is 1.

Returns:

cmf – CIE 1931 XYZ 2-deg CMFs.

Return type:

pd.DataFrame

pysilsub.CIE.get_CIES026_action_spectra(binwidth=1)

Get CIES026 photoreceptor action spectra.

This table contains data for the photoreceptor action spectra of a standard 32-year-old observer and a 10-degree field size, for wavelengths from 380 nm to 780 nm. Values are zero where data are presently unavailable at those wavelengths. The rhodopic action spectrum values are reproduced from ISO 23539/CIE S 010 without modifications. The S-cone opic action spectrum is provided for 390 nm to 615 nm, and the M- and L-cone-opic action spectra are provided for 390 nm to 780 nm, all reproduced from (CIE, 2006). By definition, the S-, M- and L-cone-opic action spectra take a maximum value of exactly 1 at 447.9 nm, 541.3 nm and 568.6 nm respectively. The melanopic action spectrum is reproduced from the underlying model in the Toolbox from (CIE, 2015), interpolated (cubic spline) from 5 nm to 1 nm resolution, and rounded to the nearest six significant figures for consistency with the cone fundamentals in (CIE, 2006).

Note

Further information on the CIES026 standard is available here.

The tabulated action spectra can be downloaded in excel format from here.

Parameters:

binwidth (int) – Desired width of the wavelength bins in nanometers. The default is 1.

Returns:

action_spectra – CIES026 action spectra for sc, mc, lc, rh, and mel.

Return type:

pd.DataFrame

pysilsub.CIE.get_CIE_1924_photopic_vl(binwidth=1)

Get the CIE1924 photopic luminosity function.

Parameters:

binwidth (int) – Desired width of the wavelength bins in nanometers. The default is 1.

Returns:

vl – The CIE1924 photopic luminosity function.

Return type:

pd.Series

pysilsub.CIE.get_matrix_10_deg_LMStoXYZ()

Get LMS to XYZ conversion matrix for 10 degree field size.

Returns:

The matrix.

Return type:

np.ndarray

pysilsub.CIE.get_matrix_2_deg_LMStoXYZ()

Get LMS to XYZ transformation matrix for 2 degree field size.

Returns:

The matrix.

Return type:

np.ndarray

pysilsub.CIE.get_CIE170_2_chromaticity_coordinates(line_of_purples=True)

Get the CIE170_2 chromaticity coordinates.

Parameters:

line_of_purples (bool) – Whether to connect the line of purples by repeating the first row at the end. The default is True.

Returns:

xyz – CIE170_2 chromaticity coordinates.

Return type:

pd.DataFrame

pysilsub.CIE.get_CIEPO06_optical_density()

Optical density of lens and other ocular media.

Function D_ocul for an average 32-yr-old observer (pupil diameter < 3mm) (Stockman, Sharpe and Fach (1999).

D_ocul can be separated into two components: D_ocul_1 represents portion affected by aging after age 20, and D_ocul_2 represents portion stable after age 20. (After Pokorny, Smith and Lutze, 1987).

The optical density of the lens of an average observer between the ages of 20 and 60 yr is determined by D_ocul = D_ocul_1 [1 + 0.02(A-32)] + D_ocul_2

For an average observer over the age of 60, D_ocul = D_ocul_1 [1.56 + 0.0667(A-60)] + D_ocul_2 where A is the observer’s age.

D_ocul_2 is the Stockman and Sharpe (2000) tabulation of lens density scaled to represent a 32-yr-old observer (the average age of the Stiles and Burch observers) with a small pupil (< 3 mm). To estimate the lens density function for a completely open pupil (> 7 mm), multiply the tabulated values by 0.86207.

Returns:

CIEPO06_optical_density – Optical density as a function of wavelength.

Return type:

pd.DataFrame

pysilsub.CIE.estimate_CIEPO06_lens_density(age)

Estimate lens density spectrum for observer using CIEPO06.

Parameters:

age (int) – Observer age.

Returns:

correct_lomd – DESCRIPTION.

Return type:

TYPE

pysilsub.CIE.get_CIE_203_2012_lens_density(age, wls)

Lens density function from CIE 203:2012 (used for melanopsin).

Parameters:
  • age (int) – Age of observer.

  • wls (array_like) – Wavelength range.

Returns:

Estimated lens density.

Return type:

np.array

pysilsub.CIE.get_CIEPO06_macula_density()

Optical density D_macula of the macular pigment.

Return type:

Series

pysilsub.CIE.get_CIE_A_lms()

Photopigment relative quantal absorbance spectra in log units.

Photopigment optical density curves calculated from the 2° (or 10°) cone spectral sensitivities of Stockman and Sharpe (2000) at 0.1, 1 or 5 nm steps. The 0.1 and 1 nm functions were obtained by the interpolation of the 5 nm functions using a cubic spline. The functions are normalized to peak at unity at the nearest 0.1 nm step. In making these calculations, a macular pigment density of 0.35 at peak, a lens density of 1.76 at 400 nm, and peak photopigment optical densities of 0.50 (for L and M) and 0.40 (for S) were assumed. The lens and macular pigment density spectra were those of Stockman, Sharpe and Fach (1999).

Stockman, A., Sharpe, L. T., & Fach, C. C. (1999). The spectral sensitivity of the human short-wavelength cones. Vision Research, 39, 2901-2927.

Stockman, A., & Sharpe, L. T. (2000). Spectral sensitivities of the middle- and long-wavelength sensitive cones derived from measurements in observers of known genotype. Vision Research, 40, 1711-1737.

Return type:

DataFrame

pysilsub.preceps

Convenience functions for accessing prereceptoral filter functions.

pysilsub.preceps.get_hemoglobin_absorptances()

Obtain Prahl’s estimates of hemoglobin absorptance spectra.

These are tabulated data included in the software. They are returned as molar extinction coefficients (cm-1/M). The wavelength spacing is 250-1000 in 2 nm bins.

T_oxy is the molar extinction of oxyhemoglobin.

T_deoxy is the molar extinction of deoxyhemoglobin.

Note

Link to source of tabulated data

See here for further information.

Parameters:

None

Returns:

data – Hemoglobin data.

Return type:

pd.DataFrame

pysilsub.preceps.get_retinal_hemoglobin_transmittance(wavelengths=[380, 781, 1], vessel_oxygenation_fraction=0.85, vessel_overall_thickness_um=5)

Get the hemoglobin transmittance spectrum for retinal vasculature.

Return the hemoglobin transmittance spectrum, given a fraction of oxy/deoxy hemoglobin and an overall thickness of the blood layer.

Note

64500 is the gram molecular weight of hemoglobin.

150 is the grams of Hgb per litre of whole blood.

Parameters:
  • wavelengths (Sequence, optional) – Start, stop, step of desired wavelengths. The default is [380, 781, 1].

  • vessel_oxygenation_fraction (float, optional) – Estimate of the fraction of oxygenated blood in vessels. The default is .85.

  • vessel_overall_thickness (int, optional) – Estimate of the overal thickness of vessels in uM. The default is 5.

  • vessel_overall_thickness_um (int) –

Returns:

hgb_transmittance – Hemoglobin transmittance spectra (oxy/deoxy).

Return type:

pd.DataFrame

pysilsub.preceps.get_melanin_transmittance(wavelengths=[380, 781, 1])

Return melanin transmittance spectrum.

The skin melanin absorption coefficient can be described by the following formula (eq. 2 in Bierman, Figuiero & Rea, 2011; and http://omlc.org/spectra/melanin/mua.html)

Parameters:

wavelengths (Sequence, optional) – Start, stop, step of desired wavelengths. The default is [380, 781, 1].

Note

This code was translated from the Silent Substution Toolbox for MATLAB. See here for more information.

Returns:

melanin_transmittance – Melanin transmittance spectrum.

Return type:

pd.Series

pysilsub.preceps.get_bilirubin_absorption()

Return optical absorption spectrum of Bilirubin in chloroform.

Units are Molar Extinction (cm-1/M)

Note

These tabulated data are from the Silent Substution Toolbox for MATLAB. See here for more information.

Returns:

data – Bilirubin absorption spectrum.

Return type:

pd.Series

pysilsub.preceps.get_bilirubin_transmittance(wavelengths=[380, 781, 1])

Return bilirubin transmittance spectrum.

Parameters:

wavelengths (Sequence, optional) – Start, stop, step of desired wavelengths. The default is [380, 781, 1].

Note

This function was translated from the Silent Substution Toolbox for MATLAB. See here for more information.

Returns:

bilirubin_transmittance – Bilirubin transmittance spectrum.

Return type:

pd.Series

pysilsub.preceps.get_eyelid_hemoglobin_transmittance(wavelengths=[380, 781, 1])

Get the hemoglobin transmittance spectrum for eyelid vasculature.

Parameters:

wavelengths (Sequence, optional) – Start, stop, step of desired wavelengths. The default is [380, 781, 1].

Returns:

hgb_transmittance – Human eyelid Hgb transmittance spectra (oxy/deoxy).

Return type:

pd.DataFrame

pysilsub.preceps.get_eyelid_transmittance(wavelengths=[380, 781, 1])

Return transmittance spectrum of human eyelid.

Parameters:

wavelengths (Sequence, optional) – Start, stop, step of desired wavelengths. The default is [380, 781, 1].

Returns:

eyelid_transmittance – Transmittance spectrum of human eyelid.

Return type:

pd.Series

pysilsub.preceps.get_lens_density_spectra(binwidth=1, asdf=True, trim_visible=False)

Get lens density spectra.

See the following refs for further information:

Stiles, W. S., & Burch, J. M. (1959). NPL colour-matching investigation:

Final report (1958). Optica Acta, 6, 1-26.

Stockman, A., Sharpe, L. T., & Fach, C. C. (1999). The spectral sensitivity

of the human short-wavelength cones. Vision Research, 39, 2901-2927.

Stockman, A., & Sharpe, L. T. (2000). Spectral sensitivities of the middle-

and long-wavelength sensitive cones derived from measurements in observers of known genotype. Vision Research, 40, 1711-1737.

van Norren, D. & Vos J.J. (1974) Spectral transmission of the human ocular

media Vision Research, 14, 1237-1244.

Parameters:
  • asdf (bool, optional) – Whether to return the results as a pandas DataFrame. The default is True.

  • binwidth (int, optional) – Width of the wavelength bins in nanometers (must be 1 or 5). The default is 1.

  • trim_visible (bool, optional) – Whether to trim the CMFs to 380-780 nm. The default is True.

Returns:

density – Lens optical density as a function of wavelength.

Return type:

numpy.ndarray or pandas.DataFrame

pysilsub.preceps.get_macula_pigment_density_spectra(binwidth=1, asdf=True, trim_visible=False)

Get macula pigment density spectra.

See the following refs for further information:

Bone, R. A., Landrum, J. T., & Cains, A. (1992). Optical density spectra of

the macular pigment in vivo and in vitro. Vision Research, 32, 105-110.

Stockman, A., Sharpe, L. T., & Fach, C. C. (1999). The spectral sensitivity

of the human short-wavelength cones. Vision Research, 39, 2901-2927.

Parameters:
  • asdf (bool, optional) – Whether to return the results as a pandas DataFrame. The default is False.

  • binwidth (int, optional) – Width of the wavelength bins in nanometers (must be 1 or 5). The default is 1.

  • trim_visible (bool, optional) – Whether to trim the CMFs to 380-780 nm. The default is True.

Returns:

density – Macula pigment optical density as a function of wavelength.

Return type:

numpy.ndarray or pandas.DataFrame

pysilsub.waves

Convenience functions for accessing prereceptoral filter functions.

pysilsub.waves.make_stimulus_waveform(frequency, sampling_frequency, phase=0, duration=1)

Make sinusoidal waveform.

Can be used as a contrast template for silent substitution contrast modulations.

Parameters:
  • frequency (int or float) – Temporal frequency of the sinusoid.

  • sampling_frequency (int) – Sampling frequency of the modulation. This should not exceed the temporal resolution (spectral switching time) of the stimulation device.

  • phase (float, optional) – Phase offset in radians. The default is 0, which gives a sine wave.

  • duration (int or flaot, optional) – Duration of the modulation in seconds. The default is 1, becasuse it is easy to repeat a sinusoidal modulation multiple times and add a new timebase.

Returns:

Sinusoidal waveform with time index.

Return type:

pd.Series

Tables and indices