示例#1
0
def test_pidon_operator_on_spherical_pde():
    set_random_seed(0)

    diff_eq = DiffusionEquation(3)
    mesh = Mesh(
        [(1., 11.), (0., 2 * np.pi), (.25 * np.pi, .75 * np.pi)],
        [2., np.pi / 5., np.pi / 4],
        CoordinateSystem.SPHERICAL)
    bcs = [
        (DirichletBoundaryCondition(
            lambda x, t: np.ones((len(x), 1)), is_static=True),
         DirichletBoundaryCondition(
             lambda x, t: np.full((len(x), 1), 1. / 11.), is_static=True)),
        (NeumannBoundaryCondition(
            lambda x, t: np.zeros((len(x), 1)), is_static=True),
         NeumannBoundaryCondition(
             lambda x, t: np.zeros((len(x), 1)), is_static=True)),
        (NeumannBoundaryCondition(
            lambda x, t: np.zeros((len(x), 1)), is_static=True),
         NeumannBoundaryCondition(
             lambda x, t: np.zeros((len(x), 1)), is_static=True))
    ]
    cp = ConstrainedProblem(diff_eq, mesh, bcs)
    ic = ContinuousInitialCondition(cp, lambda x: 1. / x[:, :1])
    t_interval = (0., .5)
    ivp = InitialValueProblem(cp, t_interval, ic)

    sampler = UniformRandomCollocationPointSampler()
    pidon = PIDONOperator(sampler, .001, True)

    training_loss_history, test_loss_history = pidon.train(
        cp,
        t_interval,
        training_data_args=DataArgs(
            y_0_functions=[ic.y_0],
            n_domain_points=20,
            n_boundary_points=10,
            n_batches=1
        ),
        model_args=ModelArgs(
            latent_output_size=20,
            branch_hidden_layer_sizes=[30, 30],
            trunk_hidden_layer_sizes=[30, 30],
        ),
        optimization_args=OptimizationArgs(
            optimizer=optimizers.Adam(learning_rate=2e-5),
            epochs=3,
            verbose=False
        )
    )

    assert len(training_loss_history) == 3
    for i in range(2):
        assert np.all(
            training_loss_history[i + 1].weighted_total_loss.numpy() <
            training_loss_history[i].weighted_total_loss.numpy())

    solution = pidon.solve(ivp)
    assert solution.d_t == .001
    assert solution.discrete_y().shape == (500, 6, 11, 3, 1)
示例#2
0
def test_beta_initial_condition_with_wrong_number_of_alpha_and_betas():
    diff_eq = DiffusionEquation(1)
    mesh = Mesh([(0., 1.)], [.1])
    bcs = [(NeumannBoundaryCondition(lambda x: np.zeros((len(x), 1))), ) * 2]
    cp = ConstrainedProblem(diff_eq, mesh, bcs)
    with pytest.raises(ValueError):
        BetaInitialCondition(cp, [(1., 1.), (1., 1)])
示例#3
0
def test_continuous_initial_condition_1d_pde():
    diff_eq = DiffusionEquation(1)
    mesh = Mesh([(0., 20.)], [.1])
    bcs = [(DirichletBoundaryCondition(lambda x, t: np.zeros((len(x), 1)),
                                       is_static=True),
            DirichletBoundaryCondition(lambda x, t: np.full((len(x), 1), 1.5),
                                       is_static=True))]
    cp = ConstrainedProblem(diff_eq, mesh, bcs)
    initial_condition = ContinuousInitialCondition(
        cp, lambda x: np.exp(-np.square(np.array(x) - 10.) / (2 * 5**2)))

    assert np.isclose(initial_condition.y_0(np.full((1, 1), 10.)), 1.)
    assert np.isclose(
        initial_condition.y_0(np.full((1, 1),
                                      np.sqrt(50) + 10.)), np.e**-1)
    assert np.allclose(initial_condition.y_0(np.full((5, 1), 10.)),
                       np.ones((5, 1)))

    y_0_vertices = initial_condition.discrete_y_0(True)
    assert y_0_vertices.shape == (201, 1)
    assert y_0_vertices[0, 0] == 0.
    assert y_0_vertices[-1, 0] == 1.5
    assert y_0_vertices[100, 0] == 1.
    assert np.all(0. < y_0_vertices[1:100, 0]) \
        and np.all(y_0_vertices[1:100, 0] < 1.)
    assert np.all(0. < y_0_vertices[101:-1, 0]) \
        and np.all(y_0_vertices[101:-1, 0] < 1.)

    y_0_cell_centers = initial_condition.discrete_y_0(False)
    assert y_0_cell_centers.shape == (200, 1)
    assert np.all(0. < y_0_cell_centers) and np.all(y_0_cell_centers < 1.)
示例#4
0
def test_beta_initial_condition_with_more_than_1d_pde():
    diff_eq = DiffusionEquation(2)
    mesh = Mesh([(0., 1.), (0., 1.)], [.1, .1])
    bcs = [(NeumannBoundaryCondition(lambda x: np.zeros((len(x), 1))), ) * 2
           ] * 2
    cp = ConstrainedProblem(diff_eq, mesh, bcs)
    with pytest.raises(ValueError):
        BetaInitialCondition(cp, [(1., 1.), (1., 1)])
示例#5
0
def test_ode_operator_on_pde():
    diff_eq = DiffusionEquation(1, 1.5)
    mesh = Mesh([(0., 10.)], [.1])
    bcs = [
        (NeumannBoundaryCondition(lambda x, t: np.zeros((len(x), 1))),
         DirichletBoundaryCondition(lambda x, t: np.zeros((len(x), 1)))),
    ]
    cp = ConstrainedProblem(diff_eq, mesh, bcs)
    ic = GaussianInitialCondition(cp, [(np.array([5.]), np.array([[2.5]]))],
                                  [20.])
    ivp = InitialValueProblem(cp, (0., 10.), ic)
    op = ODEOperator('RK23', 2.5e-3)
    with pytest.raises(ValueError):
        op.solve(ivp)
def test_cp_pde_with_wrong_boundary_constraint_length():
    diff_eq = DiffusionEquation(2)
    mesh = Mesh([(0., 5.), (-5., 5.)], [.1, .2])
    static_bcs = [(DirichletBoundaryCondition(lambda x, t: np.zeros((13, 1)),
                                              is_static=True), ) * 2] * 2
    with pytest.raises(ValueError):
        ConstrainedProblem(diff_eq, mesh, static_bcs)

    dynamic_bcs = [
        (DirichletBoundaryCondition(lambda x, t: np.zeros((13, 1))), ) * 2
    ] * 2
    cp = ConstrainedProblem(diff_eq, mesh, dynamic_bcs)
    with pytest.raises(ValueError):
        cp.create_boundary_constraints(True, 0.)
示例#7
0
def test_fdm_operator_on_spherical_pde():
    diff_eq = DiffusionEquation(3)
    mesh = Mesh([(1., 11.), (0., 2. * np.pi), (.1 * np.pi, .9 * np.pi)],
                [2., np.pi / 5., np.pi / 5], CoordinateSystem.SPHERICAL)
    bcs = [(NeumannBoundaryCondition(lambda x, t: np.zeros((len(x), 1)),
                                     is_static=True),
            NeumannBoundaryCondition(lambda x, t: np.zeros((len(x), 1)),
                                     is_static=True))] * 3
    cp = ConstrainedProblem(diff_eq, mesh, bcs)
    ic = ContinuousInitialCondition(cp, lambda x: 1. / x[:, :1])
    ivp = InitialValueProblem(cp, (0., 5.), ic)
    op = FDMOperator(RK4(), ThreePointCentralDifferenceMethod(), .1)
    solution = op.solve(ivp)

    assert solution.vertex_oriented
    assert solution.d_t == .1
    assert solution.discrete_y().shape == (50, 6, 11, 5, 1)
    assert solution.discrete_y(False).shape == (50, 5, 10, 4, 1)
