-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbymur_core.py
More file actions
1603 lines (1350 loc) · 58.2 KB
/
Copy pathbymur_core.py
File metadata and controls
1603 lines (1350 loc) · 58.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bymur Software computes Risk and Multi-Risk associated to Natural Hazards.
In particular this tool aims to provide a final working application for
the city of Naples, considering three natural phenomena, i.e earthquakes,
volcanic eruptions and tsunamis.
The tool is the final product of BYMUR, an Italian project funded by the
Italian Ministry of Education (MIUR) in the frame of 2008 FIRB, Futuro in
Ricerca funding program.
Copyright(C) 2012-2016, 2018 Paolo Perfetti, Roberto Tonini and Jacopo Selva
This file is part of BYMUR software.
BYMUR is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
BYMUR is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.
You should have received a copy of the GNU Affero General Public License
along with BYMUR. If not, see <http://www.gnu.org/licenses/>.
"""
import bymur_functions as bf
import bymur_db as db
import numpy as np # ma lo uso solo per sqrt?
import math
import random as rnd
import os
import scipy.interpolate as interpolate
class HazardPoint(object):
"""Describe data of a point in a HazardModel."""
def __init__(self, core):
"""
:rtype : bymur_core.HazardPoint
:type core: bymur_core.BymurCore
"""
self._core = core
self._hazard = None
self._index = None
self._curves = None
self._easting = None
self._northing = None
self._haz_value = None
self._prob_value = None
def update(self, hazard, index, hazard_threshold, intensity_treshold):
"""
Update object to keep track of current selected point.
:type hazard: bymur_core.HazardModel
:type hazard_threshold: float
:type intensity_treshold: float
"""
self._hazard = hazard
self._index = index
self._easting = self._hazard.grid_points[self._index]['easting']
self._northing = self._hazard.grid_points[self._index]['northing']
self._curves = self._core.db.get_point_all_curves(
self._hazard.phenomenon_id,
self._hazard.hazard_id,
self._hazard.grid_points[self._index]['id'])
self._haz_value = self._core.get_haz_value(self._hazard.iml,
hazard_threshold,
[float(x) for x
in self._curves['mean'].split(',')])
self._prob_value = self._core.get_prob_value(self._hazard.iml,
intensity_treshold,
[float(x) for x
in self._curves[
'mean'].split(',')])
@property
def easting(self):
"""
Return point easting.
:return: bigint
"""
return self._easting
@property
def northing(self):
"""
Return point northing.
:return: bigint
"""
return self._northing
@property
def index(self):
"""
Return grid point index.
:return: bigint
"""
return self._index
@property
def curves(self):
"""
Return all point data curves.
:return: list of dict{'statistic':{}, 'curve':{}}
"""
return self._curves
@property
def haz_value(self):
"""
Return point hazard value.
:return: float
"""
return self._haz_value
@property
def prob_value(self):
"""
Return point probability value.
:return: float
"""
return self._prob_value
class EnsembleModel(object):
def __init__(self, hazard_name, exposure_time, phen_name, db):
self._db = db
self._hazard_name = hazard_name
self._exposure_time = exposure_time
self._phenomenon_name = phen_name
self._statistics = None
self._datagrid_id = None
self._points_data = None
self._iml = None
self._imt = None
def save(self):
phenomenon_id = self._db.insert_id_phenomenon(self._phenomenon_name)
print " new hazard phenomenon name: %s , id: %s" \
% (self._phenomenon_name, phenomenon_id)
hazard_model_id = self._db.insert_id_hazard_model(
phenomenon_id,
self.datagrid_id,
self.hazard_name,
self.exposure_time,
" ".join([str(x) for x in self.iml]),
self.imt)
print "new hazard_model_id %s" % hazard_model_id
for stat in self._statistics:
if stat != 'mean':
stat_id = self._db.insert_id_statistic('percentile', stat)
else:
stat_id = self._db.insert_id_statistic(stat,'0')
self._db.insert_hazard_statistic_rel(hazard_model_id, stat_id)
self._db.insert_hazard_data(self.phenomenon,hazard_model_id,
stat_id,
[ point['point_id']
for point in self.points_data],
[ point['point_data'][stat]
for point in self.points_data])
@property
def hazard_name(self):
return self._hazard_name
@property
def exposure_time(self):
return self._exposure_time
@property
def datagrid_id(self):
return self._datagrid_id
@datagrid_id.setter
def datagrid_id(self, grid_id):
self._datagrid_id = grid_id
@property
def phenomenon(self):
return self._phenomenon_name
@property
def iml(self):
return self._iml
@iml.setter
def iml(self, iml_thresholds):
self._iml = iml_thresholds
@property
def imt(self):
return self._imt
@imt.setter
def imt(self, imt):
self._imt = imt
@property
def statistics(self):
return self._statistics
@statistics.setter
def statistics(self, stat_list):
self._statistics = stat_list
@property
def points_data(self):
return self._points_data
@points_data.setter
def points_data(self, data):
self._points_data = data
class HazardModel(object):
"""
Rapresentation of an Hazard model, read from data_provider and
exposed as PythonObject.
"""
def __init__(self, data_provider, id=None, hazard_name=None, exp_time=None):
"""
:type data_provider: bymur_db.BymurDB
:type id: int
:type hazard_name: str
:type exp_time: float
"""
self._db = data_provider
if id is not None:
hm = self._db.get_hazard_model_by_id(id)
elif hazard_name is not None and exp_time is not None:
hm = self._db.get_hazard_model_by_name_exptime(hazard_name,
exp_time)
else:
raise Exception("Bad initialization of HazardModel")
self._hazard_id = hm['hazard_id']
self._hazard_name = hm['hazard_name']
self._phenomenon_id = hm['phenomenon_id']
self._phenomenon_name = self._db.get_phenomenon_by_id(
hm['phenomenon_id'])['name']
self._datagrid_id = hm['datagrid_id']
self._exposure_time = float(hm['exposure_time'])
self._iml = [float(l) for l in hm['iml'].split()]
self._imt = hm['imt']
self._date = hm['date']
self.statistics = self._db.get_statistics_by_haz(self._hazard_id)
self._grid_points = self._db.get_points_by_datagrid_id(self.datagrid_id)
self._grid_limits = {'east_min': min([p['easting']
for p in self._grid_points]),
'east_max': max([p['easting']
for p in self._grid_points]),
'north_min': min([p['northing']
for p in self._grid_points]),
'north_max': max([p['northing']
for p in self._grid_points])}
self._curves = {}
self._points_data = []
def fetch_all_points_data(self):
self._points_data = self._db.get_points_all_data(self.phenomenon_id,
self.hazard_id,
self.grid_points)
# print self._points_data[1000]
# print len(self._points_data)
# print self._points_data[0]
def curves_by_statistics(self, statistic_name='mean'):
"""
Return all points and corrisponding data curve for specified statistic.
:type statistic_name: str
:return: list of dict {'point': {}, 'curve':[]}
"""
try:
return self._curves[statistic_name]
except KeyError:
# print "HazardModel fetching statistic %s curves " % statistic_name
stat_id = self._db.get_statistic_by_value(statistic_name)
self._curves[statistic_name] = self._db.get_curves(
self.phenomenon_id,
self.hazard_id,
stat_id)
return self._curves[statistic_name]
def to_xml(self):
hazard_xml = ''
return
@property
def hazard_id(self):
"""Return harzard model id. """
return self._hazard_id
@property
def hazard_name(self):
"""Return harzard model name. """
return self._hazard_name
@property
def datagrid_id(self):
"""Return associated datagrid id."""
return self._datagrid_id
@property
def phenomenon_id(self):
"""Return associated phenonmenon id."""
return self._phenomenon_id
@property
def phenomenon_name(self):
"""Return associated phenonmenon name."""
return self._phenomenon_name
@property
def exposure_time(self):
"""Return associated exposure time."""
return self._exposure_time
@property
def iml(self):
"""Return associad intensity threshold list."""
return self._iml
@property
def imt(self):
"""Return associated unit measure for hazard."""
return self._imt
@property
def date(self):
"""Return date (not yer used)."""
return self._date
@property
def grid_points(self):
"""Return the associated grid points list."""
return self._grid_points
@property
def grid_limits(self):
"""Return associated grid easting and northing min/max."""
return self._grid_limits
@property
def curves(self):
"""
Return all data curves defined for all grid point in the
hazard grid.
"""
return self._curves
@property
def points_data(self):
""" Return all points data as list of dict. """
return self._points_data
class BymurCore(object):
"""
BymurCore object contain the model of ByMuR. It is in charge of organize
hazard internals rapresentation and operations. All the values are
calculated by methods defined inside this class.
"""
# Default values regardless of hazard model
_ctrls_defaut = {
'SEISMIC': {
'ret_per': 475,
'int_thresh': 0.1
},
'TSUNAMIC': {
'ret_per': 475,
'int_thresh': 0.1
},
'VOLCANIC': {
'ret_per': 475,
'int_thresh': 0.1
},
'basedir': os.getcwd(),
# TODO: da eliminare quando scarichero' le mappe
}
ens_sample_number = 1000
ens_percentiles = np.arange(5,100,5)
def __init__(self, batch = False):
self._batch_mode = batch
self._db = None
self._db_details = None
self._ctrls_data = {}
self._grid_points = []
self._hazard_options = {}
self._hazard = None
self._hazard_data = None
self._selected_point = None
# self._selected_point = HazardPoint(self)
# self._selected_area = dict(inventory=bf.InventorySection(),
self._selected_area = dict(inventory=None,
fragility=None)
# self._inventory = bf.parse_xml_inventory("data/InventoryByMuR.xml")
self._inventory = None
self._fragility = None
self._loss = None
self._risk = None
self._compare_risks = []
self._selected_areas = []
self._hazard_schema = bf.HazardSchema()
def clear(self):
self.grid_points = []
self.hazard_options = {}
self.hazard = None
self.hazard_data = None
self.selected_point = None
self.selected_area = dict(inventory=None,
fragility=None,
loss = None,
risk = None)
self.selected_areas = []
self._inventory = None
self._fragility = None
self._loss = None
self._risk = None
self._compare_risks = []
def load_db(self, **dbDetails):
""" Connect database and load hazard models data."""
if (not self._db) and dbDetails:
self.connect_db(**dbDetails)
self._ctrls_data = self.get_controls_data()
def connect_db(self, **dbDetails):
"""
Connect database.
:param dbDetails: dict(db_host= str, db_port= str,
db_user= str, db_password= str, db_name= str)
"""
self._db_details = dbDetails
try:
self._db = db.BymurDB(**self._db_details)
except:
raise
# TODO: devo implementare un reset dei pannelli
def close_db(self):
""" Close database connection. """
if self._db:
try:
self._db.close()
self._db = None
except:
raise
self._ctrls_data = {}
self._grid_points = []
self._hazard_options = {}
self._hazard = None
self._hazard_data = None
def drop_tables(self, **kwargs):
""" Drop all tables in currently open database."""
try:
self._db.drop_tables()
except:
raise
def create_db(self, **createDBDetails):
""" Create a new database.
Create database if it doesn't exist yet. If a database with the given
name is already present, populate it with tables.
:param dbDetails: dict(db_host= str, db_port= str,
db_user= str, db_password= str, db_name= str)
"""
print "core.createDB"
if self._db:
raise Exception("You need to close the open db first!")
self._db = db.BymurDB(db_host=createDBDetails['db_host'],
db_port=createDBDetails['db_port'],
db_user=createDBDetails['db_user'],
db_password=createDBDetails['db_password'])
self.db.create(createDBDetails['db_name'])
self._ctrls_data = self.get_controls_data()
# TODO: add a dialog for successfull creation
def add_data(self, **addDBData):
"""
Read data from XML files and add to database.
:param addDBData: dict(haz_files = list(str), phenomenon = str,
datagrid_name = str)
"""
datagrid_id = self.db.get_datagrid_id_by_name(addDBData['datagrid_name'])
for f_path in addDBData['haz_files']:
print "Testing %s" % f_path
xml_type = bf.get_filetype(f_path)
if xml_type == 'hazardResult':
h_xml = bf.parse_xml_hazard(f_path)
self.db.add_hazard(h_xml, datagrid_id)
elif xml_type == 'arealFragilityModel':
f_xml = bf.parse_xml_fragility(f_path)
self.db.add_fragility(f_xml)
elif xml_type == 'arealLossModel':
l_xml = bf.parse_xml_loss(f_path)
self.db.add_loss(l_xml)
elif xml_type == 'arealRiskModel':
r_xml = bf.parse_xml_risk(f_path)
self.db.add_risk(r_xml)
self._ctrls_data = self.get_controls_data()
def load_grid(self, **gridData):
"""
Read grid from file and add it to database.
:param gridData: dict(basedir=str, filepath=str)
"""
print "core loadGrid: %s" % gridData
filepath = gridData.pop('filepath', None)
return self.db.load_grid(filepath)
def get_controls_data(self):
""" Read hazard models data from database. """
ret = {}
hazard_models = self.db.get_hazard_models_list()
for ind, hazard in enumerate(hazard_models):
haz_tmp = hazard
if haz_tmp['phenomenon_name'] == 'VOLCANIC':
haz_tmp['volcano'] = self.db.get_volcanos_list(
haz_tmp['hazard_id'])
else:
haz_tmp['volcano'] = None
hazard_models[ind] = haz_tmp
ret['hazard_models'] = hazard_models
ret['phenomena'] = self.db.get_phenomena_list()
# print "phenomena %s " % ret['phenomena']
return ret
def read_fragility_model(self, phenomenon_id):
frag_dic = self.db.get_fragility_model_by_phenid(phenomenon_id)
_fragility = bf.FragilityModel()
_fragility.id = frag_dic['id']
_fragility.model_name = frag_dic['model_name']
_fragility.description = frag_dic['description']
_fragility.imt = frag_dic['imt']
_fragility.iml = [float(l) for l in frag_dic['iml'].split(" ")]
_fragility.hazard_type = self.db.get_phenomenon_by_id(
frag_dic['phenomenon_id'])['name']
_fragility.limit_states = [ls['name'] for ls in
self.db.get_limitstates_by_frag_id(frag_dic['id'])]
_fragility.statistics = [st['name'] for st in
self.db.get_statistics_by_frag_id(frag_dic['id'])]
return _fragility
def read_loss_model(self, phenomenon_id, frag_id):
loss_dic = self.db.get_loss_model_by_phenid(phenomenon_id)
_loss = bf.LossModel()
_loss.id = loss_dic['id']
_loss.loss_type = loss_dic['loss_type']
_loss.model_name = loss_dic['model_name']
_loss.description = loss_dic['description']
_loss.unit = loss_dic['unit']
_loss.hazard_type = self.db.get_phenomenon_by_id(
loss_dic['phenomenon_id'])['name']
_loss.limit_states = [ls['name'] for ls in
self.db.get_limitstates_by_frag_id(frag_id)]
_loss.statistics = [st['name'] for st in
self.db.get_statistics_by_loss_id(loss_dic['id'])]
return _loss
def read_risk_model(self, haz_id):
risk_dic = self.db.get_risk_model_by_hazid(haz_id)
print "Risk dic: %s" % risk_dic
if risk_dic is None:
return None
_risk = bf.RiskModel()
_risk.id = risk_dic['id']
_risk.risk_type = risk_dic['risk_type']
_risk.model_name = risk_dic['model_name']
_risk.hazard_model_name = self.db.get_hazard_model_by_id(risk_dic[
'hazard_id'])['hazard_name']
_risk.fragility_model_name = self.db.get_fragility_model_by_id(risk_dic[
'fragility_id'])['model_name']
_risk.loss_model_name = self.db.get_loss_model_by_id(risk_dic[
'loss_id'])['model_name']
_risk.description = risk_dic['description']
_risk.investigation_time = risk_dic['investigation_time']
_risk.hazard_type = self.db.get_phenomenon_by_id(
risk_dic['phenomenon_id'])['name']
_risk.statistics = [st['name'] for st in
self.db.get_statistics_by_risk_id(risk_dic['id'])]
return _risk
def read_inventory_model(self, grid_id):
inv_dic = self.db.get_inventory_by_datagrid_id(grid_id)
_inventory = bf.InventoryModel(name=inv_dic['name'])
_inventory.classes.update({'generalClasses':[],
'ageClasses':[],
'houseClasses':[]})
for c in inv_dic['general_classes']:
_inventory.classes['generalClasses'].append(
bf.InventoryGeneralClass(name=c['name'],
label=c['label']))
for c in inv_dic['age_classes']:
_inventory.classes['ageClasses'].append(
bf.InventoryAgeClass(name=c['name'],
label=c['label']))
for c in inv_dic['house_classes']:
_inventory.classes['houseClasses'].append(
bf.InventoryHouseClass(name=c['name'],
label=c['label']))
_inventory.classes['costClasses'] = dict()
for phen_class in inv_dic['cost_classes']:
phen = phen_class['phenomenon_name']
_inventory.classes['costClasses'][phen.lower()] = []
for c_str in phen_class['classes'].split(":"):
c_name, c_label = c_str.lstrip("(").rstrip(")").split(",")
c_tmp = bf.InventoryCostClass(phenomenon=phen.lower(),
name=c_name,
label=c_label)
_inventory.classes['costClasses']\
[phen.lower()].append(c_tmp)
_inventory.classes['fragilityClasses'] = dict()
for phen_class in inv_dic['fragility_classes']:
phen = phen_class['phenomenon_name'].lower()
_inventory.classes['fragilityClasses'][phen] = []
for c_str in phen_class['classes'].split(":"):
c_name, c_label = c_str.lstrip("(").rstrip(")").split(",")
c_tmp = bf.InventoryFragilityClass(phenomenon=phen,
name=c_name,
label=c_label)
_inventory.classes['fragilityClasses']\
[phen].append(c_tmp)
_inventory_sections = self.db.get_sections_by_inventory_id(
inv_dic['inventory_id'])
for sec in _inventory_sections:
sec_tmp = bf.InventorySection()
sec_tmp.areaID = int(sec['areaID'])
sec_tmp.sectionID = int(sec['sectionID'])
sec_tmp.centroid = (float(sec['centroidX']),
float(sec['centroidY']))
sec_tmp.geometry = [(float(p.strip().split(" ")[0]),
float(p.strip().split(" ")[1]))
for p in sec['geometry'].split(",")]
sec_tmp.asset = bf.InventoryAsset()
sec_tmp.asset.total = int(sec['total_buildings'])
if sec_tmp.asset.total > 0:
sec_tmp.asset.counts['genClassCount'] = \
[int(i) for i in sec['general_classes_count'].split(" ")]
sec_tmp.asset.counts['ageClassCount'] = \
[int(i) for i in sec['age_classes_count'].split(" ")]
sec_tmp.asset.counts['houseClassCount'] = \
[int(i) for i in sec['house_classes_count'].split(" ")]
cc_prob = self.db.get_costclass_prob_by_area_id(sec['id'])
for phen_class in cc_prob:
phen = phen_class['phenomenon_name'].lower()
fnc_tmp = [float(f) for f in phen_class['fnc'].split(" ")]
sec_tmp.asset.cost_class_prob[phen] = dict(fnc=fnc_tmp)
fc_prob = self.db.get_fragclass_prob_by_area_id(sec['id'])
for phen_class in fc_prob:
phen = phen_class['phenomenon_name'].lower()
fnt_tmp = [float(f) for f in phen_class['fnt'].split(" ")]
fnt_given_tmp = [[float(x) for x in c_list.split(" ")]
for c_list in
phen_class['fnt_given_general_class'].split(",")]
sec_tmp.asset.frag_class_prob[phen] = \
dict(fnt=fnt_tmp,
fntGivenGeneralClass = fnt_given_tmp)
_inventory.sections.append(sec_tmp)
return _inventory
def updateModel(self, **ctrls_options):
"""Update HazardModel reflecting selected options. """
# print "ctrls_options %s" % ctrls_options
self.clear()
haz_tmp = ctrls_options
haz_tmp['hazard_threshold'] = 1 - math.exp(- haz_tmp['exp_time'] /
haz_tmp['ret_per'])
self.hazard_options = haz_tmp
self._hazard = HazardModel(self._db,
hazard_name=
self.hazard_options['hazard_name'],
exp_time=self.hazard_options['exp_time'])
self.inventory = self.read_inventory_model(self._hazard.datagrid_id)
if ctrls_options['risk_model_name'] is not None and ctrls_options[
'risk_model_name'] != '':
print "Reading fragility, loss and risk models"
self.fragility = self.read_fragility_model(self._hazard.phenomenon_id)
self.loss = self.read_loss_model(self._hazard.phenomenon_id,
self.fragility.id)
self.risk = self.read_risk_model(self._hazard.hazard_id)
# TODO: grid_point should be eliminated from here
# TODO: or from
self.grid_points = self._hazard.grid_points
self.hazard_data = self._compute_hazard_data(
self._hazard,
self.hazard_options['int_thresh'],
self.hazard_options['hazard_threshold'])
def set_areas_by_list(self, areas):
print "Selected areas: %s" % len(areas)
_area_list = []
for a in areas:
area_tmp=dict()
area_tmp['areaID'] = a['inventory'].areaID
area_tmp['area_db_id'] = \
self.db.get_area_dbid_by_areaid(area_tmp['areaID'])
area_tmp['inventory'] = a['inventory']
area_tmp['patch'] = a['patch']
if self.risk is not None:
area_tmp['fragility'] = self.db.get_fragdata_by_areaid(
self.fragility.id, area_tmp['areaID'])
area_tmp['loss'] = self.db.get_lossdata_by_areaid(
self.loss.id, area_tmp['areaID'])
area_tmp['risk'] = self.db.get_riskdata_by_areaid(
self.risk.id, area_tmp['areaID'])
area_tmp['compare_risks'] = []
for c_r in self.compare_risks:
area_tmp['compare_risks'].append(
self.db.get_riskdata_by_areaid(c_r.id,
area_tmp['areaID']))
_area_list.append(area_tmp)
self.selected_areas = _area_list
def set_areas_by_ID(self, areaID_list):
_area_list = []
for sec in self.inventory.sections:
if sec.areaID in areaID_list:
area_tmp=dict()
area_tmp['areaID'] = sec.areaID
area_tmp['area_db_id'] = \
self.db.get_area_dbid_by_areaid(sec.areaID)
area_tmp['inventory'] = sec
# TODO: questi dovrebbero diventare oggetti
if self.risk is not None:
area_tmp['fragility'] = self.db.get_fragdata_by_areaid(
self.fragility.id, sec.areaID)
area_tmp['loss'] = self.db.get_lossdata_by_areaid(
self.loss.id, sec.areaID)
area_tmp['risk'] = self.db.get_riskdata_by_areaid(
self.risk.id, sec.areaID)
area_tmp['compare_risks'] = []
for c_r in self.compare_risks:
area_tmp['compare_risks'].append(
self.db.get_riskdata_by_areaid(c_r.id, sec.areaID))
_area_list.append(area_tmp)
self.selected_areas = _area_list
def set_point_by_index(self, index):
"""
Set selected point by index in model.
:param index: bigint
"""
try:
tmp = HazardPoint(self)
tmp.update(self.hazard, index,
self.hazard_options['hazard_threshold'],
self.hazard_options['int_thresh'])
self.selected_point = tmp
# self.selected_point.update(self.hazard, index,
# self.hazard_options['hazard_threshold'],
# self.hazard_options['int_thresh'])
return True
except Exception as e:
print "Exception in select_point_by_index: %s" % str(e)
return False
# def set_selected_areas(self, areas):
# self._selected_areas = areas
def set_point_by_coordinates(self, xpoint, ypoint):
"""
Set selected point by coordinates in model.
:param xpoint: bigint
:param ypoint: bigint
"""
xsel = np.float64(xpoint)
ysel = np.float64(ypoint)
if (self.hazard.grid_limits['east_min'] <= xsel <=
self.hazard.grid_limits['east_max']
and self.hazard.grid_limits['north_min'] <= ysel <=
self.hazard.grid_limits['north_max']):
distances = np.hypot(xsel-[p['easting'] for p in self.grid_points],
ysel-[p['northing'] for p in self.grid_points])
tmp = HazardPoint(self)
tmp.update(self.hazard, distances.argmin(),
self.hazard_options['hazard_threshold'],
self.hazard_options['int_thresh'])
self.selected_point = tmp
return True
else:
return False
def get_haz_value(self, int_thresh_list, hazard_threshold, curve):
"""
Calculate and return hazard value interpolation.
:type int_thresh_list: list of float
:type hazard_threshold: float
:type curve: list of float
:return: float
"""
y_th = hazard_threshold
y = curve
x = int_thresh_list
x_1 = x_2 = float('NaN')
for i in range(len(curve)):
if y[i] < y_th:
if i > 0:
y_1 = y[i - 1]
x_1 = x[i - 1]
else:
y_1 = 1
x_1 = 0
y_2 = y[i]
x_2 = x[i]
try:
x_th = x_1 + (x_2 - x_1) * (y_th - y_1) / (y_2 - y_1)
except:
x_th = float('NaN')
finally:
return x_th
return x[len(x) - 1]
def get_prob_value(self, int_thresh_list, intensity_threshold, curve):
"""
Calculate and probability hazard value interpolation.
:type int_thresh_list: list of float
:type intensity_threshold: float
:type curve: list of float
:return: float
"""
x_th = intensity_threshold
y = curve
x = int_thresh_list
y_1 = y_2 = float('NaN')
for i in range(len(x)):
if x[i] > x_th:
if i > 0:
y_1 = y[i - 1]
x_1 = x[i - 1]
else:
y_1 = 1
x_1 = 0
y_2 = y[i]
x_2 = x[i]
try:
y_th = y_1 + (y_2 - y_1) * (x_th - x_1) / (x_2 - x_1)
except:
y_th = float('NaN')
finally:
return y_th
return y[len(x) - 1]
def _compute_hazard_data(self, hazard,
intensity_threshold, hazard_threshold,
statistic_name='mean'):
"""
Calculate hazard statistics interpolations for every point.
:type hazard: bymur_core.HazardModel
:type intensity_threshold: float
:type hazard_threshold: float
:type statistic_name: str
:return: list of dict(point: {}, haz_value: float, prob_value: float)
"""
self.hazard_data = hazard.curves_by_statistics(statistic_name)
return map((lambda p: dict(zip(['point', 'haz_value',
'prob_value'],
(p['point'],
self.get_haz_value(
hazard.iml,
hazard_threshold,
p['curve']),
self.get_prob_value(
hazard.iml,
intensity_threshold,
p['curve'])
)))),
self.hazard_data)
# def _get_grid_points(self, grid_id):
# return self.db.get_points_by_datagrid_id(grid_id)
def exportRawPoints(self, haz_array):
export_string = ''
for i in range(self.data['npts']):
export_string += "%f %f %f\n" % (self.data['lon'][i] *
1000, self.data['lat'][i] * 1000,
haz_array[i])
return export_string
def _comulative_prob(self, hazard, threshold_index):
pass
_comulative = list()
# devo escludere la media
# for key in hazard.curves.keys():
# for point in hazard.c
# _comulative.append(hazard.curves[key]['curve'][threshold_index])
def exportHaz(self, **local_data):
haz_model = HazardModel(self.db, hazard_name=local_data['expHazModel'],
exp_time=local_data['expHazExpTime'])
tmp_name = os.path.join(local_data['expHazDir'], haz_model.hazard_name)
if not os.path.exists(tmp_name):
os.makedirs(tmp_name)
tmp_name = os.path.join(tmp_name, local_data['expHazExpTime'])
if not os.path.exists(tmp_name):
os.makedirs(tmp_name)
for stat in haz_model.statistics:
haz_model_xml = bf.HazardModelXML(local_data['expHazPhen'])
if stat['name'] == 'mean':
haz_model_xml.statistic = 'mean'
haz_model_xml.percentile_value = '0'
filename = os.path.join(tmp_name,