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

Chore: Cleanup prerelease #74

Merged
merged 13 commits into from
Nov 19, 2021
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
3 changes: 2 additions & 1 deletion src/core/bio_process/calcification.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from src.core import RESHAPE
from src.core.common.constants import Constants


class Calcification:
"""Calcification rate."""

def __init__(self, constants):
def __init__(self, constants: Constants = Constants()):
"""Calcification rate."""
self.ad = 1
self.constants = constants
Expand Down
10 changes: 9 additions & 1 deletion src/core/bio_process/flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,21 @@
from scipy.optimize import newton

from src.core import RESHAPE
from src.core.common.constants import Constants
from src.core.common.space_time import CoralOnly, DataReshape


class Flow:
"""Flow micro-environment."""

def __init__(self, constants, u_current, u_wave, h, peak_period):
def __init__(
self,
u_current,
u_wave,
h,
peak_period,
constants: Constants = Constants(),
):
"""
:param u_current: current flow velocity [m s-1]
:param u_wave: wave flow velocity [m s-1]
Expand Down
8 changes: 4 additions & 4 deletions src/core/bio_process/light.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from typing import Union
from typing import Optional, Union

import numpy as np

from src.core import RESHAPE
from src.core.common.constants import Constants
from src.core.common.space_time import CoralOnly, DataReshape
from src.core.common.space_time import DataReshape
from src.core.coral.coral_only import CoralOnly

LightVariable = Union[float, list, tuple, np.ndarray]

Expand All @@ -14,16 +15,15 @@ class Light:

def __init__(
self,
constants: Constants,
light_in: LightVariable,
lac: LightVariable,
depth: LightVariable,
constants: Constants = Constants(),
):
"""
Light micro-environment.

Args:
constants (Constants): Constants required for this class.
light_in (LightVariable): Incoming light-intensity at the water-air interface [u mol photons m-2 s-1]
lac (LightVariable): light-attenuation coefficient [m-1]
depth (LightVariable): water depth [m]
Expand Down
5 changes: 4 additions & 1 deletion src/core/bio_process/morphology.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import numpy as np

from src.core import RESHAPE
from src.core.common.constants import Constants
from src.core.coral.coral_model import Coral


Expand All @@ -11,7 +12,9 @@ class Morphology:
__rp_optimal = None
__rs_optimal = None

def __init__(self, constants, calc_sum, light_in, dt_year=1):
def __init__(
self, calc_sum, light_in, dt_year=1, constants: Constants = Constants()
):
"""
Morphological development.

Expand Down
3 changes: 2 additions & 1 deletion src/core/bio_process/photosynthesis.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
import pandas as pd

from src.core import RESHAPE
from src.core.common.constants import Constants
from src.core.common.space_time import DataReshape
from src.core.coral.coral_model import Coral


class Photosynthesis:
"""Photosynthesis."""

def __init__(self, constants, light_in, first_year):
def __init__(self, light_in, first_year, constants: Constants = Constants()):
"""
Photosynthetic efficiency based on photosynthetic dependencies.

Expand Down
5 changes: 4 additions & 1 deletion src/core/bio_process/population_states.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from typing import Optional

import numpy as np

from src.core import RESHAPE
from src.core.common.constants import Constants
from src.core.coral.coral_model import Coral


Expand All @@ -9,7 +12,7 @@ class PopulationStates:

# TODO: Check this class; incl. writing tests

def __init__(self, constants, dt=1):
def __init__(self, constants: Constants = Constants(), dt: Optional[float] = 1):
"""Population dynamics.

:param dt: time step [yrs], defaults to one
Expand Down
2 changes: 1 addition & 1 deletion src/core/bio_process/recruitment.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from src.core import RESHAPE
from src.core.base_model import ExtraModel
from src.core.common.constants import Constants
from src.core.common.space_time import CoralOnly
from src.core.coral.coral_model import Coral
from src.core.coral.coral_only import CoralOnly


class Recruitment(ExtraModel):
Expand Down
3 changes: 2 additions & 1 deletion src/core/bio_process/temperature.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from src.core import RESHAPE
from src.core.common.constants import Constants
from src.core.coral.coral_model import Coral


class Temperature:
def __init__(self, constants, temperature):
def __init__(self, temperature, constants: Constants = Constants()):
"""
Thermal micro-environment.

