-
Notifications
You must be signed in to change notification settings - Fork 6
/
farmfunctions.py
1815 lines (1590 loc) · 69.5 KB
/
farmfunctions.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.
#
"""
Wind farm functions
"""
import numpy as np
import pandas as pd
import sys, os, csv
import re
import shlex
from collections import OrderedDict
try:
from tkyamlgui import moretypes
except:
pass
# Load the right version of StringIO
if sys.version_info[0] < 3:
from StringIO import StringIO
import Tkinter as Tk
import tkFileDialog as filedialog
else:
from io import StringIO
import tkinter as Tk
from tkinter import filedialog as filedialog
from plotfunctions import plotRectangle
import OpenFASTutil as OpenFAST
# Load UTM library
try:
import utm
useutm = True
except:
useutm = False
# Load ruamel or pyyaml as needed
try:
import ruamel.yaml as YAML
yaml = YAML(typ='unsafe', pure=True)
#print("# Loaded ruamel.yaml")
useruamel=True
loaderkwargs = {'Loader':yaml.RoundTripLoader}
dumperkwargs = {'Dumper':yaml.RoundTripDumper, 'indent':4, 'default_flow_style':False} # 'block_seq_indent':2, 'line_break':0, 'explicit_start':True,
except:
import yaml as yaml
#print("# Loaded yaml")
useruamel=False
loaderkwargs = {}
dumperkwargs = {'default_flow_style':False }
if useruamel:
from ruamel.yaml.comments import CommentedMap
def comseq(d):
"""
Convert OrderedDict to CommentedMap
"""
if isinstance(d, OrderedDict):
cs = CommentedMap()
for k, v in d.items():
cs[k] = comseq(v)
return cs
return d
# Helper functions to get defaults from a dictionary
getdictval = lambda d, k, default: default[k] if k not in d else d[k]
def loadcsv(f, stringinput=False, reqheaders=None, optheaders=None,
**kwargs):
"""
Load the csv input, whether from string or filename
"""
# Get input f into a string
if stringinput:
s = f.lstrip()
else:
s = open(f, 'r').read().lstrip()
# Remove comments
cleanstr = re.sub(r'(?m)^ *#.*\n?', '', s)
# Check for header
firstline = cleanstr.splitlines()[0]
firstlinewords = [x.strip().lower() for x in firstline.split(',')]
if reqheaders is not None:
hasheader = all(elem in firstlinewords for elem in reqheaders)
else:
hasheader = False
## Check for header
#sniffer = csv.Sniffer()
#hasheader = sniffer.has_header(cleanstr)
#print("hasheader = %s"%repr(hasheader))
header = None
colheaders=reqheaders+optheaders
if hasheader:
header = 0
colheaders = None
# Convert string to io stream
finput = StringIO(cleanstr)
df = pd.read_csv(finput, header=header, names=colheaders, **kwargs)
# Double check headers to make sure it has the required headers
if hasheader:
# first rename the headers
renamemap = {}
for x in list(df.columns): renamemap[x] = str(x.strip().lower())
df.rename(columns=renamemap, inplace=True)
csvheaders=list(df.columns)
#csvheaders=[x.strip().lower() for x in list(df.columns)]
#print(csvheaders)
for header in reqheaders:
if header.lower() not in csvheaders:
print('ERROR: required data column %s not present in data'%(header))
return df
def dataframe2dict(df, reqheaders, optheaders, dictkeys=[]):
"""
Convert dataframe to a list of dictionaries
dictkeys are keys in optheaders which should be parsed as dictionaries
"""
listdict = []
for index, row in df.iterrows():
rowdict = OrderedDict()
for key in reqheaders:
rowdict[key] = row[key]
# Add the optional headers
for key in optheaders:
if key in list(df.columns):
rowdict[key] = parseoptions(row[key]) if key in dictkeys else row[key]
else:
rowdict[key] = None
listdict.append(rowdict)
return listdict
def parseoptions(optionstr):
"""
Splits an option string into a dictionary. optionstr should be of
the form "key1:val1 key2:val2"
"""
sanitizestr = optionstr if isinstance(optionstr, str) else str(optionstr)
allopts = shlex.split(sanitizestr.replace(';',','))
optdict = OrderedDict()
for opt in allopts:
optsplit = opt.split(':')
key = optsplit[0]
if len(optsplit)>1:
val = optsplit[1]
else:
val = None
optdict[key] = val
return optdict
def button_loadcsv(self, filenameinput, csvtextbox):
"""
Button to load a CSV file
"""
# Get the filename to load
csvfile = self.inputvars[filenameinput].getval()
# Check if file exists
if not os.path.isfile(csvfile):
print("ERROR: %s does not exist"%csvfile)
return
# Load the filename and display it in the text box
csvstr = open(csvfile, 'r').read().lstrip()
self.inputvars[csvtextbox].setval(csvstr)
return
def loadcsv2textbox(self, csvtextbox, csvfile):
"""
Loads CSV file to a textbox
"""
# Check if file exists
if not os.path.isfile(csvfile):
print("ERROR: %s does not exist"%csvfile)
return
# Load the filename and display it in the text box
csvstr = open(csvfile, 'r').read().lstrip()
self.inputvars[csvtextbox].setval(csvstr)
return
def resetFarmSetup(self):
"""
Resets all variables with 'farmsetup' in outputdef to their defaults
"""
for key, var in self.inputvars.items():
outputkey = 'farmsetup'
if outputkey in var.outputdef:
var.setdefault()
return
# ----------- Functions for refinement zones ---------------
def get_turbProp(self, tdict):
# Get the default type
default_type = self.inputvars['Actuator_default_type'].getval()
default_type = None if len(default_type)==0 else default_type
default_type = default_type[0] if isinstance(default_type, list) else default_type
turbtype = default_type if 'Actuator_type' not in tdict else tdict['Actuator_type']
turbtype = turbtype[0] if isinstance(turbtype, list) else turbtype
# Get default diameter and HH
if 'Actuator_%s_rotor_diameter'%turbtype in self.inputvars:
default_turbD = self.inputvars['Actuator_%s_rotor_diameter'%turbtype].getval()
else:
default_turbD = 100.0
if 'Actuator_%s_hub_height'%turbtype in self.inputvars:
default_hh = self.inputvars['Actuator_%s_hub_height'%turbtype].getval()
else:
default_hh = 100.0
# Get the real values
turbhh = default_hh if tdict['Actuator_hub_height'] is None else tdict['Actuator_hub_height']
turbD = default_turbD if tdict['Actuator_rotor_diameter'] is None else tdict['Actuator_rotor_diameter']
return turbD, turbhh
def calc_FarmAvgProp(self):
# Go through all turbines
allturbines = self.listboxpopupwindict['listboxactuator']
alltags = allturbines.getitemlist()
keystr = lambda n, d1, d2: d2.name
#print(alltags)
acceptableTurbTypes = ['TurbineFastLine', 'TurbineFastDisk',
'UniformCtDisk' , 'JoukowskyDisk']
Nturbs = 0
AvgHH = 0.0
AvgTurbD = 0.0
AvgCenter = np.array([0.0, 0.0, 0.0])
for turb in alltags:
tdict = allturbines.dumpdict('AMR-Wind', subset=[turb], keyfunc=keystr)
if tdict['Actuator_type'] in acceptableTurbTypes:
Nturbs += 1
AvgCenter += tdict['Actuator_base_position']
turbD, turbhh = self.get_turbProp(tdict)
AvgHH += turbhh
AvgTurbD += turbD
#AvgHH += tdict['Actuator_hub_height']
#AvgTurbD += tdict['Actuator_rotor_diameter']
#print(tdict['Actuator_base_position'])
#print(tdict['Actuator_hub_height'])
else:
print('ERROR: '+tdict['Actuator_type']+' is not a recognized disk type')
if Nturbs>0:
AvgHH /= Nturbs
AvgTurbD /= Nturbs
AvgCenter /= Nturbs
else:
print("ERROR: calc_FarmAvgProp(): No turbines found to average over.")
return AvgCenter, AvgTurbD, AvgHH
def refine_calcZone(zonename, zonedict, zonecenter, sx, cx, vx, scale):
refinedict = {}
# Get the distances
upstream = scale*zonedict['upstream']
downstream = scale*zonedict['downstream']
lateral = scale*zonedict['lateral']
below = scale*zonedict['below']
above = scale*zonedict['above']
# Calculate the corner
corner = zonecenter - below*vx - upstream*sx - lateral*cx
axis1 = (upstream+downstream)*sx
axis2 = 2.0*lateral*cx
axis3 = (below+above)*vx
# Edit the parameters of the refinement window
refinedict['tagging_name'] = zonename
refinedict['tagging_shapes'] = zonename
refinedict['tagging_type'] = 'GeometryRefinement'
refinedict['tagging_level'] = zonedict['level']
refinedict['tagging_geom_type'] = 'box'
refinedict['tagging_geom_origin'] = list(corner)
refinedict['tagging_geom_xaxis'] = list(axis1)
refinedict['tagging_geom_yaxis'] = list(axis2)
refinedict['tagging_geom_zaxis'] = list(axis3)
return refinedict
def refine_createZoneForTurbine(self, turbname, turbinedict, zonedict,
defaultopt):
# Get the wind direction
winddir = self.inputvars['ABL_winddir'].getval()
# Get the turbine properties
base_position = np.array(turbinedict['Actuator_base_position'])
turbD, turbhh = self.get_turbProp(turbinedict)
turbyaw = winddir if turbinedict['Actuator_yaw'] is None else turbinedict['Actuator_yaw']
# Get the zone options
units = getdictval(zonedict['options'], 'units', defaultopt).lower()
orient = getdictval(zonedict['options'], 'orientation', defaultopt).lower()
# Set scale and orientation axes
scale = turbD if units=='diameter' else 1.0
if orient == 'x':
streamwise = np.array([1.0, 0.0, 0.0])
crossstream = np.array([0.0, 1.0, 0.0])
vert = np.array([0.0, 0.0, 1.0])
elif orient == 'y':
streamwise = np.array([0.0, 1.0, 0.0])
crossstream = np.array([1.0, 0.0, 0.0])
vert = np.array([0.0, 0.0, 1.0])
elif orient == 'nacdir':
streamwise, crossstream, vert = self.convert_winddir_to_xy(turbyaw)
elif isFloat(orient):
streamwise, crossstream, vert = self.convert_winddir_to_xy(float(orient))
else: # Use the wind direction
streamwise, crossstream, vert = self.convert_winddir_to_xy(winddir)
# Get the name
zonename = '%s_level_%i_zone'%(turbname, zonedict['level'])
zonecenter = base_position + turbhh*vert
refinedict = refine_calcZone(zonename, zonedict, zonecenter,
streamwise, crossstream, vert, scale)
return refinedict
def refine_createZoneForFarm(self, zonedict, autofarmcenter, AvgTurbD, AvgHH,
defaultopt):
# Get the wind direction
winddir = self.inputvars['ABL_winddir'].getval()
# Get the zone options
units = getdictval(zonedict['options'], 'units', defaultopt).lower()
orient = getdictval(zonedict['options'], 'orientation', defaultopt).lower()
# Set scale and orientation axes
scale = AvgTurbD if units=='diameter' else 1.0
if orient == 'x':
streamwise = np.array([1.0, 0.0, 0.0])
crossstream = np.array([0.0, 1.0, 0.0])
vert = np.array([0.0, 0.0, 1.0])
elif orient == 'y':
streamwise = np.array([0.0, 1.0, 0.0])
crossstream = np.array([1.0, 0.0, 0.0])
vert = np.array([0.0, 0.0, 1.0])
elif orient == 'nacdir':
print("Zone orientation nacdir not possible for farm zone.")
print("Using wind direction instead")
streamwise, crossstream, vert = self.convert_winddir_to_xy(winddir)
elif isFloat(orient):
streamwise, crossstream, vert = self.convert_winddir_to_xy(float(orient))
else: # Use the wind direction
streamwise, crossstream, vert = self.convert_winddir_to_xy(winddir)
# Set the farm center
center=getdictval(zonedict['options'], 'center', defaultopt).lower()
if center == 'specified':
defaultctr = {'centerx':0.0, 'centery':0.0, 'centerz':0.0}
# Use a specified center location
centerx = float(getdictval(zonedict['options'], 'centerx', defaultctr))
centery = float(getdictval(zonedict['options'], 'centery', defaultctr))
centerz = float(getdictval(zonedict['options'], 'centerz', defaultctr))
zonecenter = np.array([centerx, centery, centerz])
if 'name' in zonedict['options']:
zonename = zonedict['options']['name']
else:
zonename = 'Farm_level_%i_center_%.0f_%.0f_%.0f'%(zonedict['level'], centerx, centery, centerz)
else:
# Use the farm center
if self.inputvars['turbines_autocalccenter'].getval() == True:
usecenter = autofarmcenter
centerz = usecenter[2] + AvgHH
else:
usecenter = self.inputvars['turbines_farmcenter'].getval()
centerz = AvgHH
zonecenter = np.array([usecenter[0], usecenter[1], centerz])
# Get the name
zonename = 'Farm_level_%i_zone'%(zonedict['level'])
refinedict = refine_calcZone(zonename, zonedict, zonecenter,
streamwise, crossstream, vert, scale)
return refinedict
def refine_createAllZones(self):
"""
Create all of the refinement zones
"""
# Default dictionary for optional inputs
defaultopt = {'orientation':'winddir', # winddir/nacdir/x/y/float
'units':'diameter', # diameter/meter
'center':'turbine', # turbine/farm
'applyto':'', # Act only on specific turbs
}
# Get the csv input
csvstring = self.inputvars['refine_csvtextbox'].getval()
reqheaders = ['level', 'upstream', 'downstream',
'lateral', 'below', 'above']
optheaders = ['options']
#print(csvstring)
df = loadcsv(csvstring, stringinput=True,
reqheaders=reqheaders, optheaders=optheaders)
alldf = dataframe2dict(df, reqheaders, optheaders, dictkeys=optheaders)
#for zone in alldf: print(zone['options'])
# See if any zones are farm-centered
allcenters = [getdictval(z['options'], 'center', defaultopt).lower() for z in alldf]
#print(allcenters)
if 'farm' in allcenters:
#print("Calculating farm center")
AvgCenter, AvgTurbD, AvgHH = calc_FarmAvgProp(self)
#print("AvgCenter = "+repr(AvgCenter))
#print("AvgTurbD = "+repr(AvgTurbD))
#print("AvgHH = "+repr(AvgHH))
else:
AvgHH = 0.0
AvgTurbD = 0.0
AvgCenter = np.array([0.0, 0.0, 0.0])
# Get all turbine properties
allturbines = self.listboxpopupwindict['listboxactuator']
alltags = allturbines.getitemlist()
keystr = lambda n, d1, d2: d2.name
# Get the wind direction
self.ABL_calculateWDirWS()
# Delete all old zones (if necessary)
if self.inputvars['refine_deleteprev'].getval():
alltagging = self.listboxpopupwindict['listboxtagging']
alltagging.deleteall()
# Go through all rows and create zones
for zone in alldf:
center=getdictval(zone['options'], 'center', defaultopt).lower()
filterstr=getdictval(zone['options'], 'applyto', defaultopt)
if center=='turbine':
# Apply to specific turbines
if len(filterstr)>0:
applyturbs = [x for x in alltags if bool(re.search(filterstr, x))]
else:
applyturbs = alltags
for turb in applyturbs:
tdict = allturbines.dumpdict('AMR-Wind',
subset=[turb], keyfunc=keystr)
refinedict = refine_createZoneForTurbine(self, turb, tdict,
zone, defaultopt)
#print(refinedict)
if refinedict is not None:
self.add_tagging(refinedict)
else:
# Apply to the farm center
refinedict = refine_createZoneForFarm(self, zone, AvgCenter,
AvgTurbD, AvgHH, defaultopt)
#print(refinedict)
if refinedict is not None:
self.add_tagging(refinedict)
# Automatically set the max_level value
self.autoMaxLevel()
return
# ----------- Functions for wind farm turbines -------------
def convertLatLong(x, y, useutm, coordsys, stoponerror=True):
"""
Convert lat/long to utm x/y if necessary
"""
turbx = x
turby = y
if coordsys=='latlong':
if useutm:
utmxy = utm.from_latlon(x, y)
turbx = utmxy[0]
turby = utmxy[1]
else:
print("ERROR: UTM conversion not available ")
if stoponerror: sys.exit(1)
return turbx, turby
def getTurbAvgCenter(self, turbdf, updatewidget=False, convertlatlong=True):
"""
Calculate the farm center based on turbine locations
"""
AvgCenter = np.array([0.0, 0.0])
latcol = 0 # which coordinate is latitude
longcol = 1 # which coordinate is longitude
# Get the average center
if self.inputvars['turbines_autocalccenter'].getval():
for turb in turbdf:
AvgCenter += np.array([turb['x'], turb['y']])
AvgCenter = AvgCenter/len(turbdf)
else:
AvgCenter = self.inputvars['turbines_farmcenter'].getval()
# Convert from lat/long if necessary
coordsys = self.inputvars['turbines_coordsys'].getval()
if coordsys=='latlong' and convertlatlong:
# Convert AvgCenter to lat/long
if useutm:
utmxy = utm.from_latlon(AvgCenter[latcol],
AvgCenter[longcol])
AvgCenter = [utmxy[0], utmxy[1]]
#utm.from_latlon(row['ylat'], row['xlong'])
else:
print("ERROR: UTM conversion not available ")
if updatewidget:
self.inputvars['turbines_farmcenter'].setval(AvgCenter,
forcechange=True)
return AvgCenter
def turbines_getAllTurbineTypes(self):
"""
Get a list of all turbine types from csv input
"""
reqheaders = ['name', 'x', 'y', 'type', 'yaw', 'hubheight']
optheaders = ['options']
# Get the csv input
csvstring = self.inputvars['turbines_csvtextbox'].getval()
df = loadcsv(csvstring, stringinput=True,
reqheaders=reqheaders, optheaders=optheaders)
alldf = dataframe2dict(df, reqheaders, optheaders, dictkeys=optheaders)
# Get the turbine list
allturbtypes = self.listboxpopupwindict['listboxturbinetype'].getitemlist()
# build the list of turbine types
includedturbtypes = []
for turb in alldf:
turbtype = turb['type'].strip()
if turbtype not in allturbtypes:
print("ERROR: %s is not in list all turbine types:%s"%(turbtype,
allturbtypes))
continue
if (turbtype not in includedturbtypes):
includedturbtypes.append(turbtype)
return includedturbtypes
def isInt(s):
try:
int(s)
return True
except:
return False
def isFloat(s):
try:
float(s)
return True
except:
return False
def convertString(s):
if isInt(s): return int(s)
if isFloat(s): return float(s)
else: return s
def extractkeystartingwith(d, key, removeprefix=False):
"""
Extract all keys from dict that start with key
"""
returndict = OrderedDict()
for k, v in d.items():
if k.startswith(key):
newkey = k.replace(key, '', 1) if removeprefix else k
returndict[newkey] = convertString(v)
return returndict
def turbines_createAllTurbines(self):
"""
Create all of the turbines from csv input
"""
# Default dictionary for optional inputs
defaultopt = {'copyfast':False, # True/False
}
reqheaders = ['name', 'x', 'y', 'type', 'yaw', 'hubheight']
optheaders = ['options']
# Get the csv input
csvstring = self.inputvars['turbines_csvtextbox'].getval()
#print(csvstring)
df = loadcsv(csvstring, stringinput=True,
reqheaders=reqheaders, optheaders=optheaders)
alldf = dataframe2dict(df, reqheaders, optheaders, dictkeys=optheaders)
#for zone in alldf: print(zone['options'])
# Get all turbine properties
allturbines = self.listboxpopupwindict['listboxactuator']
alltags = allturbines.getitemlist()
keystr = lambda n, d1, d2: d2.name
# Calculate the farm center
AvgCenter = getTurbAvgCenter(self, alldf)
#print("AvgCenter = "+repr(AvgCenter))
createnewdomain = self.inputvars['turbines_createnewdomain'].getval()
# Set prob_lo/prob_hi/n_cell if necessary
if createnewdomain:
# Get the farm domain size
domainsize = self.inputvars['turbines_domainsize'].getval()
if domainsize is None:
# WARNING
print("ERROR: Farm domain size is not valid!")
return
if self.inputvars['turbines_freespace'].getval():
groundoffset = -0.5*domainsize[2]
else:
groundoffset = 0.0
corner1 = [AvgCenter[0] - 0.5*domainsize[0],
AvgCenter[1] - 0.5*domainsize[1],
0.0+groundoffset]
corner2 = [AvgCenter[0] + 0.5*domainsize[0],
AvgCenter[1] + 0.5*domainsize[1],
domainsize[2]+groundoffset]
self.inputvars['prob_lo'].setval(corner1)
self.inputvars['prob_hi'].setval(corner2)
# Set the mesh size (if necessary)
backgrounddx = self.inputvars['turbines_backgroundmeshsize'].getval()
if backgrounddx is not None:
Nx = int(round(domainsize[0]/backgrounddx))
Ny = int(round(domainsize[1]/backgrounddx))
Nz = int(round(domainsize[2]/backgrounddx))
self.inputvars['n_cell'].setval([Nx, Ny, Nz])
# Make sure to add turbines to simulation
source_terms = self.inputvars['ICNS_source_terms'].getval()
if source_terms is None: source_terms = []
if 'ActuatorForcing' not in source_terms:
source_terms.append('ActuatorForcing')
self.inputvars['ICNS_source_terms'].setval(source_terms)
#print(source_terms)
# Make sure to add Actuator to icns.physics
physicsterms = self.inputvars['physics'].getval()
if physicsterms is None: physicsterms = []
if 'Actuator' not in physicsterms:
physicsterms.append('Actuator')
self.inputvars['physics'].setval(physicsterms)
# Delete all old turbines (if necessary)
if self.inputvars['turbines_deleteprev'].getval():
allturbines.deleteall()
# Add all turbines
# Get the turbine list
allturbinemodels = self.listboxpopupwindict['listboxturbinetype']
allturbtypes = allturbinemodels.getitemlist()
# Get the wind direction
self.ABL_calculateWDirWS()
winddir = self.inputvars['ABL_winddir'].getval()
coordsys = self.inputvars['turbines_coordsys'].getval()
for turb in alldf:
turbtype = turb['type'].strip()
# Check the turbine type
if turbtype not in allturbtypes:
print("ERROR: turbine type %s not found for turbine %s"%(turbtype,turb['name']))
continue
modelparams = allturbinemodels.dumpdict('AMR-Wind',
subset=[turbtype],
keyfunc=lambda n, d1, d2: d2.name)
model_zHH = modelparams['Actuator_hub_height']
# Set the turbine xy
turbx, turby = convertLatLong(turb['x'], turb['y'], useutm, coordsys)
# ==== Set the turbine dictionary ====
turbdict = self.get_default_actuatordict()
turbdict['Actuator_name'] = turb['name']
# Set the hub-height
try: # Hub-height specified in CSV
hubheight = float(turb['hubheight'])
turbdict['Actuator_hub_height'] = hubheight
except: # Hub-height left alone
hubheight = model_zHH
turbdict['Actuator_base_position'] = [turbx, turby, hubheight - model_zHH]
# Set the yaw
try:
turbyaw = float(turb['yaw'])
except:
turbyaw = winddir
turbdict['Actuator_yaw'] = turbyaw
# Get all of the turbine model defaults
turbdict = self.turbinemodels_applyturbinemodel(turbdict,
turbtype,
docopy=True,
updatefast=True)
# Set any AMR-Wind options
AMRoptions = extractkeystartingwith(turb['options'], 'AMRparam_', removeprefix=True)
def tryeval(s) :
try:
x = eval(s)
except:
x = s
return x
if bool(AMRoptions):
for key, val in AMRoptions.items():
if isinstance(val, str): val = val.replace(';',',')
turbdict[key] = tryeval(val)
print("Setting "+key+" to "+repr(turbdict[key]))
# Process options if using OpenFAST model
if turbdict['Actuator_type'] in ['TurbineFastLine', 'TurbineFastDisk']:
fstfile = turbdict['Actuator_openfast_input_file']
options = turb['options']
#print("turbine fst file: "+fstfile)
#print("turbine options: "+repr(options))
# Make any edits to the FST file
FSToptions = extractkeystartingwith(options, 'FSTparam_', removeprefix=True)
if bool(FSToptions):
print(FSToptions)
OpenFAST.editFASTfile(fstfile, FSToptions)
# Make any edits to AeroDyn
ADoptions = extractkeystartingwith(options, 'ADparam_', removeprefix=True)
if bool(ADoptions):
print(ADoptions)
ADfile = OpenFAST.getFileFromFST(fstfile,'AeroFile')
OpenFAST.editFASTfile(ADfile, ADoptions)
# Make any edits to ServoDyn
SDoptions = extractkeystartingwith(options, 'SDparam_', removeprefix=True)
if bool(SDoptions):
print(SDoptions)
SDfile = OpenFAST.getFileFromFST(fstfile,'ServoFile')
OpenFAST.editFASTfile(SDfile, SDoptions)
# Make any edits to ElastoDyn
EDoptions = extractkeystartingwith(options, 'EDparam_', removeprefix=True)
if bool(EDoptions):
print(EDoptions)
EDfile = OpenFAST.getFileFromFST(fstfile,'EDFile')
OpenFAST.editFASTfile(EDfile, EDoptions)
# Make any edits to DISCON
DISCONoptions = extractkeystartingwith(options, 'DISCONparam_', removeprefix=True)
if bool(DISCONoptions):
print(DISCONoptions)
SDfile = OpenFAST.getFileFromFST(fstfile,'ServoFile')
DISCONfile = OpenFAST.getFileFromFST(SDfile, 'DLL_InFile')
OpenFAST.editDISCONfile(DISCONfile, DISCONoptions)
# Add the turbine to the list
self.add_turbine(turbdict, verbose=False)
return
def turbines_previewAllTurbines(self, ax=None):
"""
Plot all of the turbines from the csv input
"""
reqheaders = ['name', 'x', 'y', 'type', 'yaw', 'hubheight']
optheaders = ['options']
# Get the csv input
csvstring = self.inputvars['turbines_csvtextbox'].getval()
#print(csvstring)
df = loadcsv(csvstring, stringinput=True,
reqheaders=reqheaders, optheaders=optheaders)
alldf = dataframe2dict(df, reqheaders, optheaders, dictkeys=optheaders)
#for turb in alldf: print("%10s %f %f %10s"%(turb['name'], turb['x'], turb['y'], turb['type']))
createnewdomain = self.inputvars['turbines_createnewdomain'].getval()
# Set prob_lo/prob_hi/n_cell if necessary
if createnewdomain:
# Calculate the farm center
AvgCenter = getTurbAvgCenter(self, alldf)
#print("AvgCenter = "+repr(AvgCenter))
# Get the farm domain size
domainsize = self.inputvars['turbines_domainsize'].getval()
if domainsize is None:
# WARNING
print("ERROR: Farm domain size is not valid!")
return
else:
corner1 = self.inputvars['prob_lo'].getval()
corner2 = self.inputvars['prob_hi'].getval()
domainsize = np.array(corner2) - np.array(corner1)
AvgCenter = (np.array(corner2) + np.array(corner1))*0.5
# Set the corner points
corner1 = [AvgCenter[0] - 0.5*domainsize[0],
AvgCenter[1] - 0.5*domainsize[1],
0.0]
corner2 = [AvgCenter[0] + 0.5*domainsize[0],
AvgCenter[1] + 0.5*domainsize[1],
domainsize[2]]
# Clear and resize figure
if ax is None: ax=self.setupfigax()
# Do the domain plot first
ix = 0; xstr='X'
iy = 1; ystr='Y'
x1, y1, x2, y2 = plotRectangle(ax, corner1, corner2, ix, iy,
color='gray', ec='k', alpha=0.25)
# Plot the turbines
coordsys = self.inputvars['turbines_coordsys'].getval()
addturbinename = self.inputvars['turbines_plotnames'].getval()
for turb in alldf:
turbx, turby = convertLatLong(turb['x'], turb['y'], useutm, coordsys)
# plot the point
ax.plot(turbx, turby, marker='s', color='k', markersize=8)
if addturbinename:
ax.text(turbx+50, turby+50, turb['name'],
color='r', ha='right', va='top', fontdict={'fontsize':8})
# --------------------------------
# Set some plot formatting parameters
if coordsys=='latlong' or coordsys=='utm':
# this this for different hemispheres
xstr, ystr = 'EASTING', 'NORTHING'
ax.set_xlim([AvgCenter[0]-domainsize[0]*0.55,
AvgCenter[0]+domainsize[0]*0.55])
ax.set_ylim([AvgCenter[1]-domainsize[1]*0.55,
AvgCenter[1]+domainsize[1]*0.55])
ax.set_aspect('equal')
ax.set_xlabel('%s [m]'%xstr)
ax.set_ylabel('%s [m]'%ystr)
ax.set_title(r'Wind Farm Preview')
self.figcanvas.draw()
return
# ----------- Functions for sample plane creation ----------
def sampling_createDictForTurbine(self, turbname, tdict, pdict, defaultopt):
"""
Creates a sampling dictionary for turbine-oriented probes
"""
# Get the wind direction
winddir = self.inputvars['ABL_winddir'].getval()
# Get the turbine properties
base_position = np.array(tdict['Actuator_base_position'])
turbD, turbhh = self.get_turbProp(tdict)
turbyaw = winddir if tdict['Actuator_yaw'] is None else tdict['Actuator_yaw']
# Get the zone options
units = getdictval(pdict['options'], 'units', defaultopt).lower()
orient = getdictval(pdict['options'], 'orientation', defaultopt).lower()
usedx = getdictval(pdict['options'], 'usedx', defaultopt)
outputto= getdictval(pdict['options'], 'outputto', defaultopt)
outputfreq = getdictval(pdict['options'], 'outputfreq', defaultopt)
outputvars = getdictval(pdict['options'], 'outputvars', defaultopt)
outputderived = getdictval(pdict['options'], 'outputderived', defaultopt)
if outputvars is not None:
outputvars = outputvars.split(',')
#print('outputvars = '+repr(outputvars))
# Set scale and orientation axes
scale = turbD if units=='diameter' else 1.0
if orient == 'x':
streamwise = np.array([1.0, 0.0, 0.0])
crossstream = np.array([0.0, 1.0, 0.0])
vert = np.array([0.0, 0.0, 1.0])
elif orient == 'y':
streamwise = np.array([0.0, 1.0, 0.0])
crossstream = np.array([1.0, 0.0, 0.0])
vert = np.array([0.0, 0.0, 1.0])
elif orient == 'nacdir':
streamwise, crossstream, vert = self.convert_winddir_to_xy(turbyaw)
elif isFloat(orient):
streamwise, crossstream, vert = self.convert_winddir_to_xy(float(orient))
else: # Use the wind direction
streamwise, crossstream, vert = self.convert_winddir_to_xy(winddir)
# Turbine hub center
hubcenter = base_position + turbhh*vert
# # Get the distances
# upstream = scale*pdict['upstream']
# downstream = scale*pdict['downstream']
# lateral = scale*pdict['lateral']
# below = scale*pdict['below']
# above = scale*pdict['above']
# Get the name and probe type
probename = '%s_%s'%(turbname, pdict['name'])
probetype = pdict['type'].lower().strip()
sampledict = {}
# Set the output postprocessing object
if outputto is None:
sampledict['sampling_outputto'] = self.getPostProSamplingDefault()
else:
self.addPostProSamplingObject(outputto,
output_freq=outputfreq,
fields=outputvars,
derived_fields=outputderived)
sampledict['sampling_outputto'] = [outputto]
# --- Create centerline sampling probes ---
if probetype == 'centerline':
# Calculate the start, end, and number of points
upstream = scale*float(pdict['upstream'])
downstream = scale*float(pdict['downstream'])
clstart = hubcenter - upstream*streamwise
clend = hubcenter + downstream*streamwise
# Calculate the grid points
if usedx is None:
N1 = int(pdict['n1'])
else:
N1 = int(round((upstream+downstream)/(scale*float(usedx))))+1
# Set up the sampling dict
sampledict['sampling_name'] = probename
sampledict['sampling_type'] = 'LineSampler'
sampledict['sampling_l_num_points'] = N1
sampledict['sampling_l_start'] = clstart
sampledict['sampling_l_end'] = clend
# --- Create rotorplane sampling plane ---
elif probetype == 'rotorplane':
# Calculate the geometry
upstream = scale*float(pdict['upstream'])
#print('below = ['+repr(pdict['below'].strip())+']')
pdictbelow = repr(pdict['below']).replace("'",'').strip()
pdictabove = repr(pdict['above']).replace("'",'').strip()
pdictlateral = repr(pdict['lateral']).replace("'",'').strip()
below = 0.5*turbD if len(pdictbelow)<1 else scale*float(pdictbelow)
above = 0.5*turbD if len(pdictabove)<1 else scale*float(pdictabove)
lateral = 0.5*turbD if len(pdictlateral)<1 else scale*float(pdictlateral)
origin = hubcenter - upstream*streamwise
origin = origin - lateral*crossstream - below*vert
# Calculate dimensions
L1 = 2.0*lateral
L2 = above + below
# Calculate the grid points
if usedx is None:
N1 = int(pdict['n1'])
N2 = int(pdict['n2'])
else:
N1 = int(round((L1)/(scale*float(usedx))))+1
N2 = int(round((L2)/(scale*float(usedx))))+1
# Set up the sampling dict
sampledict['sampling_name'] = probename
sampledict['sampling_type'] = 'PlaneSampler'
sampledict['sampling_p_num_points'] = [N1, N2]
sampledict['sampling_p_origin'] = origin
sampledict['sampling_p_axis1'] = crossstream*L1
sampledict['sampling_p_axis2'] = vert*L2
# Calculate offsets
noffsets = int(getdictval(pdict['options'], 'noffsets', defaultopt))
if noffsets>0:
downstream = scale*float(pdict['downstream'])
offsetvec = np.linspace(0, upstream+downstream, noffsets+1)
offsetstr = ' '.join([repr(x) for x in offsetvec])
sampledict['sampling_p_normal'] = streamwise
sampledict['sampling_p_offset_vector'] = streamwise
sampledict['sampling_p_offsets'] = offsetstr
# --- Create hub-height sampling planes ---
elif probetype == 'hubheight':
# Calculate the geometry
upstream = scale*float(pdict['upstream'])
downstream = scale*float(pdict['downstream'])
lateral = scale*float(pdict['lateral'])
below = scale*float(pdict['below'])
origin = hubcenter - upstream*streamwise - below*vert
origin = origin - lateral*crossstream
# Calculate dimensions
L1 = upstream + downstream
L2 = 2.0*lateral
# Calculate the grid points
if usedx is None:
N1 = int(pdict['n1'])
N2 = int(pdict['n2'])
else:
N1 = int(round((L1)/(scale*float(usedx))))+1
N2 = int(round((L2)/(scale*float(usedx))))+1
# Set up the sampling dict
sampledict['sampling_name'] = probename