• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

WISDEM / WEIS / 12283078613

11 Dec 2024 06:59PM UTC coverage: 78.249% (-0.6%) from 78.802%
12283078613

Pull #308

github

dzalkind
Merge remote-tracking branch 'origin/DLC_RefactorCaseInputs' into DLC_RefactorCaseInputs
Pull Request #308: DLC Generation - Refactor and New Cases

446 of 665 new or added lines in 9 files covered. (67.07%)

3 existing lines in 3 files now uncovered.

21416 of 27369 relevant lines covered (78.25%)

0.78 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.16
/weis/glue_code/gc_LoadInputs.py
1
import os
1✔
2
import os.path as osp
1✔
3
import shutil
1✔
4
import numpy as np
1✔
5

6
from rosco import discon_lib_path
1✔
7
import weis.inputs as sch
1✔
8
from weis.aeroelasticse.FAST_reader import InputReader_OpenFAST
1✔
9
from wisdem.glue_code.gc_LoadInputs import WindTurbineOntologyPython
1✔
10
from weis.dlc_driver.dlc_generator    import DLCGenerator
1✔
11
from openmdao.utils.mpi import MPI
1✔
12
from rosco.toolbox.inputs.validation import load_rosco_yaml
1✔
13
from wisdem.inputs import load_yaml
1✔
14

15

16
def update_options(options,override):
1✔
17
    for key, value in override.items():
1✔
18
        if isinstance(value, dict) and key in options:
1✔
19
            update_options(options[key], value)
1✔
20
        elif key in options:
1✔
21
            options[key] = value
1✔
22
        else:
23
            raise Exception(f'Error updating option overrides. {key} is not part of {options.keys()}')
×
24

25
class WindTurbineOntologyPythonWEIS(WindTurbineOntologyPython):
1✔
26
    # Pure python class inheriting the class WindTurbineOntologyPython from WISDEM
27
    # and adding the WEIS options, namely the paths to the WEIS submodules
28
    # (OpenFAST, ROSCO, TurbSim, XFoil) and initializing the control parameters.
29

30
    def __init__(
1✔
31
            self, 
32
            fname_input_wt, 
33
            fname_input_modeling, 
34
            fname_input_analysis,
35
            modeling_override = None,
36
            analysis_override = None,
37
            ):
38

39
        self.modeling_options = sch.load_modeling_yaml(fname_input_modeling)
1✔
40
        self.modeling_options['fname_input_modeling'] = fname_input_modeling
1✔
41
        self.wt_init          = sch.load_geometry_yaml(fname_input_wt)
1✔
42
        self.analysis_options = sch.load_analysis_yaml(fname_input_analysis)
1✔
43
        self.analysis_options['fname_input_analysis'] = fname_input_analysis
1✔
44

45
        if modeling_override:
1✔
46
            update_options(self.modeling_options, modeling_override)
1✔
47
            sch.re_validate_modeling(self.modeling_options)
1✔
48
                
49
        
50
        if analysis_override:
1✔
51
            update_options(self.analysis_options, analysis_override)
×
52
            sch.re_validate_analysis(self.analysis_options)
×
53

54
        self.set_run_flags()
1✔
55
        self.set_openmdao_vectors()
1✔
56
        self.set_openmdao_vectors_control()
1✔
57
        self.set_weis_data()
1✔
58
        self.set_opt_flags()
1✔
59

60
    def set_weis_data(self):
1✔
61

62
        # Directory of modeling option input, if we want to use it for relative paths
63
        mod_opt_dir = osp.split(self.modeling_options['fname_input_modeling'])[0]
1✔
64

65
        # OpenFAST prefixes
66
        if self.modeling_options['General']['openfast_configuration']['OF_run_fst'] in ['','None','NONE','none']:
1✔
67
            self.modeling_options['General']['openfast_configuration']['OF_run_fst'] = 'weis_job'
1✔
68
            
69
        if self.modeling_options['General']['openfast_configuration']['OF_run_dir'] in ['','None','NONE','none']:
1✔
70
            self.modeling_options['General']['openfast_configuration']['OF_run_dir'] = osp.join(
1✔
71
                mod_opt_dir,        # If it's a relative path, will be relative to mod_opt directory
72
                self.analysis_options['general']['folder_output'], 
73
                'openfast_runs'
74
                )
75

76
        # BEM dir, all levels
77
        base_run_dir = os.path.join(mod_opt_dir,self.modeling_options['General']['openfast_configuration']['OF_run_dir'])
