def __init__(self, args): self.args = args self.first = True self.problem = thermal_block_problem(num_blocks=(args['XBLOCKS'], args['YBLOCKS']), parameter_range=(PARAM_MIN, PARAM_MAX)) self.m, pack = discretize_stationary_cg(self.problem, diameter=1. / args['--grid']) self.grid = pack['grid']
def __init__(self, args): self.args = args self.first = True self.problem = thermal_block_problem(num_blocks=(args['XBLOCKS'], args['YBLOCKS']), parameter_range=(PARAM_MIN, PARAM_MAX)) self.discretization, pack = discretize_stationary_cg(self.problem, diameter=1. / args['--grid']) self.grid = pack['grid']
def __init__(self, xblocks, yblocks, snapshots, rbsize, grid, product): self.snapshots, self.rbsize, self.product = snapshots, rbsize, product self.xblocks, self.yblocks = xblocks, yblocks self.first = True self.problem = thermal_block_problem(num_blocks=(xblocks, yblocks), parameter_range=(PARAM_MIN, PARAM_MAX)) self.m, pack = discretize_stationary_cg(self.problem, diameter=1. / grid) self.grid = pack['grid']
def thermalblock_factory(xblocks, yblocks, diameter, seed): from pymor.analyticalproblems.thermalblock import thermal_block_problem from pymor.discretizers.cg import discretize_stationary_cg from pymor.functions.basic import GenericFunction from pymor.operators.cg import InterpolationOperator p = thermal_block_problem((xblocks, yblocks)) d, d_data = discretize_stationary_cg(p, diameter) f = GenericFunction(lambda X, mu: X[..., 0]**mu['exp'] + X[..., 1], dim_domain=2, parameter_type={'exp': ()}) iop = InterpolationOperator(d_data['grid'], f) U = d.operator.source.empty() V = d.operator.range.empty() np.random.seed(seed) for exp in np.random.random(5): U.append(iop.as_vector(exp)) for exp in np.random.random(6): V.append(iop.as_vector(exp)) return d.operator, d.parameter_space.sample_randomly(1, seed=seed)[0], U, V, d.h1_product, d.l2_product
def thermalblock_factory(xblocks, yblocks, diameter, seed): from pymor.analyticalproblems.thermalblock import thermal_block_problem from pymor.discretizers.builtin import discretize_stationary_cg from pymor.functions.basic import GenericFunction from pymor.discretizers.builtin.cg import InterpolationOperator p = thermal_block_problem((xblocks, yblocks)) m, m_data = discretize_stationary_cg(p, diameter) f = GenericFunction(lambda X, mu: X[..., 0]**mu['exp'] + X[..., 1], dim_domain=2, parameter_type={'exp': ()}) iop = InterpolationOperator(m_data['grid'], f) U = m.operator.source.empty() V = m.operator.range.empty() np.random.seed(seed) for exp in np.random.random(5): U.append(iop.as_vector(exp)) for exp in np.random.random(6): V.append(iop.as_vector(exp)) return m.operator, m.parameter_space.sample_randomly(1, seed=seed)[0], U, V, m.h1_product, m.l2_product
def discretize_pymor(xblocks, yblocks, grid_num_intervals, use_list_vector_array): from pymor.analyticalproblems.thermalblock import thermal_block_problem from pymor.discretizers.builtin import discretize_stationary_cg from pymor.playground.discretizers.numpylistvectorarray import convert_to_numpy_list_vector_array print('Discretize ...') # setup analytical problem problem = thermal_block_problem(num_blocks=(xblocks, yblocks)) # discretize using continuous finite elements fom, _ = discretize_stationary_cg(problem, diameter=1. / grid_num_intervals) if use_list_vector_array: fom = convert_to_numpy_list_vector_array(fom) summary = f'''pyMOR model: number of blocks: {xblocks}x{yblocks} grid intervals: {grid_num_intervals} ListVectorArray: {use_list_vector_array} ''' return fom, summary
def discretize_pymor(xblocks, yblocks, grid_num_intervals, use_list_vector_array): from pymor.analyticalproblems.thermalblock import thermal_block_problem from pymor.discretizers.cg import discretize_stationary_cg from pymor.playground.discretizers.numpylistvectorarray import convert_to_numpy_list_vector_array print('Discretize ...') # setup analytical problem problem = thermal_block_problem(num_blocks=(xblocks, yblocks)) # discretize using continuous finite elements d, _ = discretize_stationary_cg(problem, diameter=1. / grid_num_intervals) if use_list_vector_array: d = convert_to_numpy_list_vector_array(d) summary = '''pyMOR discretization: number of blocks: {xblocks}x{yblocks} grid intervals: {grid_num_intervals} ListVectorArray: {use_list_vector_array} '''.format(**locals()) return d, summary
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)
# Copyright 2013-2017 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) import pytest from pymor.domaindescriptions.basic import RectDomain from pymor.analyticalproblems.burgers import burgers_problem, burgers_problem_2d from pymor.analyticalproblems.elliptic import StationaryProblem from pymor.analyticalproblems.helmholtz import helmholtz_problem from pymor.analyticalproblems.thermalblock import thermal_block_problem from pymor.functions.basic import GenericFunction, ConstantFunction, LincombFunction from pymor.parameters.functionals import ExpressionParameterFunctional picklable_thermalblock_problems = \ [thermal_block_problem(), thermal_block_problem(num_blocks=(3, 2)), thermal_block_problem(num_blocks=(1, 1)), thermal_block_problem(num_blocks=(2, 2), parameter_range=(1., 100.))] non_picklable_thermalblock_problems = \ [thermal_block_problem(num_blocks=(1, 3), parameter_range=(0.4, 0.5)).with_( 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),
# Copyright 2013-2018 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) import pytest from pymor.domaindescriptions.basic import RectDomain from pymor.analyticalproblems.burgers import burgers_problem, burgers_problem_2d from pymor.analyticalproblems.elliptic import StationaryProblem from pymor.analyticalproblems.helmholtz import helmholtz_problem from pymor.analyticalproblems.thermalblock import thermal_block_problem from pymor.functions.basic import GenericFunction, ConstantFunction, LincombFunction from pymor.parameters.functionals import ExpressionParameterFunctional picklable_thermalblock_problems = \ [thermal_block_problem(), thermal_block_problem(num_blocks=(3, 2)), thermal_block_problem(num_blocks=(1, 1)), thermal_block_problem(num_blocks=(2, 2), parameter_range=(1., 100.))] non_picklable_thermalblock_problems = \ [thermal_block_problem(num_blocks=(1, 3), parameter_range=(0.4, 0.5)).with_( 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(),
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 = 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 = StationaryProblem(domain=problem.domain, diffusion=problem.diffusion.with_(coefficients=functionals), rhs=problem.rhs, parameter_space=CubicParameterSpace({'diffusion': (2,)}, 0.1, 1.)) print('Discretize ...') discretization, _ = discretize_stationary_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)
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)