コード例 #1
0
def elliptic_demo(args):
    args['PROBLEM-NUMBER'] = int(args['PROBLEM-NUMBER'])
    assert 0 <= args['PROBLEM-NUMBER'] <= 1, ValueError('Invalid problem number')
    args['DIRICHLET-NUMBER'] = int(args['DIRICHLET-NUMBER'])
    assert 0 <= args['DIRICHLET-NUMBER'] <= 2, ValueError('Invalid Dirichlet boundary number.')
    args['NEUMANN-NUMBER'] = int(args['NEUMANN-NUMBER'])
    assert 0 <= args['NEUMANN-NUMBER'] <= 2, ValueError('Invalid Neumann boundary number.')
    args['NEUMANN-COUNT'] = int(args['NEUMANN-COUNT'])
    assert 0 <= args['NEUMANN-COUNT'] <= 3, ValueError('Invalid Neumann boundary count.')

    rhss = [ExpressionFunction('ones(x.shape[:-1]) * 10', 2, ()),
            ExpressionFunction('(x[..., 0] - 0.5) ** 2 * 1000', 2, ())]
    dirichlets = [ExpressionFunction('zeros(x.shape[:-1])', 2, ()),
                  ExpressionFunction('ones(x.shape[:-1])', 2, ()),
                  ExpressionFunction('x[..., 0]', 2, ())]
    neumanns = [None,
                ConstantFunction(3., dim_domain=2),
                ExpressionFunction('50*(0.1 <= x[..., 1]) * (x[..., 1] <= 0.2)'
                                   '+50*(0.8 <= x[..., 1]) * (x[..., 1] <= 0.9)', 2, ())]
    domains = [RectDomain(),
               RectDomain(right='neumann'),
               RectDomain(right='neumann', top='neumann'),
               RectDomain(right='neumann', top='neumann', bottom='neumann')]

    rhs = rhss[args['PROBLEM-NUMBER']]
    dirichlet = dirichlets[args['DIRICHLET-NUMBER']]
    neumann = neumanns[args['NEUMANN-NUMBER']]
    domain = domains[args['NEUMANN-COUNT']]

    problem = StationaryProblem(
        domain=domain,
        diffusion=ConstantFunction(1, dim_domain=2),
        rhs=rhs,
        dirichlet_data=dirichlet,
        neumann_data=neumann
    )

    for n in [32, 128]:
        print('Discretize ...')
        discretizer = discretize_stationary_fv if args['--fv'] else discretize_stationary_cg
        m, data = discretizer(
            analytical_problem=problem,
            grid_type=RectGrid if args['--rect'] else TriaGrid,
            diameter=np.sqrt(2) / n if args['--rect'] else 1. / n
        )
        grid = data['grid']
        print(grid)
        print()

        print('Solve ...')
        U = m.solve()
        m.visualize(U, title=repr(grid))
        print()
コード例 #2
0
ファイル: elliptic.py プロジェクト: simon-ca/pymor
def elliptic_demo(args):
    args['PROBLEM-NUMBER'] = int(args['PROBLEM-NUMBER'])
    assert 0 <= args['PROBLEM-NUMBER'] <= 1, ValueError('Invalid problem number')
    args['DIRICHLET-NUMBER'] = int(args['DIRICHLET-NUMBER'])
    assert 0 <= args['DIRICHLET-NUMBER'] <= 2, ValueError('Invalid Dirichlet boundary number.')
    args['NEUMANN-NUMBER'] = int(args['NEUMANN-NUMBER'])
    assert 0 <= args['NEUMANN-NUMBER'] <= 2, ValueError('Invalid Neumann boundary number.')
    args['NEUMANN-COUNT'] = int(args['NEUMANN-COUNT'])
    assert 0 <= args['NEUMANN-COUNT'] <= 3, ValueError('Invalid Neumann boundary count.')

    rhss = [GenericFunction(lambda X: np.ones(X.shape[:-1]) * 10, 2),
            GenericFunction(lambda X: (X[..., 0] - 0.5) ** 2 * 1000, 2)]
    dirichlets = [GenericFunction(lambda X: np.zeros(X.shape[:-1]), 2),
                  GenericFunction(lambda X: np.ones(X.shape[:-1]), 2),
                  GenericFunction(lambda X: X[..., 0], 2)]
    neumanns = [None,
                ConstantFunction(3., dim_domain=2),
                GenericFunction(lambda X:  50*(0.1 <= X[..., 1]) * (X[..., 1] <= 0.2)
                                          +50*(0.8 <= X[..., 1]) * (X[..., 1] <= 0.9), 2)]
    domains = [RectDomain(),
               RectDomain(right=BoundaryType('neumann')),
               RectDomain(right=BoundaryType('neumann'), top=BoundaryType('neumann')),
               RectDomain(right=BoundaryType('neumann'), top=BoundaryType('neumann'), bottom=BoundaryType('neumann'))]

    rhs = rhss[args['PROBLEM-NUMBER']]
    dirichlet = dirichlets[args['DIRICHLET-NUMBER']]
    neumann = neumanns[args['NEUMANN-NUMBER']]
    domain = domains[args['NEUMANN-COUNT']]

    for n in [32, 128]:
        grid_name = '{1}(({0},{0}))'.format(n, 'RectGrid' if args['--rect'] else 'TriaGrid')
        print('Solving on {0}'.format(grid_name))

        print('Setup problem ...')
        problem = EllipticProblem(domain=domain, rhs=rhs, dirichlet_data=dirichlet, neumann_data=neumann)

        print('Discretize ...')
        if args['--rect']:
            grid, bi = discretize_domain_default(problem.domain, diameter=m.sqrt(2) / n, grid_type=RectGrid)
        else:
            grid, bi = discretize_domain_default(problem.domain, diameter=1. / n, grid_type=TriaGrid)
        discretizer = discretize_elliptic_fv if args['--fv'] else discretize_elliptic_cg
        discretization, _ = discretizer(analytical_problem=problem, grid=grid, boundary_info=bi)

        print('Solve ...')
        U = discretization.solve()

        print('Plot ...')
        discretization.visualize(U, title=grid_name)

        print('')
