-
Notifications
You must be signed in to change notification settings - Fork 6
/
amrwind_frontend.py
executable file
·2526 lines (2256 loc) · 107 KB
/
amrwind_frontend.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
#!/usr/bin/env python
#
# Copyright (c) 2022, Alliance for Sustainable Energy
#
# This software is released under the BSD 3-clause license. See LICENSE file
# for more details.
#
import sys, os, re, shutil
# import the tkyamlgui library
scriptpath=os.path.dirname(os.path.realpath(__file__))
sys.path.insert(1, scriptpath+'/tkyamlgui')
sys.path.insert(1, scriptpath+'/utilities')
sys.path.insert(1, scriptpath)
import numpy as np
from functools import partial
import tkyamlgui as tkyg
import postproamrwindabl as postpro
import postproamrwindsample as ppsample
import convert_abl_stats as MMC_abl_stats
if sys.version_info[0] < 3:
import Tkinter as Tk
import tkFileDialog as filedialog
else:
import tkinter as Tk
from tkinter import filedialog as filedialog
import traceback
# Try the loading the Xvfb package
import platform
hasxvfb=False
if platform.system()=='Linux':
try:
from xvfbwrapper import Xvfb
hasxvfb=True
except:
hasxvfb=False
import numpy as np
from collections import OrderedDict
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import argparse
import subprocess
import signal
import copy
import linecache
# amrwind-frontend libraries
import validateinputs
import OpenFASTutil as OpenFAST
#from plotfunctions import readCartBoxFile, plotRectangle, plot3DBox, rotatepoint, plotTurbine
# -------------------------------------------------------------
class MyApp(tkyg.App, object):
def __init__(self, *args, **kwargs):
self.abl_stats = None
self.sample_ncdat = None
super(MyApp, self).__init__(*args, **kwargs)
self.fig.clf()
self.fig.text(0.35,0.5,'Welcome to\nAMR-Wind')
self.formatgridrows()
self.extradictparams = OrderedDict()
self.abl_profiledata = {}
self.savefile = ''
# for fast output plotting
self.fast_outdata = None
self.fast_outfiles = None
self.fast_headers = None
self.fast_units = None
# variables for local run
self.localrun_process= None
# build the map going from AMR-Wind var --> amrwind_frontend var
self.amrkeydict = OrderedDict()
for key, var in self.inputvars.items():
outputkey = 'AMR-Wind'
if outputkey in var.outputdef:
self.amrkeydict[var.outputdef[outputkey]] = key
# Load any turbines
self.turbinemodels_populate()
# Define alias functions for get_default_* dicts
self.get_default_samplingdict = \
self.listboxpopupwindict['listboxsampling'].getdefaultdict
self.get_default_averagingdict = \
self.listboxpopupwindict['listboxaveraging'].getdefaultdict
self.get_default_taggingdict = \
self.listboxpopupwindict['listboxtagging'].getdefaultdict
self.get_default_turbinetypedict = \
self.listboxpopupwindict['listboxturbinetype'].getdefaultdict
self.get_default_actuatordict = \
self.listboxpopupwindict['listboxactuator'].getdefaultdict
self.get_default_postprosetupdict = \
self.listboxpopupwindict['listboxpostprosetup'].getdefaultdict
# Shorthand aliases to add things
self.add_turbine = partial(self.add_populatefromdict,'listboxactuator')
self.add_sampling = partial(self.add_populatefromdict,'listboxsampling')
self.add_averaging = partial(self.add_populatefromdict,
'listboxaveraging')
self.add_tagging = partial(self.add_populatefromdict,'listboxtagging')
self.add_postprosetup = partial(self.add_populatefromdict,
'listboxpostprosetup')
# Shorthand aliases to edit things
self.edit_turbine = partial(self.edit_entryval, 'listboxactuator')
self.edit_sampling = partial(self.edit_entryval, 'listboxsampling')
self.edit_tagging = partial(self.edit_entryval, 'listboxtagging')
# Shorthand aliases to load CSV files
from farmfunctions import loadcsv2textbox
self.loadTurbineCSVFile = partial(loadcsv2textbox, self,
'turbines_csvtextbox')
self.loadRefineCSVFile = partial(loadcsv2textbox, self,
'refine_csvtextbox')
self.report_callback_exception = self.showerror
return
def showerror(self, *args):
err = traceback.format_exception(*args)
# Used to define alias for populatefromdict()
def add_populatefromdict(self, key, d, **kwargs):
deleteprevious = False
if 'deleteprevious' in kwargs:
deleteprevious = kwargs['deleteprevious']
del kwargs['deleteprevious']
self.listboxpopupwindict[key].populatefromdict({'x':d},
deleteprevious=deleteprevious,
**kwargs)
return
# Used to define alias for populatefromdict()
def edit_entryval(self, listboxkey, entry, key, val):
self.listboxpopupwindict[listboxkey].setentryval(entry, key, val,
outputtag='AMR-Wind')
return
@classmethod
def init_nogui(cls, *args, **kwargs):
localconfigdir=os.path.join(scriptpath,'local')
if 'localconfigdir' in kwargs:
localconfigdir=kwargs['localconfigdir']
del kwargs['localconfigdir']
cls.vdisplay = None
if hasxvfb:
try:
cls.vdisplay = Xvfb()
cls.vdisplay.start()
except:
pass
return cls(configyaml=os.path.join(scriptpath,'config.yaml'),
localconfigdir=localconfigdir, scriptpath=scriptpath,
withdraw=True, **kwargs)
def reloadconfig(self):
with open('config.yaml') as fp:
if tkyg.useruemel: Loader=tkyg.yaml.load
else: Loader=tkyg.yaml.safe_load
self.yamldict = Loader(fp)
#print('Reloaded config')
for listboxdict in self.yamldict['listboxpopupwindows']:
frame = self.tabframeselector(listboxdict)
name = listboxdict['name']
popupdict = self.yamldict['popupwindow'][listboxdict['popupinput']]
self.listboxpopupwindict[name] = tkyg.listboxpopupwindows(self, frame, listboxdict, popupdict)
return
@classmethod
def ifbool(cls, x):
if not isinstance(x, bool): return x
return 'true' if x else 'false'
def tellMeAbout(self, name):
"""
Query an AMR-Wind input or AMR-Wind frontend input
"""
inputkey = None
if name in self.amrkeydict:
inputkey = self.amrkeydict[name]
if name in self.inputvars:
inputkey = name
# Check if it can't find anything
if inputkey is None:
print("Unknown input "+name)
return
# Set inputs
inputvar = self.inputvars[inputkey]
infodict = OrderedDict()
infodict['Internal name'] = inputvar.name
infodict['AMR-Wind name'] = str(None) if 'AMR-Wind' not in inputvar.outputdef else inputvar.outputdef['AMR-Wind']
infodict['Help'] = str(None) if 'help' not in inputvar.outputdef else inputvar.outputdef['help']
infodict['Variable type'] = str(inputvar.inputtype)
infodict['GUI Label'] = inputvar.label
infodict['Default value'] = str(inputvar.defaultval)
infodict['Option list'] = str(inputvar.optionlist) if inputvar.optionlist else None
for k, g in infodict.items(): print('%-20s: %s'%(k,g))
return
def setAMRWindInput(self, name, val, updatectrlelem=True, **kwargs):
"""
Use this function to set the AMR-Wind keyword name to value.
"""
try:
if name in self.amrkeydict:
inputkey = self.amrkeydict[name]
if name in self.inputvars:
inputkey = name
self.inputvars[inputkey].setval(val, **kwargs)
if updatectrlelem and (self.inputvars[inputkey].ctrlelem is not None):
self.inputvars[inputkey].linkctrlelem(self.subframes,
self.inputvars)
self.inputvars[inputkey].onoffctrlelem(None)
except:
print("Cannot set "+name)
return
def getAMRWindInput(self, name, **kwargs):
"""
Use this function to get the value of an AMR-Wind keyword.
"""
returnval = None
try:
if name in self.amrkeydict:
inputkey = self.amrkeydict[name]
if name in self.inputvars:
inputkey = name
returnval = self.inputvars[inputkey].getval(**kwargs)
except:
print("Cannot get value of "+name)
return returnval
def getAMRWindInputType(self, name):
"""
Use this function to get the input type of an AMR-Wind keyword.
"""
returnval = None
try:
if name in self.amrkeydict:
inputkey = self.amrkeydict[name]
if name in self.inputvars:
inputkey = name
returnval = self.inputvars[inputkey].inputtype
except:
print("Cannot get inputtype of "+name)
return returnval
def getTaggingKey(self, keyname, listboxdict, datadict):
keyheader = 'tagging.'
intername = ''
#getinputtype = lambda l,n: [x['inputtype'] for x in l if x['name']==n]
if datadict.name.startswith('tagging_geom'):
#print(keyname+datadict.outputdef['AMR-Wind']+" needs fixing!")
keynamedict = self.listboxpopupwindict['listboxtagging'].dumpdict('AMR-Wind', subset=[keyname])
if keyname+".shapes" in keynamedict:
intername=keynamedict[keyname+".shapes"].strip()+"."
#print(listboxdict)
return keyheader+keyname+"."+intername+datadict.outputdef['AMR-Wind']
def writeAMRWindInput(self, filename, verbose=False,
postloadctrlelem=True,
outputextraparams=True, comments=True,amr_wind_version='latest'):
"""
Write out the input file for AMR-Wind
TODO: Do more sophisticated output control later
"""
if postloadctrlelem: self.postLoad_SetOnOffCtrlElem()
inputdict = self.getDictFromInputs('AMR-Wind')
# Get the sampling outputs
def dynamickeyfunc(n, p, d2):
prefix = p['sampling_outputto'].getval()[0]
return prefix+'.'+n+'.'+d2.outputdef['AMR-Wind']
def dynamickeyfuncavg(n, p, d2):
prefix = p['averaging_outputto'].getval()[0]
return prefix+'.'+n+'.'+d2.outputdef['AMR-Wind']
samplingkey = lambda n, d1, d2: d1['outputprefix']['AMR-Wind']+'.'+n+'.'+d2.outputdef['AMR-Wind']
if verbose: print('dumping listboxsampling')
sampledict = self.listboxpopupwindict['listboxsampling'].dumpdict('AMR-Wind', dynamicprefix_keyfunc=dynamickeyfunc)
if verbose: print('dumping listboxaveraging')
averagingict = self.listboxpopupwindict['listboxaveraging'].dumpdict('AMR-Wind', dynamicprefix_keyfunc=dynamickeyfuncavg)
if verbose: print('dumping listboxtagging')
taggingdict = self.listboxpopupwindict['listboxtagging'].dumpdict('AMR-Wind', keyfunc=self.getTaggingKey)
if verbose: print('dumping listboxactuator')
actuatordict= self.listboxpopupwindict['listboxactuator'].dumpdict('AMR-Wind', keyfunc=samplingkey)
if verbose: print('dumping listboxpostprosetup')
def postprocessingkey(n, d1, d2):
if ('outputprefix' in d2.outputdef):
return n+'.'+d2.outputdef['AMR-Wind']
else:
return d1['outputprefix']['AMR-Wind']+'.'+n+'.'+d2.outputdef['AMR-Wind']
postprocessingdict= self.listboxpopupwindict['listboxpostprosetup'].dumpdict('AMR-Wind', keyfunc=postprocessingkey)
"""
AMR_WIND version specific modification to dicts
"""
def remove_entries(data_dict, str_to_remove, how='in'):
if how=='in':
keys_to_remove = [key for key in data_dict if str_to_remove in key]
elif how=='endswith':
keys_to_remove = [key for key in data_dict if key.endswith(str_to_remove)]
# Remove the keys from the dictionary
for key in keys_to_remove:
del data_dict[key]
if amr_wind_version == 'latest':
remove_entries(sampledict,'.normal',how='endswith')
elif amr_wind_version == 'legacy':
remove_entries(sampledict,'.offset_vector',how='endswith')
# Construct the output dict
outputdict=inputdict.copy()
if len(taggingdict)>0:
commentdict = {'#comment_taggingdict':'\n#---- tagging defs ----'}
if comments: outputdict.update(commentdict)
outputdict.update(taggingdict)
if len(actuatordict)>0:
commentdict = {'#comment_actuatordict':'\n#---- actuator defs ----'}
if comments: outputdict.update(commentdict)
outputdict.update(actuatordict)
if len(postprocessingdict)>0:
commentdict = {'#comment_postprocessingdict':'\n#---- postprocessing defs ----'}
if comments: outputdict.update(commentdict)
outputdict.update(postprocessingdict)
if len(averagingict)>0:
commentdict = {'#comment_averagingdict':'\n#---- averaging defs ----'}
if comments: outputdict.update(commentdict)
outputdict.update(averagingict)
if len(sampledict)>0:
commentdict = {'#comment_sampledict':'\n#---- sample defs ----'}
if comments: outputdict.update(commentdict)
outputdict.update(sampledict)
# Add any extra parameters
if outputextraparams:
commentdict = {'#comment_extradict':'\n#---- extra params ----'}
if comments: outputdict.update(commentdict)
outputdict.update(self.extradictparams)
# Add the end comment
if comments:
outputdict.update({'#comment_end':'#== END AMR-WIND INPUT =='})
# Get the help dict
helpdict = self.getHelpFromInputs('AMR-Wind', 'help')
# Convert the dictionary to string output
returnstr = ''
if len(filename)>0: f=open(filename, "w")
for key, val in outputdict.items():
outputkey = key
# Write out a comment
if (key[0] == '#') and comments:
try:
writestr = bytes(val, "utf-8").decode("unicode_escape")
except:
writestr = val.decode('string_escape')
if verbose: print(writestr)
if len(filename)>0: f.write(writestr+"\n")
returnstr += writestr+"\n"
continue
elif (key[0] == '#'):
continue
# convert val to string
if val is None:
continue
elif isinstance(val, list):
outputstr=' '.join([str(self.ifbool(x)) for x in val])
else:
outputstr=str(self.ifbool(val))
if len(outputstr)>0 and (outputstr != 'None'):
writestr = "%-40s = %-20s"%(outputkey, outputstr)
# Add any help to this
if comments and (outputkey in helpdict):
writestr += "# "+helpdict[outputkey]
if verbose: print(writestr)
if len(filename)>0: f.write(writestr+"\n")
returnstr += writestr+"\n"
if len(filename)>0:
f.close()
self.savefile = filename
return returnstr
def writeAMRWindInputGUI(self):
filename = filedialog.asksaveasfilename(initialdir = "./",
title = "Save AMR-Wind file",
filetypes=[("input files","*.inp"),
("all files","*.*")])
if len(filename)>0:
self.writeAMRWindInput(filename)
self.savefile = filename
return
def saveAMRWindInputGUI(self):
if len(self.savefile)>0:
self.writeAMRWindInput(self.savefile)
print("Saved "+self.savefile)
else:
self.writeAMRWindInputGUI()
return
def dumpAMRWindInputGUI(self):
return tkyg.messagewindow(self, self.writeAMRWindInput(''),
height=40, title='Preview Input File')
def showyamlmesg(self, helpkey, category='helpwindows'):
"""
Displays a help message in yamldict[category][helpkey]
"""
mesg = self.yamldict[category][helpkey]['mesg']
opts = tkyg.getdictval(self.yamldict['helpwindows'][helpkey],
'options', {})
return tkyg.messagewindow(self, mesg, **opts)
def getInputHelp(self, search=''):
# Print the header
print("%-40s %-40s %-10s %s"%("INTERNAL NAME", "AMRWIND PARAMETER",
"DEFAULT VAL", "/ DESCRIPTION"))
# Print each widget
for widget in self.yamldict['inputwidgets']:
appname = widget['name']
amrname = ''
default = '' if 'defaultval' not in widget else repr(widget['defaultval'])
helpstr = '' if 'help' not in widget else repr(widget['help'])
if 'outputdef' in widget:
if 'AMR-Wind' in widget['outputdef']:
amrname = widget['outputdef']['AMR-Wind']
# Combine and search if necessary
allstrings = appname+' '+default+' '+helpstr+' '+amrname
hassearchterm = False
if ((len(search)==0) or (search.upper() in allstrings.upper())):
hassearchterm = True
#printentry = True if len(search)==0 else False
if hassearchterm:
print("%-40s %-40s %-10s %s"%(appname, amrname, default, helpstr))
return
@classmethod
def processline(cls, inputline):
line = inputline.partition('#')[0]
line = line.rstrip()
if len(line)>0:
line = line.split('=')
key = line[0].strip()
data = line[1].strip()
return key, data
return None, None
@classmethod
def AMRWindStringToDict(cls, string):
returndict = OrderedDict()
for line in string.split('\n'):
key, data = cls.processline(line)
if key is not None: returndict[key] = data
return returndict
@classmethod
def AMRWindInputToDict(cls, filename):
returndict = OrderedDict()
with open(filename) as f:
for line in f:
key, data = cls.processline(line)
if key is not None: returndict[key] = data
return returndict
def AMRWindExtractPostproDict(self, inputdict, template, samplingtemplate,
averagingtemplate, sep="."):
"""
From input dict, extract all of the sampling probe parameters
"""
postprodict = OrderedDict()
extradict = inputdict.copy()
# Get all incflo.postprocessing options
postprokey = 'incflo.post_processing'
# Check and make sure incflo.post_processing exists in the
# inputs, else skip
if postprokey not in inputdict:
return postprodict, extradict
postpronames = inputdict[postprokey].strip().split()
extradict.pop(postprokey)
# Run through all of the postprocessing objects
internalprefix = 'postprocessing_setup_'
allkeys = [key for key, item in inputdict.items()]
getinputtype = lambda l,n: [x['inputtype'] for x in l if x['name']==n]
matchlisttype = lambda x, l: x.split() if (isinstance(l, list) or l=='listbox') else x
for name in postpronames:
objectdict=OrderedDict()
objectdict[internalprefix+'name'] = name
# Process all keys for name
prefix = name+sep
probekeys = [k for k in allkeys if k.startswith(prefix) ]
for inputkey in probekeys:
inputkeytokens = inputkey.split(sep)
# Only take input parameters like sampling.type right now
if len(inputkeytokens)==2:
internalkey = internalprefix + inputkeytokens[-1]
inputtype=getinputtype(template['inputwidgets'],
internalkey)
if len(inputtype)>0:
inputtype = inputtype[0]
data = matchlisttype(inputdict[inputkey], inputtype)
objectdict[internalkey] = data
extradict.pop(inputkey)
postprodict[name] = objectdict.copy()
# load the postprodict if necessary
if len(postprodict)>0:
#print(postprodict)
self.listboxpopupwindict['listboxpostprosetup'].populatefromdict(postprodict, forcechange=True)
averagingobjects = []
# load all of the sampling inputs
if len(postprodict)>0:
samplingdict = OrderedDict()
dictkeypre= 'sampling_'
# Create the markers for probe/plane/line sampler
lmap = {}
lmap['probesampler'] = 'pf_'
lmap['linesampler'] = 'l_'
lmap['planesampler'] = 'p_'
lmap['lidarsampler'] = 'lidar_'
lmap['radarsampler'] = 'radar_'
for pname in postpronames:
# Double check and make sure it's a sampler input
listboxpopup = self.listboxpopupwindict['listboxpostprosetup']
pdict = listboxpopup.dumpdict('AMR-Wind',
subset=[pname],
keyfunc=lambda n, d1, d2: d2.name)
if pdict['postprocessing_setup_type'] != ['Sampling']:
averagingobjects.append(pname)
# Quit if it's not a Sampling type
continue
# Process the sampling
pre = pname
if pre+'.labels' not in inputdict:
# TODO: print warning here
continue
samplingnames = inputdict[pre+'.labels'].strip().split()
extradict.pop(pre+'.labels')
# Construct the sampling dict
for name in samplingnames:
probedict= OrderedDict()
# Process all keys for name
prefix = pre+sep+name+sep
probekeys = [k for k in allkeys if k.startswith(prefix) ]
# First process the type
probetype = tkyg.getdictval(inputdict, prefix+'type', None)
l = lmap[probetype.lower()]
if probetype is None:
print("ERROR: %s is not found!"%prefix+'type')
continue
probedict[dictkeypre+'name'] = name
probedict[dictkeypre+'outputto'] = pname
probedict[dictkeypre+'type'] = probetype
# Remove them from the list & dict
probekeys.remove(prefix+'type')
extradict.pop(prefix+'type')
# Go through the rest of the keys
for key in probekeys:
suffix = key[len(prefix):]
probedictkey = dictkeypre+l+suffix
# Check what kind of data it's supposed to provide
inputtype=getinputtype(samplingtemplate['inputwidgets'],
probedictkey)[0]
data = matchlisttype(inputdict[key], inputtype)
probedict[probedictkey] = data
extradict.pop(key)
samplingdict[name] = probedict.copy()
# Now populate it with the samplingdict
if len(samplingdict)>0:
#print(samplingdict)
self.listboxpopupwindict['listboxsampling'].populatefromdict(samplingdict, forcechange=True)
# load all of the averaging inputs
if len(averagingobjects)>0:
averagingdict = OrderedDict()
dictkeypre= 'averaging_'
for pname in averagingobjects:
# Double check and make sure it's an averaging input
listboxpopup = self.listboxpopupwindict['listboxpostprosetup']
pdict = listboxpopup.dumpdict('AMR-Wind',
subset=[pname],
keyfunc=lambda n, d1, d2: d2.name)
if pdict['postprocessing_setup_type'] != ['TimeAveraging']:
# Quit if it's not TimeAveraging type
continue
# Process the sampling
pre = pname
if pre+'.labels' not in inputdict:
# TODO: print warning here
continue
averagingnames = inputdict[pre+'.labels'].strip().split()
extradict.pop(pre+'.labels')
# Construct the averaging dict
for name in averagingnames:
objectdict= OrderedDict()
# Process all keys for name
prefix = pre+sep+name+sep
probekeys = [k for k in allkeys if k.startswith(prefix) ]
# First process the type
probetype = tkyg.getdictval(inputdict,
prefix+'averaging_type', None)
if probetype is None:
print("ERROR: %s is not found!"%prefix+'averaging_type')
continue
objectdict[dictkeypre+'name'] = name
objectdict[dictkeypre+'outputto'] = pname
objectdict[dictkeypre+'averaging_type'] = probetype
# Remove them from the list & dict
probekeys.remove(prefix+'averaging_type')
extradict.pop(prefix+'averaging_type')
# Go through the rest of the keys
for key in probekeys:
suffix = key[len(prefix):]
probedictkey = dictkeypre+suffix
# Check what kind of data it's supposed to provide
inputtype=getinputtype(averagingtemplate['inputwidgets'],
probedictkey)[0]
data = matchlisttype(inputdict[key], inputtype)
objectdict[probedictkey] = data
extradict.pop(key)
averagingdict[name] = objectdict.copy()
# Now populate it with the averagingdict
if len(averagingdict)>0:
self.listboxpopupwindict['listboxaveraging'].populatefromdict(averagingdict, forcechange=True)
return postprodict, extradict
# **** THIS IS DEPRECATED, REMOVE LATER *****
@classmethod
def AMRWindExtractSampleDict(cls, inputdict, template, sep=[".","."]):
"""
From input dict, extract all of the sampling probe parameters
"""
pre='sampling'
dictkeypre= 'sampling_'
samplingdict = OrderedDict()
if pre+'.labels' not in inputdict: return samplingdict, inputdict
extradict = inputdict.copy()
# Create the markers for probe/plane/line sampler
lmap = {}
lmap['probesampler'] = 'pf_'
lmap['linesampler'] = 'l_'
lmap['planesampler'] = 'p_'
# Get the sampling labels
allkeys = [key for key, item in inputdict.items()]
samplingkeys = [key for key in allkeys if key.lower().startswith(pre)]
samplingnames = inputdict[pre+'.labels'].strip().split()
extradict.pop(pre+'.labels')
getinputtype = lambda l,n: [x['inputtype'] for x in l if x['name']==n]
matchlisttype = lambda x, l: x.split() if isinstance(l, list) else x
#print(getinputtype(template['inputwidgets'], 'sampling_p_offsets')[0])
for name in samplingnames:
probedict=OrderedDict()
# Process all keys for name
prefix = pre+sep[0]+name+sep[1]
probekeys = [k for k in samplingkeys if k.startswith(prefix) ]
# First process the type
probetype = tkyg.getdictval(inputdict, prefix+'type', None)
l = lmap[probetype.lower()]
if probetype is None:
print("ERROR: %s is not found!"%prefix+'type')
continue
probedict[dictkeypre+'name'] = name
probedict[dictkeypre+'type'] = probetype
# Remove them from the list & dict
probekeys.remove(prefix+'type')
extradict.pop(prefix+'type')
# Go through the rest of the keys
for key in probekeys:
suffix = key[len(prefix):]
probedictkey = dictkeypre+l+suffix
# Check what kind of data it's supposed to provide
inputtype=getinputtype(template['inputwidgets'], probedictkey)[0]
data = matchlisttype(inputdict[key], inputtype)
probedict[probedictkey] = data
extradict.pop(key)
samplingdict[name] = probedict.copy()
#print(samplingdict)
return samplingdict, extradict
@classmethod
def AMRWindExtractTaggingDict(cls, inputdict, template, sep=['.','.','.']):
"""
From input dict, extract all of the tagging parameters
"""
pre='tagging'
dictkeypre= 'tagging_'
taggingdict = OrderedDict()
if pre+'.labels' not in inputdict: return taggingdict, inputdict
extradict = inputdict.copy()
# Get the tagging labels
allkeys = [key for key, item in inputdict.items()]
taggingkeys = [key for key in allkeys if key.lower().startswith(pre)]
taggingnames = inputdict[pre+'.labels'].strip().split()
extradict.pop(pre+'.labels')
# This lambda returns the inputtype corresponding to entry in
# dictionary l with name n
getinputtype = lambda l,n: [x['inputtype'] for x in l if x['name']==n]
matchlisttype = lambda x, l: x.split() if isinstance(l, list) else x
for name in taggingnames:
itemdict = OrderedDict()
# Process all keys for name
prefix = pre+sep[0]+name+sep[1]
tagkeys = [k for k in taggingkeys if k.startswith(prefix) ]
# First process the type
tagtype = tkyg.getdictval(inputdict, prefix+'type', None)
if tagtype is None:
print("ERROR: %s is not found!"%prefix+'type')
continue
itemdict[dictkeypre+'name'] = name
itemdict[dictkeypre+'type'] = tagtype
#print("Found tagging: %s"%name)
#print(" type: %s"%tagtype)
# Remove them from the list & dict
tagkeys.remove(prefix+'type')
extradict.pop(prefix+'type')
readtaggingkeys = True
taginsert = ''
if tagtype=='GeometryRefinement':
# Get the level
suffix = 'level'
tagdictkey= dictkeypre+suffix
key = prefix+suffix
if key in inputdict:
leveldata = int(inputdict[key])
itemdict[tagdictkey] = leveldata
extradict.pop(key)
# Get the shapes
suffix = 'shapes'
tagdictkey = dictkeypre+suffix
key = prefix+suffix
shapedata = inputdict[key]
#print("shapedata = %s"%shapedata)
extradict.pop(key)
itemdict[tagdictkey] = shapedata
if (len(shapedata.strip().split())>1):
print(" ERROR: More than one geometric refinement shape ")
print(" ERROR: Can't handle that at the moment")
readtaggingkeys = False
else:
prefix = pre+sep[0]+name+sep[1]+shapedata.strip()+sep[2]
tagkeys = [k for k in taggingkeys if k.startswith(prefix) ]
taginsert = 'geom_'
if not readtaggingkeys: continue
#print(taggingkeys)
#print(tagkeys)
# Go through the rest of the keys
for key in tagkeys:
suffix = key[len(prefix):]
tagdictkey = dictkeypre+taginsert+suffix
#print(tagdictkey)
# Check what kind of data it's supposed to provide
inputtype=getinputtype(template['inputwidgets'], tagdictkey)[0]
data = matchlisttype(inputdict[key], inputtype)
itemdict[tagdictkey] = data
extradict.pop(key)
taggingdict[name] = itemdict.copy()
return taggingdict, extradict
def AMRWindExtractActuatorDict(self, inputdict, template, sep=['.','.','.']):
"""
From input dict, extract all of the sampling probe parameters
"""
pre='Actuator'
dictkeypre= 'Actuator_'
actuatordict = OrderedDict()
if pre+'.labels' not in inputdict: return actuatordict, inputdict
extradict = inputdict.copy()
# Get the Actuator labels
allkeys = [key for key, item in inputdict.items()]
actuatorkeys = [key for key in allkeys if key.lower().startswith(pre.lower())]
actuatornames = inputdict[pre+'.labels'].strip().split()
extradict.pop(pre+'.labels')
#print(actuatorkeys)
getinputtype = lambda l,n: [x['inputtype'] for x in l if x['name']==n]
matchlisttype = lambda x, l: x.split() if isinstance(l, list) else x
#print(getinputtype(template['inputwidgets'], 'sampling_p_offsets')[0])
for name in actuatornames:
probedict=OrderedDict()
# Process all keys for name
prefix = pre+sep[0]+name+sep[1]
probekeys = [k for k in actuatorkeys if k.startswith(prefix) ]
# First process the type
probetype = tkyg.getdictval(inputdict, prefix+'type', None)
l = '' #lmap[probetype.lower()]
if probetype is None:
probetype = self.inputvars['Actuator_default_type'].getval()
probetype = str(probetype[0])
else:
probekeys.remove(prefix+'type')
extradict.pop(prefix+'type')
probedict[dictkeypre+'name'] = name
probedict[dictkeypre+'type'] = probetype
# Remove them from the list & dict
# Go through the rest of the keys
for key in probekeys:
suffix = key[len(prefix):]
probedictkey = dictkeypre+l+suffix
#print(probedictkey)
# Check what kind of data it's supposed to provide
inputtype=getinputtype(template['inputwidgets'], probedictkey)[0]
data = matchlisttype(inputdict[key], inputtype)
if inputtype=='bool': data = tkyg.to_bool(data)
probedict[probedictkey] = data
extradict.pop(key)
#print(probedict)
actuatordict[name] = probedict.copy()
#print(samplingdict)
return actuatordict, extradict
def setInternalVars(self):
"""
Set any internal variables necessary after loading AMR-Wind inputs
"""
# Set the time control variables
if self.inputvars['fixed_dt'].getval() > 0.0:
self.inputvars['time_control'].setval(['const dt'])
else:
self.inputvars['time_control'].setval(['max cfl'])
# Set the ABL boundary plane variables
if self.inputvars['ABL_bndry_io_mode'].getval() != "-1":
self.inputvars['ABL_useboundaryplane'].setval(True)
return
def postLoad_SetOnOffCtrlElem(self):
self.inputvars['zlo_temperature_type'].onoffctrlelem(None)
self.inputvars['zlo_type'].onoffctrlelem(None)
return
def loadAMRWindInput(self, filename, string=False, printunused=False):
if string:
amrdict=self.AMRWindStringToDict(filename)
else:
amrdict=self.AMRWindInputToDict(filename)
extradict=self.setinputfromdict('AMR-Wind', amrdict)
# Input the postpro objects
postprodict, extradict = \
self.AMRWindExtractPostproDict(extradict,
self.yamldict['popupwindow']['postpro_setup'],
self.yamldict['popupwindow']['sampling'],
self.yamldict['popupwindow']['averaging'],
)
# DEPRECATED
# # Input the sampling probes
# samplingdict, extradict = \
# self.AMRWindExtractSampleDict(extradict,
# self.yamldict['popupwindow']['sampling'])
# if len(samplingdict)>0:
# self.listboxpopupwindict['listboxsampling'].populatefromdict(samplingdict, forcechange=True)
# Input the tagging/refinement zones
taggingdict, extradict = \
self.AMRWindExtractTaggingDict(extradict,
self.yamldict['popupwindow']['tagging'])
if len(taggingdict)>0:
self.listboxpopupwindict['listboxtagging'].populatefromdict(taggingdict, forcechange=True)
# Input the turbine actuators
actuatordict, extradict = \
self.AMRWindExtractActuatorDict(extradict,
self.yamldict['popupwindow']['turbine'])
if len(actuatordict)>0:
self.listboxpopupwindict['listboxactuator'].populatefromdict(actuatordict, forcechange=True)
if printunused and len(extradict)>0:
print("# -- Unused variables: -- ")
for key, data in extradict.items():
print("%-40s= %s"%(key, data))
# Set the internal variables
self.setInternalVars()
# link any widgets necessary
for key, inputvar in self.inputvars.items():
if self.inputvars[key].ctrlelem is not None:
self.inputvars[key].onoffctrlelem(None)
self.postLoad_SetOnOffCtrlElem()
self.extradictparams = extradict
return extradict
def loadAMRWindInputGUI(self):
kwargs = {'filetypes':[("Input files","*.inp *.i"), ("all files","*.*")]}
filename = filedialog.askopenfilename(initialdir = "./",
title = "Select AMR-Wind file",
**kwargs)
if len(filename)>0:
self.loadAMRWindInput(filename, printunused=True)
self.savefile = filename
return
def donothing_button(self):
print("Does nothing")
return
def menubar(self, root):
"""
Adds a menu bar to root
See https://www.tutorialspoint.com/python/tk_menu.htm
"""
menubar = Tk.Menu(root)
# File menu
filemenu = Tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Save input file",
command=self.saveAMRWindInputGUI)
filemenu.add_command(label="Save input file As",
command=self.writeAMRWindInputGUI)
filemenu.add_command(label="Import AMR-Wind file",
command=self.loadAMRWindInputGUI)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
# Plot menu
plotmenu = Tk.Menu(menubar, tearoff=0)
plotmenu.add_command(label="Plot domain",
command=partial(self.launchpopupwin,
'plotdomain', savebutton=False))
plotmenu.add_command(label="FAST outputs",
command=partial(self.launchpopupwin,
'plotfastout', savebutton=False))
menubar.add_cascade(label="Plot", menu=plotmenu)
# run menu
runmenu = Tk.Menu(menubar, tearoff=0)
runmenu.add_command(label="Check Inputs",
command=self.validateGUI)
runmenu.add_command(label="Estimate mesh size",
command=self.estimateMeshSize)
runmenu.add_command(label="Preview Input File",
command=self.dumpAMRWindInputGUI)
runmenu.add_command(label="Local Run",
command=partial(self.launchpopupwin,
'localrun', savebutton=False))
runmenu.add_command(label="Job Submission",
command=partial(self.launchpopupwin,
'submitscript', savebutton=False))
menubar.add_cascade(label="Run", menu=runmenu)
# Help menu
help_text = """This is AMR-Wind!"""
helpmenu = Tk.Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index",
command=partial(tkyg.donothing, root))
helpmenu.add_command(label="About...",