Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/sphinx/source/whatsnew/v0.16.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ Bug fixes
* Document the URL default :py:func:`pvlib.iotools.get_acis_station_data` actually
uses. Its docstring named the GridData endpoint; should be StnData.
(:pull:`2950`)
* :py:func:`pvlib.spectrum.qe_to_sr` and :py:func:`pvlib.spectrum.sr_to_qe`
now apply wavelength along the rows of a DataFrame input, instead of
across its columns. The docstrings now state the accepted input shapes.
(:issue:`2970`, :ghuser:`Beehtrix`)

Enhancements
~~~~~~~~~~~~
Expand Down
59 changes: 47 additions & 12 deletions pvlib/spectrum/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,27 @@
)


def _positional(wavelength):
# Drop any labels so that pandas does not align on the index.
return wavelength if np.ndim(wavelength) == 0 else np.asarray(wavelength)


def _multiply_along_wavelength(values, wavelength):
# A DataFrame holds one spectrum per column, so wavelength runs along the
# rows. Plain ``*`` would align a 1-D operand with the columns instead.
# Wavelengths are used by position: a labeled Series is not aligned to
# the index of the DataFrame.
if isinstance(values, pd.DataFrame):
return values.mul(_positional(wavelength), axis=0)
return values * wavelength


def _divide_along_wavelength(values, wavelength):
if isinstance(values, pd.DataFrame):
return values.div(_positional(wavelength), axis=0)
return values / wavelength


