diff --git a/docs/sphinx/source/reference/pv_modeling/inverter.rst b/docs/sphinx/source/reference/pv_modeling/inverter.rst index e6e623f28b..55a042d4d0 100644 --- a/docs/sphinx/source/reference/pv_modeling/inverter.rst +++ b/docs/sphinx/source/reference/pv_modeling/inverter.rst @@ -20,3 +20,5 @@ Functions for fitting inverter models :toctree: ../generated/ inverter.fit_sandia + inverter.extract_inverter_characteristics + inverter.ond_to_sandia_inv diff --git a/docs/sphinx/source/whatsnew/v0.16.2.rst b/docs/sphinx/source/whatsnew/v0.16.2.rst index fb3ff54f76..ad4b154818 100644 --- a/docs/sphinx/source/whatsnew/v0.16.2.rst +++ b/docs/sphinx/source/whatsnew/v0.16.2.rst @@ -24,6 +24,11 @@ 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 ~~~~~~~~~~~~ @@ -31,6 +36,12 @@ Enhancements * 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 ~~~~~~~~~~~~~ @@ -84,3 +95,4 @@ Contributors * :ghuser:`xiajiahang` * Jakub Krasuski (:ghuser:`Blizzeq`) * Dylan Pulver (:ghuser:`dylanpulver`) +* :ghuser:`dihannahdi` diff --git a/pvlib/inverter.py b/pvlib/inverter.py index 622fb9b958..f10bb86601 100644 --- a/pvlib/inverter.py +++ b/pvlib/inverter.py @@ -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)) diff --git a/pvlib/iotools/panond.py b/pvlib/iotools/panond.py index 2bc8363674..b70b223edc 100644 --- a/pvlib/iotools/panond.py +++ b/pvlib/iotools/panond.py @@ -2,6 +2,9 @@ Get .PAN or .OND file data into a nested dictionary. """ +import codecs +import io + def _num_type(value): """ @@ -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, @@ -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 ------- @@ -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 @@ -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 diff --git a/tests/data/Huawei_Sun2000_40KTL_US_SLR.OND b/tests/data/Huawei_Sun2000_40KTL_US_SLR.OND new file mode 100644 index 0000000000..7fff2f1cb0 --- /dev/null +++ b/tests/data/Huawei_Sun2000_40KTL_US_SLR.OND @@ -0,0 +1,130 @@ +PVObject_=pvGInverter + Comment=Huawei Technologies SUN2000-40KTL-US Manufacturer 2018 + Version=7.3.1 + ParObj1=2017 + ParObj2=2020 + Flags=$803C1540 + + PVObject_Commercial=pvCommercial + Comment=www.huawei.com (China) + Flags=$0041 + Manufacturer=Huawei Technologies + Model=SUN2000-40KTL-US + DataSource=Manufacturer 2018 + YearBeg=2017 + YearEnd=2020 + Width=0.930 + Height=0.550 + Depth=0.260 + Weight=60.000 + NPieces=100 + PriceDate=25/04/23 12:26 + Remarks, Count=3 + Str_1=Technology: transformerless, 16 kHz, IGBT + Str_2=Protection: -25 - +60°C, IP 65, outdoor installation + Str_3=Control: LED indicator, Bluetooth + APP, USB data cable + APP + End of Remarks=Control: LED indicator, Bluetooth + APP, USB data cable + APP + End of PVObject pvCommercial + Transfo=Without + + Converter=TConverter + PNomConv=40.000 + PMaxOUT=44.000 + VOutConv=480.0 + VMppMin=200 + VMPPMax=1000 + VmppNom=720.0 + VAbsMax=1000 + PSeuil=80.0 + EfficMax=98.90 + EfficEuro=0.00 + FResNorm=0.00 + ModeOper=MPPT + CompPMax=Lim + CompVMax=Lim + MonoTri=Tri + ModeAffEnum=Efficf_PIn + UnitAffEnum=kW + PMaxDC=45.000 + IDCMax=0.0 + IMaxDC=88.0 + INomAC=48.2 + IMaxAC=53.0 + TPNom=50.0 + TPMax=45.0 + TPLim1=60.0 + TPLimAbs=62.0 + PLim1=32.000 + HasdefaultPThresh=False + VNomEff=530.0,720.0,850.0, + EfficMaxV=98.100,98.900,98.500, + EfficEuroV=97.810,98.700,98.260, + + ProfilPIOV1=TCubicProfile + NPtsMax=11 + NPtsEff=8 + LastCompile=$8089 + Mode=1 + Point_1=80.0,0.0 + Point_2=4000.0,3868.0 + Point_3=8000.0,7816.0 + Point_4=12000.0,11748.0 + Point_5=20000.0,19620.0 + Point_6=30000.0,29400.0 + Point_7=40000.0,39160.0 + Point_8=44000.0,43032.0 + Point_9=0.0,0.0 + Point_10=0.0,0.0 + Point_11=0.0,0.0 + End of TCubicProfile + + ProfilPIOV2=TCubicProfile + NPtsMax=11 + NPtsEff=8 + LastCompile=$8089 + Mode=1 + Point_1=80.0,0.0 + Point_2=4000.0,3924.0 + Point_3=8000.0,7896.0 + Point_4=12000.0,11856.0 + Point_5=20000.0,19780.0 + Point_6=30000.0,29640.0 + Point_7=40000.0,39520.0 + Point_8=44000.0,43428.0 + Point_9=0.0,0.0 + Point_10=0.0,0.0 + Point_11=0.0,0.0 + End of TCubicProfile + + ProfilPIOV3=TCubicProfile + NPtsMax=11 + NPtsEff=8 + LastCompile=$8089 + Mode=1 + Point_1=80.0,0.0 + Point_2=4000.0,3892.0 + Point_3=8000.0,7856.0 + Point_4=12000.0,11808.0 + Point_5=20000.0,19700.0 + Point_6=30000.0,29520.0 + Point_7=40000.0,39360.0 + Point_8=44000.0,43252.0 + Point_9=0.0,0.0 + Point_10=0.0,0.0 + Point_11=0.0,0.0 + End of TCubicProfile + End of TConverter + NbInputs=8 + NbMPPT=4 + TanPhiMin=-0.750 + TanPhiMax=0.750 + NbMSInterne=2 + MasterSlave=No_M_S + IsolSurvey =Yes + DC_Switch=Yes + AC_Switch=No + DiscAdjust=Yes + ENS_Protec=Yes + MS_Thresh=0.8 + Night_Loss=1.00 +End of PVObject pvGInverter diff --git a/tests/iotools/test_panond.py b/tests/iotools/test_panond.py index 3b62d9463f..b0f07057d4 100644 --- a/tests/iotools/test_panond.py +++ b/tests/iotools/test_panond.py @@ -2,6 +2,8 @@ test iotools for panond """ +import pytest + from pvlib.iotools import read_panond from tests.conftest import TESTS_DATA_DIR @@ -31,3 +33,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') diff --git a/tests/test_inverter.py b/tests/test_inverter.py index 5794669ec9..78db021841 100644 --- a/tests/test_inverter.py +++ b/tests/test_inverter.py @@ -1,3 +1,5 @@ +import re + import numpy as np import pandas as pd @@ -8,6 +10,7 @@ import pytest from pvlib import inverter +from pvlib.iotools import read_panond def test_adr(adr_inverter_parameters): @@ -211,3 +214,108 @@ def test_fit_sandia(infilen, expected): dc_voltage_level=curves['dc_voltage_level'], p_ac_0=expected['Paco'], p_nt=expected['Pnt']) assert expected == pytest.approx(result, rel=1e-3) + + +OND_FILE = TESTS_DATA_DIR / 'Huawei_Sun2000_40KTL_US_SLR.OND' +OND_FILE_CPS = TESTS_DATA_DIR / 'CPS SCH275KTL-DO-US-800-250kW_275kVA_1.OND' + + +def test_ond_to_sandia(): + content = read_panond(OND_FILE) + data = content['PVObject_'] + result = inverter.ond_to_sandia_inv(data) + expected = {'Paco': 40000., + 'Pdco': 40667.958855217, + 'Pnt': 1.0, + 'Pso': 73.847630974, + 'Vdco': 720.0, + 'C0': -1.6657324233698e-7, + 'C1': -1.7961032678822e-5, + 'C2': -0.0004676856528, + 'C3': -0.0009031894907} + assert expected == pytest.approx(result, rel=1e-8) + + +def test_ond_to_sandia_other_file(): + content = read_panond(OND_FILE_CPS)['PVObject_'] + result = inverter.ond_to_sandia_inv(content) + assert result['Paco'] == 1000. * content['Converter']['PMaxOUT'] + assert result['Pnt'] == content['Night_Loss'] + assert all(np.isfinite(list(result.values()))) + + +def test_extract_inverter_characteristics(): + content = read_panond(OND_FILE)['PVObject_'] + result = inverter.extract_inverter_characteristics(content) + assert set(result) == {'ac_power', 'dc_power', 'dc_voltage', + 'dc_voltage_level', 'p_ac_0', 'p_nt'} + assert len(result['ac_power']) == 24 + assert len(result['dc_power']) == 24 + assert len(result['dc_voltage']) == 24 + assert list(result['dc_voltage_level'][::8]) == ['Vmin', 'Vnom', 'Vmax'] + assert list(result['dc_voltage'][::8]) == [530., 720., 850.] + assert result['dc_power'][1] == 4000. + assert result['ac_power'][1] == 3868. + assert result['p_ac_0'] == 40000. + assert result['p_nt'] == 1. + expected = inverter.ond_to_sandia_inv(content) + assert inverter.fit_sandia(**result) == pytest.approx(expected) + + +def _write_modified_ond(tmp_path, old, new): + text = OND_FILE.read_text(encoding='utf-8-sig') + assert old in text + path = tmp_path / 'modified.OND' + path.write_text(text.replace(old, new, 1), encoding='utf-8') + return path + + +@pytest.mark.parametrize('old, new, missing_key', [ + ('Night_Loss=', 'Night_LossX=', 'Night_Loss'), + ('PNomConv=', 'PNomConvX=', 'Converter.PNomConv'), + ('UnitAffEnum=', 'UnitAffEnumX=', 'Converter.UnitAffEnum'), + ('VNomEff=', 'VNomEffX=', 'Converter.VNomEff'), + ('ProfilPIOV1=', 'ProfilPIOVX=', 'Converter.ProfilPIOV1'), + ('ProfilPIOV2=', 'ProfilPIOVX=', 'Converter.ProfilPIOV2'), + ('ProfilPIOV3=', 'ProfilPIOVX=', 'Converter.ProfilPIOV3'), + ('NPtsEff=', 'NPtsEffX=', 'Converter.ProfilPIOV1.NPtsEff'), + ('Point_3=', 'PointX_3=', 'Converter.ProfilPIOV1.Point_3'), +]) +def test_ond_to_sandia_missing_data(tmp_path, old, new, missing_key): + path = _write_modified_ond(tmp_path, old, new) + content = read_panond(path, encoding='utf-8')['PVObject_'] + with pytest.raises(ValueError, match=re.escape(missing_key)): + inverter.ond_to_sandia_inv(content) + + +def test_ond_to_sandia_missing_data_lists_all_keys(tmp_path): + path = _write_modified_ond(tmp_path, 'Night_Loss=', 'Night_LossX=') + text = path.read_text(encoding='utf-8') + path.write_text(text.replace('ProfilPIOV3=', 'ProfilPIOVX=', 1), + encoding='utf-8') + content = read_panond(path, encoding='utf-8')['PVObject_'] + with pytest.raises(ValueError, + match=r'Night_Loss.*Converter\.ProfilPIOV3'): + inverter.extract_inverter_characteristics(content) + + +def test_extract_inverter_characteristics_empty_content(): + with pytest.raises(ValueError) as excinfo: + inverter.extract_inverter_characteristics({}) + message = str(excinfo.value) + assert message.count('Converter,') == 1 + assert 'Night_Loss' in message + + +def test_ond_to_sandia_wrong_voltage_count(tmp_path): + path = _write_modified_ond(tmp_path, '530.0,720.0,850.0,', '530.0,720.0,') + content = read_panond(path, encoding='utf-8')['PVObject_'] + with pytest.raises(ValueError, match='VNomEff.*three voltages'): + inverter.extract_inverter_characteristics(content) + + +def test_ond_to_sandia_unsupported_unit(tmp_path): + path = _write_modified_ond(tmp_path, 'UnitAffEnum=kW', 'UnitAffEnum=MW') + content = read_panond(path, encoding='utf-8')['PVObject_'] + with pytest.raises(ValueError, match='UnitAffEnum'): + inverter.extract_inverter_characteristics(content)