Expand Down
46 changes: 11 additions & 35 deletions src/core/common/singletons.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,51 +3,27 @@
throughout the `NBSDynamics` project.
Although these classes are defined elsewhere, here we implement them as singletons.
"""
from typing import Optional, Type

from src.core.common.constants import Constants
from src.core.common.space_time import DataReshape


class RESHAPE(DataReshape):
class Singleton(object):
"""
`DataReshape` Singleton.
Singleton class representing the design pattern.
This class can be used for concepts that are not meant to change state during a simulation
such as DataReshape, represented by RESHAPE.
"""

_instance: Optional[DataReshape] = None

def __new__(cls: Type[DataReshape], **kwargs) -> DataReshape:
"""
Overriding new method to ensure this class behaves as s singleton.
_instance = None

Args:
cls (Type[Constants]): Required instance class.

Returns:
Constants: Singleton for `CommonConstants`
"""
if cls._instance == None:
cls._instance = DataReshape(**kwargs).__new__(cls)
def __new__(cls, *args, **kwargs):
if not isinstance(cls._instance, cls):
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance


class CommonConstants(Constants):
class RESHAPE(Singleton, DataReshape):
"""
Constants Singleton.
`DataReshape` Singleton.
"""

_instance: Optional[Constants] = None

def __new__(cls: Type[Constants], **kwargs) -> Constants:
"""
Overriding new method to ensure this class behaves as s singleton.

Args:
cls (Type[Constants]): Required instance class.

Returns:
Constants: Singleton for `CommonConstants`
"""
if cls._instance == None:
cls._instance = Constants(**kwargs).__new__(cls)
return cls._instance
pass
3 changes: 2 additions & 1 deletion src/core/coral/coral_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
from src.core import RESHAPE
from src.core.base_model import ExtraModel
from src.core.common.constants import Constants
from src.core.common.space_time import CoralOnly, DataReshape
from src.core.common.space_time import DataReshape
from src.core.coral.coral_only import CoralOnly

CoralAttribute = Union[float, list, tuple, np.ndarray]

Expand Down
17 changes: 17 additions & 0 deletions src/core/hydrodynamics/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,20 @@ def get_hydrodynamic_model_type(model_name: str) -> HydrodynamicProtocol:
msg = f"{model_name} not in {[x.__name__ for x in HydrodynamicsFactory.supported_modes]}."
raise ValueError(msg)
return hydromodel

@staticmethod
def create(model_name: str, *args, **kwargs) -> HydrodynamicProtocol:
"""
Creates a `HydrodynamicProtocol` based on the model_name type and the dictionary of
values (if any) given.

Args:
model_name (str): Model type name.