def get_example_spectral_response(wavelength=None):
'''
Generate a generic smooth spectral response (SR) for tests and experiments.
Expand Down Expand Up @@ -95,12 +116,20 @@ def sr_to_qe(sr, wavelength=None, normalize=False):

Parameters
----------
sr : numeric, pandas.Series or pandas.DataFrame
sr : scalar, numpy.ndarray, pandas.Series or pandas.DataFrame
Spectral response, [A/W].
Index must be the wavelength in nanometers, [nm].
If pandas subtype and ``wavelength`` is not provided, index must be
the wavelength in nanometers, [nm].
A ``DataFrame`` holds one spectrum per column, with wavelengths along
the rows. A 2D ``numpy.ndarray`` holds one spectrum per row, with
wavelengths along the last axis.

wavelength : numeric, optional
wavelength : scalar, 1D array-like, optional
Points where spectral response is measured, in nanometers, [nm].
Must be a scalar or have one value per wavelength of ``sr``: the
length of the last axis for a ``numpy.ndarray`` or of the rows for a
``DataFrame``. Values are matched to ``DataFrame`` rows by position,
not by index label, even if ``wavelength`` is a ``pandas.Series``.

normalize : bool, default False
If True, the quantum efficiency is normalized so that the maximum value
Expand All @@ -110,7 +139,7 @@ def sr_to_qe(sr, wavelength=None, normalize=False):

Returns
-------
quantum_efficiency : numeric, same type as ``sr``
quantum_efficiency : same type as ``sr``
Quantum efficiency, in the interval [0, 1].

Notes
Expand Down Expand Up @@ -168,8 +197,7 @@ def sr_to_qe(sr, wavelength=None, normalize=False):
+ " or 'wavelength' must be provided"
)
quantum_efficiency = (
sr
/ wavelength
_divide_along_wavelength(sr, wavelength)
* _PLANCK_BY_LIGHT_SPEED_OVER_ELEMENTAL_CHARGE_BY_BILLION
)

Expand All @@ -194,12 +222,20 @@ def qe_to_sr(qe, wavelength=None, normalize=False):

Parameters
----------
qe : numeric, pandas.Series or pandas.DataFrame
qe : scalar, numpy.ndarray, pandas.Series or pandas.DataFrame
Quantum efficiency.
If pandas subtype, index must be the wavelength in nanometers, [nm].
If pandas subtype and ``wavelength`` is not provided, index must be
the wavelength in nanometers, [nm].
A ``DataFrame`` holds one spectrum per column, with wavelengths along
the rows. A 2D ``numpy.ndarray`` holds one spectrum per row, with
wavelengths along the last axis.

wavelength : numeric, optional
wavelength : scalar, 1D array-like, optional
Points where quantum efficiency is measured, in nanometers, [nm].
Must be a scalar or have one value per wavelength of ``qe``: the
length of the last axis for a ``numpy.ndarray`` or of the rows for a
``DataFrame``. Values are matched to ``DataFrame`` rows by position,
not by index label, even if ``wavelength`` is a ``pandas.Series``.

normalize : bool, default False
If True, the spectral response is normalized so that the maximum value
Expand All @@ -209,7 +245,7 @@ def qe_to_sr(qe, wavelength=None, normalize=False):

Returns
-------
spectral_response : numeric, same type as ``qe``
spectral_response : same type as ``qe``
Spectral response, [A/W].

Notes
Expand Down Expand Up @@ -267,8 +303,7 @@ def qe_to_sr(qe, wavelength=None, normalize=False):
+ " or 'wavelength' must be provided"
)
spectral_responsivity = (
qe
* wavelength
_multiply_along_wavelength(qe, wavelength)
/ _PLANCK_BY_LIGHT_SPEED_OVER_ELEMENTAL_CHARGE_BY_BILLION
)

Expand Down
72 changes: 72 additions & 0 deletions tests/spectrum/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,75 @@ def test_qe_and_sr_reciprocal_conversion(sr_and_eqe_fixture):
assert_allclose(sr, sr_and_eqe_fixture["spectral_response"])
qe = spectrum.sr_to_qe(sr)
assert_allclose(qe, sr_and_eqe_fixture["quantum_efficiency"])


@pytest.mark.parametrize("func, inp, out", [
(spectrum.qe_to_sr, "quantum_efficiency", "spectral_response"),
(spectrum.sr_to_qe, "spectral_response", "quantum_efficiency"),
])
def test_conversion_dataframe_wavelength_along_rows(
sr_and_eqe_fixture, func, inp, out
):
# GH 2970: DataFrame columns are spectra, wavelengths run along the rows
fx = sr_and_eqe_fixture
# identical columns, square table (as many columns as rows)
n = 2
df = pd.DataFrame(
{"A": fx[inp].iloc[:n], "B": fx[inp].iloc[:n]}
)
result = func(df)
expected = fx[out].iloc[:n]
assert_allclose(result["A"], expected)
assert_allclose(result["B"], expected)
# rectangular table: more wavelengths than columns
df = pd.DataFrame({"A": fx[inp], "B": fx[inp] * 0.5})
result = func(df)
pd.testing.assert_series_equal(
result["A"], func(fx[inp]), check_names=False
)
pd.testing.assert_series_equal(
result["B"], func(fx[inp] * 0.5), check_names=False
)
assert list(result.columns) == ["A", "B"]
# explicit wavelength is also applied along the rows
result = func(df, fx.index.values)
pd.testing.assert_frame_equal(result, func(df))
# normalization is per column
result = func(df, normalize=True)
assert_allclose(result.max(), [1.0, 1.0])


@pytest.mark.parametrize("func", [spectrum.qe_to_sr, spectrum.sr_to_qe])
def test_conversion_dataframe_series_wavelength_is_positional(func):
# the labels of a Series wavelength are ignored, not aligned to the rows
df = pd.DataFrame({"A": [0.8, 0.8], "B": [0.4, 0.4]}, index=[500, 750])
expected = func(df, np.array([500, 750]))
for labels in ([0, 1], [750, 500], [10, 20]):
wl = pd.Series([500, 750], index=labels)
pd.testing.assert_frame_equal(func(df, wl), expected)
assert not expected.isna().any().any()


def test_qe_to_sr_dataframe_issue_2970_example():
qe = pd.DataFrame({"A": [0.8, 0.8], "B": [0.8, 0.8]}, index=[500, 750])
expected = pd.DataFrame(
{"A": [0.322622, 0.483933], "B": [0.322622, 0.483933]},
index=[500, 750],
)
pd.testing.assert_frame_equal(
spectrum.qe_to_sr(qe), expected, atol=1e-6, rtol=0
)
assert_allclose(spectrum.sr_to_qe(spectrum.qe_to_sr(qe)), qe)


@pytest.mark.parametrize("func", [spectrum.qe_to_sr, spectrum.sr_to_qe])
def test_conversion_scalar_and_2d_array(func):
wl = np.array([500, 750])
# scalar value and scalar wavelength
assert_allclose(func(0.8, 500), func(np.array([0.8]), wl[:1])[0])
# 2D numpy array: one spectrum per row, wavelength along the last axis
arr = np.array([[0.8, 0.8], [0.4, 0.4], [0.2, 0.2]])
result = func(arr, wl)
assert result.shape == arr.shape
for row, res in zip(arr, result):
assert_allclose(res, func(row, wl))