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
/
albion.sql
1783 lines (1586 loc) · 65.7 KB
/
albion.sql
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
-------------------------------------------------------------------------------
-- PUBLIC SCHEMA FOR DATABASE INTERFACE
-------------------------------------------------------------------------------
create schema albion
;
-------------------------------------------------------------------------------
-- UTILITY FUNCTIONS
-------------------------------------------------------------------------------
create or replace function albion.triangle_aspect_ratio(geom geometry)
returns float
language plpgsql
as
$$
declare
a float;
b float;
c float;
s float;
begin
a := st_distance(st_pointn(st_exteriorring(geom), 1), st_pointn(st_exteriorring(geom), 2));
b := st_distance(st_pointn(st_exteriorring(geom), 2), st_pointn(st_exteriorring(geom), 3));
c := st_distance(st_pointn(st_exteriorring(geom), 3), st_pointn(st_exteriorring(geom), 1));
s := (a+b+c)/2;
return a*b*c/(8*(s-a)*(s-b)*(s-c));
end;
$$
;
create or replace function albion.hole_geom(hole_id_ varchar)
returns geometry
language plpgsql stable
as
$$
declare
depth_max_ real;
hole_geom_ geometry;
x_ double precision;
y_ double precision;
z_ double precision;
collar_geom_ geometry;
path_ varchar;
begin
select x, y, z, depth_ from _albion.hole where id=hole_id_ into x_, y_, z_, depth_max_;
collar_geom_ := st_setsrid(st_makepoint(x_, y_, z_), $SRID);
with dz as (
select
from_ as md2, coalesce(lag(from_) over w, 0) as md1,
(dip + 90)*pi()/180 as wd2, coalesce(lag((dip+90)*pi()/180) over w, 0) as wd1,
azimuth*pi()/180 as haz2, coalesce(lag(azimuth*pi()/180) over w, 0) as haz1
from _albion.deviation
where azimuth >= 0 and azimuth <=360 and dip < 0 and dip > -180
and hole_id=hole_id_
window w AS (order by from_)
),
pt as (
select md2, wd2, haz2,
x_ + sum(0.5 * (md2 - md1) * (sin(wd1) * sin(haz1) + sin(wd2) * sin(haz2))) over w as x,
y_ + sum(0.5 * (md2 - md1) * (sin(wd1) * cos(haz1) + sin(wd2) * cos(haz2))) over w as y,
z_ - sum(0.5 * (md2 - md1) * (cos(wd2) + cos(wd1))) over w as z
from dz
window w AS (order by md1)
),
line as (
select st_makeline(('SRID=$SRID; POINTZ('||x||' '||y||' '||z||')')::geometry order by md2 asc) as geom
from pt
)
select ST_RemoveRepeatedPoints(st_addpoint(geom, collar_geom_, 0), 1.e-6)
from line as l
into hole_geom_;
if hole_geom_ is not null and st_3dlength(hole_geom_) < depth_max_ and st_3dlength(hole_geom_) > 0 then
path_ := 'too short';
-- holes is not long enough
with last_segment as (
select st_pointn(hole_geom_, st_numpoints(hole_geom_)-1) as start_, st_endpoint(hole_geom_) as end_
),
direction as (
select
(st_x(end_) - st_x(start_))/st_3ddistance(end_, start_) as x,
(st_y(end_) - st_y(start_))/st_3ddistance(end_, start_) as y,
(st_z(end_) - st_z(start_))/st_3ddistance(end_, start_) as z
from last_segment
)
select st_addpoint(hole_geom_,
st_makepoint(
st_x(s.end_) + (depth_max_-st_3dlength(hole_geom_))*d.x,
st_y(s.end_) + (depth_max_-st_3dlength(hole_geom_))*d.y,
st_z(s.end_) + (depth_max_-st_3dlength(hole_geom_))*d.z
))
from direction as d, last_segment as s
into hole_geom_;
-- hole have no deviation
elsif hole_geom_ is null or st_3dlength(hole_geom_) = 0 then
path_ := 'no length';
select st_makeline( collar_geom_, st_translate(collar_geom_, 0, 0, -depth_max_)) into hole_geom_;
end if;
if abs(st_3dlength(hole_geom_) - depth_max_) > 1e-3 then
raise 'hole %s %s %s %', hole_id_, depth_max_, st_3dlength(hole_geom_), path_;
end if;
return hole_geom_;
end;
$$
;
create or replace function albion.hole_piece(from_ real, to_ real, hole_id_ varchar)
returns geometry
language plpgsql stable
as
$$
begin
return (
select st_makeline(
st_3dlineinterpolatepoint(geom, least(from_/l, 1)),
st_3dlineinterpolatepoint(geom, least(to_/l, 1)))
from (select geom, st_3dlength(geom) as l from albion.hole where id=hole_id_) as t
);
end;
$$
;
create or replace view albion.collar as select id, st_startpoint(geom)::geometry('POINTZ', $SRID) as geom, date_, comments, depth_ from _albion.hole
;
alter view albion.collar alter id set default _albion.unique_id()::varchar
;
create or replace function albion.collar_instead_fct()
returns trigger
language plpgsql
as
$$
begin
if tg_op in ('INSERT', 'UPDATE') then
new.date_ := coalesce(new.date_, now()::date::varchar);
end if;
if tg_op = 'INSERT' then
insert into _albion.hole(id, date_, depth_, x, y, z, comments)
values(new.id, new.date_, new.depth_, st_x(new.geom), st_y(new.geom), st_z(new.geom), new.comments)
returning id into new.id;
update _albion.hole set geom = albion.hole_geom(new.id) where id=new.id;
return new;
elsif tg_op = 'UPDATE' then
update _albion.hole set id=new.id, date_=new.date_, depth_=new.depth_, x=st_x(new.geom), y=st_y(new.geom), z=st_z(new.geom), comments=new.comments
where id=old.id;
update _albion.hole set geom = albion.hole_geom(new.id) where id=new.id;
return new;
elsif tg_op = 'DELETE' then
delete from _albion.collar where id=old.id;
return old;
end if;
end;
$$
;
create trigger collar_instead_trig
instead of insert or update or delete on albion.collar
for each row execute procedure albion.collar_instead_fct()
;
create view albion.metadata as select id, srid, close_collar_distance, snap_distance, precision, interpolation, end_node_relative_distance, end_node_relative_thickness, correlation_distance, correlation_angle, parent_correlation_angle from _albion.metadata
;
create view albion.layer as select name, fields_definition from _albion.layer
;
create view albion.hole as select id, depth_, geom::geometry('LINESTRINGZ', $SRID) from _albion.hole
;
create view albion.deviation as select hole_id, from_, dip, azimuth from _albion.deviation
;
create or replace view albion.graph as
select id, parent from _albion.graph
;
create or replace view albion.node as
select id, graph_id, hole_id, from_, to_, parent, geom::geometry('LINESTRINGZ', $SRID)
from _albion.node
;
alter view albion.node alter column id set default _albion.unique_id()::varchar
;
create or replace function albion.node_instead_fct()
returns trigger
language plpgsql
as
$$
begin
if tg_op in ('INSERT', 'UPDATE') then
if (select parent is not null from _albion.graph where id=new.graph_id) then
new.parent := coalesce(new.parent,
(select id from _albion.node as n
where .5*(new.from_+new.to_) between n.from_ and n.to_
and n.hole_id=new.hole_id and
n.graph_id=(select g.parent from _albion.graph as g where g.id=new.graph_id)));
end if;
end if;
new.geom := coalesce(new.geom, albion.hole_piece(new.from_, new.to_, new.hole_id));
if tg_op = 'INSERT' then
insert into _albion.node(id, graph_id, hole_id, from_, to_, geom, parent)
values(new.id, new.graph_id, new.hole_id, new.from_, new.to_, new.geom, new.parent)
returning id into new.id;
return new;
elsif tg_op = 'UPDATE' then
update _albion.node set id=new.id, graph_id=new.graph_id, hole_id=new.hole_id, from_=new.from_, to_=new.to_, geom=new.geom, parent=new.parent
where id=old.id;
return new;
elsif tg_op = 'DELETE' then
delete from _albion.node where id=old.id;
return old;
end if;
end;
$$
;
create trigger node_instead_trig
instead of insert or update or delete on albion.node
for each row execute procedure albion.node_instead_fct()
;
create or replace view albion.close_collar as
select distinct on (a.id) a.id, a.geom from albion.collar as a, albion.collar as b, _albion.metadata as m
where a.id != b.id and st_dwithin(a.geom, b.geom, m.close_collar_distance)
;
create view albion.cell as select id, a, b, c, geom::geometry('POLYGON', $SRID), albion.triangle_aspect_ratio(geom) as aspect_ratio from _albion.cell
;
create or replace function albion.cell_after_fct()
returns trigger
language plpgsql
as
$$
begin
refresh materialized view albion.all_edge;
return null;
end;
$$
;
-- this trigger should work on the view instead of the table, but for unknown reason it doesn't, so we put it on the table
drop trigger if exists cell_after_trig ON _albion.cell
;
create trigger cell_after_trig
after delete on _albion.cell
for each statement execute procedure albion.cell_after_fct()
;
create or replace function albion.tesselate(polygon_ geometry, lines_ geometry, points_ geometry)
returns geometry
language plpython3u volatile
as
$$
from shapely import wkb
from shapely import geos
geos.WKBWriter.defaults['include_srid'] = True
from fourmy import tessellate
polygon = wkb.loads(bytes.fromhex(polygon_))
lines = wkb.loads(bytes.fromhex(lines_)) if lines_ else None
points = wkb.loads(bytes.fromhex(points_)) if points_ else None
result = tessellate(polygon, lines, points)
geos.lgeos.GEOSSetSRID(result._geom, geos.lgeos.GEOSGetSRID(polygon._geom))
return result.wkb_hex
$$
;
create or replace function albion.triangulate()
returns integer
language plpgsql volatile
as
$$
begin
delete from _albion.cell;
insert into _albion.cell(a, b, c, geom)
with cell as (
select albion.tesselate(
st_convexhull((select st_collect(st_force2d(geom)) from albion.collar)),
st_multi((select st_collectionhomogenize(st_collect(cut)) from albion.named_section)),
st_multi((select st_collect(st_force2d(geom)) from albion.collar))
) as geom
),
splt as (
select (ST_Dump(geom)).geom from cell
)
select
(select c.id from albion.collar as c where st_intersects(c.geom, st_pointn(st_exteriorring(s.geom), 1))),
(select c.id from albion.collar as c where st_intersects(c.geom, st_pointn(st_exteriorring(s.geom), 2))),
(select c.id from albion.collar as c where st_intersects(c.geom, st_pointn(st_exteriorring(s.geom), 3))),
s.geom
from splt as s;
refresh materialized view albion.all_edge;
return (select count(1) from _albion.cell);
end;
$$
;
create or replace function albion.cos_angle(anchor_ geometry, start_ geometry, end_ geometry)
returns real
language plpython3u immutable
as
$$
import numpy
from numpy.linalg import norm
from shapely import wkb
anchor = wkb.loads(bytes.fromhex(anchor_))
start = wkb.loads(bytes.fromhex(start_))
end = wkb.loads(bytes.fromhex(end_))
dir = numpy.array(anchor.coords[-1]) - numpy.array(anchor.coords[0])
dir /= norm(dir)
seg = numpy.array(end.coords[0]) - numpy.array(start.coords[0])
seg /= norm(seg)
return dir.dot(seg)
$$
;
create or replace function albion.is_touchingrightside(line geometry, poly geometry)
returns boolean
language plpgsql immutable
as
$$
declare
ring geometry;
p1 geometry;
p2 geometry;
p3 geometry;
i1 boolean;
i2 boolean;
i3 boolean;
alpha1 real;
alpha2 real;
alpha3 real;
begin
ring := st_exteriorring(poly);
if st_numpoints(ring) = 4 then
p1 := st_pointn(ring, 1);
p2 := st_pointn(ring, 2);
p3 := st_pointn(ring, 3);
i1 := st_intersects(line, p1);
i2 := st_intersects(line, p2);
i3 := st_intersects(line, p3);
if i1 and i2 and i3 then
alpha1 := st_linelocatepoint(line, p1);
alpha2 := st_linelocatepoint(line, p2);
alpha3 := st_linelocatepoint(line, p3);
return (alpha1 > alpha2 and alpha2 > alpha3)
or (alpha2 > alpha3 and alpha3 > alpha1)
or (alpha3 > alpha1 and alpha1 > alpha2);
end if;
if i1 and i2 then
return st_linelocatepoint(line, p1) > st_linelocatepoint(line, p2);
end if;
if i2 and i3 then
return st_linelocatepoint(line, p2) > st_linelocatepoint(line, p3);
end if;
if i3 and i1 then
return st_linelocatepoint(line, p3) > st_linelocatepoint(line, p1);
end if;
else
for i in 1..(st_numpoints(ring)-1) loop
p1 := st_pointn(ring, i);
p2 := st_pointn(ring, i+1);
if st_intersects(line, p1) and st_intersects(line, p2) then
return st_linelocatepoint(line, p1) > st_linelocatepoint(line, p2);
end if;
end loop;
end if;
return 'f';
end;
$$
;
select albion.is_touchingrightside('LINESTRING(327627.06 2079630.27,327229.65 2079063.55,326442.66 2078981.33,326224.82 2079030.19,326024.52 2079029.9,325824.61 2079029.57,325424.75 2079032.28,325226.26 2079030.34,325024.4 2079029.96,324826.45 2079029.17,324625.02 2079031.02,324426.44 2079030.49,324025.18 2079031.17,323624.52 2079029.32,323024.35 2079030.9,322824.89 2079030.38,322705.36 2079915.6)'::geometry, 'POLYGON((324426.44 2079030.49,324826.45 2079029.17,324625.02 2079031.02,324426.44 2079030.49))'::geometry)
;
-- polygon is visible if points are on the line, or by removing the edge that touches
-- the line, the line of sight from anchor to point doesn't cross the line
create or replace function albion.is_visible(anchor geometry, section geometry, poly geometry)
returns boolean
language plpgsql immutable
as
$$
declare
nb_visible integer;
ring geometry;
occluder geometry;
point_on_poly geometry;
line_od_sight geometry;
begin
nb_visible := 0;
ring := st_exteriorring(poly);
occluder := st_difference(section, ring);
if occluder is not null then
for i in 1..st_numpoints(ring) loop
if st_intersects(section, st_pointn(ring, i)) then
nb_visible := nb_visible + 1;
else
line_od_sight := st_makeline(st_closestpoint(anchor, st_pointn(ring, i)), st_pointn(ring, i));
--raise notice 'occluder %', st_astext(occluder);
--raise notice 'los %', st_astext(line_od_sight);
if not st_intersects(line_od_sight, occluder) then
nb_visible := nb_visible + 1;
end if;
end if;
end loop;
end if;
-- we also check that the line between a point on surface and the anchor crosses the section (we are looking "away" from anchor)
point_on_poly := st_pointonsurface(poly);
line_od_sight := st_makeline(st_closestpoint(anchor, point_on_poly), point_on_poly);
return nb_visible = st_numpoints(ring) and st_intersects(line_od_sight, section);
end;
$$
;
select albion.is_touchingrightside('LINESTRING(0 0, 2 0)'::geometry, 'POLYGON((0 0, 1 1, 2 0, 0 0))'::geometry)
;
create or replace function albion.offset_section(offset_ integer, anchor geometry, old_geom geometry)
returns geometry
language plpgsql stable
as
$$
begin
if offset_ > 0 then
for r in 1..offset_ loop
with candidates as (
select rank() over(order by st_distance(anchor, st_centroid(geom))) as rk,
st_linemerge(st_symdifference(old_geom, st_reverse(st_exteriorring(geom)))) as geom
from _albion.cell
where st_intersects(geom, old_geom)
and st_dimension(st_intersection(geom, old_geom)) = 1
and albion.is_touchingrightside(old_geom, geom) = 't'
and albion.is_visible(anchor, old_geom, geom) = 't'
)
select
case when st_linelocatepoint(anchor, st_startpoint(geom)) > st_linelocatepoint(anchor, st_endpoint(geom))
then geom
else st_reverse(geom)
end from candidates where rk=1 into old_geom;
end loop;
return old_geom;
else
return geometry;
end if;
end;
$$
;
create view albion.section as select id, scale, anchor::geometry('LINESTRING', $SRID), geom::geometry('MULTILINESTRING', $SRID)
from _albion.section
;
alter view albion.section alter column id set default _albion.unique_id()::varchar
;
alter view albion.section alter column scale set default 1;
;
create or replace function albion.section_instead_fct()
returns trigger
language plpgsql
as
$$
begin
if tg_op = 'INSERT' then
insert into _albion.section(id, anchor, geom, scale)
values(new.id, new.anchor, new.geom, new.scale)
returning id, geom into new.id, new.geom;
return new;
elsif tg_op = 'UPDATE' then
update _albion.section set id=new.id, anchor=new.anchor, geom=new.geom, scale=new.scale
where id=old.id;
return new;
elsif tg_op = 'DELETE' then
delete from _albion.section where id=old.id;
return old;
end if;
end;
$$
;
create trigger section_instead_trig
instead of insert or update or delete on albion.section
for each row execute procedure albion.section_instead_fct()
;
create view albion.group as
select id from _albion.group
;
create view albion.group_cell as
select gc.section_id || ' ' || gc.cell_id as id, gc.cell_id, c.geom, gc.group_id, gc.section_id
from _albion.cell as c
join _albion.group_cell as gc on gc.cell_id=c.id
;
create or replace function albion.group_cell_instead_fct()
returns trigger
language plpgsql
as
$$
begin
if tg_op = 'INSERT' then
insert into _albion.group_cell(section_id, group_id, cell_id)
values(new.section_id, new.group_id, new.cell_id);
return new;
elsif tg_op = 'UPDATE' then
update _albion.group_cell set section_id=new.section_id, group_id=new.group_id where cell_id=new.cell_id;
return new;
elsif tg_op = 'DELETE' then
delete from _albion.group_cell where cell_id=old.cell_id and group_id=old.group_id;
return old;
end if;
end;
$$
;
create trigger group_cell_instead_trig
instead of insert or update or delete on albion.group_cell
for each row execute procedure albion.group_cell_instead_fct()
;
create or replace function albion.to_section(geom geometry, anchor geometry, z_scale real)
returns geometry
language plpython3u immutable
as
$$
import plpy
from shapely.ops import transform
from shapely.geometry import LineString
from shapely import wkb
from shapely import geos
import numpy
from numpy.linalg import norm
geos.WKBWriter.defaults['include_srid'] = True
if geom is None:
return None
g = wkb.loads(bytes.fromhex(geom))
a = wkb.loads(bytes.fromhex(anchor))
orig = numpy.array(a.coords[0])
dir_ = numpy.array(a.coords[-1]) - orig
dir_ /= norm(dir_)
nrml_ = numpy.array([-dir_[1] , dir_[0]])
if g.type == 'LineString':
xyz = numpy.array(g.coords)
xyz[:,:2] -= orig
xy = xyz[:,:2].dot(dir_).reshape(-1,1)*dir_
xy += z_scale*xyz[:,2].reshape(-1,1)*nrml_
xy += orig
result = LineString(xy)
else:
def tr(x, y, z=None):
z = z or (0,)*len(x)
xy = (numpy.array((x,y)).T - orig).dot(dir_).reshape(-1,1)*dir_
xy += z_scale*numpy.array(z).reshape(-1,1)*nrml_
xy += orig
return zip(*((x_, y_) for x_, y_ in xy ))
result = transform(tr, g)
geos.lgeos.GEOSSetSRID(result._geom, geos.lgeos.GEOSGetSRID(g._geom))
return result.wkb_hex
$$
;
create or replace function albion.from_section(geom_ geometry, anchor_ geometry, section_ geometry, z_scale_ real)
returns geometry
language plpython3u immutable
as
$$
import plpy
from shapely.ops import transform
from shapely.geometry import LineString
from shapely import wkb
from shapely import geos
from numpy import array, dot
from numpy.linalg import norm
geos.WKBWriter.defaults['include_srid'] = True
if geom_ is None:
return None
g = wkb.loads(bytes.fromhex(geom_))
a = wkb.loads(bytes.fromhex(anchor_))
s = wkb.loads(bytes.fromhex(section_))
orig = array(a.coords[0])
dir_ = array(a.coords[-1]) - orig
dir_ /= norm(dir_)
nrml_ = array([-dir_[1] , dir_[0]])
if g.type == 'LineString':
xy = array(g.coords)
points = []
for p in xy:
z = dot(nrml_, p-orig)/z_scale_
big_distance = 100*z_scale_*z
# intersection between section geom and line extending from point in the normal direction
plpy.warning(big_distance, nrml_, z, p, s.intersection(LineString([p-nrml_*big_distance, p+nrml_*big_distance])).wkt)
x, y = s.intersection(LineString([p-nrml_*big_distance, p+nrml_*big_distance])).coords[0]
points.append((x,y,z))
result = LineString(points)
else:
assert(False)
geos.lgeos.GEOSSetSRID(result._geom, geos.lgeos.GEOSGetSRID(g._geom))
return result.wkb_hex
$$
;
create view albion.hole_section as
select row_number() over() as id, h.id as hole_id, h.depth_, s.id as section_id,
(albion.to_section(h.geom, s.anchor, s.scale))::geometry('LINESTRING', $SRID) as geom
from _albion.section as s
join _albion.hole as h on s.geom && h.geom and st_intersects(st_startpoint(h.geom), s.geom)
;
create view albion.node_section as
select row_number() over() as id, n.id as node_id, h.id as hole_id, n.from_, n.to_, n.graph_id, s.id as section_id,
(albion.to_section(n.geom, s.anchor, s.scale))::geometry('LINESTRING', $SRID) as geom, n.parent
from _albion.section as s
join _albion.hole as h on s.geom && h.geom and st_intersects(st_startpoint(h.geom), s.geom)
join _albion.node as n on n.hole_id = h.id
;
create or replace function albion.section_at_group(section_id_ varchar, group_id_ integer)
returns geometry
language plpgsql
as
$$
begin
return (
with hull as (
select st_multi(st_unaryunion(st_collect(c.geom))) as geom
from _albion.cell as c
join _albion.group_cell as gc on gc.cell_id=c.id
where gc.section_id=section_id_ and gc.group_id <= group_id_
),
hull_contour as (
select st_exteriorring(geom) as geom from (select (st_dump(geom)).geom from hull) as t
),
seg as (
select ST_PointN(geom, generate_series(1, ST_NPoints(geom)-1)) as sp, ST_PointN(geom, generate_series(2, ST_NPoints(geom) )) as ep
from hull_contour
),
facing as (
select st_force2d(st_makeline(seg.sp, seg.ep)) as geom
from seg join _albion.section as s on s.id = section_id_
where albion.cos_angle(s.anchor, seg.sp, seg.ep) > cos(89*pi()/180)
),
merged as (
select st_linemerge(st_collect(facing.geom)) as geom
from facing join _albion.section as s on s.id = section_id_
),
sorted as (
select rank() over(order by st_length(geom) desc) as rk, geom
from (select (st_dump(geom)).geom from merged) as t
)
select st_reverse(geom) from sorted where rk=1
);
end;
$$
;
create materialized view albion.section_geom as
select row_number() over() as id, group_id, section_id, albion.section_at_group(section_id, group_id)::geometry('LINESTRING', $SRID) as geom
from (select distinct section_id, group_id from _albion.group_cell) as t
;
create or replace function albion.segmentation(
radiometry_ real[], from_ real[], to_ real[], ic_ real, oc_ real, cut_ real, measure_thickness real default .1)
returns TABLE (level_ real, from_ real, to_ real, oc real, accu real, grade real)
language plpython3u immutable
as
$$
import plpy
import numpy
import math
IC = int(round(ic_/measure_thickness)) # nb echantillon, intercalaire stérile minimale
OC = int(round(oc_/measure_thickness)) # nb echantillon, ouverture chantier (épaisseur mini)
cut = cut_ # cutoff
first_from_ = from_[0]
AVP = []
for gamma, f, t in zip(radiometry_, from_, to_):
AVP += [gamma]*int(round((t-f)/measure_thickness))
AVP = numpy.array(AVP, dtype=numpy.float32)
N = len(AVP)+2*IC+OC-1
# Vecteurs de travail
# note: le code est un portage de R
# pour garder l indexation démarrant à 1
# on alloue N + 1 éléments, le premier élément est inutilisé
t = numpy.zeros((N+1,))
t [(IC+OC):(IC+OC+len(AVP))] = AVP
v = t - cut
v[0] = 0
SV = numpy.zeros((N+1,))
SV1 = numpy.zeros((N+1,))
SV2 = numpy.zeros((N+1,))
SO = numpy.zeros((N+1,))
SO1 = numpy.zeros((N+1,))
SO2 = numpy.zeros((N+1,))
SVP = numpy.zeros((N+1,), dtype=numpy.int32)
SOP = numpy.zeros((N+1,), dtype=numpy.int32)
# Initialisation
for i in range(OC, (IC+OC-1)+1):
SV[i] = numpy.sum(v[(i-OC+1):(i+1)])
SVP[IC+OC-1]=IC
SOP[IC+OC-1]=1
# Calcul des valeurs
for i in range(IC+OC, N+1):
# Calcul de SV
SV1[i] = SV[i-1]+v[i]
SV2[i] = SO[i-OC]+numpy.sum(v[(i-OC+1):(i+1)])
SV[i] = max(SV1[i], SV2[i])
# Calcul de SO
SO1[i] = SO[i-1]
SO2[i] = SV[i-IC]
SO[i] = max(SO1[i], SO2[i])
# Limites de chantiers
if SV1[i] >= SV2[i]:
SVP[i] = SVP[i-1]
else:
SVP[i] = i - OC + 1
if SO1[i] > SO2[i]:
SOP[i] = SOP[i-1]
else:
SOP[i] = i - IC + 1
# Calcul des chantiers
class Rec(object):
def __init__(self, N, OC, IC):
self.nbr_max = 2*int(math.ceil(N/(OC+IC)))
self.from_ = numpy.zeros(self.nbr_max+1, dtype=numpy.int32)
self.to = numpy.zeros(self.nbr_max+1, dtype=numpy.int32)
self.code = numpy.zeros(self.nbr_max+1, dtype=numpy.int32)
self.accu = numpy.zeros(self.nbr_max+1, dtype=numpy.int32)
self.nbr = 0
self.idx = N
int_ = Rec(N, OC, IC)
while SOP[int_.idx] > 1:
# L intercalaire
int_.nbr += 1
int_.to[int_.nbr] = int_.idx
int_.from_[int_.nbr] = SOP[int_.to[int_.nbr]]
int_.code[int_.nbr] = 0
int_.accu[int_.nbr] = 0.0
# Le chantier
int_.nbr += 1
int_.to[int_.nbr] = int_.from_[int_.nbr-1]-1
int_.from_[int_.nbr] = SVP[int_.to[int_.nbr]]
int_.code[int_.nbr] = 1
int_.accu[int_.nbr] = numpy.sum(cut+v[int_.from_[int_.nbr]:int_.to[int_.nbr]+1])
# mise à jour l index
int_.idx = int_.from_[int_.nbr]-1
result = []
for ifrom_, ito_, c in zip(int_.from_, int_.to, int_.code):
ifrom_ -= OC+IC
ito_ -= OC+IC-1
if ifrom_ >= 0 and ito_ > 0 and c:
accu = numpy.sum(AVP[ifrom_:ito_])
oc = (ito_ - ifrom_)*measure_thickness
grade = accu/oc
result.append((cut, ifrom_*measure_thickness + first_from_, ito_*measure_thickness + first_from_, oc, accu, grade))
return result
$$
;
create materialized view albion.all_edge as
select case when a < b then a else b end as start_, case when a < b then b else a end as end_
from _albion.cell
union
select case when b < c then b else c end as start_, case when b < c then c else b end as end_
from _albion.cell
union
select case when c < a then c else a end as start_, case when c < a then a else c end as end_
from _albion.cell
;
create or replace view albion.possible_edge as
with tan_ang as (
select tan(correlation_angle*pi()/180) as value, tan(parent_correlation_angle*pi()/180) as parent_value
from _albion.metadata
),
result as (
select ns.id as start_, ne.id as end_, ns.graph_id as graph_id, (st_makeline(st_3dlineinterpolatepoint(ns.geom, .5), st_3dlineinterpolatepoint(ne.geom, .5)))::geometry('LINESTRINGZ', $SRID) as geom --, null as parent
from albion.all_edge as e
join _albion.hole as hs on hs.id=e.start_
join _albion.hole as he on he.id=e.end_
join _albion.node as ns on ns.hole_id=hs.id
join _albion.node as ne on ne.hole_id=he.id, tan_ang
where ns.graph_id = ne.graph_id
and (
(
abs(ns.from_-ns.to_) >= abs(ne.from_-ne.to_)
and st_z(st_startpoint(ns.geom)) + st_distance(st_startpoint(ns.geom), st_startpoint(ne.geom))*tan_ang.value >= st_z(st_startpoint(ne.geom))
and st_z(st_endpoint(ns.geom)) - st_distance(st_startpoint(ns.geom), st_startpoint(ne.geom))*tan_ang.value <= st_z(st_endpoint(ne.geom))
)
or
(
abs(ns.from_-ns.to_) < abs(ne.from_-ne.to_)
and st_z(st_startpoint(ne.geom)) + st_distance(st_startpoint(ns.geom), st_startpoint(ne.geom))*tan_ang.value >= st_z(st_startpoint(ns.geom))
and st_z(st_endpoint(ne.geom)) - st_distance(st_startpoint(ns.geom), st_startpoint(ne.geom))*tan_ang.value <= st_z(st_endpoint(ns.geom))
)
)
and st_distance( ne.geom, ns.geom ) < ( select correlation_distance from albion.metadata )
and ns.parent is null
and ne.parent is null
union all -- for graphs with parents
select ns.id as start_, ne.id as end_, ns.graph_id as graph_id, (st_makeline(st_3dlineinterpolatepoint(ns.geom, .5), st_3dlineinterpolatepoint(ne.geom, .5)))::geometry('LINESTRINGZ', $SRID) as geom --, ns.parent as parent
from _albion.edge as pe
join _albion.node as pns on pns.id=pe.start_
join _albion.node as pne on pne.id=pe.end_
join _albion.node as ns on ns.parent=pns.id
join _albion.node as ne on ne.parent=pne.id, tan_ang
where ns.graph_id = ne.graph_id
and
(
(
abs(ns.from_-ns.to_) >= abs(ne.from_-ne.to_)
and st_z(st_startpoint(ns.geom)) + st_distance(st_startpoint(ns.geom), st_startpoint(ne.geom))*tan_ang.parent_value + (st_z(st_3dlineinterpolatepoint(pne.geom, .5)) - st_z(st_3dlineinterpolatepoint(pns.geom, .5))) >= st_z(st_startpoint(ne.geom))
and st_z(st_endpoint(ns.geom)) - st_distance(st_startpoint(ns.geom), st_startpoint(ne.geom))*tan_ang.parent_value + (st_z(st_3dlineinterpolatepoint(pne.geom, .5)) - st_z(st_3dlineinterpolatepoint(pns.geom, .5))) <= st_z(st_endpoint(ne.geom))
)
or
(
abs(ns.from_-ns.to_) < abs(ne.from_-ne.to_)
and st_z(st_startpoint(ne.geom)) + st_distance(st_startpoint(ns.geom), st_startpoint(ne.geom))*tan_ang.parent_value + (st_z(st_3dlineinterpolatepoint(pns.geom, .5)) - st_z(st_3dlineinterpolatepoint(pne.geom, .5))) >= st_z(st_startpoint(ns.geom))
and st_z(st_endpoint(ne.geom)) - st_distance(st_startpoint(ns.geom), st_startpoint(ne.geom))*tan_ang.parent_value + (st_z(st_3dlineinterpolatepoint(pns.geom, .5)) - st_z(st_3dlineinterpolatepoint(pne.geom, .5)) ) <= st_z(st_endpoint(ns.geom))
)
)
)
select row_number() over() as id, * from result
;
create view albion.edge as
select id, start_, end_, graph_id, geom::geometry('LINESTRINGZ', $SRID)
from _albion.edge
;
alter view albion.edge alter column id set default _albion.unique_id();
create or replace function albion.edge_instead_fct()
returns trigger
language plpgsql
as
$$
declare
edge_ok integer;
begin
if tg_op in ('INSERT', 'UPDATE') then
new.start_ := coalesce(new.start_, (select id from _albion.node where st_intersects(geom, new.geom) and st_centroid(geom)::varchar=st_startpoint(new.geom)::varchar));
new.end_ := coalesce(new.end_, (select id from _albion.node where st_intersects(geom, new.geom) and st_centroid(geom)::varchar=st_endpoint(new.geom)::varchar));
if new.start_ > new.end_ then
select new.start_, new.end_ into new.end_, new.start_;
end if;
-- check that edge is in all_edge
select count(1)
from albion.all_edge as ae
join _albion.hole as hs on hs.id=ae.start_
join _albion.hole as he on he.id=ae.end_
join _albion.node as ns on (ns.hole_id in (hs.id, he.id) and ns.id=new.start_)
join _albion.node as ne on (ne.hole_id in (hs.id, he.id) and ne.id=new.end_)
into edge_ok;
if edge_ok = 0 then
raise EXCEPTION 'impossible edge (not a cell edge)';
end if;
new.geom := st_makeline(
st_3dlineinterpolatepoint((select geom from _albion.node where id=new.start_), .5),
st_3dlineinterpolatepoint((select geom from _albion.node where id=new.end_), .5));
end if;
if tg_op = 'INSERT' then
insert into _albion.edge(id, start_, end_, graph_id, geom)
values(new.id, new.start_, new.end_, new.graph_id, new.geom)
returning id into new.id;
return new;
elsif tg_op = 'UPDATE' then
update _albion.edge set id=new.id, start_=new.start_, end_=new.end_, graph_id=new.graph_id, new._geom=new.geom
where id=old.id;
return new;
elsif tg_op = 'DELETE' then
delete from _albion.edge where id=old.id;
return old;
end if;
end;
$$
;
create trigger edge_instead_trig
instead of insert or update or delete on albion.edge
for each row execute procedure albion.edge_instead_fct()
;
create view albion.edge_section as
with hole_idx as (
select h.id, rank() over(partition by s.id order by st_linelocatepoint(s.anchor, st_startpoint(h.geom))) as rk, s.id as section_id
from _albion.section as s
join _albion.hole as h on s.geom && h.geom and st_intersects(s.geom, st_startpoint(h.geom))
)
select s.id || ' ' || e.id as id, e.id as edge_id, e.start_, e.end_, e.graph_id, s.id as section_id,
(albion.to_section(e.geom, s.anchor, s.scale))::geometry('LINESTRING', $SRID) as geom
from _albion.edge as e
join _albion.node as ns on ns.id=e.start_
join _albion.node as ne on ne.id=e.end_
join _albion.hole as hs on hs.id=ns.hole_id
join _albion.hole as he on he.id=ne.hole_id
join hole_idx as cs on cs.id=hs.id
join hole_idx as ce on ce.id=he.id,
_albion.section as s
where ((cs.rk = ce.rk + 1) or (ce.rk = cs.rk + 1))
and cs.section_id=s.id
and ce.section_id=s.id
;
alter view albion.edge_section alter column id set default _albion.unique_id();
create or replace function albion.edge_section_instead_fct()
returns trigger
language plpgsql
as
$$
declare
new_geom geometry;
begin
if tg_op in ('INSERT', 'UPDATE') then
new.start_ := coalesce(new.start_, (select node_id from albion.node_section as n, _albion.metadata as m
where st_dwithin(n.geom, st_startpoint(new.geom), m.snap_distance)
and graph_id=new.graph_id
order by st_distance(n.geom, st_startpoint(new.geom)) asc
limit 1
));
new.end_ := coalesce(new.end_, (select node_id from albion.node_section as n, _albion.metadata as m
where st_dwithin(n.geom, st_endpoint(new.geom), m.snap_distance)
and graph_id=new.graph_id
order by st_distance(n.geom, st_endpoint(new.geom)) asc
limit 1
));
if new.start_ > new.end_ then
select new.start_, new.end_ into new.end_, new.start_;
select st_reverse(new.geom) into new.geom;
end if;
select st_makeline(st_3dlineinterpolatepoint(s.geom, .5), st_3dlineinterpolatepoint(e.geom, .5))
from _albion.node as s, _albion.node as e
where s.id=new.start_ and e.id=new.end_ into new_geom;
-- test if edge is possible
if not exists (select 1
from albion.all_edge as ae
join _albion.node as ns on ae.start_ = ns.hole_id