Skip to content

Commit

Permalink
Fixed some representation issues
Browse files Browse the repository at this point in the history
  • Loading branch information
SanPen committed Oct 1, 2024
1 parent a527ed9 commit a0c30f3
Show file tree
Hide file tree
Showing 9 changed files with 121 additions and 101 deletions.
112 changes: 58 additions & 54 deletions .idea/workspace.xml

Large diffs are not rendered by default.

13 changes: 7 additions & 6 deletions src/GridCal/Gui/Diagrams/MapWidget/grid_map_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -875,7 +875,6 @@ def wheelEvent(self, event: QWheelEvent):
"""

# SANTIAGO: NO TOCAR ESTO ES EL COMPORTAMIENTO DESEADO

self.update_device_sizes()

def get_branch_width(self):
Expand All @@ -901,14 +900,14 @@ def update_device_sizes(self):
DeviceType.HVDCLineDevice,
DeviceType.FluidPathDevice]:
graphics_dict = self.graphics_manager.get_device_type_dict(device_type=dev_tpe)
for key, lne in graphics_dict.items():
lne.set_width_scale(self.get_branch_width())
for key, elm_graphics in graphics_dict.items():
elm_graphics.set_width_scale(self.get_branch_width())

# rescale substations
data: Dict[str, SubstationGraphicItem] = self.graphics_manager.get_device_type_dict(DeviceType.SubstationDevice)
for se_key, se in data.items():
se.set_api_object_color()
se.set_size(r=self.diagram.min_bus_width)
for se_key, elm_graphics in data.items():
elm_graphics.set_api_object_color()
elm_graphics.set_size(r=self.diagram.min_bus_width)

def change_size_and_pen_width_all(self, new_radius, pen_width):
"""
Expand Down Expand Up @@ -1085,6 +1084,7 @@ def colour_results(self,
weight = self.get_branch_width()

graphic_object.set_colour(color=color, style=style, tool_tip=tooltip)
graphic_object.set_width_scale(weight)

if hasattr(graphic_object, 'set_arrows_with_power'):
graphic_object.set_arrows_with_power(
Expand Down Expand Up @@ -1158,6 +1158,7 @@ def colour_results(self,
graphic_object.set_arrows_with_hvdc_power(Pf=hvdc_Pf[i], Pt=-hvdc_Pf[i])

graphic_object.set_colour(color=color, style=style, tool_tip=tooltip)
graphic_object.set_width_scale(weight)

def get_image(self, transparent: bool = False) -> QImage:
"""
Expand Down
2 changes: 1 addition & 1 deletion src/GridCal/Gui/Main/MainWindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -4628,7 +4628,7 @@ def setupUi(self, mainWindow):

self.tabWidget.setCurrentIndex(0)
self.tabWidget_3.setCurrentIndex(0)
self.tabWidget_6.setCurrentIndex(1)
self.tabWidget_6.setCurrentIndex(0)
self.tabWidget_5.setCurrentIndex(0)
self.tabWidget_4.setCurrentIndex(0)
self.tabWidget_2.setCurrentIndex(0)
Expand Down
2 changes: 1 addition & 1 deletion src/GridCal/Gui/Main/MainWindow.ui
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ QProgressBar::chunk{
<enum>QTabWidget::North</enum>
</property>
<property name="currentIndex">
<number>1</number>
<number>0</number>
</property>
<widget class="QWidget" name="tab_3">
<attribute name="icon">
Expand Down
20 changes: 13 additions & 7 deletions src/GridCal/Gui/Main/SubClasses/Model/time_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@
from matplotlib import pyplot as plt

import GridCal.Gui.gui_functions as gf
from GridCalEngine.basic_structures import Logger
from GridCalEngine.enumerations import DeviceType
from GridCalEngine.Devices.types import ALL_DEV_TYPES
from GridCal.Gui.general_dialogues import NewProfilesStructureDialogue, TimeReIndexDialogue
from GridCal.Gui.general_dialogues import NewProfilesStructureDialogue, TimeReIndexDialogue, LogsDialogue
from GridCal.Gui.messages import yes_no_question, warning_msg, info_msg
from GridCal.Gui.Main.SubClasses.Model.objects import ObjectsTableMain
from GridCal.Gui.ProfilesInput.models_dialogue import ModelsInputGUI
Expand Down Expand Up @@ -328,7 +329,7 @@ def set_profile_as_linear_combination(self):
Edit profiles with a linear combination
Returns: Nothing
"""

logger: Logger = Logger()
# value = self.ui.profile_factor_doubleSpinBox.value()

dev_type_text = self.get_db_object_selected_type()
Expand Down Expand Up @@ -356,13 +357,14 @@ def set_profile_as_linear_combination(self):

# Assign profiles
if len(objects) > 0:
attr_from = objects[0].properties_with_profile[magnitude_from]
attr_to = objects[0].properties_with_profile[magnitude_to]

for i, elm in enumerate(objects):
profile_from = elm.get_profile(magnitude=attr_from)
profile_to = elm.get_profile(magnitude=attr_to)
profile_to.set(profile_from.toarray())
profile_from = elm.get_profile(magnitude=magnitude_from)
profile_to = elm.get_profile(magnitude=magnitude_to)
if profile_from is not None and profile_to is not None:
profile_to.set(profile_from.toarray())
else:
print(f"P or Q profile None in {elm.name}")

self.display_profiles()

Expand All @@ -374,6 +376,10 @@ def set_profile_as_linear_combination(self):
# no buses or no actual change
pass

if logger.has_logs():
dlg = LogsDialogue("Set profile", logger=logger)
dlg.exec_()

def re_index_time(self):
"""
Re-index time
Expand Down
33 changes: 9 additions & 24 deletions src/GridCalEngine/Devices/assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,11 +504,6 @@ def ensure_profiles_exist(self) -> None:
if self.time_profile is None:
raise Exception('Cannot ensure profiles existence without a time index. Try format_profiles instead')

# for key, tpe in self.device_type_name_dict.items():
# elements = self.get_elements_by_type(device_type=tpe)
# for elm in elements:
# elm.ensure_profiles_exist(self.time_profile)

for elm in self.items():
elm.ensure_profiles_exist(self.time_profile)

Expand Down Expand Up @@ -4321,7 +4316,6 @@ def injection_items(self) -> Generator[INJECTION_DEVICE_TYPES, None, None]:
for elm in lst:
yield elm


# ------------------------------------------------------------------------------------------------------------------
# Load-like devices
# ------------------------------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -4508,28 +4502,28 @@ def get_elements_by_type(self, device_type: DeviceType) -> Union[pd.DatetimeInde
"""

if device_type == DeviceType.LoadDevice:
return self.get_loads()
return self._loads

elif device_type == DeviceType.StaticGeneratorDevice:
return self.get_static_generators()
return self._static_generators

elif device_type == DeviceType.GeneratorDevice:
return self.get_generators()
return self._generators

elif device_type == DeviceType.BatteryDevice:
return self.get_batteries()
return self._batteries

elif device_type == DeviceType.ShuntDevice:
return self.get_shunts()
return self._shunts

elif device_type == DeviceType.ExternalGridDevice:
return self.get_external_grids()
return self._external_grids

elif device_type == DeviceType.CurrentInjectionDevice:
return self.get_current_injections()
return self._current_injections

elif device_type == DeviceType.ControllableShuntDevice:
return self.get_controllable_shunts()
return self._controllable_shunts

elif device_type == DeviceType.LineDevice:
return self._lines
Expand Down Expand Up @@ -4641,15 +4635,6 @@ def get_elements_by_type(self, device_type: DeviceType) -> Union[pd.DatetimeInde
elif device_type == DeviceType.EmissionGasDevice:
return self._emission_gases

# elif device_type == DeviceType.GeneratorTechnologyAssociation:
# return self._generators_technologies
#
# elif device_type == DeviceType.GeneratorFuelAssociation:
# return self._generators_fuels
#
# elif device_type == DeviceType.GeneratorEmissionAssociation:
# return self._generators_emissions

elif device_type == DeviceType.ConnectivityNodeDevice:
return self._connectivity_nodes

Expand Down Expand Up @@ -5296,7 +5281,7 @@ def add_or_replace_object(self, api_obj: ALL_DEV_TYPES, logger: Logger) -> bool:

return found

def get_all_elements_dict(self, logger = Logger()) -> Tuple[Dict[str, ALL_DEV_TYPES], bool]:
def get_all_elements_dict(self, logger=Logger()) -> Tuple[Dict[str, ALL_DEV_TYPES], bool]:
"""
Get a dictionary of all elements
:param: logger: Logger
Expand Down
20 changes: 18 additions & 2 deletions src/GridCalEngine/Devices/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
from collections import Counter
import numpy as np
import numba as nb
from numpy import dtype

from GridCalEngine.basic_structures import Numeric, NumericVec, IntVec
from GridCalEngine.enumerations import DeviceType
from GridCalEngine.Utils.Sparse.sparse_array import SparseArray, PROFILE_TYPES, check_type
Expand Down Expand Up @@ -336,7 +338,16 @@ def __getitem__(self, key: int):
if self._is_sparse:
return self._sparse_array[key]
else:
return self._dense_array[key]

if self._dense_array is None:
# WTF, initialize sparse
self._is_sparse = True
self._sparse_array = SparseArray(data_type=self.dtype)
self._sparse_array.default_value = self.default_value
print("Initializing sparse when querying, this signals a mis initilaization")
return self.default_value
else:
return self._dense_array[key]

def __setitem__(self, key: int, value):
"""
Expand Down Expand Up @@ -392,7 +403,12 @@ def resize(self, n: int):
if self._is_sparse:
self._sparse_array.resize(n=n)
else:
self._dense_array.resize(n)
try:
self._dense_array.resize(n)
except ValueError:
new_arr = np.zeros(n, dtype=self._dense_array.dtype)
new_arr[:len(self._dense_array)] = self._dense_array
self._dense_array = new_arr # this is to avoid ValueError when resizing a numpy array of Objects
else:
self._initialized = True
self.create_sparse(size=n, default_value=self.default_value)
Expand Down
18 changes: 13 additions & 5 deletions src/GridCalEngine/IO/gridcal/pack_unpack.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,7 @@ def profile_todict(profile: Profile) -> Dict[str, str]:
return {
'is_sparse': True,
'size': s,
'default': profile.default_value
if profile.sparse_array is None else profile.sparse_array.default_value,
'default': profile.default_value if profile.sparse_array is None else profile.sparse_array.default_value,
'sparse_data': {
'map': dict()
}
Expand All @@ -288,16 +287,18 @@ def profile_todict_idtag(profile: Profile) -> Dict[str, str]:
'size': profile.size(),
'default': default,
'sparse_data': {
'map': {key: val.idtag for key, val in profile.sparse_array.get_map().items()}
if profile.sparse_array else dict()
'map': {key: val.idtag if hasattr(val, 'idtag') else None
for key, val in profile.sparse_array.get_map().items()}
if profile.sparse_array is not None else dict()
}
}
else:
return {
'is_sparse': profile.is_sparse,
'size': profile.size(),
'default': default,
'dense_data': [e.idtag for e in profile.dense_array] if profile.dense_array else list(),
'dense_data': [e.idtag if hasattr(e, 'idtag') else None for e in profile.dense_array]
if profile.dense_array is not None else list(),
}


Expand Down Expand Up @@ -434,6 +435,10 @@ def gather_model_as_jsons(circuit: MultiCircuit) -> Dict[str, Dict[str, str]]:
:param circuit:
:return:
"""

if circuit.has_time_series:
circuit.ensure_profiles_exist()

data: Dict[str, Union[Dict[str, str], List[Dict[str, str]]]] = dict()

# declare objects to iterate name: [sample object, list of objects, headers]
Expand Down Expand Up @@ -1469,4 +1474,7 @@ def parse_gridcal_data(data: Dict[str, Union[str, float, pd.DataFrame, Dict[str,
if text_func is not None:
text_func("Done!")

if circuit.has_time_series:
circuit.ensure_profiles_exist()

return circuit
2 changes: 1 addition & 1 deletion src/GridCalEngine/Simulations/results_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ def plot_device(self, ax=None, device_idx: int = 0, stacked=False):
"""
index, columns, data = self.get_data()

columns = columns[device_idx]
columns = [columns[device_idx]]
data = data[:, device_idx]

if ax is None:
Expand Down

0 comments on commit a0c30f3

Please sign in to comment.