Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix OMOO DOPF #60

Merged
merged 18 commits into from
Mar 20, 2024
Merged
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
46 changes: 46 additions & 0 deletions .github/workflows/test-omoo.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: RunOMOO

on: [push]
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
python-version: ['3.10']
#include:
#- os: ubuntu-latest
#python-version: 3.10

steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: conda-incubator/setup-miniconda@v2
with:
auto-update-conda: true
python-version: ${{ matrix.python-version }}
- name: Install python dependencies
shell: bash -l {0}
run: |
pip install -r requirements.txt
pip install plotille
pip install click
- name: Run example
shell: bash -l {0}
run: |
git clone https://github.com/openEDI/oedisi-ieee123
mv oedisi-ieee123/profiles LocalFeeder/profiles
mv oedisi-ieee123/qsts LocalFeeder/opendss
# Change every kVA=50 and Pmpp=50 to kVA=200 and Pmpp=200 in LocalFeeder/opendss/IEEE123Pv.dss
sed -i 's/kVA=50/kVA=200/g; s/Pmpp=50/Pmpp=200/g' LocalFeeder/opendss/IEEE123Pv.dss
oedisi build --system scenarios/omoo_system.json
oedisi run
python opf_analysis.py
- name: Archive logs
uses: actions/upload-artifact@v2
if: always()
with:
name: test_logs
path: |
build/*.log
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ COPY README.md .
COPY measuring_federate measuring_federate
COPY wls_federate wls_federate
COPY recorder recorder
COPY omoo_federate omoo_federate

RUN mkdir -p outputs build

Expand Down
47 changes: 26 additions & 21 deletions LocalFeeder/FeederSimulator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Core class to abstract OpenDSS into Feeder class."""

import json
import logging
import math
Expand Down Expand Up @@ -63,11 +64,12 @@ class FeederConfig(BaseModel):
existing_feeder_file: Optional[str] = None
sensor_location: Optional[str] = None
start_date: str
number_of_timesteps: float
number_of_timesteps: int
run_freq_sec: float = 15 * 60
start_time_index: int = 0
topology_output: str = "topology.json"
use_sparse_admittance: bool = False
tap_setting: Optional[int] = None


class FeederMapping(BaseModel):
Expand Down Expand Up @@ -125,6 +127,8 @@ def __init__(self, config: FeederConfig):
self._number_of_timesteps = config.number_of_timesteps
self._vmult = 0.001

self.tap_setting = config.tap_setting

self._simulation_time_step = "15m"
if config.existing_feeder_file is None:
if self._use_smartds:
Expand Down Expand Up @@ -296,12 +300,15 @@ def load_feeder(self):
self._pvsystems = set()
for PV in get_pvsystems(dss):
self._pvsystems.add("PVSystem." + PV["name"])

if self.tap_setting is not None:
# Doesn't work with AutoTrans or 3-winding transformers.
dss.Text.Command(f"batchedit transformer..* wdg=2 tap={self.tap_setting}")
AadilLatif marked this conversation as resolved.
Show resolved Hide resolved
self._state = OpenDSSState.LOADED

def disable_elements(self):
"""Disable most elements. Used in disabled_run."""
assert self._state != OpenDSSState.UNLOADED, f"{self._state}"
# dss.Text.Command("batchedit transformer..* wdg=2 tap=1")
dss.Text.Command("batchedit regcontrol..* enabled=false")
dss.Text.Command("batchedit vsource..* enabled=false")
dss.Text.Command("batchedit isource..* enabled=false")
Expand Down Expand Up @@ -590,9 +597,9 @@ def _get_voltages(self):
name_voltage_dict = get_voltages(self._circuit)
res_feeder_voltages = np.zeros((len(self._AllNodeNames)), dtype=np.complex_)
for voltage_name in name_voltage_dict.keys():
res_feeder_voltages[
self._name_index_dict[voltage_name]
] = name_voltage_dict[voltage_name]
res_feeder_voltages[self._name_index_dict[voltage_name]] = (
name_voltage_dict[voltage_name]
)

return xr.DataArray(
res_feeder_voltages, {"ids": list(name_voltage_dict.keys())}
Expand Down Expand Up @@ -725,7 +732,6 @@ def set_properties_to_inverter(self, inverter: str, inv_control: InverterControl

def set_pv_output(self, pv_system, p, q):
"""Sets the P and Q values for a PV system in OpenDSS"""

max_pv = self.get_max_pv_available(pv_system)
# pf = q / ((p**2 + q **2)**0.5)

Expand All @@ -748,30 +754,29 @@ def set_pv_output(self, pv_system, p, q):
]
self.change_obj(command)

def get_pv_output(self, pv_system):
dss.PVsystems.First()
while True:
if dss.PVsystems.Name() == pv_system:
kw = dss.PVsystems.kW()
kvar = dss.PVsystems.kvar()
if not dss.PVsystems.Next() > 0:
break
return kw, kvar

def get_max_pv_available(self, pv_system):
dss.PVsystems.First()
irradiance = None
pmpp = None
while True:
flag = dss.PVsystems.First()
while flag:
if dss.PVsystems.Name() == pv_system:
irradiance = dss.PVsystems.Irradiance()
irradiance = dss.PVsystems.IrradianceNow()
pmpp = dss.PVsystems.Pmpp()
if not dss.PVsystems.Next() > 0:
break
flag = dss.PVsystems.Next()
if irradiance is None or pmpp is None:
raise ValueError(f"Irradiance or PMPP not found for {pv_system}")
return irradiance * pmpp

def get_available_pv(self):
pv_names = []
powers = []
flag = dss.PVsystems.First()
while flag:
pv_names.append(f"PVSystem.{dss.PVsystems.Name()}")
powers.append(dss.PVsystems.Pmpp() * dss.PVsystems.IrradianceNow())
flag = dss.PVsystems.Next()
return xr.DataArray(powers, coords={"ids": pv_names})

josephmckinsey marked this conversation as resolved.
Show resolved Hide resolved
def apply_inverter_control(self, inv_control: InverterControl):
"""Apply inverter control to OpenDSS.

Expand Down
92 changes: 76 additions & 16 deletions LocalFeeder/component_definition.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,84 @@
"directory": "LocalFeeder",
"execute_function": "python sender_cosim.py",
"static_inputs": [
{"type": "", "port_id": "feeder_file"},
{"type": "", "port_id": "start_date"},
{"type": "", "port_id": "run_freq_sec"},
{"type": "", "port_id": "number_of_timesteps"},
{"type": "", "port_id": "start_time_index"}
{
"type": "",
"port_id": "feeder_file"
},
{
"type": "",
"port_id": "start_date"
},
{
"type": "",
"port_id": "run_freq_sec"
},
{
"type": "",
"port_id": "number_of_timesteps"
},
{
"type": "",
"port_id": "start_time_index"
},
{
"type": "",
"port_id": "tap_setting"
}
],
"dynamic_inputs": [
{"type": "CommandList", "port_id": "change_commands", "optional": true},
{"type": "InverterControlList", "port_id": "inv_control", "optional": true}
{
"type": "",
"port_id": "pv_set",
"optional": true
},
{
"type": "CommandList",
"port_id": "change_commands",
"optional": true
},
{
"type": "InverterControlList",
"port_id": "inv_control",
"optional": true
}
],
"dynamic_outputs": [
{"type": "VoltagesMagnitude", "port_id": "voltages_magnitude"},
{"type": "VoltagesReal", "port_id": "voltages_real"},
{"type": "VoltagesImaginary", "port_id": "voltages_imag"},
{"type": "PowersReal", "port_id": "powers_real"},
{"type": "PowersImaginary", "port_id": "powers_imag"},
{"type": "Topology", "port_id": "topology"},
{"type": "Injection", "port_id": "injections"},
{"type": "", "port_id": "load_y_matrix"}
{
"type": "VoltagesMagnitude",
"port_id": "voltages_magnitude"
},
{
"type": "VoltagesReal",
"port_id": "voltages_real"
},
{
"type": "VoltagesImaginary",
"port_id": "voltages_imag"
},
{
"type": "PowersReal",
"port_id": "powers_real"
},
{
"type": "PowersImaginary",
"port_id": "powers_imag"
},
{
"type": "Topology",
"port_id": "topology"
},
{
"type": "Injection",
"port_id": "injections"
},
{
"type": "",
"port_id": "load_y_matrix"
},
{
"type": "PowersReal",
"port_id": "available_power"
}
]
}
}
36 changes: 33 additions & 3 deletions LocalFeeder/sender_cosim.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""HELICS wrapper for OpenDSS feeder simulation."""

import json
import logging
from dataclasses import dataclass
Expand Down Expand Up @@ -312,6 +313,9 @@ def go_cosim(
pub_injections = h.helicsFederateRegisterPublication(
vfed, "injections", h.HELICS_DATA_TYPE_STRING, ""
)
pub_available_power = h.helicsFederateRegisterPublication(
vfed, "available_power", h.HELICS_DATA_TYPE_STRING, ""
)
pub_load_y_matrix = h.helicsFederateRegisterPublication(
vfed, "load_y_matrix", h.HELICS_DATA_TYPE_STRING, ""
)
Expand All @@ -323,7 +327,7 @@ def go_cosim(
)
sub_command_set = vfed.register_subscription(command_set_key, "")
sub_command_set.set_default("[]")
sub_command_set.option["CONNECTION_OPTIONAL"] = 1
sub_command_set.option["CONNECTION_OPTIONAL"] = True

inv_control_key = (
"unused/inv_control"
Expand All @@ -332,7 +336,15 @@ def go_cosim(
)
sub_invcontrol = vfed.register_subscription(inv_control_key, "")
sub_invcontrol.set_default("[]")
sub_invcontrol.option["CONNECTION_OPTIONAL"] = 1
sub_invcontrol.option["CONNECTION_OPTIONAL"] = True

pv_set_key = (
"unused/pv_set" if "pv_set" not in input_mapping else input_mapping["pv_set"]
)

sub_pv_set = vfed.register_subscription(pv_set_key, "")
sub_pv_set.set_default("[]")
sub_pv_set.option["CONNECTION_OPTIONAL"] = True

h.helicsFederateEnterExecutingMode(vfed)
initial_data = get_initial_data(sim, config)
Expand All @@ -343,8 +355,15 @@ def go_cosim(
pub_topology.publish(initial_data.topology.json())

granted_time = -1
for request_time in range(0, int(config.number_of_timesteps)):
request_time = 0

while request_time < int(config.number_of_timesteps):
granted_time = h.helicsFederateRequestTime(vfed, request_time)
assert (
granted_time <= request_time + deltat
), f"granted_time: {granted_time} past {request_time}"
if granted_time >= request_time - deltat:
request_time += 1

current_index = int(granted_time) # floors
current_timestamp = datetime.strptime(
Expand All @@ -361,6 +380,10 @@ def go_cosim(
for inv_control in inverter_controls.__root__:
sim.apply_inverter_control(inv_control)

pv_sets = sub_pv_set.json
for pv_set in pv_sets:
sim.set_pv_output(pv_set[0].split(".")[1], pv_set[1], pv_set[2])

logger.info(
f"Solve at hour {floored_timestamp.hour} second "
f"{60*floored_timestamp.minute + floored_timestamp.second}"
Expand Down Expand Up @@ -426,6 +449,13 @@ def go_cosim(
).json()
)
pub_injections.publish(current_data.injections.json())
pub_available_power.publish(
MeasurementArray(
**xarray_to_dict(sim.get_available_pv()),
time=current_timestamp,
units="kWA",
).json()
)

if config.use_sparse_admittance:
pub_load_y_matrix.publish(
Expand Down
30 changes: 22 additions & 8 deletions LocalFeeder/tests/test_feeder.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,22 +609,36 @@ def test_pv_setpoints(federate_config):
]
)
sim.set_pv_output("113", 20, 5)
kw, kvar = sim.get_pv_output("113")
assert kw == 20
assert kvar == 5
sim.snapshot_run()
power = (
-sim.get_PQs_pv(static=True)
.groupby("equipment_ids")["PVSystem.113"]
.sum()
.item()
)
assert np.isclose(power.real, 20), f"Real power is {power.real}"
assert np.isclose(power.imag, 5), f"Reactive power is {power.imag}"

sim.change_obj(
[
FeederSimulator.Command(
obj_name="PVSystem.113",
obj_property="irradiance",
val="0.2",
obj_property="Pmpp",
val="8",
)
]
)
sim.snapshot_run()
sim.set_pv_output("113", 20, 5)
kw, kvar = sim.get_pv_output("113")
assert kw == 8
assert kvar == 2
sim.snapshot_run()
power = (
-sim.get_PQs_pv(static=True)
.groupby("equipment_ids")["PVSystem.113"]
.sum()
.item()
)
assert np.isclose(power.real, 8), f"Real power is {power.real}"
assert np.isclose(power.imag, 2), f"Reactive power is {power.imag}"


def test_incidence_matrix(federate_config):
Expand Down
Loading
Loading