def reduce_greedy(d, reductor, snapshots_per_block, extension_alg_name, max_extensions, use_estimator, pool): from pymor.algorithms.greedy import greedy # run greedy training_set = d.parameter_space.sample_uniformly(snapshots_per_block) greedy_data = greedy(d, reductor, training_set, use_estimator=use_estimator, error_norm=d.h1_0_semi_norm, extension_params={'method': extension_alg_name}, max_extensions=max_extensions, pool=pool) rd = greedy_data['reduced_discretization'] # generate summary real_rb_size = rd.solution_space.dim training_set_size = len(training_set) summary = '''Greedy basis generation: size of training set: {training_set_size} error estimator used: {use_estimator} extension method: {extension_alg_name} prescribed basis size: {max_extensions} actual basis size: {real_rb_size} elapsed time: {greedy_data[time]} '''.format(**locals()) return rd, summary
def reduce_greedy(d, reductor, snapshots_per_block, extension_alg_name, max_extensions, use_estimator, pool): from pymor.algorithms.greedy import greedy # run greedy training_set = d.parameter_space.sample_uniformly(snapshots_per_block) greedy_data = greedy(d, reductor, training_set, use_estimator=use_estimator, error_norm=d.h1_0_semi_norm, extension_params={'method': extension_alg_name}, max_extensions=max_extensions, pool=pool) rd = greedy_data['rd'] # generate summary real_rb_size = rd.solution_space.dim training_set_size = len(training_set) summary = '''Greedy basis generation: size of training set: {training_set_size} error estimator used: {use_estimator} extension method: {extension_alg_name} prescribed basis size: {max_extensions} actual basis size: {real_rb_size} elapsed time: {greedy_data[time]} '''.format(**locals()) return rd, summary
def _first(self): args = self.args product = self.discretization.h1_0_semi_product if args['--estimator-norm'] == 'h1' else None reductor = CoerciveRBReductor(product=product) greedy_data = greedy(self.discretization, reductor, self.discretization.parameter_space.sample_uniformly(args['SNAPSHOTS']), use_estimator=True, error_norm=self.discretization.h1_0_semi_norm, max_extensions=args['RBSIZE']) self.rb_discretization, self.reductor = greedy_data['reduced_discretization'], reductor self.first = False
def _first(self): args = self.args product = self.m.h1_0_semi_product if args['--product'] == 'h1' else None reductor = CoerciveRBReductor(self.m, product=product) greedy_data = greedy(self.m, reductor, self.m.parameter_space.sample_uniformly(args['SNAPSHOTS']), use_estimator=True, error_norm=self.m.h1_0_semi_norm, max_extensions=args['RBSIZE']) self.rom, self.reductor = greedy_data['rom'], reductor self.first = False
def reduce_pod_greedy(config, detailed_data, training_samples): greedy_data = greedy(detailed_data['parabolic_disc'], partial(reductor, config, detailed_data), training_samples, initial_basis=detailed_data['initial_basis'] if 'initial_basis' in detailed_data else None, use_estimator=True, error_norm=None, extension_algorithm=partial(extension, detailed_data['elliptic_LRBMS_disc'], config['extension_product']), max_extensions=config['max_rb_size'], atol=config['target_error']) return greedy_data
def _first(self): args = self.args error_product = self.discretization.h1_product if args['--estimator-norm'] == 'h1' else None reductor = partial(reduce_stationary_affine_linear, error_product=error_product) extension_algorithm = partial(gram_schmidt_basis_extension, product=self.discretization.h1_product) greedy_data = greedy(self.discretization, reductor, self.discretization.parameter_space.sample_uniformly(args['SNAPSHOTS']), use_estimator=True, error_norm=self.discretization.h1_norm, extension_algorithm=extension_algorithm, max_extensions=args['RBSIZE']) self.rb_discretization, self.reconstructor = greedy_data['reduced_discretization'], greedy_data['reconstructor'] self.first = False
def reduce_pod_greedy(config, detailed_data, training_samples): greedy_data = greedy(detailed_data['parabolic_disc'], partial(reductor, config, detailed_data), training_samples, initial_basis=detailed_data['initial_basis'] if 'initial_basis' in detailed_data else None, use_estimator=True, error_norm=None, extension_algorithm=partial( extension, detailed_data['elliptic_LRBMS_disc'], config['extension_product']), max_extensions=config['max_rb_size'], atol=config['target_error']) return greedy_data
def reduce_greedy(d, reductor, snapshots_per_block, extension_alg_name, max_extensions, use_estimator, pool): from pymor.algorithms.basisextension import trivial_basis_extension, gram_schmidt_basis_extension from pymor.algorithms.greedy import greedy # choose basis extension algorithm if extension_alg_name == "trivial": extension_algorithm = trivial_basis_extension elif extension_alg_name == "gram_schmidt": extension_algorithm = gram_schmidt_basis_extension elif extension_alg_name == "h1_gram_schmidt": extension_algorithm = partial(gram_schmidt_basis_extension, product=d.h1_0_semi_product) else: assert False # run greedy training_set = d.parameter_space.sample_uniformly(snapshots_per_block) greedy_data = greedy( d, reductor, training_set, use_estimator=use_estimator, error_norm=d.h1_0_semi_norm, extension_algorithm=extension_algorithm, max_extensions=max_extensions, pool=pool, ) rd, rc = greedy_data["reduced_discretization"], greedy_data["reconstructor"] # generate summary real_rb_size = rd.solution_space.dim training_set_size = len(training_set) summary = """Greedy basis generation: size of training set: {training_set_size} error estimator used: {use_estimator} extension method: {extension_alg_name} prescribed basis size: {max_extensions} actual basis size: {real_rb_size} elapsed time: {greedy_data[time]} """.format( **locals() ) return rd, rc, summary
def reduce_greedy(d, reductor, snapshots_per_block, extension_alg_name, max_extensions, use_estimator, pool): from pymor.algorithms.basisextension import trivial_basis_extension, gram_schmidt_basis_extension from pymor.algorithms.greedy import greedy # choose basis extension algorithm if extension_alg_name == 'trivial': extension_algorithm = trivial_basis_extension elif extension_alg_name == 'gram_schmidt': extension_algorithm = gram_schmidt_basis_extension elif extension_alg_name == 'h1_gram_schmidt': extension_algorithm = partial(gram_schmidt_basis_extension, product=d.h1_0_semi_product) else: assert False # run greedy training_set = d.parameter_space.sample_uniformly(snapshots_per_block) greedy_data = greedy(d, reductor, training_set, use_estimator=use_estimator, error_norm=d.h1_0_semi_norm, extension_algorithm=extension_algorithm, max_extensions=max_extensions, pool=pool) rd, rc = greedy_data['reduced_discretization'], greedy_data[ 'reconstructor'] # generate summary real_rb_size = rd.solution_space.dim training_set_size = len(training_set) summary = '''Greedy basis generation: size of training set: {training_set_size} error estimator used: {use_estimator} extension method: {extension_alg_name} prescribed basis size: {max_extensions} actual basis size: {real_rb_size} elapsed time: {greedy_data[time]} '''.format(**locals()) return rd, rc, summary
def thermalblock_demo(args): args['XBLOCKS'] = int(args['XBLOCKS']) args['YBLOCKS'] = int(args['YBLOCKS']) args['--grid'] = int(args['--grid']) args['SNAPSHOTS'] = int(args['SNAPSHOTS']) args['RBSIZE'] = int(args['RBSIZE']) args['--test'] = int(args['--test']) 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 {'default', 'numpy_default'} import IPython.parallel as p from pymor.playground.remote import setup_remote, RemoteStationaryDiscretization rc = p.Client() rv = rc[0] print('Discretize ...') rv.execute(''' import numpy as np import pymor.core as core core.logger.MAX_HIERACHY_LEVEL = 2 from pymor.analyticalproblems import ThermalBlockProblem from pymor.discretizers import discretize_elliptic_cg core.getLogger('pymor.algorithms').setLevel('INFO') core.getLogger('pymor.discretizations').setLevel('INFO') core.getLogger('pymor.la').setLevel('INFO') print('Setup Problem ...') problem = ThermalBlockProblem(num_blocks=({nx}, {ny})) print('Discretize ...') discretization, _ = discretize_elliptic_cg(problem, diameter=m.sqrt(2) / {grid}) '''.format(nx=args['XBLOCKS'], ny=args['YBLOCKS'], grid=args['--grid'])) discretization_id = setup_remote(rv, 'discretization') discretization = RemoteStationaryDiscretization(rv, discretization_id) print('The parameter type is {}'.format(discretization.parameter_type)) print('RB generation ...') error_product = discretization.h1_product if args[ '--estimator-norm'] == 'h1' else None reductors = { 'default': partial(reduce_stationary_affine_linear, error_product=error_product) } 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_product) } extension_algorithm = extension_algorithms[args['--extension-alg']] greedy_data = greedy( discretization, reductor, discretization.parameter_space.sample_uniformly(args['SNAPSHOTS']), use_estimator=args['--with-estimator'], error_norm=discretization.h1_norm, initial_basis=discretization.operator.type_source.empty( dim=discretization.operator.dim_source), # NOQA extension_algorithm=extension_algorithm, max_extensions=args['RBSIZE']) rb_discretization, reconstructor = greedy_data[ 'reduced_discretization'], greedy_data['reconstructor'] print('\nSearching for maximum error on random snapshots ...') tic = time.time() h1_err_max = -1 cond_max = -1 for mu in discretization.parameter_space.sample_randomly(args['--test']): print('Solving RB-Scheme for mu = {} ... '.format(mu), end='') URB = reconstructor.reconstruct(rb_discretization.solve(mu)) U = discretization.solve(mu) h1_err = discretization.h1_norm(U - URB)[0] cond = np.linalg.cond(rb_discretization.operator.assemble(mu)._matrix) if h1_err > h1_err_max: h1_err_max = h1_err Umax = U URBmax = URB mumax = mu if cond > cond_max: cond_max = cond cond_max_mu = mu print('H1-error = {}, condition = {}'.format(h1_err, cond)) toc = time.time() t_est = toc - tic real_rb_size = len(greedy_data['basis']) print(''' *** RESULTS *** Problem: number of blocks: {args[XBLOCKS]}x{args[YBLOCKS]} h: sqrt(2)/{args[--grid]} Greedy basis generation: number of snapshots: {args[SNAPSHOTS]}^({args[XBLOCKS]}x{args[YBLOCKS]}) used estimator: {args[--with-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]} Stochastic error estimation: number of samples: {args[--test]} maximal H1-error: {h1_err_max} (mu = {mumax}) maximal condition of system matrix: {cond_max} (mu = {cond_max_mu}) elapsed time: {t_est} '''.format(**locals())) sys.stdout.flush()
def burgers_demo(args): 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['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 ...') grid_type_map = {'rect': RectGrid, 'tria': TriaGrid} domain_discretizer = partial(discretize_domain_default, grid_type=grid_type_map[args['--grid-type']]) problem = Burgers2DProblem(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 ...') discretizer = discretize_nonlinear_instationary_advection_fv if args['--grid-type'] == 'rect': args['--grid'] *= 1. / m.sqrt(2) discretization, _ = discretizer(problem, diameter=1. / args['--grid'], num_flux=args['--num-flux'], lxf_lambda=args['--lxf-lambda'], nt=args['--nt'], domain_discretizer=domain_discretizer) print(discretization.operator.grid) print('The parameter type is {}'.format(discretization.parameter_type)) if args['--plot-solutions']: print('Showing some solutions') Us = tuple() legend = tuple() for mu in discretization.parameter_space.sample_uniformly(4): print('Solving for exponent = {} ... '.format(mu['exponent'])) sys.stdout.flush() Us = Us + (discretization.solve(mu), ) legend = legend + ('exponent: {}'.format(mu['exponent']), ) discretization.visualize(Us, legend=legend, title='Detailed Solutions', block=True) ei_discretization, ei_data = interpolate_operators( discretization, ['operator'], discretization.parameter_space.sample_uniformly( args['EI_SNAPSHOTS']), # NOQA error_norm=discretization.l2_norm, target_error=1e-10, max_interpolation_dofs=args['EISIZE'], projection='orthogonal', product=discretization.l2_product) if args['--plot-ei-err']: print('Showing some EI errors') ERRs = tuple() legend = tuple() for mu in discretization.parameter_space.sample_randomly(2): print('Solving for exponent = \n{} ... '.format(mu['exponent'])) sys.stdout.flush() U = discretization.solve(mu) U_EI = ei_discretization.solve(mu) ERR = U - U_EI ERRs = ERRs + (ERR, ) legend = legend + ('exponent: {}'.format(mu['exponent']), ) print('Error: {}'.format(np.max(discretization.l2_norm(ERR)))) discretization.visualize(ERRs, legend=legend, title='EI Errors', separate_colorbars=True) print('Showing interpolation DOFs ...') U = np.zeros(U.dim) dofs = ei_discretization.operator.interpolation_dofs U[dofs] = np.arange(1, len(dofs) + 1) U[ei_discretization.operator.source_dofs] += int(len(dofs) / 2) discretization.visualize(NumpyVectorArray(U), title='Interpolation DOFs') print('RB generation ...') def reductor(discretization, rb, extends=None): return reduce_generic_rb(ei_discretization, rb, extends=extends) extension_algorithm = partial(pod_basis_extension) greedy_data = greedy( discretization, reductor, discretization.parameter_space.sample_uniformly(args['SNAPSHOTS']), use_estimator=False, error_norm=lambda U: np.max(discretization.l2_norm(U)), extension_algorithm=extension_algorithm, max_extensions=args['RBSIZE']) rb_discretization, reconstructor = greedy_data[ 'reduced_discretization'], greedy_data['reconstructor'] print('\nSearching for maximum error on random snapshots ...') tic = time.time() mus = list(discretization.parameter_space.sample_randomly(args['--test'])) def error_analysis(N, M): print('N = {}, M = {}: '.format(N, M), end='') rd, rc, _ = reduce_to_subbasis(rb_discretization, N, reconstructor) rd = rd.with_(operator=rd.operator.projected_to_subbasis( dim_collateral=M)) l2_err_max = -1 mumax = None for mu in mus: print('.', end='') sys.stdout.flush() u = rd.solve(mu) URB = rc.reconstruct(u) U = discretization.solve(mu) l2_err = np.max(discretization.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(greedy_data['basis']) 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 = 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)
def offline_phase(cfg, data): logger = getLogger('.OS2015_SISC__6_2.offline_phase') logger.setLevel('INFO') discretization = data['discretization'] example = data['example'] local_products = data['local_products'] norm = data['norm'] mu_bar_dune = data['mu_bar_dune'] mu_hat_dune = data['mu_hat_dune'] wrapper = data['wrapper'] if cfg['training_sampling_strategy'] == 'random': training_samples = list( discretization.parameter_space.sample_randomly( cfg['num_training_samples'])) elif cfg['training_sampling_strategy'] == 'uniform': training_samples = list( discretization.parameter_space.sample_uniformly( cfg['num_training_samples'])) add_values(training_samples=training_samples) if cfg['compute_some_solution_norms'] and len(training_samples) > 0: logger.info('Computing solution norms:') if norm is not None: solution_norms = [ norm(discretization.solve(mu)) for mu in training_samples ] else: solution_norms = [ discretization.solve(mu).l2_norm()[0] for mu in training_samples ] logger.info(' range: [{}, {}]'.format( np.amin(solution_norms), np.amax(solution_norms))) logger.info(' mean: {}'.format( np.mean(solution_norms))) add_values(solution_norms=solution_norms) extension_algorithm = partial(gram_schmidt_block_basis_extension, product=local_products) initial_basis = discretization.functionals['rhs'].source.empty()._blocks if cfg['initialize_basis_with'] >= 0: logger.info('Initializing local bases of up to order {} ...'.format( cfg['initialize_basis_with'])) one = make_listvectorarray(wrapper[example.project('1')]) one = BlockVectorArray([ discretization.localize_vector(one, ss) for ss in np.arange(discretization.num_subdomains) ]) initial_basis, _ = extension_algorithm(initial_basis, one) if cfg['initialize_basis_with'] >= 1: xx = make_listvectorarray(wrapper[example.project('x[0]')]) xx = BlockVectorArray([ discretization.localize_vector(xx, ss) for ss in np.arange(discretization.num_subdomains) ]) initial_basis, _ = extension_algorithm(initial_basis, xx) yy = make_listvectorarray(wrapper[example.project('x[1]')]) yy = BlockVectorArray([ discretization.localize_vector(yy, ss) for ss in np.arange(discretization.num_subdomains) ]) initial_basis, _ = extension_algorithm(initial_basis, yy) xy = make_listvectorarray(wrapper[example.project('x[0]*x[1]')]) xy = BlockVectorArray([ discretization.localize_vector(xy, ss) for ss in np.arange(discretization.num_subdomains) ]) initial_basis, _ = extension_algorithm(initial_basis, xy) if cfg['initialize_basis_with'] >= 2: logger.warn('Ignoring initialize_basis_with higher than 1: {}'.format( cfg['initialize_basis_with'])) logger.info('') reduced_estimator = ReducedEstimator(discretization, example, wrapper, mu_hat_dune, mu_bar_dune, norm, cfg['estimator_compute'], cfg['estimator_return']) greedy_data = greedy(discretization, partial(reduce_with_estimator, reduced_estimator=reduced_estimator), training_samples, initial_basis=initial_basis, use_estimator=cfg['greedy_use_estimator'], error_norm=norm, extension_algorithm=extension_algorithm, max_extensions=cfg['greedy_max_extensions'], target_error=cfg['greedy_target_error']) add_values(time=greedy_data['time'], max_err_mus=greedy_data['max_err_mus'], extensions=greedy_data['extensions'], max_errs=greedy_data['max_errs'], offline_estimator_data=reduced_estimator.data) rd, rc = greedy_data['reduced_discretization'], greedy_data[ 'reconstructor'] basis, basis_mus = greedy_data['basis'], greedy_data['max_err_mus'] print('') logger.info('Offline phase finished.') logger.info('Basis sizes range from {} to {}.'.format( np.min([len(bb) for bb in basis]), np.max([len(bb) for bb in basis]))) return {'basis': basis, 'basis_mus': basis_mus, 'rc': rc, 'rd': rd}
def thermalblock_demo(args): args["XBLOCKS"] = int(args["XBLOCKS"]) args["YBLOCKS"] = int(args["YBLOCKS"]) args["--grid"] = int(args["--grid"]) args["--order"] = int(args["--order"]) args["SNAPSHOTS"] = int(args["SNAPSHOTS"]) args["RBSIZE"] = int(args["RBSIZE"]) args["--test"] = int(args["--test"]) 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"} print("Discretize ...") discretization = discretize(args) print("The parameter type is {}".format(discretization.parameter_type)) if args["--plot-solutions"]: print("Showing some solutions") Us = tuple() legend = tuple() 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") print("RB generation ...") error_product = discretization.h1_product if args["--estimator-norm"] == "h1" else None coercivity_estimator = ExpressionParameterFunctional("min(diffusion)", discretization.parameter_type) reductors = { "residual_basis": partial( reduce_stationary_coercive, error_product=error_product, coercivity_estimator=coercivity_estimator ), "traditional": partial( reduce_stationary_affine_linear, error_product=error_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_product), } extension_algorithm = extension_algorithms[args["--extension-alg"]] greedy_data = greedy( discretization, reductor, discretization.parameter_space.sample_uniformly(args["SNAPSHOTS"]), use_estimator=args["--with-estimator"], error_norm=discretization.h1_norm, extension_algorithm=extension_algorithm, max_extensions=args["RBSIZE"], ) 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", "w") as f: dump(rb_discretization, f) print("\nSearching for maximum error on random snapshots ...") tic = time.time() real_rb_size = len(greedy_data["basis"]) mus = list(discretization.parameter_space.sample_randomly(args["--test"])) h1_err_max = -1 h1_est_max = -1 cond_max = -1 for mu in mus: print(".", end="") sys.stdout.flush() u = rb_discretization.solve(mu) URB = reconstructor.reconstruct(u) U = discretization.solve(mu) h1_err = discretization.h1_norm(U - URB)[0] h1_est = rb_discretization.estimate(u, mu=mu) cond = np.linalg.cond(rb_discretization.operator.assemble(mu)._matrix) if h1_err > h1_err_max: h1_err_max = h1_err mumax = mu if h1_est > h1_est_max: h1_est_max = h1_est mu_est_max = mu if cond > cond_max: cond_max = cond cond_max_mu = mu print() toc = time.time() t_est = toc - tic print( """ *** RESULTS *** Problem: number of blocks: {args[XBLOCKS]}x{args[YBLOCKS]} h: sqrt(2)/{args[--grid]} Greedy basis generation: number of snapshots: {args[SNAPSHOTS]}^({args[XBLOCKS]}x{args[YBLOCKS]}) used estimator: {args[--with-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]} Stochastic error estimation: number of samples: {args[--test]} maximal H1-error: {h1_err_max} (mu = {mumax}) maximal condition of system matrix: {cond_max} (mu = {cond_max_mu}) elapsed time: {t_est} """.format( **locals() ) ) sys.stdout.flush() if args["--plot-err"]: 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" )
def thermalblock_demo(args): args['XBLOCKS'] = int(args['XBLOCKS']) args['YBLOCKS'] = int(args['YBLOCKS']) args['--grid'] = int(args['--grid']) args['SNAPSHOTS'] = int(args['SNAPSHOTS']) args['RBSIZE'] = int(args['RBSIZE']) args['--test'] = int(args['--test']) 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'} print('Solving on TriaGrid(({0},{0}))'.format(args['--grid'])) print('Setup Problem ...') problem = ThermalBlockProblem(num_blocks=(args['XBLOCKS'], args['YBLOCKS'])) print('Discretize ...') discretization, _ = discretize_elliptic_cg(problem, diameter=1. / args['--grid']) print('The parameter type is {}'.format(discretization.parameter_type)) if args['--plot-solutions']: print('Showing some solutions') Us = tuple() legend = tuple() 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 ...') error_product = discretization.h1_product if args[ '--estimator-norm'] == 'h1' else None coercivity_estimator = ExpressionParameterFunctional( 'min(diffusion)', discretization.parameter_type) reductors = { 'residual_basis': partial(reduce_stationary_coercive, error_product=error_product, coercivity_estimator=coercivity_estimator), 'traditional': partial(reduce_stationary_affine_linear, error_product=error_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_product) } extension_algorithm = extension_algorithms[args['--extension-alg']] greedy_data = greedy(discretization, reductor, discretization.parameter_space.sample_uniformly( args['SNAPSHOTS']), use_estimator=args['--with-estimator'], error_norm=discretization.h1_norm, extension_algorithm=extension_algorithm, max_extensions=args['RBSIZE']) 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', 'w') as f: dump(rb_discretization, f) print( 'Writing detailed discretization and reconstructor to file {} ...'. format(args['--pickle'] + '_detailed')) with open(args['--pickle'] + '_detailed', 'w') as f: dump((discretization, reconstructor), f) print('\nSearching for maximum error on random snapshots ...') def error_analysis(d, rd, rc, mus): print('N = {}: '.format(rd.operator.source.dim), end='') h1_err_max = -1 h1_est_max = -1 cond_max = -1 for mu in mus: print('.', end='') sys.stdout.flush() u = rd.solve(mu) URB = rc.reconstruct(u) U = d.solve(mu) h1_err = d.h1_norm(U - URB)[0] h1_est = rd.estimate(u, mu=mu) cond = np.linalg.cond(rd.operator.assemble(mu)._matrix) if h1_err > h1_err_max: h1_err_max = h1_err mumax = mu if h1_est > h1_est_max: h1_est_max = h1_est mu_est_max = mu if cond > cond_max: cond_max = cond cond_max_mu = mu print() return h1_err_max, mumax, h1_est_max, mu_est_max, cond_max, cond_max_mu tic = time.time() real_rb_size = len(greedy_data['basis']) if args['--plot-error-sequence']: N_count = min(real_rb_size - 1, 25) Ns = np.linspace(1, real_rb_size, N_count).astype(np.int) else: Ns = np.array([real_rb_size]) rd_rcs = [ reduce_to_subbasis(rb_discretization, N, reconstructor)[:2] for N in Ns ] mus = list(discretization.parameter_space.sample_randomly(args['--test'])) errs, err_mus, ests, est_mus, conds, cond_mus = zip( *(error_analysis(discretization, rd, rc, mus) for rd, rc in rd_rcs)) h1_err_max = errs[-1] mumax = err_mus[-1] cond_max = conds[-1] cond_max_mu = cond_mus[-1] toc = time.time() t_est = toc - tic print(''' *** RESULTS *** Problem: number of blocks: {args[XBLOCKS]}x{args[YBLOCKS]} h: sqrt(2)/{args[--grid]} Greedy basis generation: number of snapshots: {args[SNAPSHOTS]}^({args[XBLOCKS]}x{args[YBLOCKS]}) used estimator: {args[--with-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]} Stochastic error estimation: number of samples: {args[--test]} maximal H1-error: {h1_err_max} (mu = {mumax}) maximal condition of system matrix: {cond_max} (mu = {cond_max_mu}) elapsed time: {t_est} '''.format(**locals())) sys.stdout.flush() if args['--plot-error-sequence']: plt.semilogy(Ns, errs, Ns, ests) plt.legend(('error', 'estimator')) plt.show() if args['--plot-err']: 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 burgers_demo(args): args['--grid'] = int(args['--grid']) 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['EXP_MIN'] = int(args['EXP_MIN']) args['EXP_MAX'] = int(args['EXP_MAX']) args['DIFF_MIN'] = float(args['DIFF_MIN']) args['DIFF_MAX'] = float(args['DIFF_MAX']) args['EXP_EI_SNAPSHOTS'] = int(args['EXP_EI_SNAPSHOTS']) args['DIFF_EI_SNAPSHOTS'] = int(args['DIFF_EI_SNAPSHOTS']) args['EISIZE'] = int(args['EISIZE']) args['EXP_SNAPSHOTS'] = int(args['EXP_SNAPSHOTS']) args['DIFF_SNAPSHOTS'] = int(args['DIFF_SNAPSHOTS']) args['RBSIZE'] = int(args['RBSIZE']) print('Setup Problem ...') domain_discretizer = partial(discretize_domain_default, grid_type=RectGrid) problem = ViscousBurgersProblem(vx=args['--vx'], vy=args['--vy'], initial_data=args['--initial-data'], parameter_range={'exponent': (args['EXP_MIN'], args['EXP_MAX']), 'diffusion': (args['DIFF_MIN'], args['DIFF_MAX'])}, torus=not args['--not-periodic']) print('Discretize ...') discretizer = discretize_nonlinear_instationary_advection_diffusion_fv discretization, _ = discretizer(problem, diameter=m.sqrt(2) / args['--grid'], num_flux=args['--num-flux'], lxf_lambda=args['--lxf-lambda'], nt=args['--nt'], domain_discretizer=domain_discretizer) print(discretization.explicit_operator.grid) print('The parameter type is {}'.format(discretization.parameter_type)) if args['--plot-solutions']: print('Showing some solutions') for mu in discretization.parameter_space.sample_randomly(2): print('Solving for exponent = \n{} ... '.format(mu['exponent'])) print('Solving for diffusion = \n{} ... '.format(mu['diffusion'])) sys.stdout.flush() U = discretization.solve(mu) discretization.visualize(U) if args['EXP_MIN'] == args['EXP_MAX']: ei_samples = discretization.parameter_space.sample_uniformly({'exponent': 1, 'diffusion': args['DIFF_EI_SNAPSHOTS']}) samples = discretization.parameter_space.sample_uniformly({'exponent': 1, 'diffusion': args['DIFF_SNAPSHOTS']}) elif args['DIFF_MIN'] == args['DIFF_MAX']: ei_samples = discretization.parameter_space.sample_uniformly({'exponent': args['EXP_EI_SNAPSHOTS'], 'diffusion': 1}) samples = discretization.parameter_space.sample_uniformly({'exponent': args['EXP_SNAPSHOTS'], 'diffusion': 1}) else: ei_samples = discretization.parameter_space.sample_uniformly({'exponent': args['EXP_EI_SNAPSHOTS'], 'diffusion': args['DIFF_EI_SNAPSHOTS']}) samples = discretization.parameter_space.sample_uniformly({'exponent': args['EXP_SNAPSHOTS'], 'diffusion': args['DIFF_SNAPSHOTS']}) ei_discretization, ei_data = interpolate_operators(discretization, ['explicit_operator'], ei_samples, error_norm=discretization.l2_norm, target_error=1e-10, max_interpolation_dofs=args['EISIZE'], projection='orthogonal', product=discretization.l2_product) if args['--plot-ei-err']: print('Showing some EI errors') for mu in discretization.parameter_space.sample_randomly(2): print('Solving for exponent = \n{} ... '.format(mu['exponent'])) print('Solving for diffusion = \n{} ... '.format(mu['diffusion'])) sys.stdout.flush() U = discretization.solve(mu) U_EI = ei_discretization.solve(mu) ERR = U - U_EI print('Error: {}'.format(np.max(discretization.l2_norm(ERR)))) discretization.visualize(ERR) print('Showing interpolation DOFs ...') U = np.zeros(U.dim) dofs = ei_discretization.explicit_operator.interpolation_dofs U[dofs] = np.arange(1, len(dofs) + 1) U[ei_discretization.explicit_operator.source_dofs] += int(len(dofs)/2) discretization.visualize(NumpyVectorArray(U)) print('RB generation ...') def reductor(discretization, rb, extends=None): return reduce_generic_rb(ei_discretization, rb, extends=extends) extension_algorithm = partial(pod_basis_extension) rb_initial_basis = discretization.initial_data.as_vector() rb_initial_basis *= 1 / rb_initial_basis.l2_norm()[0] greedy_data = greedy(discretization, reductor, samples, initial_basis = rb_initial_basis, use_estimator=False, error_norm=lambda U: np.max(discretization.l2_norm(U)), extension_algorithm=extension_algorithm, max_extensions=args['RBSIZE']) rb_discretization, reconstructor = greedy_data['reduced_discretization'], greedy_data['reconstructor'] print('\nSearching for maximum error on random snapshots ...') tic = time.time() mus = list(discretization.parameter_space.sample_randomly(args['--test'])) #mus.append({'diffusion': np.array([0.0]), 'exponent': np.array(2.0)}) def error_analysis(N, M): print('N = {}, M = {}: '.format(N, M), end='') rd, rc, _ = reduce_to_subbasis(rb_discretization, N, reconstructor) rd = rd.with_(explicit_operator=rd.explicit_operator.projected_to_subbasis(dim_collateral=M)) l2_err_max = -1 mumax = None for mu in mus: print('.', end='') sys.stdout.flush() u = rd.solve(mu) URB = rc.reconstruct(u) U = discretization.solve(mu) l2_err = np.max(discretization.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(mumax) print() return l2_err_max, mumax error_analysis = np.frompyfunc(error_analysis, 2, 2) real_rb_size = len(greedy_data['basis']) 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]}), ({args[DIFF_MIN]}, {args[DIFF_MAX]}) h: sqrt(2)/{args[--grid]} 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[EXP_EI_SNAPSHOTS]}, {args[DIFF_EI_SNAPSHOTS]}) prescribed collateral basis size: {args[EISIZE]} actual collateral basis size: {real_cb_size} number of snapshots: ({args[EXP_SNAPSHOTS]}, {args[DIFF_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}) maximum errors: {errs} N_grid (RB size): {N_grid} M_grid (CB size): {M_grid} elapsed time: {t_est} '''.format(**locals())) sys.stdout.flush() if args['--plot-error-landscape']: import matplotlib.pyplot as plt import mpl_toolkits.mplot3d 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']: discretization.visualize(U - URB)
def thermalblock_demo(args): args['XBLOCKS'] = int(args['XBLOCKS']) args['YBLOCKS'] = int(args['YBLOCKS']) args['--grid'] = int(args['--grid']) args['SNAPSHOTS'] = int(args['SNAPSHOTS']) args['RBSIZE'] = int(args['RBSIZE']) args['--test'] = int(args['--test']) 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'} print('Solving on TriaGrid(({0},{0}))'.format(args['--grid'])) print('Setup Problem ...') problem = ThermalBlockProblem(num_blocks=(args['XBLOCKS'], args['YBLOCKS'])) print('Discretize ...') discretization, _ = discretize_elliptic_cg(problem, diameter=1. / args['--grid']) print('The parameter type is {}'.format(discretization.parameter_type)) if args['--plot-solutions']: print('Showing some solutions') Us = tuple() legend = tuple() 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 ...') error_product = discretization.h1_product if args['--estimator-norm'] == 'h1' else None coercivity_estimator=ExpressionParameterFunctional('min(diffusion)', discretization.parameter_type) reductors = {'residual_basis': partial(reduce_stationary_coercive, error_product=error_product, coercivity_estimator=coercivity_estimator), 'traditional': partial(reduce_stationary_affine_linear, error_product=error_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_product)} extension_algorithm = extension_algorithms[args['--extension-alg']] greedy_data = greedy(discretization, reductor, discretization.parameter_space.sample_uniformly(args['SNAPSHOTS']), use_estimator=args['--with-estimator'], error_norm=discretization.h1_norm, extension_algorithm=extension_algorithm, max_extensions=args['RBSIZE']) 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', 'w') as f: dump(rb_discretization, f) print('Writing detailed discretization and reconstructor to file {} ...'.format(args['--pickle'] + '_detailed')) with open(args['--pickle'] + '_detailed', 'w') as f: dump((discretization, reconstructor), f) print('\nSearching for maximum error on random snapshots ...') def error_analysis(d, rd, rc, mus): print('N = {}: '.format(rd.operator.source.dim), end='') h1_err_max = -1 h1_est_max = -1 cond_max = -1 for mu in mus: print('.', end='') sys.stdout.flush() u = rd.solve(mu) URB = rc.reconstruct(u) U = d.solve(mu) h1_err = d.h1_norm(U - URB)[0] h1_est = rd.estimate(u, mu=mu) cond = np.linalg.cond(rd.operator.assemble(mu)._matrix) if h1_err > h1_err_max: h1_err_max = h1_err mumax = mu if h1_est > h1_est_max: h1_est_max = h1_est mu_est_max = mu if cond > cond_max: cond_max = cond cond_max_mu = mu print() return h1_err_max, mumax, h1_est_max, mu_est_max, cond_max, cond_max_mu tic = time.time() real_rb_size = len(greedy_data['basis']) if args['--plot-error-sequence']: N_count = min(real_rb_size - 1, 25) Ns = np.linspace(1, real_rb_size, N_count).astype(np.int) else: Ns = np.array([real_rb_size]) rd_rcs = [reduce_to_subbasis(rb_discretization, N, reconstructor)[:2] for N in Ns] mus = list(discretization.parameter_space.sample_randomly(args['--test'])) errs, err_mus, ests, est_mus, conds, cond_mus = zip(*(error_analysis(discretization, rd, rc, mus) for rd, rc in rd_rcs)) h1_err_max = errs[-1] mumax = err_mus[-1] cond_max = conds[-1] cond_max_mu = cond_mus[-1] toc = time.time() t_est = toc - tic print(''' *** RESULTS *** Problem: number of blocks: {args[XBLOCKS]}x{args[YBLOCKS]} h: sqrt(2)/{args[--grid]} Greedy basis generation: number of snapshots: {args[SNAPSHOTS]}^({args[XBLOCKS]}x{args[YBLOCKS]}) used estimator: {args[--with-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]} Stochastic error estimation: number of samples: {args[--test]} maximal H1-error: {h1_err_max} (mu = {mumax}) maximal condition of system matrix: {cond_max} (mu = {cond_max_mu}) elapsed time: {t_est} '''.format(**locals())) sys.stdout.flush() if args['--plot-error-sequence']: plt.semilogy(Ns, errs, Ns, ests) plt.legend(('error', 'estimator')) plt.show() if args['--plot-err']: 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)
ops = [DealIIMatrixOperator(getattr(cpp_disc, name)()) for name in ['lambda_mat', 'mu_mat']] op = LincombOperator(ops, (lambda_fn, mu_fn)) rhs = VectorFunctional(ListVectorArray([DealIIVector(cpp_disc.rhs())])) viz = PyVis(cpp_disc) h1_op = DealIIMatrixOperator(cpp_disc.h1_mat(), "h1_0_semi") energy_op = DealIIMatrixOperator(cpp_disc.mu_mat(), "energy") py_disc = StationaryDiscretization(op, rhs, products={"energy": energy_op}, visualizer=viz, parameter_space=CubicParameterSpace(parameter_type, LOW, HIGH)) coercivity_estimator = ExpressionParameterFunctional("max(mu)", parameter_type) reductor = partial(reduce_stationary_coercive, error_product=energy_op, coercivity_estimator=coercivity_estimator) greedy_data = greedy(py_disc, reductor, py_disc.parameter_space.sample_uniformly(3), use_estimator=True, extension_algorithm=gram_schmidt_basis_extension, max_extensions=3) rb_disc, reconstructor = greedy_data['reduced_discretization'], greedy_data['reconstructor'] half = (HIGH - LOW) / 2. values = itertools.product((LOW, HIGH, half), (LOW, HIGH, half)) for new_param in ({"lambda": [a], "mu": [b]} for a, b in values): for disc, s in [(cpp_disc, 'cpp'), (py_disc, 'py'), (rb_disc, 'rb')]: with Timer(s): solution = disc.solve(new_param) try: disc.visualize(solution, filename='param_{}-{}.vtk'.format(new_param,s)) except NotImplementedError: py_disc.visualize(reconstructor.reconstruct(solution), filename='param_{}-{}.vtk'.format(new_param,s)) fr = disc.energy_norm(solution)
]) return pod_block_basis_extension( basis, U, count=1, product=[ stat_blocked_disc.local_product(ss, 'h1') for ss in np.arange(stat_blocked_disc.num_subdomains) ]) greedy_data = greedy(nonblocked_disc, reductor, nonblocked_disc.parameter_space.sample_uniformly( config['num_training_samples']), use_estimator=False, error_norm=norm, extension_algorithm=extension, max_extensions=config['max_rb_size'], target_error=config['target_error']) rd, rc = greedy_data['reduced_discretization'], greedy_data['reconstructor'] RB = greedy_data['basis'] logger.info(' ') add_values(time=greedy_data['time'], max_err_mus=greedy_data['max_err_mus'], extensions=greedy_data['extensions'], max_errs=greedy_data['max_errs'], basis_sizes=[len(local_RB) for local_RB in RB]) add_logfile(logfile)
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
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 = 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