Example #1
0
def run(default_config: Dict) -> None:
    config, output_path, run_name = setup_run(default_config)
    recorder = DataRecorder.make_data_recorder(output_path)
    
    max_evaluations = config['max_evaluations']
    optimizer_config = config['optimizer_config']
    
    site_info = SiteInfo(flatirons_site)
    inner_problem = WindOptimizationProblem(site_info, config['num_turbines'])
    problem = WindParametrization(inner_problem)
    
    optimizer = ParametrizedOptimizationDriver(problem, recorder=recorder, **optimizer_config)
    
    figure = plt.figure(1)
    ax = figure.add_subplot(111)
    plt.grid()
    plt.tick_params(which='both', labelsize=15)
    plt.xlabel('x (m)', fontsize=15)
    plt.ylabel('y (m)', fontsize=15)
    site_info.plot()
    
    score, evaluation, best_solution = optimizer.central_solution()
    score, evaluation = problem.objective(best_solution) if score is None else score
    
    print(-1, ' ', score)
    
    optimizer.problem.plot_candidate(best_solution, (1.0, 0, 0), .2)
    
    prev = optimizer.best_solution()[1]
    try:
        while optimizer.num_evaluations() < max_evaluations:
            print('step start')
            optimizer.step()
            print('step end')

            proportion = min(1.0, optimizer.num_evaluations() / max_evaluations)
            g = 1.0 * proportion
            b = 1.0 - g
            a = .5
            color = (b, g, b)
            score, eval, best = optimizer.best_solution()
            score = problem.objective(best) if score is None else score
            problem.plot_candidate(best, color, .3)
            prev = best
            print(optimizer.num_iterations(), ' ', optimizer.num_evaluations(), score)

    except:
        raise RuntimeError("Optimizer error encountered. Try modifying the config to use larger generation_size if"
                           " encountering singular matrix errors.")

    print('best: ', optimizer.best_solution().__repr__())
    optimizer.problem.plot_candidate(optimizer.best_solution()[2], (0, 0, 0), 1.0)

    # Create the figure
    legend_elements = [Line2D([0], [0], marker='o', color='w', markerfacecolor=(0, 0, 0), label='Optimal')]
    plt.legend(handles=legend_elements)
    plt.show()
    
    optimizer.close()
Example #2
0
def test_create_grid():
    site_info = SiteInfo(flatirons_site)
    bounding_shape = site_info.polygon.buffer(-200)
    site_info.plot()
    turbine_positions = create_grid(bounding_shape, site_info.polygon.centroid,
                                    np.pi / 4, 200, 200, .5)
    expected_positions = [[242., 497.], [383., 355.], [312.,
                                                       709.], [454., 568.],
                          [595., 426.], [525., 780.], [666., 638.],
                          [737., 850.], [878., 709.]]
    for n, t in enumerate(turbine_positions):
        assert (t.x == pytest.approx(expected_positions[n][0], 1e-1))
        assert (t.y == pytest.approx(expected_positions[n][1], 1e-1))
