-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbymur_db.py
More file actions
1869 lines (1653 loc) · 78.6 KB
/
Copy pathbymur_db.py
File metadata and controls
1869 lines (1653 loc) · 78.6 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 os
import MySQLdb as mdb
import bymur_functions as bf
class BymurDB(object):
_sql_schema = """
SET FOREIGN_KEY_CHECKS=0;
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
DROP TABLE IF EXISTS `datagrids`;
CREATE TABLE IF NOT EXISTS `datagrids` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=7 ;
DROP TABLE IF EXISTS `grid_points`;
CREATE TABLE IF NOT EXISTS `grid_points` (
`id_datagrid` int(11) NOT NULL,
`id_point` bigint(20) NOT NULL,
PRIMARY KEY (`id_datagrid`,`id_point`),
KEY `fk_grid_points_1` (`id_datagrid`),
KEY `fk_grid_points_2` (`id_point`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
DROP TABLE IF EXISTS `hazard_models`;
CREATE TABLE IF NOT EXISTS `hazard_models` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_phenomenon` int(11) NOT NULL,
`id_datagrid` int(11) NOT NULL,
`name` varchar(45) COLLATE utf8_bin NOT NULL,
`exposure_time` varchar(10) COLLATE utf8_bin DEFAULT NULL,
`iml` mediumtext COLLATE utf8_bin,
`imt` varchar(45) COLLATE utf8_bin DEFAULT NULL,
`date` date DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_hazard_models_1_idx` (`id_datagrid`),
KEY `fk_hazard_models_2_idx` (`id_phenomenon`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=44 ;
DROP TABLE IF EXISTS `hazmodel_statistics`;
CREATE TABLE IF NOT EXISTS `hazmodel_statistics` (
`id_hazard_model` int(11) NOT NULL,
`id_statistic` int(11) NOT NULL,
PRIMARY KEY (`id_hazard_model`,`id_statistic`),
KEY `fk_hazmodels_statistics_1` (`id_hazard_model`),
KEY `fk_hazmodels_statistics_2` (`id_statistic`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
DROP TABLE IF EXISTS `hazmodel_volcanos`;
CREATE TABLE IF NOT EXISTS `hazmodel_volcanos` (
`id_hazard_model` int(11) NOT NULL,
`id_volcano` int(11) NOT NULL,
PRIMARY KEY (`id_hazard_model`,`id_volcano`),
KEY `fk_hazmodel_volcano_1` (`id_hazard_model`),
KEY `fk_hazmodel_volcano_2` (`id_volcano`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
DROP TABLE IF EXISTS `phenomena`;
CREATE TABLE IF NOT EXISTS `phenomena` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=10 ;
DROP TABLE IF EXISTS `points`;
CREATE TABLE IF NOT EXISTS `points` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`easting` bigint(20) NOT NULL,
`northing` bigint(20) NOT NULL,
`zone_number` tinyint(4) DEFAULT NULL,
`zone_letter` char(1) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `coords` (`easting`,`northing`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=206903 ;
DROP TABLE IF EXISTS `seismic_data`;
CREATE TABLE IF NOT EXISTS `seismic_data` (
`id_hazard_model` int(11) NOT NULL,
`id_point` bigint(20) NOT NULL,
`id_statistic` int(11) NOT NULL,
`hazard_curve` mediumtext COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id_hazard_model`,`id_point`,`id_statistic`),
KEY `index_haz_grid_stat` (`id_hazard_model`,`id_statistic`),
KEY `fk_seismic_data_1` (`id_hazard_model`),
KEY `fk_seismic_data_2` (`id_point`),
KEY `fk_seismic_data_4` (`id_statistic`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
DROP TABLE IF EXISTS `statistics`;
CREATE TABLE IF NOT EXISTS `statistics` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=152 ;
DROP TABLE IF EXISTS `tsunamic_data`;
CREATE TABLE IF NOT EXISTS `tsunamic_data` (
`id_hazard_model` int(11) NOT NULL,
`id_point` bigint(20) NOT NULL,
`id_statistic` int(11) NOT NULL,
`hazard_curve` mediumtext COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id_hazard_model`,`id_point`,`id_statistic`),
KEY `index_haz_grid_stat` (`id_hazard_model`,`id_statistic`),
KEY `fk_tsunamic_data_1` (`id_hazard_model`),
KEY `fk_tsunamic_data_2_idx` (`id_point`),
KEY `fk_tsunamic_data_3_idx` (`id_statistic`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
DROP TABLE IF EXISTS `volcanic_data`;
CREATE TABLE IF NOT EXISTS `volcanic_data` (
`id_hazard_model` int(11) NOT NULL,
`id_point` bigint(20) NOT NULL,
`id_statistic` int(11) NOT NULL,
`hazard_curve` mediumtext COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id_hazard_model`,`id_point`,`id_statistic`),
KEY `index_haz_grid_stat` (`id_hazard_model`,`id_statistic`),
KEY `fk_volcanic_data_3_idx` (`id_statistic`),
KEY `fk_volcanic_data_2` (`id_point`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
DROP TABLE IF EXISTS `volcanos`;
CREATE TABLE IF NOT EXISTS `volcanos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;
ALTER TABLE `grid_points`
ADD CONSTRAINT `fk_grid_points_1` FOREIGN KEY (`id_datagrid`) REFERENCES `datagrids` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_grid_points_2` FOREIGN KEY (`id_point`) REFERENCES `points` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE `hazard_models`
ADD CONSTRAINT `fk_hazard_models_1` FOREIGN KEY (`id_datagrid`) REFERENCES `datagrids` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_hazard_models_2` FOREIGN KEY (`id_phenomenon`) REFERENCES `phenomena` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE `hazmodel_statistics`
ADD CONSTRAINT `fk_hazmodels_statistics_1` FOREIGN KEY (`id_hazard_model`) REFERENCES `hazard_models` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_hazmodels_statistics_2` FOREIGN KEY (`id_statistic`) REFERENCES `statistics` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE `hazmodel_volcanos`
ADD CONSTRAINT `fk_hazmodel_volcano_1` FOREIGN KEY (`id_hazard_model`) REFERENCES `hazard_models` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_hazmodel_volcano_2` FOREIGN KEY (`id_volcano`) REFERENCES `volcanos` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE `seismic_data`
ADD CONSTRAINT `fk_seismic_data_1` FOREIGN KEY (`id_hazard_model`) REFERENCES `hazard_models` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_seismic_data_2` FOREIGN KEY (`id_point`) REFERENCES `points` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_seismic_data_3` FOREIGN KEY (`id_statistic`) REFERENCES `statistics` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE `tsunamic_data`
ADD CONSTRAINT `fk_tsunamic_data_1` FOREIGN KEY (`id_hazard_model`) REFERENCES `hazard_models` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_tsunamic_data_2` FOREIGN KEY (`id_point`) REFERENCES `points` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_tsunamic_data_3` FOREIGN KEY (`id_statistic`) REFERENCES `statistics` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE `volcanic_data`
ADD CONSTRAINT `fk_volcanic_data_1` FOREIGN KEY (`id_hazard_model`) REFERENCES `hazard_models` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_volcanic_data_2` FOREIGN KEY (`id_point`) REFERENCES `points` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_volcanic_data_3` FOREIGN KEY (`id_statistic`) REFERENCES `statistics` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
SET FOREIGN_KEY_CHECKS=1;
INSERT INTO `phenomena` (`name`) VALUES('SEISMIC');
INSERT INTO `phenomena` (`name`) VALUES('TSUNAMIC');
INSERT INTO `phenomena` (`name`) VALUES('VOLCANIC')
"""
def __init__(self, **kwargs):
"""
Connecting to database
"""
try:
if kwargs.get('db_name') is None:
print "Creating db!"
self._connection = mdb.connect(host=kwargs.pop('db_host',
'localhost'),
port=int(kwargs.pop('db_port',
3306)),
user=kwargs.pop('db_user',
'bymurTEST'),
passwd=kwargs.pop('db_password',
'bymurTEST'))
else:
print "Connecting db!"
self._connection = mdb.connect(host=kwargs.pop('db_host',
'localhost'),
port=int(kwargs.pop('db_port',
3306)),
user=kwargs.pop('db_user',
'bymurTEST'),
passwd=kwargs.pop('db_password',
'bymurTEST'),
db=kwargs.pop('db_name',
'bymurTEST'))
self._connection.autocommit(True)
self._cursor = self._connection.cursor()
except:
raise
def create(self, dbname):
# print "db.create"
# print "dbname %s" % dbname
# using manual escape to avoid unsupported quoting
sqlquery = "CREATE DATABASE IF NOT EXISTS %s"
sqlquery %= mdb.escape_string(dbname)
self._cursor.execute(sqlquery)
# print "use"
sqlquery = "USE %s"
sqlquery %= mdb.escape_string(dbname)
self._cursor.execute(sqlquery)
# print "import"
for sql in self._sql_schema.split(";"):
self._cursor.execute(sql)
self.commit()
def commit(self):
self._connection.commit()
def drop_tables(self):
query = "SHOW TABLES"
self._cursor.execute("SET FOREIGN_KEY_CHECKS = 0")
self._cursor.execute(query)
tables = self._cursor.fetchall()
print tables
for tab in tables:
query = "DROP TABLE %s"
query %= tab[0]
print query
self._cursor.execute(query)
self._cursor.execute("SET FOREIGN_KEY_CHECKS = 1")
def close(self):
self._connection.close()
def get_datagrid_id_by_name(self, name):
sqlquery = "SELECT id FROM datagrids WHERE name = '{0}'"
self._cursor.execute(sqlquery.format(name.upper()))
id = self._cursor.fetchone()
if id:
return id[0]
else:
return 0
def get_datagrid_name_by_id(self, id):
sqlquery = "SELECT name FROM datagrids WHERE id = {0}"
self._cursor.execute(sqlquery.format(id))
id = self._cursor.fetchone()
if id:
return id[0]
else:
return 0
def get_datagrids_list(self):
sqlquery = "SELECT id, name FROM datagrids"
self._cursor.execute(sqlquery)
return [dict(zip(('datagrid_id', 'datagrid_name'), phen))
for phen in self._cursor.fetchall()]
def insert_id_datagrid(self, name):
sqlquery = "SELECT id FROM datagrids WHERE name = '{0}'"
self._cursor.execute(sqlquery.format(name.upper()))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = "INSERT INTO datagrids (name) VALUES('{0}')"
self._cursor.execute(sqlquery.format(name.upper()))
return self._cursor.lastrowid
def insert_datagrid_points(self, datagrid_id, points):
"""
"""
# # Insert grid if it doesn't exists
# datagrid_id = self.datagrid_get_insert_id(datagrid_name)
# Insert points
# print "Point insert result: %s" % self.points_insert(points)
# Get list of points id
pointsid_list = self.get_pointsid_list_by_coords(points)
# print "Points id list: %s " % pointsid_list
# Associate grid with points
return self.insert_datagrid_points_rels(datagrid_id, pointsid_list)
def insert_datagrid_points_rels(self, datagrid_id, points_id_list):
"""
"""
sqlquery = """
INSERT IGNORE INTO grid_points (id_datagrid, id_point)
VALUES(""" + str(datagrid_id) + """, %s)"""
return self._cursor.executemany(sqlquery, [(id,) for id
in points_id_list])
def get_points_by_datagrid_id(self, datagrid_id):
sqlquery = """ SELECT `p`.`id`, `p`.`easting`, `p`.`northing`,
`p`.`zone_number`, `p`.`zone_letter`
FROM `points` p LEFT JOIN `grid_points` gp ON p.`id`=gp.`id_point`
WHERE gp.`id_datagrid`= %s ORDER BY `p`.`id`
"""
sqlquery %= str(datagrid_id)
self._cursor.execute(sqlquery)
return [dict(zip(['id', 'easting', 'northing',
'zone_number', 'zone_letter'], x))
for x in self._cursor.fetchall()]
def get_pointsid_list_by_coords(self, points):
"""
Get points id list from table 'point'
:param points: list of point dictionaries
:return:
"""
# print points
sqlquery = """
SELECT id FROM points WHERE (easting, northing,
zone_number, zone_letter)
IN (%s)
"""
if len(points) < 1:
return -1
points_list = ', '.join([str((x['easting'], x['northing'],
x['zone_number'], x['zone_letter'])) for
x in
points])
sqlquery %= points_list
self._cursor.execute(sqlquery)
return [item[0] for item in self._cursor.fetchall()]
def insert_utm_points(self, points):
"""
Insert multiple point in table 'points' if they don't already exist
:param points: list of point dictionaries
:return: number of new points inserted
"""
sqlquery = """
INSERT IGNORE INTO points (easting,
northing, zone_number, zone_letter)
VALUES(%(easting)s, %(northing)s,
%(zone_number)s, %(zone_letter)s)
"""
return self._cursor.executemany(sqlquery, points)
def get_hazard_models_list(self):
sqlquery = """
SELECT `haz`.`id` as `haz_id`,
`haz`.`name` as `haz_name`,
`haz`.`exposure_time` as `exp_time`,
`haz`.`iml` as `iml`,
`haz`.`imt` as `imt`,
`haz`.`date` as `date`,
`phen`.`id` as `id_phenomenon`,
`phen`.`name` as `phenomenon_name`,
`haz`.`id_datagrid` as `grid_id`,
`grid`.`name` as `grid_name`,
`risk`.`model_name`
FROM ((`hazard_models` haz LEFT JOIN `phenomena` phen
ON `haz`.`id_phenomenon`=`phen`.`id`) JOIN
`datagrids` grid ON `haz`.`id_datagrid`=`grid`.`id`)
LEFT JOIN `risk_models` `risk`
ON `haz`.`id` = `risk`.`id_hazard_model`
"""
self._cursor.execute(sqlquery)
return [dict(zip(['hazard_id', 'hazard_name', 'exposure_time', 'iml',
'imt', 'date', 'phenomenon_id',
'phenomenon_name', 'grid_id', 'grid_name',
'risk_model_name'], x))
for x in self._cursor.fetchall()]
def get_hazard_model_by_id(self, haz_id):
sqlquery = """ SELECT `haz_mod`.`id`,
`haz_mod`.`id_phenomenon`,
`haz_mod`.`id_datagrid`,
`haz_mod`.`name`,
`haz_mod`.`exposure_time`,
`haz_mod`.`iml`,
`haz_mod`.`imt`,
`haz_mod`.`date`
FROM `hazard_models` `haz_mod`
WHERE `haz_mod`.`id`= %s
"""
sqlquery %= str(haz_id)
# print sqlquery
self._cursor.execute(sqlquery)
return dict(zip(['hazard_id', 'phenomenon_id', 'datagrid_id',
'hazard_name', 'exposure_time', 'iml', 'imt', 'date'],
self._cursor.fetchone()))
# TODO: sistemare questa
def get_hazard_model_by_name_exptime(self, haz_name, exp_time):
sqlquery = """ SELECT `haz_mod`.`id`,
`haz_mod`.`id_phenomenon`,
`haz_mod`.`id_datagrid`,
`haz_mod`.`name`,
`haz_mod`.`exposure_time`,
`haz_mod`.`iml`,
`haz_mod`.`imt`,
`haz_mod`.`date`
FROM `hazard_models` `haz_mod`
WHERE `haz_mod`.`name`= '%s' AND `haz_mod`.`exposure_time`= '%s'
"""
sqlquery %= (str(haz_name.upper()), str(exp_time))
self._cursor.execute(sqlquery)
return dict(zip(['hazard_id', 'phenomenon_id', 'datagrid_id',
'hazard_name', 'exposure_time', 'iml', 'imt', 'date'],
self._cursor.fetchone()))
def insert_id_hazard_model(self, id_phen, id_datagrid, name,
exp_time, iml, imt, date='0'):
sqlquery = """SELECT id FROM hazard_models
WHERE name = '{0}' AND exposure_time = '{1}'
"""
self._cursor.execute(sqlquery.format(name.upper(), exp_time))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = """
INSERT INTO hazard_models (id_phenomenon, id_datagrid,
name, exposure_time, iml, imt, date)
VALUES({0}, {1}, '{2}', '{3}', '{4}',
'{5}', {6})
"""
self._cursor.execute(sqlquery.format(id_phen, id_datagrid,
name.upper(), exp_time,
iml, imt, date))
return self._cursor.lastrowid
def get_phenomena_list(self):
sqlquery = "SELECT id, name FROM phenomena"
self._cursor.execute(sqlquery)
return [dict(zip(('phenomenon_id', 'phenomenon_name'), phen))
for phen in self._cursor.fetchall()]
def get_phenomenon_by_id(self, phenomeon_id):
sqlquery = """ SELECT `ph`.`id`, `ph`.`name`
FROM `phenomena` `ph` WHERE `ph`.`id`= '{0}'
"""
self._cursor.execute(sqlquery.format(phenomeon_id))
return dict(zip(['id', 'name'], self._cursor.fetchone()))
def insert_id_phenomenon(self, phenomenon_name):
sqlquery = "SELECT id FROM phenomena WHERE name = '{0}'"
self._cursor.execute(sqlquery.format(phenomenon_name.upper()))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = "INSERT INTO phenomena (name) VALUES('{0}')"
self._cursor.execute(sqlquery.format(phenomenon_name.upper()))
return self._cursor.lastrowid
def get_statistic_by_value(self, statistic_name):
sqlquery = """ SELECT `st`.`id`
FROM `statistics` `st` WHERE `st`.`name`= '{0}'
"""
# sqlquery %= str(statistic_name)
self._cursor.execute(sqlquery.format(statistic_name))
return self._cursor.fetchone()[0]
def get_statistics_by_haz(self, haz_id):
sqlquery = """ SELECT `st`.`id`, `st`.`name`
FROM `hazmodel_statistics` `haz_stat` LEFT JOIN
`statistics` `st` ON
`haz_stat`.`id_statistic`=`st`.`id`
WHERE `haz_stat`.`id_hazard_model`= %s
"""
sqlquery %= str(haz_id)
self._cursor.execute(sqlquery)
return [dict(zip(['id', 'name'], (x[0], x[1])))
for x in self._cursor.fetchall()]
def insert_id_statistic(self, statistic,
percentile_value):
sqlquery = "SELECT id FROM statistics WHERE name = '{0}'"
if (percentile_value) == '0' or (percentile_value is None) or (
percentile_value == 0):
statistic_name = statistic
else:
statistic_name = statistic + str(percentile_value).zfill(2)
self._cursor.execute(sqlquery.format(statistic_name))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = "INSERT INTO statistics (name) VALUES('{0}')"
self._cursor.execute(sqlquery.format(statistic_name))
return self._cursor.lastrowid
def insert_id_statistic_new(self, statistic):
sqlquery = "SELECT id FROM statistics WHERE name = '{0}'"
self._cursor.execute(sqlquery.format(statistic))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = "INSERT INTO statistics (name) VALUES('{0}')"
self._cursor.execute(sqlquery.format(statistic))
return self._cursor.lastrowid
def insert_hazard_statistic_rel(self, hazard_id, statistic_id):
"""
"""
sqlquery = """
INSERT IGNORE INTO hazmodel_statistics
(id_hazard_model, id_statistic)
VALUES ({0}, {1})"""
return self._cursor.execute(sqlquery.format(hazard_id, statistic_id))
def get_volcanos_list(self, haz_id):
sqlquery = """ SELECT `vol`.`id`, `vol`.`name`
FROM `hazmodel_volcanos` `haz_vol` LEFT JOIN
`volcanos` `vol` ON
`haz_vol`.`id_volcano`=`vol`.`id`
WHERE `haz_vol`.`id_hazard_model`= %s
"""
sqlquery %= str(haz_id)
self._cursor.execute(sqlquery)
return [dict(zip(['id', 'name'], x))
for x in self._cursor.fetchall()]
def insert_id_volcano(self, volcano):
sqlquery = "SELECT id FROM volcanos WHERE name = '{0}'"
self._cursor.execute(sqlquery.format(volcano.upper()))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = "INSERT INTO volcanos (name) VALUES('{0}')"
self._cursor.execute(sqlquery.format(volcano.upper()))
return self._cursor.lastrowid
def insert_hazard_volcano_rel(self, hazard_id, volcano_id):
"""
"""
sqlquery = """
INSERT IGNORE INTO hazmodel_volcanos
(id_hazard_model, id_volcano)
VALUES({0}, {1})"""
return self._cursor.execute(sqlquery.format(hazard_id, volcano_id))
def get_point_all_curves(self, phenomenon_id, hazard_id, point_id):
"""
:rtype : object
"""
phenomenon = self.get_phenomenon_by_id(phenomenon_id)
if phenomenon['name'] == 'VOLCANIC':
table_name = "volcanic_data"
elif phenomenon['name'] == 'SEISMIC':
table_name = "seismic_data"
elif phenomenon['name'] == 'TSUNAMIC':
table_name = "tsunamic_data"
else:
return None
sqlquery = """
SELECT `st`.`name`,
`dt`.`hazard_curve`
FROM `{0}` `dt` JOIN `statistics` `st` ON
`dt`.`id_statistic` = `st`.`id`
WHERE `dt`.`id_hazard_model`={1} AND
`dt`.`id_point`={2}
"""
query = sqlquery.format(table_name, hazard_id, point_id)
self._cursor.execute(query)
res = self._cursor.fetchall()
return dict(res)
def get_points_all_data(self, phenomenon_id, hazard_model_id, points):
_res = list()
for p in points:
data = self.get_point_all_curves(phenomenon_id,
hazard_model_id,
p['id'])
_point_data = dict(zip([stat[len("percentile"):]
for stat in data.keys() if stat != "mean"],
[[float(x) for x in val.split(',')]
for val in data.values()]))
_res.append(dict(zip(['point_id', 'point_data'],
[p['id'], _point_data])))
return _res
def get_curves(self, phenomenon_id, hazard_model_id, stat_id):
phenomenon = self.get_phenomenon_by_id(phenomenon_id)
if phenomenon['name'] == 'VOLCANIC':
table_name = "volcanic_data"
elif phenomenon['name'] == 'SEISMIC':
table_name = "seismic_data"
elif phenomenon['name'] == 'TSUNAMIC':
table_name = "tsunamic_data"
else:
return None
sqlquery = """ SELECT `p`.`id`, `p`.`easting`, `p`.`northing`,
`p`.`zone_number`, `p`.`zone_letter`,
`d`.`hazard_curve` FROM
`{0}` `d` LEFT JOIN `points` `p`
ON `d`.`id_point`=`p`.`id`
WHERE `d`.`id_hazard_model`= {1}
AND `d`.`id_statistic` = {2}
"""
self._cursor.execute(sqlquery.format(table_name,
hazard_model_id,
stat_id))
return [dict(zip(['point', 'curve'],
(dict(zip(['id', 'easting', 'northing',
'zone_number', 'zone_letter'],
(x[0], x[1], x[2], x[3], x[4]))),
([float(a) for a in x[5].split(',')]))))
for x in self._cursor.fetchall()]
def insert_hazard_data(self, phenomenon, hazard_model_id, stat_id,
points, curves):
if phenomenon == 'VOLCANIC':
table_name = "volcanic_data"
elif phenomenon == 'SEISMIC':
table_name = "seismic_data"
elif phenomenon == 'TSUNAMIC':
table_name = "tsunamic_data"
if len(curves)>0:
point_curve_map = zip(points,
[", ".join(map(str, x)) for x in curves])
else:
return 0
sqlquery = """
INSERT IGNORE INTO `{0}` (id_hazard_model,
id_point, id_statistic, hazard_curve)
VALUES ( """ + str(hazard_model_id) + """
, %s, """ + str(stat_id) + """, %s )"""
sqlquery = sqlquery.format(table_name)
return self._cursor.executemany(sqlquery, point_curve_map)
def insert_volcanic_data(self, hazard_model_id, stat_id, points, curves):
return self.insert_hazard_data('VOLCANIC', hazard_model_id, stat_id,
points, curves)
def insert_seismic_data(self, hazard_model_id, stat_id, points, curves):
return self.insert_hazard_data('SEISMIC', hazard_model_id, stat_id,
points, curves)
def load_grid(self, datagridfile_path):
datagrid_name, datagrid_ext = os.path.splitext(os.path.basename(
datagridfile_path))
datagrid_points = bf.get_gridpoints_from_file(datagridfile_path)
newpoints = self.insert_utm_points(datagrid_points)
datagrid_id = self.insert_id_datagrid(datagrid_name)
rel_tmp = self.insert_datagrid_points(datagrid_id, datagrid_points)
print "Filename: %s , datagrid name: %s , id: %s" \
% (os.path.basename(datagridfile_path),
datagrid_name,
datagrid_id)
print "Read points: %s , new points inserted: %s, new rels: %s" \
% (len(datagrid_points),
newpoints,
rel_tmp)
return datagrid_name
def add_hazard(self, hazard, datagrid_id):
"""
"""
# Foreign keys are already defined
# Now insert hazard, after this other
# many-to-many relationship
phenomenon_id = self.insert_id_phenomenon(
hazard.phenomenon.upper())
print " phenomenon name: %s , id: %s" \
% (hazard.phenomenon.upper(), phenomenon_id)
print "DB > Creating hazarm_models entry"
if hazard.hazard_model_name != '':
_name = hazard.hazard_model_name
else:
_name = hazard.model_name
print "_name = %s" % _name
hazard_model_id = self.insert_id_hazard_model(
phenomenon_id,
datagrid_id,
_name,
hazard.exp_time,
hazard.iml_thresholds,
hazard.iml_imt)
# Data in hazmodel_statistics
print "DB > Inserting statistics"
stat_id = self.insert_id_statistic(
hazard.statistic,
hazard.percentile_value)
self.insert_hazard_statistic_rel(hazard_model_id,
stat_id)
print "DB > Inserting hazard data: " \
"phenomenon: %s \n" \
"hazard_model_id: %s \n" \
"datagrid_id: %s \n" \
"stat_id: %s \n" \
"exp_time : %s \n" \
"iml : %s \n" \
"imt : %s \n" \
"points_id_len: %s \n" \
"points_value_len: %s \n" \
% (
hazard.phenomenon,
hazard_model_id,
datagrid_id,
stat_id,
hazard.exp_time,
hazard.iml_thresholds,
hazard.iml_imt,
len(hazard.points_coords),
len(hazard.points_values)
)
points_idlist = self.get_pointsid_list_by_coords(
hazard.points_coords)
self.insert_hazard_data(hazard.phenomenon,
hazard_model_id,
stat_id,
points_idlist,
hazard.points_values)
# def add_data(self, datagrid_name, haz_files):
# """
#
# """
# datagrid_id = self.insert_id_datagrid(datagrid_name)
# print " datagrid name: %s , id: %s" \
# % (datagrid_name, datagrid_id)
#
# for hazFile in haz_files:
# try:
# fileXmlModel = bf.parse_xml_hazard(hazFile)
# except Exception as e:
# print "ERROR: %s is not a valid ByMuR file! %s" \
# "Skipping to next one" % (hazFile, str(e))
# continue
# # Foreign keys are already defined
# # Now insert hazard, after this other
# # many-to-many relationship
# phenomenon_id = self.insert_id_phenomenon(
# fileXmlModel.phenomenon.upper())
# print " phenomenon name: %s , id: %s" \
# % (fileXmlModel.phenomenon.upper(), phenomenon_id)
# print "DB > Creating hazarm_models entry"
# if fileXmlModel.hazard_model_name != '':
# _name = fileXmlModel.hazard_model_name
# else:
# _name = fileXmlModel.model_name
#
# print "_name = %s" % _name
# hazard_model_id = self.insert_id_hazard_model(
# phenomenon_id,
# datagrid_id,
# _name,
# fileXmlModel.exp_time,
# fileXmlModel.iml_thresholds,
# fileXmlModel.iml_imt)
#
# # Data in hazmodel_statistics
# print "DB > Inserting statistics"
# stat_id = self.insert_id_statistic(
# fileXmlModel.statistic,
# fileXmlModel.percentile_value)
#
# self.insert_hazard_statistic_rel(hazard_model_id,
# stat_id)
#
# print "DB > Inserting hazard data: " \
# "phenomenon: %s \n" \
# "hazard_model_id: %s \n" \
# "datagrid_id: %s \n" \
# "stat_id: %s \n" \
# "exp_time : %s \n" \
# "iml : %s \n" \
# "imt : %s \n" \
# "points_id_len: %s \n" \
# "points_value_len: %s \n" \
# % (
# fileXmlModel.phenomenon,
# hazard_model_id,
# datagrid_id,
# stat_id,
# fileXmlModel.exp_time,
# fileXmlModel.iml_thresholds,
# fileXmlModel.iml_imt,
# len(fileXmlModel.points_coords),
# len(fileXmlModel.points_values)
# )
#
# points_idlist = self.get_pointsid_list_by_coords(
# fileXmlModel.points_coords)
# self.insert_hazard_data(fileXmlModel.phenomenon,
# hazard_model_id,
# stat_id,
# points_idlist,
# fileXmlModel.points_values)
# del fileXmlModel
# return True
def get_general_classes_list(self):
sqlquery = "SELECT id, name, label FROM general_classes"
self._cursor.execute(sqlquery)
return [dict(zip(('id', 'name', 'label'), c))
for c in self._cursor.fetchall()]
def get_age_classes_list(self):
sqlquery = "SELECT id, name, label FROM age_classes"
self._cursor.execute(sqlquery)
return [dict(zip(('id', 'name', 'label'), c))
for c in self._cursor.fetchall()]
def get_house_classes_list(self):
sqlquery = "SELECT id, name, label FROM house_classes"
self._cursor.execute(sqlquery)
return [dict(zip(('id', 'name', 'label'), c))
for c in self._cursor.fetchall()]
def insert_id_age_class(self, name, label):
sqlquery = "SELECT id FROM age_classes WHERE name LIKE '{0}'"
self._cursor.execute(sqlquery.format(name))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = "INSERT INTO age_classes (name, label)" \
"VALUES('{0}', '{1}')"
self._cursor.execute(sqlquery.format(name, label))
return self._cursor.lastrowid
def insert_id_general_class(self, name, label):
sqlquery = "SELECT id FROM general_classes WHERE name LIKE '{0}'"
self._cursor.execute(sqlquery.format(name))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = "INSERT INTO general_classes (name, label)" \
"VALUES('{0}', '{1}')"
self._cursor.execute(sqlquery.format(name, label))
return self._cursor.lastrowid
def insert_id_house_class(self, name, label):
sqlquery = "SELECT id FROM house_classes WHERE name LIKE '{0}'"
self._cursor.execute(sqlquery.format(name))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = "INSERT INTO house_classes (name, label)" \
"VALUES('{0}', '{1}')"
self._cursor.execute(sqlquery.format(name, label))
return self._cursor.lastrowid
def insert_id_cost_classes(self, cost_classes_str, phen_id):
sqlquery = "SELECT id FROM cost_classes WHERE classes LIKE '{0}' AND " \
"id_phenomenon = '{1}'"
self._cursor.execute(sqlquery.format(cost_classes_str, phen_id))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = "INSERT INTO cost_classes (id_phenomenon, classes)" \
"VALUES('{0}', '{1}')"
self._cursor.execute(sqlquery.format(phen_id, cost_classes_str))
return self._cursor.lastrowid
def insert_id_frag_classes(self, frag_classes_str, phen_id):
sqlquery = "SELECT id FROM fragility_classes WHERE classes LIKE '{" \
"0}' AND id_phenomenon = '{1}'"
self._cursor.execute(sqlquery.format(frag_classes_str, phen_id))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = "INSERT INTO fragility_classes (id_phenomenon, " \
"classes) VALUES('{0}', '{1}')"
self._cursor.execute(sqlquery.format(phen_id, frag_classes_str))
return self._cursor.lastrowid
def get_fragility_classes_by_inv_id(self, inv_id):
sqlquery = """ SELECT `phen`.`name`, `fc`.`classes`
FROM (`inventory_frag_classes` `inv_fc` LEFT JOIN
`fragility_classes` `fc` ON
`inv_fc`.`id_frag_class`=`fc`.`id`)
LEFT JOIN `phenomena` `phen`
ON `fc`.`id_phenomenon` = `phen`.`id`
WHERE `inv_fc`.`id_inventory`= %s
"""
sqlquery %= str(inv_id)
self._cursor.execute(sqlquery)
return [dict(zip(['phenomenon_name', 'classes'], (x[0], x[1])))
for x in self._cursor.fetchall()]
def get_cost_classes_by_inv_id(self, inv_id):
sqlquery = """ SELECT `phen`.`name`, `cc`.`classes`
FROM (`inventory_cost_classes` `inv_cc` LEFT JOIN
`cost_classes` `cc` ON
`inv_cc`.`id_cost_class`=`cc`.`id`)
LEFT JOIN `phenomena` `phen`
ON `cc`.`id_phenomenon` = `phen`.`id`
WHERE `inv_cc`.`id_inventory`= %s
"""
sqlquery %= str(inv_id)
self._cursor.execute(sqlquery)
return [dict(zip(['phenomenon_name', 'classes'], (x[0], x[1])))
for x in self._cursor.fetchall()]
def get_costclass_prob_by_area_id(self, area_id):
sqlquery = """ SELECT `phen`.`name`, `cc_prob`.`fnc`
FROM `area_costclass_prob` `cc_prob` LEFT JOIN
`phenomena` `phen` ON
`cc_prob`.`id_phenomenon`=`phen`.`id`
WHERE `cc_prob`.`id_area`= %s
"""
sqlquery %= str(area_id)
self._cursor.execute(sqlquery)
return [dict(zip(['phenomenon_name', 'fnc'], (x[0], x[1])))
for x in self._cursor.fetchall()]
def get_fragclass_prob_by_area_id(self, area_id):
sqlquery = """ SELECT `phen`.`name`, `fc_prob`.`fnt`,
`fc_prob`.`fnt_given_general_class`
FROM `area_fragclass_prob` `fc_prob` LEFT JOIN
`phenomena` `phen` ON
`fc_prob`.`id_phenomenon`=`phen`.`id`
WHERE `fc_prob`.`id_area`= %s
"""
sqlquery %= str(area_id)
self._cursor.execute(sqlquery)
return [dict(zip(['phenomenon_name', 'fnt', 'fnt_given_general_class'],
(x[0], x[1], x[2]))) for x in self._cursor.fetchall()]
def insert_id_inventory(self, id_grid, name,
gen_classes, age_classes, house_classes):
sqlquery = """SELECT id FROM inventory
WHERE name = '{0}'
"""
self._cursor.execute(sqlquery.format(name.upper()))
id = self._cursor.fetchone()
if id:
return id[0]
else:
sqlquery = """
INSERT INTO inventory (grid_id, name, general_classes,
age_classes, house_classes)