1✔
78
        if MPI:
1✔
79
            rank    = MPI.COMM_WORLD.Get_rank()
×
80
            bemDir = osp.join(base_run_dir,'rank_%000d'%int(rank),'BEM')
×
81
        else:
82
            bemDir = osp.join(base_run_dir,'BEM')
1✔
83

84

85

86
        # Openfast
87
        if self.modeling_options['Level2']['flag'] or self.modeling_options['Level3']['flag']:
1✔
88
            fast = InputReader_OpenFAST()
1✔
89
            self.modeling_options['General']['openfast_configuration']['fst_vt'] = {}
1✔
90
            self.modeling_options['General']['openfast_configuration']['fst_vt']['outlist'] = fast.fst_vt['outlist']
1✔
91

92
                
93
            # User-defined control dylib (path2dll)
94
            path2dll = self.modeling_options['General']['openfast_configuration']['path2dll']
1✔
95
            if path2dll == 'none':   #Default option, use above
1✔
96
                self.modeling_options['General']['openfast_configuration']['path2dll'] = discon_lib_path
1✔
97
            else:
98
                if not osp.isabs(path2dll):  # make relative path absolute
×
99
                    self.modeling_options['General']['openfast_configuration']['path2dll'] = \
×
100
                        osp.join(osp.dirname(self.options['modeling_options']['fname_input_modeling']), path2dll)
101
            path2dll = self.modeling_options['General']['openfast_configuration']['path2dll']
1✔
102
            if not osp.exists( path2dll ):
1✔
103
                raise NameError("Cannot find DISCON library: "+path2dll)
×
104

105
            # Activate HAMS in Level1 if requested for Level 2 or 3
106
            if self.modeling_options["flags"]["offshore"] or self.modeling_options["Level3"]["from_openfast"]:
1✔
107
                if self.modeling_options["Level1"]["potential_model_override"] == 2:
1✔
108
                    self.modeling_options["Level3"]["HydroDyn"]["PotMod"] = 1
1✔
109
                elif ( (self.modeling_options["Level1"]["potential_model_override"] == 0) and
1✔
110
                       (len(self.modeling_options["Level1"]["potential_bem_members"]) > 0) ):
111
                    self.modeling_options["Level3"]["HydroDyn"]["PotMod"] = 1
×
112
                elif self.modeling_options["Level1"]["potential_model_override"] == 1:
1✔
113
                    self.modeling_options["Level3"]["HydroDyn"]["PotMod"] = 0
×
114
                else:
115
                    # Keep user defined value of PotMod
116
                    pass
1✔
117

118
                if self.modeling_options["Level3"]["HydroDyn"]["PotMod"] == 1:
1✔
119

120
                    # If user requested PotMod but didn't specify any override or members, just run everything
121
                    if ( (self.modeling_options["Level1"]["potential_model_override"] == 0) and
1✔
122
                       (len(self.modeling_options["Level1"]["potential_bem_members"]) == 0) ):
123
                        self.modeling_options["Level1"]["potential_model_override"] == 2
×
124
                        
125
                    cwd = os.getcwd()
1✔
126
                    weis_dir = osp.dirname(osp.dirname(osp.dirname(osp.abspath(__file__))))
1✔
127
                    potpath = self.modeling_options["Level3"]["HydroDyn"]["PotFile"].replace('.hst','').replace('.12','').replace('.3','').replace('.1','')
1✔
128
                    if ( (len(potpath) == 0) or (potpath.lower() in ['unused','default','none']) ):
1✔
129
                        
130
                        self.modeling_options['Level1']['flag'] = True
×
131
                        self.modeling_options["Level3"]["HydroDyn"]["PotFile"] = osp.join(bemDir,'Output','Wamit_format','Buoy')
×
132
                        
133

134
                    else:
135
                        if self.modeling_options['Level1']['runPyHAMS']:
1✔
136
                            print('Found existing potential model: {}\n    - Trying to use this instead of running PyHAMS.'.format(potpath))
1✔
137
                            self.modeling_options['Level1']['runPyHAMS'] = False
1✔
138
                        if osp.exists( potpath+'.1' ):
1✔
139
                            self.modeling_options["Level3"]["HydroDyn"]["PotFile"] = osp.realpath(potpath)
1✔
140
                        elif osp.exists( osp.join(cwd, potpath+'.1') ):
×
141
                            self.modeling_options["Level3"]["HydroDyn"]["PotFile"] = osp.realpath( osp.join(cwd, potpath) )
