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
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
173 changes: 133 additions & 40 deletions pvlib/inverter.py
Original file line number Diff line number Diff line change
Expand Up @@ -549,55 +549,148 @@ def extract_c(x_d, add):
'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 content of a
Get parameters for :py:func:`pvlib.inverter.sandia` from the content of a
PVsyst OND file.

Parameters
----------
content : dict
OND file content from the nested dict returned from
:py:func:`pvlib.iotools.panond.read_panond`
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`
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
"""
# get power unit
if content['Converter']['UnitAffEnum'] == 'kW':
multiplier = 1000.
else:
multiplier = 1.
# to fit pvlib.inverter.sandia, we need ac_power, dc_power, dc_voltage,
# dc_voltage_level, p_ac_0, p_nt
p_ac_0 = content['Converter']['PNomConv'] * multiplier
p_nt = content['Night_Loss']
# assemble ac_power and dc_power
ac_power = []
dc_power = []
dc_voltage = []
dc_voltage_level = []
voltages = content['Converter']['VNomEff']
if voltages[-1] =='':
voltages = voltages[:-1]
voltage_lvls = ['Vmin', 'Vnom', 'Vmax']
for v, lvl, profile in zip(voltages, voltage_lvls,
['ProfilPIOV1', 'ProfilPIOV2', 'ProfilPIOV3']):
data = content['Converter'][profile]
npts = int(data['NPtsEff'])
for p in range(1, npts+1):
dc_voltage.append(v)
dc_voltage_level.append(lvl)
vals = data['Point_' + str(p)]
ac_power.append(vals[1])
dc_power.append(vals[0])
dc_power = np.array(dc_power)
ac_power = np.array(ac_power)
dc_voltage = np.array(dc_voltage)
dc_voltage_level = np.array(dc_voltage_level)
return fit_sandia(ac_power, dc_power,
dc_voltage, dc_voltage_level,
p_ac_0, p_nt)
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
54 changes: 54 additions & 0 deletions pvlib/tests/iotools/test_panond.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
test iotools for panond
"""

import pytest

from pvlib.iotools import read_panond
from pvlib.tests.conftest import DATA_DIR

Expand Down Expand Up @@ -30,3 +32,55 @@ def test_read_panond():
assert ond['NbMPPT'] == 12
assert ond['Converter']['ModeOper'] == 'MPPT'
assert ond['Converter']['ProfilPIOV2']['Point_5'] == [75795.9, 75000.0]


def _ond_text_with_manufacturer(manufacturer):
text = OND_FILE.read_text(encoding='utf-8-sig')
old = 'Manufacturer=ChintPower'
assert old in text
return text.replace(old, 'Manufacturer=' + manufacturer, 1)


def _manufacturer(content):
return content['PVObject_']['PVObject_Commercial']['Manufacturer']


def test_read_panond_detects_utf8_bom(tmp_path):
expected = read_panond(OND_FILE, encoding='utf-8-sig')
path = tmp_path / 'bom.OND'
path.write_bytes(OND_FILE.read_bytes())
assert OND_FILE.read_bytes().startswith(b'\xef\xbb\xbf')
assert read_panond(path) == expected


def test_read_panond_detects_utf8_without_bom(tmp_path):
text = _ond_text_with_manufacturer('Müller 25°C')
path = tmp_path / 'utf8.OND'
path.write_bytes(text.encode('utf-8'))
assert _manufacturer(read_panond(path)) == 'Müller 25°C'


def test_read_panond_detects_cp1252(tmp_path):
text = _ond_text_with_manufacturer('Müller 25°C')
path = tmp_path / 'cp1252.OND'
path.write_bytes(text.encode('cp1252'))
assert b'\xb0' in path.read_bytes()
assert _manufacturer(read_panond(path)) == 'Müller 25°C'


def test_read_panond_explicit_encoding(tmp_path):
text = _ond_text_with_manufacturer('25°C')
path = tmp_path / 'utf8.OND'
path.write_bytes(text.encode('utf-8'))
assert _manufacturer(read_panond(path)) == '25°C'
assert _manufacturer(read_panond(path, encoding='latin-1')) == '25°C'


def test_read_panond_undecodable(tmp_path):
# 0x81 is not valid UTF-8 and is undefined in Windows-1252
text = _ond_text_with_manufacturer('ChintPower')
path = tmp_path / 'bad.OND'
path.write_bytes(text.encode('utf-8') + b'\x81\n')
with pytest.raises(ValueError, match='encoding'):
read_panond(path)
assert read_panond(path, encoding='latin-1')
Loading