def test_cp_1d_pde():
    diff_eq = DiffusionEquation(1)
    mesh = Mesh([(0., 1.)], [.1])
    bcs = [(NeumannBoundaryCondition(lambda x, t: np.zeros((1, 1)),
                                     is_static=True), ) * 2]
    cp = ConstrainedProblem(diff_eq, mesh, bcs)

    assert cp.are_all_boundary_conditions_static
    assert not cp.are_there_boundary_conditions_on_y
    assert cp.y_shape(True) == (11, 1)
    assert cp.y_shape(False) == (10, 1)

    assert cp.differential_equation == diff_eq
    assert cp.mesh == mesh
    assert np.array_equal(cp.boundary_conditions, bcs)

    y_vertex_constraints = cp.static_y_vertex_constraints
    assert y_vertex_constraints.shape == (1, )
    assert np.all(y_vertex_constraints[0].mask == [False])
    assert np.all(y_vertex_constraints[0].values == [])

    vertex_boundary_constraints = cp.static_boundary_constraints(True)
    y_vertex_boundary_constraints = vertex_boundary_constraints[0]
    assert y_vertex_boundary_constraints.shape == (1, 1)
    assert y_vertex_boundary_constraints[0, 0][0] is None
    assert y_vertex_boundary_constraints[0, 0][1] is None
    d_y_vertex_boundary_constraints = vertex_boundary_constraints[1]
    assert d_y_vertex_boundary_constraints.shape == (1, 1)
    assert np.all(d_y_vertex_boundary_constraints[0, 0][0].mask == [True])
    assert np.all(d_y_vertex_boundary_constraints[0, 0][0].values == [0.])
    assert np.all(d_y_vertex_boundary_constraints[0, 0][1].mask == [True])
    assert np.all(d_y_vertex_boundary_constraints[0, 0][1].values == [0.])

    cell_boundary_constraints = cp.static_boundary_constraints(False)
    y_cell_boundary_constraints = cell_boundary_constraints[0]
    assert y_cell_boundary_constraints.shape == (1, 1)
    assert y_cell_boundary_constraints[0, 0][0] is None
    assert y_cell_boundary_constraints[0, 0][1] is None
    d_y_cell_boundary_constraints = cell_boundary_constraints[1]
    assert d_y_cell_boundary_constraints.shape == (1, 1)
    assert np.all(d_y_cell_boundary_constraints[0, 0][0].mask == [True])
    assert np.all(d_y_cell_boundary_constraints[0, 0][0].values == [0.])
    assert np.all(d_y_cell_boundary_constraints[0, 0][1].mask == [True])
    assert np.all(d_y_cell_boundary_constraints[0, 0][1].values == [0.])
示例#9
0
def test_fdm_operator_on_pde_with_dynamic_boundary_conditions():
    diff_eq = DiffusionEquation(1, 1.5)
    mesh = Mesh([(0., 10.)], [1.])
    bcs = [
        (NeumannBoundaryCondition(lambda x, t: np.zeros((len(x), 1))),
         DirichletBoundaryCondition(lambda x, t: np.full((len(x), 1), t / 5.))
         ),
    ]
    cp = ConstrainedProblem(diff_eq, mesh, bcs)
    ic = GaussianInitialCondition(cp, [(np.array([5.]), np.array([[2.5]]))],
                                  [20.])
    ivp = InitialValueProblem(cp, (0., 10.), ic)
    op = FDMOperator(RK4(), ThreePointCentralDifferenceMethod(), .5)
    solution = op.solve(ivp)
    y = solution.discrete_y()

    assert solution.vertex_oriented
    assert solution.d_t == .5
    assert y.shape == (20, 11, 1)
    assert solution.discrete_y(False).shape == (20, 10, 1)

    assert np.isclose(y[0, -1, 0], .1)
    assert np.isclose(y[-1, -1, 0], 2.)
def test_parareal_operator_on_pde():
    diff_eq = DiffusionEquation(2)
    mesh = Mesh([(0., 5.), (0., 5.)], [1., 1.])
    bcs = [(NeumannBoundaryCondition(lambda x, _: np.zeros((len(x), 1)),
                                     is_static=True),
            NeumannBoundaryCondition(lambda x, _: np.zeros((len(x), 1)),
                                     is_static=True))] * 2
    cp = ConstrainedProblem(diff_eq, mesh, bcs)
    ic = GaussianInitialCondition(
        cp, [(np.array([2.5, 2.5]), np.array([[1., 0.], [0., 1.]]))])
    ivp = InitialValueProblem(cp, (0., 5.), ic)

    f = FDMOperator(RK4(), ThreePointCentralDifferenceMethod(), .05)
    g = FDMOperator(RK4(), ThreePointCentralDifferenceMethod(), .5)
    p = PararealOperator(f, g, .005)

    f_solution = f.solve(ivp)
    p_solution = p.solve(ivp)

    assert p_solution.vertex_oriented == f_solution.vertex_oriented
    assert p_solution.d_t == f_solution.d_t
    assert np.array_equal(p_solution.t_coordinates, f_solution.t_coordinates)
    assert np.allclose(p_solution.discrete_y(), f_solution.discrete_y())
