-
Notifications
You must be signed in to change notification settings - Fork 4
/
_gui.py
2536 lines (2204 loc) · 77.8 KB
/
_gui.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
#!python
'''
Copyright 2017 - 2024 Vale
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*** You can contribute to the main repository at: ***
https://github.com/pemn/usage-gui
---------------------------------
'''
__version__ = 20221222
### { HOUSEKEEPING
import sys, os, os.path, time, logging, re, pickle, threading
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as messagebox
import tkinter.filedialog as filedialog
# fix for wrong path of pythoncomXX.dll in vulcan 10.1.5
if 'VULCAN_EXE' in os.environ:
os.environ['PATH'] += ';' + os.environ['VULCAN_EXE'] + "/Lib/site-packages/pywin32_system32"
### } HOUSEKEEPING
### { UTIL
logging.basicConfig(format='%(message)s', level=99)
log = lambda *argv: logging.log(99, time.strftime('%H:%M:%S ') + ' '.join(map(str,argv)))
def pyd_zip_extract():
''' embedded module unpacker '''
zip_path = os.path.splitext(sys.argv[0])[0] + '.pyz'
if not os.path.exists(zip_path):
return
platform_arch = '.cp%d%d-win_amd64' % (sys.hexversion >> 24, sys.hexversion >> 16 & 0xFF)
pyd_path = os.environ.get('TEMP', '.') + "/pyz_" + platform_arch
if not os.path.isdir(pyd_path):
os.mkdir(pyd_path)
sys.path.insert(0, pyd_path)
os.environ['PATH'] = os.environ.get('PATH', '') + ';' + pyd_path
import zipfile
zip_root = zipfile.ZipFile(zip_path)
for name in zip_root.namelist():
m = re.match('[^/]+' + platform_arch + r'\.(pyd|zip)$', name, re.IGNORECASE)
if m:
if not os.path.exists(os.path.join(pyd_path, name)):
zip_root.extract(name, pyd_path)
if m.group(1) == "zip":
subzip = os.path.join(pyd_path, name)
zipfile.ZipFile(subzip).extractall(pyd_path)
def package_install(*argv):
r = [sys.executable, '-m', 'pip', 'install'] + list(argv)
print(' '.join(r))
os.system(' '.join(r))
sys.exit()
def package_require(*argv):
from importlib.util import find_spec
r = []
for kv in argv:
k = v = kv
if isinstance(kv, tuple):
k,v = kv
if not find_spec(k):
r.append(v)
if len(r):
if messagebox.askyesno(sys.argv[0], 'install required modules: ' + ','.join(r)):
package_install(*r)
def import_vulcan():
# custom vulcan import for hybrid scripts
try:
import __main__, __mp_main__, vulcan
# main package
__main__.vulcan = vulcan
__mp_main__.vulcan = vulcan
# this package
globals()['vulcan'] = vulcan
except:
messagebox.showerror('import vulcan', 'This script must be run within Maptek Vulcan')
sys.exit(1)
def list_any(l):
return sum(map(bool, l))
class commalist(list):
'''
subclass of list with a string representation compatible to perl argument input
which expects a comma separated list with semicolumns between rows
'''
_rowfs = ";"
_colfs = ","
def __init__(self, arg = None):
if isinstance(arg, str):
for row in arg.split(self._rowfs):
self.append(row.split(self._colfs))
elif arg:
super().__init__(arg)
def parse(self, arg):
''' backward compatibility '''
return commalist(arg)
def __str__(self):
r = ""
# custom join
for i in self:
if(isinstance(i, list)):
i = self._colfs.join(i)
if len(r) > 0:
r += self._rowfs
r += i
return r
def __hash__(self):
return len(self)
# sometimes we have one element, but that element is ""
# unless we override, this will evaluate as True
def __bool__(self):
return len(str(self)) > 0
# compatibility if the user try to treat us as a real string
def split(self, *args):
return [",".join(_) for _ in self]
def table_name_selector(df_path, table_name = None):
if table_name is None:
m = re.match(r'^(.+)!(\w+)$', df_path)
if m:
df_path = m.group(1)
table_name = m.group(2)
return df_path, table_name
def bm_sanitize_condition(condition):
if condition is None:
condition = ""
if len(condition) > 0:
# convert a raw condition into a actual block select string
if re.match(r'\s*\-', condition):
# condition is already a select syntax
pass
elif re.search(r'\.00t$', condition, re.IGNORECASE):
# bounding solid
condition = '-X -t "%s"' % (condition)
else:
condition = '-C "%s"' % (condition.replace('"', "'"))
return condition
# convert field names in the TABLE:FIELD to just FIELD or just TABLE
def table_field(args, table=False):
if isinstance(args, list):
args = [table_field(arg, table) for arg in args]
elif args.find(':') != -1:
if table:
args = args[0:args.find(':')]
else:
args = args[args.find(':')+1:]
return args
# wait and unlock block model
def bmf_wait_lock(path, unlock = False, tries = None):
blk_lock = os.path.splitext(path)[0] + ".blk_lock"
print("waiting lock", blk_lock)
while os.path.isfile(blk_lock):
if unlock and not tries:
os.remove(blk_lock)
print("removed lock", blk_lock)
break
if tries == 0:
break
if tries is not None:
tries -= 1
print("waiting lock", blk_lock, tries, "seconds")
time.sleep(1)
### } UTIL
### { IO
def pd_load_dataframe(df_path, condition = '', table_name = None, vl = None, keep_null = False):
'''
convenience function to return a dataframe based on the input file extension
csv: ascii tabular data
xls: excel workbook
bmf: vulcan block model
dgd.isis: vulcan design object layer
isis: vulcan generic database
00t: vulcan triangulation
dm: datamine generic database
shp: ESRI shape file
'''
import pandas as pd
# early exit for cases where a script is calling another
if isinstance(df_path, pd.DataFrame):
return df_path
if table_name is None:
df_path, table_name = table_name_selector(df_path)
df = None
if not os.path.exists(df_path):
print(df_path,"not found")
df = pd.DataFrame()
elif re.search(r'(csv|asc|prn|txt)$', df_path, re.IGNORECASE):
df = pd.read_csv(df_path, sep=None, engine='python', encoding='latin_1')
elif re.search(r'xls\w?$', df_path, re.IGNORECASE):
df = pd_load_excel(df_path, table_name)
elif df_path.lower().endswith('bmf'):
df = pd_load_bmf(df_path, condition, vl)
condition = ''
elif df_path.lower().endswith('dgd.isis'):
df = pd_load_dgd(df_path, table_name)
elif df_path.lower().endswith('isis'):
df = pd_load_isisdb(df_path, table_name)
elif df_path.lower().endswith('00t'):
df = pd_load_tri(df_path)
elif df_path.lower().endswith('00g'):
df = pd_load_grid(df_path)
elif df_path.lower().endswith('dm'):
df = pd_load_dm(df_path)
elif df_path.lower().endswith('shp'):
df = pd_load_shape(df_path)
elif df_path.lower().endswith('dxf'):
df = pd_load_dxf(df_path)
elif df_path.lower().endswith('json'):
df = pd.read_json(df_path)
elif df_path.lower().endswith('jsdb'):
import jsdb_driver
df = jsdb_driver.pd_load_database(df_path)
elif df_path.lower().endswith('msh'):
df = pd_load_mesh(df_path)
elif df_path.lower().endswith('png'):
df = pd_load_spectral(df_path)
elif df_path.lower().endswith('obj'):
df = pd_load_obj(df_path)
elif df_path.lower().endswith('vtk'):
from pd_vtk import pv_read, vtk_mesh_to_df
mesh = pv_read(df_path)
df = vtk_mesh_to_df(mesh)
elif df_path.lower().endswith('arch_d'):
from vulcan_mapfile import pd_load_arch
df = pd_load_arch(df_path)
elif re.search(r'tiff?$', df_path, re.IGNORECASE):
import vulcan_save_tri
df = vulcan_save_tri.pd_load_geotiff(df_path)
else:
df = pd.DataFrame()
if not int(keep_null):
df.mask(df == -99, inplace=True)
# replace -99 with NaN, meaning they will not be included in the stats
if len(condition):
df.query(condition, inplace=True)
return df
def pd_synonyms(df, synonyms, default = 0):
import pandas as pd
s_lut = {}
s_lut['hid'] = ['hid', 'hole', 'hole_number', 'furo', 'bhid', 'dhid']
s_lut['x'] = ['x', 'xpt', 'mid_x', 'east', 'easting', 'leste']
s_lut['y'] = ['y', 'ypt', 'mid_y', 'north', 'northing', 'norte']
s_lut['z'] = ['z', 'zpt', 'mid_z', 'level', 'cota', 'elev']
s_lut['depth'] = ['depth', 'prof']
s_lut['brg'] = ['brg', 'azimuth', 'azim', 'azi']
s_lut['dip'] = ['dip', 'inclin']
s_lut['from'] = ['from', 'de']
s_lut['to'] = ['to', 'ate']
s_lut['length'] = ['length', 'comp']
if isinstance(synonyms, str) and synonyms in s_lut:
synonyms = s_lut[synonyms]
''' from a list of synonyms, find the best candidate amongst the dataframe columns '''
if len(synonyms):
# first try a direct match
for v in synonyms:
if v in df:
return v
# second try a case insensitive match
for v in synonyms:
m = pd.Series(df.columns, dtype='str').str.match(v, False)
if m.any():
return df.columns[m.argmax()]
# fail safe to the first column
if default is not None:
return df.columns[default]
return None
def pd_detect_xyz(df, z = True):
xyz = None
dfcs = set(df.columns)
for s in [['x','y','z'], ['midx','midy','midz'], ['mid_x','mid_y','mid_z'], ['xworld','yworld','zworld'], ['xcentre','ycentre','zcentre'], ['centroid_x', 'centroid_y', 'centroid_z'], ['xc','yc','zc'], ['leste', 'norte', 'cota']]:
if z == False:
s.pop()
for c in [str.lower, str.upper,str.capitalize]:
cs = list(map(c, s))
if dfcs.issuperset(cs):
xyz = cs
break
else:
continue
# break also the outter loop if the inner loop broke
break
# try again looking only for xy
if xyz is None and z:
return pd_detect_xyz(df, False)
return xyz
def pd_flat_columns(df):
""" convert a column multi index into flat concatenated strings """
return df.set_axis([" ".join(map(str,_)) for _ in df.columns.to_flat_index()], axis=1)
def pd_save_dataframe(df, df_path, sheet_name='Sheet1'):
import pandas as pd
''' save a dataframe to one of the supported formats '''
if df is not None and df.size:
if df.ndim == 1:
# we got a series somehow?
df = df.to_frame()
if not str(df.index.dtype).startswith('int'):
levels = list(set(df.index.names).intersection(df.columns))
if len(levels):
df.reset_index(levels, drop=True, inplace=True)
df.reset_index(inplace=True)
if isinstance(df.columns, pd.MultiIndex):
df = pd_flat_columns(df)
if isinstance(df_path, pd.ExcelWriter) or df_path.lower().endswith('.xlsx'):
# multiple excel sheets mode
df.to_excel(df_path, index=False, sheet_name=sheet_name)
elif df_path.lower().endswith('dgd.isis'):
pd_save_dgd(df, df_path)
elif df_path.lower().endswith('isis'):
pd_save_isisdb(df, df_path)
elif df_path.lower().endswith('bmf'):
pd_save_bmf(df, df_path)
elif df_path.lower().endswith('shp'):
pd_save_shape(df, df_path)
elif df_path.lower().endswith('dxf'):
pd_save_dxf(df, df_path)
elif df_path.lower().endswith('00t'):
pd_save_tri(df, df_path)
elif df_path.lower().endswith('json'):
df.to_json(df_path, 'records')
elif df_path.lower().endswith('jsdb'):
import jsdb_driver
jsdb_driver.pd_save_database(df, df_path)
elif df_path.lower().endswith('msh'):
pd_save_mesh(df, df_path)
elif df_path.lower().endswith('obj'):
pd_save_obj(df, df_path)
elif df_path.lower().endswith('png'):
pd_save_spectral(df, df_path)
elif df_path.lower().endswith('vtk'):
from pd_vtk import pv_save, vtk_df_to_mesh
mesh = vtk_df_to_mesh(df)
pv_save(mesh, df_path)
elif re.search(r'tiff?$', df_path, re.IGNORECASE):
import vulcan_save_tri
vulcan_save_tri.pd_save_geotiff(df, df_path)
elif len(df_path) and df_path != '|':
if sys.hexversion < 0x3080000:
# no single case works for vulcan python 3.5
try:
df.to_csv(df_path, index=False, encoding='latin_1')
except:
df.to_csv(df_path, index=False, encoding='utf8')
else:
df.to_csv(df_path, index=False, encoding='utf8', errors='backslashreplace')
else:
print(df.to_string(index=False))
else:
print(df_path,"empty")
def dgd_list_layers(file_path):
''' return the list of layers stored in a dgd '''
import vulcan
r = []
if vulcan.version_major < 11:
db = vulcan.isisdb(file_path)
r = [db.get_key() for _ in db.keys if db.get_key().find('$') == -1]
db.close()
else:
dgd = vulcan.dgd(file_path)
r = [_ for _ in dgd.list_layers() if _.find('$') == -1]
dgd.close()
return r
# Vulcan BMF
def bmf_field_list(file_path):
import vulcan
bm = vulcan.block_model(file_path)
r = bm.field_list()
bm.close()
return r
def bm_get_pandas_proportional(self, vl=None, select=None):
"""
custom get_pandas dropin replacement with proportional volume inside solid/surface
"""
import pandas as pd
if select is None:
select = ''
if vl is None:
vl = self.field_list() + [ 'xlength', 'ylength', 'zlength', 'xcentre', 'ycentre', 'zcentre', 'xworld', 'yworld', 'zworld' ]
vi = None
if 'volume' in vl:
vi = vl.index('volume')
self.select(select)
data = []
for block in self:
row = [self.get_string(v) if self.is_string( v ) else self.get(v) for v in vl]
if vi is not None:
row[vi] = self.match_volume()
data.append(row)
return pd.DataFrame(data, columns=vl)
def pd_load_bmf(df_path, condition = '', vl = None):
import vulcan
bm = vulcan.block_model(df_path)
if vl is not None:
vl = list(filter(bm.is_field, vl))
# get a DataFrame with block model data
if '-X' in condition:
return bm_get_pandas_proportional(bm, vl, bm_sanitize_condition(condition))
else:
return bm.get_pandas(vl, bm_sanitize_condition(condition))
def pd_auto_schema(df, xyzd):
import numpy as np
import pandas as pd
xyz0 = np.zeros(3)
xyzo = np.min(df.loc[:, ['xworld','yworld','zworld']])
xyz1 = np.subtract(np.max(df.loc[:, ['xworld','yworld','zworld']]), xyzo)
xyz1 = np.multiply(np.ceil(np.divide(xyz1, xyzd)), xyzd)
xyzo = np.subtract(xyzo, np.multiply(xyzd, [0.5,0.5,0.5]))
xyzn = np.ceil(np.divide(xyz1, xyzd))
return xyzo, xyz0, xyz1, xyzn
def pd_save_bmf(df, df_path):
import vulcan
import numpy as np
import pandas as pd
xyzw = ['xworld','yworld','zworld']
xyzd = np.ones(3)
vlc = 3
for v in xyzw:
if v not in df:
break
else:
if 'xlength' in df:
vlc += 1
xyzd[0] = df['xlength'].mean()
if 'ylength' in df:
vlc += 1
xyzd[1] = df['ylength'].mean()
if 'zlength' in df:
vlc += 1
xyzd[2] = df['zlength'].mean()
xyzo, xyz0, xyz1, xyzn = pd_auto_schema(df, xyzd)
vl = df.columns[vlc:]
bm = vulcan.block_model()
# self, name, x0, y0, z0, x1, y1, z1, nx, ny, nz
# bm.create_regular(df_path, *xyz0, *xyz1, *xyzn)
# xyzn = xyzn.astype(np.int_)
bm.create_regular(df_path, *xyz0, *xyz1, int(xyzn[0]), int(xyzn[1]), int(xyzn[2]))
bm.set_model_origin(*xyzo)
for v in vl:
if df.dtypes[v] == 'object':
bm.add_variable(v, 'name', 'n', '')
else:
bm.add_variable(v, 'float', '-99', '')
bm.write()
print("index model")
bm.index_model()
bm.write()
for row in df.index:
if row % 10000 == 0:
print("blocks processed:",row)
bm.find_world_xyz(*df.loc[row, xyzw])
for v in vl:
if df.dtypes[v] == 'object':
bm.put_string(v, df.loc[row, v])
else:
bm.put(v, df.loc[row, v])
print("blocks processed:",row)
print(df_path, "saved")
# Vulcan ISIS database
def isisdb_list(file_path, alternate = False):
import vulcan
db = vulcan.isisdb(file_path)
if alternate:
vl = db.table_list()
else:
key = db.synonym('GEO','HOLEID')
if not key:
key = 'KEY'
vl = db.field_list(db.table_list()[-1])
vl.insert(0, key)
db.close()
return vl
def isisdb_check_table_name(db, table_name):
# by default, use last table which is the desired one in most cases
if table_name is None or table_name not in db.table_list():
table_name = db.table_list()[-1]
return table_name
def pd_load_isisdb(df_path, table_name = None):
import vulcan
import pandas as pd
if os.path.exists(df_path + '_lock'):
raise Exception('Input database locked')
db = vulcan.isisdb(df_path)
table_name = isisdb_check_table_name(db, table_name)
vl = list(db.field_list(table_name))
key = db.synonym('GEO','HOLEID')
if not key:
key = 'KEY'
fdata = []
db.rewind()
while not db.eof():
if table_name == db.get_table_name():
row = [db[field] for field in vl]
if key not in vl:
row.insert(0, db.get_key())
fdata.append(row)
db.next()
if key not in vl:
vl.insert(0, key)
return pd.DataFrame(fdata, None, vl)
def pd_save_isisdb(df, df_path, table_name = None):
import vulcan
import pandas as pd
if os.path.exists(df_path + '_lock'):
raise Exception('Input database locked')
db = vulcan.isisdb(df_path)
table_name = isisdb_check_table_name(db, table_name)
header = db.synonym('IDENT', 'HOLEID')
if not header:
header = db.table_list()[0]
key = db.synonym('GEO','HOLEID')
# default to first field of first table
if not key:
key = db.field_list(header)[0]
if key not in df:
df[key] = os.path.basename(df_path)
vl = set(df.columns).intersection(db.field_list(table_name))
print("header",header,"key",key,"table",table_name,"vl",vl)
for gp,df_key in df.groupby(key):
if db.find_key(gp) == 0:
print("replaced",key,gp)
db.delete_key(gp)
else:
print("created",key,gp)
db.put_table_name(header)
db.put_string(key, gp)
db.append()
db.put_table_name(table_name)
for row in df_key.index:
for v in vl:
if db.is_string(v, table_name):
db.put_string(v, str(df_key.loc[row, v]))
else:
db.put(v, df_key.loc[row, v])
db.append()
def pd_update_isisdb(df, df_path, table_name = None, vl = None):
import vulcan
import numpy as np
import pandas as pd
if os.path.exists(df_path + '_lock'):
raise Exception('Input database locked')
if vl is None:
vl = df.columns
if np.ndim(vl) == 0:
vl = [vl]
db = vulcan.isisdb(df_path)
table_name = isisdb_check_table_name(db, table_name)
row = 0
df.index = pd.RangeIndex(row,len(df))
while not db.eof():
if table_name == db.get_table_name():
for v in vl:
if db.is_string(v, table_name):
db.put_string(v, str(df.loc[row, v]))
else:
db.put(v, float(df.loc[row, v]))
row += 1
if row >= len(df):
break
db.next()
def pd_load_dgd(df_path, layer_dgd = None):
''' create a dataframe with object points and attributes '''
import vulcan
import pandas as pd
obj_attr = ['name', 'group', 'feature', 'description', 'value', 'colour']
df = pd.DataFrame(None, columns=smartfilelist.default_columns + ['p','closed','layer','oid'] + obj_attr)
dgd = vulcan.dgd(df_path)
row = 0
if dgd.is_open():
layers = layer_dgd
if layer_dgd is None:
layers = dgd_list_layers(df_path)
elif not isinstance(layer_dgd, list):
layers = [layer_dgd]
for l in layers:
if not dgd.is_layer(l):
continue
log("reading layer", l)
layer = dgd.get_layer(l)
oid = 0
for obj in layer:
df_row = pd.Series()
df_row['oid'] = str(oid)
df_row['layer'] = layer.get_name()
for t in obj_attr:
df_row[t] = getattr(obj, t)
if obj.get_type().startswith('TEXT'):
df_row['x'],df_row['y'],df_row['z'],df_row['w'],df_row['t'],df_row['p'] = obj.get_origin()
df_row['n'] = 0
df.loc[row] = df_row
row += 1
else:
for n in range(obj.num_points()):
df_row['closed'] = obj.is_closed()
p = obj.get_point(n)
df_row['x'] = p.get_x()
df_row['y'] = p.get_y()
df_row['z'] = p.get_z()
df_row['w'] = p.get_w()
df_row['t'] = p.get_t()
df_row['p'] = p.get_name()
# point sequence within this polygon
df_row['n'] = n
df.loc[row] = df_row
row += 1
oid += 1
return df
def pd_to_vulcan_layers(df, xyz):
import vulcan
obj_attr = ['value', 'name', 'group', 'feature', 'description']
layer_cache = dict()
c = []
n = None
for row in df.index[::-1]:
layer_name = '0'
if 'layer' in df:
layer_name = df.loc[row, 'layer']
if layer_name not in layer_cache:
layer_cache[layer_name] = vulcan.layer(str(layer_name))
if 'n' in df:
n = df.loc[row, 'n']
else:
n = row
# last row special case
c.insert(0, row)
if n == 0:
points = df.loc[c, xyz].values.tolist()
obj = vulcan.polyline(points)
if 'closed' in df:
obj.set_closed(bool(df.loc[row, 'closed']))
for i in range(len(obj_attr)):
if obj_attr[i] in df:
v = df.loc[row, obj_attr[i]]
if i == 0:
v = float(v)
elif v != v:
# v is nan
v = ''
else:
# vulcan API crashes on some unicode characters
v = str(bytes(v, 'ascii', 'replace'), 'ascii')
setattr(obj, obj_attr[i], v)
layer_cache[layer_name].append(obj)
c.clear()
return layer_cache
def pd_save_dgd(df, df_path):
''' create vulcan objects from a dataframe '''
import vulcan
xyz = ['x','y','z','w','t']
if 'w' not in df:
df['w'] = 0
if 't' not in df:
df['t'] = 0
layer_cache = pd_to_vulcan_layers(df, xyz)
dgd = vulcan.dgd(df_path, 'w' if os.path.exists(df_path) else 'c')
for v in layer_cache.values():
log("saving layer", v.name)
dgd.save_layer(v)
# Vulcan Triangulation 00t
def pd_load_tri(df_path):
import vulcan
import numpy as np
import pandas as pd
tri = vulcan.triangulation(df_path)
ta = vulcan.tri_attributes(df_path)
cv = tri.get_colour()
cn = 'colour'
if vulcan.version_major >= 11 and tri.is_rgb():
cv = np.sum(np.multiply(tri.get_rgb(), [2**16,2**8,1]))
cn = 'rgb'
#print("pd_load_tri nodes",tri.n_nodes(),"faces",tri.n_faces())
#df = [tri.get_node(int(f[n])) + [0,bool(n),n,1,f[n],cv] for f in tri.get_faces() for n in range(3)],
# orphan nodes
df = nodes_faces_to_df(tri.get_vertices(), tri.get_faces())
if ta.is_ok():
for k,v in ta.get_hash().items():
df[k] = v
return df
def df_to_nodes_faces_simple(df, node_name = 'node', xyz = ['x','y','z']):
''' fast version only supporting a single triangulation '''
import pandas as pd
# nodes are duplicated for each face in df
# create a list where they are unique again
i_row = df[node_name].drop_duplicates().sort_values()
nodes = df.loc[i_row.index, xyz]
face_size = 3
if 'n' in df and len(df):
# handle orphan nodes
face_n = df['n'].dropna()
face_size = int(face_n.max()) + 1
faces = df.loc[face_n.index, node_name].values.reshape((len(face_n) // face_size, face_size))
else:
# faces are unique so we can use the input data
faces = df[node_name].values.reshape((len(df) // face_size, face_size))
return nodes.values, faces
def df_to_nodes_faces_lines(df, node_name = 'node', xyz = ['x','y','z']):
nodes = []
lines = []
if 'type' in df:
l_nodes, lines = df_to_nodes_lines(df.query("type != 'TRIANGLE'"), node_name, xyz)
nodes.extend(l_nodes)
df = df.query("type == 'TRIANGLE'")
t_nodes, faces = df_to_nodes_faces(df, node_name, xyz)
nodes.extend(t_nodes)
return nodes, faces, lines
def df_to_nodes_lines(df, node_name, xyz):
nodes = df[xyz].values.take(df[node_name], 0)
lines = []
n = len(df)
part = []
for row in df.index[::-1]:
if 'n' in df:
n = df.loc[row, 'n']
else:
n -= 1
part.insert(0, n)
if n == 0:
lines.insert(0, part)
part = []
return nodes, lines
df_to_nodes_faces = df_to_nodes_faces_simple
def pd_save_tri(df, df_path):
import vulcan
import numpy as np
if os.path.exists(df_path):
os.remove(df_path)
tri = vulcan.triangulation("", "w")
if 'rgb' in df:
rgb = np.floor(np.divide(np.mod(np.repeat(df.loc[0, 'rgb'],3), [2**32, 2**16, 2**8]), [2**16,2**8,1]))
print('color r %d g %d b %d' % tuple(rgb))
tri.set_rgb(rgb.tolist())
elif 'colour' in df:
print('colour index ', df.loc[0, 'colour'])
tri.set_colour(int(df.loc[0, 'colour']))
else:
print('default color')
tri.set_colour(1)
if 'filename' not in df:
df['filename'] = ''
nodes, faces = df_to_nodes_faces(df)
print("nodes",len(nodes))
print("faces",len(faces))
for n in nodes:
tri.add_node(*n)
for f in faces:
tri.add_face(*map(int,f))
tri.save(df_path)
# Vulcan Grid 00g
def pd_load_grid(df_path):
import vulcan
grid = vulcan.grid(df_path)
df = grid.get_pandas()
df['filename'] = os.path.basename(df_path)
return df
# Datamine DM
def pd_load_dm(df_path, condition = ''):
import win32com.client
import pandas as pd
dm = win32com.client.Dispatch('DmFile.DmTable')
dm.Open(df_path, 0)
fdata = []
n = dm.Schema.FieldCount
for i in range(dm.GetRowCount()):
#fdata.append([dm.GetColumn(j) for j in range(1, n)])
row = [None] * n
for j in range(n):
v = dm.GetColumn(j+1)
if v != dm.Schema.SpecialValueAbsent:
row[j] = v
fdata.append(row)
dm.GetNextRow()
return pd.DataFrame(fdata, None, [dm.Schema.GetFieldName(j+1) for j in range(n)])
def dm_field_list(file_path):
import win32com.client
dm = win32com.client.Dispatch('DmFile.DmTable')
dm.Open(file_path, 0)
r = [dm.Schema.GetFieldName(j) for j in range(1, dm.Schema.FieldCount + 1)]
return r
# Microsoft Excel compatibles
def excel_field_list(df_path, table_name, alternate = False):
r = []
try:
import openpyxl
wb = openpyxl.load_workbook(df_path)
if alternate:
r = wb.sheetnames
elif table_name and table_name in wb:
r = next(wb[table_name].values)
else:
r = next(wb.active.values)
except:
print("openpyxl not available")
import pandas as pd
r = pd.read_excel(df_path).columns
return r
def pd_from_openpyxl(ws):
import pandas as pd
data = ws.values
cols = list(next(data))
# handle duplicate columns
for i in range(len(cols)):
for j in range(i-1,-1,-1):
if cols[i] == cols[j]:
cols[i] += '.' + str(i)
return pd.DataFrame(data, columns=[i if cols[i] is None else cols[i] for i in range(len(cols))])
def pd_load_excel_350(df_path, table_name):
import openpyxl
wb = openpyxl.load_workbook(df_path)
ws = None
if table_name and table_name in wb:
ws = wb[table_name]
else:
ws = wb.active
# handle duplicated columns
return pd_from_openpyxl(ws)
def pd_load_excel(df_path, table_name = None):
if sys.hexversion < 0x3060000:
return pd_load_excel_350(df_path, table_name)
import pandas as pd
df = None
engine = 'openpyxl'
if df_path.lower().endswith('.xls'):
# openpyxl is not handling xls anymore
engine = None
if not table_name:
table_name = None
df = pd.read_excel(df_path, table_name, engine=engine)
if not isinstance(df, pd.DataFrame):
_, df = df.popitem()
return df
def pd_save_excel_tables(save_path, *arg, header=True):
import openpyxl
from openpyxl.worksheet.table import Table
from openpyxl.utils import get_column_letter
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
from openpyxl.worksheet.worksheet import Worksheet
wb = openpyxl.Workbook()
# remove the default Sheet1
wb.remove(wb.active)
for i in range(0, len(arg), 2):
t = None
if i+1 < len(arg):
t = arg[i+1]
if not t:
t = 'Table%d' % (i / 2 + 1)
df = arg[i]
# solve IllegalCharacterError problems
if not isinstance(df, Worksheet):
df.replace(ILLEGAL_CHARACTERS_RE, ' ', inplace=True)
ws = wb.create_sheet(title=t)
if isinstance(df, openpyxl.worksheet.worksheet.Worksheet):
for row in df.values:
ws.append(row)
else:
if not str(arg[i].index.dtype).startswith('int'):
df = arg[i].reset_index()
for r in dataframe_to_rows(df, index=False, header=header):
ws.append(r)
if header:
tab = Table(displayName=t, ref="A1:%s%d" % (get_column_letter(ws.max_column), ws.max_row))
ws.add_table(tab)
wb.save(save_path)
# ESRI shape
def pd_load_shape(file_path):
import pandas as pd
import shapefile
shapes = shapefile.Reader(file_path, encodingErrors='replace')
columns = smartfilelist.default_columns + ['oid','part','type','layer']
record_n = 0
row = 0