Skip to content

Commit

Permalink
Formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
schmoelder committed Aug 21, 2024
1 parent 596667e commit 3b37b05
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 67 deletions.
20 changes: 11 additions & 9 deletions CADETPythonSimulator/unit_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def initialize(self) -> NoReturn:

@property
def states(self) -> dict[str, State]:
"""dict: State array blocks of the unit operation, indexed by name."""
"""dict: State array block of the unit operation, indexed by name."""
if self._states is None:
raise NotInitializedError("Unit operation state is not yet initialized.")

Expand All @@ -115,7 +115,7 @@ def y(self, y: np.ndarray) -> NoReturn:

@property
def state_derivatives(self) -> dict[str, State]:
"""dict: State derivative array blocks of the unit operation, indexed by name."""
"""dict: State derivative array block of the unit operation, indexed by name."""
if self._state_derivatives is None:
raise NotInitializedError("Unit operation state is not yet initialized.")

Expand Down Expand Up @@ -327,7 +327,7 @@ def get_outlet_state(
def get_outlet_state_flat(
self,
unit_port_index: int
) -> NoReturn:
) -> dict[str, np.ndarray]:
"""
Get the state of the unit operation outlet for a given port.
Expand Down Expand Up @@ -573,14 +573,16 @@ def compute_residual(
Q_in = self.Q_in[0]
Q_out = self.Q_out[0]

# for i in range(self.n_comp):
# self.residuals['bulk']['c'][i] = c_dot[i] * V + V_dot * c[i] - Q_in * c_in[i] + Q_out * c[i]
# Alternative: Can we vectorize this?
self.residuals['bulk']['c'] = calculate_residual_concentration_cstr(c, c_dot, V, V_dot, Q_in, Q_out, c_in)

self.residuals['bulk']['Volume'] = calculate_residual_volume_cstr(V, V_dot, Q_in, Q_out)
self.residuals['bulk']['c'] = calculate_residual_concentration_cstr(
c, c_dot, V, V_dot, Q_in, Q_out, c_in
)

self.residuals['bulk']['Volume'] = calculate_residual_volume_cstr(
V, V_dot, Q_in, Q_out
)

self.residuals['inlet']['viscosity'] = calculate_residuals_visc_cstr()
self.residuals['inlet']['viscosity'] = calculate_residual_visc_cstr()

class DeadEndFiltration(UnitOperationBase):
"""
Expand Down
12 changes: 9 additions & 3 deletions CADETPythonSimulator/viscosity.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ class ViscosityBase(Structure):
"""Base class for mixed viscosity calculations."""

@abstractmethod
def get_mixture_viscosity(self, viscosities: np.ndarray, fractions: np.ndarray) -> float:
def get_mixture_viscosity(
self, viscosities: np.ndarray, fractions: np.ndarray
) -> float:
"""Calculate mixed viscosity with given viscosities and volume fractions.
Parameters
Expand Down Expand Up @@ -44,7 +46,9 @@ def _validate_viscosities_input(
class AverageViscosity(ViscosityBase):
"""Calculate mixed viscosity using the average mean."""

def get_mixture_viscosity(self, viscosities: np.ndarray, fractions: np.ndarray) -> float:
def get_mixture_viscosity(
self, viscosities: np.ndarray, fractions: np.ndarray
) -> float:
"""Calculate mixed viscosity using the arithmetic mean.
Parameters
Expand All @@ -68,7 +72,9 @@ def get_mixture_viscosity(self, viscosities: np.ndarray, fractions: np.ndarray)
class LogarithmicMixingViscosity(ViscosityBase):
"""Calculate mixed viscosity using the logarithmic mixing rule."""

