def setup_default_output(self, conf=None, options=None): """ Provide default values to `ProblemDefinition.setup_output()` from `conf.options` and `options`. """ conf = get_default(conf, self.conf) if options and options.output_filename_trunk: default_output_dir, of = op.split(options.output_filename_trunk) default_trunk = io.get_trunk(of) else: default_trunk = None default_output_dir = get_default_attr(conf.options, 'output_dir', None) if options and options.output_format: default_output_format = options.output_format else: default_output_format = get_default_attr(conf.options, 'output_format', None) default_file_per_var = get_default_attr(conf.options, 'file_per_var', None) default_float_format = get_default_attr(conf.options, 'float_format', None) default_linearization = Struct(kind='strip') self.setup_output(output_filename_trunk=default_trunk, output_dir=default_output_dir, file_per_var=default_file_per_var, output_format=default_output_format, float_format=default_float_format, linearization=default_linearization)
def add_from_bc(self, bc, field): """ Create a new LCBC operator described by `bc`, and add it to the container. Parameters ---------- bc : LinearCombinationBC instance The LCBC condition description. field : Field instance The field of the variable. """ region = bc.region dofs, kind = bc.dofs nmaster = field.get_dofs_in_region(region, merge=True) if kind == 'rigid': op = RigidOperator('%d_rigid' % len(self), nmaster, field, dofs, self.eq_map.dof_names) elif kind == 'no_penetration': filename = get_default_attr(bc, 'filename', None) op = NoPenetrationOperator('%d_no_penetration' % len(self), nmaster, region, field, dofs, filename=filename) elif kind == 'normal_direction': filename = get_default_attr(bc, 'filename', None) op = NormalDirectionOperator('%d_normal_direction' % len(self), nmaster, region, field, dofs, filename=filename) elif kind == 'integral_mean_value': filename = get_default_attr(bc, 'filename', None) op = IntegralMeanValueOperator('%d_integral_mean_value' % len(self), nmaster, region, field, dofs, filename=filename) self.append(op)
def from_conf(conf, functions): """ Construct Material instance from configuration. """ kind = get_default_attr(conf, 'kind', 'time-dependent') flags = get_default_attr(conf, 'flags', {}) function = get_default_attr(conf, 'function', None) values = get_default_attr(conf, 'values', None) if isinstance(function, basestr): function = functions[function] obj = Material(conf.name, kind, function, values, flags) return obj
def new_ulf_iteration(self, nls, vec, it, err, err0): pb = self.problem vec = self.make_full_vec(vec) pb.equations.set_variables_from_state(vec) upd_vars = get_default_attr(pb.conf.options, 'mesh_update_variables', None) for varname in upd_vars: try: state = pb.equations.variables[varname] except IndexError: msg = 'variable "%s" does not exist!' % varname raise KeyError(msg) nods = state.field.get_dofs_in_region(state.field.region, merge=True) coors = pb.domain.get_mesh_coors().copy() vs = state() coors[nods, :] = coors[nods, :] + vs.reshape(len(nods), state.n_components) if pb.ts.step == 1 and it == 0: state.field.save_mappings() state.field.clear_mappings() pb.set_mesh_coors(coors, update_fields=False, actual=True, clear_all=False)
def new_ulf_iteration(self, nls, vec, it, err, err0): pb = self.problem vec = self.make_full_vec(vec) pb.equations.set_variables_from_state(vec) upd_vars = get_default_attr(pb.conf.options, 'mesh_update_variables', None) for varname in upd_vars: try: state = pb.equations.variables[varname] except IndexError: msg = 'variable "%s" does not exist!' % varname raise KeyError( msg ) nods = state.field.get_dofs_in_region(state.field.region, merge=True) coors = pb.domain.get_mesh_coors().copy() vs = state() coors[nods,:] = coors[nods,:] + vs.reshape(len(nods), state.n_components) if pb.ts.step == 1 and it == 0: state.field.save_mappings() state.field.clear_mappings() pb.set_mesh_coors(coors, update_fields=False, actual=True, clear_all=False)
def load_coefs(filename): coefs = Coefficients.from_file_hdf5(filename) try: options = import_file(coefs.filename).options except: options = None if options is not None: plot_info = options['plot_info'] tex_names = options['tex_names'] else: plot_info = get_default_attr(coefs, 'plot_info', {}) tex_names = get_default_attr(coefs, 'tex_names', {}) return coefs, plot_info, tex_names
def load_coefs( filename ): coefs = Coefficients.from_file_hdf5( filename ) try: options = import_file( coefs.filename ).options except: options = None if options is not None: plot_info = options['plot_info'] tex_names = options['tex_names'] else: plot_info = get_default_attr(coefs, 'plot_info', {}) tex_names = get_default_attr(coefs, 'tex_names', {}) return coefs, plot_info, tex_names
def test_solvers( self ): from sfepy.base.base import IndexedStruct, get_default_attr import os.path as op solver_confs = self._list_linear_solvers( self.problem.solver_confs ) ok = True tt = [] for solver_conf in solver_confs: method = get_default_attr( solver_conf, 'method', '' ) precond = get_default_attr( solver_conf, 'precond', '' ) name = ' '.join( (solver_conf.name, solver_conf.kind, method, precond) ).rstrip() self.report( name ) self.report( 'matrix size:', self.problem.mtx_a.shape ) self.report( ' nnz:', self.problem.mtx_a.nnz ) status = IndexedStruct() try: self.problem.init_solvers( nls_status = status, ls_conf = solver_conf ) state = self.problem.solve() failed = status.condition != 0 ## self.problem.mtx_a.save( 'mtx_laplace_cube', ## format='%d %d %.12e\n' ) except Exception, exc: failed = True status = None ok = ok and ((not failed) or (solver_conf.kind in self.can_fail)) if status is not None: for kv in status.time_stats.iteritems(): self.report( '%10s: %7.2f [s]' % kv ) self.report( 'condition: %d, err0: %.3e, err: %.3e'\ % (status.condition, status.err0, status.err) ) tt.append( [name, status.time_stats['solve'], status.err] ) aux = name.replace(' ', '_') fname = op.join( self.options.out_dir, op.split( self.conf.output_name )[1] ) % aux self.problem.save_state( fname, state ) else: self.report( 'solver failed:' ) self.report( exc ) tt.append( [name, 1e10, 1e10] )
def test_solvers(self): from sfepy.base.base import IndexedStruct, get_default_attr import os.path as op solver_confs = self._list_linear_solvers(self.problem.solver_confs) ok = True tt = [] for solver_conf in solver_confs: method = get_default_attr(solver_conf, 'method', '') precond = get_default_attr(solver_conf, 'precond', '') name = ' '.join((solver_conf.name, solver_conf.kind, method, precond)).rstrip() self.report(name) self.report('matrix size:', self.problem.mtx_a.shape) self.report(' nnz:', self.problem.mtx_a.nnz) status = IndexedStruct() try: self.problem.init_solvers(nls_status=status, ls_conf=solver_conf) state = self.problem.solve() failed = status.condition != 0 ## self.problem.mtx_a.save( 'mtx_laplace_cube', ## format='%d %d %.12e\n' ) except Exception, exc: failed = True status = None ok = ok and ((not failed) or (solver_conf.kind in self.can_fail)) if status is not None: for kv in status.time_stats.iteritems(): self.report('%10s: %7.2f [s]' % kv) self.report( 'condition: %d, err0: %.3e, err: %.3e'\ % (status.condition, status.err0, status.err) ) tt.append([name, status.time_stats['solve'], status.err]) aux = name.replace(' ', '_') fname = op.join(self.options.out_dir, op.split(self.conf.output_name)[1]) % aux self.problem.save_state(fname, state) else: self.report('solver failed:') self.report(exc) tt.append([name, 1e10, 1e10])
def init_solvers(self, nls_status=None, ls_conf=None, nls_conf=None, mtx=None, presolve=False): """Create and initialize solvers.""" ls_conf = get_default( ls_conf, self.ls_conf, 'you must set linear solver!' ) nls_conf = get_default( nls_conf, self.nls_conf, 'you must set nonlinear solver!' ) if presolve: tt = time.clock() if get_default_attr(ls_conf, 'needs_problem_instance', False): extra_args = {'problem' : self} else: extra_args = {} ls = Solver.any_from_conf(ls_conf, mtx=mtx, presolve=presolve, **extra_args) if presolve: tt = time.clock() - tt output('presolve: %.2f [s]' % tt) if get_default_attr(nls_conf, 'needs_problem_instance', False): extra_args = {'problem' : self} else: extra_args = {} ev = self.get_evaluator() if get_default_attr(self.conf.options, 'ulf', False): self.nls_iter_hook = ev.new_ulf_iteration nls = Solver.any_from_conf(nls_conf, fun=ev.eval_residual, fun_grad=ev.eval_tangent_matrix, lin_solver=ls, iter_hook=self.nls_iter_hook, status=nls_status, **extra_args) self.solvers = Struct( name = 'solvers', ls = ls, nls = nls )
def recover_micro_hook(micro_filename, region, macro, naming_scheme='step_iel', recovery_file_tag=''): # Create a micro-problem instance. required, other = get_standard_keywords() required.remove('equations') pb = ProblemDefinition.from_conf_file(micro_filename, required=required, other=other, init_equations=False, init_solvers=False) coefs_filename = pb.conf.options.get_default_attr('coefs_filename', 'coefs') output_dir = pb.conf.options.get_default_attr('output_dir', '.') coefs_filename = op.join(output_dir, coefs_filename) + '.h5' # Coefficients and correctors coefs = Coefficients.from_file_hdf5(coefs_filename) corrs = get_correctors_from_file(dump_names=coefs.dump_names) recovery_hook = get_default_attr(pb.conf.options, 'recovery_hook', None) if recovery_hook is not None: recovery_hook = pb.conf.get_function(recovery_hook) aux = max(pb.domain.shape.n_gr, 2) format = get_print_info( aux, fill = '0' )[1] \ + '_' + get_print_info( pb.domain.mesh.n_el, fill = '0' )[1] for ig, ii, iel in region.iter_cells(): print 'ig: %d, ii: %d, iel: %d' % (ig, ii, iel) local_macro = {} for k, v in macro.iteritems(): local_macro[k] = v[ii, 0] out = recovery_hook(pb, corrs, local_macro) # save data suffix = format % (ig, iel) micro_name = pb.get_output_name(extra='recovered_'\ + recovery_file_tag + suffix) filename = op.join(output_dir, op.basename(micro_name)) fpv = pb.conf.options.get_default_attr('file_per_var', False) pb.save_state(filename, out=out, file_per_var=fpv)
def recover_micro_hook( micro_filename, region, macro, naming_scheme = 'step_iel', recovery_file_tag='' ): # Create a micro-problem instance. required, other = get_standard_keywords() required.remove( 'equations' ) pb = ProblemDefinition.from_conf_file(micro_filename, required=required, other=other, init_equations=False, init_solvers=False) coefs_filename = pb.conf.options.get_default_attr('coefs_filename', 'coefs') output_dir = pb.conf.options.get_default_attr('output_dir', '.') coefs_filename = op.join(output_dir, coefs_filename) + '.h5' # Coefficients and correctors coefs = Coefficients.from_file_hdf5( coefs_filename ) corrs = get_correctors_from_file( dump_names = coefs.dump_names ) recovery_hook = get_default_attr( pb.conf.options, 'recovery_hook', None ) if recovery_hook is not None: recovery_hook = getattr( pb.conf.funmod, recovery_hook ) aux = max(pb.domain.shape.n_gr, 2) format = get_print_info( aux, fill = '0' )[1] \ + '_' + get_print_info( pb.domain.mesh.n_el, fill = '0' )[1] for ig, ii, iel in region.iter_cells(): print 'ig: %d, ii: %d, iel: %d' % (ig, ii, iel) local_macro = {} for k, v in macro.iteritems(): local_macro[k] = v[ii,0] out = recovery_hook( pb, corrs, local_macro ) # save data suffix = format % (ig, iel) micro_name = pb.get_output_name(extra='recovered_'\ + recovery_file_tag + suffix) filename = op.join(output_dir, op.basename(micro_name)) fpv = pb.conf.options.get_default_attr('file_per_var', False) pb.save_state(filename, out=out, file_per_var=fpv)
def from_conf(conf, init_fields=True, init_equations=True, init_solvers=True): if conf.options.get_default_attr('absolute_mesh_path', False): conf_dir = None else: conf_dir = op.dirname(conf.funmod.__file__) functions = Functions.from_conf(conf.functions) mesh = Mesh.from_file(conf.filename_mesh, prefix_dir=conf_dir) trans_mtx = conf.options.get_default_attr('mesh_coors_transform', None) if trans_mtx is not None: mesh.transform_coors(trans_mtx) domain = Domain(mesh.name, mesh) if get_default_attr(conf.options, 'ulf', False): domain.mesh.coors_act = domain.mesh.coors.copy() obj = ProblemDefinition('problem_from_conf', conf=conf, functions=functions, domain=domain, auto_conf=False, auto_solvers=False) obj.set_regions(conf.regions, obj.functions) obj.clear_equations() if init_fields: obj.set_fields( conf.fields ) if init_equations: obj.set_equations(conf.equations, user={'ts' : obj.ts}) if init_solvers: obj.set_solvers( conf.solvers, conf.options ) return obj
def generate_probes(filename_input, filename_results, options, conf=None, problem=None, probes=None, labels=None, probe_hooks=None): """ Generate probe figures and data files. """ if conf is None: required, other = get_standard_keywords() conf = ProblemConf.from_file(filename_input, required, other) opts = conf.options if options.auto_dir: output_dir = get_default_attr(opts, 'output_dir', '.') filename_results = os.path.join(output_dir, filename_results) output('results in: %s' % filename_results) io = MeshIO.any_from_filename(filename_results) all_data = io.read_data(options.step) output('loaded:', all_data.keys()) if options.only_names is None: data = all_data else: data = {} for key, val in all_data.iteritems(): if key in options.only_names: data[key] = val if problem is None: problem = ProblemDefinition.from_conf(conf, init_equations=False, init_solvers=False) if probes is None: gen_probes = conf.get_function(conf.options.gen_probes) probes, labels = gen_probes(problem) if probe_hooks is None: probe_hooks = {None: conf.get_function(conf.options.probe_hook)} if options.output_filename_trunk is None: options.output_filename_trunk = problem.ofn_trunk filename_template = options.output_filename_trunk \ + ('_%%d.%s' % options.output_format) if options.same_dir: filename_template = os.path.join(os.path.dirname(filename_results), filename_template) output_dir = os.path.dirname(filename_results) for ip, probe in enumerate(probes): output(ip, probe.name) probe.set_options(close_limit=options.close_limit) for key, probe_hook in probe_hooks.iteritems(): out = probe_hook(data, probe, labels[ip], problem) if out is None: continue if isinstance(out, tuple): fig, results = out else: fig = out if key is not None: filename = filename_template % (key, ip) else: filename = filename_template % ip if fig is not None: if isinstance(fig, dict): for fig_name, fig_fig in fig.iteritems(): fig_filename = edit_filename(filename, suffix='_' + fig_name) fig_fig.savefig(fig_filename) output('figure ->', os.path.normpath(fig_filename)) else: fig.savefig(filename) output('figure ->', os.path.normpath(filename)) if results is not None: txt_filename = edit_filename(filename, new_ext='.txt') fd = open(txt_filename, 'w') fd.write('\n'.join(probe.report()) + '\n') for key, res in results.iteritems(): pars, vals = res fd.write('\n# %s\n' % key) if vals.ndim == 1: aux = nm.hstack((pars[:, None], vals[:, None])) else: aux = nm.hstack((pars[:, None], vals)) nm.savetxt(fd, aux) fd.close() output('data ->', os.path.normpath(txt_filename))
def generate_probes(filename_input, filename_results, options, conf=None, problem=None, probes=None, labels=None, probe_hooks=None): """Generate probe figures and data files.""" if conf is None: required, other = get_standard_keywords() conf = ProblemConf.from_file( filename_input, required, other ) opts = conf.options if options.auto_dir: output_dir = get_default_attr( opts, 'output_dir', '.' ) filename_results = os.path.join(output_dir, filename_results) output('results in: %s' % filename_results) io = MeshIO.any_from_filename(filename_results) all_data = io.read_data(options.step) output('loaded:', all_data.keys()) if options.only_names is None: data = all_data else: data = {} for key, val in all_data.iteritems(): if key in options.only_names: data[key] = val if problem is None: problem = ProblemDefinition.from_conf(conf, init_equations=False, init_solvers=False) if probes is None: gen_probes = getattr(conf.funmod, conf.options.gen_probes) probes, labels = gen_probes(problem) if probe_hooks is None: probe_hooks = {None : getattr(conf.funmod, conf.options.probe_hook)} if options.output_filename_trunk is None: options.output_filename_trunk = problem.ofn_trunk filename_template = options.output_filename_trunk \ + ('_%%d.%s' % options.output_format) if options.same_dir: filename_template = os.path.join(os.path.dirname(filename_results), filename_template) output_dir = os.path.dirname(filename_results) edit_pname = re.compile('[^a-zA-Z0-9-_.\[\]]').sub for ip, probe in enumerate(probes): output(ip, probe.name) for key, probe_hook in probe_hooks.iteritems(): out = probe_hook(data, probe, labels[ip], problem) if out is None: continue if isinstance(out, tuple): fig, results = out else: fig = out if key is not None: filename = filename_template % (key, ip) else: filename = filename_template % ip if fig is not None: fig.savefig(filename) output('figure ->', os.path.normpath(filename)) if results is not None: aux = os.path.splitext(filename)[0] txt_filename = aux + '.txt' fd = open(txt_filename, 'w') fd.write('\n'.join(probe.report()) + '\n') for key, res in results.iteritems(): pars, vals = res fd.write('\n# %s\n' % key) if vals.ndim == 1: aux = nm.hstack((pars[:,None], vals[:,None])) else: aux = nm.hstack((pars[:,None], vals)) nm.savetxt(fd, aux) fd.close() output('data ->', os.path.normpath(txt_filename))
def get_ref_coors(field, coors, strategy='kdtree', close_limit=0.1, cache=None): """ Get reference element coordinates and elements corresponding to given physical coordinates. Parameters ---------- field : Field instance The field defining the approximation. coors : array The physical coordinates. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. Returns ------- ref_coors : array The reference coordinates. cells : array The cell indices corresponding to the reference coordinates. status : array The status: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. """ ref_coors = get_default_attr(cache, 'ref_coors', None) if ref_coors is None: mesh = get_default_attr(cache, 'mesh', None) if mesh is None: mesh = field.create_mesh(extra_nodes=False) scoors = mesh.coors output('reference field: %d vertices' % scoors.shape[0]) iconn = get_default_attr(cache, 'iconn', None) if iconn is None: offsets, iconn = make_inverse_connectivity(mesh.conns, mesh.n_nod, ret_offsets=True) ii = nm.where(offsets[1:] == offsets[:-1])[0] if len(ii): raise ValueError('some vertices not in any element! (%s)' % ii) else: offsets = cache.offsets if strategy == 'kdtree': kdtree = get_default_attr(cache, 'kdtree', None) if kdtree is None: from scipy.spatial import cKDTree as KDTree tt = time.clock() kdtree = KDTree(scoors) output('kdtree: %f s' % (time.clock() - tt)) tt = time.clock() ics = kdtree.query(coors)[1] output('kdtree query: %f s' % (time.clock() - tt)) tt = time.clock() ics = nm.asarray(ics, dtype=nm.int32) vertex_coorss, nodess, mtx_is = [], [], [] conns = [] for ig, ap in field.aps.iteritems(): ps = ap.interp.gel.interp.poly_spaces['v'] vertex_coorss.append(ps.geometry.coors) nodess.append(ps.nodes) mtx_is.append(ps.get_mtx_i()) conns.append(mesh.conns[ig].copy()) # Get reference element coordinates corresponding to # destination coordinates. ref_coors = nm.empty_like(coors) cells = nm.empty((coors.shape[0], 2), dtype=nm.int32) status = nm.empty((coors.shape[0], ), dtype=nm.int32) find_ref_coors(ref_coors, cells, status, coors, ics, offsets, iconn, scoors, conns, vertex_coorss, nodess, mtx_is, 1, close_limit, 1e-15, 100, 1e-8) output('ref. coordinates: %f s' % (time.clock() - tt)) elif strategy == 'crawl': raise NotImplementedError else: raise ValueError('unknown search strategy! (%s)' % strategy) else: ref_coors = cache.ref_coors cells = cache.cells status = cache.status return ref_coors, cells, status
def get_ref_coors(field, coors, strategy='kdtree', close_limit=0.1, cache=None, verbose=True): """ Get reference element coordinates and elements corresponding to given physical coordinates. Parameters ---------- field : Field instance The field defining the approximation. coors : array The physical coordinates. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. verbose : bool If False, reduce verbosity. Returns ------- ref_coors : array The reference coordinates. cells : array The cell indices corresponding to the reference coordinates. status : array The status: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. """ ref_coors = get_default_attr(cache, 'ref_coors', None) if ref_coors is None: mesh = get_default_attr(cache, 'mesh', None) if mesh is None: mesh = field.create_mesh(extra_nodes=False) scoors = mesh.coors output('reference field: %d vertices' % scoors.shape[0], verbose=verbose) iconn = get_default_attr(cache, 'iconn', None) if iconn is None: offsets, iconn = make_inverse_connectivity(mesh.conns, mesh.n_nod, ret_offsets=True) ii = nm.where(offsets[1:] == offsets[:-1])[0] if len(ii): raise ValueError('some vertices not in any element! (%s)' % ii) else: offsets = cache.offsets if strategy == 'kdtree': kdtree = get_default_attr(cache, 'kdtree', None) if kdtree is None: from scipy.spatial import cKDTree as KDTree tt = time.clock() kdtree = KDTree(scoors) output('kdtree: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() ics = kdtree.query(coors)[1] output('kdtree query: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() ics = nm.asarray(ics, dtype=nm.int32) vertex_coorss, nodess, mtx_is = [], [], [] conns = [] for ig, ap in field.aps.iteritems(): ps = ap.interp.gel.interp.poly_spaces['v'] vertex_coorss.append(ps.geometry.coors) nodess.append(ps.nodes) mtx_is.append(ps.get_mtx_i()) conns.append(mesh.conns[ig].copy()) # Get reference element coordinates corresponding to # destination coordinates. ref_coors = nm.empty_like(coors) cells = nm.empty((coors.shape[0], 2), dtype=nm.int32) status = nm.empty((coors.shape[0],), dtype=nm.int32) find_ref_coors(ref_coors, cells, status, coors, ics, offsets, iconn, scoors, conns, vertex_coorss, nodess, mtx_is, 1, close_limit, 1e-15, 100, 1e-8) output('ref. coordinates: %f s' % (time.clock()-tt), verbose=verbose) elif strategy == 'crawl': raise NotImplementedError else: raise ValueError('unknown search strategy! (%s)' % strategy) else: ref_coors = cache.ref_coors cells = cache.cells status = cache.status return ref_coors, cells, status
def get_ref_coors_general(field, coors, close_limit=0.1, get_cells_fun=None, cache=None, verbose=False): """ Get reference element coordinates and elements corresponding to given physical coordinates. Parameters ---------- field : Field instance The field defining the approximation. coors : array The physical coordinates. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. get_cells_fun : callable, optional If given, a function with signature ``get_cells_fun(coors, cmesh, **kwargs)`` returning cells and offsets that potentially contain points with the coordinates `coors`. When not given, :func:`get_potential_cells()` is used. cache : Struct, optional To speed up a sequence of evaluations, the field mesh and other data can be cached. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the mesh related data are ignored. verbose : bool If False, reduce verbosity. Returns ------- ref_coors : array The reference coordinates. cells : array The cell indices corresponding to the reference coordinates. status : array The status: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure, 4 is failure due to non-convergence of the Newton iteration in tensor product cells. If close_limit is 0, then status 5 indicates points outside of the field domain that had no potential cells. """ ref_coors = get_default_attr(cache, "ref_coors", None) if ref_coors is None: extrapolate = close_limit > 0.0 get = get_potential_cells if get_cells_fun is None else get_cells_fun ref_coors = nm.empty_like(coors) cells = nm.empty((coors.shape[0],), dtype=nm.int32) status = nm.empty((coors.shape[0],), dtype=nm.int32) cmesh = get_default_attr(cache, "cmesh", None) if cmesh is None: tt = time.clock() mesh = field.create_mesh(extra_nodes=False) cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() if get_cells_fun is None: centroids = cmesh.get_centroids(cmesh.tdim) else: centroids = None output("cmesh setup: %f s" % (time.clock() - tt), verbose=verbose) else: centroids = cache.centroids tt = time.clock() potential_cells, offsets = get(coors, cmesh, centroids=centroids, extrapolate=extrapolate) output("potential cells: %f s" % (time.clock() - tt), verbose=verbose) ap = field.ap ps = ap.interp.gel.interp.poly_spaces["v"] mtx_i = ps.get_mtx_i() ac = nm.ascontiguousarray tt = time.clock() crc.find_ref_coors( ref_coors, cells, status, ac(coors), cmesh, potential_cells, offsets, ps.geometry.coors, ps.nodes, mtx_i, extrapolate, close_limit, 1e-15, 100, 1e-8, ) if extrapolate: assert_(nm.all(status < 5)) output("ref. coordinates: %f s" % (time.clock() - tt), verbose=verbose) else: cells = cache.cells status = cache.status return ref_coors, cells, status
def get_ref_coors_convex(field, coors, close_limit=0.1, cache=None, verbose=False): """ Get reference element coordinates and elements corresponding to given physical coordinates. Parameters ---------- field : Field instance The field defining the approximation. coors : array The physical coordinates. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh and other data can be cached. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the mesh related data are ignored. verbose : bool If False, reduce verbosity. Returns ------- ref_coors : array The reference coordinates. cells : array The cell indices corresponding to the reference coordinates. status : array The status: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure, 4 is failure due to non-convergence of the Newton iteration in tensor product cells. Notes ----- Outline of the algorithm for finding xi such that X(xi) = P: 1. make inverse connectivity - for each vertex have cells it is in. 2. find the closest vertex V. 3. choose initial cell: i0 = first from cells incident to V. 4. while not P in C_i, change C_i towards P, check if P in new C_i. """ ref_coors = get_default_attr(cache, "ref_coors", None) if ref_coors is None: extrapolate = close_limit > 0.0 ref_coors = nm.empty_like(coors) cells = nm.empty((coors.shape[0],), dtype=nm.int32) status = nm.empty((coors.shape[0],), dtype=nm.int32) cmesh = get_default_attr(cache, "cmesh", None) if cmesh is None: tt = time.clock() mesh = field.create_mesh(extra_nodes=False) cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() centroids = cmesh.get_centroids(cmesh.tdim) if field.gel.name != "3_8": normals0 = cmesh.get_facet_normals() normals1 = None else: normals0 = cmesh.get_facet_normals(0) normals1 = cmesh.get_facet_normals(1) output("cmesh setup: %f s" % (time.clock() - tt), verbose=verbose) else: centroids = cache.centroids normals0 = cache.normals0 normals1 = cache.normals1 kdtree = get_default_attr(cache, "kdtree", None) if kdtree is None: from scipy.spatial import cKDTree as KDTree tt = time.clock() kdtree = KDTree(cmesh.coors) output("kdtree: %f s" % (time.clock() - tt), verbose=verbose) tt = time.clock() ics = kdtree.query(coors)[1] output("kdtree query: %f s" % (time.clock() - tt), verbose=verbose) ics = nm.asarray(ics, dtype=nm.int32) ap = field.ap ps = ap.interp.gel.interp.poly_spaces["v"] mtx_i = ps.get_mtx_i() ac = nm.ascontiguousarray tt = time.clock() crc.find_ref_coors_convex( ref_coors, cells, status, ac(coors), cmesh, centroids, normals0, normals1, ics, ps.geometry.coors, ps.nodes, mtx_i, extrapolate, close_limit, 1e-15, 100, 1e-8, ) output("ref. coordinates: %f s" % (time.clock() - tt), verbose=verbose) else: cells = cache.cells status = cache.status return ref_coors, cells, status
def main(): parser = OptionParser(usage = usage, version = "%prog " + sfepy.__version__) parser.add_option('-c', '--conf', metavar='"key : value, ..."', action='store', dest='conf', type='string', default=None, help= help['conf']) parser.add_option('-O', '--options', metavar='"key : value, ..."', action='store', dest='app_options', type='string', default=None, help=help['options']) parser.add_option('-d', '--define', metavar='"key : value, ..."', action='store', dest='define_args', type='string', default=None, help=help['define']) parser.add_option( "-o", "", metavar = 'filename', action = "store", dest = "output_filename_trunk", default = None, help = help['filename'] ) parser.add_option( "", "--format", metavar = 'format', action = "store", dest = "output_format", default = None, help = help['output_format'] ) parser.add_option( "", "--log", metavar = 'file', action = "store", dest = "log", default = None, help = help['log'] ) parser.add_option( "-q", "--quiet", action = "store_true", dest = "quiet", default = False, help = help['quiet'] ) parser.add_option( "", "--save-ebc", action = "store_true", dest = "save_ebc", default = False, help = help['save_ebc'] ) parser.add_option( "", "--save-regions", action = "store_true", dest = "save_regions", default = False, help = help['save_regions'] ) parser.add_option( "", "--save-regions-as-groups", action = "store_true", dest = "save_regions_as_groups", default = False, help = help['save_regions_as_groups'] ) parser.add_option( "", "--save-field-meshes", action = "store_true", dest = "save_field_meshes", default = False, help = help['save_field_meshes'] ) parser.add_option( "", "--solve-not", action = "store_true", dest = "solve_not", default = False, help = help['solve_not'] ) parser.add_option( "", "--list", metavar = 'what', action = "store", dest = "_list", default = None, help = help['list'] ) options, args = parser.parse_args() if (len( args ) == 1): filename_in = args[0]; else: if options._list == 'terms': print_terms() else: parser.print_help(), return output.set_output(filename=options.log, quiet=options.quiet, combined=options.log is not None) required, other = get_standard_keywords() if options.solve_not: required.remove( 'equations' ) required.remove( 'solver_[0-9]+|solvers' ) other.extend( ['equations'] ) conf = ProblemConf.from_file_and_options(filename_in, options, required, other, define_args=options.define_args) opts = conf.options output_prefix = get_default_attr( opts, 'output_prefix', 'sfepy:' ) app = SimpleApp( conf, options, output_prefix ) if hasattr( opts, 'parametric_hook' ): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize( parametric_hook ) app()
def get_ref_coors_general(field, coors, close_limit=0.1, get_cells_fun=None, cache=None, verbose=False): """ Get reference element coordinates and elements corresponding to given physical coordinates. Parameters ---------- field : Field instance The field defining the approximation. coors : array The physical coordinates. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. get_cells_fun : callable, optional If given, a function with signature ``get_cells_fun(coors, cmesh, **kwargs)`` returning cells and offsets that potentially contain points with the coordinates `coors`. When not given, :func:`get_potential_cells()` is used. cache : Struct, optional To speed up a sequence of evaluations, the field mesh and other data can be cached. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the mesh related data are ignored. verbose : bool If False, reduce verbosity. Returns ------- ref_coors : array The reference coordinates. cells : array The cell indices corresponding to the reference coordinates. status : array The status: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure, 4 is failure due to non-convergence of the Newton iteration in tensor product cells. If close_limit is 0, then status 5 indicates points outside of the field domain that had no potential cells. """ timer = Timer() ref_coors = get_default_attr(cache, 'ref_coors', None) if ref_coors is None: extrapolate = close_limit > 0.0 get = get_potential_cells if get_cells_fun is None else get_cells_fun ref_coors = nm.empty_like(coors) cells = nm.empty((coors.shape[0], ), dtype=nm.int32) status = nm.empty((coors.shape[0], ), dtype=nm.int32) cmesh = get_default_attr(cache, 'cmesh', None) if cmesh is None: timer.start() mesh = field.create_mesh(extra_nodes=False) cmesh = mesh.cmesh if get_cells_fun is None: centroids = cmesh.get_centroids(cmesh.tdim) else: centroids = None output('cmesh setup: %f s' % timer.stop(), verbose=verbose) else: centroids = cache.centroids timer.start() potential_cells, offsets = get(coors, cmesh, centroids=centroids, extrapolate=extrapolate) output('potential cells: %f s' % timer.stop(), verbose=verbose) coors = nm.ascontiguousarray(coors) ctx = field.create_basis_context() eval_cmesh = get_default_attr(cache, 'eval_cmesh', None) if eval_cmesh is None: timer.start() mesh = field.create_eval_mesh() if mesh is None: eval_cmesh = cmesh else: eval_cmesh = mesh.cmesh output('eval_cmesh setup: %f s' % timer.stop(), verbose=verbose) timer.start() crc.find_ref_coors(ref_coors, cells, status, coors, eval_cmesh, potential_cells, offsets, extrapolate, 1e-15, close_limit, ctx) if extrapolate: assert_(nm.all(status < 5)) output('ref. coordinates: %f s' % timer.stop(), verbose=verbose) else: cells = cache.cells status = cache.status return ref_coors, cells, status
def get_ref_coors_convex(field, coors, close_limit=0.1, cache=None, verbose=False): """ Get reference element coordinates and elements corresponding to given physical coordinates. Parameters ---------- field : Field instance The field defining the approximation. coors : array The physical coordinates. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh and other data can be cached. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the mesh related data are ignored. verbose : bool If False, reduce verbosity. Returns ------- ref_coors : array The reference coordinates. cells : array The cell indices corresponding to the reference coordinates. status : array The status: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure, 4 is failure due to non-convergence of the Newton iteration in tensor product cells. Notes ----- Outline of the algorithm for finding xi such that X(xi) = P: 1. make inverse connectivity - for each vertex have cells it is in. 2. find the closest vertex V. 3. choose initial cell: i0 = first from cells incident to V. 4. while not P in C_i, change C_i towards P, check if P in new C_i. """ timer = Timer() ref_coors = get_default_attr(cache, 'ref_coors', None) if ref_coors is None: extrapolate = close_limit > 0.0 ref_coors = nm.empty_like(coors) cells = nm.empty((coors.shape[0], ), dtype=nm.int32) status = nm.empty((coors.shape[0], ), dtype=nm.int32) cmesh = get_default_attr(cache, 'cmesh', None) if cmesh is None: timer.start() mesh = field.create_mesh(extra_nodes=False) cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() centroids = cmesh.get_centroids(cmesh.tdim) if field.gel.name != '3_8': normals0 = cmesh.get_facet_normals() normals1 = None else: normals0 = cmesh.get_facet_normals(0) normals1 = cmesh.get_facet_normals(1) output('cmesh setup: %f s' % timer.stop(), verbose=verbose) else: centroids = cache.centroids normals0 = cache.normals0 normals1 = cache.normals1 kdtree = get_default_attr(cache, 'kdtree', None) if kdtree is None: from scipy.spatial import cKDTree as KDTree timer.start() kdtree = KDTree(cmesh.coors) output('kdtree: %f s' % timer.stop(), verbose=verbose) timer.start() ics = kdtree.query(coors)[1] output('kdtree query: %f s' % timer.stop(), verbose=verbose) ics = nm.asarray(ics, dtype=nm.int32) coors = nm.ascontiguousarray(coors) ctx = field.create_basis_context() timer.start() crc.find_ref_coors_convex(ref_coors, cells, status, coors, cmesh, centroids, normals0, normals1, ics, extrapolate, 1e-15, close_limit, ctx) output('ref. coordinates: %f s' % timer.stop(), verbose=verbose) else: cells = cache.cells status = cache.status return ref_coors, cells, status
def main(): parser = OptionParser(usage=usage, version='%prog ' + sfepy.__version__) parser.add_option('-c', '--conf', metavar='"key : value, ..."', action='store', dest='conf', type='string', default=None, help= help['conf']) parser.add_option('-O', '--options', metavar='"key : value, ..."', action='store', dest='app_options', type='string', default=None, help=help['options']) parser.add_option('-d', '--define', metavar='"key : value, ..."', action='store', dest='define_args', type='string', default=None, help=help['define']) parser.add_option('-o', '', metavar='filename', action='store', dest='output_filename_trunk', default=None, help=help['filename']) parser.add_option('', '--format', metavar='format', action='store', dest='output_format', default=None, help=help['output_format']) parser.add_option('', '--log', metavar='file', action='store', dest='log', default=None, help=help['log']) parser.add_option('-q', '--quiet', action='store_true', dest='quiet', default=False, help=help['quiet']) parser.add_option('', '--save-ebc', action='store_true', dest='save_ebc', default=False, help=help['save_ebc']) parser.add_option('', '--save-ebc-nodes', action='store_true', dest='save_ebc_nodes', default=False, help=help['save_ebc_nodes']) parser.add_option('', '--save-regions', action='store_true', dest='save_regions', default=False, help=help['save_regions']) parser.add_option('', '--save-regions-as-groups', action='store_true', dest='save_regions_as_groups', default=False, help=help['save_regions_as_groups']) parser.add_option('', '--save-field-meshes', action='store_true', dest='save_field_meshes', default=False, help=help['save_field_meshes']) parser.add_option('', '--solve-not', action='store_true', dest='solve_not', default=False, help=help['solve_not']) parser.add_option('', '--list', metavar='what', action='store', dest='_list', default=None, help=help['list']) options, args = parser.parse_args() if (len(args) == 1): filename_in = args[0]; else: if options._list == 'terms': print_terms() else: parser.print_help(), return output.set_output(filename=options.log, quiet=options.quiet, combined=options.log is not None) required, other = get_standard_keywords() if options.solve_not: required.remove('equations') required.remove('solver_[0-9]+|solvers') other.extend(['equations']) conf = ProblemConf.from_file_and_options(filename_in, options, required, other, define_args=options.define_args) opts = conf.options output_prefix = get_default_attr(opts, 'output_prefix', 'sfepy:') app = PDESolverApp(conf, options, output_prefix) if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) app()