コード例 #3
0
ファイル: thermalblock.py プロジェクト: michaellaier/pymor
    def __init__(self,
                 num_blocks=(3, 3),
                 parameter_range=(0.1, 1),
                 rhs=ConstantFunction(dim_domain=2)):

        domain = RectDomain()
        parameter_space = CubicParameterSpace(
            {'diffusion': (num_blocks[1], num_blocks[0])}, *parameter_range)

        def parameter_functional_factory(x, y):
            return ProjectionParameterFunctional(
                component_name='diffusion',
                component_shape=(num_blocks[1], num_blocks[0]),
                coordinates=(num_blocks[1] - y - 1, x),
                name='diffusion_{}_{}'.format(x, y))

        diffusion_functions = tuple(
            ThermalBlockDiffusionFunction(x, y, num_blocks[0], num_blocks[1])
            for x, y in product(xrange(num_blocks[0]), xrange(num_blocks[1])))
        parameter_functionals = tuple(
            parameter_functional_factory(x, y)
            for x, y in product(xrange(num_blocks[0]), xrange(num_blocks[1])))

        super(ThermalBlockProblem, self).__init__(domain,
                                                  rhs,
                                                  diffusion_functions,
                                                  parameter_functionals,
                                                  name='ThermalBlock')
        self.parameter_space = parameter_space
        self.parameter_range = parameter_range
        self.num_blocks = num_blocks
コード例 #4
0
ファイル: parabolic.py プロジェクト: simon-ca/pymor
    def __init__(self,
                 domain=RectDomain(),
                 rhs=ConstantFunction(dim_domain=2),
                 diffusion_functions=(ConstantFunction(dim_domain=2), ),
                 diffusion_functionals=None,
                 dirichlet_data=None,
                 neumann_data=None,
                 initial_data=ConstantFunction(dim_domain=2),
                 T=1,
                 parameter_space=None,
                 name=None):

        assert isinstance(diffusion_functions, (tuple, list))
        assert diffusion_functionals is None and len(diffusion_functions) == 1 \
            or len(diffusion_functionals) == len(diffusion_functions)
        assert rhs.dim_domain == diffusion_functions[0].dim_domain
        assert dirichlet_data is None or dirichlet_data.dim_domain == diffusion_functions[
            0].dim_domain
        assert neumann_data is None or neumann_data.dim_domain == diffusion_functions[
            0].dim_domain
        assert initial_data is None or initial_data.dim_domain == diffusion_functions[
            0].dim_domain
        self.domain = domain
        self.rhs = rhs
        self.diffusion_functions = diffusion_functions
        self.diffusion_functionals = diffusion_functionals
        self.dirichlet_data = dirichlet_data
        self.neumann_data = neumann_data
        self.initial_data = initial_data
        self.T = T
        self.parameter_space = parameter_space
        self.name = name
