Skip to content

Commit 78df213

Browse files
committed
speed up in TC and TCTracks. Rename EARTH_RADIUS_KM
1 parent 7882931 commit 78df213

File tree

12 files changed

+682
-443
lines changed

12 files changed

+682
-443
lines changed

climada/hazard/base.py

Lines changed: 62 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ def clear(self):
136136
"""Reinitialize attributes."""
137137
for (var_name, var_val) in self.__dict__.items():
138138
if isinstance(var_val, np.ndarray) and var_val.ndim == 1:
139-
setattr(self, var_name, np.array([]))
139+
setattr(self, var_name, np.array([], dtype=var_val.dtype))
140140
elif isinstance(var_val, sparse.csr_matrix):
141141
setattr(self, var_name, sparse.csr_matrix(np.empty((0, 0))))
142142
else:
@@ -547,6 +547,40 @@ def size(self):
547547
self.check()
548548
return self.event_id.size
549549

550+
def _append_all(self, list_haz_ev):
551+
"""Append event by event with same centroids.
552+
553+
Parameters:
554+
list_haz_ev (list): Hazard instances with one event and same
555+
centroids
556+
"""
557+
self.clear()
558+
num_ev = len(list_haz_ev)
559+
num_cen = list_haz_ev[0].centroids.size
560+
for var_name, var_val in self.__dict__.items():
561+
if isinstance(var_val, np.ndarray) and var_val.ndim == 1:
562+
setattr(self, var_name, np.zeros((num_ev,), dtype=var_val.dtype))
563+
elif isinstance(var_val, sparse.csr.csr_matrix):
564+
setattr(self, var_name, sparse.lil_matrix((num_ev, num_cen)))
565+
566+
for i_ev, haz_ev in enumerate(list_haz_ev):
567+
for (var_name, var_val), ev_val in zip(self.__dict__.items(),
568+
haz_ev.__dict__.values()):
569+
if isinstance(var_val, np.ndarray) and var_val.ndim == 1:
570+
var_val[i_ev] = ev_val[0]
571+
elif isinstance(var_val, list):
572+
var_val.extend(ev_val)
573+
elif isinstance(var_val, sparse.lil_matrix):
574+
var_val[i_ev, :] = ev_val[0, :]
575+
elif isinstance(var_val, TagHazard):
576+
var_val.append(ev_val)
577+
578+
self.centroids = copy.deepcopy(list_haz_ev[0].centroids)
579+
self.units = list_haz_ev[0].units
580+
self.intensity = self.intensity.tocsr()
581+
self.fraction = self.fraction.tocsr()
582+
self.event_id = np.arange(1, num_ev+1)
583+
550584
def _append_haz_cent(self, centroids):
551585
"""Append centroids. Get positions of new centroids.
552586
@@ -616,33 +650,6 @@ def _events_set(self):
616650
ev_set.add((ev_name, ev_date))
617651
return ev_set
618652

619-
def _check_events(self):
620-
""" Check that all attributes but centroids contain consistent data.
621-
Put default date, event_name and orig if not provided. Check not
622-
repeated events (i.e. with same date and name)
623-
624-
Raises:
625-
ValueError
626-
"""
627-
num_ev = len(self.event_id)
628-
num_cen = len(self.centroids.id)
629-
if np.unique(self.event_id).size != num_ev:
630-
LOGGER.error("There are events with the same identifier.")
631-
raise ValueError
632-
633-
check.check_oligatories(self.__dict__, self.vars_oblig, 'Hazard.',
634-
num_ev, num_ev, num_cen)
635-
check.check_optionals(self.__dict__, self.vars_opt, 'Hazard.', num_ev)
636-
self.event_name = check.array_default(num_ev, self.event_name, \
637-
'Hazard.event_name', list(self.event_id))
638-
self.date = check.array_default(num_ev, self.date, 'Hazard.date', \
639-
np.ones(self.event_id.shape, dtype=int))
640-
self.orig = check.array_default(num_ev, self.orig, 'Hazard.orig', \
641-
np.zeros(self.event_id.shape, dtype=bool))
642-
if len(self._events_set()) != num_ev:
643-
LOGGER.error("There are events with same date and name.")
644-
raise ValueError
645-
646653
def _event_plot(self, event_id, mat_var, col_name, **kwargs):
647654
""""Plot an event of the input matrix.
648655
@@ -758,6 +765,33 @@ def _loc_return_inten(self, return_periods, inten, exc_inten):
758765
inten_sort[:, cen_idx], freq_sort[:, cen_idx],
759766
self.intensity_thres, return_periods)
760767

768+
def _check_events(self):
769+
""" Check that all attributes but centroids contain consistent data.
770+
Put default date, event_name and orig if not provided. Check not
771+
repeated events (i.e. with same date and name)
772+
773+
Raises:
774+
ValueError
775+
"""
776+
num_ev = len(self.event_id)
777+
num_cen = len(self.centroids.id)
778+
if np.unique(self.event_id).size != num_ev:
779+
LOGGER.error("There are events with the same identifier.")
780+
raise ValueError
781+
782+
check.check_oligatories(self.__dict__, self.vars_oblig, 'Hazard.',
783+
num_ev, num_ev, num_cen)
784+
check.check_optionals(self.__dict__, self.vars_opt, 'Hazard.', num_ev)
785+
self.event_name = check.array_default(num_ev, self.event_name, \
786+
'Hazard.event_name', list(self.event_id))
787+
self.date = check.array_default(num_ev, self.date, 'Hazard.date', \
788+
np.ones(self.event_id.shape, dtype=int))
789+
self.orig = check.array_default(num_ev, self.orig, 'Hazard.orig', \
790+
np.zeros(self.event_id.shape, dtype=bool))
791+
if len(self._events_set()) != num_ev:
792+
LOGGER.error("There are events with same date and name.")
793+
raise ValueError
794+
761795
@staticmethod
762796
def _cen_return_inten(inten, freq, inten_th, return_periods):
763797
"""From ordered intensity and cummulative frequency at centroid, get

climada/hazard/centroids/test/test_base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,8 @@ def test_calc_dist_coast_pass(self):
267267
centr_brb = Centroids(CENTR_BRB)
268268
centr_brb.calc_dist_to_coast()
269269
self.assertEqual(centr_brb.id.size, centr_brb.dist_coast.size)
270-
self.assertEqual(5.7988200982894105, centr_brb.dist_coast[1])
271-
self.assertEqual(166.36505441711506, centr_brb.dist_coast[-2])
270+
self.assertAlmostEqual(5.7988200982894105, centr_brb.dist_coast[1])
271+
self.assertAlmostEqual(166.36505441711506, centr_brb.dist_coast[-2])
272272

273273
# Execute Tests
274274
TESTS = unittest.TestLoader().loadTestsFromTestCase(TestLoader)

0 commit comments

Comments
 (0)