×
142
                        elif osp.exists( osp.join(weis_dir, potpath+'.1') ):
×
143
                            self.modeling_options["Level3"]["HydroDyn"]["PotFile"] = osp.realpath( osp.join(weis_dir, potpath) )
×
144
                        elif osp.exists( osp.join(mod_opt_dir, potpath+'.1') ):
×
145
                            self.modeling_options["Level3"]["HydroDyn"]["PotFile"] = osp.realpath( osp.join(mod_opt_dir, potpath) )
×
146
                        else:
147
                            raise Exception(f'No valid Wamit-style output found for specified PotFile option, {potpath}.1')
×
148

149
        # OpenFAST dir
150
        if self.modeling_options["Level3"]["from_openfast"]:
1✔
151
            if not osp.isabs(self.modeling_options['Level3']['openfast_dir']):
1✔
152
                # Make relative to modeling options input
153
                self.modeling_options['Level3']['openfast_dir'] = osp.realpath(osp.join(
1✔
154
                    mod_opt_dir, self.modeling_options['Level3']['openfast_dir'] ))
155
        
156
        # BEM dir, all levels
157
        base_run_dir = os.path.join(mod_opt_dir,self.modeling_options['General']['openfast_configuration']['OF_run_dir'])
1✔
158
        if MPI:
1✔
NEW
159
            rank    = MPI.COMM_WORLD.Get_rank()
×
NEW
160
            bemDir = osp.join(base_run_dir,'rank_%000d'%int(rank),'BEM')
×
161
        else:
162
            bemDir = osp.join(base_run_dir,'BEM')
1✔
163

164
        self.modeling_options["Level1"]['BEM_dir'] = bemDir
1✔
165
        if MPI:
1✔
166
            # If running MPI, RAFT won't be able to save designs in parallel
NEW
167
            self.modeling_options["Level1"]['save_designs'] = False
×
168
        
169
        # RAFT
170
        if self.modeling_options["flags"]["floating"]:
1✔
171
            bool_init = True if self.modeling_options["Level1"]["potential_model_override"]==2 else False
1✔
172
            self.modeling_options["Level1"]["model_potential"] = [bool_init] * self.modeling_options["floating"]["members"]["n_members"]
1✔
173

174
            if self.modeling_options["Level1"]["potential_model_override"] == 0:
1✔
175
                for k in self.modeling_options["Level1"]["potential_bem_members"]:
1✔
176
                    idx = self.modeling_options["floating"]["members"]["name"].index(k)
1✔
177
                    self.modeling_options["Level1"]["model_potential"][idx] = True
1✔
178
        elif self.modeling_options["flags"]["offshore"]:
1✔
179
            self.modeling_options["Level1"]["model_potential"] = [False]*1000
1✔
180
            
181
        # ROSCO
182
        self.modeling_options['ROSCO']['flag'] = (self.modeling_options['Level1']['flag'] or
1✔
183
                                                  self.modeling_options['Level2']['flag'] or
184
                                                  self.modeling_options['Level3']['flag'])
185
        
186
        if self.modeling_options['ROSCO']['tuning_yaml'] != 'none':  # default is empty
1✔
187
            # Make path absolute if not, relative to modeling options input
188
            if not osp.isabs(self.modeling_options['ROSCO']['tuning_yaml']):
1✔
189
                self.modeling_options['ROSCO']['tuning_yaml'] = osp.realpath(osp.join(
1✔
190
                    mod_opt_dir, self.modeling_options['ROSCO']['tuning_yaml'] ))
191
                
192
        # Apply tuning yaml input if available, this needs to be here for sizing tune_rosco_ivc
193
        if os.path.split(self.modeling_options['ROSCO']['tuning_yaml'])[1] != 'none':  # default is none
1✔
194
            inps = load_rosco_yaml(self.modeling_options['ROSCO']['tuning_yaml'])  # tuning yaml validated in here
1✔
195
            self.modeling_options['ROSCO'].update(inps['controller_params'])
1✔
196

197
            # Apply changes in modeling options, should have already been validated
198
            modopts_no_defaults = load_yaml(self.modeling_options['fname_input_modeling'])  
1✔
199
            skip_options = ['tuning_yaml']  # Options to skip loading, tuning_yaml path has been updated, don't overwrite
1✔
200
            for option, value in modopts_no_defaults['ROSCO'].items():
1✔
201
                if option not in skip_options:
1✔
202
                    self.modeling_options['ROSCO'][option] = value
1✔
203
        