Returns:
HydrodynamicProtocol: Instance of the requested model.
"""
m_type: HydrodynamicProtocol = HydrodynamicsFactory.get_hydrodynamic_model_type(
model_name
)
return m_type(**kwargs)
15 changes: 5 additions & 10 deletions src/core/simulation/base_simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@

class BaseSimulation(BaseModel, ABC):
"""
Implements the `SimulationProtocol`
Implements the `SimulationProtocol`.
Facade class that can be implemented through an Adapter pattern.
CoralModel simulation.
"""

Expand Down Expand Up @@ -122,14 +123,9 @@ def validate_hydrodynamics_present(
if field_values is None:
field_values = dict()
if isinstance(field_values, dict):
model_type = HydrodynamicsFactory.get_hydrodynamic_model_type(
field_values.get("mode", values["mode"])
return HydrodynamicsFactory.create(
field_values.get("mode", values["mode"]), **field_values
)
# Emphasize working dir from explicit definition takes preference over simulation one.
field_values["working_dir"] = field_values.get(
"working_dir", values["working_dir"]
)
return model_type(**field_values)

return field_values

Expand Down Expand Up @@ -283,19 +279,18 @@ def run(self, duration: Optional[int] = None):
progress.set_postfix(inner_loop="coral environment")
# light micro-environment
lme = Light(
constants=self.constants,
light_in=time_series_year(self.environment.light, years[i]),
lac=time_series_year(self.environment.light_attenuation, years[i]),
depth=self.hydrodynamics.water_depth,
)
lme.rep_light(self.coral)
# flow micro-environment
fme = Flow(
constants=self.constants,
u_current=current_vel,
u_wave=wave_vel,
h=self.hydrodynamics.water_depth,
peak_period=wave_per,
constants=self.constants,
)
fme.velocities(self.coral, in_canopy=self.constants.fme)
fme.thermal_boundary_layer(self.coral)
Expand Down
8 changes: 5 additions & 3 deletions test/core/bio_process/bio_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
from src.core.coral.coral_model import Coral


@pytest.fixture(scope="module", autouse=True)
def default_constants() -> Constants:
return Constants()


@pytest.fixture(scope="module", autouse=False)
def matrix_1x1() -> DataReshape:
RESHAPE().spacetime = (1, 1)
Expand All @@ -31,7 +36,6 @@ def valid_coral() -> Coral:
assert rs.spacetime == (1, 1)
return Coral(
**dict(
constants=Constants(),
dc=0.2,
hc=0.3,
bc=0.1,
Expand All @@ -55,7 +59,6 @@ def coral_2x2() -> Coral:
assert rs.spacetime == (2, 2)
return Coral(
**dict(
constants=Constants(),
dc=0.2,
hc=0.3,
bc=0.1,
Expand All @@ -69,7 +72,6 @@ def coral_2x2() -> Coral:
@pytest.fixture(scope="module", autouse=False)
def no_base_coral_2x2() -> Coral:
return Coral(
constants=Constants(),
RESHAPE=DataReshape((2, 2)),
dc=0.4,
hc=0.3,
Expand Down
3 changes: 1 addition & 2 deletions test/core/bio_process/test_calcification.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@
import pytest

from src.core.bio_process.calcification import Calcification
from src.core.common.constants import Constants
from src.core.coral.coral_model import Coral


class TestCalcification:
@pytest.fixture(autouse=False)
def calc_test(self) -> Calcification:
return Calcification(Constants())
return Calcification()

def test_init_calcification(self, calc_test: Calcification):
assert calc_test.ad == 1
Expand Down
1 change: 0 additions & 1 deletion test/core/bio_process/test_dislodgement.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,6 @@ def test_csf1(self, coral_2x2: Coral, reshape_2x2: DataReshape):
def test_csf2(self):
dislodgement = Dislodgement()
coral = Coral(
constants=Constants(),
dc=[0.2, 0],
hc=[0.3, 0],
bc=[0.1, 0],
Expand Down
4 changes: 2 additions & 2 deletions test/core/bio_process/test_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

class TestFlow:
def test_init_flow(self, matrix_1x1):
flow = Flow(Constants(), 0.1, 0.1, 5, 4)
flow = Flow(0.1, 0.1, 5, 4)
assert flow.uc[0] == 0.1
assert flow.uw[0] == 0.1
assert flow.h == 5
Expand Down Expand Up @@ -119,7 +119,7 @@ def test_wave_attenuation(self):

class TestFlox2x2:
def test_initiation(self, matrix_2x2: DataReshape):
flow = Flow(Constants(), [0.1, 0.1], [0.1, 0.1], [5, 5], [4, 4])
flow = Flow([0.1, 0.1], [0.1, 0.1], [5, 5], [4, 4])
for i in range(matrix_2x2.space):
assert float(flow.uc[i]) == 0.1
assert float(flow.uw[i]) == 0.1
Expand Down
4 changes: 2 additions & 2 deletions test/core/bio_process/test_light.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class TestLight:
@pytest.fixture(autouse=False)
def light_test(self, matrix_1x1: DataReshape) -> Light:
assert matrix_1x1.spacetime == (1, 1)
return Light(Constants(), 600, 0.1, 5)
return Light(600, 0.1, 5)

def test_initiation(self, light_test: Light):
assert light_test.I0, pytest.approx(600, tolerance)
Expand Down Expand Up @@ -77,7 +77,7 @@ class TestLight2x2:

@pytest.fixture(autouse=False)
def light_2x2(self) -> Light:
return Light(Constants(), [600, 600], [0.1, 0.1], [5, 5])
return Light([600, 600], [0.1, 0.1], [5, 5])

def test_initiation(self, light_2x2: Light, matrix_2x2: DataReshape):
for i in range(matrix_2x2.space):
Expand Down
Loading