This repository has been archived by the owner on Jun 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
project.py
1251 lines (1104 loc) · 44.4 KB
/
project.py
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
# coding = utf-8
from builtins import str
from builtins import object
from pglite import cluster_params
import psycopg2
import os
import sys
import atexit
import binascii
import string
from qgis import processing
from qgis.core import QgsDataSourceUri, QgsVectorLayer, QgsWkbTypes
from shapely import wkb
from dxfwrite import DXFEngine as dxf
from pglite import (
start_cluster,
stop_cluster,
init_cluster,
check_cluster,
cluster_params,
export_db,
import_db,
)
from builtins import bytes
from qgis.core import QgsMessageLog
import time
from psycopg2.extras import LoggingConnection, LoggingCursor
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# MyLoggingCursor simply sets self.timestamp at start of each query
class MyLoggingCursor(LoggingCursor):
def execute(self, query, vars=None):
self.timestamp = time.time()
return super(MyLoggingCursor, self).execute(query, vars)
def callproc(self, procname, vars=None):
self.timestamp = time.time()
return super(MyLoggingCursor, self).callproc(procname, vars)
# MyLogging Connection:
# a) calls MyLoggingCursor rather than the default
# b) adds resulting execution (+ transport) time via filter()
class MyLoggingConnection(LoggingConnection):
def filter(self, msg, curs):
return "{} {} ms".format(msg, int((time.time() - curs.timestamp) * 1000))
def cursor(self, *args, **kwargs):
kwargs.setdefault('cursor_factory', MyLoggingCursor)
return LoggingConnection.cursor(self, *args, **kwargs)
if not check_cluster():
init_cluster()
start_cluster()
#atexit.register(stop_cluster)
TABLES = [
{'NAME': 'radiometry',
'FIELDS_DEFINITION': 'gamma real',
},
{'NAME': 'resistivity',
'FIELDS_DEFINITION': 'rho real',
},
{'NAME': 'formation',
'FIELDS_DEFINITION': 'code integer, comments varchar',
},
{'NAME': 'lithology',
'FIELDS_DEFINITION': 'code integer, comments varchar',
},
{'NAME': 'facies',
'FIELDS_DEFINITION': 'code integer, comments varchar',
},
{'NAME': 'chemical',
'FIELDS_DEFINITION': 'num_sample varchar, element varchar, thickness real, gt real, grade real, equi real, comments varchar',
},
{'NAME': 'mineralization',
'FIELDS_DEFINITION': 'level_ real, oc real, accu real, grade real, comments varchar',
}]
def find_in_dir(dir_, name):
for filename in os.listdir(dir_):
if filename.find(name) != -1:
return os.path.abspath(os.path.join(dir_, filename))
return ""
class DummyProgress(object):
def __init__(self):
sys.stdout.write("\n")
self.setPercent(0)
def __del__(self):
sys.stdout.write("\n")
def setPercent(self, percent):
l = 50
a = int(round(l * float(percent) / 100))
b = l - a
sys.stdout.write("\r|" + "#" * a + " " * b + "| % 3d%%" % (percent))
sys.stdout.flush()
class ProgressBar(object):
def __init__(self, progress_bar):
self.__bar = progress_bar
self.__bar.setMaximum(100)
self.setPercent(0)
def setPercent(self, percent):
self.__bar.setValue(int(percent))
class Project(object):
def __init__(self, project_name):
# assert Project.exists(project_name)
self.__name = project_name
self.__conn_info = "dbname={} {}".format(project_name, cluster_params())
def connect(self):
con = psycopg2.connect(self.__conn_info)#, connection_factory=MyLoggingConnection)
#con.initialize(logger)
return con
def vacuum(self):
with self.connect() as con:
con.set_isolation_level(0)
cur = con.cursor()
cur.execute("vacuum analyze")
con.commit()
@staticmethod
def exists(project_name):
with psycopg2.connect("dbname=postgres {}".format(cluster_params())) as con:
cur = con.cursor()
con.set_isolation_level(0)
cur.execute(
"select pg_terminate_backend(pg_stat_activity.pid) \
from pg_stat_activity \
where pg_stat_activity.datname = '{}'".format(
project_name
)
)
cur.execute(
"select count(1) from pg_catalog.pg_database where datname='{}'".format(
project_name
)
)
res = cur.fetchone()[0] == 1
return res
@staticmethod
def delete(project_name):
assert Project.exists(project_name)
with psycopg2.connect("dbname=postgres {}".format(cluster_params())) as con:
cur = con.cursor()
con.set_isolation_level(0)
cur.execute(
"select pg_terminate_backend(pg_stat_activity.pid) \
from pg_stat_activity \
where pg_stat_activity.datname = '{}'".format(
project_name
)
)
cur.execute("drop database if exists {}".format(project_name))
cur.execute(
"select count(1) from pg_catalog.pg_database where datname='{}'".format(
project_name
)
)
con.commit()
@staticmethod
def create(project_name, srid):
assert not Project.exists(project_name)
with psycopg2.connect("dbname=postgres {}".format(cluster_params())) as con:
cur = con.cursor()
con.set_isolation_level(0)
cur.execute("create database {}".format(project_name))
con.commit()
project = Project(project_name)
with project.connect() as con:
cur = con.cursor()
cur.execute("create extension postgis")
cur.execute("create extension plpython3u")
cur.execute("create extension hstore")
cur.execute("create extension hstore_plpython3u")
include_elementary_volume = open(
os.path.join(
os.path.dirname(__file__), "elementary_volume", "__init__.py"
)
).read()
for file_ in ("_albion.sql", "albion.sql"):
for statement in (
open(os.path.join(os.path.dirname(__file__), file_))
.read()
.split("\n;\n")[:-1]
):
cur.execute(
statement.replace("$SRID", str(srid)).replace(
"$INCLUDE_ELEMENTARY_VOLUME", include_elementary_volume
)
)
con.commit()
for table in TABLES:
table['SRID'] = srid
project.add_table(table)
return project
def add_table(self, table, values=None, view_only=False):
"""
table: a dict with keys
NAME: the name of the table to create
FIELDS_DEFINITION: the sql definition (name type) of the "additional" fields (i.e. excludes hole_id, from_ and to_)
SRID: the project's SRID
values: list of tuples (hole_id, from_, to_, ...)
"""
fields = [f.split()[0].strip() for f in table['FIELDS_DEFINITION'].split(',')]
table['FIELDS'] = ', '.join(fields)
table['T_FIELDS'] = ', '.join(['t.{}'.format(f.replace(' ', '')) for f in fields])
table['FORMAT'] = ','.join([' %s' for v in fields])
table['NEW_FIELDS'] = ','.join(['new.{}'.format(v) for v in fields])
table['SET_FIELDS'] = ','.join(['{}=new.{}'.format(v,v) for v in fields])
with self.connect() as con:
cur = con.cursor()
for file_ in (("albion_table.sql",) if view_only else ("_albion_table.sql", "albion_table.sql")):
for statement in (
open(os.path.join(os.path.dirname(__file__), file_))
.read()
.split("\n;\n")[:-1]
):
cur.execute(
string.Template(statement).substitute(table)
)
if values is not None:
cur.executemany("""
insert into albion.{NAME}(hole_id, from_, to_, {FIELDS})
values (%s, %s, %s, {FORMAT})
""".format(**table), values)
cur.execute("""
refresh materialized view albion.{NAME}_section_geom_cache
""".format(**table))
con.commit()
self.vacuum()
def update(self):
"reload schema albion without changing data"
with self.connect() as con:
cur = con.cursor()
# test if version number is in metadata
cur.execute("""
select column_name
from information_schema.columns where table_name = 'metadata'
and column_name='version'
""");
if cur.fetchone():
# here goes future upgrades
cur.execute("select version from _albion.metadata")
if cur.fetchone()[0] == "2.0" and self.__has_cell():
with open(os.path.join(os.path.dirname(__file__),
"albion_raster.sql")) as f:
for statement in f.read().split("\n;\n")[:-1]:
cur.execute(statement)
cur.execute("UPDATE _albion.metadata SET version = '2.3'")
con.commit()
else:
cur.execute("select srid from albion.metadata")
srid, = cur.fetchone()
cur.execute("drop schema if exists albion cascade")
# old albion version, we upgrade the data
for statement in (
open(os.path.join(os.path.dirname(__file__), "_albion_v1_to_v2.sql"))
.read()
.split("\n;\n")[:-1]
):
cur.execute(statement.replace("$SRID", str(srid)))
include_elementary_volume = open(
os.path.join(
os.path.dirname(__file__), "elementary_volume", "__init__.py"
)
).read()
for statement in (
open(os.path.join(os.path.dirname(__file__), "albion.sql"))
.read()
.split("\n;\n")[:-1]
):
cur.execute(
statement.replace("$SRID", str(srid)).replace(
"$INCLUDE_ELEMENTARY_VOLUME", include_elementary_volume
)
)
con.commit()
cur.execute("select name, fields_definition from albion.layer")
tables = [{'NAME': r[0], 'FIELDS_DEFINITION': r[1]} for r in cur.fetchall()]
for table in tables:
table['SRID'] = str(srid)
self.add_table(table, view_only=True)
self.vacuum()
def export_sections_obj(self, graph, filename):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
with hole_idx as (
select s.id as section_id, h.id as hole_id
from _albion.named_section as s
join _albion.hole as h on s.geom && h.geom and st_intersects(s.geom, st_startpoint(h.geom))
)
select albion.to_obj(st_collectionhomogenize(st_collect(ef.geom)))
from albion.all_edge as e
join hole_idx as hs on hs.hole_id = e.start_
join hole_idx as he on he.hole_id = e.end_ and he.section_id = hs.section_id
join albion.edge_face as ef on ef.start_ = e.start_ and ef.end_ = e.end_ and not st_isempty(ef.geom)
where ef.graph_id='{}'
""".format(
graph
)
)
open(filename, "w").write(cur.fetchone()[0])
def export_sections_dxf(self, graph, filename):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
with hole_idx as (
select s.id as section_id, h.id as hole_id
from _albion.named_section as s
join _albion.hole as h on s.geom && h.geom and st_intersects(s.geom, st_startpoint(h.geom))
)
select st_collectionhomogenize(st_collect(ef.geom))
from albion.all_edge as e
join hole_idx as hs on hs.hole_id = e.start_
join hole_idx as he on he.hole_id = e.end_ and he.section_id = hs.section_id
join albion.edge_face as ef on ef.start_ = e.start_ and ef.end_ = e.end_ and not st_isempty(ef.geom)
where ef.graph_id='{}'
""".format(
graph
)
)
drawing = dxf.drawing(filename)
m = wkb.loads(bytes.fromhex(cur.fetchone()[0]))
for p in m:
r = p.exterior.coords
drawing.add(
dxf.face3d([tuple(r[0]), tuple(r[1]), tuple(r[2])], flags=1)
)
drawing.save()
def __srid(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("select srid from albion.metadata")
srid, = cur.fetchone()
return srid
def __getattr__(self, name):
if name == "has_hole":
return self.__has_hole()
elif name == "has_section":
return self.__has_section()
elif name == "has_volume":
return self.__has_volume()
elif name == "has_group_cell":
return self.__has_group_cell()
elif name == "has_graph":
return self.__has_graph()
elif name == "has_radiometry":
return self.__has_radiometry()
elif name == "has_cell":
return self.__has_cell()
elif name == "has_grid":
return self.__has_grid()
elif name == "name":
return self.__name
elif name == "srid":
return self.__srid()
else:
raise AttributeError(name)
def __has_cell(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("select count(1) from albion.cell")
return cur.fetchone()[0] > 0
def __has_grid(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("select exists(select * from information_schema.tables where table_schema='_albion' and table_name='grid')")
return cur.fetchone()[0]
def __has_hole(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("select count(1) from albion.hole where geom is not null")
return cur.fetchone()[0] > 0
def __has_volume(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("select count(1) from albion.volume")
return cur.fetchone()[0] > 0
def __has_section(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("select count(1) from albion.named_section")
return cur.fetchone()[0] > 0
def __has_group_cell(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("select count(1) from albion.group_cell")
return cur.fetchone()[0] > 0
def __has_graph(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("select count(1) from albion.graph")
return cur.fetchone()[0] > 0
def __has_radiometry(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("select count(1) from albion.radiometry")
return cur.fetchone()[0] > 0
def import_data(self, dir_, progress=None):
progress = progress if progress is not None else DummyProgress()
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
copy _albion.hole(id, x, y, z, depth_, date_, comments) from '{}' delimiter ';' csv header
""".format(
find_in_dir(dir_, "collar")
)
)
progress.setPercent(5)
cur.execute(
"""
copy _albion.deviation(hole_id, from_, dip, azimuth) from '{}' delimiter ';' csv header
""".format(
find_in_dir(dir_, "devia")
)
)
progress.setPercent(10)
cur.execute(
"""
update _albion.hole set geom = albion.hole_geom(id)
"""
)
progress.setPercent(15)
if find_in_dir(dir_, "avp"):
cur.execute(
"""
copy _albion.radiometry(hole_id, from_, to_, gamma) from '{}' delimiter ';' csv header
""".format(
find_in_dir(dir_, "avp")
)
)
progress.setPercent(20)
if find_in_dir(dir_, "formation"):
cur.execute(
"""
copy _albion.formation(hole_id, from_, to_, code, comments) from '{}' delimiter ';' csv header
""".format(
find_in_dir(dir_, "formation")
)
)
progress.setPercent(25)
if find_in_dir(dir_, "lithology"):
cur.execute(
"""
copy _albion.lithology(hole_id, from_, to_, code, comments) from '{}' delimiter ';' csv header
""".format(
find_in_dir(dir_, "lithology")
)
)
progress.setPercent(30)
if find_in_dir(dir_, "facies"):
cur.execute(
"""
copy _albion.facies(hole_id, from_, to_, code, comments) from '{}' delimiter ';' csv header
""".format(
find_in_dir(dir_, "facies")
)
)
progress.setPercent(35)
if find_in_dir(dir_, "resi"):
cur.execute(
"""
copy _albion.resistivity(hole_id, from_, to_, rho) from '{}' delimiter ';' csv header
""".format(
find_in_dir(dir_, "resi")
)
)
progress.setPercent(40)
if find_in_dir(dir_, "chemical"):
cur.execute(
"""
copy _albion.chemical(hole_id, from_, to_, num_sample,
element, thickness, gt, grade, equi, comments)
from '{}' delimiter ';' csv header
""".format(
find_in_dir(dir_, "chemical")
)
)
progress.setPercent(45)
progress.setPercent(100)
con.commit()
self.vacuum()
def triangulate(self, createAlbionRaster):
with self.connect() as con:
cur = con.cursor()
cur.execute("select albion.triangulate()")
if createAlbionRaster:
with open(os.path.join(os.path.dirname(__file__),
"albion_raster.sql")) as f:
for statement in f.read().split("\n;\n")[:-1]:
cur.execute(statement)
else:
cur.execute("REFRESH MATERIALIZED VIEW _albion.hole_nodes")
cur.execute("REFRESH MATERIALIZED VIEW _albion.cells")
con.commit()
def create_sections(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("refresh materialized view albion.section_geom")
con.commit()
def execute_script(self, file_):
with self.connect() as con:
cur = con.cursor()
cur.execute("select srid from albion.metadata")
srid, = cur.fetchone()
for statement in open(file_).read().split("\n;\n")[:-1]:
cur.execute(statement.replace("$SRID", str(srid)))
con.commit()
def new_graph(self, graph, parent=None):
with self.connect() as con:
cur = con.cursor()
cur.execute("delete from albion.graph cascade where id='{}';".format(graph))
if parent:
cur.execute(
"insert into albion.graph(id, parent) values ('{}', '{}');".format(
graph, parent
)
)
else:
cur.execute("insert into albion.graph(id) values ('{}');".format(graph))
con.commit()
def delete_graph(self, graph):
with self.connect() as con:
cur = con.cursor()
cur.execute("delete from albion.graph cascade where id='{}';".format(graph))
def previous_section(self, section):
if not section:
return
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
update albion.section set geom=coalesce(albion.previous_section(%s), geom) where id=%s
""", (section, section))
con.commit()
def next_section(self, section):
if not section:
return
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
update albion.section set geom=coalesce(albion.next_section(%s), geom) where id=%s
""", (section, section))
con.commit()
def next_subsection(self, section):
with self.connect() as con:
print("select section from distance")
cur = con.cursor()
cur.execute(
"""
select sg.group_id
from albion.section_geom sg
join albion.section s on s.id=sg.section_id
where s.id='{section}'
order by st_distance(s.geom, sg.geom), st_HausdorffDistance(s.geom, sg.geom) asc
limit 1
""".format(section=section))
res = cur.fetchone()
if not res:
return
group = res[0] or 0
print("select geom for next")
cur.execute(
"""
select geom from albion.section_geom
where section_id='{section}'
and group_id > {group}
order by group_id asc
limit 1 """.format( group=group, section=section)
)
res = cur.fetchone()
print("update section")
if res:
sql = """
update albion.section set geom=st_multi('{}'::geometry) where id='{}'
""".format(res[0], section)
cur.execute(sql)
con.commit()
print("done")
def previous_subsection(self, section):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
select sg.group_id
from albion.section_geom sg
join albion.section s on s.id=sg.section_id
where s.id='{section}'
order by st_distance(s.geom, sg.geom), st_HausdorffDistance(s.geom, sg.geom) asc
limit 1
""".format(section=section))
res = cur.fetchone()
if not res:
return
group = res[0] or 0
cur.execute(
"""
select geom from albion.section_geom
where section_id='{section}'
and group_id < {group}
order by group_id desc
limit 1
""".format(group=group, section=section))
res = cur.fetchone()
if res:
sql = """
update albion.section set geom=st_multi('{}'::geometry) where id='{}'
""".format(res[0], section)
cur.execute(sql)
con.commit()
# def next_group_ids(self):
# with self.connect() as con:
# cur = con.cursor()
# cur.execute(
# """
# select cell_id from albion.next_group where section_id='{}'
# """.format(
# self.__current_section.currentText()
# )
# )
# return [cell_id for cell_id, in cur.fetchall()]
#
def create_group(self, section, ids):
with self.connect() as con:
# add group
cur = con.cursor()
cur.execute(
"""
insert into albion.group(id) values ((select coalesce(max(id)+1, 1) from albion.group)) returning id
"""
)
group, = cur.fetchone()
cur.executemany(
"""
insert into albion.group_cell(section_id, cell_id, group_id) values(%s, %s, %s)
""",
((section, id_, group) for id_ in ids),
)
con.commit()
def sections(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("select id from albion.section")
return [id_ for id_, in cur.fetchall()]
def graphs(self):
with self.connect() as con:
cur = con.cursor()
cur.execute("select id from albion.graph")
return [id_ for id_, in cur.fetchall()]
def compute_mineralization(self, cutoff, ci, oc):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"delete from albion.mineralization where level_={}".format(cutoff)
)
cur.execute(
"""
insert into albion.mineralization(hole_id, level_, from_, to_, oc, accu, grade)
select hole_id, (t.r).level_, (t.r).from_, (t.r).to_, (t.r).oc, (t.r).accu, (t.r).grade
from (
select hole_id, albion.segmentation(
array_agg(gamma order by from_),array_agg(from_ order by from_), array_agg(to_ order by from_),
{ci}, {oc}, {cutoff}) as r
from albion.radiometry
group by hole_id
) as t
""".format(
oc=oc, ci=ci, cutoff=cutoff
)
)
cur.execute("refresh materialized view albion.mineralization_section_geom_cache")
con.commit()
def export_obj(self, graph_id, filename):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
select albion.to_obj(albion.volume_union(st_collectionhomogenize(st_collect(triangulation))))
from albion.volume
where graph_id='{}'
and albion.is_closed_volume(triangulation)
and albion.volume_of_geom(triangulation) > 1
""".format(
graph_id
)
)
open(filename, "w").write(cur.fetchone()[0])
def export_elementary_volume_obj(self, graph_id, cell_ids, outdir, closed_only=False):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
select cell_id, row_number() over(partition by cell_id order by closed desc), obj, closed
from (
select cell_id, albion.to_obj(triangulation) as obj, albion.is_closed_volume(triangulation) as closed
from albion.volume
where cell_id in ({}) and graph_id='{}'
) as t
""".format(
','.join(["'{}'".format(c) for c in cell_ids]), graph_id
)
)
for cell_id, i, obj, closed in cur.fetchall():
if closed_only and not closed:
continue
filename = '{}_{}_{}_{}.obj'.format(cell_id, graph_id, "closed" if closed else "opened", i)
path = os.path.join(outdir, filename)
open(path, "w").write(obj[0])
def export_elementary_volume_dxf(self, graph_id, cell_ids, outdir, closed_only=False):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
select cell_id, row_number() over(partition by cell_id order by closed desc), geom, closed
from (
select cell_id, triangulation as geom, albion.is_closed_volume(triangulation) as closed
from albion.volume
where cell_id in ({}) and graph_id='{}'
) as t
""".format(
','.join(["'{}'".format(c) for c in cell_ids]), graph_id
)
)
for cell_id, i, wkb_geom, closed in cur.fetchall():
geom = wkb.loads(bytes.fromhex(wkb_geom))
if closed_only and not closed:
continue
filename = '{}_{}_{}_{}.dxf'.format(cell_id, graph_id, "closed" if closed else "opened", i)
path = os.path.join(outdir, filename)
drawing = dxf.drawing(path)
for p in geom:
r = p.exterior.coords
drawing.add(
dxf.face3d([tuple(r[0]), tuple(r[1]), tuple(r[2])], flags=1)
)
drawing.save()
def errors_obj(self, graph_id, filename):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
select albion.to_obj(st_collectionhomogenize(st_collect(triangulation)))
from albion.volume
where graph_id='{}'
and (not albion.is_closed_volume(triangulation) or albion.volume_of_geom(triangulation) <= 1)
""".format(
graph_id
)
)
open(filename, "w").write(cur.fetchone()[0])
def export_dxf(self, graph_id, filename):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
select albion.volume_union(st_collectionhomogenize(st_collect(triangulation)))
from albion.volume
where graph_id='{}'
and albion.is_closed_volume(triangulation)
and albion.volume_of_geom(triangulation) > 1
""".format(
graph_id
)
)
drawing = dxf.drawing(filename)
m = wkb.loads(bytes.fromhex(cur.fetchone()[0]))
for p in m:
r = p.exterior.coords
drawing.add(
dxf.face3d([tuple(r[0]), tuple(r[1]), tuple(r[2])], flags=1)
)
drawing.save()
def export_holes_vtk(self, filename):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
select albion.to_vtk(st_collect(geom))
from albion.hole
"""
)
open(filename, "w").write(cur.fetchone()[0])
def export_holes_dxf(self, filename):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
select st_collect(geom)
from albion.hole
"""
)
drawing = dxf.drawing(filename)
m = wkb.loads(bytes.fromhex(cur.fetchone()[0]))
for l in m:
r = l.coords
drawing.add(
dxf.polyline(list(l.coords))
)
drawing.save()
def export_layer_vtk(self, table, filename):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
select albion.to_vtk(st_collect(albion.hole_piece(from_, to_, hole_id)))
from albion.{}
""".format(table)
)
open(filename, "w").write(cur.fetchone()[0])
def export_layer_dxf(self, table, filename):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
select st_collect(albion.hole_piece(from_, to_, hole_id))
from albion.{}
""".format(table)
)
drawing = dxf.drawing(filename)
m = wkb.loads(bytes.fromhex(cur.fetchone()[0]))
for l in m:
r = l.coords
drawing.add(
dxf.polyline(list(l.coords))
)
drawing.save()
def create_volumes(self, graph_id):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
delete from albion.volume where graph_id='{}'
""".format(
graph_id
)
)
cur.execute(
"""
insert into _albion.volume(graph_id, cell_id, triangulation, face1, face2, face3)
select graph_id, cell_id, geom, face1, face2, face3
from albion.dynamic_volume
where graph_id='{}'
and geom is not null --not st_isempty(geom)
""".format(
graph_id
)
)
con.commit()
def create_terminations(self, graph_id):
with self.connect() as con:
cur = con.cursor()
cur.execute(
"""
delete from albion.end_node where graph_id='{}'
""".format(
graph_id
)
)
cur.execute(
"""
insert into albion.end_node(geom, node_id, hole_id, graph_id)
select geom, node_id, hole_id, graph_id
from albion.dynamic_end_node
where graph_id='{}'
""".format(
graph_id
)
)
con.commit()
def export(self, filename):
export_db(self.name, filename)
@staticmethod
def import_(name, filename):
import_db(filename, name)
project = Project(name)
project.update()
project.create_sections()
return project