Skip to content

Commit

Permalink
Deleted system_solver.py+final editing
Browse files Browse the repository at this point in the history
  • Loading branch information
daklauss committed Sep 13, 2024
1 parent 16253ab commit eea9791
Show file tree
Hide file tree
Showing 17 changed files with 171 additions and 361 deletions.
2 changes: 1 addition & 1 deletion CADETPythonSimulator/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# Version information
"""Version information."""
name = "CADET-Python-Simulator"
__version__ = "0.0.1"
5 changes: 5 additions & 0 deletions CADETPythonSimulator/cake_compressibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ def specific_resistance(self, delta_p: float) -> float:
-------
float
Specific pressure difference.
"""
return

Expand All @@ -33,6 +34,7 @@ class NoCakeCompressibility(CakeCompressibilityBase):
----------
cake_resistance: float
Constant value of cake resistance factor.
"""

cake_resistance = UnsignedFloat()
Expand All @@ -50,6 +52,7 @@ def specific_resistance(self, delta_p: float) -> float:
-------
float
Specific pressure difference.
"""
return self.cake_resistance

Expand All @@ -64,6 +67,7 @@ class LinearCakeCompressibility(CakeCompressibilityBase):
Base value of cake resistance factor.
cake_resistance_linear: float
Slope of cake resistance factor.
"""

cake_resistance_base = UnsignedFloat()
Expand All @@ -82,5 +86,6 @@ def specific_resistance(self, delta_p: float) -> float:
-------
float
Specific pressure difference.
"""
return self.cake_resistance_base + self.cake_resistance_linear * delta_p
4 changes: 4 additions & 0 deletions CADETPythonSimulator/componentsystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from CADETPythonSimulator.exception import CADETPythonSimError
from functools import wraps


class CPSSpecies(Structure):
"""
Species class.
Expand Down Expand Up @@ -34,6 +35,7 @@ class CPSSpecies(Structure):
density = UnsignedFloat()
molecular_volume = UnsignedFloat()


