### Install and Install Pre-commit Hooks Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/installation.rst Installs the pre-commit framework and then installs the git hooks for the repository. This ensures code formatting and linting checks are performed automatically before commits. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Install TOPFARM from GitLab Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/installation.rst Installs the latest development version of TOPFARM directly from its GitLab repository. Use with caution as it may contain bugs. ```bash pip install git+https://gitlab.windenergy.dtu.dk/TOPFARM/TopFarm2.git ``` -------------------------------- ### Install TOPFARM from PyPi Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/installation.rst Installs the latest stable release of TOPFARM from the Python Package Index (PyPi). This is the recommended method for most users. ```bash pip install topfarm ``` -------------------------------- ### Setup Boundary and Dummy Cost Model Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/constraints Demonstrates setting up a boundary using arbitrary points and initializing a dummy cost model component for a TOPFARM optimization problem with two wind turbines. This is a preparatory step for constraint examples. ```python # set up a "boundary" array with arbitrary points for use in the example boundary = np.array([(0, 0), (1, 1), (3, 0), (3, 2), (0, 2)]) # set up dummy design variables and cost model component. # This example includes 2 turbines (n_wt=2) located at x,y=0.5,0.5 and 1.5,1.5 respectively x = [0.5,1.5] y = [.5,1.5] dummy_cost = CostModelComponent(input_keys=[], n_wt=2, cost_function=lambda : 1) ``` -------------------------------- ### Install TopFarm2 Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/exclusion_zones.ipynb Installs the TopFarm2 library from its GitLab repository if it's not already found in the current environment. This is a prerequisite for running the optimization examples. ```python # Install TopFarm if needed import importlib if not importlib.util.find_spec("topfarm"): %pip install git+https://gitlab.windenergy.dtu.dk/TOPFARM/TopFarm2.git ``` -------------------------------- ### Setup Inputs and Outputs for CostModelComponent (Python) Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/cost_models/cost_model_wrappers The setup method initializes inputs and outputs for the CostModelComponent. It dynamically adds inputs based on provided keys and units, and outputs for cost and cost components. It also declares partial derivatives based on whether a cost gradient function is provided. ```python def setup(self): for i, u in zip(self.input_keys + self.additional_input, self.input_units): if isinstance(i, tuple) and len(i) == 2: self.add_input(i[0], val=i[1], units=u) else: self.add_input(i, val=np.zeros(self.n_wt), units=u) if self.use_constraint_violation: self.add_input('constraint_violation', val=0.0) if self.objective: self.add_output('cost', val=0.0) self.add_output('cost_comp_eval', val=0.0) for o, v in zip(self.output_keys, self.output_vals): if isinstance(o, tuple) and len(o) == 2: self.add_output(o[0], val=o[1]) else: self.add_output(o, val=v) for key, val in self.additional_output: self.add_output(key, val=val) if self.cost_gradient_function: if self.objective: self.declare_partials('cost', self.input_keys_only, method='exact') for o in self.out_keys_only: self.declare_partials(o, self.input_keys_only, method='exact') else: if self.step == {}: if self.objective: self.declare_partials('cost', self.input_keys_only, method='fd') for o in self.out_keys_only: self.declare_partials(o, self.input_keys_only, method='fd') else: for i in self.input_keys_only: if self.objective: self.declare_partials('cost', i, step=self.step[i], method='fd') for o in self.out_keys_only: self.declare_partials(o, i, step=self.step[i], method='fd') ``` -------------------------------- ### Install TopFarm2 and PyWake Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/bathymetry Installs the TopFarm2 library and its dependency PyWake from GitLab. Includes conditional installation for Google Colab environments and a specific SciPy version constraint. ```python import importlib if not importlib.util.find_spec("topfarm"): %pip install git+https://gitlab.windenergy.dtu.dk/TOPFARM/TopFarm2.git try: RunningInCOLAB = 'google.colab' in str(get_ipython()) except NameError: RunningInCOLAB = False if RunningInCOLAB: %pip install git+https://gitlab.windenergy.dtu.dk/TOPFARM/PyWake.git %pip install git+https://gitlab.windenergy.dtu.dk/TOPFARM/TopFarm2.git %pip install scipy==1.6.3 # constraint is not continuous which trips vers. 1.4.1 which presently is the default version import os os.kill(os.getpid(), 9) ``` -------------------------------- ### Install TOPFARM with TensorFlow Support Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/installation.rst Installs TOPFARM along with the TensorFlow library, enabling functionalities that depend on TensorFlow. This is for users whose workflows require TensorFlow. ```bash pip install topfarm[tensorflow] ``` -------------------------------- ### Developer Installation of TOPFARM Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/installation.rst Clones the TOPFARM 2 repository and installs it in editable mode, allowing for direct code modifications and testing. This is recommended for developers contributing to the project. ```bash git clone https://gitlab.windenergy.dtu.dk/TOPFARM/TopFarm2.git cd TopFarm2 pip install -e . ``` -------------------------------- ### Setup Model Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/_topfarm Calls the final setup method for the model. This is a standard procedure after all components have been added and configured. ```python self.setup() ``` -------------------------------- ### Check and Install Python Packages Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/design_variables This snippet demonstrates how to define a list of Python packages and iterate through them to check for and install any missing dependencies. It includes example output showing the installation process and dependency resolution for 'openmdao[doe]' and 'pyDOE2'. It also highlights a warning about running pip as root. ```python packages = ["openmdao[doe]", "pyDOE2"] for pkg in packages: check_and_install(pkg) ``` -------------------------------- ### Install TopFarm2 Python Package Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/sgd_slsqp_comparison.ipynb Installs the TopFarm2 package from its GitLab repository if it's not already found in the current environment. This is a prerequisite for running the optimization examples. ```python import importlib if not importlib.util.find_spec("topfarm"): %pip install git+https://gitlab.windenergy.dtu.dk/TOPFARM/TopFarm2.git ``` -------------------------------- ### Problem Setup and Finalization in Python Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/_topfarm Handles the setup and finalization process for the problem, including managing derivative modes and warning filters. It ensures the problem is correctly configured before execution. ```python def setup(self): if not self._metadata: Problem.setup(self) if self._metadata['setup_status'] == _SetupStatus.PRE_SETUP: Problem.setup(self) if self._metadata['setup_status'] < _SetupStatus.POST_FINAL_SETUP: with warnings.catch_warnings(): warnings.filterwarnings('error') try: if len(self.driver._rec_mgr._recorders) == 0: tmp_recorder = TopFarmListRecorder() self.driver.add_recorder(tmp_recorder) Problem.final_setup(self) else: Problem.final_setup(self) except Warning as w: if str(w).startswith('Inefficient choice of derivative mode'): Problem.setup(self, mode='fwd') else: raise w finally: try: self.driver._rec_mgr._recorders.remove(tmp_recorder) except Exception: pass ``` -------------------------------- ### Setup Post-Constraints Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/_topfarm Adds post-constraints to the model, handling different constraint types and ensuring they are correctly integrated into the optimization setup. ```python if len(post_constraints) > 0: if not constraints_as_penalty: for constr in post_constraints: if isinstance(constr, Constraint): if 'constraints_group2' not in self.model._subsystems_allprocs: # and 'post_constraints' not in self.model._static_subsystems_allprocs: self.model.add_subsystem('constraints_group2', ParallelGroup(), promotes=['*']) constr.setup_as_constraint(self, group='constraints_group2') elif isinstance(constr[-1], dict): self.model.add_constraint(str(constr[0]), **constr[-1]) else: warnings.warn("""constraint tuples should be of type (keyword, {constraint options}).""", DeprecationWarning, stacklevel=2) ``` -------------------------------- ### Compute AEP with Smart Start Approach (Python) Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/cost_models/py_wake_wrapper Provides a method to compute AEP using a 'smart start' approach, which is useful for initializing optimization algorithms. It allows specifying wind speeds, directions, and turbine types to simulate different scenarios. ```python def get_aep4smart_start(self, ws=[6, 8, 10, 12, 14], wd=np.arange(360), type=0, **kwargs): """Compute AEP with a smart start approach""" def aep4smart_start(X, Y, wt_x, wt_y, T=0, wt_t=0): H = np.full(X.shape, self.windFarmModel.windTurbines.hub_height()) if type == 0: sim_res = self.windFarmModel(wt_x, wt_y, type=wt_t, wd=wd, ws=ws, n_cpu=self.n_cpu, **kwargs) next_type = T else: type_ = np.atleast_1d(type) t = np.zeros_like(wt_x) + type_[:len(wt_x)] sim_res = self.windFarmModel(wt_x, wt_y, type=t, wd=wd, ws=ws, n_cpu=self.n_cpu, **kwargs) H = np.full(X.shape, self.windFarmModel.windTurbines.hub_height()) next_type = type_[min(len(type_) - 1, len(wt_x) + 1)] return sim_res.aep_map(Points(X, Y, H), type=next_type, n_cpu=self.n_cpu).values return aep4smart_start ``` -------------------------------- ### Smart Start for Optimization Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/cables Implements a smart start strategy for the optimization process. It generates a grid of potential starting points, calculates AEP for these points, and then uses this information to initialize the optimization. ```python x = np.linspace(500, 5500, 41) y = np.linspace(-9500, -500, 41) YY, XX = np.meshgrid(y, x) tf.smart_start( XX, YY, tf.cost_comp.comp_0.get_aep4smart_start(ws=8, wd=270), random_pct=20 ) tf.evaluate() ``` -------------------------------- ### Install TopFarm Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/constraints Installs the TopFarm library from a Git repository if it's not already found in the current environment. This is a prerequisite for using TOPFARM functionalities. ```python # Install TopFarm if needed import importlib if not importlib.util.find_spec("topfarm"): %pip install git+https://gitlab.windenergy.dtu.dk/TOPFARM/TopFarm2.git ``` -------------------------------- ### Smart Start Turbine Placement Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/_topfarm Performs a smart start for turbine placement using provided XX, YY, and optional ZZ coordinates. It considers minimum spacing constraints and boundary conditions to find optimal initial positions for turbines. ```python def smart_start(self, XX, YY, ZZ=None, min_space=None, radius=None, random_pct=0, plot=False, seed=None, types=None, show_progress=True): assert XX.shape == YY.shape ZZ_is_func = hasattr(ZZ, '__call__') spacing_comp_lst = [c for c in self.model.constraint_components if isinstance(c, SpacingComp)] if min_space is not None: min_spacing = min_space else: if len(spacing_comp_lst) == 1: min_spacing = spacing_comp_lst[0].min_spacing else: min_spacing = 0 if not types: min_spacing = np.max(min_spacing) X, Y = XX.flatten(), YY.flatten() if not ZZ_is_func: if ZZ is None: ZZ = np.full(XX.shape, 0) Z = ZZ.flatten() else: Z = ZZ for comp in self.model.constraint_components: if isinstance(comp, BoundaryBaseComp): dist = comp.distances(X, Y) if len(dist.shape) == 2: dist = dist.min(1) mask = dist >= 0 X, Y = X[mask], Y[mask] if not ZZ_is_func: Z = Z[mask] res = smart_start(X, Y, Z, self.n_wt, min_spacing, radius, random_pct, plot, seed=seed, types=types, show_progress=show_progress) self.update_state({topfarm.x_key: res[0], topfarm.y_key: res[1]}) if types: self.set_val(topfarm.type_key, res[2]) return res ``` -------------------------------- ### Setup Constraints with Penalty Option Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/_topfarm Iterates through constraints, setting them up either as standard constraints or as penalties based on the 'constraints_as_penalty' flag. This allows flexible constraint handling. ```python if len(constraints) > 0: self.model.add_subsystem('constraint_group', ParallelGroup(), promotes=['*']) for constr in constraints: if constraints_as_penalty: constr.setup_as_penalty(self) else: constr.setup_as_constraint(self) constraint_violation_comp = ConstraintViolationComponent(constraints) self.model.add_subsystem('constraint_violation_comp', constraint_violation_comp, promotes=['*']) ``` -------------------------------- ### Set Up Site, Wind Farm Model, and Optimization Problem Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/regular_grid_optimization Configures the wind farm simulation by specifying the site, wind turbine model, and wind farm model. It then defines the optimization problem, including design variables, constraints, cost components (AEP and layout), and the optimization driver. ```python #specifying the site and wind turbines to use site = Hornsrev1Site() wt = V80() D = wt.diameter() windFarmModel = BastankhahGaussian(site, wt) n_wt = 16 boundary = [[-800,-50], [1200, -50], [1200,2300], [-800, 2300]] stagger = 1 * D #to create a staggered layout def reg_func(sx, sy, rotation, **kwargs): x, y = regular_generic_layout(n_wt, sx, sy, stagger, rotation) return [x, y] def reg_grad(sx, sy, rotation, **kwargs): dx_dsx, dy_dsx, dx_dsy, dy_dsy, dx_dr, dy_dr = regular_generic_layout_gradients(n_wt, sx, sy, stagger, rotation) return [[dx_dsx, dy_dsx], [dx_dsy, dy_dsy], [dx_dr, dy_dr]] reg_grid_comp = CostModelComponent(input_keys=[('sx', 0), ('sy', 0), ('rotation', 0)], n_wt=n_wt, cost_function=reg_func, cost_gradient_function = reg_grad, output_keys= [('x', np.zeros(n_wt)), ('y', np.zeros(n_wt))], objective=False, use_constraint_violation=False, ) def aep_fun(x, y): aep = windFarmModel(x, y).aep().sum() return aep daep = windFarmModel.aep_gradients(gradient_method=autograd, wrt_arg=['x', 'y']) aep_comp = CostModelComponent(input_keys=['x', 'y'], n_wt=n_wt, cost_function=aep_fun, cost_gradient_function = daep, output_keys= ("aep", 0), output_unit="GWh", maximize=True, objective=True) problem = TopFarmProblem(design_vars={'sx': (3*D, 2*D, 15*D), 'sy': (4*D, 2*D, 15*D), 'rotation': (50, 0, 90) }, constraints=[XYBoundaryConstraint(boundary), SpacingConstraint(4*D)], grid_layout_comp=reg_grid_comp, n_wt = n_wt, cost_comp=aep_comp, driver=EasyScipyOptimizeDriver(optimizer='SLSQP', maxiter=30), plot_comp=XYPlotComp(), expected_cost=0.1, ) ``` -------------------------------- ### Topfarm Problem Setup and Optimization Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/cost_models/py_wake_wrapper This code snippet demonstrates how to set up a Topfarm problem for wind farm optimization. It initializes site, wind turbines, and a wind farm model, then configures the problem with design variables, cost component, driver, constraints, and plotting component before running the optimization. ```python def main(): if __name__ == '__main__': n_wt = 16 site = IEA37Site(n_wt) windTurbines = IEA37_WindTurbines() windFarmModel = IEA37SimpleBastankhahGaussian(site, windTurbines) tf = TopFarmProblem( design_vars=dict(zip('xy', site.initial_position.T)), cost_comp=PyWakeAEPCostModelComponent(windFarmModel, n_wt), driver=EasyRandomSearchDriver(randomize_func=RandomizeTurbinePosition_Circle(), max_iter=5), constraints=[CircleBoundaryConstraint([0, 0], 1300.1)], plot_comp=XYPlotComp()) tf.optimize() tf.plot_comp.show() main() ``` -------------------------------- ### Developer Installation of TOPFARM Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/installation Clones the TOPFARM repository from GitLab and installs it in editable mode, allowing for direct code modifications and testing. It also includes steps to install and set up pre-commit hooks for code formatting and linting. ```bash git clone https://gitlab.windenergy.dtu.dk/TOPFARM/TopFarm2.git cd TopFarm2 pip install -e . pip install pre-commit pre-commit install ``` -------------------------------- ### TopFarmProblem Optimization Example (Python) Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/_topfarm This Python code demonstrates how to set up and run an optimization problem using TopFarmProblem. It includes defining design variables, cost components, constraints, and an optimization driver. ```python import numpy as np from topfarm.drivers import EasyScipyOptimizeDriver from topfarm.topfarm import TopFarmProblem from topfarm.cost_models.dummy import DummyCost, DummyCostPlotComp from topfarm.constraint_components.spacing import SpacingConstraint from topfarm.constraint_components.boundary import XYBoundaryConstraint def main(): if __name__ == '__main__': initial = np.array([[6, 0], [6, -8], [1, 1]]) # initial turbine layouts optimal = np.array([[2.5, -3], [6, -7], [4.5, -3]]) # optimal turbine layouts boundary = np.array([(0, 0), (6, 0), (6, -10), (0, -10)]) # turbine boundaries desired = np.array([[3, -3], [7, -7], [4, -3]]) # desired turbine layouts drivers = [EasyScipyOptimizeDriver()] plot_comp = DummyCostPlotComp(optimal) tf = TopFarmProblem( design_vars=dict(zip('xy', initial.T)), cost_comp=DummyCost(optimal_state=desired, inputs=['x', 'y']), constraints=[XYBoundaryConstraint(boundary), SpacingConstraint(2) ], driver=drivers[0], plot_comp=plot_comp ) cost, _, recorder = tf.optimize() plot_comp.show() main() ``` -------------------------------- ### Update Anaconda Environment Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/installation.rst Updates all packages within the root Anaconda environment. This command ensures that all installed packages are at their latest compatible versions. ```bash conda update --all ``` -------------------------------- ### Configure Wind Farm Site and Optimization Problem Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/bathymetry Sets up the wind farm site using `ParqueFicticioOffshore`, defines turbine parameters, and creates a cost function that calculates Annual Energy Production (AEP) and water depth. It then configures the `TopFarmProblem` with design variables, constraints, and an optimization driver. ```python #setting up the site and the initial position of turbines site = ParqueFicticioOffshore() site.bounds = 'ignore' x_init, y_init = site.initial_position[:,0], site.initial_position[:,1] boundary = site.boundary #Wind turbines and wind farm model definition windTurbines = IEA37_WindTurbines() wfm = IEA37SimpleBastankhahGaussian(site, windTurbines) #parameters for the AEP calculation wsp = np.asarray([10, 15]) dir = np.arange(0,360,45) maximum_water_depth = -52 #[m] n_wt = x_init.size def aep_func(x, y, **kwargs): simres = wfm(x, y, wd=wdir, ws=wsp) aep = simres.aep().values.sum() water_depth = np.diag(wfm.site.ds.interp(x=x, y=y)['water_depth']) return [aep, water_depth] #parameters for the optimization problem tol = 1e-8 ec = 1e-2 min_spacing = 260 maxiter = 30 #Cost model component and Topfarm problem cost_comp = CostModelComponent(input_keys=[('x', x_init),('y', y_init)], n_wt=n_wt, cost_function=aep_func, objective=True, maximize=True, output_keys=[('AEP', 0), ('water_depth', np.zeros(n_wt))] ) problem = TopFarmProblem(design_vars={'x': x_init, 'y': y_init}, constraints=[XYBoundaryConstraint(boundary), SpacingConstraint(min_spacing)], post_constraints=[('water_depth', {'lower': maximum_water_depth})], n_wt = n_wt, cost_comp=cost_comp, driver=EasyScipyOptimizeDriver(optimizer='SLSQP', maxiter=maxiter, tol=tol), plot_comp=XYPlotComp(), expected_cost=ec) ``` -------------------------------- ### Initialize EasySGDDriver Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/easy_drivers Provides an easy initialization for the Stochastic Gradient Descent (SGD) Driver. It sets parameters like maximum iterations, learning rate, and constraint aggregation multipliers. Dependencies include SGDDriver and EasyDriverBase. ```python class EasySGDDriver(SGDDriver, EasyDriverBase): def __init__(self, maxiter=100, disp=False, run_parallel=False, learning_rate=10, upper=0.1, lower=0, beta1=0.1, beta2=0.2, gamma_min_factor=1e-2, speedupSGD=False, sgd_thresh=0.1, additional_constant_lr_iterations=0): """Easy initialization of Stochastic Gradient Descent (SGD) Driver Parameters ---------- maxiter : int, optional Maximum iterations max_time : int Maximum evaluation time in seconds learning_rate : int, optional determines the step size gamma_min_factor : int, optional initial value for constraint aggregation multiplier """ # self.T = T self.learning_rate = learning_rate self.upper = upper self.lower = lower self.beta1 = beta1 self.beta2 = beta2 self.gamma_min_factor = gamma_min_factor self.gamma_min = gamma_min_factor # * learning_rate self.additional_constant_lr_iterations = additional_constant_lr_iterations SGDDriver.__init__(self, maxiter=maxiter, disp=disp, run_parallel=run_parallel, speedupSGD=speedupSGD, sgd_thresh=sgd_thresh, additional_constant_lr_iterations=additional_constant_lr_iterations) ``` -------------------------------- ### Install TopFarm Python Package Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/nested_optimization_type_and_positions Installs the TopFarm2 Python package from a Git repository if it's not already found in the current environment. This is a prerequisite for running the optimization examples. ```python import importlib if not importlib.util.find_spec("topfarm"): %pip install git+https://gitlab.windenergy.dtu.dk/TOPFARM/TopFarm2.git ``` -------------------------------- ### Set up and Run TopFarmProblem - Python Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/problems Constructs the TopFarmProblem, defining the design variables (x, y), cost component (AEP), constraints, and the optimization driver (EasyScipyOptimizeDriver). It then runs the optimization process. ```python problem = TopFarmProblem(design_vars={'x': x, 'y': y}, n_wt=n_wt, cost_comp=aep_comp, constraints=constraint, driver=EasyScipyOptimizeDriver(disp=False), plot_comp=XYPlotComp() ) _, state,_ = problem.optimize() ``` -------------------------------- ### Initialize Turbine and Substation Geometry Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/cables.ipynb Generates initial random positions for turbines and a single substation within defined boundaries. This setup is used as the starting point for the optimization process. ```python rng1 = np.random.default_rng(1) rng2 = np.random.default_rng(2) initial = np.asarray([rng1.random(n_wt)*(x_max-x_min)+x_min, rng2.random(n_wt)*(y_max-y_min)+y_min]).T x_init = initial[:,0] y_init = initial[:,1] x_ss_init = x_init.mean() y_ss_init = y_init.mean() turbines_pos=np.asarray([x_init, y_init]).T substations_pos = np.asarray([[x_ss_init], [y_ss_init]]).T boundary = np.array([(x_min, y_min), (x_max, y_min), (x_max, y_max), (x_min, y_max)]) # turbine boundaries ``` -------------------------------- ### Alternative PyWakeAEPCostModelComponent Setup (Python) Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/problems.ipynb Demonstrates an alternative approach using `PyWakeAEPCostModelComponent` for defining the cost model. This wrapper simplifies the integration of PyWake's AEP calculations directly into TopFarm's optimization framework. ```python from py_wake.deficit_models.gaussian import IEA37SimpleBastankhahGaussian #wake model from py_wake.examples.data.iea37 import IEA37_WindTurbines, IEA37Site #wind turbines and site used from topfarm.cost_models.py_wake_wrapper import PyWakeAEPCostModelComponent #cost model #creating a function to simulate the flow conditions of the IEA37 Site, specifying the desired number of turbines and wind directions def get_iea37_cost(n_wt=9, n_wd=16): ``` -------------------------------- ### Create and Activate Anaconda Environment Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/installation.rst Creates a new Anaconda environment named 'topfarm' with a Python version less than 3.12, and then activates this environment. This is recommended to avoid dependency conflicts. ```bash conda create --name topfarm "python<3.12" conda activate topfarm ``` -------------------------------- ### Setup XYBoundaryConstraint in Optimization Problem Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/constraint_components/boundary Sets up the XYBoundaryConstraint within a TopFarm optimization problem. This involves getting the appropriate boundary component, assigning the problem to it, and adjusting the design variable limits to enforce the spatial constraints. ```python def _setup(self, problem, group='constraint_group'): n_wt = problem.n_wt self.boundary_comp = self.get_comp(n_wt) self.boundary_comp.problem = problem self.set_design_var_limits(problem.design_vars) # problem.xy_boundary = np.r_[self.boundary_comp.xy_boundary, self.boundary_comp.xy_boundary[:1]] ``` -------------------------------- ### Initialize IPOPT Driver with pyOptSparse Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/easy_drivers Initializes the EasyPyOptSparseIPOPT driver, which uses the IPOPT optimizer from pyOptSparse. It allows setting the maximum number of iterations and a flag for expecting infeasible problems. ```Python class EasyPyOptSparseIPOPT(pyOptSparseDriver): def __init__(self, max_iter=200): pyOptSparseDriver.__init__(self) self.options.update({'optimizer': 'IPOPT'}) self.opt_settings.update( {"max_iter": max_iter, "expect_infeasible_problem": "yes"} ) ``` -------------------------------- ### Install Python Packages with Pip Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/drivers.ipynb Checks if specified Python packages are installed and installs them if they are not. It uses the `subprocess` module to run `pip install` commands. This is useful for ensuring all project dependencies are met before execution. ```python import sys import subprocess def check_and_install(package): try: __import__(package) print(f"{package} is already installed.") except ImportError: print(f"{package} is not installed. Installing...") subprocess.check_call([sys.executable, "-m", "pip", "install", package]) # List of packages to check and install packages = ["openmdao[doe]", "pyDOE2"] for pkg in packages: check_and_install(pkg) ``` -------------------------------- ### Setup Site and Wind Farm Model Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/regular_grid_optimization.ipynb Initializes the wind farm site, turbine model, and wind farm simulation model. It defines the number of turbines, boundary conditions, and stagger distance for a regular grid layout. ```python #specifying the site and wind turbines to use site = Hornsrev1Site() wt = V80() D = wt.diameter() windFarmModel = BastankhahGaussian(site, wt) n_wt = 16 boundary = [[-800,-50], [1200, -50], [1200,2300], [-800, 2300]] stagger = 1 * D #to create a staggered layout ``` -------------------------------- ### Setup Wind Farm Problem with Multiple Turbine Types Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/smart_start_with_predefined_types.ipynb Configures a TopFarmProblem instance for a wind farm with 16 turbines of three different types (T1, T2, T3). It defines the site, wind turbines with specific characteristics, and the cost component using PyWake for AEP calculation. Constraints for boundary and spacing are also included. ```python %%capture n_wt = 16 site = IEA37Site(n_wt) windTurbines = WindTurbines(names=['T1', 'T2', 'T3'], diameters=[110, 130, 150], hub_heights=[110, 130, 150], powerCtFunctions = [CubePowerSimpleCt(power_rated=200 * 110 ** 2, power_unit='W'), CubePowerSimpleCt(power_rated=200 * 130 ** 2, power_unit='W'), CubePowerSimpleCt(power_rated=200 * 150 ** 2, power_unit='W')],) windFarmModel = IEA37SimpleBastankhahGaussian(site, windTurbines) init_types = 5 * [2] + 6 * [1] + 5 *[0] tf = TopFarmProblem( design_vars=dict(zip('xy', site.initial_position.T)), cost_comp=PyWakeAEPCostModelComponent(windFarmModel, n_wt, additional_input=[('type', np.zeros(n_wt))], grad_method=None), driver=EasyScipyOptimizeDriver(maxiter=30), constraints=[CircleBoundaryConstraint([0, 0], 1300.1), SpacingTypeConstraint([windTurbines.diameter(t) * 3.5 for t in [0, 1, 2]])], plot_comp=XYPlotComp()) tf['type']=init_types x = np.linspace(-1300,1300,51) y = np.linspace(-1300,1300,51) YY, XX = np.meshgrid(y, x) ``` -------------------------------- ### Check and Install Python Packages Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/design_variables A utility function to check if a Python package is installed and install it using pip if it's not found. This helps manage project dependencies. ```python import subprocess import sys # check if a package is installed def check_and_install(package): try: __import__(package) print(f"{package} is already installed.") except ImportError: print(f"{package} is not installed. Installing...") subprocess.check_call([sys.executable, "-m", "pip", "install", package]) ``` -------------------------------- ### Install TopFarm and PyWake Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/bathymetry.ipynb Installs the TopFarm and PyWake libraries from GitLab. Includes logic to check if TopFarm is already installed and handles installation within a Google Colab environment. It also specifies a particular version of SciPy to avoid compatibility issues. ```python # Install TopFarm if needed import importlib if not importlib.util.find_spec("topfarm"): %pip install git+https://gitlab.windenergy.dtu.dk/TOPFARM/TopFarm2.git ``` ```python try: RunningInCOLAB = 'google.colab' in str(get_ipython()) except NameError: RunningInCOLAB = False ``` ```python %%capture if RunningInCOLAB: %pip install git+https://gitlab.windenergy.dtu.dk/TOPFARM/PyWake.git %pip install git+https://gitlab.windenergy.dtu.dk/TOPFARM/TopFarm2.git %pip install scipy==1.6.3 # constraint is not continuous which trips vers. 1.4.1 which presently is the default version import os os.kill(os.getpid(), 9) ``` -------------------------------- ### Initialize TopFarmProblem Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/api_reference/topfarmproblem Initializes the TopFarmProblem with design variables, cost component, driver, constraints, and other optional parameters. Design variables can be specified as dictionaries or lists of tuples, with options for initial values, bounds, and units. The cost component should be an OpenMDAO v2 ExplicitComponent or a TopFarmProblem/Group. Various drivers and constraint types are supported. ```python TopFarmProblem(design_vars, cost_comp=None, driver=, constraints=[], plot_comp=, record_id=None, expected_cost=1, ext_vars={}, approx_totals=False, recorder=None, additional_recorders=None, n_wt=0, grid_layout_comp=None, penalty_comp=None, reports=False, **kwargs) ``` -------------------------------- ### Set up wind farm model parameters using PyWake Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/design_variables.ipynb Initializes the wind farm simulation parameters including the number of turbines, number of wind directions, site definition, wind turbine model, and wind directions. This prepares the environment for wake effect calculations. ```python n_wt = 9 n_wd = 16 site = IEA37Site(9) wind_turbines = IEA37_WindTurbines() wd = np.linspace(0.,360.,n_wd, endpoint=False)wfmodel = IEA37SimpleBastankhahGaussian(site, wind_turbines) #PyWake's wind farm model ``` -------------------------------- ### Evaluate and Optimize Wind Farm Layouts Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/smart_start_with_predefined_types.ipynb This code block evaluates the initial wind farm layout, optimizes it, applies the smart start algorithm, and then evaluates and optimizes again. It compares the AEP costs for the initial layout, optimized layout, smart start layout, and smart start optimized layout. ```python # initial layout: cost1, state1 = tf.evaluate(dict(zip('xy', site.initial_position.T))) # initial layout + optimization: cost2, state2, recorder2 = tf.optimize() # smart start: tf.smart_start(XX, YY, tf.cost_comp.get_aep4smart_start(type=init_types), seed=42) cost3, state3 = tf.evaluate() # smart start + optimization: cost4, state4, recorder4 = tf.optimize() ``` -------------------------------- ### Import TopFarm2 Core Components and Examples Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/problems.ipynb This code imports key classes and functions from the TopFarm2 library. It includes `TopFarmProblem` for defining optimization problems, `EasyScipyOptimizeDriver` for setting up optimization drivers, functions for the IEA37 benchmark (`get_iea37_initial`, `get_iea37_constraints`, `get_iea37_cost`), and plotting components (`NoPlot`, `XYPlotComp`). ```python from topfarm import TopFarmProblem from topfarm.easy_drivers import EasyScipyOptimizeDriver from topfarm.examples.iea37 import get_iea37_initial, get_iea37_constraints, get_iea37_cost from topfarm.plotting import NoPlot, XYPlotComp ``` -------------------------------- ### Setup Wind Farm Problem with Multiple Turbine Types Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/smart_start_with_predefined_types Configures a TopFarm problem with a site and three different generic turbine types. It defines the number of each turbine type, their properties (diameter, hub height, power/CT functions), and sets up the wind farm model using a Gaussian deficit model. Constraints like circular boundary and spacing are also defined. ```python import numpy as np from topfarm._topfarm import TopFarmProblem from topfarm.constraint_components.boundary import CircleBoundaryConstraint from topfarm.constraint_components.spacing import SpacingTypeConstraint from topfarm.plotting import XYPlotComp from topfarm.easy_drivers import EasyScipyOptimizeDriver from topfarm.cost_models.py_wake_wrapper import PyWakeAEPCostModelComponent from py_wake.examples.data.iea37._iea37 import IEA37Site from py_wake.deficit_models.gaussian import IEA37SimpleBastankhahGaussian from py_wake.wind_turbines import WindTurbines from py_wake.wind_turbines.power_ct_functions import CubePowerSimpleCt %%capture n_wt = 16 site = IEA37Site(n_wt) windTurbines = WindTurbines(names=['T1', 'T2', 'T3'], diameters=[110, 130, 150], hub_heights=[110, 130, 150], powerCtFunctions = [CubePowerSimpleCt(power_rated=200 * 110 ** 2, power_unit='W'), CubePowerSimpleCt(power_rated=200 * 130 ** 2, power_unit='W'), CubePowerSimpleCt(power_rated=200 * 150 ** 2, power_unit='W')],) windFarmModel = IEA37SimpleBastankhahGaussian(site, windTurbines) init_types = 5 * [2] + 6 * [1] + 5 *[0] # 5 x T1, 6 x T2, 5 x T3 tf = TopFarmProblem( design_vars=dict(zip('xy', site.initial_position.T)), cost_comp=PyWakeAEPCostModelComponent(windFarmModel, n_wt, additional_input=[('type', np.zeros(n_wt))], grad_method=None), driver=EasyScipyOptimizeDriver(maxiter=30), constraints=[CircleBoundaryConstraint([0, 0], 1300.1), SpacingTypeConstraint([windTurbines.diameter(t) * 3.5 for t in [0, 1, 2]])], plot_comp=XYPlotComp()) tf['type']=init_types x = np.linspace(-1300,1300,51) y = np.linspace(-1300,1300,51) YY, XX = np.meshgrid(y, x) ``` -------------------------------- ### Import TopFarm2 and PyWake Components Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/smart_start_with_predefined_types.ipynb Imports necessary modules from TopFarm2 and PyWake for setting up and running wind farm simulations. This includes classes for problem definition, constraints, cost models, drivers, and specific wind farm and turbine models. ```python import numpy as np from topfarm._topfarm import TopFarmProblem from topfarm.constraint_components.boundary import CircleBoundaryConstraint from topfarm.constraint_components.spacing import SpacingTypeConstraint from topfarm.plotting import XYPlotComp from topfarm.easy_drivers import EasyScipyOptimizeDriver from topfarm.cost_models.py_wake_wrapper import PyWakeAEPCostModelComponent from py_wake.examples.data.iea37._iea37 import IEA37Site from py_wake.deficit_models.gaussian import IEA37SimpleBastankhahGaussian from py_wake.wind_turbines import WindTurbines from py_wake.wind_turbines.power_ct_functions import CubePowerSimpleCt ``` -------------------------------- ### Check and Install Python Package Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/drivers.ipynb A Python function to check if a specified package is installed and install it if it's missing. This is useful for managing dependencies within a project. It uses `__import__` to check for the package's existence. ```python import subprocess import sys # check if a package is installed def check_and_install(package): try: __import__(package) ``` -------------------------------- ### Setup Site, Exclusion Zone, and Wind Farm Model Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/exclusion_zones Initializes the wind farm site, defines initial turbine positions, and sets up the wind farm model using IEA37 turbines and a Gaussian deficit model. It also prepares parameters for Annual Energy Production (AEP) calculation and defines the exclusion zone based on maximum water depth. ```python #setting up the site and the initial position of turbines site = ParqueFicticioOffshore() site.bounds = 'ignore' x_init, y_init = site.initial_position[:, 0], site.initial_position[:, 1] boundary = site.boundary # Wind turbines and wind farm model definition windTurbines = IEA37_WindTurbines() wfm = IEA37SimpleBastankhahGaussian(site, windTurbines) #parameters for the AEP calculation wsp = np.asarray([10, 15]) dir = np.arange(0, 360, 45) n_wt = x_init.size #setting up the exclusion zone maximum_water_depth = -52 values = site.ds.water_depth.values x = site.ds.x.values y = site.ds.y.values levels = np.arange(int(values.min()), int(values.max())) max_wd_index = np.argwhere(levels == maximum_water_depth).item() cs = plt.contour(x, y, values.T, levels) lines = [] if max_wd_index < len(cs.allsegs): for line in cs.allsegs[max_wd_index]: lines.append(line) else: print("Maximum water depth index is out of range.") plt.close() ``` -------------------------------- ### Check and Install Python Packages Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/design_variables.ipynb A utility function to check if a specified Python package is installed and installs it using pip if it's not found. This is used to ensure dependencies like openmdao and pyDOE2 are available. ```python import subprocess import sys # check if a package is installed def check_and_install(package): try: __import__(package) print(f"{package} is already installed.") except ImportError: print(f"{package} is not installed. Installing...") subprocess.check_call([sys.executable, "-m", "pip", "install", package]) # List of packages to check and install packages = ["openmdao[doe]", "pyDOE2"] for pkg in packages: check_and_install(pkg) ``` -------------------------------- ### Setup Economic Model for Offshore Wind Plants (Python) Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/economic_cost_models.ipynb Configures an economic model for offshore wind plants using the OffshoreWindPlantFinanceWrapper. It sets parameters like lifetime and electricity price, then runs the cost model to calculate outputs based on AEP and water depth. ```python # Economic LIFETIME = 25 el_price = np.random.uniform(0, 6, LIFETIME) # time series el_price = 6 # fixed ppa price npv_comp = OffshoreWindPlantFinanceWrapper(windTurbines, n_wt, el_price, LIFETIME) cost_model = npv_comp.cost_model out = cost_model.run(aep=373206.64521435613, water_depth=20.0) print(out) ``` -------------------------------- ### Setup Penalty Group Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_modules/topfarm/constraint_components/boundary Sets up a boundary component to be used as a penalty in the optimization problem. This method calls the internal setup logic. ```python def setup_as_penalty(self, problem, group='constraint_group'): self._setup(problem, group=group) ``` -------------------------------- ### Setup Cost Model for Optimization (Python) Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/_sources/notebooks/joint_multi_wf_optimization.ipynb Configures a cost model using PyWake's AEP calculations for wind farm optimization. Supports Stochastic Gradient Descent (SGD) and Sequential Least Squares Programming (SLSQP). Allows for AEP calculation on partial wind speed and direction samples for SGD. ```python np.random.seed(42) # Wind Resouces full_wd = np.arange(0, 360, 1) # wind directions full_ws = np.arange(3, 25, 1) # wind speeds freqs = site.local_wind( # sector frequencies X_full, Y_full, wd=full_wd, ws=full_ws, ).Sector_frequency_ilk[0, :, 0] # weibull parameters As = site.local_wind(X_full, Y_full, wd=full_wd, ws=full_ws).Weibull_A_ilk[0, :, 0] ``` -------------------------------- ### Setup and Run TopFarmProblem Optimization Source: https://topfarm.pages.windenergy.dtu.dk/TopFarm2/notebooks/joint_multi_wf_optimization Creates a TopFarmProblem instance with defined design variables, constraints, cost component, and driver. It then executes the optimization process using the `problem.optimize()` method, returning the cost, state, and recorder. ```python problem = TopFarmProblem( design_vars={"x": X_full, "y": Y_full}, n_wt=n_wt, constraints=constraints, cost_comp=cost_comp, driver=driver, plot_comp=XYPlotComp(), ) cost, state, recorder = problem.optimize(disp=True) ```