コード例 #5
0
def burgers_problem_2d(vx=1.,
                       vy=1.,
                       torus=True,
                       initial_data_type='sin',
                       parameter_range=(1., 2.)):
    """Two-dimensional Burgers-type problem.

    The problem is to solve ::

        ∂_t u(x, t, μ)  +  ∇ ⋅ (v * u(x, t, μ)^μ) = 0
                                       u(x, 0, μ) = u_0(x)

    for u with t in [0, 0.3], x in [0, 2] x [0, 1].

    Parameters
    ----------
    vx
        The x component of the velocity vector v.
    vy
        The y component of the velocity vector v.
    torus
        If `True`, impose periodic boundary conditions. Otherwise,
        Dirichlet left and bottom, outflow top and right.
    initial_data_type
        Type of initial data (`'sin'` or `'bump'`).
    parameter_range
        The interval in which μ is allowed to vary.
    """

    assert initial_data_type in ('sin', 'bump')

    if initial_data_type == 'sin':
        initial_data = ExpressionFunction(
            "0.5 * (sin(2 * pi * x[..., 0]) * sin(2 * pi * x[..., 1]) + 1.)",
            2, ())
        dirichlet_data = ConstantFunction(dim_domain=2, value=0.5)
    else:
        initial_data = ExpressionFunction(
            "(x[..., 0] >= 0.5) * (x[..., 0] <= 1) * 1", 2, ())
        dirichlet_data = ConstantFunction(dim_domain=2, value=0.)

    return InstationaryProblem(
        StationaryProblem(
            domain=TorusDomain([[0, 0], [2, 1]])
            if torus else RectDomain([[0, 0], [2, 1]], right=None, top=None),
            dirichlet_data=dirichlet_data,
            rhs=None,
            nonlinear_advection=ExpressionFunction("abs(x)**exponent * v", 1,
                                                   (2, ), {'exponent': ()},
                                                   {'v': np.array([vx, vy])}),
            nonlinear_advection_derivative=ExpressionFunction(
                "exponent * abs(x)**(exponent-1) * sign(x) * v", 1, (2, ),
                {'exponent': ()}, {'v': np.array([vx, vy])}),
        ),
        initial_data=initial_data,
        T=0.3,
        parameter_space=CubicParameterSpace({'exponent': 0}, *parameter_range),
        name="burgers_problem_2d({}, {}, {}, '{}')".format(
            vx, vy, torus, initial_data_type))
コード例 #6
0
ファイル: advection.py プロジェクト: michaellaier/pymor
 def __init__(self, domain=RectDomain(), rhs=ConstantFunction(dim_domain=2),
              flux_function=ConstantFunction(value=np.array([0, 0]), dim_domain=1),
              flux_function_derivative=ConstantFunction(value=np.array([0, 0]), dim_domain=1),
              dirichlet_data=ConstantFunction(value=0, dim_domain=2),
              initial_data=ConstantFunction(value=1, dim_domain=2), T=1, name=None):
     self.domain = domain
     self.rhs = rhs
     self.flux_function = flux_function
     self.flux_function_derivative = flux_function_derivative
     self.dirichlet_data = dirichlet_data
     self.initial_data = initial_data
     self.T = T
     self.name = name
コード例 #7
0
ファイル: helmholtz.py プロジェクト: simon-ca/pymor
    def __init__(self, domain=RectDomain(), rhs=None, parameter_range=(0., 100.),
                 dirichlet_data=None, neumann_data=None):

        self.parameter_range = parameter_range  # needed for with_
        parameter_space = CubicParameterSpace({'k': ()}, *parameter_range)
        super().__init__(
            diffusion_functions=[ConstantFunction(1., dim_domain=domain.dim)],
            diffusion_functionals=[1.],
            reaction_functions=[ConstantFunction(1., dim_domain=domain.dim)],
            reaction_functionals=[ExpressionParameterFunctional('-k**2', {'k': ()})],
            domain=domain,
            rhs=rhs or ConstantFunction(1., dim_domain=domain.dim),
            parameter_space=parameter_space,
            dirichlet_data=dirichlet_data,
            neumann_data=neumann_data)
コード例 #8
0
ファイル: gui.py プロジェクト: ftschindler-work/pymor
def test_visualize_patch(backend_gridtype):
    backend, gridtype = backend_gridtype
    domain = LineDomain() if gridtype is OnedGrid else RectDomain()
    dim = 1 if gridtype is OnedGrid else 2
    rhs = GenericFunction(lambda X: np.ones(X.shape[:-1]) * 10, dim)  # NOQA
    dirichlet = GenericFunction(lambda X: np.zeros(X.shape[:-1]), dim)  # NOQA
    diffusion = GenericFunction(lambda X: np.ones(X.shape[:-1]), dim)  # NOQA
    problem = StationaryProblem(domain=domain, rhs=rhs, dirichlet_data=dirichlet, diffusion=diffusion)
    grid, bi = discretize_domain_default(problem.domain, grid_type=gridtype)
    m, data = discretize_stationary_cg(analytical_problem=problem, grid=grid, boundary_info=bi)
    U = m.solve()
    try:
        visualize_patch(data['grid'], U=U, backend=backend)
    except QtMissing as ie:
        pytest.xfail("Qt missing")
    finally:
        stop_gui_processes()
コード例 #9
0
ファイル: helmholtz.py プロジェクト: ftschindler-work/pymor
def helmholtz_problem(domain=RectDomain(), rhs=None, parameter_range=(0., 100.),
                      dirichlet_data=None, neumann_data=None):
    """Helmholtz equation problem.

    This problem is to solve the Helmholtz equation ::

      - ∆ u(x, k) - k^2 u(x, k) = f(x, k)

    on a given domain.

    Parameters
    ----------
    domain
        A |DomainDescription| of the domain the problem is posed on.
    rhs
        The |Function| f(x, μ).
    parameter_range
        A tuple `(k_min, k_max)` describing the interval in which k is allowd to vary.
    dirichlet_data
        |Function| providing the Dirichlet boundary values.
    neumann_data
        |Function| providing the Neumann boundary values.
    """

    return StationaryProblem(

        domain=domain,

        rhs=rhs or ConstantFunction(1., dim_domain=domain.dim),

        dirichlet_data=dirichlet_data,

        neumann_data=neumann_data,

        diffusion=ConstantFunction(1., dim_domain=domain.dim),

        reaction=LincombFunction([ConstantFunction(1., dim_domain=domain.dim)],
                                 [ExpressionParameterFunctional('-k**2', {'k': ()})]),

        parameter_space=CubicParameterSpace({'k': ()}, *parameter_range),

        name='helmholtz_problem'

    )
コード例 #10
0
ファイル: gui.py プロジェクト: michaellaier/pymor
def test_visualize_patch(backend_gridtype):
    backend, gridtype = backend_gridtype
    domain = LineDomain() if gridtype is OnedGrid else RectDomain()
    dim = 1 if gridtype is OnedGrid else 2
    rhs = GenericFunction(lambda X: np.ones(X.shape[:-1]) * 10, dim)  # NOQA
    dirichlet = GenericFunction(lambda X: np.zeros(X.shape[:-1]), dim)  # NOQA
    diffusion = GenericFunction(lambda X: np.ones(X.shape[:-1]), dim)  # NOQA
    problem = EllipticProblem(domain=domain,
                              rhs=rhs,
                              dirichlet_data=dirichlet,
                              diffusion_functions=(diffusion, ))
    grid, bi = discretize_domain_default(problem.domain, grid_type=gridtype)
    discretization, data = discretize_elliptic_cg(analytical_problem=problem,
                                                  grid=grid,
                                                  boundary_info=bi)
    U = discretization.solve()
    visualize_patch(data['grid'], U=U, backend=backend)
    sleep(2)  # so gui has a chance to popup
    for child in multiprocessing.active_children():
        child.terminate()
コード例 #11
0
def elliptic2_demo(args):
    args['PROBLEM-NUMBER'] = int(args['PROBLEM-NUMBER'])
    assert 0 <= args['PROBLEM-NUMBER'] <= 1, ValueError(
        'Invalid problem number.')
    args['N'] = int(args['N'])

    rhss = [
        GenericFunction(lambda X: np.ones(X.shape[:-1]) * 10, dim_domain=2),
        GenericFunction(lambda X: (X[..., 0] - 0.5)**2 * 1000, dim_domain=2)
    ]
    rhs = rhss[args['PROBLEM-NUMBER']]

    d0 = GenericFunction(lambda X: 1 - X[..., 0], dim_domain=2)
    d1 = GenericFunction(lambda X: X[..., 0], dim_domain=2)

    parameter_space = CubicParameterSpace({'diffusionl': 0}, 0.1, 1)
    f0 = ProjectionParameterFunctional('diffusionl', 0)
    f1 = GenericParameterFunctional(lambda mu: 1, {})

    print('Solving on TriaGrid(({0},{0}))'.format(args['N']))

    print('Setup Problem ...')
    problem = EllipticProblem(domain=RectDomain(),
                              rhs=rhs,
                              diffusion_functions=(d0, d1),
                              diffusion_functionals=(f0, f1),
                              name='2DProblem')

    print('Discretize ...')
    discretizer = discretize_elliptic_fv if args[
        '--fv'] else discretize_elliptic_cg
    discretization, _ = discretizer(problem, diameter=1. / args['N'])

    print('The parameter type is {}'.format(discretization.parameter_type))

    U = discretization.solution_space.empty()
    for mu in parameter_space.sample_uniformly(10):
        U.append(discretization.solve(mu))

    print('Plot ...')
    discretization.visualize(U, title='Solution for diffusionl in [0.1, 1]')
コード例 #12
0
ファイル: burgers.py プロジェクト: michaellaier/pymor
    def __init__(self,
                 vx=1.,
                 vy=1.,
                 torus=True,
                 initial_data_type='sin',
                 parameter_range=(1., 2.)):

        assert initial_data_type in ('sin', 'bump')

        flux_function = Burgers2DFlux(vx, vy)
        flux_function_derivative = Burgers2DFluxDerivative(vx, vy)

        if initial_data_type == 'sin':
            initial_data = Burgers2DSinInitialData()
            dirichlet_data = ConstantFunction(dim_domain=2, value=0.5)
        else:
            initial_data = Burgers2DBumpInitialData()
            dirichlet_data = ConstantFunction(dim_domain=2, value=0)

        domain = TorusDomain([[0, 0], [2, 1]]) if torus else RectDomain(
            [[0, 0], [2, 1]], right=None, top=None)

        super(Burgers2DProblem,
              self).__init__(domain=domain,
                             rhs=None,
                             flux_function=flux_function,
                             flux_function_derivative=flux_function_derivative,
                             initial_data=initial_data,
                             dirichlet_data=dirichlet_data,
                             T=0.3,
                             name='Burgers2DProblem')

        self.parameter_space = CubicParameterSpace({'exponent': 0},
                                                   *parameter_range)
        self.parameter_range = parameter_range
        self.initial_data_type = initial_data_type
        self.torus = torus
        self.vx = vx
        self.vy = vy
コード例 #13
0
def elliptic2_demo(args):
    args['PROBLEM-NUMBER'] = int(args['PROBLEM-NUMBER'])
    assert 0 <= args['PROBLEM-NUMBER'] <= 1, ValueError(
        'Invalid problem number.')
    args['N'] = int(args['N'])

    rhss = [
        ExpressionFunction('ones(x.shape[:-1]) * 10', 2, ()),
        ExpressionFunction('(x[..., 0] - 0.5)**2 * 1000', 2, ())
    ]
    rhs = rhss[args['PROBLEM-NUMBER']]

    problem = StationaryProblem(
        domain=RectDomain(),
        rhs=rhs,
        diffusion=LincombFunction([
            ExpressionFunction('1 - x[..., 0]', 2, ()),
            ExpressionFunction('x[..., 0]', 2, ())
        ], [
            ProjectionParameterFunctional('diffusionl', 0),
            ExpressionParameterFunctional('1', {})
        ]),
        parameter_space=CubicParameterSpace({'diffusionl': 0}, 0.1, 1),
        name='2DProblem')

    print('Discretize ...')
    discretizer = discretize_stationary_fv if args[
        '--fv'] else discretize_stationary_cg
    m, data = discretizer(problem, diameter=1. / args['N'])
    print(data['grid'])
    print()

    print('Solve ...')
    U = m.solution_space.empty()
    for mu in m.parameter_space.sample_uniformly(10):
        U.append(m.solve(mu))
    m.visualize(U, title='Solution for diffusionl in [0.1, 1]')
コード例 #14
0
def thermal_block_problem(num_blocks=(3, 3), parameter_range=(0.1, 1)):
    """Analytical description of a 2D 'thermal block' diffusion problem.

    The problem is to solve the elliptic equation ::

      - ∇ ⋅ [ d(x, μ) ∇ u(x, μ) ] = f(x, μ)

    on the domain [0,1]^2 with Dirichlet zero boundary values. The domain is
    partitioned into nx x ny blocks and the diffusion function d(x, μ) is
    constant on each such block (i,j) with value μ_ij. ::

           ----------------------------
           |        |        |        |
           |  μ_11  |  μ_12  |  μ_13  |
           |        |        |        |
           |---------------------------
           |        |        |        |
           |  μ_21  |  μ_22  |  μ_23  |
           |        |        |        |
           ----------------------------

    Parameters
    ----------
    num_blocks
        The tuple `(nx, ny)`
    parameter_range
        A tuple `(μ_min, μ_max)`. Each |Parameter| component μ_ij is allowed
        to lie in the interval [μ_min, μ_max].
    """

    def parameter_functional_factory(ix, iy):
        return ProjectionParameterFunctional(component_name='diffusion',
                                             component_shape=(num_blocks[1], num_blocks[0]),
                                             index=(num_blocks[1] - iy - 1, ix),
                                             name=f'diffusion_{ix}_{iy}')

    def diffusion_function_factory(ix, iy):
        if ix + 1 < num_blocks[0]:
            X = '(x[..., 0] >= ix * dx) * (x[..., 0] < (ix + 1) * dx)'
        else:
            X = '(x[..., 0] >= ix * dx)'
        if iy + 1 < num_blocks[1]:
            Y = '(x[..., 1] >= iy * dy) * (x[..., 1] < (iy + 1) * dy)'
        else:
            Y = '(x[..., 1] >= iy * dy)'
        return ExpressionFunction(f'{X} * {Y} * 1.',
                                  2, (), {}, {'ix': ix, 'iy': iy, 'dx': 1. / num_blocks[0], 'dy': 1. / num_blocks[1]},
                                  name=f'diffusion_{ix}_{iy}')

    return StationaryProblem(

        domain=RectDomain(),

        rhs=ConstantFunction(dim_domain=2, value=1.),

        diffusion=LincombFunction([diffusion_function_factory(ix, iy)
                                   for ix, iy in product(range(num_blocks[0]), range(num_blocks[1]))],
                                  [parameter_functional_factory(ix, iy)
                                   for ix, iy in product(range(num_blocks[0]), range(num_blocks[1]))],
                                  name='diffusion'),

        parameter_space=CubicParameterSpace({'diffusion': (num_blocks[1], num_blocks[0])}, *parameter_range),

        name=f'ThermalBlock({num_blocks})'

    )
コード例 #15
0
ファイル: elliptic2.py プロジェクト: ftschindler-work/pymor
def elliptic2_demo(args):
    args['PROBLEM-NUMBER'] = int(args['PROBLEM-NUMBER'])
    assert 0 <= args['PROBLEM-NUMBER'] <= 1, ValueError(
        'Invalid problem number.')
    args['N'] = int(args['N'])

    rhss = [
        ExpressionFunction('ones(x.shape[:-1]) * 10', 2, ()),
        LincombFunction([
            ExpressionFunction('ones(x.shape[:-1]) * 10', 2, ()),
            ConstantFunction(1., 2)
        ], [
            ProjectionParameterFunctional('mu', 0),
            ExpressionParameterFunctional('0.1', {})
        ])
    ]

    dirichlets = [
        ExpressionFunction('zeros(x.shape[:-1])', 2, ()),
        LincombFunction([
            ExpressionFunction('2 * x[..., 0]', 2, ()),
            ConstantFunction(1., 2)
        ], [
            ProjectionParameterFunctional('mu', 0),
            ExpressionParameterFunctional('0.5', {})
        ])
    ]

    neumanns = [
        None,
        LincombFunction([
            ExpressionFunction('1 - x[..., 1]', 2, ()),
            ConstantFunction(1., 2)
        ], [
            ProjectionParameterFunctional('mu', 0),
            ExpressionParameterFunctional('0.5**2', {})
        ])
    ]

    robins = [
        None,
        (LincombFunction(
            [ExpressionFunction('x[..., 1]', 2, ()),
             ConstantFunction(1., 2)], [
                 ProjectionParameterFunctional('mu', 0),
                 ExpressionParameterFunctional('1', {})
             ]), ConstantFunction(1., 2))
    ]

    domains = [
        RectDomain(),
        RectDomain(right='neumann', top='dirichlet', bottom='robin')
    ]

    rhs = rhss[args['PROBLEM-NUMBER']]
    dirichlet = dirichlets[args['PROBLEM-NUMBER']]
    neumann = neumanns[args['PROBLEM-NUMBER']]
    domain = domains[args['PROBLEM-NUMBER']]
    robin = robins[args['PROBLEM-NUMBER']]

    problem = StationaryProblem(domain=RectDomain(),
                                rhs=rhs,
                                diffusion=LincombFunction([
                                    ExpressionFunction('1 - x[..., 0]', 2, ()),
                                    ExpressionFunction('x[..., 0]', 2, ())
                                ], [
                                    ProjectionParameterFunctional('mu', 0),
                                    ExpressionParameterFunctional('1', {})
                                ]),
                                dirichlet_data=dirichlet,
                                neumann_data=neumann,
                                robin_data=robin,
                                parameter_space=CubicParameterSpace({'mu': 0},
                                                                    0.1, 1),
                                name='2DProblem')

    print('Discretize ...')
    discretizer = discretize_stationary_fv if args[
        '--fv'] else discretize_stationary_cg
    m, data = discretizer(problem, diameter=1. / args['N'])
    print(data['grid'])
    print()

    print('Solve ...')
    U = m.solution_space.empty()
    for mu in m.parameter_space.sample_uniformly(10):
        U.append(m.solve(mu))
    m.visualize(U, title='Solution for mu in [0.1, 1]')
コード例 #16
0
ファイル: text.py プロジェクト: prklVIP/pymor
def text_problem(text='pyMOR', font_name=None):
    import numpy as np
    from PIL import Image, ImageDraw, ImageFont
    from tempfile import NamedTemporaryFile

    font_list = [font_name] if font_name else [
        'DejaVuSansMono.ttf', 'VeraMono.ttf', 'UbuntuMono-R.ttf', 'Arial.ttf'
    ]
    font = None
    for filename in font_list:
        try:
            font = ImageFont.truetype(
                filename, 64)  # load some font from file of given size
        except (OSError, IOError):
            pass
    if font is None:
        raise ValueError('Could not load TrueType font')

    size = font.getsize(text)  # compute width and height of rendered text
    size = (size[0] + 20, size[1] + 20
            )  # add a border of 10 pixels around the text

    def make_bitmap_function(
            char_num
    ):  # we need to genereate a BitmapFunction for each character
        img = Image.new('L',
                        size)  # create new Image object of given dimensions
        d = ImageDraw.Draw(img)  # create ImageDraw object for the given Image

        # in order to position the character correctly, we first draw all characters from the first
        # up to the wanted character
        d.text((10, 10), text[:char_num + 1], font=font, fill=255)

        # next we erase all previous character by drawing a black rectangle
        if char_num > 0:
            d.rectangle(
                ((0, 0), (font.getsize(text[:char_num])[0] + 10, size[1])),
                fill=0,
                outline=0)

        # open a new temporary file
        with NamedTemporaryFile(
                suffix='.png'
        ) as f:  # after leaving this 'with' block, the temporary
            # file is automatically deleted
            img.save(f, format='png')
            return BitmapFunction(f.name,
                                  bounding_box=[(0, 0), size],
                                  range=[0., 1.])

    # create BitmapFunctions for each character
    dfs = [make_bitmap_function(n) for n in range(len(text))]

    # create an indicator function for the background
    background = ConstantFunction(1., 2) - LincombFunction(
        dfs, np.ones(len(dfs)))

    # form the linear combination
    dfs = [background] + dfs
    coefficients = [1] + [
        ProjectionParameterFunctional('diffusion', (len(text), ), (i, ))
        for i in range(len(text))
    ]
    diffusion = LincombFunction(dfs, coefficients)

    return StationaryProblem(domain=RectDomain(dfs[1].bounding_box,
                                               bottom='neumann'),
                             neumann_data=ConstantFunction(-1., 2),
                             diffusion=diffusion,
                             parameter_space=CubicParameterSpace(
                                 diffusion.parameter_type, 0.1, 1.))
コード例 #17
0
from src.base import plot2d

import logging
logging.getLogger('matplotlib').setLevel(logging.ERROR)

if __name__ == '__main__':
    argvs = sys.argv
    parser = OptionParser()
    parser.add_option("--dir", dest="dir", default="./")
    opt, argc = parser.parse_args(argvs)
    print(opt, argc)

    rhs = ExpressionFunction('(x[..., 0] - 0.5)**2 * 1000', 2, ())

    problem = StationaryProblem(
        domain=RectDomain(),
        rhs=rhs,
        diffusion=LincombFunction(
            [ExpressionFunction('1 - x[..., 0]', 2, ()),
             ExpressionFunction('x[..., 0]', 2, ())],
            [ProjectionParameterFunctional(
                'diffusionl', 0), ExpressionParameterFunctional('1', {})]
        ),
        parameter_space=CubicParameterSpace({'diffusionl': 0}, 0.01, 0.1),
        name='2DProblem'
    )

    args = {'N': 100, 'samples': 10}
    m, data = discretize_stationary_cg(problem, diameter=1. / args['N'])
    U = m.solution_space.empty()
    for mu in m.parameter_space.sample_uniformly(args['samples']):
コード例 #18
0
ファイル: discrete_pou.py プロジェクト: deneick/pymor
        result[space] = myfunction

    return result


if __name__ == "__main__":
    from pymor.analyticalproblems.elliptic import EllipticProblem
    from pymor.domaindescriptions.basic import RectDomain
    from pymor.functions.basic import ConstantFunction
    from my_discretize_elliptic_cg import discretize_elliptic_cg
    from lmor.localizer import NumpyLocalizer
    from lmor.partitioner import build_subspaces, partition_any_grid

    coarse_grid_resolution = 10

    p = EllipticProblem(domain=RectDomain([[0, 0], [1, 1]]),
                        diffusion_functions=(ConstantFunction(1.,
                                                              dim_domain=2), ),
                        diffusion_functionals=(1., ),
                        rhs=ConstantFunction(1., dim_domain=2))
    d, data = discretize_elliptic_cg(p, diameter=0.01)
    grid = data["grid"]

    subspaces, subspaces_per_codim = build_subspaces(*partition_any_grid(
        grid, num_intervals=(coarse_grid_resolution, coarse_grid_resolution)))

    localizer = NumpyLocalizer(d.solution_space, subspaces['dofs'])

    images = d.solution_space.empty()
    fdict = localized_pou(subspaces, subspaces_per_codim, localizer,
                          coarse_grid_resolution, grid)
