Skip to content
2 changes: 2 additions & 0 deletions docs/sphinx/source/reference/pv_modeling/inverter.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,5 @@ Functions for fitting inverter models
:toctree: ../generated/

inverter.fit_sandia
inverter.extract_inverter_characteristics
inverter.ond_to_sandia_inv
12 changes: 12 additions & 0 deletions docs/sphinx/source/whatsnew/v0.16.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,24 @@ 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.iotools.read_panond` now detects the encoding of the file
when ``encoding`` is not specified: UTF-8 if the file starts with a byte
order mark or is valid UTF-8, otherwise Windows-1252. Previously the
platform's default encoding was used, so the result depended on the
operating system's locale. (:pull:`2959`)

Enhancements
~~~~~~~~~~~~
* Add ``pandas==3.1.0`` support. (:pull:`2924`)
* Add ``dataset`` parameter to :py:func:`~pvlib.iotools.get_era5`
allowing for choosing between ERA5 and ERA5-Land datasets.
(:pull:`2780`)
* Add :py:func:`pvlib.inverter.ond_to_sandia_inv` to determine parameters for
:py:func:`pvlib.inverter.sandia` from the content of a PVsyst OND file, and
:py:func:`pvlib.inverter.extract_inverter_characteristics` to extract the
efficiency curves and ratings from that content. A ``ValueError`` naming the
missing OND keys is raised when the file lacks required data.
Based on work by :ghuser:`cwhanse`. (:pull:`1888`, :pull:`2959`)

Documentation
~~~~~~~~~~~~~
Expand Down Expand Up @@ -84,3 +95,4 @@ Contributors
* :ghuser:`xiajiahang`
* Jakub Krasuski (:ghuser:`Blizzeq`)
* Dylan Pulver (:ghuser:`dylanpulver`)
* :ghuser:`dihannahdi`
147 changes: 147 additions & 0 deletions pvlib/inverter.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,3 +551,150 @@ def extract_c(x_d, add):
# prepare dict and return
return {'Paco': p_ac_0, 'Pdco': p_dc0, 'Vdco': v_nom, 'Pso': p_s0,
'C0': c0, 'C1': c1, 'C2': c2, 'C3': c3, 'Pnt': p_nt}


def extract_inverter_characteristics(content):
"""
Extract the efficiency curves and ratings needed to fit an inverter
model from the content of a PVsyst OND file.

The returned values are those required by :py:func:`fit_sandia`, and can
be used as input to other inverter model fitting procedures.

Parameters
----------
content : dict
OND file content, i.e., the ``'PVObject_'`` entry of the nested dict
returned by :py:func:`pvlib.iotools.read_panond`.

Returns
-------
dict
A dict with the following keys:

* ``ac_power`` : numpy.ndarray - AC power output at each data point
[W].
* ``dc_power`` : numpy.ndarray - DC power input at each data point
[W].
* ``dc_voltage`` : numpy.ndarray - DC input voltage at each data point
[V].
* ``dc_voltage_level`` : numpy.ndarray - DC input voltage level at
each data point, one of ``'Vmin'``, ``'Vnom'`` or ``'Vmax'``.
* ``p_ac_0`` : float - Rated AC power of the inverter [W], from
``PNomConv``.
* ``p_nt`` : float - Night tare, i.e., power consumed by the inverter
when it is not delivering AC power [W], from ``Night_Loss``.

Raises
------
ValueError
If the content lacks data that is required, e.g., night-time
consumption or the efficiency curves at the three DC voltage levels.
The message names the missing OND keys. No default values are
substituted for missing data.

See Also
--------
pvlib.inverter.ond_to_sandia_inv
pvlib.inverter.fit_sandia
pvlib.iotools.read_panond

Notes
-----
Many OND files do not contain all of the required data.
"""
missing = []

def get(*keys):
node = content
for i, key in enumerate(keys):
if not isinstance(node, dict) or node.get(key) is None:
missing.append('.'.join(keys[:i + 1]))
return None
node = node[key]
return node

unit = get('Converter', 'UnitAffEnum')
if unit is not None and unit not in ('kW', 'W'):
raise ValueError("Unsupported power unit in OND key "
f"'Converter.UnitAffEnum': {unit!r}")
p_ac_0 = get('Converter', 'PNomConv')
if p_ac_0 is not None and unit is not None:
p_ac_0 = p_ac_0 * (1000. if unit == 'kW' else 1.)
p_nt = get('Night_Loss')

voltages = get('Converter', 'VNomEff')
if voltages is not None:
if not isinstance(voltages, list):
voltages = [voltages]
# the OND list has a trailing comma
voltages = [v for v in voltages if v != '']
if len(voltages) != 3:
raise ValueError("OND key 'Converter.VNomEff' must hold three "
f"voltages, found {len(voltages)}")

ac_power, dc_power, dc_voltage, dc_voltage_level = [], [], [], []
levels = ['Vmin', 'Vnom', 'Vmax']
for n, level in enumerate(levels, start=1):
profile = f'ProfilPIOV{n}'
npts = get('Converter', profile, 'NPtsEff')
if npts is None:
continue
if int(npts) < 1:
missing.append(f'Converter.{profile}.Point_1')
continue
for p in range(1, int(npts) + 1):
point = get('Converter', profile, f'Point_{p}')
if point is None:
continue
if not isinstance(point, list) or len(point) < 2:
raise ValueError(f"OND key 'Converter.{profile}.Point_{p}' "
"must hold a DC power and an AC power")
dc_power.append(point[0])
ac_power.append(point[1])
dc_voltage_level.append(level)
if voltages is not None:
dc_voltage.append(voltages[n - 1])

if missing:
raise ValueError(
"The OND content lacks data required to extract inverter "
"characteristics. Missing OND keys: "
+ ', '.join(dict.fromkeys(missing)))

return {'ac_power': np.array(ac_power), 'dc_power': np.array(dc_power),
'dc_voltage': np.array(dc_voltage),
'dc_voltage_level': np.array(dc_voltage_level),
'p_ac_0': p_ac_0, 'p_nt': p_nt}


def ond_to_sandia_inv(content):
"""
Get parameters for :py:func:`pvlib.inverter.sandia` from the content of a
PVsyst OND file.

Parameters
----------
content : dict
OND file content, i.e., the ``'PVObject_'`` entry of the nested dict
returned by :py:func:`pvlib.iotools.read_panond`.

Returns
-------
dict
Parameters for :py:func:`pvlib.inverter.sandia`. See
:py:func:`pvlib.inverter.fit_sandia`.

Raises
------
ValueError
If the content lacks data required for the fit. See
:py:func:`pvlib.inverter.extract_inverter_characteristics`.

See Also
--------
pvlib.inverter.extract_inverter_characteristics
pvlib.inverter.fit_sandia
pvlib.iotools.read_panond
"""
return fit_sandia(**extract_inverter_characteristics(content))
51 changes: 46 additions & 5 deletions pvlib/iotools/panond.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
Get .PAN or .OND file data into a nested dictionary.
"""

import codecs
import io


def _num_type(value):
"""
Expand Down Expand Up @@ -101,6 +104,25 @@ def _parse_panond(fbuf):
return component_info


def _decode_panond(raw):
"""
Decode the bytes of a .pan or .ond file: UTF-8 if there is a byte order
mark or the bytes are valid UTF-8, otherwise Windows-1252.
"""
if raw.startswith(codecs.BOM_UTF8):
encodings = ['utf-8-sig']
else:
encodings = ['utf-8', 'cp1252']
for encoding in encodings:
try:
return raw.decode(encoding)
except UnicodeDecodeError:
pass
raise ValueError(
f"Could not decode the file as {' or '.join(encodings)}. "
"Specify the encoding with the `encoding` parameter.")


def read_panond(filename, encoding=None):
"""
Retrieve Module or Inverter data from a .pan or .ond text file,
Expand All @@ -112,8 +134,10 @@ def read_panond(filename, encoding=None):
Name or path of a .pan/.ond file

encoding : str, optional
Encoding of the file. Some files may require specifying
``encoding='utf-8-sig'`` to import correctly.
Encoding of the file. If not specified, the encoding is detected:
UTF-8 if the file starts with a UTF-8 byte order mark or is valid
UTF-8, otherwise Windows-1252 (cp1252). The result does not depend on
the platform's default encoding.

Returns
-------
Expand All @@ -122,13 +146,25 @@ def read_panond(filename, encoding=None):
file. The value of datatypes are assumed during reading. The value
units are the default used by PVsyst.

Raises
------
ValueError
If ``encoding`` is not specified and the file can be decoded neither
as UTF-8 nor as Windows-1252.

See Also
--------
pvlib.inverter.ond_to_sandia_inv

Notes
-----
The parser is intended for use with .pan and .ond files that were created
for use by PVsyst. At time of publication, no documentation for these
files was available. So, this parser is based on inferred logic, rather
than anything specified by PVsyst. At time of creation, tested
.pan/.ond files used UTF-8 encoding.
.pan/.ond files used UTF-8 encoding. PVsyst has used UTF-8 since
version 6.80; older files and some files from manufacturers use
Windows-1252.

The parser assumes that the file being parsed uses indentation of two
spaces (' ') to create a new level in a nested dictionary, and that
Expand All @@ -148,7 +184,12 @@ def read_panond(filename, encoding=None):
that event the user would need to convert to the desired datatype.
"""

with open(filename, "r", encoding=encoding) as fbuf:
content = _parse_panond(fbuf)
if encoding is None:
with open(filename, "rb") as fbuf:
raw = fbuf.read()
content = _parse_panond(io.StringIO(_decode_panond(raw)))
else:
with open(filename, "r", encoding=encoding) as fbuf:
content = _parse_panond(fbuf)

return content
Loading