class CPSComponent(Component):
"""
Information about single component.
Expand Down Expand Up @@ -100,6 +102,7 @@ def __init__(self,
raise CADETPythonSimError("Could not determine number of species")

def add_species(self, species, *args, **kwargs):
"""Add a species to the component System."""
if not isinstance(species, CPSSpecies):
species = CPSSpecies(species, *args, **kwargs)
self._species.append(species)
Expand All @@ -119,6 +122,7 @@ def molecular_weight(self):
"""List of float or None: The molecular weights of the subspecies."""
return [spec.molecular_weight for spec in self.species]


class CPSComponentSystem(ComponentSystem):
"""
Component System Class.
Expand Down
4 changes: 2 additions & 2 deletions CADETPythonSimulator/coupling_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def get_coupled_state(
"""Calculate new state for destination_unit."""


class AverageCoupling(CouplingInterface):
class WeightedAverageCoupling(CouplingInterface):
"""Implements the Coupling Interface for average Coupling."""

def get_coupled_state(self,
Expand All @@ -26,7 +26,7 @@ def get_coupled_state(self,
ret = np.zeros(origin_list[0][0][state].shape)
rate_tot = 0
for list_state, rate in origin_list:
ret += list_state[state]*rate
ret += list_state[state] * rate
rate_tot += rate

ret /= rate_tot
Expand Down
6 changes: 0 additions & 6 deletions CADETPythonSimulator/residual.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ def calculate_residual_volume_cstr(

return V_dot - Q_in + Q_out


def calculate_residual_concentration_cstr(
c: np.ndarray,
c_dot: np.ndarray,
Expand Down Expand Up @@ -72,14 +71,12 @@ def calculate_residual_concentration_cstr(

return c_dot * V + V_dot * c - Q_in * c_in + Q_out * c


def calculate_residual_visc_cstr():
"""Calculate the residual of the Viscosity equation of the CSTR."""
warnings.warn("Viscosity of CSTR not yet implemented")

return 0


def calculate_residual_cake_vol_def(
V_dot_f: float,
rejection: np.ndarray,
Expand All @@ -106,7 +103,6 @@ def calculate_residual_cake_vol_def(
"""
return -V_dot_C + np.sum(rejection * molar_volume * c_in * V_dot_f)


def calculate_residual_press_easy_def(
V_dot_Perm: float,
V_C: float,
Expand Down Expand Up @@ -144,8 +140,6 @@ def calculate_residual_press_easy_def(

return -V_dot_Perm + deltap * A *hyd_resistance



def calculate_residual_visc_def():
"""Calculate the residual of the Viscosity equation of the CSTR."""
warnings.warn("Viscosity of def not yet implemented")
Expand Down
44 changes: 8 additions & 36 deletions CADETPythonSimulator/solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,9 @@ def __init__(self, system: SystemBase, sections: list[dict]):
self._system: Optional[SystemBase] = system
self._setup_sections(sections)


def _setup_sections(self, sections):
"""
Check Connections.
Set up sections.
Converts dict sections into addict.Dicts. Checks if start and end times
are continusly
Expand All @@ -41,7 +40,6 @@ def _setup_sections(self, sections):
previous_end = section.end
self.sections = sections


def initialize_solver(self, solver: str = 'ida') -> NoReturn:
"""
Initialize solver.
Expand All @@ -63,7 +61,7 @@ def system(self) -> SystemBase:
return self._system

@system.setter
def system(self, system:SystemBase) -> NoReturn:
def system(self, system: SystemBase) -> NoReturn:
"""Setter for System."""
self._system = system

Expand Down Expand Up @@ -146,8 +144,8 @@ def write_solution(
for sol_tuple in state_dict.values():
itp = it + sol_tuple["values"].shape[1]

y = y_history[:,it:itp]
ydot = y_dot_history[:,it:itp]
y = y_history[:, it:itp]
ydot = y_dot_history[:, it:itp]

sol_tuple["values"] = np.concatenate((sol_tuple["values"], y))
sol_tuple["derivatives"] = np.concatenate((
Expand Down Expand Up @@ -221,27 +219,25 @@ def get_section_solution_times(self, section: Dict) -> np.ndarray:
Parameters
----------
section : Dict
Section Dict that describes the Parameters
Section dict that describes the Parameters
"""
# TODO: How to get section_solution_times from section.start, section.end, if
# TODO: How to get section_solution_times from section.start, section.end, if
# user_solution times are provided?
time_resolution = section.get("time_resolution", 1.0)
start = section.start
end = section.end
return np.arange(start, end, time_resolution)



def _update_unit_operation_parameters(
self,
start: float,
end: float,
unit_operation_parameters: dict[
UnitOperationBase | str,
dict[str, npt.ArrayLike]
]
) -> np.ndarray:
]
) -> np.ndarray:
"""
Update time dependent unit operation parameters.
Expand All @@ -266,27 +262,3 @@ def _update_unit_operation_parameters(
raise CADETPythonSimError(f"Unit {unit} is not Part of the System.")

unit.update_parameters(start, end, parameters)

# @property
# def port_mapping(self) -> dict[int, str]:
# """dict: Mapping of port indices to corresponding state entries."""
# # TODO: Let this be handled by the SystemSolver?
# port_mapping = defaultdict(dict)

# counter = 0
# for mapped_state, n_ports in self.inlet_ports.items():
# for port in range(n_ports):
# port_mapping['inlet'][counter] = {}
# port_mapping['inlet'][counter]['mapped_state'] = mapped_state
# port_mapping['inlet'][counter]['port_index'] = port
# counter += 1

# counter = 0
# for mapped_state, n_ports in self.outlet_ports.items():
# for port in range(n_ports):
# port_mapping['outlet'][counter] = {}
# port_mapping['outlet'][counter]['mapped_state'] = mapped_state
# port_mapping['outlet'][counter]['port_index'] = port
# counter += 1

# return dict(port_mapping)
1 change: 1 addition & 0 deletions CADETPythonSimulator/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def __init__(
n_inlet_ports: int = 0,
n_outlet_ports: int = 0,
) -> NoReturn:
"""Init a state."""
self.name = name
self.dimensions = dimensions
self.entries = entries
Expand Down
36 changes: 21 additions & 15 deletions CADETPythonSimulator/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
from scikits.odes.dae import dae

from CADETPythonSimulator.state import State, state_factory
from CADETPythonSimulator.coupling_interface import CouplingInterface, AverageCoupling
from CADETPythonSimulator.coupling_interface import (
CouplingInterface,
WeightedAverageCoupling
)

from CADETProcess.dataStructure import Structure
from CADETPythonSimulator.exception import NotInitializedError, CADETPythonSimError
Expand All @@ -30,7 +33,6 @@ def __init__(self, unit_operations: list[UnitOperationBase]):
= None
self._setup_unit_operations(unit_operations)


@property
def unit_operations(self) -> dict[str, UnitOperationBase]:
"""dict: Unit operations, indexed by name."""
Expand Down Expand Up @@ -254,7 +256,18 @@ def compute_residual(
def couple_unit_operations(
self,
) -> NoReturn:
"""Couple unit operations for set parameters."""
"""
Couple unit operations for set parameters.
Iterates first over all rows of the connectivity-matrix which is the
destination. If the total flow is 0, the row is ignored.
Then it iterates over every origin flow by iterating over the row itself and
saves the state and the rate into a touple that gets added to a list.
With this list, the new state for destination_unit is created with the
coupled_state_func. And afterward is set.
"""
for destination_port_index, Q_destinations in enumerate(self.connectivity):
Q_destination_total = sum(Q_destinations)
if Q_destination_total == 0:
Expand All @@ -264,8 +277,6 @@ def couple_unit_operations(
self.destination_index_unit_operations[destination_port_index]
destination_unit = self.unit_operations[destination_info['name']]
destination_port = destination_info['port']


unit_Q_list = []
for origin_port_index, Q_destination in enumerate(Q_destinations):
if Q_destination == 0:
Expand All @@ -274,13 +285,11 @@ def couple_unit_operations(
origin_info = self.origin_index_unit_operations[origin_port_index]
origin_unit = self.unit_operations[origin_info['name']]
origin_port = origin_info['port']

unit_Q_list.append(
(origin_unit.get_outlet_state_flat(origin_port), Q_destination)
)
)

s_new = self.coupled_state_func(unit_Q_list)

destination_unit.set_inlet_state_flat(
s_new, destination_port
)
Expand All @@ -304,7 +313,6 @@ def coupled_state_func(self, unit_Q_list: list[dict, float]) -> dict:
ret[state] = calc_method.get_coupled_state(unit_Q_list, state)
return ret


def _compute_connectivity_matrix(self, connections: list) -> np.ndarray:
# TODO: This could be the setter for `connectivity`
# Note, maybe we already adapt the interface s.t. we compute this matrix,
Expand Down Expand Up @@ -363,8 +371,6 @@ def _compute_connectivity_matrix(self, connections: list) -> np.ndarray:
self._connectivity = connections_matrix




class FlowSystem(SystemBase):
"""
SystemBase Class.
Expand All @@ -376,8 +382,8 @@ class FlowSystem(SystemBase):
def __init__(self, unit_operations: list[UnitOperationBase]):
"""Construct FlowSystem Object."""
self.coupling_state_structure={
'c': AverageCoupling(),
'viscosity': AverageCoupling()
'c': WeightedAverageCoupling(),
'viscosity': WeightedAverageCoupling()
}
super().__init__(unit_operations)

Expand All @@ -394,9 +400,9 @@ def set_rates(self) -> NoReturn:
for dest_i, Q_n in enumerate(self.connectivity):
unit_operation = self.destination_index_unit_operations[dest_i]['name']
unit_port = self.destination_index_unit_operations[dest_i]['port']
self.unit_operations[unit_operation].set_Q_in(unit_port, np.sum(Q_n))
self.unit_operations[unit_operation].set_Q_in_port(unit_port, np.sum(Q_n))

for origin_i, Q_n in enumerate(self.connectivity.T):
unit_operation = self.origin_index_unit_operations[origin_i]['name']
unit_port = self.origin_index_unit_operations[origin_i]['port']
self.unit_operations[unit_operation].set_Q_out(unit_port, np.sum(Q_n))
self.unit_operations[unit_operation].set_Q_out_port(unit_port, np.sum(Q_n))
Loading

0 comments on commit eea9791

Please sign in to comment.