示例#11
0
def test_pidon_operator_in_ar_mode_training_with_dynamic_boundary_conditions():
    diff_eq = DiffusionEquation(1, .25)
    mesh = Mesh([(0., .5)], (.05,))
    bcs = [
        (NeumannBoundaryCondition(
            lambda x, t: np.full((len(x), 1), t), is_static=False),
         NeumannBoundaryCondition(
             lambda x, t: np.zeros((len(x), 1)), is_static=True)),
    ]
    cp = ConstrainedProblem(diff_eq, mesh, bcs)
    t_interval = (0., .5)
    y_0_functions = [lambda x: np.zeros((len(x), 1))]

    pidon = PIDONOperator(UniformRandomCollocationPointSampler(), .001, True)

    with pytest.raises(ValueError):
        pidon.train(
            cp,
            t_interval,
            training_data_args=DataArgs(
                y_0_functions=y_0_functions,
                n_domain_points=50,
                n_boundary_points=20,
                n_batches=2
            ),
            model_args=ModelArgs(
                latent_output_size=50,
                branch_hidden_layer_sizes=[50, 50],
                trunk_hidden_layer_sizes=[50, 50],
            ),
            optimization_args=OptimizationArgs(
                optimizer={'class_name': 'Adam'},
                epochs=3,
                ic_loss_weight=10.,
                verbose=False
            )
        )
示例#12
0
def test_fdm_operator_conserves_density_on_zero_flux_diffusion_equation():
    diff_eq = DiffusionEquation(1, 5.)
    mesh = Mesh([(0., 500.)], [.1])
    bcs = [
        (NeumannBoundaryCondition(lambda x, t: np.zeros((len(x), 1)),
                                  is_static=True),
         NeumannBoundaryCondition(lambda x, t: np.zeros((len(x), 1)),
                                  is_static=True)),
    ]
    cp = ConstrainedProblem(diff_eq, mesh, bcs)
    ic = GaussianInitialCondition(cp, [(np.array([250]), np.array([[250.]]))],
                                  [1000.])
    ivp = InitialValueProblem(cp, (0., 20.), ic)

    y_0 = ic.discrete_y_0(True)
    y_0_sum = np.sum(y_0)

    fdm_op = FDMOperator(CrankNicolsonMethod(),
                         ThreePointCentralDifferenceMethod(), 1e-3)
    solution = fdm_op.solve(ivp)
    y = solution.discrete_y()
    y_sums = np.sum(y, axis=tuple(range(1, y.ndim)))

    assert np.allclose(y_sums, y_0_sum)
示例#13
0
def test_pidon_operator_on_pde_with_dynamic_boundary_conditions():
    set_random_seed(0)

    diff_eq = DiffusionEquation(1, .25)
    mesh = Mesh([(0., 1.)], (.1,))
    bcs = [
        (NeumannBoundaryCondition(lambda x, t: np.full((len(x), 1), t)),
         NeumannBoundaryCondition(lambda x, t: np.full((len(x), 1), t))),
    ]
    cp = ConstrainedProblem(diff_eq, mesh, bcs)
    t_interval = (0., .5)

    training_y_0_functions = [
        BetaInitialCondition(cp, [(p, p)]).y_0 for p in [2., 3., 4., 5.]
    ]
    test_y_0_functions = [
        BetaInitialCondition(cp, [(p, p)]).y_0 for p in [2.5, 3.5, 4.5]
    ]

    sampler = UniformRandomCollocationPointSampler()
    pidon = PIDONOperator(sampler, .001, True)

    training_loss_history, test_loss_history = pidon.train(
        cp,
        t_interval,
        training_data_args=DataArgs(
            y_0_functions=training_y_0_functions,
            n_domain_points=50,
            n_boundary_points=20,
            n_batches=2
        ),
        test_data_args=DataArgs(
            y_0_functions=test_y_0_functions,
            n_domain_points=25,
            n_boundary_points=10,
            n_batches=1
        ),
        model_args=ModelArgs(
            latent_output_size=50,
            branch_hidden_layer_sizes=[50, 50],
            trunk_hidden_layer_sizes=[50, 50],
        ),
        optimization_args=OptimizationArgs(
            optimizer={
                'class_name': 'Adam',
                'config': {
                    'learning_rate': 1e-4
                }
            },
            epochs=3,
            ic_loss_weight=10.,
            verbose=False
        )
    )

    assert len(training_loss_history) == 3
    assert len(test_loss_history) == 3
    for i in range(2):
        assert training_loss_history[i + 1].weighted_total_loss.numpy() < \
            training_loss_history[i].weighted_total_loss.numpy()
        assert test_loss_history[i + 1].weighted_total_loss.numpy() < \
            test_loss_history[i].weighted_total_loss.numpy()

    ic = BetaInitialCondition(cp, [(3.5, 3.5)])
    ivp = InitialValueProblem(cp, t_interval, ic)

    solution = pidon.solve(ivp)
    assert solution.d_t == .001
    assert solution.discrete_y().shape == (500, 11, 1)