204
        # XFoil
205
        if not osp.isfile(self.modeling_options['Level3']["xfoil"]["path"]) and self.modeling_options['ROSCO']['Flp_Mode']:
1✔
206
            raise Exception("A distributed aerodynamic control device is defined in the geometry yaml, but the path to XFoil in the modeling options is not defined correctly")
×
207

208
        # Compute the number of DLCs that will be run
209
        DLCs = self.modeling_options['DLC_driver']['DLCs']
1✔
210
        # Initialize the DLC generator
211
        cut_in = self.wt_init['control']['supervisory']['Vin']
1✔
212
        cut_out = self.wt_init['control']['supervisory']['Vout']
1✔
213
        metocean = self.modeling_options['DLC_driver']['metocean_conditions']
1✔
214
        dlc_generator = DLCGenerator(cut_in, cut_out, metocean=metocean)
1✔
215
        # Generate cases from user inputs
216
        for i_DLC in range(len(DLCs)):
1✔
217
            DLCopt = DLCs[i_DLC]
1✔
218
            dlc_generator.generate(DLCopt['DLC'], DLCopt)
1✔
219
        self.modeling_options['DLC_driver']['n_cases'] = dlc_generator.n_cases
1✔
220
        
221
        # Determine wind speeds that will be used to calculate AEP (using DLC AEP or 1.1)
222
        DLCs = [i_dlc['DLC'] for i_dlc in self.modeling_options['DLC_driver']['DLCs']]
1✔
223
        if 'AEP' in DLCs:
1✔
NEW
224
            DLC_label_for_AEP = 'AEP'
×
225
        else:
226
            DLC_label_for_AEP = '1.1'
1✔
227
        dlc_aep_ws = [c.URef for c in dlc_generator.cases if c.label == DLC_label_for_AEP]
1✔
228
        self.modeling_options['DLC_driver']['n_ws_aep'] = len(np.unique(dlc_aep_ws))
1✔
229

230
        # TMD modeling
231
        self.modeling_options['flags']['TMDs'] = False
1✔
232
        if 'TMDs' in self.wt_init:
1✔
233
            if self.modeling_options['Level3']['flag']:
1✔
234
                self.modeling_options['flags']['TMDs'] = True
1✔
235
            else:
236
                raise Exception("TMDs in Levels 1 and 2 are not supported yet")
×
237

238

239
    def set_openmdao_vectors_control(self):
1✔
240
        # Distributed aerodynamic control devices along blade
241
        self.modeling_options['WISDEM']['RotorSE']['n_te_flaps']      = 0
1✔
242
        if 'aerodynamic_control' in self.wt_init['components']['blade']:
1✔
243
            if 'te_flaps' in self.wt_init['components']['blade']['aerodynamic_control']:
×
244
                self.modeling_options['WISDEM']['RotorSE']['n_te_flaps'] = len(self.wt_init['components']['blade']['aerodynamic_control']['te_flaps'])
×
245
                self.modeling_options['WISDEM']['RotorSE']['n_tab']   = 3
×
246
            else:
247
                raise Exception('A distributed aerodynamic control device is provided in the yaml input file, but not supported by wisdem.')
×
248

249
        if 'TMDs' in self.wt_init:
1✔
250
            n_TMDs = len(self.wt_init['TMDs'])
1✔
251
            self.modeling_options['TMDs'] = {}
1✔
252
            self.modeling_options['TMDs']['n_TMDs']                 = n_TMDs
1✔
253
            # TODO: come back and check how many of these need to be modeling options
254
            self.modeling_options['TMDs']['name']                   = [tmd['name'] for  tmd in self.wt_init['TMDs']]
1✔
255
            self.modeling_options['TMDs']['component']              = [tmd['component'] for  tmd in self.wt_init['TMDs']]
1✔
256
            self.modeling_options['TMDs']['location']               = [tmd['location'] for  tmd in self.wt_init['TMDs']]
1✔
257
            self.modeling_options['TMDs']['mass']                   = [tmd['mass'] for  tmd in self.wt_init['TMDs']]
1✔
258
            self.modeling_options['TMDs']['stiffness']              = [tmd['stiffness'] for  tmd in self.wt_init['TMDs']]
1✔
259
            self.modeling_options['TMDs']['damping']                = [tmd['damping'] for  tmd in self.wt_init['TMDs']]
1✔
260
            self.modeling_options['TMDs']['natural_frequency']      = [tmd['natural_frequency'] for  tmd in self.wt_init['TMDs']]
