コード例 #1
0
    def run(
        self,
        run_mode,
        initial_guess=None,
        bounds=None,
        signal_window=None,
        optimization_method=None,
    ):
        self.logger.run_mode = run_mode
        # 1. define control
        # `time_grid` defines the time grid for the direct simulation
        self.time_grid = TimeSeries.from_parameters(
            Decimal("0"), self.timer["T"], self.timer["dt"]
        )
        # `midpoint_grid` defines the time grid for the adjoint simulation
        self.midpoint_grid = TimeSeries.from_parameters(
            Decimal("0.5") * Decimal(self.timer["dt"]),
            self.timer["T"] - Decimal("0.5") * Decimal(self.timer["dt"]),
            self.timer["dt"],
        )
        # We define a control space, a PiecewiseLinearBasis in this case
        self.basis = PiecewiseLinearBasis(
            np.array([float(key) for key in self.time_grid.keys()]),
            width=signal_window,
            reduced_basis=True,
        )

        # We prepare the initial guess and bounds on the control
        if bounds is not None:
            low_bound = [bounds[0] for _ in range(len(self.time_grid))]
            top_bound = [bounds[1] for _ in range(len(self.time_grid))]
            top_bound = self.basis.discretize(top_bound)
            low_bound = self.basis.discretize(low_bound)
            bounds = list(zip(low_bound, top_bound))

        if initial_guess is None:
            initial_guess = np.zeros(len(self.basis.basis))

        if run_mode == "optimization":
            res = self.minimize(
                initial_guess, bounds, optimization_method=optimization_method
            )
        elif run_mode == "single_run":
            res = self._objective_state(initial_guess)
        elif run_mode == "direct_adjoint":
            res = self._objective_state(initial_guess)
            grad = self._jacobian(res)
        else:
            log.warning(f"The run mode {run_mode} is not implemented")
            res = None

        return res
コード例 #2
0
def test_from_parameters():
    start = decimal.Decimal("1")
    stop = decimal.Decimal("2")
    step = decimal.Decimal("0.1")

    series = TimeSeries.from_parameters(start, stop, step)
    assert series.first == 0
    assert series.last == 0
    for i in range(11):
        assert series[start + i * step] == 0
    assert series[stop] == 0

    midpoint_grid = TimeSeries.from_parameters(
        start + decimal.Decimal("0.5") * step,
        stop - decimal.Decimal("0.5") * step,
        step,
    )
    assert len(midpoint_grid) == 10
    assert start + decimal.Decimal("0.5") * step in midpoint_grid
    assert stop - decimal.Decimal("0.5") * step in midpoint_grid