pyStrata 0.5.3__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.
pystrata/tools.py ADDED
@@ -0,0 +1,299 @@
1
+ # -*- coding: utf-8 -*-
2
+ # The MIT License (MIT)
3
+ #
4
+ # Copyright (c) 2016-2018 Albert Kottke
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in
14
+ # all copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ import collections
24
+ import os
25
+ import re
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+ import scipy.constants as C
30
+
31
+ from . import motion
32
+ from . import propagation
33
+ from . import site
34
+
35
+
36
+ def to_str(s):
37
+ """Parse a string and strip the extra characters."""
38
+ return str(s).strip()
39
+
40
+
41
+ def to_float(s):
42
+ """Try to parse a float."""
43
+ try:
44
+ return float(s)
45
+ except ValueError:
46
+ return np.nan
47
+
48
+
49
+ def parse_fixed_width(types, lines):
50
+ """Parse a fixed width line."""
51
+ values = []
52
+ line = []
53
+ for width, parser in types:
54
+ if not line:
55
+ line = lines.pop(0).replace("\n", "")
56
+
57
+ values.append(parser(line[:width]))
58
+ line = line[width:]
59
+
60
+ return values
61
+
62
+
63
+ def split_line(line, parsers, sep=" "):
64
+ """Split a line into pieces and parse the strings."""
65
+ parts = [part for part in line.split(sep) if part]
66
+ values = [parser(part) for parser, part in zip(parsers, parts)]
67
+ return values if len(values) > 1 else values[0]
68
+
69
+
70
+ def _parse_curves(block, **kwargs):
71
+ """Parse nonlinear curves block."""
72
+ count = int(block.pop(0))
73
+
74
+ curves = []
75
+ for i in range(count):
76
+ for param in ["mod_reduc", "damping"]:
77
+ length, name = parse_fixed_width([(5, int), (65, to_str)], block)
78
+ curves.append(
79
+ site.NonlinearProperty(
80
+ name,
81
+ parse_fixed_width(length * [(10, float)], block),
82
+ parse_fixed_width(length * [(10, float)], block),
83
+ param,
84
+ )
85
+ )
86
+
87
+ length = int(block[0][:5])
88
+ soil_types = parse_fixed_width((length + 1) * [(5, int)], block)[1:]
89
+
90
+ # Group soil type number and curves together
91
+ return {(soil_types[i // 2], c.param): c for i, c in enumerate(curves)}
92
+
93
+
94
+ def _parse_soil_profile(block, units, curves, **kwargs):
95
+ """Parse soil profile block."""
96
+ wt_layer, length, _, name = parse_fixed_width(3 * [(5, int)] + [(55, to_str)], block)
97
+
98
+ layers = []
99
+ soil_types = []
100
+ for i in range(length):
101
+ (
102
+ index,
103
+ soil_idx,
104
+ thickness,
105
+ shear_mod,
106
+ damping,
107
+ unit_wt,
108
+ shear_vel,
109
+ ) = parse_fixed_width([(5, int), (5, int), (15, to_float)] + 4 * [(10, to_float)], block)
110
+
111
+ st = site.SoilType(
112
+ soil_idx,
113
+ unit_wt,
114
+ curves[(soil_idx, "mod_reduc")],
115
+ curves[(soil_idx, "damping")],
116
+ )
117
+ try:
118
+ # Try to find previously added soil type
119
+ st = soil_types[soil_types.index(st)]
120
+ except ValueError:
121
+ soil_types.append(st)
122
+
123
+ layers.append(site.Layer(st, thickness, shear_vel))
124
+
125
+ if units == "english":
126
+ # Convert from English to metric
127
+ for st in soil_types:
128
+ st.unit_wt *= 0.00015708746
129
+
130
+ for l in layers:
131
+ l.thickness *= 0.3048
132
+ l.shear_vel *= 0.3048
133
+
134
+ p = site.Profile(layers)
135
+ p.update_layers()
136
+ p.wt_depth = p[wt_layer - 1].depth
137
+
138
+ return p
139
+
140
+
141
+ def _parse_motion(block, **kwargs):
142
+ """Parse motin specification block."""
143
+ _, fa_length, time_step, name, fmt = parse_fixed_width(
144
+ [(5, int), (5, int), (10, float), (30, to_str), (30, to_str)], block
145
+ )
146
+
147
+ scale, pga, _, header_lines, _ = parse_fixed_width(
148
+ 3 * [(10, to_float)] + 2 * [(5, int)], block
149
+ )
150
+
151
+ m = re.search(r"(\d+)\w(\d+)\.\d+", fmt)
152
+ count_per_line = int(m.group(1))
153
+ width = int(m.group(2))
154
+
155
+ fname = os.path.join(os.path.dirname(kwargs["fname"]), name)
156
+ accels = np.genfromtxt(
157
+ fname,
158
+ delimiter=(count_per_line * [width]),
159
+ skip_header=header_lines,
160
+ )
161
+
162
+ if np.isfinite(scale):
163
+ pass
164
+ elif np.isfinite(pga):
165
+ scale = pga / np.abs(accels).max()
166
+ else:
167
+ scale = 1.0
168
+
169
+ accels *= scale
170
+ m = motion.TimeSeriesMotion(fname, "", time_step, accels, fa_length)
171
+
172
+ return m
173
+
174
+
175
+ def _parse_input_loc(block, profile, **kwargs):
176
+ """Parse input location block."""
177
+ layer, wave_field = parse_fixed_width(2 * [(5, int)], block)
178
+
179
+ return profile.location(
180
+ motion.WaveField[wave_field],
181
+ index=(layer - 1),
182
+ )
183
+
184
+
185
+ def _parse_run_control(block):
186
+ """Parse run control block."""
187
+ _, max_iterations, strain_ratio, _, _ = parse_fixed_width(
188
+ 2 * [(5, int)] + [(10, float)] + 2 * [(5, int)], block
189
+ )
190
+
191
+ return propagation.EquivalentLinearCalculation(strain_ratio, max_iterations, tolerance=10.0)
192
+
193
+
194
+ def _parse_output_accel(block):
195
+ raise NotImplementedError
196
+
197
+
198
+ def _parse_output_stress(block):
199
+ raise NotImplementedError
200
+
201
+
202
+ def _parse_output_spectra(block):
203
+ raise NotImplementedError
204
+
205
+
206
+ def load_shake_inp(fname):
207
+ with open(fname) as fp:
208
+ lines = fp.readlines()
209
+
210
+ lines.pop(0)
211
+ units = lines.pop(0)
212
+
213
+ # Parse the option blocks
214
+ option, block = None, []
215
+ options = []
216
+ for l in lines:
217
+ m = re.match(r"^\s+(\d+)$", l)
218
+
219
+ if m:
220
+ if option and not block:
221
+ block.append(l)
222
+ else:
223
+ if option and block:
224
+ # Save the previous block
225
+ options.append((option, block))
226
+ block = []
227
+ option = int(m.group(1))
228
+ else:
229
+ block.append(l)
230
+
231
+ parsers = {
232
+ 1: ("curves", _parse_curves),
233
+ 2: ("profile", _parse_soil_profile),
234
+ 3: ("motion", _parse_motion),
235
+ 4: ("input_loc", _parse_input_loc),
236
+ 5: ("run_control", _parse_run_control),
237
+ 6: ("output", _parse_output_accel),
238
+ 7: ("output", _parse_output_stress),
239
+ 9: ("output", _parse_output_spectra),
240
+ }
241
+
242
+ input = collections.OrderedDict(
243
+ {
244
+ "fname": fname,
245
+ "units": units,
246
+ }
247
+ )
248
+ for option, block in options:
249
+ key, parser = parsers[option]
250
+ input[key] = parser(block, **input)
251
+
252
+ return input
253
+
254
+
255
+ def read_nrattle_ctl(fpath):
256
+ """Read an nrattle control file."""
257
+ lines = list(fpath.open())
258
+ lines = [line for line in lines if line[0] != "!"]
259
+
260
+ d = {k: lines.pop(0) for k in ["revision", "prefix"]}
261
+ d["freq_count"], d["freq_max"] = split_line(lines.pop(0), [int, float])
262
+ d["out_depth"] = split_line(
263
+ lines.pop(0),
264
+ [
265
+ float,
266
+ ],
267
+ )
268
+
269
+ profile = []
270
+ while line := lines.pop(0):
271
+ try:
272
+ profile.append(split_line(line, [int, float, float, float, float]))
273
+ except ValueError:
274
+ break
275
+
276
+ d["profile"] = np.rec.fromrecords(profile, names="layer,thickness,vel_shear,density,inv_qual")
277
+ d["hs_vel_shear"], d["hs_density"] = split_line(line, [float, float])
278
+ d["hs_layer"], d["inci_angle"] = split_line(lines.pop(0), [int, float])
279
+
280
+ return d
281
+
282
+
283
+ def profile_from_nrattle_ctl(ctl):
284
+ df = pd.DataFrame(ctl["profile"]).set_index("layer")
285
+ # Here the index is based on layer number which starts at 1 in Fortran
286
+ # convention.
287
+ df.loc[len(df) + 1] = [0, ctl["hs_vel_shear"], ctl["hs_density"], 0]
288
+
289
+ # Scale from km to m
290
+ df["vel_shear"] *= 1000
291
+ df["thickness"] *= 1000
292
+ # Convert Q to damping:
293
+ # damping (dec) = 0.5 * 1 / Q = 1 / (2 * Q)
294
+ df["damping"] = df["inv_qual"].apply(
295
+ lambda iq: 0 if np.isclose(iq, 0) else 0.5 * 1 / (iq if iq > 1 else 1 / iq)
296
+ )
297
+ df["unit_wt"] = C.g * df["density"]
298
+
299
+ return site.Profile.from_dataframe(df, 0)