pyswap 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyswap/__init__.py +3 -0
- pyswap/atmosphere/__init__.py +13 -0
- pyswap/atmosphere/meteorology.py +123 -0
- pyswap/atmosphere/metfile.py +107 -0
- pyswap/atmosphere/tables.py +34 -0
- pyswap/boundary/__init__.py +9 -0
- pyswap/boundary/boundary.py +146 -0
- pyswap/core/__init__.py +22 -0
- pyswap/core/basemodel.py +87 -0
- pyswap/core/database/__init__.py +11 -0
- pyswap/core/database/connection.py +64 -0
- pyswap/core/database/events.py +36 -0
- pyswap/core/database/models.py +83 -0
- pyswap/core/defaults.py +14 -0
- pyswap/core/fields.py +56 -0
- pyswap/core/files.py +46 -0
- pyswap/core/plot/__init__.py +11 -0
- pyswap/core/plot/evapotranspiration.py +32 -0
- pyswap/core/plot/gwl.py +34 -0
- pyswap/core/plot/watercontent.py +35 -0
- pyswap/core/serializers.py +85 -0
- pyswap/core/tablevalidation.py +42 -0
- pyswap/core/valueranges.py +16 -0
- pyswap/drainage/__init__.py +12 -0
- pyswap/drainage/drafile.py +196 -0
- pyswap/drainage/drainage.py +39 -0
- pyswap/extras/__init__.py +6 -0
- pyswap/extras/heatflow.py +73 -0
- pyswap/extras/solutetransport.py +63 -0
- pyswap/extras/tables.py +30 -0
- pyswap/irrigation/__init__.py +13 -0
- pyswap/irrigation/irgfile.py +48 -0
- pyswap/irrigation/irrigation.py +160 -0
- pyswap/irrigation/tables.py +27 -0
- pyswap/libs/swap420-exe/swap.exe +0 -0
- pyswap/libs/swap420-linux/swap420 +0 -0
- pyswap/model/__init__.py +12 -0
- pyswap/model/model.py +206 -0
- pyswap/model/result.py +61 -0
- pyswap/plant/__init__.py +13 -0
- pyswap/plant/create_crp_tables.py +59 -0
- pyswap/plant/crop.py +47 -0
- pyswap/plant/crpfile.py +708 -0
- pyswap/plant/read_yaml.py +87 -0
- pyswap/plant/tables.py +103 -0
- pyswap/simsettings/__init__.py +13 -0
- pyswap/simsettings/general.py +139 -0
- pyswap/simsettings/metadata.py +30 -0
- pyswap/simsettings/richards.py +37 -0
- pyswap/soilwater/__init__.py +19 -0
- pyswap/soilwater/evaporation.py +51 -0
- pyswap/soilwater/snow.py +41 -0
- pyswap/soilwater/soilmoisture.py +41 -0
- pyswap/soilwater/soilprofile.py +46 -0
- pyswap/soilwater/surfaceflow.py +44 -0
- pyswap/soilwater/tables.py +76 -0
- pyswap/testcase/__init__.py +2 -0
- pyswap/testcase/data/1-hupselbrook/283.csv +8870 -0
- pyswap/testcase/data/1-hupselbrook/grassd.crp +492 -0
- pyswap/testcase/data/1-hupselbrook/swap.dra +381 -0
- pyswap/testcase/hupselbrook.py +464 -0
- pyswap/testcase/load_data.py +26 -0
- pyswap/testcase/run_testcase.py +11 -0
- pyswap/tests/test_boundary.py +15 -0
- pyswap/tests/test_db.py +38 -0
- pyswap/tests/test_metadata.py +19 -0
- pyswap-0.1.0.dist-info/LICENSE +21 -0
- pyswap-0.1.0.dist-info/METADATA +66 -0
- pyswap-0.1.0.dist-info/RECORD +70 -0
- pyswap-0.1.0.dist-info/WHEEL +4 -0
pyswap/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""
|
|
2
|
+
# Atmosphere subpackage
|
|
3
|
+
|
|
4
|
+
Meteorological settings and data for SWAP simulations.
|
|
5
|
+
|
|
6
|
+
Modules:
|
|
7
|
+
metfile: meteorological data for SWAP simulations
|
|
8
|
+
meteorology: meteorological settings for SWAP simulations
|
|
9
|
+
___________________________________________________________________________
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from .meteorology import *
|
|
13
|
+
from .metfile import *
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Meteorological settings for SWAP simulations.
|
|
3
|
+
|
|
4
|
+
!!! note
|
|
5
|
+
`Meteorology` object requires the `MetFile` object to be passed upon initialization. When the model is run,
|
|
6
|
+
the `MetFile` object is saved to a .met file.
|
|
7
|
+
|
|
8
|
+
Classes:
|
|
9
|
+
Meteorology: Holds the settings of the meteo section of the .swp file.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from ..core.basemodel import PySWAPBaseModel
|
|
13
|
+
from ..core.fields import Table
|
|
14
|
+
from ..core.files import save_file
|
|
15
|
+
from ..core.valueranges import UNITRANGE
|
|
16
|
+
from .metfile import MetFile
|
|
17
|
+
from pydantic import Field, model_validator
|
|
18
|
+
from typing import Optional, Literal
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Meteorology(PySWAPBaseModel):
|
|
22
|
+
"""Meteorological settings of the simulation.
|
|
23
|
+
|
|
24
|
+
Attributes:
|
|
25
|
+
lat (float): latitude of the meteo station [degrees].
|
|
26
|
+
swetr (int): Switch type of weather data for potential evapotranspiration:
|
|
27
|
+
|
|
28
|
+
* 0 - Use basic weather data and apply Penman-Monteith equation.
|
|
29
|
+
* 1 - Use reference evapotranspiration data in combination with crop factors.
|
|
30
|
+
|
|
31
|
+
swdivide (int): Switch for distribution of E and T. Defaults to 0:
|
|
32
|
+
|
|
33
|
+
* 0 - Based on crop and soil factors.
|
|
34
|
+
* 1 - Based on direct application of Penman-Monteith.
|
|
35
|
+
|
|
36
|
+
swmetdetail (int): Switch for time interval of evapotranspiration and rainfall weather data:
|
|
37
|
+
|
|
38
|
+
* 0 - Daily data.
|
|
39
|
+
* 1 - Subdaily data.
|
|
40
|
+
|
|
41
|
+
swrain (int): Switch for use of actual rainfall intensity, defaults to 0:
|
|
42
|
+
|
|
43
|
+
* 0 - Use daily rainfall amounts.
|
|
44
|
+
* 1 - Use daily rainfall amounts + mean intensity.
|
|
45
|
+
* 2 - Use daily rainfall amounts + duration.
|
|
46
|
+
* 3 - Use detailed rainfall records (dt < 1 day), as supplied in separate file.
|
|
47
|
+
|
|
48
|
+
swetsine (int): Switch, distribute daily Tp and Ep according to sinus wave, default to 0:
|
|
49
|
+
|
|
50
|
+
* 0 - No distribution.
|
|
51
|
+
* 1 - Distribute Tp and Ep according to sinus wave.
|
|
52
|
+
|
|
53
|
+
metfile (MetFile): MetFile model containing meteorological data to be saved to .met file.
|
|
54
|
+
alt (float): Altitude of the meteo station [m].
|
|
55
|
+
altw (float): Altitude of the wind [m].
|
|
56
|
+
angstroma (float): Fraction of extraterrestrial radiation reaching the earth on overcast days.
|
|
57
|
+
angstromb (float): Additional fraction of extraterrestrial radiation reaching the earth on clear days.
|
|
58
|
+
table_rainflux (Table): rainfall intensity RAINFLUX as function of time TIME.
|
|
59
|
+
rainfil (str): file name of file with detailed rainfall data.
|
|
60
|
+
nmetdetail (int): Number of weather data records each day.
|
|
61
|
+
|
|
62
|
+
Methods:
|
|
63
|
+
write_met: Write the .met file.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
# metfil: str
|
|
67
|
+
lat: float = Field(ge=-90, le=90)
|
|
68
|
+
swetr: Literal[0, 1]
|
|
69
|
+
swdivide: Literal[0, 1]
|
|
70
|
+
# TODO: SWRAIN should be optional, but Fortran code evaluates its presence anyway
|
|
71
|
+
swrain: Optional[Literal[0, 1, 2, 3]] = 0
|
|
72
|
+
# TODO: SWETSINE should be optional, but Fortran code evaluates its presence anyway
|
|
73
|
+
swetsine: Literal[0, 1] = 0
|
|
74
|
+
metfile: Optional[MetFile] = Field(
|
|
75
|
+
default=None, repr=False)
|
|
76
|
+
alt: float = Field(ge=-400.0, le=3000.0)
|
|
77
|
+
altw: float = Field(default=None, ge=0.0, le=99.0)
|
|
78
|
+
angstroma: float = Field(default=None, **UNITRANGE)
|
|
79
|
+
angstromb: float = Field(default=None, **UNITRANGE)
|
|
80
|
+
swmetdetail: Optional[Literal[0, 1]] = None
|
|
81
|
+
table_rainflux: Optional[Table] = None
|
|
82
|
+
rainfil: Optional[str] = None
|
|
83
|
+
nmetdetail: Optional[int] = Field(default=None, ge=1, le=96)
|
|
84
|
+
|
|
85
|
+
@model_validator(mode='after')
|
|
86
|
+
def _validate_meteo_section(self):
|
|
87
|
+
|
|
88
|
+
if self.swetr == 1: # if PM method is NOT used
|
|
89
|
+
assert self.swetsine is not None, "SWETSINE is required when SWETR is 1"
|
|
90
|
+
assert self.swrain is not None, "SWRAIN is required when SWETR is 1"
|
|
91
|
+
if self.swrain == 1:
|
|
92
|
+
assert self.table_rainflux is not None, "RAINFLUX is required when SWRAIN is 1"
|
|
93
|
+
elif self.swrain == 3:
|
|
94
|
+
assert self.rainfil, "RAINFIL is required when SWRAIN is 3"
|
|
95
|
+
|
|
96
|
+
else:
|
|
97
|
+
assert self.alt is not None, "alt settings are required when SWETR is 0"
|
|
98
|
+
assert self.altw is not None, "altw settings are required when SWETR is 0"
|
|
99
|
+
assert self.angstroma is not None, "angstroma settings are required when SWETR is 0"
|
|
100
|
+
assert self.angstromb is not None, "angstromb settings are required when SWETR is 0"
|
|
101
|
+
assert self.swmetdetail is not None, "SWMETDETAIL is required when SWETR is 0"
|
|
102
|
+
if self.swmetdetail == 1:
|
|
103
|
+
assert self.nmetdetail is not None, "NMETDETAIL is required when SWMETDETAIL is 1"
|
|
104
|
+
|
|
105
|
+
def write_met(self, path: str):
|
|
106
|
+
"""Write the .met file.
|
|
107
|
+
|
|
108
|
+
!!! note
|
|
109
|
+
|
|
110
|
+
in this function the extension is not passed because
|
|
111
|
+
swp file requires the metfile parameter to be passed already with
|
|
112
|
+
the extension.
|
|
113
|
+
|
|
114
|
+
Parameters:
|
|
115
|
+
path (str): Path to the file.
|
|
116
|
+
"""
|
|
117
|
+
save_file(
|
|
118
|
+
string=self.metfile.content.to_csv(index=False),
|
|
119
|
+
fname=self.metfile.metfil,
|
|
120
|
+
path=path
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
print(f'{self.metfile.metfil} saved.')
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Getting and formatting meteorological data for SWAP similation.
|
|
3
|
+
|
|
4
|
+
Classes:
|
|
5
|
+
MetFile: meteorological data for the .met file
|
|
6
|
+
|
|
7
|
+
Functions:
|
|
8
|
+
load_from_csv: loading meteorological data from a CSV file
|
|
9
|
+
load_from_knmi: retrieving meteorological data from KNMI API
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from typing import Optional, Literal
|
|
13
|
+
from pandas import read_csv
|
|
14
|
+
from datetime import datetime as dt
|
|
15
|
+
from knmi import get_day_data_dataframe, get_hour_data_dataframe
|
|
16
|
+
from ..core import PySWAPBaseModel
|
|
17
|
+
from ..core import CSVTable
|
|
18
|
+
from pydantic import Field
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class MetFile(PySWAPBaseModel):
|
|
22
|
+
"""Meteorological data for the .met file.
|
|
23
|
+
|
|
24
|
+
This object is created by functions fetching or loading meteorological data
|
|
25
|
+
from various sources. The data is stored as a pandas.DataFrame, but is formatted
|
|
26
|
+
with a custom field serializer of the CSVTable field type.
|
|
27
|
+
|
|
28
|
+
Attributes:
|
|
29
|
+
metfil (str): name of the .met file
|
|
30
|
+
content (CSVTable): meteorological data file
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
metfil: str
|
|
34
|
+
content: Optional[CSVTable] = Field(default=None, exclude=True)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def load_from_csv(metfil: str, csv_path: str, **kwargs) -> MetFile:
|
|
38
|
+
"""Method for loading meteorological data from a CSV file.
|
|
39
|
+
|
|
40
|
+
Parameters:
|
|
41
|
+
metfil (str): name of the .met file
|
|
42
|
+
csv_path (str): path to the CSV file
|
|
43
|
+
**kwargs (dict): keyword arguments for pandas.read_csv
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
MetFile object.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
return MetFile(metfil=metfil, content=read_csv(csv_path, **kwargs))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def load_from_knmi(metfil: str,
|
|
53
|
+
stations: str | list,
|
|
54
|
+
variables: str | list = [
|
|
55
|
+
'TEMP', 'PRCP', 'Q', 'UG', 'FG', 'UX', 'UN'],
|
|
56
|
+
start: str | dt = '20000101',
|
|
57
|
+
end: str | dt = '20200101',
|
|
58
|
+
frequency: Literal['day', 'hour'] = 'day',
|
|
59
|
+
inseason: bool = False) -> MetFile:
|
|
60
|
+
"""Retrieves the meteorological data from KNMI API using knmi-py.
|
|
61
|
+
|
|
62
|
+
Parameters:
|
|
63
|
+
metfil (str): name of the .met file
|
|
64
|
+
stations (str | list): station number(s) to retrieve data from
|
|
65
|
+
variables (str | list): variables to retrieve
|
|
66
|
+
start (str | dt): start date of the data
|
|
67
|
+
end (str | dt): end date of the data
|
|
68
|
+
frequency (Literal['day', 'hour']): frequency of the data (day or hour)
|
|
69
|
+
inseason (bool): whether to retrieve in-season data
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
MetFile object.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
if isinstance(stations, str):
|
|
76
|
+
stations = [stations]
|
|
77
|
+
if isinstance(variables, str):
|
|
78
|
+
variables = [variables]
|
|
79
|
+
|
|
80
|
+
get_func = get_day_data_dataframe if frequency == 'day' else get_hour_data_dataframe
|
|
81
|
+
|
|
82
|
+
df = get_func(stations=stations,
|
|
83
|
+
start=start,
|
|
84
|
+
end=end,
|
|
85
|
+
variables=variables,
|
|
86
|
+
inseason=inseason)
|
|
87
|
+
|
|
88
|
+
# rename some columns
|
|
89
|
+
required_column_names = {'STN': 'Station',
|
|
90
|
+
'TN': 'Tmin',
|
|
91
|
+
'TX': 'Tmax',
|
|
92
|
+
'UG': 'HUM',
|
|
93
|
+
'DR': 'WET',
|
|
94
|
+
'FG': 'WIND',
|
|
95
|
+
'RH': 'RAIN',
|
|
96
|
+
'EV24': 'ETref',
|
|
97
|
+
'Q': 'RAD'}
|
|
98
|
+
|
|
99
|
+
df = df.rename(columns=required_column_names)
|
|
100
|
+
|
|
101
|
+
# recalculation of the parameters
|
|
102
|
+
df[['Tmin', 'Tmax', 'ETref', 'RAIN', 'WIND']] = df[['Tmin', 'Tmax', 'ETref', 'RAIN',
|
|
103
|
+
'WIND']] * 0.1 # the original unit is 0.1 Unit
|
|
104
|
+
df['WET'] = df['WET'] * \
|
|
105
|
+
0.1 * 24 # the required unit is days
|
|
106
|
+
|
|
107
|
+
return MetFile(metfil=metfil, content=df)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from ..core.tablevalidation import BaseModel
|
|
2
|
+
from pandera.typing import Series
|
|
3
|
+
import pandera as pa
|
|
4
|
+
|
|
5
|
+
class DAILYMETEODATA(BaseModel):
|
|
6
|
+
Station: Series[str]
|
|
7
|
+
DD: Series[str]
|
|
8
|
+
MM: Series[str]
|
|
9
|
+
YYYY: Series[str]
|
|
10
|
+
RAD: Series[float]
|
|
11
|
+
Tmin: Series[float]
|
|
12
|
+
Tmax: Series[float]
|
|
13
|
+
HUM: Series[float]
|
|
14
|
+
WIND: Series[float]
|
|
15
|
+
RAIN: Series[float]
|
|
16
|
+
ETref: Series[float]
|
|
17
|
+
WET: Series[float]
|
|
18
|
+
|
|
19
|
+
class SHORTINTERVALMETEODATA(BaseModel):
|
|
20
|
+
Date: Series[pa.DateTime]
|
|
21
|
+
Record: Series[int] = pa.Field(ge=1, le=10)
|
|
22
|
+
Rad: Series[float]
|
|
23
|
+
Temp: Series[float]
|
|
24
|
+
Hum: Series[float]
|
|
25
|
+
Wind: Series[float]
|
|
26
|
+
Rain: Series[float]
|
|
27
|
+
|
|
28
|
+
class DETAILEDRAINFALL(BaseModel):
|
|
29
|
+
Station: Series[str]
|
|
30
|
+
Day: Series[int]
|
|
31
|
+
Month: Series[int]
|
|
32
|
+
Year: Series[int]
|
|
33
|
+
Time: Series[float]
|
|
34
|
+
Amount: Series[float]
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Bottom boundary condition settings for the SWAP model.
|
|
3
|
+
|
|
4
|
+
Classes:
|
|
5
|
+
BottomBoundary: Holds the settings of the bottom boundary conditions of the .swp file.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Optional, Literal
|
|
9
|
+
from pydantic import model_validator, Field
|
|
10
|
+
from ..core import PySWAPBaseModel
|
|
11
|
+
from ..core import Table
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class BottomBoundary(PySWAPBaseModel):
|
|
15
|
+
"""
|
|
16
|
+
Bottom boundary settings for SWAP model.
|
|
17
|
+
|
|
18
|
+
Attributes:
|
|
19
|
+
swbbcfile (Literal[0, 1]): Switch for file with bottom boundary data:
|
|
20
|
+
|
|
21
|
+
* 0 - data are specified in current file
|
|
22
|
+
* 1 - data are specified in separate file
|
|
23
|
+
|
|
24
|
+
swbotb (Literal[1, 2, 3, 4, 5, 6, 7, 8]): Switch for type of bottom boundary.
|
|
25
|
+
|
|
26
|
+
* 1 - prescribe groundwater level;
|
|
27
|
+
* 2 - prescribe bottom flux;
|
|
28
|
+
* 3 - calculate bottom flux from hydraulic head of deep aquifer;
|
|
29
|
+
* 4 - calculate bottom flux as function of groundwater level;
|
|
30
|
+
* 5 - prescribe soil water pressure head of bottom compartment;
|
|
31
|
+
* 6 - bottom flux equals zero;
|
|
32
|
+
* 7 - free drainage of soil profile;
|
|
33
|
+
* 8 - free outflow at soil-air interface.
|
|
34
|
+
|
|
35
|
+
sw2 (Optional[Literal[1, 2]]): Specify whether a sinus function or a table are used for the bottom flux.
|
|
36
|
+
|
|
37
|
+
* 1 - sinus function;
|
|
38
|
+
* 2 - table.
|
|
39
|
+
|
|
40
|
+
sw3 (Optional[Literal[1, 2]]): Specify whether a sinus function or a table are used for the hydraulic head in the deep aquifer.
|
|
41
|
+
|
|
42
|
+
* 1 - sinus function;
|
|
43
|
+
* 2 - table.
|
|
44
|
+
|
|
45
|
+
sw4 (Optional[Literal[0, 1]]): An extra groundwater flux can be specified which is added to above specified flux.
|
|
46
|
+
|
|
47
|
+
* 0 - no extra flux;
|
|
48
|
+
* 1 - extra flux.
|
|
49
|
+
|
|
50
|
+
swbotb3resvert (Optional[Literal[0, 1]]): Switch for vertical hydraulic resistance between bottom boundary and groundwater level.
|
|
51
|
+
|
|
52
|
+
* 0 - Include vertical hydraulic resistance
|
|
53
|
+
* 1 - Suppress vertical hydraulic resistance
|
|
54
|
+
|
|
55
|
+
swbotb3impl (Optional[Literal[0, 1]]): Switch for numerical solution of bottom flux.
|
|
56
|
+
|
|
57
|
+
* 0 - Explicit solution (choose always when SHAPE < 1.0);
|
|
58
|
+
* 1 - Implicit solution.
|
|
59
|
+
|
|
60
|
+
swqhbot (Optional[Literal[1, 2]]): Specify whether an exponential relation or a table is used.
|
|
61
|
+
|
|
62
|
+
* 1 - bottom flux is calculated with an exponential relation
|
|
63
|
+
* 2 - bottom flux is derived from a table
|
|
64
|
+
|
|
65
|
+
bbcfile (Optional[str]): Name of file with bottom boundary data (without .BBC extension).
|
|
66
|
+
sinave (Optional[float]): Average value of bottom flux.
|
|
67
|
+
sinamp (Optional[float]): Amplitude of bottom flux sine function.
|
|
68
|
+
sinmax (Optional[float]): Time of the year with maximum bottom flux.
|
|
69
|
+
shape (Optional[float]): Shape factor to derive average groundwater level.
|
|
70
|
+
hdrain (Optional[float]): Mean drain base to correct for average groundwater level.
|
|
71
|
+
rimlay (Optional[float]): Vertical resistance of aquitard.
|
|
72
|
+
aqave (Optional[float]): Average hydraulic head in underlaying aquifer.
|
|
73
|
+
aqamp (Optional[float]): Amplitude hydraulic head sinus wave.
|
|
74
|
+
aqtmax (Optional[float]): First time of the year with maximum hydraulic head.
|
|
75
|
+
aqper (Optional[float]): Period of hydraulic head sinus wave.
|
|
76
|
+
cofqha (Optional[float]): Coefficient A for exponential relation for bottom flux.
|
|
77
|
+
cofqhb (Optional[float]): Coefficient B for exponential relation for bottom flux.
|
|
78
|
+
cofqhc (Optional[float]): Coefficient C for exponential relation for bottom flux.
|
|
79
|
+
gwlevel (Optional[Table]): Table with groundwater level data.
|
|
80
|
+
table_qbot (Optional[Table]): Table with bottom flux data.
|
|
81
|
+
table_haquif (Optional[Table]): Table with average pressure head in underlaying aquifer.
|
|
82
|
+
table_qbot4 (Optional[Table]): Table with bottom flux data.
|
|
83
|
+
table_qtab (Optional[Table]): Table with groundwater level-bottom flux relation
|
|
84
|
+
table_hbot (Optional[Table]): Table with the bottom compartment pressure head.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
swbbcfile: Literal[0, 1]
|
|
88
|
+
swbotb: Literal[1, 2, 3, 4, 5, 6, 7, 8]
|
|
89
|
+
sw2: Optional[Literal[1, 2]] = None
|
|
90
|
+
sw3: Optional[Literal[1, 2]] = None
|
|
91
|
+
sw4: Optional[Literal[0, 1]] = None
|
|
92
|
+
swbotb3resvert: Optional[Literal[0, 1]] = None
|
|
93
|
+
swbotb3impl: Optional[Literal[0, 1]] = None
|
|
94
|
+
swqhbot: Optional[Literal[1, 2]] = None
|
|
95
|
+
bbcfile: Optional[str] = None
|
|
96
|
+
sinave: Optional[float] = Field(ge=-10.0, le=10.0, default=None)
|
|
97
|
+
sinamp: Optional[float] = Field(ge=-10.0, le=10.0, default=None)
|
|
98
|
+
sinmax: Optional[float] = Field(ge=0.0, le=366.0, default=None)
|
|
99
|
+
shape: Optional[float] = None
|
|
100
|
+
hdrain: Optional[float] = None
|
|
101
|
+
rimlay: Optional[float] = None
|
|
102
|
+
aqave: Optional[float] = None
|
|
103
|
+
aqamp: Optional[float] = None
|
|
104
|
+
aqtmax: Optional[float] = None
|
|
105
|
+
aqper: Optional[float] = None
|
|
106
|
+
cofqha: Optional[float] = None
|
|
107
|
+
cofqhb: Optional[float] = None
|
|
108
|
+
cofqhc: Optional[float] = None
|
|
109
|
+
table_gwlevel: Optional[Table] = None
|
|
110
|
+
table_qbot: Optional[Table] = None
|
|
111
|
+
table_haquif: Optional[Table] = None
|
|
112
|
+
table_qbot4: Optional[Table] = None
|
|
113
|
+
table_qtab: Optional[Table] = None
|
|
114
|
+
table_hbot5: Optional[Table] = None
|
|
115
|
+
|
|
116
|
+
@model_validator(mode='after')
|
|
117
|
+
def _check_swbotb(self):
|
|
118
|
+
if self.swbotb == 1:
|
|
119
|
+
assert self.gwlevel, 'gwlevel must be provided if swbotb is 1'
|
|
120
|
+
elif self.swbotb == 2:
|
|
121
|
+
assert self.sw2, 'sw2 must be provided if swbotb is 2'
|
|
122
|
+
if self.sw2 == 1:
|
|
123
|
+
assert self.sinave, 'sinave must be provided if sw2 is 1'
|
|
124
|
+
assert self.sinamp, 'sinamp must be provided if sw2 is 1'
|
|
125
|
+
assert self.sinmax, 'sinmax must be provided if sw2 is 1'
|
|
126
|
+
elif self.sw2 == 2:
|
|
127
|
+
assert self.table_qbot, 'qbot must be provided if sw2 is 2'
|
|
128
|
+
elif self.swbotb == 3:
|
|
129
|
+
assert self.sw3, 'sw3 must be provided if swbotb is 3'
|
|
130
|
+
if self.sw3 == 1:
|
|
131
|
+
assert self.aqave, 'aqave must be provided if sw3 is 1'
|
|
132
|
+
assert self.aqamp, 'auamp must be provided if sw3 is 1'
|
|
133
|
+
assert self.aqtmax, 'aqtmax must be provided if sw3 is 1'
|
|
134
|
+
assert self.aqper, 'aqper must be provided if sw3 is 1'
|
|
135
|
+
elif self.sw3 == 2:
|
|
136
|
+
assert self.table_haquif, 'haquif must be provided if sw3 is 2'
|
|
137
|
+
elif self.swbotb == 4:
|
|
138
|
+
assert self.swqhbot, 'swqhbot must be provided if swbotb is 4'
|
|
139
|
+
if self.swqhbot == 1:
|
|
140
|
+
assert self.cofqha, 'cofqha must be provided if swqhbot is 1'
|
|
141
|
+
assert self.cofqhb, 'cofqhb must be provided if swqhbot is 1'
|
|
142
|
+
assert self.cofqhc, 'cofqhc must be provided if swqhbot is 1'
|
|
143
|
+
elif self.swqhbot == 2:
|
|
144
|
+
assert self.table_qtab, 'qtab must be provided if swqhbot is 2'
|
|
145
|
+
elif self.swbotb == 5:
|
|
146
|
+
assert self.table_hbot5, 'hbot5 must be provided if swbotb is 5'
|
pyswap/core/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""
|
|
2
|
+
# Core subpackage
|
|
3
|
+
|
|
4
|
+
Core package containing the main classes and functions for the SWAP model.
|
|
5
|
+
|
|
6
|
+
Modules:
|
|
7
|
+
basemodel: Base model class for pySWAP.
|
|
8
|
+
fields: Field types for pyswap used for serialization.
|
|
9
|
+
files: Functions to interact with file system.
|
|
10
|
+
serializers: Functions to fine tune the serializatino of pySWAP objects.
|
|
11
|
+
valueranges: Objects containing value ranges used is validation of pySWAP objects.
|
|
12
|
+
model: Contains the classes for the model of the simulation.
|
|
13
|
+
result: Contains the classes for the results of the simulation.
|
|
14
|
+
___________________________________________________________________________
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from .basemodel import *
|
|
18
|
+
from .fields import *
|
|
19
|
+
from .files import *
|
|
20
|
+
from .serializers import *
|
|
21
|
+
from .valueranges import *
|
|
22
|
+
from .tablevalidation import *
|
pyswap/core/basemodel.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from pydantic import BaseModel, ConfigDict
|
|
3
|
+
from .serializers import quote_string
|
|
4
|
+
from .files import save_file
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class PySWAPBaseModel(BaseModel):
|
|
8
|
+
"""Base class for PySWAP models.
|
|
9
|
+
|
|
10
|
+
Attributes:
|
|
11
|
+
model_config (ConfigDict): Overriding Pydantic model configuration.
|
|
12
|
+
|
|
13
|
+
Methods:
|
|
14
|
+
save_element: Saves model element to a file.
|
|
15
|
+
model_string: Returns a custom model string representation that matches the requirements of .swp file.
|
|
16
|
+
_concat_sections: Concatenate a string from individual sections.
|
|
17
|
+
model_string: Returns a custom model string representation that matches the requirements of .swp file.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
model_config = ConfigDict(
|
|
21
|
+
arbitrary_types_allowed=True,
|
|
22
|
+
validate_assignment=True,
|
|
23
|
+
extra='forbid'
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
@staticmethod
|
|
27
|
+
def save_element(string: str, path: str, filename: str, extension: str | None = None) -> str:
|
|
28
|
+
"""Saves model element to a file.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
string (str): String to be saved.
|
|
32
|
+
path (str): Path to the file.
|
|
33
|
+
filename (str): File name.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
str: Success message.
|
|
37
|
+
"""
|
|
38
|
+
save_file(
|
|
39
|
+
string=string,
|
|
40
|
+
fname=filename,
|
|
41
|
+
extension=extension,
|
|
42
|
+
path=path
|
|
43
|
+
)
|
|
44
|
+
return f'{filename}.{extension} saved successfully.'
|
|
45
|
+
|
|
46
|
+
def model_string(self) -> str:
|
|
47
|
+
"""Returns a custom model string representation that matches the requirements of .swp file.
|
|
48
|
+
|
|
49
|
+
Note:
|
|
50
|
+
If values are simple types, they are formatted as 'ATTR = VALUE'. If the valies are
|
|
51
|
+
tables (in pySWAP pd.DataFrame are used), they are formatted simply as 'TABLE_VALUE'. Additionally,
|
|
52
|
+
a custom serializer (pyswap.core.utils.serializers.quote_string) is used to quote strings.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
str: Custom model string representation.
|
|
56
|
+
"""
|
|
57
|
+
string = ''
|
|
58
|
+
|
|
59
|
+
def formatter(attr, value, string):
|
|
60
|
+
if attr.startswith('table_') or attr.startswith('list_'):
|
|
61
|
+
return string + value
|
|
62
|
+
else:
|
|
63
|
+
return string + f'{attr.upper()} = {quote_string(value)}\n'
|
|
64
|
+
|
|
65
|
+
for attr, value in self.model_dump(
|
|
66
|
+
mode='json', exclude_none=True).items():
|
|
67
|
+
if isinstance(value, dict):
|
|
68
|
+
for k, v in value.items():
|
|
69
|
+
string = formatter(k, v, string)
|
|
70
|
+
else:
|
|
71
|
+
string = formatter(attr, value, string)
|
|
72
|
+
|
|
73
|
+
return string
|
|
74
|
+
|
|
75
|
+
def _concat_sections(self) -> str:
|
|
76
|
+
"""Concatenate a string from individual sections.
|
|
77
|
+
|
|
78
|
+
This method is meant to be used on models that collect other
|
|
79
|
+
models, like DraFile, or Model.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
string = ''
|
|
83
|
+
for k, v in dict(self).items():
|
|
84
|
+
if v is None or isinstance(v, str):
|
|
85
|
+
continue
|
|
86
|
+
string += v.model_string()
|
|
87
|
+
return string
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""
|
|
2
|
+
All modules related to the database connection and models.
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
!!! warning
|
|
6
|
+
This module is in review and may be significantly changed or removed in the future.
|
|
7
|
+
|
|
8
|
+
!!! tip
|
|
9
|
+
pySWAP is meant to enable saving model runs to a SQLite database. That way, the users will be
|
|
10
|
+
able to easily exchange models they built and run them on their own machines.
|
|
11
|
+
"""
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This module is responsible for creating a connection to the database.
|
|
3
|
+
|
|
4
|
+
Classes:
|
|
5
|
+
DatabaseConnection: Creates a connection to the database.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from sqlalchemy import create_engine, inspect
|
|
9
|
+
from sqlalchemy.orm import sessionmaker
|
|
10
|
+
import os
|
|
11
|
+
from .models import Base
|
|
12
|
+
|
|
13
|
+
"""
|
|
14
|
+
TODO: Implement an option to use different databases like MySQL, PostgreSQL, etc.
|
|
15
|
+
TODO: Implement a way to dump a database like postgresql, mysql, etc. to sqlite.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class DatabaseConnection:
|
|
20
|
+
"""Creates a connection to the database.
|
|
21
|
+
|
|
22
|
+
Upon calling the connect method, a check is made to see if the database file
|
|
23
|
+
exists. If it does not, the file is created. The tables are then checked
|
|
24
|
+
and created if they do not exist.
|
|
25
|
+
|
|
26
|
+
Attributes:
|
|
27
|
+
engine: The database engine.
|
|
28
|
+
session: The database session.
|
|
29
|
+
db_path: The path to the database file.
|
|
30
|
+
|
|
31
|
+
Methods:
|
|
32
|
+
connect: Connect to the database.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(self, db_path: str = 'pyswap.db'):
|
|
36
|
+
self.engine = None
|
|
37
|
+
self.session = None
|
|
38
|
+
self.db_path = db_path
|
|
39
|
+
self.connect()
|
|
40
|
+
|
|
41
|
+
def connect(self):
|
|
42
|
+
"""Connect to the dabase or create a new one."""
|
|
43
|
+
if os.path.exists(self.db_path):
|
|
44
|
+
if os.path.isfile(self.db_path):
|
|
45
|
+
print("Database exists. Connecting...")
|
|
46
|
+
|
|
47
|
+
else:
|
|
48
|
+
print("Database does not exist. Creating...")
|
|
49
|
+
|
|
50
|
+
self.engine = create_engine(f'sqlite:///{self.db_path}')
|
|
51
|
+
session = sessionmaker(bind=self.engine)
|
|
52
|
+
self.session = session()
|
|
53
|
+
|
|
54
|
+
# Check if tables exist in the database
|
|
55
|
+
inspector = inspect(self.engine)
|
|
56
|
+
table_names = inspector.get_table_names()
|
|
57
|
+
|
|
58
|
+
for table in Base.metadata.tables.keys():
|
|
59
|
+
if table not in table_names:
|
|
60
|
+
print(
|
|
61
|
+
f"Table {table} does not exist in the database. Creating...")
|
|
62
|
+
Base.metadata.tables[table].create(self.engine)
|
|
63
|
+
else:
|
|
64
|
+
print(f"Table {table} exists in the database.")
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
from sqlalchemy.orm import state, session
|
|
2
|
+
|
|
3
|
+
from models import ModelRun, SWAPModel
|
|
4
|
+
from sqlalchemy import event, text, func, bindparam, select, insert
|
|
5
|
+
from sqlalchemy.orm import Session
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@event.listens_for(ModelRun, 'before_insert')
|
|
9
|
+
def auto_set_iteration(mapper, connection, target):
|
|
10
|
+
|
|
11
|
+
query = select(func.max(ModelRun.iteration)).where(ModelRun.model_id == bindparam('model_id')).\
|
|
12
|
+
params(model_id=target.model_id)
|
|
13
|
+
|
|
14
|
+
result = connection.execute(query).scalar()
|
|
15
|
+
|
|
16
|
+
max_iteration = result if result is not None else 0
|
|
17
|
+
target.iteration = max_iteration + 1
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# This would be a more elegant solution, but it doesn't work. There might be a something wrong with the way
|
|
21
|
+
# I use session.
|
|
22
|
+
|
|
23
|
+
# @event.listens_for(SWAPModel, 'after_insert')
|
|
24
|
+
# def auto_create_iteration(mapper, connection, target):
|
|
25
|
+
# # Prepare the insert statement
|
|
26
|
+
# stmt = insert(ModelIteration).values(
|
|
27
|
+
# model_id=target.id,
|
|
28
|
+
# iteration=1,
|
|
29
|
+
# swp_change={},
|
|
30
|
+
# drainage_change={},
|
|
31
|
+
# crop_change={},
|
|
32
|
+
# met_change=None
|
|
33
|
+
# )
|
|
34
|
+
#
|
|
35
|
+
# # Execute the statement
|
|
36
|
+
# connection.execute(stmt)
|