Example #3
0
def run(default_config: Dict) -> None:
    config, output_path, run_name = setup_run(default_config)
    recorder = DataRecorder.make_data_recorder(output_path)

    max_evaluations = config['max_evaluations']
    
    location_index = config['location']
    location = locations[location_index]
    
    site = config['site']
    site_data = None
    if site == 'circular':
        site_data = make_circular_site(lat=location[0], lon=location[1], elev=location[2])
    elif site == 'irregular':
        site_data = make_irregular_site(lat=location[0], lon=location[1], elev=location[2])
    else:
        raise Exception("Unknown site '" + site + "'")
    
    site_info = SiteInfo(site_data)
    inner_problem = HybridOptimizationProblem(site_info, config['num_turbines'], config['solar_capacity'])
    problem = HybridParametrization(inner_problem)
    
    optimizer = ParametrizedOptimizationDriver(problem, recorder=recorder, **config['optimizer_config'])
    
    figure = plt.figure(1)
    axes = figure.add_subplot(111)
    axes.set_aspect('equal')
    plt.grid()
    plt.tick_params(which='both', labelsize=15)
    plt.xlabel('x (m)', fontsize=15)
    plt.ylabel('y (m)', fontsize=15)
    site_info.plot()

    score, evaluation, best_solution = optimizer.central_solution()
    score, evaluation = problem.objective(best_solution) if score is None else score
    
    print(-1, ' ', score, evaluation)
    
    print('setup 1')
    
    num_substeps = 1
    figure, axes = plt.subplots(dpi=200)
    axes.set_aspect(1)
    animation_writer = PillowWriter(2 * num_substeps)
    animation_writer.setup(figure, os.path.join(output_path, 'trajectory.gif'), dpi=200)
    
    print('setup 2')
    _, _, central_solution = optimizer.central_solution()
    
    print('setup 3')
    bounds = problem.inner_problem.site_info.polygon.bounds
    site_sw_bound = np.array([bounds[0], bounds[1]])
    site_ne_bound = np.array([bounds[2], bounds[3]])
    site_center = .5 * (site_sw_bound + site_ne_bound)
    max_delta = max(bounds[2] - bounds[0], bounds[3] - bounds[1])
    reach = (max_delta / 2) * 1.3
    min_plot_bound = site_center - reach
    max_plot_bound = site_center + reach
    
    print('setup 4')
    
    best_score, best_evaluation, best_solution = 0.0, 0.0, None
    
    def plot_candidate(candidate):
        nonlocal best_score, best_evaluation, best_solution
        axes.cla()
        axes.set(xlim=(min_plot_bound[0], max_plot_bound[0]), ylim=(min_plot_bound[1], max_plot_bound[1]))
        wind_color = (153 / 255, 142 / 255, 195 / 255)
        solar_color = (241 / 255, 163 / 255, 64 / 255)
        central_color = (.5, .5, .5)
        conforming_candidate, _, __ = problem.make_conforming_candidate_and_get_penalty(candidate)
        problem.plot_candidate(conforming_candidate, figure, axes, central_color, central_color, alpha=.7)
        
        if best_solution is not None:
            conforming_best, _, __ = problem.make_conforming_candidate_and_get_penalty(best_solution)
            problem.plot_candidate(conforming_best, figure, axes, wind_color, solar_color, alpha=1.0)
            axes.set_xlabel('Best Solution AEP: {}'.format(best_evaluation))
        else:
            axes.set_xlabel('')
        
        axes.legend([
            Line2D([0], [0], color=wind_color, lw=8),
            Line2D([0], [0], color=solar_color, lw=8),
            Line2D([0], [0], color=central_color, lw=8),
            ],
            ['Wind Layout', 'Solar Layout', 'Mean Search Vector'],
            loc='lower left')
        animation_writer.grab_frame()
    
    print('plot candidate')
    
    plot_candidate(central_solution)
    
    central_prev = central_solution
    # TODO: make a smooth transition between points
    # TODO: plot exclusion zones
    print('begin')

    try:
        while optimizer.num_evaluations() < max_evaluations:

            print('step start')
            logger.info("Starting step, num evals {}".format(optimizer.num_evaluations()))
            optimizer.step()
            print('step end')

            proportion = min(1.0, optimizer.num_evaluations() / max_evaluations)
            g = 1.0 * proportion
            b = 1.0 - g
            a = .5
            color = (b, g, b)
            best_score, best_evaluation, best_solution = optimizer.best_solution()
            central_score, central_evaluation, central_solution = optimizer.central_solution()

            a1 = optimizer.converter.convert_from(central_prev)
            b1 = optimizer.converter.convert_from(central_solution)
            a = np.array(a1, dtype=np.float64)
            b = np.array(b1, dtype=np.float64)

            for i in range(num_substeps):
                p = (i + 1) / num_substeps
                c = (1 - p) * a + p * b
                candidate = optimizer.converter.convert_to(c)
                plot_candidate(candidate)

            central_prev = central_solution
            print(optimizer.num_iterations(), ' ', optimizer.num_evaluations(), best_score, best_evaluation)
    except:
        raise RuntimeError("Optimizer error encountered. Try modifying the config to use larger generation_size if"
                           " encountering singular matrix errors.")

    animation_writer.finish()

    optimizer.close()

    print("Results and animation written to " + os.path.abspath(output_path))