def get_mixture_viscosity(self, viscosities: np.ndarray, fractions: np.ndarray) -> float:
def get_mixture_viscosity(
self, viscosities: np.ndarray, fractions: np.ndarray
) -> float:
"""Calculate mixed viscosity using the logarithmic mixing rule.
Parameters
Expand Down
52 changes: 26 additions & 26 deletions tests/test_residual.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
from CADETPythonSimulator.exception import CADETPythonSimError


# random number test
TestCaseConc_level1 = {
# Arbitrary parameter values
TestCaseCSTRConc_level1 = {
"values": {
"c": np.array([1, 2, 3]),
"c_dot": np.array([4, 5, 6]),
Expand All @@ -24,8 +24,8 @@
"expected": np.array([-11, -7, -3])
}

# flow in and out are equal, concentrations to
TestCaseConc_equal = {
# Flow in and out are equal, concentrations are equal
TestCaseCSTRConc_equal = {
"values": {
"c": np.array([0.1,]),
"c_dot": np.array([0,]),
Expand All @@ -38,8 +38,8 @@
"expected": np.array([0,])
}

# flow in and out are equal, but concentrations going into the unit are not
TestCaseConc_diffcin = {
# Flow in and out are equal, concentrations differ
TestCaseCSTRConc_diffcin = {
"values": {
"c": np.array([0.1,]),
"c_dot": np.array([0,]),
Expand All @@ -52,8 +52,8 @@
"expected": np.array([-0.1,])
}

# flow in and out are not equal, concentrantions going in are
TestCaseConc_diffvol = {
# Flow in and out differ, concentrations are equal
TestCaseCSTRConc_diffvol = {
"values": {
"c": np.array([0.1,]),
"c_dot": np.array([0,]),
Expand All @@ -66,8 +66,8 @@
"expected": np.array([0,])
}

# flow in and out are not, equal, concentrations aren't equal too
TestCaseConc_diffvolc = {
# Flow in and out differ, concentrations differ
TestCaseCSTRConc_diffvolc = {
"values": {
"c": np.array([0.1,]),
"c_dot": np.array([0.2,]),
Expand All @@ -84,24 +84,25 @@
@pytest.mark.parametrize(
"parameters",
[
TestCaseConc_level1,
TestCaseConc_equal,
TestCaseConc_diffcin,
TestCaseConc_diffvol,
TestCaseConc_diffvolc
TestCaseCSTRConc_level1,
TestCaseCSTRConc_equal,
TestCaseCSTRConc_diffcin,
TestCaseCSTRConc_diffvol,
TestCaseCSTRConc_diffvolc
]
)
class TestResidualConcCSTR():
def test_calculation_concentration_cstr(self, parameters):

param_vec_conc = parameters["values"].values()

residual = calculate_residual_concentration_cstr(*param_vec_conc)

np.testing.assert_array_almost_equal(residual, parameters["expected"])
np.testing.assert_array_almost_equal(
calculate_residual_concentration_cstr(*param_vec_conc),
parameters["expected"]
)


# random number test
# Arbitrary parameter values
TestCaseVol = {
"values": {
"V": 1,
Expand All @@ -123,7 +124,7 @@ def test_calculation_concentration_cstr(self, parameters):
"expected": 0
}

# Flow in is larger than out
# Flow in is larger than flow out
TestCaseVol_inge = {
"values": {
"V": 1,
Expand All @@ -134,7 +135,7 @@ def test_calculation_concentration_cstr(self, parameters):
"expected": 0
}

# Flow in is lesser than out
# Flow in is sameller than flow out
TestCaseVol_inle = {
"values": {
"V": 1,
Expand All @@ -145,11 +146,10 @@ def test_calculation_concentration_cstr(self, parameters):
"expected": 0
}

# Residual does not depend on Volumne

# Residual does not depend on volume
TestCaseVol_vol = {
"values": {
"V": 1e10,
"V": 1,
"V_dot": 0,
"Q_in": 0,
"Q_out": 0,
Expand All @@ -170,10 +170,10 @@ def test_calculation_concentration_cstr(self, parameters):
)
class TestResidualVolCSTR():
def test_calculation_cstr(self, parameters):

param_vec_volume = parameters["values"].values()

residual = calculate_residual_volume_cstr(*param_vec_volume)
np.testing.assert_equal(residual, parameters["expected"])


# Testcase 1: Membrane rejects all
TestCaseDEFCake_rejects_all = {
Expand Down
71 changes: 42 additions & 29 deletions tests/test_unit_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from CADETPythonSimulator.rejection import StepCutOff


# %% Unit Operation Fixtures
class TwoComponentFixture(CPSComponentSystem):
def __init__(self, *args, **kwargs):
Expand Down Expand Up @@ -71,7 +72,6 @@ def __init__(self, component_system=None, name='cstr', *args, **kwargs):
super().__init__(component_system, name, *args, **kwargs)



class DeadEndFiltrationFixture(UnitOperationFixture, DeadEndFiltration):
def __init__(self,
component_system=None,
Expand Down Expand Up @@ -116,7 +116,6 @@ def __init__(self,
super().__init__(component_system, name, *args, **kwargs)



# %% Unit Operation State Structure

@pytest.mark.parametrize(
Expand Down Expand Up @@ -360,41 +359,51 @@ def test_initialize(self, unit_operation: UnitOperationBase, expected: dict):
(
CstrFixture(),
{
'states' : {
'inlet' : {
'c' : np.array([7, 8]),
'viscosity' : [3]
'states': {
'inlet': {
'c': np.array([7, 8]),
'viscosity': [3]
},
'bulk' : {
'c' : np.array([1, 2]),
'Volume' : 1
'bulk': {
'c': np.array([1, 2]),
'Volume': 1
}
},
'state_derivatives' : {
'inlet' : {
'c' : [6, 7]
'state_derivatives': {
'inlet': {
'c': [6, 7]
},
'bulk' : {
'c' : np.array([4, 5]),
'Volume' : 2
'bulk': {
'c': np.array([4, 5]),
'Volume': 2
}
},
'Q_in' : [3],
'Q_out' : [4]
'Q_in': [3],
'Q_out': [4]
},
[
("calculate_residual_concentration_cstr", lambda c, c_dot, V, V_dot, Q_in, Q_out, c_in: c_dot * V + V_dot * c - Q_in * c_in + Q_out * c),
("calculate_residuals_visc_cstr", lambda *args : 0),
("calculate_residual_volume_cstr", lambda V, V_dot, Q_in, Q_out: V_dot - Q_in + Q_out)
(
"calculate_residual_concentration_cstr",
lambda c, c_dot, V, V_dot, Q_in, Q_out, c_in:
c_dot * V + V_dot * c - Q_in * c_in + Q_out * c
),
(
"calculate_residual_visc_cstr",
lambda *args: 0
),
(
"calculate_residual_volume_cstr",
lambda V, V_dot, Q_in, Q_out: V_dot - Q_in + Q_out
)
],
{
'inlet' : {
'c' : np.array([7, 8]),
'viscosity' : 0
'inlet': {
'c': np.array([7, 8]),
'viscosity': 0
},
'bulk' : {
'c' : np.array([-11,-7]),
'Volume' : 3
'bulk': {
'c': np.array([-11, -7]),
'Volume': 3
}
}
),
Expand Down Expand Up @@ -480,7 +489,7 @@ def test_unit_residual(
"""Test the residual of unit operations."""

for funcname, func in residualfunc:
monkeypatch.setattr('CADETPythonSimulator.unit_operation.'+funcname, func )
monkeypatch.setattr('CADETPythonSimulator.unit_operation.'+funcname, func)

for key, value in case['states'].items():
unit_operation.states[key] = value
Expand All @@ -495,9 +504,13 @@ def test_unit_residual(

for unit_module, module_dict in expected.items():
for property, value in module_dict.items():
np.testing.assert_equal(value, unit_operation.residuals[unit_module][property])
np.testing.assert_equal(
value,
unit_operation.residuals[unit_module][property]
)


# %% Run tests

if __name__ == "__main__":
pytest.main(["test_unit_operation.py"])
pytest.main(["test_unit_operation.py"])

0 comments on commit 3b37b05

Please sign in to comment.