Skip to content

Commit 4cc80fa

Browse files
committed
pep8 refactoring (part 6)
1 parent 8c5047d commit 4cc80fa

File tree

11 files changed

+103
-114
lines changed

11 files changed

+103
-114
lines changed

egsim/api/forms/__init__.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -175,8 +175,9 @@ def errors_json_data(self) -> dict:
175175

176176
# build message. Sort params to make tests deterministic
177177
return {
178-
'message': '; '.join(sorted(f'{", ".join(sorted(ps))}: {err}'
179-
for err, ps in errors.items()))
178+
'message': '; '.join(sorted(
179+
f'{", ".join(sorted(ps))}: {err}' for err, ps in errors.items()
180+
))
180181
}
181182

182183
def param_name_of(self, field: str) -> str:
@@ -317,6 +318,8 @@ def get_region_selected_model_names(
317318
The returned dict keys are ground motion models, mapped to the hazard source
318319
regionalizations they were defined for (e.g. {'CauzziEtAl2014: ['share']})
319320
321+
:param lat: latitude, in degrees
322+
:param lon: longitude, in degrees
320323
:param reg_names: sequence of strings or None, indicating the names of the
321324
regionalizations to use None (the default) will use all regionalizations
322325
"""
@@ -423,9 +426,8 @@ class GsimInfoForm(GsimForm, APIForm):
423426
gsim = GsimForm.base_fields['gsim'].__class__(
424427
required=False,
425428
help_text=f"{GsimForm.base_fields['gsim'].help_text}. For any input value, "
426-
f"any model whose name contains (case-insensitive search) the value "
427-
f"is used. The model names are usually formatted as "
428-
f"[AuthorYearAdditionalInformation]"
429+
f"any model whose name contains the value is used (case-insensitive search). "
430+
f"The model names are usually formatted as [AuthorYearAdditionalInformation]"
429431
)
430432

431433
_field2params: dict[str, list[str]] = {'gsim': ('name', 'model')}
@@ -478,7 +480,10 @@ def output(self) -> dict:
478480
}
479481
# pretty print doc (removing all newlines, double quotes, etc.):
480482
doc = " ".join(
481-
line.strip().replace("\n", " ").replace("\t", " ").replace('"', "''").
483+
line.strip().
484+
replace("\n", " ").
485+
replace("\t", " ").
486+
replace('"', "''").
482487
replace(":class:`", "`")
483488
for line in doc.strip().split("\n") if line.strip()
484489
)

egsim/api/forms/flatfile.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
get_dtype_of,
1818
column_exists,
1919
column_type,
20-
column_categorical_dtype, column_aliases,
20+
column_categorical_dtype,
21+
column_aliases,
2122
column_dtype,
2223
column_help,
2324
query as flatfile_query,

egsim/api/forms/scenarios.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -83,16 +83,16 @@ class PredictionsForm(GsimImtForm, APIForm):
8383
# RUPTURE PARAMS:
8484
magnitude = ArrayField(
8585
FloatField(),
86-
help_text='Magnitude(s). Each magnitude defines a Rupture of the user-defined scenario',
87-
required=True
86+
required=True,
87+
help_text='Magnitude(s). Each magnitude defines a Rupture of the user-defined scenario'
8888
)
8989
distance = ArrayField(
9090
FloatField(),
91-
help_text='Distances (km). Each distance defines a Site of the user-defined Scenario',
92-
required=True
91+
required=True,
92+
help_text='Distances (km). Each distance defines a Site of the user-defined Scenario'
9393
)
9494
aspect = FloatField(
95-
help_text='Rupture Length / Width ≥ 0 and ≤ 1', min_value=0., initial=1.0
95+
min_value=0., initial=1.0, help_text='Rupture Length / Width ≥ 0 and ≤ 1'
9696
)
9797
dip = FloatField(
9898
min_value=0., max_value=90., initial=90, help_text="Dip of rupture (deg) ≥ 0 and ≤ 90"
@@ -107,13 +107,13 @@ class PredictionsForm(GsimImtForm, APIForm):
107107
min_value=0., max_value=360., initial=0., help_text="Strike of rupture (deg) ≥ 0 and ≤ 360"
108108
)
109109
ztor = FloatField(
110-
help_text='Top of Rupture Depth (km) ≥ 0', min_value=0., initial=0.
110+
min_value=0., initial=0., help_text='Top of Rupture Depth (km) ≥ 0'
111111
)
112112
# WARNING IF RENAMING FIELD BELOW: RENAME+MODIFY also `clean_msr`
113113
msr = ChoiceField(
114-
help_text='Magnitude-Area Scaling Relationship',
115114
choices=[(_, _) for _ in _mag_scalerel],
116-
initial="WC1994"
115+
initial="WC1994",
116+
help_text='Magnitude-Area Scaling Relationship'
117117
)
118118
# WARNING IF RENAMING FIELD BELOW: RENAME+MODIFY also `clean_location`
119119
initial_point = ArrayField(

egsim/api/models.py

Lines changed: 4 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -159,34 +159,10 @@ def read_from_filepath(self, **kwargs) -> Any:
159159

160160
class Regionalization(MediaFile, Reference):
161161
"""
162-
Class handling regionalizations stored in the file system. A regionalization
163-
is a collection of regions, where each region is an object denoted by:
164-
- a geometry (e.g. a Polygon enclosed by poitns in (lat, lon) coordinates),
165-
- a unique name (identifier)
166-
- a list of ground shaking models selected for the region.
167-
For each row of this table, the associated media file is a geoJSON file where a
168-
regionalization is stored as FeatureCollection object, and each region is a
169-
geoJSON Feature object. E.g.:
170-
```
171-
{
172-
"type": 'FeatureCollection',
173-
"features" : [
174-
{
175-
"type": "Feature",
176-
"geometry": list,
177-
"properties": {
178-
"region": str,
179-
"models": list[str],
180-
...
181-
}
182-
},
183-
...
184-
]
185-
}
186-
```
187-
Note for developers:. See `read_from_filepath` to convert a Feature
188-
geometry to a shapely `shape` object
189-
""" # noqa
162+
Class handling regionalizations stored in the file system. For each row of this table,
163+
the associated media file is a geoJSON text file representing a valid regionalization
164+
mapping regions to models (in each Polygon or MultiPolygon "properties")
165+
"""
190166

191167
def read_from_filepath(self, **kwargs) -> dict:
192168
"""

egsim/api/views.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -124,9 +124,9 @@ def handle_exception(self, exc: Exception, request) -> HttpResponse: # noqa
124124
as response body / content
125125
"""
126126
return error_response(
127-
(f'Server error ({exc.__class__.__name__}): {exc}'.strip() +
128-
f'. Please contact the server administrator '
129-
f'if you think this error is due to a code bug'),
127+
f'Server error ({exc.__class__.__name__}): {str(exc).strip()}. '
128+
f'. Please contact the server administrator '
129+
f'if you think this error is due to a code bug',
130130
status=500
131131
)
132132

@@ -166,7 +166,7 @@ def error_response(
166166
**kwargs
167167
) -> HttpResponse:
168168
"""
169-
Return a HttpResponse with status 400 (client error) as default
169+
Return a HttpResponse with default status 400 (client error)
170170
and custom message in the response body / content. For custom status,
171171
provide the `status` explicitly as keyword argument
172172
"""

egsim/app/forms.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ class PredictionsVisualizeForm(PredictionsForm):
3838
('d', 'IMT vs. Distance'),
3939
('s', 'Magnitude-Distance Spectra')
4040
],
41-
help_text='the plot type to be displayed: '
41+
help_text='the plot type to be displayed'
4242
)
4343

4444
def clean(self):
@@ -164,7 +164,9 @@ def groupby(dframe: pd.DataFrame):
164164
def get_plot_traces_and_layout(
165165
x: dict[str, np.ndarray],
166166
y: dict[str, tuple[np.ndarray, np.ndarray]],
167-
x_label, y_label, colors: dict[str, str]
167+
x_label,
168+
y_label,
169+
colors: dict[str, str]
168170
) -> tuple[list[dict], dict]:
169171
"""
170172
Return the traces and layout of a prediction plot (to be displayed using the
@@ -291,11 +293,17 @@ def output(self) -> dict:
291293

292294
plots = {} # will be returned as list (taking the dict values)
293295

294-
total_res, intra_res, inter_res = \
295-
(Clabel.total_res, Clabel.intra_ev_res, Clabel.inter_ev_res)
296+
total_res, intra_res, inter_res = (
297+
Clabel.total_res,
298+
Clabel.intra_ev_res,
299+
Clabel.inter_ev_res
300+
)
296301
if likelihood:
297-
total_res, intra_res, inter_res = \
298-
(Clabel.total_lh, Clabel.intra_ev_lh, Clabel.inter_ev_lh)
302+
total_res, intra_res, inter_res = (
303+
Clabel.total_lh,
304+
Clabel.intra_ev_lh,
305+
Clabel.inter_ev_lh
306+
)
299307
res_columns = {total_res, intra_res, inter_res}
300308
residual_label = {
301309
total_res: 'Total',
@@ -569,7 +577,9 @@ def output(self) -> dict:
569577
data, layout = self.get_plot_traces_and_layout(
570578
dataframe[x_label] if x_label else None,
571579
dataframe[y_label] if y_label else None,
572-
x_label, y_label, next(colors_cycle())
580+
x_label,
581+
y_label,
582+
next(colors_cycle())
573583
)
574584
plot = {
575585
'data': data,

egsim/smtk/flatfile.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""flatfile root module"""
1+
"""Flatfile root module"""
22

33
from __future__ import annotations
44

@@ -170,9 +170,11 @@ def _read_csv_get_header(filepath_or_buffer: IOBase, sep=None, **kwargs) -> list
170170
_pos = filepath_or_buffer.tell()
171171
# use only args necessary to parse columns, we might raise unnecessary errors
172172
# otherwise (these errors might be fixed afterward before reading the whole csv):
173-
args = ['header', 'names', 'skip_blank_lines', 'skipinitialspace', 'engine',
174-
'lineterminator', 'quotechar', 'quoting', 'doublequote', 'escapechar',
175-
'comment', 'dialect', 'delim_whitespace']
173+
args = [
174+
'header', 'names', 'skip_blank_lines', 'skipinitialspace', 'engine',
175+
'lineterminator', 'quotechar', 'quoting', 'doublequote', 'escapechar',
176+
'comment', 'dialect', 'delim_whitespace'
177+
]
176178
_kwargs = {k: kwargs[k] for k in args if k in kwargs}
177179
_kwargs['nrows'] = 0 # read just header
178180
_kwargs['sep'] = sep

egsim/smtk/residuals.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -176,10 +176,8 @@ def get_observed_motions(flatfile: pd.DataFrame, imts: Container[str], log=True)
176176

177177

178178
def yield_event_contexts(flatfile: pd.DataFrame) -> Iterable[EventContext]:
179-
"""
180-
Group the flatfile by events, and yield `EventContext`s objects, one for
181-
each event
182-
"""
179+
"""Group the flatfile by events, and yield `EventContext`s objects, one for each event"""
180+
183181
# check event id column or use the event location to group events:
184182
# group flatfile by events. Use ev. id (_EVENT_COLUMNS[0]) or, when
185183
# no ID found, event spatio-temporal coordinates (_EVENT_COLUMNS[1:])
@@ -372,8 +370,7 @@ def get_residuals_likelihood(residuals: pd.DataFrame, inplace=True) -> pd.DataFr
372370

373371
def get_likelihood(values: Union[np.ndarray, pd.Series]) -> Union[np.ndarray, pd.Series]:
374372
"""
375-
Return the likelihood of the given values according to Equation 9 of
376-
Scherbaum et al. (2004)
373+
Return the likelihood of the given values according to Equation 9 of Scherbaum et al. (2004)
377374
"""
378375
zvals = np.fabs(values)
379376
return 1.0 - erf(zvals / sqrt(2.))
@@ -384,9 +381,10 @@ def get_likelihood(values: Union[np.ndarray, pd.Series]) -> Union[np.ndarray, pd
384381
def get_column_name(flatfile: pd.DataFrame, column: str) -> Union[str, None]:
385382
"""
386383
Return the flatfile column matching `column`. This could be `column`
387-
itself, or any of its aliases (see `columns` module and YAML file)
388-
Returns None if no column is found, raise `IncompatibleColumnError` if more than
389-
a matching column is found"""
384+
itself, or any of its aliases (see `columns` module and YAML file)
385+
Returns None if no column is found, raise `IncompatibleColumnError` if more than
386+
a matching column is found
387+
"""
390388
ff_cols = set(flatfile.columns)
391389
cols = set(column_aliases(column)) & ff_cols
392390
if len(cols) > 1:

egsim/smtk/scenarios.py

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -132,18 +132,15 @@ class RuptureProperties)
132132
# build our dataframe data (horizontal concat data + meta_data into data):
133133
data.append(meta_data)
134134
# build our dataframe columns (append the meta_data columns from meta_columns):
135-
meta_columns = [
136-
(Clabel.input, str(column_type(m).value), m) for m in meta_fields
137-
]
135+
meta_columns = [(Clabel.input, str(column_type(m).value), m) for m in meta_fields]
138136
columns.extend(meta_columns)
139137

140138
# compute final DataFrame:
141139
output = pd.DataFrame(columns=columns, data=np.hstack(data))
142140

143141
# sort columns (maybe we could use reindex but let's be more explicit):
144142
computed_cols = set(output.columns)
145-
expected_cols = \
146-
list(product(imts, [Clabel.median, Clabel.std], gsims)) + meta_columns
143+
expected_cols = list(product(imts, [Clabel.median, Clabel.std], gsims)) + meta_columns
147144
output = output[[c for c in expected_cols if c in computed_cols]].copy()
148145
if header_sep:
149146
output.columns = [header_sep.join(c) for c in output.columns]
@@ -242,8 +239,7 @@ def create_planar_surface(
242239
:param aspect: Aspect ratio of rupture
243240
:param ztor: top of rupture depth, in km
244241
245-
:return: Rupture as an instance of
246-
:class:`openquake.hazardlib.geo.surface.planar.PlanarSurface`
242+
:return: Rupture as instance of :class:`openquake.hazardlib.geo.surface.planar.PlanarSurface`
247243
"""
248244
# If the top of rupture depth in the initial
249245
if fabs(top_centroid.depth - ztor) > 1E-9:
@@ -362,8 +358,7 @@ def get_hypocentre_on_planar_surface(
362358
a hypocentre located in a position 3/4 along the length, and 1/4 of the
363359
way down dip of the rupture plane would be entered as (0.75, 0.25)
364360
365-
:return: Hypocentre location as instance of
366-
:class:`openquake.hazardlib.geo.point.Point`
361+
:return: Hypocentre location as instance of :class:`openquake.hazardlib.geo.point.Point`
367362
"""
368363
centroid = plane.get_middle_point()
369364
if hypo_loc is None:
@@ -412,17 +407,18 @@ def _rup_to_point(
412407
dist_sin_dip = distance / sin_dip
413408
iterval = 0
414409
while (np.fabs(r_diff) >= iter_stop) and (iterval <= maxiter):
415-
pt1mesh = Mesh(np.array([pt1.longitude]),
416-
np.array([pt1.latitude]),
417-
None)
410+
pt1mesh = Mesh(
411+
np.array([pt1.longitude]),
412+
np.array([pt1.latitude]),
413+
None
414+
)
418415
if distance_type == 'rjb' or np.fabs(dip - 90.0) < 1.0E-3:
419416
r_diff = (distance - surface.get_joyner_boore_distance(pt1mesh)).flatten()
420417
pt0 = Point(pt1.longitude, pt1.latitude)
421418
if r_diff > 0.:
422419
pt1 = pt0.point_at(r_diff, 0., azimuth)
423420
else:
424-
pt1 = pt0.point_at(np.fabs(r_diff), 0.,
425-
(azimuth + 180.) % 360.)
421+
pt1 = pt0.point_at(np.fabs(r_diff), 0., (azimuth + 180.) % 360.)
426422
elif distance_type == 'rrup':
427423
rrup = surface.get_min_distance(pt1mesh).flatten()
428424
if 0.0 <= azimuth <= 180.0:
@@ -435,8 +431,7 @@ def _rup_to_point(
435431
if r_diff > 0.:
436432
pt1 = pt0.point_at(r_diff, 0., azimuth)
437433
else:
438-
pt1 = pt0.point_at(np.fabs(r_diff), 0.,
439-
(azimuth + 180.) % 360.)
434+
pt1 = pt0.point_at(np.fabs(r_diff), 0., (azimuth + 180.) % 360.)
440435
else:
441436
raise ValueError('Distance type must be rrup or rjb')
442437
iterval += 1

egsim/smtk/validation.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,8 @@ def get_ground_motion_values(
209209
m_buf[:, start:end],
210210
s_buf[:, start:end],
211211
t_buf[:, start:end],
212-
p_buf[:, start:end])
212+
p_buf[:, start:end]
213+
)
213214
except oq_exceptions as exc:
214215
raise _format_model_error(model_name or model, exc)
215216
# set computed values back to our variables:
@@ -240,8 +241,9 @@ def _format_model_error(model: Union[GMPE, str], exception: Exception) -> ModelE
240241
if '/openquake/' in fname and fname.rfind('/') < len(fname) - 3:
241242
suffix = f"OpenQuake {suffix} @{fname[fname.rfind('/') + 1:]}:{lineno}"
242243

243-
return ModelError(f'{model if isinstance(model, str) else gsim_name(model)}: '
244-
f'{str(exception)} ({suffix})')
244+
return ModelError(
245+
f'{model if isinstance(model, str) else gsim_name(model)}: {str(exception)} ({suffix})'
246+
)
245247

246248

247249
# Custom Exceptions ===========================================================

0 commit comments

Comments
 (0)