1✔
261
            self.modeling_options['TMDs']['damping_ratio']          = [tmd['damping_ratio'] for  tmd in self.wt_init['TMDs']]
1✔
262
            self.modeling_options['TMDs']['X_DOF']                  = [tmd['X_DOF'] for  tmd in self.wt_init['TMDs']]
1✔
263
            self.modeling_options['TMDs']['Y_DOF']                  = [tmd['Y_DOF'] for  tmd in self.wt_init['TMDs']]
1✔
264
            self.modeling_options['TMDs']['Z_DOF']                  = [tmd['Z_DOF'] for  tmd in self.wt_init['TMDs']]
1✔
265
            self.modeling_options['TMDs']['preload_spring']         = [tmd['preload_spring'] for  tmd in self.wt_init['TMDs']]
1✔
266

267
            # Check that TMD locations map to somewhere valid (tower or platform member)
268
            self.modeling_options['TMDs']['num_tower_TMDs'] = 0
1✔
269
            self.modeling_options['TMDs']['num_ptfm_TMDs']  = 0
1✔
270
            
271
            for i_TMD, component in enumerate(self.modeling_options['TMDs']['component']):
1✔
272
                if self.modeling_options['flags']['floating'] and component in self.modeling_options['floating']['members']['name']:
1✔
273
                    self.modeling_options['TMDs']['num_ptfm_TMDs'] += 1
1✔
274
                elif component == 'tower':
×
275
                    self.modeling_options['TMDs']['num_tower_TMDs'] += 1
×
276
                else:
277
                    raise Exception('Invalid TMD component mapping for {} on {}'.format(
×
278
                        self.modeling_options['TMDs']['name'][i_TMD],component))      
279

280
            # Set TMD group  mapping: list of length n_groups, with i_TMDs in each group
281
            # Loop through TMD names, assign to own group if not in an analysis group
282
            if 'TMDs' in self.analysis_options['design_variables']:
1✔
283
                tmd_group_map = []
1✔
284
                tmd_names = self.modeling_options['TMDs']['name']
1✔
285
                
286
                for i_group, tmd_group in enumerate(self.analysis_options['design_variables']['TMDs']['groups']):
1✔
287
                    tmds_in_group_i = [tmd_names.index(tmd_name) for tmd_name in tmd_group['names']]
1✔
288

289
                    tmd_group_map.append(tmds_in_group_i)
1✔
290
                
291
                self.modeling_options['TMDs']['group_mapping'] = tmd_group_map
1✔
292

293
    def update_ontology_control(self, wt_opt):
1✔
294
        # Update controller
295
        if self.modeling_options['flags']['control']:
×
296
            self.wt_init['control']['pitch']['omega_pc'] = wt_opt['tune_rosco_ivc.omega_pc']
×
297
            self.wt_init['control']['pitch']['zeta_pc']  = wt_opt['tune_rosco_ivc.zeta_pc']
×
298
            self.wt_init['control']['torque']['omega_vs'] = float(wt_opt['tune_rosco_ivc.omega_vs'])
×
299
            self.wt_init['control']['torque']['zeta_vs']  = float(wt_opt['tune_rosco_ivc.zeta_vs'])
×
300
            self.wt_init['control']['pitch']['Kp_float']  = float(wt_opt['tune_rosco_ivc.Kp_float'])
×
301
            self.wt_init['control']['pitch']['ptfm_freq']  = float(wt_opt['tune_rosco_ivc.ptfm_freq'])
×
302
            self.wt_init['control']['IPC']['IPC_Ki_1P'] = float(wt_opt['tune_rosco_ivc.IPC_Kp1p'])
×
303
            self.wt_init['control']['IPC']['IPC_Kp_1P'] = float(wt_opt['tune_rosco_ivc.IPC_Ki1p'])
×
304
            if self.modeling_options['ROSCO']['Flp_Mode'] > 0:
×
305
                self.wt_init['control']['dac']['flp_kp_norm']= float(wt_opt['tune_rosco_ivc.flp_kp_norm'])
×
306
                self.wt_init['control']['dac']['flp_tau'] = float(wt_opt['tune_rosco_ivc.flp_tau'])
×
307

308

309
    def write_options(self, fname_output):
1✔
310
        # Override the WISDEM version to ensure that the WEIS options files are written instead
311
        sch.write_modeling_yaml(self.modeling_options, fname_output)
1✔
312
        sch.write_analysis_yaml(self.analysis_options, fname_output)
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc