Skip to content

Commit 600e470

Browse files
committed
refactor polygon to models module
1 parent e0d0065 commit 600e470

File tree

6 files changed

+89
-75
lines changed

6 files changed

+89
-75
lines changed

csep/core/catalogs.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import pandas
1111

1212
# CSEP Imports
13-
from csep.core import regions
1413
from csep.utils.time_utils import epoch_time_to_utc_datetime, datetime_to_utc_epoch, strptime_to_utc_datetime, \
1514
millis_to_days, parse_string_format, days_to_millis, strptime_to_utc_epoch, utc_now_datetime, create_utc_datetime
1615
from csep.utils.stats import min_or_none, max_or_none

csep/core/forecasts.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
import numpy
88

99
from csep.utils.log import LoggingMixin
10-
from csep.core.regions import CartesianGrid2D, Polygon, create_space_magnitude_region
10+
from csep.core.regions import CartesianGrid2D, create_space_magnitude_region
11+
from csep.models import Polygon
1112
from csep.utils.calc import bin1d_vec
1213
from csep.utils.time_utils import decimal_year, datetime_to_utc_epoch
1314
from csep.core.catalogs import AbstractBaseCatalog

csep/core/regions.py

Lines changed: 2 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@
55
from xml.etree import ElementTree as ET
66

77
# Third-party imports
8-
import matplotlib.path
98
import numpy
109
import numpy as np
11-
import pyproj
1210

1311
# PyCSEP imports
1412
from csep.utils.calc import bin1d_vec, cleaner_range, first_nonnan, last_nonnan
1513
from csep.utils.scaling_relationships import WellsAndCoppersmith
14+
from csep.models import Polygon
15+
1616

1717
def california_relm_collection_region(dh_scale=1, magnitudes=None, name="relm-california-collection"):
1818
""" Return collection region for California RELM testing region
@@ -463,74 +463,6 @@ def _bin_catalog_probability(lons, lats, n_poly, mask, idx_map, binx, biny):
463463
event_counts[hash_idx] = 1
464464
return event_counts
465465

466-
class Polygon:
467-
"""
468-
Represents polygons defined through a collection of vertices.
469-
470-
This polygon is assumed to be 2d, but could contain an arbitrary number of vertices. The path is treated as not being
471-
closed.
472-
"""
473-
def __init__(self, points):
474-
# instance members
475-
self.points = points
476-
self.origin = self.points[0]
477-
478-
# https://matplotlib.org/3.1.1/api/path_api.html
479-
self.path = matplotlib.path.Path(self.points)
480-
481-
def __str__(self):
482-
return str(self.origin)
483-
484-
def contains(self, points):
485-
""" Returns a bool array which is True if the path contains the corresponding point.
486-
487-
Args:
488-
points: 2d numpy array
489-
490-
"""
491-
nd_points = np.array(points)
492-
if nd_points.ndim == 1:
493-
nd_points = nd_points.reshape(1,-1)
494-
return self.path.contains_points(nd_points)
495-
496-
def centroid(self):
497-
""" return the centroid of the polygon."""
498-
c0, c1 = 0, 0
499-
k = len(self.points)
500-
for p in self.points:
501-
c0 = c0 + p[0]
502-
c1 = c1 + p[1]
503-
return c0 / k, c1 / k
504-
505-
def get_xcoords(self):
506-
return np.array(self.points)[:,0]
507-
508-
def get_ycoords(self):
509-
return np.array(self.points)[:,1]
510-
511-
@classmethod
512-
def from_great_circle_radius(cls, centroid, radius, num_points=10):
513-
"""
514-
Generates a polygon object from a given radius and centroid location.
515-
516-
Args:
517-
centroid: (lon, lat)
518-
radius: should be in (meters)
519-
num_points: more points is higher resolution polygon
520-
521-
Returns:
522-
polygon
523-
"""
524-
geod = pyproj.Geod(ellps='WGS84')
525-
azim = np.linspace(0, 360, num_points)
526-
# create vectors with same length as azim for computations
527-
center_lons = np.ones(num_points) * centroid[0]
528-
center_lats = np.ones(num_points) * centroid[1]
529-
radius = np.ones(num_points) * radius
530-
# get new lons and lats
531-
endlon, endlat, backaz = geod.fwd(center_lons, center_lats, azim, radius)
532-
# class method
533-
return cls(np.column_stack([endlon, endlat]))
534466

535467
class CartesianGrid2D:
536468
"""Represents a 2D cartesian gridded region.

csep/models.py

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1+
import matplotlib.path
12
import numpy
23

34
# CSEP Imports
5+
import numpy as np
6+
import pyproj
7+
48
from csep.utils.time_utils import datetime_to_utc_epoch, epoch_time_to_utc_datetime
59
from csep.utils import plots
610

@@ -142,6 +146,7 @@ def plot(self, show=False, plot_args=None):
142146
ax = plots.plot_number_test(self, show=show, plot_args=plot_args)
143147
return ax
144148

149+
145150
class CatalogPseudolikelihoodTestResult(EvaluationResult):
146151

147152
def __init__(self, **kwargs):
@@ -158,6 +163,7 @@ def plot(self, show=False, plot_args=None):
158163
ax = plots.plot_likelihood_test(self, show=show, plot_args=plot_args)
159164
return ax
160165

166+
161167
class CatalogMagnitudeTestResult(EvaluationResult):
162168

163169
def __init__(self, **kwargs):
@@ -172,6 +178,7 @@ def plot(self, show=False, plot_args=None):
172178
ax = plots.plot_magnitude_test(self, show=show, plot_args=plot_args)
173179
return ax
174180

181+
175182
class CatalogSpatialTestResult(EvaluationResult):
176183

177184
def __init__(self, **kwargs):
@@ -190,6 +197,7 @@ def plot(self, show=False, plot_args=None):
190197
ax = plots.plot_spatial_test(self, show=show, plot_args=plot_args)
191198
return ax
192199

200+
193201
class CalibrationTestResult(EvaluationResult):
194202

195203
def __init__(self, **kwargs):
@@ -206,6 +214,7 @@ def plot(self, show=False, axes=None, plot_args=None):
206214
ax = plots.plot_calibration_test(self, show=show, axes=axes, plot_args=plot_args)
207215
return ax
208216

217+
209218
class EvaluationConfiguration:
210219
"""
211220
Store information about the evaluation which will be used to store metadata about the evaluation.
@@ -282,4 +291,74 @@ def update_version(self, name, version, fnames):
282291
e['fnames'] = fnames
283292
found = True
284293
if not found:
285-
self.evaluations.append({'name': name, 'version': version, 'fnames': fnames})
294+
self.evaluations.append({'name': name, 'version': version, 'fnames': fnames})
295+
296+
297+
class Polygon:
298+
"""
299+
Represents polygons defined through a collection of vertices.
300+
301+
This polygon is assumed to be 2d, but could contain an arbitrary number of vertices. The path is treated as not being
302+
closed.
303+
"""
304+
def __init__(self, points):
305+
# instance members
306+
self.points = points
307+
self.origin = self.points[0]
308+
309+
# https://matplotlib.org/3.1.1/api/path_api.html
310+
self.path = matplotlib.path.Path(self.points)
311+
312+
def __str__(self):
313+
return str(self.origin)
314+
315+
def contains(self, points):
316+
""" Returns a bool array which is True if the path contains the corresponding point.
317+
318+
Args:
319+
points: 2d numpy array
320+
321+
"""
322+
nd_points = np.array(points)
323+
if nd_points.ndim == 1:
324+
nd_points = nd_points.reshape(1,-1)
325+
return self.path.contains_points(nd_points)
326+
327+
def centroid(self):
328+
""" return the centroid of the polygon."""
329+
c0, c1 = 0, 0
330+
k = len(self.points)
331+
for p in self.points:
332+
c0 = c0 + p[0]
333+
c1 = c1 + p[1]
334+
return c0 / k, c1 / k
335+
336+
def get_xcoords(self):
337+
return np.array(self.points)[:,0]
338+
339+
def get_ycoords(self):
340+
return np.array(self.points)[:,1]
341+
342+
@classmethod
343+
def from_great_circle_radius(cls, centroid, radius, num_points=10):
344+
"""
345+
Generates a polygon object from a given radius and centroid location.
346+
347+
Args:
348+
centroid: (lon, lat)
349+
radius: should be in (meters)
350+
num_points: more points is higher resolution polygon
351+
352+
Returns:
353+
polygon
354+
"""
355+
geod = pyproj.Geod(ellps='WGS84')
356+
azim = np.linspace(0, 360, num_points)
357+
# create vectors with same length as azim for computations
358+
center_lons = np.ones(num_points) * centroid[0]
359+
center_lats = np.ones(num_points) * centroid[1]
360+
radius = np.ones(num_points) * radius
361+
# get new lons and lats
362+
endlon, endlat, backaz = geod.fwd(center_lons, center_lats, azim, radius)
363+
# class method
364+
return cls(np.column_stack([endlon, endlat]))

tests/test_catalog.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
from csep.core import regions, forecasts
1010
from csep.utils.time_utils import strptime_to_utc_epoch, strptime_to_utc_datetime
1111
from csep.core.catalogs import CSEPCatalog, AbstractBaseCatalog
12-
from csep.core.regions import CartesianGrid2D, Polygon, compute_vertices
12+
from csep.core.regions import CartesianGrid2D, compute_vertices
13+
from csep.models import Polygon
14+
1315

1416
def comcat_path():
1517
root_dir = os.path.dirname(os.path.abspath(__file__))

tests/test_spatial.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
import numpy
66

77
from csep.core.regions import CartesianGrid2D, compute_vertex, compute_vertices, _bin_catalog_spatio_magnitude_counts, \
8-
_bin_catalog_spatial_counts, _bin_catalog_probability, Polygon, global_region
8+
_bin_catalog_spatial_counts, _bin_catalog_probability, global_region
9+
from csep.models import Polygon
910

1011

1112
class TestPolygon(unittest.TestCase):

0 commit comments

Comments
 (0)