tilupy 2.0.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.
tilupy/calibration.py ADDED
@@ -0,0 +1,134 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ from tilupy import read
7
+ from tilupy import utils
8
+ from tilupy import raster
9
+
10
+
11
+ def CSI(simu, observation=None, h_threshs=[1], state="h_final"):
12
+ res = []
13
+ assert observation is not None
14
+
15
+ if isinstance(observation, str):
16
+ _, _, observation, _ = raster.read_raster(observation)
17
+
18
+ if state == "h_max":
19
+ d = simu.h_max
20
+ else:
21
+ d = simu.get_output(state).d
22
+ for h_thresh in h_threshs:
23
+ array = 1 * d > h_thresh
24
+ res.append(utils.CSI(array, observation))
25
+
26
+ return h_threshs, res
27
+
28
+
29
+ def diff_runout(
30
+ simu,
31
+ point=None,
32
+ h_threshs=[1],
33
+ section=None,
34
+ orientation="W-E",
35
+ state="h_max",
36
+ get_contour_kws=None,
37
+ ):
38
+ res = []
39
+ assert point is not None
40
+
41
+ if get_contour_kws is None:
42
+ get_contour_kws = dict()
43
+
44
+ if state == "h_max":
45
+ d = simu.h_max
46
+ else:
47
+ d = simu.get_output(state).d
48
+ xc, yc = utils.get_contour(simu.x, simu.y, d, h_threshs, **get_contour_kws)
49
+
50
+ for h in h_threshs:
51
+ res.append(
52
+ utils.diff_runout(
53
+ xc[h], yc[h], point, section=section, orientation=orientation
54
+ )
55
+ )
56
+
57
+ return h_threshs, res
58
+
59
+
60
+ def eval_simus(
61
+ simus,
62
+ methods,
63
+ calib_parameters,
64
+ methods_kws,
65
+ code="shaltop",
66
+ recorded_params=["delta1"],
67
+ calib_parameter_name="h_threshs",
68
+ ):
69
+ """
70
+ Evaluate simulation results with different methods
71
+
72
+ Parameters
73
+ ----------
74
+ simus : TYPE
75
+ DESCRIPTION.
76
+ methods : TYPE
77
+ DESCRIPTION.
78
+
79
+ Returns
80
+ -------
81
+ None.
82
+
83
+ """
84
+ if not isinstance(methods, list):
85
+ methods = [methods]
86
+ if not isinstance(methods_kws, list):
87
+ methods_kws = [methods_kws]
88
+
89
+ if isinstance(simus, dict):
90
+ simus = pd.DataFrame(simus)
91
+ if isinstance(simus, pd.DataFrame):
92
+ simus_list = []
93
+ for i in range(simus.shape[0]):
94
+ simus_list.append(
95
+ read.get_results(code, **simus.iloc[i, :].to_dict())
96
+ )
97
+ simus2 = simus.copy()
98
+ else:
99
+ simus_list = simus
100
+ simus2 = pd.DataFrame()
101
+
102
+ for param in recorded_params:
103
+ simus2[param] = np.nan
104
+ fn = dict()
105
+ for method in methods:
106
+ fn[method] = globals()[method]
107
+ simus2[method] = np.nan
108
+ simus2[calib_parameter_name] = np.nan
109
+
110
+ ns = len(simus_list)
111
+ nc = len(calib_parameters)
112
+ nn = ns * nc
113
+
114
+ res = pd.DataFrame(columns=simus2.columns, index=np.arange(nn))
115
+
116
+ for i, simu in enumerate(simus_list):
117
+ # Initiate fields
118
+ istart = i * nc
119
+ iend = (i + 1) * nc
120
+ res.iloc[istart:iend, :] = simus2.loc[i, :].copy()
121
+ for j, method in enumerate(methods):
122
+ kws = methods_kws[j]
123
+ kws[calib_parameter_name] = calib_parameters
124
+ _, calib_res = fn[method](simu, **kws)
125
+ for param in recorded_params:
126
+ res.iloc[
127
+ istart:iend, res.columns.get_loc(param)
128
+ ] = simu.params[param]
129
+ res.iloc[
130
+ istart:iend, res.columns.get_loc(calib_parameter_name)
131
+ ] = calib_parameters
132
+ res.iloc[istart:iend, res.columns.get_loc(method)] = calib_res
133
+
134
+ return res
tilupy/cmd.py ADDED
@@ -0,0 +1,177 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import tilupy.read
4
+ # import tilupy.raster
5
+
6
+ import os
7
+ import argparse
8
+ import glob
9
+
10
+
11
+ def process_results(
12
+ fn_name,
13
+ model,
14
+ res_name,
15
+ folder=None,
16
+ param_files=None,
17
+ kwargs_read=None,
18
+ **kwargs_fn
19
+ ):
20
+ assert model is not None
21
+
22
+ if folder is None:
23
+ folder = os.getcwd()
24
+
25
+ if param_files is None:
26
+ param_files = "*.txt"
27
+
28
+ print(folder, param_files)
29
+
30
+ param_files = [
31
+ os.path.basename(x)
32
+ for x in glob.glob(os.path.join(folder, param_files))
33
+ ]
34
+
35
+ if len(param_files) == 0:
36
+ print("No parameter file matching param_files pattern was found")
37
+ return
38
+
39
+ if kwargs_read is None:
40
+ kwargs_read = dict()
41
+
42
+ kw_read = dict(folder=folder)
43
+ kw_read.update(kwargs_read)
44
+
45
+ for param_file in param_files:
46
+ print_str = "Processing simulation {:s}, {:s} {:s} ....."
47
+ print(print_str.format(param_file, fn_name, res_name))
48
+ kw_read["file_params"] = param_file
49
+ res = tilupy.read.get_results(model, **kw_read)
50
+ getattr(res, fn_name)(res_name, **kwargs_fn)
51
+
52
+
53
+ def to_raster(
54
+ model=None,
55
+ res_name="h",
56
+ param_files=None,
57
+ folder=None,
58
+ kwargs_read=None,
59
+ **kwargs
60
+ ):
61
+ kw = dict(fmt="asc")
62
+ kw.update(kwargs)
63
+
64
+ process_results(
65
+ "save",
66
+ model,
67
+ res_name,
68
+ folder=folder,
69
+ param_files=param_files,
70
+ kwargs_read=kwargs_read,
71
+ **kw
72
+ )
73
+
74
+
75
+ def plot_results(
76
+ model=None,
77
+ res_name="h",
78
+ param_files=None,
79
+ folder=None,
80
+ kwargs_read=None,
81
+ **kwargs
82
+ ):
83
+ kw = dict(save=True)
84
+ kw.update(kwargs)
85
+
86
+ process_results(
87
+ "plot",
88
+ model,
89
+ res_name,
90
+ folder=folder,
91
+ param_files=param_files,
92
+ kwargs_read=kwargs_read,
93
+ **kwargs
94
+ )
95
+
96
+
97
+ def _get_parser(prog, description):
98
+ parser = argparse.ArgumentParser(
99
+ prog=prog,
100
+ description=description,
101
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
102
+ )
103
+ parser.add_argument("model", help="Model name", type=str)
104
+ parser.add_argument(
105
+ "-n",
106
+ "--res_name",
107
+ help="Name of output, only for maps",
108
+ default="h",
109
+ type=str,
110
+ )
111
+ parser.add_argument(
112
+ "-p",
113
+ "--param_files",
114
+ help="Parameter file (globbing)",
115
+ default="*.txt",
116
+ type=str,
117
+ )
118
+ parser.add_argument(
119
+ "-f",
120
+ "--folder",
121
+ help="Root folder, default is current folder",
122
+ default=None,
123
+ type=str,
124
+ )
125
+ return parser
126
+
127
+
128
+ def _tilupy_plot():
129
+ parser = _get_parser("tilupy_plot", "Plot thin-layer simulation results")
130
+ parser.add_argument(
131
+ "--fmt",
132
+ help=("Plot output format " "(any accepted by matplotlib.savefig)"),
133
+ default="png",
134
+ type=str,
135
+ )
136
+ parser.add_argument(
137
+ "--vmin",
138
+ help=("Minimum plotted value, " "adapted to data by default"),
139
+ default=None,
140
+ type=float,
141
+ )
142
+ parser.add_argument(
143
+ "--vmax",
144
+ help=("Maximum plotted value, " "adapted to data by default"),
145
+ default=None,
146
+ type=float,
147
+ )
148
+ parser.add_argument(
149
+ "--minval_abs",
150
+ help=("Minimum plotted absolute value," " adapted to data by default"),
151
+ default=None,
152
+ type=float,
153
+ )
154
+ args = parser.parse_args()
155
+ plot_results(**vars(args))
156
+
157
+
158
+ def _tilupy_to_raster():
159
+ parser = _get_parser(
160
+ "tilupy_to_raster", "Convert simulation results to rasters"
161
+ )
162
+ parser.add_argument(
163
+ "--fmt",
164
+ help=("File output format, " "tif/tiff requires rasterio"),
165
+ default="asc",
166
+ type=str,
167
+ choices=["tif", "tiff", "txt", "asc", "ascii"],
168
+ )
169
+ args = parser.parse_args()
170
+ # plot_results(parser.model, parser.res_name)
171
+ to_raster(**vars(args))
172
+
173
+
174
+ if __name__ == "__main__":
175
+ # folder = 'd:/Documents/peruzzetto/tmp/test_shaltop/7p30e04_m3/coulomb'
176
+ # plot_results('shaltop', 'h_max', '*18p00.txt', folder=folder)
177
+ _tilupy_plot()
tilupy/compare.py ADDED
@@ -0,0 +1,195 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Wed Jun 2 17:57:31 2021
5
+
6
+ @author: peruzzetto
7
+ """
8
+
9
+ import importlib
10
+ import os
11
+ import string
12
+ import numpy as np
13
+ import matplotlib.pyplot as plt
14
+ import mpl_toolkits.axes_grid1 as mplt
15
+
16
+ # import tilupy.dem
17
+ import tilupy.plot as plt_fn
18
+ import tilupy.notations
19
+ import tilupy
20
+
21
+ from tilupy.notations import LABELS
22
+ from tilupy.read import STATIC_DATA_2D
23
+
24
+
25
+ def compare_spatial_results(results, name, stat, import_kwargs=None,
26
+ x=None, y=None, zinit=None,
27
+ nrows_ncols=None, figsize=None,
28
+ folder_out=None, file_prefix=None,
29
+ fmt='png', dpi=150,
30
+ cbar_location='bottom', cbar_size="5%",
31
+ cmap_intervals=None, cmap='inferno',
32
+ topo_kwargs=None,
33
+ title_loc='top right', title_x_offset=0.02,
34
+ title_y_offset=0.02):
35
+ """
36
+ Compare spatiale results of different simulations
37
+
38
+ Parameters
39
+ ----------
40
+ results : TYPE
41
+ DESCRIPTION.
42
+ name : TYPE
43
+ DESCRIPTION.
44
+ import_kwargs : TYPE, optional
45
+ DESCRIPTION. The default is None.
46
+ x : TYPE, optional
47
+ DESCRIPTION. The default is None.
48
+ y : TYPE, optional
49
+ DESCRIPTION. The default is None.
50
+ zinit : TYPE, optional
51
+ DESCRIPTION. The default is None.
52
+ figsize : TYPE, optional
53
+ DESCRIPTION. The default is None.
54
+ folder_out : TYPE, optional
55
+ DESCRIPTION. The default is None.
56
+ cbar_location : TYPE, optional
57
+ DESCRIPTION. The default is 'bottom'.
58
+ cbar_size : TYPE, optional
59
+ DESCRIPTION. The default is "5%".
60
+ cmap_intervals : TYPE, optional
61
+ DESCRIPTION. The default is None.
62
+ cmap : TYPE, optional
63
+ DESCRIPTION. The default is 'inferno'.
64
+ topo_kwargs : TYPE, optional
65
+ DESCRIPTION. The default is None.
66
+
67
+ Returns
68
+ -------
69
+ None.
70
+
71
+ """
72
+ if x is None or y is None:
73
+ results[0].set_axes()
74
+ x = results[0].x
75
+ y = results[0].y
76
+
77
+ if zinit is None:
78
+ results[0].set_zinit()
79
+ zinit = results[0].zinit
80
+
81
+ topo_kwargs = {} if topo_kwargs is None else topo_kwargs
82
+ import_kwargs = {} if import_kwargs is None else import_kwargs
83
+ nplots = len(results)
84
+ if nrows_ncols is None:
85
+ nrows_ncols = (1, nplots)
86
+
87
+ fig = plt.figure(figsize=figsize)
88
+ axes = mplt.AxesGrid(fig, 111,
89
+ nrows_ncols=nrows_ncols,
90
+ axes_pad=0.1,
91
+ share_all=True,
92
+ aspect='True',
93
+ label_mode='L',
94
+ cbar_location=cbar_location,
95
+ cbar_mode="single",
96
+ cbar_pad="12%",
97
+ cbar_size=cbar_size)
98
+
99
+ # Titles
100
+ alignments = title_loc.split(' ')
101
+ ha = alignments[1]
102
+ va = alignments[0]
103
+ if va == 'top':
104
+ xt = 1-title_x_offset
105
+ elif va == 'center':
106
+ xt = 0.5
107
+ elif va == 'bottom':
108
+ xt = title_x_offset
109
+ if ha == 'right':
110
+ yt = 1-title_y_offset
111
+ elif ha == 'center':
112
+ yt = 0.5
113
+ elif ha == 'bottom':
114
+ yt = title_y_offset
115
+
116
+ for i, result in enumerate(results):
117
+ data = result.get_static_output(name, stat, **import_kwargs)
118
+ plt_fn.plot_data_on_topo(x, y, zinit, data.d,
119
+ axe=axes[i],
120
+ plot_colorbar=False,
121
+ colorbar_kwargs={'extend': 'max'},
122
+ cmap_intervals=cmap_intervals,
123
+ cmap=cmap,
124
+ topo_kwargs=topo_kwargs)
125
+ letter = '({:s})'.format(string.ascii_lowercase[i])
126
+ axes[i].text(xt, yt, '{:s} {:s}'.format(letter, result.code),
127
+ ha=ha, va=va,
128
+ fontsize=11, zorder=100,
129
+ bbox=dict(boxstyle="round",
130
+ fc="w", ec="k", pad=0.2),
131
+ transform=axes[i].transAxes)
132
+ axes[i].grid(False)
133
+
134
+ # Colorbar
135
+ axe_cc = axes.cbar_axes[0]
136
+ if cbar_location in ['right', 'left']:
137
+ orientation = 'vertical'
138
+ else:
139
+ orientation = 'horizontal'
140
+ fig.colorbar(axes[0].images[-1],
141
+ cax=axe_cc,
142
+ ax=axes[0],
143
+ orientation=orientation,
144
+ extend='max')
145
+ if orientation == 'vertical':
146
+ axe_cc.set_ylabel(LABELS[name+stat])
147
+ else:
148
+ axe_cc.set_xlabel(LABELS[name+stat])
149
+
150
+ fig.tight_layout()
151
+
152
+ if folder_out is not None:
153
+ if file_prefix is None:
154
+ file = name + stat + '.' + fmt
155
+ else:
156
+ file = file_prefix + '_' + name + stat + '.' + fmt
157
+ fig.savefig(os.path.join(folder_out, file),
158
+ dpi=dpi)
159
+
160
+
161
+ def compare_simus(codes, topo_name, law,
162
+ rheol_params, output_name, stat_name,
163
+ subfolder_topo='',
164
+ folder_benchmark=None, folder_out=None, **kwargs):
165
+ """Compare simulations with different codes."""
166
+
167
+ modules = dict()
168
+ for c in codes:
169
+ modules[c] = importlib.import_module('tilupy.models.'+c+'.read')
170
+
171
+ if folder_benchmark is None:
172
+ folder_benchmark = os.getcwd()
173
+
174
+ folder_topo = os.path.join(folder_benchmark, topo_name)
175
+
176
+ txt_params = tilupy.notations.make_rheol_string(rheol_params, law)
177
+
178
+ if folder_out is None:
179
+ folder_out = os.path.join(folder_topo, subfolder_topo,
180
+ 'comparison', law)
181
+ os.makedirs(folder_out, exist_ok=True)
182
+
183
+ file = np.os.path.join(folder_topo, 'topo.asc')
184
+ x, y, zinit, dx = tilupy.dem.read_ascii(file)
185
+
186
+ simus = []
187
+ for code in codes:
188
+ folder_simus = os.path.join(folder_topo, subfolder_topo, code, law)
189
+ simus.append(modules[code].Results(txt_params, folder_simus))
190
+
191
+ if output_name+stat_name in STATIC_DATA_2D:
192
+ compare_spatial_results(simus, output_name, stat_name,
193
+ x=x, y=y, zinit=zinit,
194
+ folder_out=folder_out, file_prefix=txt_params,
195
+ **kwargs)
@@ -0,0 +1,68 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import requests
4
+ import os
5
+
6
+ def import_frankslide_dem(folder_out: str = None,
7
+ file_out: str = None
8
+ ) -> str:
9
+ """Import frankslide topography.
10
+
11
+ Parameters
12
+ ----------
13
+ folder_out : str, optional
14
+ Path to the folder output. If None the current folder will be choosed. By default None.
15
+ file_out : str, optional
16
+ Name of the file. If None choose "Frankslide_topography.asc". By default None.
17
+
18
+ Returns
19
+ -------
20
+ str
21
+ Path to the saved file.
22
+ """
23
+ if folder_out is None:
24
+ folder_out = '.'
25
+ if file_out is None:
26
+ file_out = 'Frankslide_topography.asc'
27
+
28
+ file_save = os.path.join(folder_out, file_out)
29
+
30
+ url = ('https://raw.githubusercontent.com/marcperuz/tilupy/main/data/'+
31
+ 'frankslide/rasters/Frankslide_topography.asc')
32
+ r = requests.get(url)
33
+ open(file_save, 'w').write(r.text)
34
+
35
+ return file_save
36
+
37
+
38
+ def import_frankslide_pile(folder_out: str = None,
39
+ file_out: str = None
40
+ ) -> str:
41
+ """Import frankslide pile.
42
+
43
+ Parameters
44
+ ----------
45
+ folder_out : str, optional
46
+ Path to the folder output. If None the current folder will be choosed. By default None.
47
+ file_out : str, optional
48
+ Name of the file. If None choose "Frankslide_pile.asc". By default None.
49
+
50
+ Returns
51
+ -------
52
+ str
53
+ Path to the saved file.
54
+ """
55
+
56
+ if folder_out is None:
57
+ folder_out = '.'
58
+ if file_out is None:
59
+ file_out = 'Frankslide_pile.asc'
60
+
61
+ file_save = os.path.join(folder_out, file_out)
62
+
63
+ url = ('https://raw.githubusercontent.com/marcperuz/tilupy/main/data/'+
64
+ 'frankslide/rasters/Frankslide_pile.asc')
65
+ r = requests.get(url)
66
+ open(file_save, 'w').write(r.text)
67
+
68
+ return file_save