-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_gui.py
1570 lines (1320 loc) · 48.9 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 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
---------------------------------
'''
### UTIL { ###
import sys, os, os.path, time
# import modules from a pyz (zip) file with same name as scripts
sys.path.insert(0, os.path.splitext(sys.argv[0])[0] + '.pyz')
import numpy as np
import pandas as pd
from PIL import Image, ImageDraw
# 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"
def pyd_zip_extract(pyd_path = None):
pyz_path = os.path.splitext(sys.argv[0])[0] + '.pyz'
if not os.path.exists(pyz_path):
return
from zipfile import ZipFile
pyz = ZipFile(pyz_path)
# extract any pyd library to current folder since they are not supported by zipimport
# also, extract modules which for other reasons do no work inside a zip
platform_arch = '.cp%s%s-win_amd64' % tuple(sys.version.split('.')[:2])
if pyd_path is None:
pyd_path = os.environ['TEMP'] + "/pyz"
if not os.path.isdir(pyd_path):
os.mkdir(pyd_path)
sys.path.insert(0, pyd_path)
os.environ['PATH'] += ';' + pyd_path
for name in pyz.namelist():
if re.match('[^/]+' + platform_arch + r'\.(pyd|zip)$', name, re.IGNORECASE):
if name.endswith('zip'):
# workaround for some weird bug in python 3.5
if sys.hexversion < 0x3070000:
pyz.extract(name)
ZipFile(name).extractall(pyd_path)
os.remove(name)
else:
ZipFile(pyz.open(name)).extractall(pyd_path)
elif not os.path.exists(name):
pyz.extract(name, pyd_path)
def usage_gui(usage = None):
'''
this function handles most of the details required when using a exe interface
'''
# we already have argument, just proceed with execution
if(len(sys.argv) > 1):
# traps help switches: /? -? /h -h /help -help
if(usage is not None and re.match(r'[\-/](?:\?|h|help)$', sys.argv[1])):
print(usage)
elif 'main' in globals():
main(*sys.argv[1:])
else:
print("main() not found")
else:
AppTk(usage).mainloop()
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
'''
if table_name is None:
df_path, table_name = table_name_selector(df_path)
df = None
if df_path.lower().endswith('csv'):
df = pd.read_csv(df_path, encoding="latin1")
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('dm'):
df = pd_load_dm(df_path)
elif df_path.lower().endswith('shp'):
df = pd_load_shape(df_path)
elif df_path.lower().endswith('msh'):
df = pd_load_mesh(df_path)
elif re.search(r'tiff?$', df_path, re.IGNORECASE):
df = pd_load_spectral(df_path)
else:
df = pd.DataFrame()
if len(condition):
df.query(condition, True)
# replace -99 with NaN, meaning they will not be included in the stats
if not int(keep_null):
df.mask(df == -99, inplace=True)
return df
# temporary backward compatibility
pd_get_dataframe = pd_load_dataframe
def pd_save_dataframe(df, df_path, sheet_name='Sheet1'):
''' save a dataframe to one of the supported formats '''
if df.size:
if not df.index.dtype_str.startswith('int'):
df.reset_index(inplace=True)
while isinstance(df.columns, pd.MultiIndex):
df.columns = df.columns.droplevel(1)
if isinstance(df_path, pd.ExcelWriter) or df_path.lower().endswith('.xlsx'):
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('.shp'):
pd_save_shape(df, df_path)
elif df_path.lower().endswith('.00t'):
pd_save_tri(df, df_path)
elif df_path.lower().endswith('.msh'):
pd_save_mesh(df, df_path)
elif re.search(r'tiff?$', df_path, re.IGNORECASE):
pd_save_spectral(df, df_path)
elif len(df_path):
df.to_csv(df_path, index=False)
else:
print(df.to_string())
else:
print(df_path,"empty")
def pd_synonyms(df, synonyms):
''' from a list of synonyms, find the best candidate amongst the dataframe columns '''
if len(synonyms) == 0:
return df.columns[0]
# 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 = df.columns.str.match(v, False)
if m.any():
return df.columns[m.argmax()]
# fail safe to the first column
return df.columns[0]
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 ###
## GUI { ###
import re
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as messagebox
import tkinter.filedialog as filedialog
import pickle
import threading
class ClientScript(list):
'''Handles the script with the same name as this interface file'''
# magic signature that a script file must have for defining its gui
_magic = r"usage:\s*\S+\s*([^\"\'\\]+)"
_usage = None
_type = None
_file = None
_base = None
@classmethod
def init(cls, client):
cls._file = client
cls._base = os.path.splitext(cls._file)[0]
# HARDCODED list of supporte file types
# to add a new file type, just add it to the list
for ext in ['csh','lava','pl','bat','vbs','js']:
if os.path.exists(cls._base + '.' + ext):
cls._file = cls._base + '.' + ext
cls._type = ext.lower()
break
@classmethod
def exe(cls):
if cls._type == "csh":
return ["csh","-f"]
if cls._type == "bat":
return ["cmd", "/c"]
if cls._type == "vbs" or cls._type == "js":
return ["cscript", "/nologo"]
if cls._type == "lava" or cls._type == "pl":
return ["perl"]
if cls._type is None:
return ["python"]
return []
@classmethod
def run(cls, script):
print("# %s %s started" % (time.strftime('%H:%M:%S'), cls.file()))
p = None
if cls._type is None:
import multiprocessing
p = multiprocessing.Process(None, main, None, script.get())
p.start()
p.join()
p = p.exitcode
else:
import subprocess
# create a new process and passes the arguments on the command line
p = subprocess.Popen(cls.exe() + [cls._file] + script.getArgs())
p.wait()
p = p.returncode
if not p:
print("# %s %s finished" % (time.strftime('%H:%M:%S'), cls.file()))
return p
@classmethod
def type(cls):
return cls._type
@classmethod
def base(cls):
return cls._base
@classmethod
def file(cls, ext = None):
if ext is not None:
return cls._base + '.' + ext
return os.path.basename(cls._file)
@classmethod
def args(cls, usage = None):
r = []
if usage is None and cls._type is not None:
usage = cls.parse()
if usage:
m = re.search(cls._magic, usage, re.IGNORECASE)
if(m):
cls._usage = m.group(1)
if cls._usage is None or len(cls._usage) == 0:
r = ['arguments']
else:
r = cls._usage.split()
return r
@classmethod
def fields(cls, usage = None):
return [re.match(r"^\w+", _).group(0) for _ in cls.args(usage)]
@classmethod
def parse(cls):
if os.path.exists(cls._file):
with open(cls._file, 'r') as file:
for line in file:
if re.search(cls._magic, line, re.IGNORECASE):
return line
return None
@classmethod
def header(cls):
r = ""
if os.path.exists(cls._file):
with open(cls._file, 'r') as file:
for line in file:
if(line.startswith('#!')):
continue
m = re.match(r'#\s*(.+)', line)
if m:
r += m.group(1) + "\n"
else:
break
return r
class Settings(str):
'''provide persistence for control values using pickled ini files'''
_ext = '.ini'
def __new__(cls, value=''):
if len(value) == 0:
value = os.path.splitext(os.path.realpath(sys.argv[0]))[0]
if not value.endswith(cls._ext):
value += cls._ext
return super().__new__(cls, value)
def save(self, obj):
pickle.dump(obj, open(self,'wb'), -1)
def load(self):
if os.path.exists(self):
return pickle.load(open(self, 'rb'))
return {}
# subclass of list with a string representation compatible to perl argument input
# which expects a comma separated list with semicolumns between rows
# this is to mantain compatibility with older versions of the usage gui
class commalist(list):
_rowfs = ";"
_colfs = ","
def parse(self, arg):
"fill this instance with data from a string"
if isinstance(arg, str):
for row in arg.split(self._rowfs):
self.append(row.split(self._colfs))
else:
self = commalist(arg)
return self
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 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
"""
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))
# Vulcan ISIS database
def isisdb_list(file_path, alternate = False):
import vulcan
db = vulcan.isisdb(file_path)
if alternate:
r = db.table_list()
else:
r = db.field_list(db.table_list()[-1])
db.close()
return r
def pd_load_isisdb(df_path, table_name = None):
if os.path.exists(df_path + '_lock'):
raise Exception('Input database locked')
import vulcan
db = vulcan.isisdb(df_path)
# 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]
field_list = list(db.field_list(table_name))
fdata = []
db.rewind()
while not db.eof():
if table_name == db.get_table_name():
fdata.append([db.get_key()] + [db[field] for field in field_list])
db.next()
key = db.synonym('GEO','HOLEID')
if not key:
key = 'KEY'
return pd.DataFrame(fdata, None, [key] + field_list)
def pd_load_dgd(df_path, layer_dgd = None):
''' create a dataframe with object points and attributes '''
import vulcan
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)
if dgd.is_open():
layers = layer_dgd
if layer_dgd is None:
layers = dgd.list_layers()
elif not isinstance(layer_dgd, list):
layers = [layer_dgd]
for l in layers:
if not dgd.is_layer(l):
continue
layer = dgd.get_layer(l)
oid = 0
for obj in layer:
for n in range(obj.num_points()):
row = len(df)
df.loc[row] = [None] * df.shape[1]
p = obj.get_point(n)
df.loc[row, 'x'] = p.get_x()
df.loc[row, 'y'] = p.get_y()
df.loc[row, 'z'] = p.get_z()
df.loc[row, 'w'] = p.get_w()
df.loc[row, 't'] = p.get_t()
# point sequence withing this polygon
df.loc[row, 'n'] = n
# point name attribute
df.loc[row, 'p'] = p.get_name()
df.loc[row, 'closed'] = obj.is_closed()
df.loc[row, 'layer'] = layer.get_name()
df.loc[row, 'oid'] = oid
for t in obj_attr:
df.loc[row, t] = getattr(obj, t)
oid += 1
return df
def pd_save_dgd(df, df_path):
''' create vulcan objects from a dataframe '''
import vulcan
obj_attr = ['value', 'name', 'group', 'feature', 'description']
dgd = vulcan.dgd(df_path, 'w' if os.path.exists(df_path) else 'c')
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(layer_name)
n = df.loc[row, 'n']
# last row special case
c.insert(0, row)
if n == 0:
points = df.take(c).take(range(5), 1).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 = str(df.loc[row, obj_attr[i]])
if i == 0:
v = float(df.loc[row, obj_attr[i]])
setattr(obj, obj_attr[i], v)
layer_cache[layer_name].append(obj)
c.clear()
for v in layer_cache.values():
dgd.save_layer(v)
# Vulcan Triangulation 00t
def pd_load_tri(df_path):
import vulcan
tri = vulcan.triangulation(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'
return pd.DataFrame([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)], columns=smartfilelist.default_columns + ['closed','node',cn])
def df_to_nodes_faces(df, node_name = 'node'):
nodes = []
faces = []
df.set_index(['filename', node_name], True, False, True)
df['i'] = range(len(df))
df[node_name] = -1
node_loc = df.columns.get_loc(node_name)
df.sort_index(inplace=True)
for irow in df.index.unique():
drow = df.xs(irow)
df.loc[irow, node_name] = len(nodes)
nodes.append([drow.iat[0, 0], drow.iat[0, 1], drow.iat[0, 2]])
df.sort_values('i', inplace=True)
f = []
for i in range(len(df)):
f.append(int(df.iat[i, node_loc]))
if len(f) == 3:
faces.append(f.copy())
f.clear()
return(nodes, faces)
def pd_save_tri(df, df_path):
import vulcan
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)
for n in nodes:
tri.add_node(*n)
for f in faces:
tri.add_face(*f)
tri.save(df_path)
# Datamine DM
def pd_load_dm(df_path, condition = ''):
import win32com.client
dm = win32com.client.Dispatch('DmFile.DmTable')
dm.Open(df_path, 0)
fdata = []
n = dm.Schema.FieldCount + 1
for i in range(dm.GetRowCount()):
fdata.append([dm.GetColumn(j) for j in range(1, n)])
dm.GetNextRow()
return pd.DataFrame(fdata, None, [dm.Schema.GetFieldName(j) for j in range(1, 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 csv_field_list(df_path):
df = pd.read_csv(df_path, encoding="latin1", nrows=1)
return list(df.columns)
def excel_field_list(df_path, table_name, alternate = False):
import openpyxl
wb = openpyxl.load_workbook(df_path)
r = []
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)
return r
def pd_load_excel(df_path, table_name = None):
df = None
if pd.__version__ < '0.20':
import openpyxl
wb = openpyxl.load_workbook(df_path)
data = wb.active.values
if table_name and table_name in wb:
data = wb[table_name].values
cols = next(data)
df = pd.DataFrame(data, columns=[i if cols[i] is None else cols[i] for i in range(len(cols))])
else:
df = pd.read_excel(df_path, table_name)
if not isinstance(df, pd.DataFrame):
_, df = df.popitem(False)
return df
# ESRI shape
def pd_load_shape(file_path):
import shapefile
shapes = shapefile.Reader(file_path)
df = pd.DataFrame(None, columns=smartfilelist.default_columns + ['oid','part','type','layer'])
record_n = 0
row = 0
for item in shapes.shapeRecords():
# object without a valid layer name will have this default layer
fields = item.record.as_dict()
p1 = len(item.shape.points)
# each object may have multiple parts
# create a object for each of these parts
part_n = len(item.shape.parts)
for p in reversed(item.shape.parts):
part_n -= 1
for n in range(p,p1):
for c in range(len(item.shape.points[n])):
df.loc[row, df.columns[c]] = item.shape.points[n][c]
for k,v in fields.items():
df.loc[row, k] = v
df.loc[row, 'n'] = n
df.loc[row, 'w'] = 0
df.loc[row, 't'] = n != p
df.loc[row, 'oid'] = record_n
df.loc[row, 'type'] = item.shape.shapeTypeName
df.loc[row, 'part'] = part_n
row += 1
p1 = p
record_n += 1
return df
def pd_save_shape(df, df_path):
import shapefile
shpw = shapefile.Writer(os.path.splitext(df_path)[0])
for i in range(5, df.shape[1]):
shpw.field(df.columns[i], 'C' if df.dtypes[i] == 'object' else 'N')
p = []
n = len(df)
for row in df.index[::-1]:
if 'n' in df:
n = df.loc[row, 'n']
else:
n -= 1
p.insert(0, row)
xyzwt = [_ for _ in 'xyzwt' if _ in df]
if n == 0:
rows = df.take(p)
shpw.polyz([rows[xyzwt].values.tolist()])
shpw.record(*[pd.np.nan_to_num(df.iloc[row, c]) for c in range(5, df.shape[1])])
p.clear()
shpw.close()
def shape_field_list(file_path):
import shapefile
shapes = shapefile.Reader(file_path)
return [shapes.fields[i][0] for i in range(1, len(shapes.fields))]
# Leapfrog Mesh
def pd_load_mesh(df_path):
import struct
file = open(df_path, "rb")
index = None
binary = None
while True:
if binary is None:
line = file.readline()
if line.startswith(b'[index]'):
index = line[7:]
elif line.startswith(b'[binary]'):
binary = line[8:]
elif index is not None:
index += line
else:
line = file.read(0xff)
binary += line
if len(line) < 0xff:
break
if len(line) == 0:
break
face_type, face_wide, face_size = re.findall(r'Tri (\w+) (\d+) (\d+)', str(index))[0]
node_type, node_wide, node_size = re.findall(r'Location (\w+) (\d+) (\d+)', str(index))[0]
face_wide = int(face_wide)
face_size = int(face_size)
node_wide = int(node_wide)
node_size = int(node_size)
node_pack = struct.Struct('d' * node_wide)
face_pack = struct.Struct('i' * face_wide)
# skip unknown 12 byte header
# maybe on some cases it contains rgb color?
print("%02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x = %.2f %.2f %.2f" % tuple(struct.unpack_from('12B', binary, 0) + struct.unpack_from('3f', binary, 0)))
p = 12
node_list = list()
face_list = list()
for i in range(face_size):
face_list.append(face_pack.unpack_from(binary, p))
p += face_pack.size
for i in range(node_size):
node_list.append(node_pack.unpack_from(binary, p))
p += node_pack.size
return pd.DataFrame([node_list[int(f[n])] + (0,bool(n),n,1,f[n]) for f in face_list for n in range(3)], columns=smartfilelist.default_columns + ['closed','node'])
def pd_save_mesh(df, df_path):
import struct
node_pack = struct.Struct('3d')
face_pack = struct.Struct('3i')
file = open(df_path, "wb")
nodes, faces = df_to_nodes_faces(df)
file.write(b'%%ARANZ-1.0\n\n[index]\nTri Integer 3 %d;\nLocation Double 3 %d;\n\n[binary]' % (len(faces), len(nodes)))
# write unknown header
file.write(struct.pack('3i', 15732735, 1115938331, 1072939210))
for f in faces:
file.write(face_pack.pack(*f))
for n in nodes:
file.write(node_pack.pack(*n))
file.close()
# images and other binary databases
def pd_load_spectral(df_path):
import skimage.io
df = skimage.io.imread(df_path)
channels = 1
if df.ndim >= 3:
channels = df.shape[2]
dfi = np.indices(df.shape[:2]).transpose(1,2,0).reshape((np.prod(df.shape[:2]),2))
dfx = df.reshape((np.prod(df.shape[:2]), channels))
return pd.DataFrame(np.concatenate([dfi, dfx], 1), columns=['x','y'] + list(range(channels)))
def pd_save_spectral(df, df_path):
import skimage.io
# original image width and height are recoverable from the max x and max y
wh = np.max(df, 0)
dfx = df.drop(df.columns[:2], 1)
im_out = np.reshape(dfx.values, (wh.values[0] + 1, wh.values[1] + 1, wh.size - 2))
skimage.io.imsave(df_path, im_out)
class smartfilelist(object):
'''
detects file type and return a list of relevant options
searches are cached, so subsequent searcher for the same file path are instant
'''
default_columns = ['x','y','z','w','t','n']
# global value cache, using path as key
_cache = [{},{}]
@staticmethod
def get(df_path, s = 0):
# special case for multiple files. use first
if isinstance(df_path, commalist):
if len(df_path):
df_path = df_path[0][0]
else:
df_path = ""
r = []
# if this file is already cached, skip to the end
if(df_path in smartfilelist._cache[s]):
r = smartfilelist._cache[s][df_path]
else:
df_path, table_name = table_name_selector(df_path)
if os.path.exists(df_path):
input_ext = os.path.splitext(df_path.lower())[1]
if df_path.lower().endswith(".dgd.isis"):
if s == 1:
r = dgd_list_layers(df_path)
else:
r = smartfilelist.default_columns + ['p','closed','layer','oid','name','group','feature','description','value','colour']
elif input_ext == ".isis":
r = isisdb_list(df_path, s)
elif input_ext == ".bmf":
r = bmf_field_list(df_path)
elif input_ext == ".00t" and s == 0:
r = smartfilelist.default_columns + ['closed','node','rgb','colour']
elif input_ext == ".msh" and s == 0:
r = smartfilelist.default_columns + ['closed','node']
elif input_ext == ".csv" and s == 0:
r = csv_field_list(df_path)
elif re.search(r'xls\w?$', df_path, re.IGNORECASE):
r = excel_field_list(df_path, table_name, s)
elif input_ext == ".dm" and s == 0:
r = dm_field_list(df_path)
elif input_ext == ".shp" and s == 0:
r = shape_field_list(df_path)
elif input_ext == ".dxf" and s == 0:
r = smartfilelist.default_columns + ['layer']
elif input_ext == ".zip" and s == 0:
from zipfile import ZipFile
r = ZipFile(df_path).namelist()
elif re.search(r'tiff?$', df_path, re.IGNORECASE):
r = list('xy0123456789')
smartfilelist._cache[s][df_path] = r
return r
class UsageToken(str):
'''handles the token format used to creating controls'''
_name = None
_type = None
_data = None
def __init__(self, arg):
super().__init__()
m = re.match(r"(\w*)(\*|@|#|=|:|%|~|!)(.*)", arg)
if (m):
self._name = m.group(1)
self._type = m.group(2)
self._data = m.group(3)
else:
self._name = arg
@property
def name(self):
return self._name
@property
def type(self):
return self._type
@property
def data(self):
return self._data
class ScriptFrame(ttk.Frame):
'''frame that holds the script argument controls'''
_tokens = None
def __init__(self, master, usage = None):
ttk.Frame.__init__(self, master)
self._tokens = [UsageToken(_) for _ in ClientScript.args(usage)]
# for each token, create a child control of the apropriated type
for token in self._tokens:
c = None
if token.type == '@':
c = CheckBox(self, token.name, int(token.data) if token.data else 0)
elif token.type == '*':
c = FileEntry(self, token.name, token.data)
elif token.type == '=':
c = LabelCombo(self, token.name, token.data)
elif token.type == '#':
c = tkTable(self, token.name, token.data.split('#'))
elif token.type == '%':
c = LabelRadio(self, token.name, token.data)
elif token.type == '!':
c = ComboPicker(self, token.name, token.data, True)
elif token.type == ':':
if token.data == 'portal':
import gisportal
c = gisportal.ArcGisField(self, token.name, token.data)
else:
c = ComboPicker(self, token.name, token.data)
elif token.type == '~':
import gisportal
c = gisportal.ArcGisPortal(self, token.name, None, token.data)
elif token.name: