Beispiel #1
0
def thermalblock_demo(args):

    args = parse_arguments(args)

    pool = new_parallel_pool(ipython_num_engines=args['--ipython-engines'], ipython_profile=args['--ipython-profile'])

    if args['--fenics']:
        d, d_summary = discretize_fenics(args['XBLOCKS'], args['YBLOCKS'], args['--grid'], args['--order'])
    else:
        d, d_summary = discretize_pymor(args['XBLOCKS'], args['YBLOCKS'], args['--grid'], args['--list-vector-array'])

    if args['--cache-region'] != 'none':
        d.enable_caching(args['--cache-region'])

    if args['--plot-solutions']:
        print('Showing some solutions')
        Us = tuple()
        legend = tuple()
        for mu in d.parameter_space.sample_randomly(2):
            print('Solving for diffusion = \n{} ... '.format(mu['diffusion']))
            sys.stdout.flush()
            Us = Us + (d.solve(mu),)
            legend = legend + (str(mu['diffusion']),)
        d.visualize(Us, legend=legend, title='Detailed Solutions for different parameters',
                    separate_colorbars=False, block=True)

    print('RB generation ...')

    # define estimator for coercivity constant
    from pymor.parameters.functionals import ExpressionParameterFunctional
    coercivity_estimator = ExpressionParameterFunctional('min(diffusion)', d.parameter_type)

    # inner product for computation of Riesz representatives
    error_product = d.h1_0_semi_product if args['--estimator-norm'] == 'h1' else None

    if args['--reductor'] == 'residual_basis':
        from pymor.reductors.stationary import reduce_stationary_coercive
        reductor = partial(reduce_stationary_coercive, error_product=error_product,
                           coercivity_estimator=coercivity_estimator)
    elif args['--reductor'] == 'traditional':
        from pymor.reductors.linear import reduce_stationary_affine_linear
        reductor = partial(reduce_stationary_affine_linear, error_product=error_product,
                           coercivity_estimator=coercivity_estimator)
    else:
        assert False  # this should never happen

    if args['--pod']:
        rd, rc, red_summary = reduce_pod(d=d, reductor=reductor, snapshots_per_block=args['SNAPSHOTS'],
                                         basis_size=args['RBSIZE'], product_name=args['--pod-product'])
    else:
        rd, rc, red_summary = reduce_greedy(d=d, reductor=reductor, snapshots_per_block=args['SNAPSHOTS'],
                                            extension_alg_name=args['--extension-alg'],
                                            max_extensions=args['RBSIZE'],
                                            use_estimator=not args['--without-estimator'], pool=pool)

    if args['--pickle']:
        print('\nWriting reduced discretization to file {} ...'.format(args['--pickle'] + '_reduced'))
        with open(args['--pickle'] + '_reduced', 'w') as f:
            dump(rd, f)
        if not args['--fenics']:  # FEniCS data structures do not support serialization
            print('Writing detailed discretization and reconstructor to file {} ...'
                  .format(args['--pickle'] + '_detailed'))
            with open(args['--pickle'] + '_detailed', 'w') as f:
                dump((d, rc), f)

    print('\nSearching for maximum error on random snapshots ...')

    results = reduction_error_analysis(rd,
                                       discretization=d,
                                       reconstructor=rc,
                                       estimator=True,
                                       error_norms=(d.h1_0_semi_norm, d.l2_norm),
                                       condition=True,
                                       test_mus=args['--test'],
                                       basis_sizes=0 if args['--plot-error-sequence'] else 1,
                                       plot=args['--plot-error-sequence'],
                                       pool=pool)

    print('\n*** RESULTS ***\n')
    print(d_summary)
    print(red_summary)
    print(results['summary'])
    sys.stdout.flush()

    if args['--plot-error-sequence']:
        from matplotlib import pyplot as plt
        plt.show(results['figure'])
    if args['--plot-err']:
        mumax = results['max_error_mus'][0, -1]
        U = d.solve(mumax)
        URB = rc.reconstruct(rd.solve(mumax))
        d.visualize((U, URB, U - URB), legend=('Detailed Solution', 'Reduced Solution', 'Error'),
                    title='Maximum Error Solution', separate_colorbars=True, block=True)
Beispiel #2
0
def main(
        exp_min: float = Argument(..., help='Minimal exponent'),
        exp_max: float = Argument(..., help='Maximal exponent'),
        ei_snapshots: int = Argument(
            ..., help='Number of snapshots for empirical interpolation.'),
        ei_size: int = Argument(..., help='Number of interpolation DOFs.'),
        snapshots: int = Argument(
            ..., help='Number of snapshots for basis generation.'),
        rb_size: int = Argument(..., help='Size of the reduced basis.'),
        cache_region: Choices('none memory disk persistent') = Option(
            'disk',
            help='Name of cache region to use for caching solution snapshots.'
        ),
        ei_alg: Choices('ei_greedy deim') = Option(
            'ei_greedy', help='Interpolation algorithm to use.'),
        grid: int = Option(60, help='Use grid with (2*NI)*NI elements.'),
        grid_type: Choices('rect tria') = Option('rect',
                                                 help='Type of grid to use.'),
        initial_data: Choices('sin bump') = Option(
            'sin', help='Select the initial data (sin, bump).'),
        ipython_engines:
    int = Option(
        0,
        help=
        'If positive, the number of IPython cluster engines to use for parallel greedy search. '
        'If zero, no parallelization is performed.'),
        ipython_profile: str = Option(
            None, help='IPython profile to use for parallelization.'),
        lxf_lambda: float = Option(
            1., help='Parameter lambda in Lax-Friedrichs flux.'),
        periodic:
    bool = Option(
        True,
        help
        ='If not, solve with dirichlet boundary conditions on left and bottom boundary.'
    ),
        nt: int = Option(100, help='Number of time steps.'),
        num_flux: Choices('lax_friedrichs engquist_osher') = Option(
            'engquist_osher', help='Numerical flux to use.'),
        plot_err: bool = Option(False, help='Plot error.'),
        plot_ei_err: bool = Option(False,
                                   help='Plot empirical interpolation error.'),
        plot_error_landscape: bool = Option(
            False,
            help='Calculate and show plot of reduction error vs. basis sizes.'
        ),
        plot_error_landscape_M: int = Option(
            10, help='Number of collateral basis sizes to test.'),
        plot_error_landscape_N: int = Option(
            10, help='Number of basis sizes to test.'),
        plot_solutions: bool = Option(False,
                                      help='Plot some example solutions.'),
        test: int = Option(
            10,
            help='Number of snapshots to use for stochastic error estimation.'
        ),
        vx: float = Option(1., help='Speed in x-direction.'),
        vy: float = Option(1., help='Speed in y-direction.'),
):
    """Model order reduction of a two-dimensional Burgers-type equation
    (see pymor.analyticalproblems.burgers) using the reduced basis method
    with empirical operator interpolation.
    """
    print('Setup Problem ...')
    problem = burgers_problem_2d(vx=vx,
                                 vy=vy,
                                 initial_data_type=initial_data.value,
                                 parameter_range=(exp_min, exp_max),
                                 torus=periodic)

    print('Discretize ...')
    if grid_type == 'rect':
        grid *= 1. / math.sqrt(2)
    fom, _ = discretize_instationary_fv(
        problem,
        diameter=1. / grid,
        grid_type=RectGrid if grid_type == 'rect' else TriaGrid,
        num_flux=num_flux.value,
        lxf_lambda=lxf_lambda,
        nt=nt)

    if cache_region != 'none':
        # building a cache_id is only needed for persistent CacheRegions
        cache_id = (
            f"pymordemos.burgers_ei {vx} {vy} {initial_data}"
            f"{periodic} {grid} {grid_type} {num_flux} {lxf_lambda} {nt}")
        fom.enable_caching(cache_region.value, cache_id)

    print(fom.operator.grid)

    print(f'The parameters are {fom.parameters}')

    if plot_solutions:
        print('Showing some solutions')
        Us = ()
        legend = ()
        for mu in problem.parameter_space.sample_uniformly(4):
            print(f"Solving for exponent = {mu['exponent']} ... ")
            sys.stdout.flush()
            Us = Us + (fom.solve(mu), )
            legend = legend + (f"exponent: {mu['exponent']}", )
        fom.visualize(Us,
                      legend=legend,
                      title='Detailed Solutions',
                      block=True)

    pool = new_parallel_pool(ipython_num_engines=ipython_engines,
                             ipython_profile=ipython_profile)
    eim, ei_data = interpolate_operators(
        fom, ['operator'],
        problem.parameter_space.sample_uniformly(ei_snapshots),
        error_norm=fom.l2_norm,
        product=fom.l2_product,
        max_interpolation_dofs=ei_size,
        alg=ei_alg.value,
        pool=pool)

    if plot_ei_err:
        print('Showing some EI errors')
        ERRs = ()
        legend = ()
        for mu in problem.parameter_space.sample_randomly(2):
            print(f"Solving for exponent = \n{mu['exponent']} ... ")
            sys.stdout.flush()
            U = fom.solve(mu)
            U_EI = eim.solve(mu)
            ERR = U - U_EI
            ERRs = ERRs + (ERR, )
            legend = legend + (f"exponent: {mu['exponent']}", )
            print(f'Error: {np.max(fom.l2_norm(ERR))}')
        fom.visualize(ERRs,
                      legend=legend,
                      title='EI Errors',
                      separate_colorbars=True)

        print('Showing interpolation DOFs ...')
        U = np.zeros(U.dim)
        dofs = eim.operator.interpolation_dofs
        U[dofs] = np.arange(1, len(dofs) + 1)
        U[eim.operator.source_dofs] += int(len(dofs) / 2)
        fom.visualize(fom.solution_space.make_array(U),
                      title='Interpolation DOFs')

    print('RB generation ...')

    reductor = InstationaryRBReductor(eim)

    greedy_data = rb_greedy(
        fom,
        reductor,
        problem.parameter_space.sample_uniformly(snapshots),
        use_error_estimator=False,
        error_norm=lambda U: np.max(fom.l2_norm(U)),
        extension_params={'method': 'pod'},
        max_extensions=rb_size,
        pool=pool)

    rom = greedy_data['rom']

    print('\nSearching for maximum error on random snapshots ...')

    tic = time.perf_counter()

    mus = problem.parameter_space.sample_randomly(test)

    def error_analysis(N, M):
        print(f'N = {N}, M = {M}: ', end='')
        rom = reductor.reduce(N)
        rom = rom.with_(operator=rom.operator.with_cb_dim(M))
        l2_err_max = -1
        mumax = None
        for mu in mus:
            print('.', end='')
            sys.stdout.flush()
            u = rom.solve(mu)
            URB = reductor.reconstruct(u)
            U = fom.solve(mu)
            l2_err = np.max(fom.l2_norm(U - URB))
            l2_err = np.inf if not np.isfinite(l2_err) else l2_err
            if l2_err > l2_err_max:
                l2_err_max = l2_err
                mumax = mu
        print()
        return l2_err_max, mumax

    error_analysis = np.frompyfunc(error_analysis, 2, 2)

    real_rb_size = len(reductor.bases['RB'])
    real_cb_size = len(ei_data['basis'])
    if plot_error_landscape:
        N_count = min(real_rb_size - 1, plot_error_landscape_N)
        M_count = min(real_cb_size - 1, plot_error_landscape_M)
        Ns = np.linspace(1, real_rb_size, N_count).astype(np.int)
        Ms = np.linspace(1, real_cb_size, M_count).astype(np.int)
    else:
        Ns = np.array([real_rb_size])
        Ms = np.array([real_cb_size])

    N_grid, M_grid = np.meshgrid(Ns, Ms)

    errs, err_mus = error_analysis(N_grid, M_grid)
    errs = errs.astype(np.float)

    l2_err_max = errs[-1, -1]
    mumax = err_mus[-1, -1]
    toc = time.perf_counter()
    t_est = toc - tic

    print('''
    *** RESULTS ***

    Problem:
       parameter range:                    ({exp_min}, {exp_max})
       h:                                  sqrt(2)/{grid}
       grid-type:                          {grid_type}
       initial-data:                       {initial_data}
       lxf-lambda:                         {lxf_lambda}
       nt:                                 {nt}
       not-periodic:                       {periodic}
       num-flux:                           {num_flux}
       (vx, vy):                           ({vx}, {vy})

    Greedy basis generation:
       number of ei-snapshots:             {ei_snapshots}
       prescribed collateral basis size:   {ei_size}
       actual collateral basis size:       {real_cb_size}
       number of snapshots:                {snapshots}
       prescribed basis size:              {rb_size}
       actual basis size:                  {real_rb_size}
       elapsed time:                       {greedy_data[time]}

    Stochastic error estimation:
       number of samples:                  {test}
       maximal L2-error:                   {l2_err_max}  (mu = {mumax})
       elapsed time:                       {t_est}
    '''.format(**locals()))

    sys.stdout.flush()
    if plot_error_landscape:
        import matplotlib.pyplot as plt
        import mpl_toolkits.mplot3d  # NOQA
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        # rescale the errors since matplotlib does not support logarithmic scales on 3d plots
        # https://github.com/matplotlib/matplotlib/issues/209
        surf = ax.plot_surface(M_grid,
                               N_grid,
                               np.log(np.minimum(errs, 1)) / np.log(10),
                               rstride=1,
                               cstride=1,
                               cmap='jet')
        plt.show()
    if plot_err:
        U = fom.solve(mumax)
        URB = reductor.reconstruct(rom.solve(mumax))
        fom.visualize(
            (U, URB, U - URB),
            legend=('Detailed Solution', 'Reduced Solution', 'Error'),
            title='Maximum Error Solution',
            separate_colorbars=True)

    global test_results
    test_results = (ei_data, greedy_data)
Beispiel #3
0
def main(args):

    args = parse_arguments(args)

    pool = new_parallel_pool(ipython_num_engines=args["--ipython-engines"], ipython_profile=args["--ipython-profile"])

    if args["--fenics"]:
        d, d_summary = discretize_fenics(args["XBLOCKS"], args["YBLOCKS"], args["--grid"], args["--order"])
    else:
        d, d_summary = discretize_pymor(args["XBLOCKS"], args["YBLOCKS"], args["--grid"], args["--list-vector-array"])

    if args["--cache-region"] != "none":
        d.enable_caching(args["--cache-region"])

    if args["--plot-solutions"]:
        print("Showing some solutions")
        Us = ()
        legend = ()
        for mu in d.parameter_space.sample_randomly(2):
            print("Solving for diffusion = \n{} ... ".format(mu["diffusion"]))
            sys.stdout.flush()
            Us = Us + (d.solve(mu),)
            legend = legend + (str(mu["diffusion"]),)
        d.visualize(
            Us, legend=legend, title="Detailed Solutions for different parameters", separate_colorbars=False, block=True
        )

    print("RB generation ...")

    # define estimator for coercivity constant
    from pymor.parameters.functionals import ExpressionParameterFunctional

    coercivity_estimator = ExpressionParameterFunctional("min(diffusion)", d.parameter_type)

    # inner product for computation of Riesz representatives
    product = d.h1_0_semi_product if args["--estimator-norm"] == "h1" else None

    if args["--reductor"] == "residual_basis":
        from pymor.reductors.coercive import reduce_coercive

        reductor = partial(reduce_coercive, product=product, coercivity_estimator=coercivity_estimator)
    elif args["--reductor"] == "traditional":
        from pymor.reductors.coercive import reduce_coercive_simple

        reductor = partial(reduce_coercive_simple, product=product, coercivity_estimator=coercivity_estimator)
    else:
        assert False  # this should never happen

    if args["--alg"] == "naive":
        rd, rc, red_summary = reduce_naive(d=d, reductor=reductor, basis_size=args["RBSIZE"])
    elif args["--alg"] == "greedy":
        parallel = not (args["--fenics"] and args["--greedy-without-estimator"])  # cannot pickle FEniCS discretization
        rd, rc, red_summary = reduce_greedy(
            d=d,
            reductor=reductor,
            snapshots_per_block=args["SNAPSHOTS"],
            extension_alg_name=args["--extension-alg"],
            max_extensions=args["RBSIZE"],
            use_estimator=not args["--greedy-without-estimator"],
            pool=pool if parallel else None,
        )
    elif args["--alg"] == "adaptive_greedy":
        parallel = not (args["--fenics"] and args["--greedy-without-estimator"])  # cannot pickle FEniCS discretization
        rd, rc, red_summary = reduce_adaptive_greedy(
            d=d,
            reductor=reductor,
            validation_mus=args["SNAPSHOTS"],
            extension_alg_name=args["--extension-alg"],
            max_extensions=args["RBSIZE"],
            use_estimator=not args["--greedy-without-estimator"],
            rho=args["--adaptive-greedy-rho"],
            gamma=args["--adaptive-greedy-gamma"],
            theta=args["--adaptive-greedy-theta"],
            pool=pool if parallel else None,
        )
    elif args["--alg"] == "pod":
        rd, rc, red_summary = reduce_pod(
            d=d,
            reductor=reductor,
            snapshots_per_block=args["SNAPSHOTS"],
            basis_size=args["RBSIZE"],
            product_name=args["--pod-product"],
        )
    else:
        assert False  # this should never happen

    if args["--pickle"]:
        print("\nWriting reduced discretization to file {} ...".format(args["--pickle"] + "_reduced"))
        with open(args["--pickle"] + "_reduced", "wb") as f:
            dump(rd, f)
        if not args["--fenics"]:  # FEniCS data structures do not support serialization
            print(
                "Writing detailed discretization and reconstructor to file {} ...".format(
                    args["--pickle"] + "_detailed"
                )
            )
            with open(args["--pickle"] + "_detailed", "wb") as f:
                dump((d, rc), f)

    print("\nSearching for maximum error on random snapshots ...")

    results = reduction_error_analysis(
        rd,
        discretization=d,
        reconstructor=rc,
        estimator=True,
        error_norms=(d.h1_0_semi_norm, d.l2_norm),
        condition=True,
        test_mus=args["--test"],
        basis_sizes=0 if args["--plot-error-sequence"] else 1,
        plot=args["--plot-error-sequence"],
        pool=None if args["--fenics"] else pool,  # cannot pickle FEniCS discretization
        random_seed=999,
    )

    print("\n*** RESULTS ***\n")
    print(d_summary)
    print(red_summary)
    print(results["summary"])
    sys.stdout.flush()

    if args["--plot-error-sequence"]:
        import matplotlib.pyplot

        matplotlib.pyplot.show(results["figure"])
    if args["--plot-err"]:
        mumax = results["max_error_mus"][0, -1]
        U = d.solve(mumax)
        URB = rc.reconstruct(rd.solve(mumax))
        d.visualize(
            (U, URB, U - URB),
            legend=("Detailed Solution", "Reduced Solution", "Error"),
            title="Maximum Error Solution",
            separate_colorbars=True,
            block=True,
        )

    return results
Beispiel #4
0
def main(args):
    args = docopt(__doc__, args)
    args['--cache-region'] = args['--cache-region'].lower()
    args['--grid'] = int(args['--grid'])
    args['--grid-type'] = args['--grid-type'].lower()
    assert args['--grid-type'] in ('rect', 'tria')
    args['--initial-data'] = args['--initial-data'].lower()
    assert args['--initial-data'] in ('sin', 'bump')
    args['--lxf-lambda'] = float(args['--lxf-lambda'])
    args['--nt'] = int(args['--nt'])
    args['--not-periodic'] = bool(args['--not-periodic'])
    args['--num-flux'] = args['--num-flux'].lower()
    assert args['--num-flux'] in ('lax_friedrichs', 'engquist_osher')
    args['--plot-error-landscape-N'] = int(args['--plot-error-landscape-N'])
    args['--plot-error-landscape-M'] = int(args['--plot-error-landscape-M'])
    args['--test'] = int(args['--test'])
    args['--vx'] = float(args['--vx'])
    args['--vy'] = float(args['--vy'])
    args['--ipython-engines'] = int(args['--ipython-engines'])
    args['EXP_MIN'] = int(args['EXP_MIN'])
    args['EXP_MAX'] = int(args['EXP_MAX'])
    args['EI_SNAPSHOTS'] = int(args['EI_SNAPSHOTS'])
    args['EISIZE'] = int(args['EISIZE'])
    args['SNAPSHOTS'] = int(args['SNAPSHOTS'])
    args['RBSIZE'] = int(args['RBSIZE'])

    print('Setup Problem ...')
    problem = burgers_problem_2d(vx=args['--vx'], vy=args['--vy'], initial_data_type=args['--initial-data'],
                                 parameter_range=(args['EXP_MIN'], args['EXP_MAX']), torus=not args['--not-periodic'])

    print('Discretize ...')
    if args['--grid-type'] == 'rect':
        args['--grid'] *= 1. / m.sqrt(2)
    d, _ = discretize_instationary_fv(
        problem,
        diameter=1. / args['--grid'],
        grid_type=RectGrid if args['--grid-type'] == 'rect' else TriaGrid,
        num_flux=args['--num-flux'],
        lxf_lambda=args['--lxf-lambda'],
        nt=args['--nt']
    )

    if args['--cache-region'] != 'none':
        d.enable_caching(args['--cache-region'])

    print(d.operator.grid)

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

    if args['--plot-solutions']:
        print('Showing some solutions')
        Us = ()
        legend = ()
        for mu in d.parameter_space.sample_uniformly(4):
            print('Solving for exponent = {} ... '.format(mu['exponent']))
            sys.stdout.flush()
            Us = Us + (d.solve(mu),)
            legend = legend + ('exponent: {}'.format(mu['exponent']),)
        d.visualize(Us, legend=legend, title='Detailed Solutions', block=True)

    pool = new_parallel_pool(ipython_num_engines=args['--ipython-engines'], ipython_profile=args['--ipython-profile'])
    ei_d, ei_data = interpolate_operators(d, ['operator'],
                                          d.parameter_space.sample_uniformly(args['EI_SNAPSHOTS']),  # NOQA
                                          error_norm=d.l2_norm,
                                          max_interpolation_dofs=args['EISIZE'],
                                          pool=pool)

    if args['--plot-ei-err']:
        print('Showing some EI errors')
        ERRs = ()
        legend = ()
        for mu in d.parameter_space.sample_randomly(2):
            print('Solving for exponent = \n{} ... '.format(mu['exponent']))
            sys.stdout.flush()
            U = d.solve(mu)
            U_EI = ei_d.solve(mu)
            ERR = U - U_EI
            ERRs = ERRs + (ERR,)
            legend = legend + ('exponent: {}'.format(mu['exponent']),)
            print('Error: {}'.format(np.max(d.l2_norm(ERR))))
        d.visualize(ERRs, legend=legend, title='EI Errors', separate_colorbars=True)

        print('Showing interpolation DOFs ...')
        U = np.zeros(U.dim)
        dofs = ei_d.operator.interpolation_dofs
        U[dofs] = np.arange(1, len(dofs) + 1)
        U[ei_d.operator.source_dofs] += int(len(dofs)/2)
        d.visualize(d.solution_space.make_array(U),
                                 title='Interpolation DOFs')

    print('RB generation ...')

    reductor = GenericRBReductor(ei_d)

    greedy_data = greedy(d, reductor, d.parameter_space.sample_uniformly(args['SNAPSHOTS']),
                         use_estimator=False, error_norm=lambda U: np.max(d.l2_norm(U)),
                         extension_params={'method': 'pod'}, max_extensions=args['RBSIZE'],
                         pool=pool)

    rd = greedy_data['rd']

    print('\nSearching for maximum error on random snapshots ...')

    tic = time.time()

    mus = d.parameter_space.sample_randomly(args['--test'])

    def error_analysis(N, M):
        print('N = {}, M = {}: '.format(N, M), end='')
        rd = reductor.reduce(N)
        rd = rd.with_(operator=rd.operator.with_cb_dim(M))
        l2_err_max = -1
        mumax = None
        for mu in mus:
            print('.', end='')
            sys.stdout.flush()
            u = rd.solve(mu)
            URB = reductor.reconstruct(u)
            U = d.solve(mu)
            l2_err = np.max(d.l2_norm(U - URB))
            l2_err = np.inf if not np.isfinite(l2_err) else l2_err
            if l2_err > l2_err_max:
                l2_err_max = l2_err
                mumax = mu
        print()
        return l2_err_max, mumax
    error_analysis = np.frompyfunc(error_analysis, 2, 2)

    real_rb_size = len(reductor.RB)
    real_cb_size = len(ei_data['basis'])
    if args['--plot-error-landscape']:
        N_count = min(real_rb_size - 1, args['--plot-error-landscape-N'])
        M_count = min(real_cb_size - 1, args['--plot-error-landscape-M'])
        Ns = np.linspace(1, real_rb_size, N_count).astype(np.int)
        Ms = np.linspace(1, real_cb_size, M_count).astype(np.int)
    else:
        Ns = np.array([real_rb_size])
        Ms = np.array([real_cb_size])

    N_grid, M_grid = np.meshgrid(Ns, Ms)

    errs, err_mus = error_analysis(N_grid, M_grid)
    errs = errs.astype(np.float)

    l2_err_max = errs[-1, -1]
    mumax = err_mus[-1, -1]
    toc = time.time()
    t_est = toc - tic

    print('''
    *** RESULTS ***

    Problem:
       parameter range:                    ({args[EXP_MIN]}, {args[EXP_MAX]})
       h:                                  sqrt(2)/{args[--grid]}
       grid-type:                          {args[--grid-type]}
       initial-data:                       {args[--initial-data]}
       lxf-lambda:                         {args[--lxf-lambda]}
       nt:                                 {args[--nt]}
       not-periodic:                       {args[--not-periodic]}
       num-flux:                           {args[--num-flux]}
       (vx, vy):                           ({args[--vx]}, {args[--vy]})

    Greedy basis generation:
       number of ei-snapshots:             {args[EI_SNAPSHOTS]}
       prescribed collateral basis size:   {args[EISIZE]}
       actual collateral basis size:       {real_cb_size}
       number of snapshots:                {args[SNAPSHOTS]}
       prescribed basis size:              {args[RBSIZE]}
       actual basis size:                  {real_rb_size}
       elapsed time:                       {greedy_data[time]}

    Stochastic error estimation:
       number of samples:                  {args[--test]}
       maximal L2-error:                   {l2_err_max}  (mu = {mumax})
       elapsed time:                       {t_est}
    '''.format(**locals()))

    sys.stdout.flush()
    if args['--plot-error-landscape']:
        import matplotlib.pyplot as plt
        import mpl_toolkits.mplot3d             # NOQA
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        # we have to rescale the errors since matplotlib does not support logarithmic scales on 3d plots
        # https://github.com/matplotlib/matplotlib/issues/209
        surf = ax.plot_surface(M_grid, N_grid, np.log(np.minimum(errs, 1)) / np.log(10),
                               rstride=1, cstride=1, cmap='jet')
        plt.show()
    if args['--plot-err']:
        U = d.solve(mumax)
        URB = reductor.reconstruct(rd.solve(mumax))
        d.visualize((U, URB, U - URB), legend=('Detailed Solution', 'Reduced Solution', 'Error'),
                    title='Maximum Error Solution', separate_colorbars=True)

    return ei_data, greedy_data
Beispiel #5
0
def main(args):

    args = parse_arguments(args)

    pool = new_parallel_pool(ipython_num_engines=args['--ipython-engines'], ipython_profile=args['--ipython-profile'])

    if args['--fenics']:
        fom, fom_summary = discretize_fenics(args['XBLOCKS'], args['YBLOCKS'], args['--grid'], args['--order'])
    else:
        fom, fom_summary = discretize_pymor(args['XBLOCKS'], args['YBLOCKS'], args['--grid'], args['--list-vector-array'])

    if args['--cache-region'] != 'none':
        # building a cache_id is only needed for persistent CacheRegions
        cache_id = (f"pymordemos.thermalblock {args['--fenics']} {args['XBLOCKS']} {args['YBLOCKS']}"
                    f"{args['--grid']} {args['--order']}")
        fom.enable_caching(args['--cache-region'], cache_id)

    if args['--plot-solutions']:
        print('Showing some solutions')
        Us = ()
        legend = ()
        for mu in fom.parameter_space.sample_randomly(2):
            print(f"Solving for diffusion = \n{mu['diffusion']} ... ")
            sys.stdout.flush()
            Us = Us + (fom.solve(mu),)
            legend = legend + (str(mu['diffusion']),)
        fom.visualize(Us, legend=legend, title='Detailed Solutions for different parameters',
                      separate_colorbars=False, block=True)

    print('RB generation ...')

    # define estimator for coercivity constant
    from pymor.parameters.functionals import ExpressionParameterFunctional
    coercivity_estimator = ExpressionParameterFunctional('min(diffusion)', fom.parameter_type)

    # inner product for computation of Riesz representatives
    product = fom.h1_0_semi_product if args['--product'] == 'h1' else None

    if args['--reductor'] == 'residual_basis':
        from pymor.reductors.coercive import CoerciveRBReductor
        reductor = CoerciveRBReductor(fom, product=product, coercivity_estimator=coercivity_estimator,
                                      check_orthonormality=False)
    elif args['--reductor'] == 'traditional':
        from pymor.reductors.coercive import SimpleCoerciveRBReductor
        reductor = SimpleCoerciveRBReductor(fom, product=product, coercivity_estimator=coercivity_estimator,
                                            check_orthonormality=False)
    else:
        assert False  # this should never happen

    if args['--alg'] == 'naive':
        rom, red_summary = reduce_naive(fom=fom, reductor=reductor, basis_size=args['RBSIZE'])
    elif args['--alg'] == 'greedy':
        parallel = not (args['--fenics'] and args['--greedy-without-estimator'])  # cannot pickle FEniCS model
        rom, red_summary = reduce_greedy(fom=fom, reductor=reductor, snapshots_per_block=args['SNAPSHOTS'],
                                         extension_alg_name=args['--extension-alg'],
                                         max_extensions=args['RBSIZE'],
                                         use_estimator=not args['--greedy-without-estimator'],
                                         pool=pool if parallel else None)
    elif args['--alg'] == 'adaptive_greedy':
        parallel = not (args['--fenics'] and args['--greedy-without-estimator'])  # cannot pickle FEniCS model
        rom, red_summary = reduce_adaptive_greedy(fom=fom, reductor=reductor, validation_mus=args['SNAPSHOTS'],
                                                  extension_alg_name=args['--extension-alg'],
                                                  max_extensions=args['RBSIZE'],
                                                  use_estimator=not args['--greedy-without-estimator'],
                                                  rho=args['--adaptive-greedy-rho'],
                                                  gamma=args['--adaptive-greedy-gamma'],
                                                  theta=args['--adaptive-greedy-theta'],
                                                  pool=pool if parallel else None)
    elif args['--alg'] == 'pod':
        rom, red_summary = reduce_pod(fom=fom, reductor=reductor, snapshots_per_block=args['SNAPSHOTS'],
                                      basis_size=args['RBSIZE'])
    else:
        assert False  # this should never happen

    if args['--pickle']:
        print(f"\nWriting reduced model to file {args['--pickle']}_reduced ...")
        with open(args['--pickle'] + '_reduced', 'wb') as f:
            dump(rom, f)
        if not args['--fenics']:  # FEniCS data structures do not support serialization
            print(f"Writing detailed model and reductor to file {args['--pickle']}_detailed ...")
            with open(args['--pickle'] + '_detailed', 'wb') as f:
                dump((fom, reductor), f)

    print('\nSearching for maximum error on random snapshots ...')

    results = reduction_error_analysis(rom,
                                       fom=fom,
                                       reductor=reductor,
                                       estimator=True,
                                       error_norms=(fom.h1_0_semi_norm, fom.l2_norm),
                                       condition=True,
                                       test_mus=args['--test'],
                                       basis_sizes=0 if args['--plot-error-sequence'] else 1,
                                       plot=args['--plot-error-sequence'],
                                       pool=None if args['--fenics'] else pool,  # cannot pickle FEniCS model
                                       random_seed=999)

    print('\n*** RESULTS ***\n')
    print(fom_summary)
    print(red_summary)
    print(results['summary'])
    sys.stdout.flush()

    if args['--plot-error-sequence']:
        import matplotlib.pyplot
        matplotlib.pyplot.show(results['figure'])
    if args['--plot-err']:
        mumax = results['max_error_mus'][0, -1]
        U = fom.solve(mumax)
        URB = reductor.reconstruct(rom.solve(mumax))
        fom.visualize((U, URB, U - URB), legend=('Detailed Solution', 'Reduced Solution', 'Error'),
                    title='Maximum Error Solution', separate_colorbars=True, block=True)

    return results
def thermalblock_demo(args):
    args['--grid'] = int(args['--grid'])
    args['RBSIZE'] = int(args['RBSIZE'])
    args['--test'] = int(args['--test'])
    args['--ipython-engines'] = int(args['--ipython-engines'])
    args['--extension-alg'] = args['--extension-alg'].lower()
    assert args['--extension-alg'] in {'trivial', 'gram_schmidt'}
    args['--product'] = args['--product'].lower()
    assert args['--product'] in {'trivial', 'h1'}
    args['--reductor'] = args['--reductor'].lower()
    assert args['--reductor'] in {'traditional', 'residual_basis'}
    args['--cache-region'] = args['--cache-region'].lower()
    args['--validation-mus'] = int(args['--validation-mus'])
    args['--rho'] = float(args['--rho'])
    args['--gamma'] = float(args['--gamma'])
    args['--theta'] = float(args['--theta'])

    problem = thermal_block_problem(num_blocks=(2, 2))
    functionals = [
        ExpressionParameterFunctional('diffusion[0]', {'diffusion': 2}),
        ExpressionParameterFunctional('diffusion[1]**2', {'diffusion': 2}),
        ExpressionParameterFunctional('diffusion[0]', {'diffusion': 2}),
        ExpressionParameterFunctional('diffusion[1]', {'diffusion': 2})
    ]
    problem = problem.with_(
        diffusion=problem.diffusion.with_(coefficients=functionals), )

    print('Discretize ...')
    fom, _ = discretize_stationary_cg(problem, diameter=1. / args['--grid'])

    if args['--list-vector-array']:
        from pymor.discretizers.builtin.list import convert_to_numpy_list_vector_array
        fom = convert_to_numpy_list_vector_array(fom)

    if args['--cache-region'] != 'none':
        # building a cache_id is only needed for persistent CacheRegions
        cache_id = f"pymordemos.thermalblock_adaptive {args['--grid']}"
        fom.enable_caching(args['--cache-region'], cache_id)

    if args['--plot-solutions']:
        print('Showing some solutions')
        Us = ()
        legend = ()
        for mu in problem.parameter_space.sample_randomly(2):
            print(f"Solving for diffusion = \n{mu['diffusion']} ... ")
            sys.stdout.flush()
            Us = Us + (fom.solve(mu), )
            legend = legend + (str(mu['diffusion']), )
        fom.visualize(Us,
                      legend=legend,
                      title='Detailed Solutions for different parameters',
                      block=True)

    print('RB generation ...')

    product = fom.h1_0_semi_product if args['--product'] == 'h1' else None
    coercivity_estimator = ExpressionParameterFunctional(
        'min([diffusion[0], diffusion[1]**2])', fom.parameters)
    reductors = {
        'residual_basis':
        CoerciveRBReductor(fom,
                           product=product,
                           coercivity_estimator=coercivity_estimator),
        'traditional':
        SimpleCoerciveRBReductor(fom,
                                 product=product,
                                 coercivity_estimator=coercivity_estimator)
    }
    reductor = reductors[args['--reductor']]

    pool = new_parallel_pool(ipython_num_engines=args['--ipython-engines'],
                             ipython_profile=args['--ipython-profile'])
    greedy_data = rb_adaptive_greedy(
        fom,
        reductor,
        problem.parameter_space,
        validation_mus=args['--validation-mus'],
        rho=args['--rho'],
        gamma=args['--gamma'],
        theta=args['--theta'],
        use_estimator=not args['--without-estimator'],
        error_norm=fom.h1_0_semi_norm,
        max_extensions=args['RBSIZE'],
        visualize=not args['--no-visualize-refinement'])

    rom = greedy_data['rom']

    if args['--pickle']:
        print(
            f"\nWriting reduced model to file {args['--pickle']}_reduced ...")
        with open(args['--pickle'] + '_reduced', 'wb') as f:
            dump(rom, f)
        print(
            f"Writing detailed model and reductor to file {args['--pickle']}_detailed ..."
        )
        with open(args['--pickle'] + '_detailed', 'wb') as f:
            dump((fom, reductor), f)

    print('\nSearching for maximum error on random snapshots ...')

    results = reduction_error_analysis(
        rom,
        fom=fom,
        reductor=reductor,
        estimator=True,
        error_norms=(fom.h1_0_semi_norm, ),
        condition=True,
        test_mus=problem.parameter_space.sample_randomly(args['--test']),
        basis_sizes=25 if args['--plot-error-sequence'] else 1,
        plot=True,
        pool=pool)

    real_rb_size = rom.solution_space.dim

    print('''
*** RESULTS ***

Problem:
   number of blocks:                   2x2
   h:                                  sqrt(2)/{args[--grid]}

Greedy basis generation:
   estimator disabled:                 {args[--without-estimator]}
   extension method:                   {args[--extension-alg]}
   product:                            {args[--product]}
   prescribed basis size:              {args[RBSIZE]}
   actual basis size:                  {real_rb_size}
   elapsed time:                       {greedy_data[time]}
'''.format(**locals()))
    print(results['summary'])

    sys.stdout.flush()

    if args['--plot-error-sequence']:
        from matplotlib import pyplot as plt
        plt.show(results['figure'])
    if args['--plot-err']:
        mumax = results['max_error_mus'][0, -1]
        U = fom.solve(mumax)
        URB = reductor.reconstruct(rom.solve(mumax))
        fom.visualize(
            (U, URB, U - URB),
            legend=('Detailed Solution', 'Reduced Solution', 'Error'),
            title='Maximum Error Solution',
            separate_colorbars=True,
            block=True)
Beispiel #7
0
def main(args):
    args = docopt(__doc__, args)
    args['--cache-region'] = args['--cache-region'].lower()
    args['--ei-alg'] = args['--ei-alg'].lower()
    assert args['--ei-alg'] in ('ei_greedy', 'deim')
    args['--grid'] = int(args['--grid'])
    args['--grid-type'] = args['--grid-type'].lower()
    assert args['--grid-type'] in ('rect', 'tria')
    args['--initial-data'] = args['--initial-data'].lower()
    assert args['--initial-data'] in ('sin', 'bump')
    args['--lxf-lambda'] = float(args['--lxf-lambda'])
    args['--nt'] = int(args['--nt'])
    args['--not-periodic'] = bool(args['--not-periodic'])
    args['--num-flux'] = args['--num-flux'].lower()
    assert args['--num-flux'] in ('lax_friedrichs', 'engquist_osher')
    args['--plot-error-landscape-N'] = int(args['--plot-error-landscape-N'])
    args['--plot-error-landscape-M'] = int(args['--plot-error-landscape-M'])
    args['--test'] = int(args['--test'])
    args['--vx'] = float(args['--vx'])
    args['--vy'] = float(args['--vy'])
    args['--ipython-engines'] = int(args['--ipython-engines'])
    args['EXP_MIN'] = int(args['EXP_MIN'])
    args['EXP_MAX'] = int(args['EXP_MAX'])
    args['EI_SNAPSHOTS'] = int(args['EI_SNAPSHOTS'])
    args['EISIZE'] = int(args['EISIZE'])
    args['SNAPSHOTS'] = int(args['SNAPSHOTS'])
    args['RBSIZE'] = int(args['RBSIZE'])

    print('Setup Problem ...')
    problem = burgers_problem_2d(vx=args['--vx'],
                                 vy=args['--vy'],
                                 initial_data_type=args['--initial-data'],
                                 parameter_range=(args['EXP_MIN'],
                                                  args['EXP_MAX']),
                                 torus=not args['--not-periodic'])

    print('Discretize ...')
    if args['--grid-type'] == 'rect':
        args['--grid'] *= 1. / math.sqrt(2)
    fom, _ = discretize_instationary_fv(
        problem,
        diameter=1. / args['--grid'],
        grid_type=RectGrid if args['--grid-type'] == 'rect' else TriaGrid,
        num_flux=args['--num-flux'],
        lxf_lambda=args['--lxf-lambda'],
        nt=args['--nt'])

    if args['--cache-region'] != 'none':
        fom.enable_caching(args['--cache-region'])

    print(fom.operator.grid)

    print(f'The parameter type is {fom.parameter_type}')

    if args['--plot-solutions']:
        print('Showing some solutions')
        Us = ()
        legend = ()
        for mu in fom.parameter_space.sample_uniformly(4):
            print(f"Solving for exponent = {mu['exponent']} ... ")
            sys.stdout.flush()
            Us = Us + (fom.solve(mu), )
            legend = legend + (f"exponent: {mu['exponent']}", )
        fom.visualize(Us,
                      legend=legend,
                      title='Detailed Solutions',
                      block=True)

    pool = new_parallel_pool(ipython_num_engines=args['--ipython-engines'],
                             ipython_profile=args['--ipython-profile'])
    eim, ei_data = interpolate_operators(
        fom,
        ['operator'],
        fom.parameter_space.sample_uniformly(args['EI_SNAPSHOTS']),  # NOQA
        error_norm=fom.l2_norm,
        product=fom.l2_product,
        max_interpolation_dofs=args['EISIZE'],
        alg=args['--ei-alg'],
        pool=pool)

    if args['--plot-ei-err']:
        print('Showing some EI errors')
        ERRs = ()
        legend = ()
        for mu in fom.parameter_space.sample_randomly(2):
            print(f"Solving for exponent = \n{mu['exponent']} ... ")
            sys.stdout.flush()
            U = fom.solve(mu)
            U_EI = eim.solve(mu)
            ERR = U - U_EI
            ERRs = ERRs + (ERR, )
            legend = legend + (f"exponent: {mu['exponent']}", )
            print(f'Error: {np.max(fom.l2_norm(ERR))}')
        fom.visualize(ERRs,
                      legend=legend,
                      title='EI Errors',
                      separate_colorbars=True)

        print('Showing interpolation DOFs ...')
        U = np.zeros(U.dim)
        dofs = eim.operator.interpolation_dofs
        U[dofs] = np.arange(1, len(dofs) + 1)
        U[eim.operator.source_dofs] += int(len(dofs) / 2)
        fom.visualize(fom.solution_space.make_array(U),
                      title='Interpolation DOFs')

    print('RB generation ...')

    reductor = InstationaryRBReductor(eim)

    greedy_data = rb_greedy(fom,
                            reductor,
                            fom.parameter_space.sample_uniformly(
                                args['SNAPSHOTS']),
                            use_estimator=False,
                            error_norm=lambda U: np.max(fom.l2_norm(U)),
                            extension_params={'method': 'pod'},
                            max_extensions=args['RBSIZE'],
                            pool=pool)

    rom = greedy_data['rom']

    print('\nSearching for maximum error on random snapshots ...')

    tic = time.time()

    mus = fom.parameter_space.sample_randomly(args['--test'])

    def error_analysis(N, M):
        print(f'N = {N}, M = {M}: ', end='')
        rom = reductor.reduce(N)
        rom = rom.with_(operator=rom.operator.with_cb_dim(M))
        l2_err_max = -1
        mumax = None
        for mu in mus:
            print('.', end='')
            sys.stdout.flush()
            u = rom.solve(mu)
            URB = reductor.reconstruct(u)
            U = fom.solve(mu)
            l2_err = np.max(fom.l2_norm(U - URB))
            l2_err = np.inf if not np.isfinite(l2_err) else l2_err
            if l2_err > l2_err_max:
                l2_err_max = l2_err
                mumax = mu
        print()
        return l2_err_max, mumax

    error_analysis = np.frompyfunc(error_analysis, 2, 2)

    real_rb_size = len(reductor.bases['RB'])
    real_cb_size = len(ei_data['basis'])
    if args['--plot-error-landscape']:
        N_count = min(real_rb_size - 1, args['--plot-error-landscape-N'])
        M_count = min(real_cb_size - 1, args['--plot-error-landscape-M'])
        Ns = np.linspace(1, real_rb_size, N_count).astype(np.int)
        Ms = np.linspace(1, real_cb_size, M_count).astype(np.int)
    else:
        Ns = np.array([real_rb_size])
        Ms = np.array([real_cb_size])

    N_grid, M_grid = np.meshgrid(Ns, Ms)

    errs, err_mus = error_analysis(N_grid, M_grid)
    errs = errs.astype(np.float)

    l2_err_max = errs[-1, -1]
    mumax = err_mus[-1, -1]
    toc = time.time()
    t_est = toc - tic

    print('''
    *** RESULTS ***

    Problem:
       parameter range:                    ({args[EXP_MIN]}, {args[EXP_MAX]})
       h:                                  sqrt(2)/{args[--grid]}
       grid-type:                          {args[--grid-type]}
       initial-data:                       {args[--initial-data]}
       lxf-lambda:                         {args[--lxf-lambda]}
       nt:                                 {args[--nt]}
       not-periodic:                       {args[--not-periodic]}
       num-flux:                           {args[--num-flux]}
       (vx, vy):                           ({args[--vx]}, {args[--vy]})

    Greedy basis generation:
       number of ei-snapshots:             {args[EI_SNAPSHOTS]}
       prescribed collateral basis size:   {args[EISIZE]}
       actual collateral basis size:       {real_cb_size}
       number of snapshots:                {args[SNAPSHOTS]}
       prescribed basis size:              {args[RBSIZE]}
       actual basis size:                  {real_rb_size}
       elapsed time:                       {greedy_data[time]}

    Stochastic error estimation:
       number of samples:                  {args[--test]}
       maximal L2-error:                   {l2_err_max}  (mu = {mumax})
       elapsed time:                       {t_est}
    '''.format(**locals()))

    sys.stdout.flush()
    if args['--plot-error-landscape']:
        import matplotlib.pyplot as plt
        import mpl_toolkits.mplot3d  # NOQA
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        # we have to rescale the errors since matplotlib does not support logarithmic scales on 3d plots
        # https://github.com/matplotlib/matplotlib/issues/209
        surf = ax.plot_surface(M_grid,
                               N_grid,
                               np.log(np.minimum(errs, 1)) / np.log(10),
                               rstride=1,
                               cstride=1,
                               cmap='jet')
        plt.show()
    if args['--plot-err']:
        U = fom.solve(mumax)
        URB = reductor.reconstruct(rom.solve(mumax))
        fom.visualize(
            (U, URB, U - URB),
            legend=('Detailed Solution', 'Reduced Solution', 'Error'),
            title='Maximum Error Solution',
            separate_colorbars=True)

    return ei_data, greedy_data
def thermalblock_demo(args):
    args['--grid'] = int(args['--grid'])
    args['RBSIZE'] = int(args['RBSIZE'])
    args['--test'] = int(args['--test'])
    args['--ipython-engines'] = int(args['--ipython-engines'])
    args['--estimator-norm'] = args['--estimator-norm'].lower()
    assert args['--estimator-norm'] in {'trivial', 'h1'}
    args['--extension-alg'] = args['--extension-alg'].lower()
    assert args['--extension-alg'] in {'trivial', 'gram_schmidt', 'h1_gram_schmidt'}
    args['--reductor'] = args['--reductor'].lower()
    assert args['--reductor'] in {'traditional', 'residual_basis'}
    args['--cache-region'] = args['--cache-region'].lower()
    args['--validation-mus'] = int(args['--validation-mus'])
    args['--rho'] = float(args['--rho'])
    args['--gamma'] = float(args['--gamma'])
    args['--theta'] = float(args['--theta'])

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

    print('Setup Problem ...')
    problem = ThermalBlockProblem(num_blocks=(2, 2))
    functionals = [ExpressionParameterFunctional('diffusion[0]', {'diffusion': (2,)}),
                   ExpressionParameterFunctional('diffusion[1]**2', {'diffusion': (2,)}),
                   ExpressionParameterFunctional('diffusion[0]', {'diffusion': (2,)}),
                   ExpressionParameterFunctional('diffusion[1]', {'diffusion': (2,)})]
    problem = EllipticProblem(domain=problem.domain,
                              diffusion_functions=problem.diffusion_functions,
                              diffusion_functionals=functionals,
                              rhs=problem.rhs,
                              parameter_space=CubicParameterSpace({'diffusion': (2,)}, 0.1, 1.))

    print('Discretize ...')
    discretization, _ = discretize_elliptic_cg(problem, diameter=1. / args['--grid'])

    if args['--list-vector-array']:
        from pymor.playground.discretizers.numpylistvectorarray import convert_to_numpy_list_vector_array
        discretization = convert_to_numpy_list_vector_array(discretization)

    if args['--cache-region'] != 'none':
        discretization.enable_caching(args['--cache-region'])

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

    if args['--plot-solutions']:
        print('Showing some solutions')
        Us = ()
        legend = ()
        for mu in discretization.parameter_space.sample_randomly(2):
            print('Solving for diffusion = \n{} ... '.format(mu['diffusion']))
            sys.stdout.flush()
            Us = Us + (discretization.solve(mu),)
            legend = legend + (str(mu['diffusion']),)
        discretization.visualize(Us, legend=legend, title='Detailed Solutions for different parameters', block=True)

    print('RB generation ...')

    product = discretization.h1_0_semi_product if args['--estimator-norm'] == 'h1' else None
    coercivity_estimator=ExpressionParameterFunctional('min([diffusion[0], diffusion[1]**2])', discretization.parameter_type)
    reductors = {'residual_basis': partial(reduce_coercive, product=product,
                                   coercivity_estimator=coercivity_estimator),
                 'traditional': partial(reduce_coercive_simple, product=product,
                                        coercivity_estimator=coercivity_estimator)}
    reductor = reductors[args['--reductor']]
    extension_algorithms = {'trivial': trivial_basis_extension,
                            'gram_schmidt': gram_schmidt_basis_extension,
                            'h1_gram_schmidt': partial(gram_schmidt_basis_extension, product=discretization.h1_0_semi_product)}
    extension_algorithm = extension_algorithms[args['--extension-alg']]

    pool = new_parallel_pool(ipython_num_engines=args['--ipython-engines'], ipython_profile=args['--ipython-profile'])
    greedy_data = adaptive_greedy(discretization, reductor,
                                  validation_mus=args['--validation-mus'], rho=args['--rho'], gamma=args['--gamma'],
                                  theta=args['--theta'],
                                  use_estimator=not args['--without-estimator'], error_norm=discretization.h1_0_semi_norm,
                                  extension_algorithm=extension_algorithm, max_extensions=args['RBSIZE'],
                                  visualize=args['--visualize-refinement'])

    rb_discretization, reconstructor = greedy_data['reduced_discretization'], greedy_data['reconstructor']

    if args['--pickle']:
        print('\nWriting reduced discretization to file {} ...'.format(args['--pickle'] + '_reduced'))
        with open(args['--pickle'] + '_reduced', 'wb') as f:
            dump(rb_discretization, f)
        print('Writing detailed discretization and reconstructor to file {} ...'.format(args['--pickle'] + '_detailed'))
        with open(args['--pickle'] + '_detailed', 'wb') as f:
            dump((discretization, reconstructor), f)

    print('\nSearching for maximum error on random snapshots ...')

    results = reduction_error_analysis(rb_discretization,
                                       discretization=discretization,
                                       reconstructor=reconstructor,
                                       estimator=True,
                                       error_norms=(discretization.h1_0_semi_norm,),
                                       condition=True,
                                       test_mus=args['--test'],
                                       basis_sizes=25 if args['--plot-error-sequence'] else 1,
                                       plot=True,
                                       pool=pool)

    real_rb_size = rb_discretization.solution_space.dim

    print('''
*** RESULTS ***

Problem:
   number of blocks:                   2x2
   h:                                  sqrt(2)/{args[--grid]}

Greedy basis generation:
   estimator disabled:                 {args[--without-estimator]}
   estimator norm:                     {args[--estimator-norm]}
   extension method:                   {args[--extension-alg]}
   prescribed basis size:              {args[RBSIZE]}
   actual basis size:                  {real_rb_size}
   elapsed time:                       {greedy_data[time]}
'''.format(**locals()))
    print(results['summary'])

    sys.stdout.flush()

    if args['--plot-error-sequence']:
        from matplotlib import pyplot as plt
        plt.show(results['figure'])
    if args['--plot-err']:
        mumax = results['max_error_mus'][0, -1]
        U = discretization.solve(mumax)
        URB = reconstructor.reconstruct(rb_discretization.solve(mumax))
        discretization.visualize((U, URB, U - URB), legend=('Detailed Solution', 'Reduced Solution', 'Error'),
                                 title='Maximum Error Solution', separate_colorbars=True, block=True)
Beispiel #9
0
def main(
    xblocks: int = Argument(..., help='Number of blocks in x direction.'),
    yblocks: int = Argument(..., help='Number of blocks in y direction.'),
    snapshots: int = Argument(
        ...,
        help='naive: ignored\n\n'
        'greedy/pod: Number of training_set parameters per block '
        '(in total SNAPSHOTS^(XBLOCKS * YBLOCKS) parameters).\n\n'
        'adaptive_greedy: size of validation set.\n\n'),
    rbsize: int = Argument(..., help='Size of the reduced basis.'),
    adaptive_greedy_gamma: float = Option(
        0.2, help='See pymor.algorithms.adaptivegreedy.'),
    adaptive_greedy_rho: float = Option(
        1.1, help='See pymor.algorithms.adaptivegreedy.'),
    adaptive_greedy_theta: float = Option(
        0., help='See pymor.algorithms.adaptivegreedy.'),
    alg: Choices('naive greedy adaptive_greedy pod') = Option(
        'greedy', help='The model reduction algorithm to use.'),
    cache_region: Choices('none memory disk persistent') = Option(
        'none',
        help='Name of cache region to use for caching solution snapshots.'),
    extension_alg: Choices('trivial gram_schmidt') = Option(
        'gram_schmidt', help='Basis extension algorithm to be used.'),
    fenics: bool = Option(False, help='Use FEniCS model.'),
    greedy_with_error_estimator: bool = Option(
        True, help='Use error estimator for basis generation.'),
    grid: int = Option(100, help='Use grid with 4*NI*NI elements'),
    ipython_engines: int = Option(
        None,
        help='If positive, the number of IPython cluster engines to use for '
        'parallel greedy search. If zero, no parallelization is performed.'),
    ipython_profile: str = Option(
        None, help='IPython profile to use for parallelization.'),
    list_vector_array: bool = Option(
        False,
        help=
        'Solve using ListVectorArray[NumpyVector] instead of NumpyVectorArray.'
    ),
    order: int = Option(
        1,
        help=
        'Polynomial order of the Lagrange finite elements to use in FEniCS.'),
    pickle: str = Option(
        None,
        help=
        'Pickle reduced model, as well as reductor and high-dimensional model '
        'to files with this prefix.'),
    product: Choices('euclidean h1') = Option(
        'h1',
        help=
        'Product w.r.t. which to orthonormalize and calculate Riesz representatives.'
    ),
    plot_err: bool = Option(False, help='Plot error'),
    plot_error_sequence: bool = Option(
        False, help='Plot reduction error vs. basis size.'),
    plot_solutions: bool = Option(False, help='Plot some example solutions.'),
    reductor: Choices('traditional residual_basis') = Option(
        'residual_basis', help='Reductor (error estimator) to choose.'),
    test: int = Option(
        10, help='Use COUNT snapshots for stochastic error estimation.'),
):
    """Thermalblock demo."""

    if fenics and cache_region != 'none':
        raise ValueError(
            'Caching of high-dimensional solutions is not supported for FEniCS model.'
        )
    if not fenics and order != 1:
        raise ValueError(
            'Higher-order finite elements only supported for FEniCS model.')

    pool = new_parallel_pool(ipython_num_engines=ipython_engines,
                             ipython_profile=ipython_profile)

    if fenics:
        fom, fom_summary = discretize_fenics(xblocks, yblocks, grid, order)
    else:
        fom, fom_summary = discretize_pymor(xblocks, yblocks, grid,
                                            list_vector_array)

    parameter_space = fom.parameters.space(0.1, 1.)

    if cache_region != 'none':
        # building a cache_id is only needed for persistent CacheRegions
        cache_id = (f"pymordemos.thermalblock {fenics} {xblocks} {yblocks}"
                    f"{grid} {order}")
        fom.enable_caching(cache_region.value, cache_id)

    if plot_solutions:
        print('Showing some solutions')
        Us = ()
        legend = ()
        for mu in parameter_space.sample_randomly(2):
            print(f"Solving for diffusion = \n{mu['diffusion']} ... ")
            sys.stdout.flush()
            Us = Us + (fom.solve(mu), )
            legend = legend + (str(mu['diffusion']), )
        fom.visualize(Us,
                      legend=legend,
                      title='Detailed Solutions for different parameters',
                      separate_colorbars=False,
                      block=True)

    print('RB generation ...')

    # define estimator for coercivity constant
    from pymor.parameters.functionals import ExpressionParameterFunctional
    coercivity_estimator = ExpressionParameterFunctional(
        'min(diffusion)', fom.parameters)

    # inner product for computation of Riesz representatives
    product = fom.h1_0_semi_product if product == 'h1' else None

    if reductor == 'residual_basis':
        from pymor.reductors.coercive import CoerciveRBReductor
        reductor = CoerciveRBReductor(
            fom,
            product=product,
            coercivity_estimator=coercivity_estimator,
            check_orthonormality=False)
    elif reductor == 'traditional':
        from pymor.reductors.coercive import SimpleCoerciveRBReductor
        reductor = SimpleCoerciveRBReductor(
            fom,
            product=product,
            coercivity_estimator=coercivity_estimator,
            check_orthonormality=False)
    else:
        assert False  # this should never happen

    if alg == 'naive':
        rom, red_summary = reduce_naive(fom=fom,
                                        reductor=reductor,
                                        parameter_space=parameter_space,
                                        basis_size=rbsize)
    elif alg == 'greedy':
        parallel = greedy_with_error_estimator or not fenics  # cannot pickle FEniCS model
        rom, red_summary = reduce_greedy(
            fom=fom,
            reductor=reductor,
            parameter_space=parameter_space,
            snapshots_per_block=snapshots,
            extension_alg_name=extension_alg.value,
            max_extensions=rbsize,
            use_error_estimator=greedy_with_error_estimator,
            pool=pool if parallel else None)
    elif alg == 'adaptive_greedy':
        parallel = greedy_with_error_estimator or not fenics  # cannot pickle FEniCS model
        rom, red_summary = reduce_adaptive_greedy(
            fom=fom,
            reductor=reductor,
            parameter_space=parameter_space,
            validation_mus=snapshots,
            extension_alg_name=extension_alg.value,
            max_extensions=rbsize,
            use_error_estimator=greedy_with_error_estimator,
            rho=adaptive_greedy_rho,
            gamma=adaptive_greedy_gamma,
            theta=adaptive_greedy_theta,
            pool=pool if parallel else None)
    elif alg == 'pod':
        rom, red_summary = reduce_pod(fom=fom,
                                      reductor=reductor,
                                      parameter_space=parameter_space,
                                      snapshots_per_block=snapshots,
                                      basis_size=rbsize)
    else:
        assert False  # this should never happen

    if pickle:
        print(f"\nWriting reduced model to file {pickle}_reduced ...")
        with open(pickle + '_reduced', 'wb') as f:
            dump((rom, parameter_space), f)
        if not fenics:  # FEniCS data structures do not support serialization
            print(
                f"Writing detailed model and reductor to file {pickle}_detailed ..."
            )
            with open(pickle + '_detailed', 'wb') as f:
                dump((fom, reductor), f)

    print('\nSearching for maximum error on random snapshots ...')

    results = reduction_error_analysis(
        rom,
        fom=fom,
        reductor=reductor,
        error_estimator=True,
        error_norms=(fom.h1_0_semi_norm, fom.l2_norm),
        condition=True,
        test_mus=parameter_space.sample_randomly(test, seed=999),
        basis_sizes=0 if plot_error_sequence else 1,
        plot=plot_error_sequence,
        pool=None if fenics else pool  # cannot pickle FEniCS model
    )

    print('\n*** RESULTS ***\n')
    print(fom_summary)
    print(red_summary)
    print(results['summary'])
    sys.stdout.flush()

    if plot_error_sequence:
        import matplotlib.pyplot
        matplotlib.pyplot.show()
    if plot_err:
        mumax = results['max_error_mus'][0, -1]
        U = fom.solve(mumax)
        URB = reductor.reconstruct(rom.solve(mumax))
        fom.visualize(
            (U, URB, U - URB),
            legend=('Detailed Solution', 'Reduced Solution', 'Error'),
            title='Maximum Error Solution',
            separate_colorbars=True,
            block=True)

    global test_results
    test_results = results