コード例 #19
0
        rhs=GenericFunction(dim_domain=2, mapping=lambda X: X[..., 0] + X[..., 1]))]

thermalblock_problems = picklable_thermalblock_problems + non_picklable_thermalblock_problems


burgers_problems = \
    [burgers_problem(),
     burgers_problem(v=0.2, circle=False),
     burgers_problem(v=0.4, initial_data_type='bump'),
     burgers_problem(parameter_range=(1., 1.3)),
     burgers_problem_2d(),
     burgers_problem_2d(torus=False, initial_data_type='bump', parameter_range=(1.3, 1.5))]


picklable_elliptic_problems = \
    [StationaryProblem(domain=RectDomain(), rhs=ConstantFunction(dim_domain=2, value=1.)),
     helmholtz_problem()]


non_picklable_elliptic_problems = \
    [StationaryProblem(domain=RectDomain(),
                     rhs=ConstantFunction(dim_domain=2, value=21.),
                     diffusion=LincombFunction(
                         [GenericFunction(dim_domain=2, mapping=lambda X, p=p: X[..., 0]**p)
                          for p in range(5)],
                         [ExpressionParameterFunctional('max(mu["exp"], {})'.format(m), parameter_type={'exp': ()})
                          for m in range(5)]
                     ))]

elliptic_problems = picklable_thermalblock_problems + non_picklable_elliptic_problems
コード例 #20
0
    def __init__(self,
                 domain=RectDomain(),
                 rhs=ConstantFunction(dim_domain=2),
                 diffusion_functions=None,
                 diffusion_functionals=None,
                 advection_functions=None,
                 advection_functionals=None,
                 reaction_functions=None,
                 reaction_functionals=None,
                 dirichlet_data=None,
                 neumann_data=None,
                 robin_data=None,
                 parameter_space=None,
                 name=None):
        assert diffusion_functions is None or isinstance(
            diffusion_functions, (tuple, list))
        assert advection_functions is None or isinstance(
            advection_functions, (tuple, list))
        assert reaction_functions is None or isinstance(
            reaction_functions, (tuple, list))

        assert diffusion_functionals is None and diffusion_functions is None \
            or diffusion_functionals is None and len(diffusion_functions) == 1 \
            or len(diffusion_functionals) == len(diffusion_functions)
        assert advection_functionals is None and advection_functions is None \
            or advection_functionals is None and len(advection_functions) == 1 \
            or len(advection_functionals) == len(advection_functions)
        assert reaction_functionals is None and reaction_functions is None \
            or reaction_functionals is None and len(reaction_functions) == 1 \
            or len(reaction_functionals) == len(reaction_functions)

        # for backward compatibility:
        if (diffusion_functions is None and advection_functions is None
                and reaction_functions is None):
            diffusion_functions = (ConstantFunction(dim_domain=2), )

        # dim_domain:
        if diffusion_functions is not None:
            dim_domain = diffusion_functions[0].dim_domain

        assert rhs.dim_domain == dim_domain
        if diffusion_functions is not None:
            for f in diffusion_functions:
                assert f.dim_domain == dim_domain
        if advection_functions is not None:
            for f in advection_functions:
                assert f.dim_domain == dim_domain
        if reaction_functions is not None:
            for f in reaction_functions:
                assert f.dim_domain == dim_domain

        assert dirichlet_data is None or dirichlet_data.dim_domain == dim_domain
        assert neumann_data is None or neumann_data.dim_domain == dim_domain
        assert robin_data is None or (isinstance(robin_data, tuple)
                                      and len(robin_data) == 2)
        assert robin_data is None or np.all(
            [f.dim_domain == dim_domain for f in robin_data])
        self.domain = domain
        self.rhs = rhs
        self.diffusion_functions = diffusion_functions
        self.diffusion_functionals = diffusion_functionals
        self.advection_functions = advection_functions
        self.advection_functionals = advection_functionals
        self.reaction_functions = reaction_functions
        self.reaction_functionals = reaction_functionals
        self.dirichlet_data = dirichlet_data
        self.neumann_data = neumann_data
        self.robin_data = robin_data
        self.parameter_space = parameter_space
        self.name = name