Beispiel #10
0
def main(args):

    args = parse_arguments(args)

    pool = new_parallel_pool(ipython_num_engines=args['--ipython-engines'], ipython_profile=args['--ipython-profile'])

    if args['--fenics']:
        fom, fom_summary = discretize_fenics(args['XBLOCKS'], args['YBLOCKS'], args['--grid'], args['--order'])
    else:
        fom, fom_summary = discretize_pymor(args['XBLOCKS'], args['YBLOCKS'], args['--grid'], args['--list-vector-array'])

    if args['--cache-region'] != 'none':
        fom.enable_caching(args['--cache-region'])

    if args['--plot-solutions']:
        print('Showing some solutions')
        Us = ()
        legend = ()
        for mu in fom.parameter_space.sample_randomly(2):
            print(f"Solving for diffusion = \n{mu['diffusion']} ... ")
            sys.stdout.flush()
            Us = Us + (fom.solve(mu),)
            legend = legend + (str(mu['diffusion']),)
        fom.visualize(Us, legend=legend, title='Detailed Solutions for different parameters',
                      separate_colorbars=False, block=True)

    print('RB generation ...')

    # define estimator for coercivity constant
    from pymor.parameters.functionals import ExpressionParameterFunctional
    coercivity_estimator = ExpressionParameterFunctional('min(diffusion)', fom.parameter_type)

    # inner product for computation of Riesz representatives
    product = fom.h1_0_semi_product if args['--product'] == 'h1' else None

    if args['--reductor'] == 'residual_basis':
        from pymor.reductors.coercive import CoerciveRBReductor
        reductor = CoerciveRBReductor(fom, product=product, coercivity_estimator=coercivity_estimator,
                                      check_orthonormality=False)
    elif args['--reductor'] == 'traditional':
        from pymor.reductors.coercive import SimpleCoerciveRBReductor
        reductor = SimpleCoerciveRBReductor(fom, product=product, coercivity_estimator=coercivity_estimator,
                                            check_orthonormality=False)
    else:
        assert False  # this should never happen

    if args['--alg'] == 'naive':
        rom, red_summary = reduce_naive(fom=fom, reductor=reductor, basis_size=args['RBSIZE'])
    elif args['--alg'] == 'greedy':
        parallel = not (args['--fenics'] and args['--greedy-without-estimator'])  # cannot pickle FEniCS model
        rom, red_summary = reduce_greedy(fom=fom, reductor=reductor, snapshots_per_block=args['SNAPSHOTS'],
                                         extension_alg_name=args['--extension-alg'],
                                         max_extensions=args['RBSIZE'],
                                         use_estimator=not args['--greedy-without-estimator'],
                                         pool=pool if parallel else None)
    elif args['--alg'] == 'adaptive_greedy':
        parallel = not (args['--fenics'] and args['--greedy-without-estimator'])  # cannot pickle FEniCS model
        rom, red_summary = reduce_adaptive_greedy(fom=fom, reductor=reductor, validation_mus=args['SNAPSHOTS'],
                                                  extension_alg_name=args['--extension-alg'],
                                                  max_extensions=args['RBSIZE'],
                                                  use_estimator=not args['--greedy-without-estimator'],
                                                  rho=args['--adaptive-greedy-rho'],
                                                  gamma=args['--adaptive-greedy-gamma'],
                                                  theta=args['--adaptive-greedy-theta'],
                                                  pool=pool if parallel else None)
    elif args['--alg'] == 'pod':
        rom, red_summary = reduce_pod(fom=fom, reductor=reductor, snapshots_per_block=args['SNAPSHOTS'],
                                      basis_size=args['RBSIZE'])
    else:
        assert False  # this should never happen

    if args['--pickle']:
        print(f"\nWriting reduced model to file {args['--pickle']}_reduced ...")
        with open(args['--pickle'] + '_reduced', 'wb') as f:
            dump(rom, f)
        if not args['--fenics']:  # FEniCS data structures do not support serialization
            print(f"Writing detailed model and reductor to file {args['--pickle']}_detailed ...")
            with open(args['--pickle'] + '_detailed', 'wb') as f:
                dump((fom, reductor), f)

    print('\nSearching for maximum error on random snapshots ...')

    results = reduction_error_analysis(rom,
                                       fom=fom,
                                       reductor=reductor,
                                       estimator=True,
                                       error_norms=(fom.h1_0_semi_norm, fom.l2_norm),
                                       condition=True,
                                       test_mus=args['--test'],
                                       basis_sizes=0 if args['--plot-error-sequence'] else 1,
                                       plot=args['--plot-error-sequence'],
                                       pool=None if args['--fenics'] else pool,  # cannot pickle FEniCS model
                                       random_seed=999)

    print('\n*** RESULTS ***\n')
    print(fom_summary)
    print(red_summary)
    print(results['summary'])
    sys.stdout.flush()

    if args['--plot-error-sequence']:
        import matplotlib.pyplot
        matplotlib.pyplot.show(results['figure'])
    if args['--plot-err']:
        mumax = results['max_error_mus'][0, -1]
        U = fom.solve(mumax)
        URB = reductor.reconstruct(rom.solve(mumax))
        fom.visualize((U, URB, U - URB), legend=('Detailed Solution', 'Reduced Solution', 'Error'),
                    title='Maximum Error Solution', separate_colorbars=True, block=True)

    return results
Beispiel #11
0
def main(
    rbsize: int = Argument(..., help='Size of the reduced basis.'),

    cache_region: Choices('none memory disk persistent') = Option(
        'none',
        help='Name of cache region to use for caching solution snapshots.'
    ),
    error_estimator: bool = Option(True, help='Use error estimator for basis generation.'),
    gamma: float = Option(0.2, help='Weight factor for age penalty term in refinement indicators.'),
    grid: int = Option(100, help='Use grid with 2*NI*NI elements.'),
    ipython_engines: int = Option(
        0,
        help='If positive, the number of IPython cluster engines to use for parallel greedy search. '
             'If zero, no parallelization is performed.'
    ),
    ipython_profile: str = Option(None, help='IPython profile to use for parallelization.'),
    list_vector_array: bool = Option(
        False,
        help='Solve using ListVectorArray[NumpyVector] instead of NumpyVectorArray.'
    ),
    pickle: str = Option(
        None,
        help='Pickle reduced discretization, as well as reductor and high-dimensional model to files with this prefix.'
    ),
    plot_err: bool = Option(False, help='Plot error.'),
    plot_solutions: bool = Option(False, help='Plot some example solutions.'),
    plot_error_sequence: bool = Option(False, help='Plot reduction error vs. basis size.'),
    product: Choices('euclidean h1') = Option(
        'h1',
        help='Product  w.r.t. which to orthonormalize and calculate Riesz representatives.'
    ),
    reductor: Choices('traditional residual_basis') = Option(
        'residual_basis',
        help='Reductor (error estimator) to choose (traditional, residual_basis).'
    ),
    rho: float = Option(1.1, help='Maximum allowed ratio between error on validation set and on training set.'),
    test: int = Option(10, help='Use COUNT snapshots for stochastic error estimation.'),
    theta: float = Option(0., help='Ratio of elements to refine.'),
    validation_mus: int = Option(0, help='Size of validation set.'),
    visualize_refinement: bool = Option(True, help='Visualize the training set refinement indicators.'),
):
    """Modified thermalblock demo using adaptive greedy basis generation algorithm."""

    problem = thermal_block_problem(num_blocks=(2, 2))
    functionals = [ExpressionParameterFunctional('diffusion[0]', {'diffusion': 2}),
                   ExpressionParameterFunctional('diffusion[1]**2', {'diffusion': 2}),
                   ExpressionParameterFunctional('diffusion[0]', {'diffusion': 2}),
                   ExpressionParameterFunctional('diffusion[1]', {'diffusion': 2})]
    problem = problem.with_(
        diffusion=problem.diffusion.with_(coefficients=functionals),
    )

    print('Discretize ...')
    fom, _ = discretize_stationary_cg(problem, diameter=1. / grid)

    if list_vector_array:
        from pymor.discretizers.builtin.list import convert_to_numpy_list_vector_array
        fom = convert_to_numpy_list_vector_array(fom)

    if cache_region != 'none':
        # building a cache_id is only needed for persistent CacheRegions
        cache_id = f"pymordemos.thermalblock_adaptive {grid}"
        fom.enable_caching(cache_region.value, cache_id)

    if plot_solutions:
        print('Showing some solutions')
        Us = ()
        legend = ()
        for mu in problem.parameter_space.sample_randomly(2):
            print(f"Solving for diffusion = \n{mu['diffusion']} ... ")
            sys.stdout.flush()
            Us = Us + (fom.solve(mu),)
            legend = legend + (str(mu['diffusion']),)
        fom.visualize(Us, legend=legend, title='Detailed Solutions for different parameters', block=True)

    print('RB generation ...')

    product_op = fom.h1_0_semi_product if product == 'h1' else None
    coercivity_estimator = ExpressionParameterFunctional('min([diffusion[0], diffusion[1]**2])',
                                                         fom.parameters)
    reductors = {'residual_basis': CoerciveRBReductor(fom, product=product_op,
                                                      coercivity_estimator=coercivity_estimator),
                 'traditional': SimpleCoerciveRBReductor(fom, product=product_op,
                                                         coercivity_estimator=coercivity_estimator)}
    reductor = reductors[reductor]

    pool = new_parallel_pool(ipython_num_engines=ipython_engines, ipython_profile=ipython_profile)
    greedy_data = rb_adaptive_greedy(
        fom, reductor, problem.parameter_space,
        validation_mus=validation_mus,
        rho=rho,
        gamma=gamma,
        theta=theta,
        use_error_estimator=error_estimator,
        error_norm=fom.h1_0_semi_norm,
        max_extensions=rbsize,
        visualize=visualize_refinement
    )

    rom = greedy_data['rom']

    if pickle:
        print(f"\nWriting reduced model to file {pickle}_reduced ...")
        with open(pickle + '_reduced', 'wb') as f:
            dump(rom, f)
        print(f"Writing detailed model and reductor to file {pickle}_detailed ...")
        with open(pickle + '_detailed', 'wb') as f:
            dump((fom, reductor), f)

    print('\nSearching for maximum error on random snapshots ...')

    results = reduction_error_analysis(rom,
                                       fom=fom,
                                       reductor=reductor,
                                       error_estimator=True,
                                       error_norms=(fom.h1_0_semi_norm,),
                                       condition=True,
                                       test_mus=problem.parameter_space.sample_randomly(test),
                                       basis_sizes=25 if plot_error_sequence else 1,
                                       plot=True,
                                       pool=pool)

    real_rb_size = rom.solution_space.dim

    print('''
*** RESULTS ***

Problem:
   number of blocks:                   2x2
   h:                                  sqrt(2)/{grid}

Greedy basis generation:
   error estimator enalbed:            {error_estimator}
   product:                            {product}
   prescribed basis size:              {rbsize}
   actual basis size:                  {real_rb_size}
   elapsed time:                       {greedy_data[time]}
'''.format(**locals()))
    print(results['summary'])

    sys.stdout.flush()

    if plot_error_sequence:
        from matplotlib import pyplot as plt
        plt.show()
    if plot_err:
        mumax = results['max_error_mus'][0, -1]
        U = fom.solve(mumax)
        URB = reductor.reconstruct(rom.solve(mumax))
        fom.visualize((U, URB, U - URB), legend=('Detailed Solution', 'Reduced Solution', 'Error'),
                      title='Maximum Error Solution', separate_colorbars=True, block=True)