def __init__(self, name='mesh', filename=None, prefix_dir=None, **kwargs): """Create a Mesh. Parameters ---------- name : str Object name. filename : str Loads a mesh from the specified file, if not None. prefix_dir : str If not None, the filename is relative to that directory. """ Struct.__init__(self, name=name, **kwargs) self.nodal_bcs = {} if filename is None: self.io = None self.setup_done = 0 else: io = MeshIO.any_from_filename(filename, prefix_dir=prefix_dir) output('reading mesh (%s)...' % (io.filename)) tt = time.clock() io.read(self) output('...done in %.2f s' % (time.clock() - tt)) self._set_shape_info()
def __init__(self, name='mesh', filename=None, prefix_dir=None, **kwargs): """Create a Mesh. Parameters ---------- name : str Object name. filename : str Loads a mesh from the specified file, if not None. prefix_dir : str If not None, the filename is relative to that directory. """ Struct.__init__(self, name=name, **kwargs) if filename is None: self.io = None self.setup_done = 0 else: io = MeshIO.any_from_filename(filename, prefix_dir=prefix_dir) output('reading mesh (%s)...' % (io.filename)) tt = time.clock() io.read(self) output('...done in %.2f s' % (time.clock() - tt)) self._set_shape_info()
def __init__(self, name, dtype, shape, region, space='H1', poly_space_base='lagrange', approx_order=1): """Create a Field. Parameters ---------- name : str Object name. dtype : numpy.dtype Field data type: float64 or complex128. shape : int/tuple/str Field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector'. The field shape determines the shape of the FE base functions and can be different from a FieldVariable instance shape. (TODO) region : Region The region where the field is defined. space : str The function space name. poly_space_base : str The name of polynomial space base. approx_order : int/str FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble). Notes ----- Assumes one cell type for the whole region! """ if isinstance(shape, str): try: shape = {'scalar' : (1,), 'vector' : (region.domain.shape.dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, int): shape = (shape,) Struct.__init__(self, name = name, dtype = dtype, shape = shape, region = region, space = space, poly_space_base = poly_space_base) self.domain = self.region.domain self.clear_dof_conns() self.set_approx_order(approx_order) self.setup_geometry() # To refactor below... self.create_interpolant() self.setup_approximations() ## print self.aps ## pause() self.setup_global_base() self.setup_coors()
def __init__(self, name, share_geometry=True, n_point=None, **kwargs): """ Parameters ---------- name : str The probe name, set automatically by the subclasses. share_geometry : bool Set to True to indicate that all the probes will work on the same domain. Certain data are then computed only for the first probe and cached. n_point : int The (fixed) number of probe points, when positive. When non-positive, the number of points is adaptively increased starting from -n_point, until the neighboring point distance is less than the diameter of the elements enclosing the points. When None, it is set to -10. For additional parameters see the __init__() docstrings of the subclasses. """ Struct.__init__(self, name=name, share_geometry=share_geometry, **kwargs) self.set_n_point(n_point) self.options = Struct(close_limit=0.1, size_hint=None) self.cache = Struct(name='probe_local_evaluate_cache') self.is_refined = False
def __init__(self, name, share_geometry=True, n_point=None, **kwargs): """ Parameters ---------- name : str The probe name, set automatically by the subclasses. share_geometry : bool Set to True to indicate that all the probes will work on the same domain. Certain data are then computed only for the first probe and cached. n_point : int The (fixed) number of probe points, when positive. When non-positive, the number of points is adaptively increased starting from -n_point, until the neighboring point distance is less than the diameter of the elements enclosing the points. When None, it is set to -10. For additional parameters see the __init__() docstrings of the subclasses. """ Struct.__init__(self, name=name, share_geometry=share_geometry, **kwargs) self.set_n_point(n_point) self.options = Struct(close_limit=0.1, size_hint=None) self.cache = Struct(name='probe_local_evaluate_cache') self.is_refined = False
def __init__(self, name, definition, domain, parse_def, kind='cell', parent=None): """ Create region instance. Parameters ---------- name : str The region name, either given, or automatic for intermediate regions. definition : str The region selector definition. domain : Domain instance The domain of the region. parse_def : str The parsed definition of the region. kind : str The region kind - one of 'cell', 'facet', 'face', 'edge', 'vertex', 'cell_only', ..., 'vertex_only'. parent : str, optional The name of the parent region. """ tdim = domain.shape.tdim Struct.__init__(self, name=name, definition=definition, domain=domain, parse_def=parse_def, n_v_max=domain.shape.n_nod, dim=domain.shape.dim, tdim=tdim, kind_tdim=None, entities=[None] * (tdim + 1), kind=None, parent=parent, shape=None, mirror_regions={}, mirror_maps={}, is_empty=False) self.set_kind(kind)
def __init__(self, name='timer', start=False): Struct.__init__(self, name=name) self.time_function = time.perf_counter if PY3 else time.clock self.reset() if start: self.start()
def __init__(self, name, definition, domain, parse_def): """ Create region instance. Parameters ---------- name : str The region name, either given, or automatic for intermediate regions. definition : str The region selector definition. domain : Domain instance The domain of the region. parse_def : str The parsed definition of the region. Notes ----- conns, vertex_groups are links to domain data. """ Struct.__init__(self, name=name, definition=definition, n_v_max=domain.shape.n_nod, domain=domain, parse_def=parse_def, all_vertices=None, igs=[], vertices={}, edges={}, faces={}, cells={}, fis={}, can_cells=True, true_cells={}, must_update=True, is_complete=False, mirror_region=None, ig_map=None, ig_map_i=None)
def __init__(self, name, definition, domain, parse_def, kind='cell', parent=None): """ Create region instance. Parameters ---------- name : str The region name, either given, or automatic for intermediate regions. definition : str The region selector definition. domain : Domain instance The domain of the region. parse_def : str The parsed definition of the region. Notes ----- conns, vertex_groups are links to domain data. """ tdim = domain.shape.tdim Struct.__init__(self, name=name, definition=definition, domain=domain, parse_def=parse_def, n_v_max=domain.shape.n_nod, dim=domain.shape.dim, tdim=tdim, entities=[None] * (tdim + 1), kind=None, parent=parent, shape=None, mirror_region=None, ig_map=None, ig_map_i=None) self.set_kind(kind)
def __init__(self, name_map, gamma=None, delta=None, tau=None, tau_red=1.0, tau_mul=1.0, delta_mul=1.0, gamma_mul=1.0, diameter_mode='max'): Struct.__init__(self, name_map=name_map, gamma=gamma, delta=delta, tau=tau, tau_red=tau_red, tau_mul=tau_mul, delta_mul=delta_mul, gamma_mul=gamma_mul, diameter_mode=diameter_mode)
def __init__(self, conf, options, output_prefix, **kwargs): Struct.__init__(self, conf=conf, options=options, output_prefix=output_prefix) output.prefix = self.output_prefix self.restore()
def __init__(self, filename, watch=False, animate=False, anim_format=None, ffmpeg_options=None, output_dir='.', offscreen=False, auto_screenshot=True): Struct.__init__(self, filename=filename, watch=watch, animate=animate, anim_format=anim_format, ffmpeg_options=ffmpeg_options, output_dir=output_dir, offscreen=offscreen, auto_screenshot=auto_screenshot, scene=None, gui=None) self.options = get_arguments(omit=['self']) if mlab is None: output('mlab cannot be imported, check your installation!') insert_as_static_method(self.__class__, '__call__', self.call_empty) else: insert_as_static_method(self.__class__, '__call__', self.call_mlab)
def __init__(self, iplane=None): """ Parameters ---------- iplane : list The vector of indices denoting the plane, e.g.: [0, 1] """ if iplane is None: iplane = [0, 1] # Choose the "master" variables and the "slave" ones # ... for vectors i_m = nm.sort(iplane) i_s = nm.setdiff1d(nm.arange(3), i_m) # ... for second order tensors (symmetric storage) i_ms = { (0, 1): [0, 1, 3], (0, 2): [0, 2, 4], (1, 2): [1, 2, 5] }[tuple(i_m)] i_ss = nm.setdiff1d(nm.arange(6), i_ms) Struct.__init__(self, iplane=iplane, i_m=i_m, i_s=i_s, i_ms=i_ms, i_ss=i_ss)
def __init__(self, name, kind, domain, single_facets, n_obj, indices, facets): Struct.__init__( self, name=name, kind=kind, domain=domain, single_facets=single_facets, n_obj=n_obj, indices=indices, facets=facets, ) self.n_all_obj, self.n_col = facets.shape self.n_gr = len(self.n_obj) self.indx = {} ii = 0 for ig, nn in enumerate(self.n_obj): self.indx[ig] = slice(ii, ii + nn) ii += nn self.n_fps_vec = nm.empty(self.n_all_obj, dtype=nm.int32) self.n_fps = {} for ig, facet in self.single_facets.iteritems(): self.n_fps_vec[self.indx[ig]] = facet.shape[1] self.n_fps[ig] = facet.shape[1]
def __init__(self, problem, pdofs, drange, is_overlap, psol, comm, matrix_hook=None, verbose=False): BasicEvaluator.__init__(self, problem, matrix_hook=matrix_hook) Struct.__init__(self, pdofs=pdofs, drange=drange, is_overlap=is_overlap, comm=comm, verbose=verbose) variables = problem.get_variables() di = variables.di ebc_rows = [] for ii, variable in enumerate(variables.iter_state(ordered=True)): eq_map = variable.eq_map ebc_rows.append(eq_map.eq_ebc + di.ptr[ii]) self.ebc_rows = nm.concatenate(ebc_rows) self.psol_i = pp.create_local_petsc_vector(pdofs) self.gather, self.scatter = pp.create_gather_scatter(pdofs, self.psol_i, psol, comm=comm)
def __init__( self, conf, options, output_prefix, **kwargs ): Struct.__init__( self, conf = conf, options = options, output_prefix = output_prefix ) output.prefix = self.output_prefix self.restore()
def __init__(self, name, times, kernel, decay=None, exp_coefs=None, exp_decay=None): Struct.__init__(self, name=name, times=times, c=kernel, d=decay, ec=exp_coefs, e=exp_decay) if decay is None: self.d = compute_mean_decay(kernel) if exp_decay is None: self.ec, self.e = fit_exponential(times, self.d, return_coefs=True) self.en = self.e / self.e[0] self.c0 = self.c[0] self.e_c0 = self.c0 * self.e[0] self.e_d1 = self.e[1] / self.e[0] self.c_slice = (slice(None), ) + ((None, ) * (self.c.ndim - 1))
def init(self, young=None, poisson=None, bulk=None, lam=None, mu=None, p_wave=None): """ Set exactly two of the elastic constants, and compute the remaining. (Re)-initializes the existing instance of ElasticConstants. """ Struct.__init__(self, young=young, poisson=poisson, bulk=bulk, lam=lam, mu=mu, p_wave=p_wave) values = {} for key, val in six.iteritems(self.__dict__): if (key in self.names) and (val is not None): sym = getattr(self.ec, key) values[sym] = val known = list(values.keys()) if len(known) != 2: raise ValueError('exactly two elastic constants must be provided!') known = [ii.name for ii in known] unknown = set(self.names).difference(known) for name in unknown: key = tuple(sorted(known)) + (name,) val = float(self.relations[key].n(subs=values)) setattr(self, name, val)
def __init__(self, name_map, gamma=None, delta=None, tau=None, tau_red=1.0, tau_mul=1.0, delta_mul=1.0, gamma_mul=1.0, diameter_mode='max'): Struct.__init__(self, name_map=name_map, gamma=gamma, delta=delta, tau=tau, tau_red=tau_red, tau_mul=tau_mul, delta_mul=delta_mul, gamma_mul=gamma_mul, diameter_mode=diameter_mode)
def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds = la.dot_sequences(mm, self.bounds) bounds2d = rbounds[:, :2] assert_(nm.allclose(nm.dot(mtx, self.normal), e3, rtol=0.0, atol=1e-12)) self.adotn = nm.dot(self.anchor, self.normal) self.rot_angle = rot_angle self.mtx = mtx self.bounds2d = bounds2d
def __init__(self, name, definition, domain, parse_def, kind='cell', parent=None): """ Create region instance. Parameters ---------- name : str The region name, either given, or automatic for intermediate regions. definition : str The region selector definition. domain : Domain instance The domain of the region. parse_def : str The parsed definition of the region. kind : str The region kind - one of 'cell', 'facet', 'face', 'edge', 'vertex', 'cell_only', ..., 'vertex_only'. parent : str, optional The name of the parent region. """ tdim = domain.shape.tdim Struct.__init__(self, name=name, definition=definition, domain=domain, parse_def=parse_def, n_v_max=domain.shape.n_nod, dim=domain.shape.dim, tdim=tdim, kind_tdim=None, entities=[None] * (tdim + 1), kind=None, parent=parent, shape=None, mirror_region=None, is_empty=False) self.set_kind(kind)
def __init__(self, name, regions, dof_names, dof_map_fun, variables, functions=None): Struct.__init__(self, name=name, regions=regions, dof_names=dof_names) if dof_map_fun is not None: self.dof_map_fun = get_condition_value(dof_map_fun, functions, 'LCBC', 'dof_map_fun') self._setup_dof_names(variables)
def __init__(self, name, function, is_constant=False, extra_args=None): Struct.__init__(self, name=name, function=function, is_constant=is_constant) if extra_args is None: extra_args = {} self.extra_args = extra_args
def __init__(self, name, kind='time-dependent', function=None, values=None, flags=None, **kwargs): """ Parameters ---------- name : str The name of the material. kind : 'time-dependent' or 'stationary' The kind of the material. function : function The function for setting up the material values. values : dict Constant material values. flags : dict, optional Special flags. **kwargs : keyword arguments, optional Constant material values passed by their names. """ Struct.__init__(self, name=name, kind=kind, is_constant=False) if (function is not None) and ((values is not None) or len(kwargs)): msg = 'material can have function or values but not both! (%s)' \ % self.name raise ValueError(msg) self.flags = get_default(flags, {}) if hasattr(function, '__call__'): self.function = function elif (values is not None) or len(kwargs): # => function is None if isinstance(values, dict): key0 = list(values.keys())[0] assert_(isinstance(key0, str)) else: key0 = None if (key0 and (not key0.startswith('.')) and isinstance(values[key0], dict)): self.function = ConstantFunctionByRegion(values) self.is_constant = True else: all_values = {} if values is not None: all_values.update(values) all_values.update(kwargs) self.function = ConstantFunction(all_values) self.is_constant = True else: # => both values and function are None msg = 'material %s: neither function nor values given! (%s)' \ % self.name raise ValueError(msg) self.reset()
def __init__(self, name, kind='time-dependent', function=None, values=None, flags=None, **kwargs): """ Parameters ---------- name : str The name of the material. kind : 'time-dependent' or 'stationary' The kind of the material. function : function The function for setting up the material values. values : dict Constant material values. flags : dict, optional Special flags. **kwargs : keyword arguments, optional Constant material values passed by their names. """ Struct.__init__(self, name=name, kind=kind, is_constant=False) if (function is not None) and ((values is not None) or len(kwargs)): msg = 'material can have function or values but not both! (%s)' \ % self.name raise ValueError(msg) self.flags = get_default(flags, {}) if hasattr(function, '__call__'): self.function = function elif (values is not None) or len(kwargs): # => function is None if isinstance(values, dict): key0 = values.keys()[0] assert_(isinstance(key0, str)) else: key0 = None if (key0 and (not key0.startswith('.')) and isinstance(values[key0], dict)): self.function = ConstantFunctionByRegion(values) self.is_constant = True else: all_values = {} if values is not None: all_values.update(values) all_values.update(kwargs) self.function = ConstantFunction(all_values) self.is_constant = True else: # => both values and function are None msg = 'material %s: neither function nor values given! (%s)' \ % self.name raise ValueError(msg) self.reset()
def __init__(self, data_names=None, yscales=None, xlabels=None, ylabels=None, is_plot=True, aggregate=200, formats=None, log_filename=None): """`data_names` ... tuple of names grouped by subplots: ([name1, name2, ...], [name3, name4, ...], ...) where name<n> are strings to display in (sub)plot legends.""" try: import matplotlib as mpl except: mpl = None if (mpl is not None) and mpl.rcParams['backend'] == 'GTKAgg': can_live_plot = True else: can_live_plot = False Struct.__init__(self, data_names = {}, n_arg = 0, n_gr = 0, data = {}, x_values = {}, n_calls = 0, yscales = {}, xlabels = {}, ylabels = {}, plot_pipe = None, formats = {}, output = None) if data_names is not None: n_gr = len(data_names) else: n_gr = 0 data_names = [] yscales = get_default(yscales, ['linear'] * n_gr) xlabels = get_default(xlabels, ['iteration'] * n_gr) ylabels = get_default(ylabels, [''] * n_gr ) if formats is None: formats = [None] * n_gr for ig, names in enumerate(data_names): self.add_group(names, yscales[ig], xlabels[ig], ylabels[ig], formats[ig]) self.is_plot = get_default( is_plot, True ) self.aggregate = get_default( aggregate, 100 ) self.can_plot = (can_live_plot and (mpl is not None) and (Process is not None)) if log_filename is not None: self.output = Output('', filename=log_filename) self.output('# started: %s' % time.asctime()) self.output('# groups: %d' % n_gr) for ig, names in enumerate(data_names): self.output('# %d' % ig) self.output('# xlabel: "%s", ylabel: "%s", yscales: "%s"' % (xlabels[ig], ylabels[ig], yscales[ig])) self.output('# names: "%s"' % ', '.join(names)) if self.is_plot and (not self.can_plot): output(_msg_no_live)
def __init__(self, name, terms): Struct.__init__(self, name=name) if isinstance(terms, Term): # A single term. terms = Terms([terms]) self.terms = terms self.terms.setup()
def __init__(self, filename, approx, region_selects, mat_pars, options, evp_options, eigenmomenta_options, band_gaps_options, coefs_save_name='coefs', corrs_save_names=None, incwd=None, output_dir=None, **kwargs): Struct.__init__(self, approx=approx, region_selects=region_selects, mat_pars=mat_pars, options=options, evp_options=evp_options, eigenmomenta_options=eigenmomenta_options, band_gaps_options=band_gaps_options, **kwargs) self.incwd = get_default(incwd, lambda x: x) self.conf = Struct() self.conf.filename_mesh = self.incwd(filename) output_dir = get_default(output_dir, self.incwd('output')) default = {'evp' : 'evp', 'corrs_rs' : 'corrs_rs'} self.corrs_save_names = get_default(corrs_save_names, default) io = MeshIO.any_from_filename(self.conf.filename_mesh) self.bbox, self.dim = io.read_bounding_box(ret_dim=True) rpc_axes = nm.eye(self.dim, dtype=nm.float64) \ * (self.bbox[1] - self.bbox[0]) self.conf.options = options self.conf.options.update({ 'output_dir' : output_dir, 'volume' : { 'value' : get_lattice_volume(rpc_axes), }, 'coefs' : 'coefs', 'requirements' : 'requirements', 'coefs_filename' : coefs_save_name, }) self.conf.mat_pars = mat_pars self.conf.solvers = self.define_solvers() self.conf.regions = self.define_regions() self.conf.materials = self.define_materials() self.conf.fields = self.define_fields() self.conf.variables = self.define_variables() (self.conf.ebcs, self.conf.epbcs, self.conf.lcbcs, self.all_periodic) = self.define_bcs() self.conf.functions = self.define_functions() self.conf.integrals = self.define_integrals() self.equations, self.expr_coefs = self.define_equations() self.conf.coefs = self.define_coefs() self.conf.requirements = self.define_requirements()
def __init__(self, name, terms): Struct.__init__(self, name = name) if isinstance(terms, Term): # single Term terms = Terms([terms]) self.terms = terms self.terms.setup()
def __init__(self, name): Struct.__init__(self, name=name) self.n_var = 0 self.var_names = [] self.n_dof = {} self.ptr = [0] self.indx = {} self.details = {}
def __init__(self, filename, approx, region_selects, mat_pars, options, evp_options, eigenmomenta_options, band_gaps_options, coefs_save_name='coefs', corrs_save_names=None, incwd=None, output_dir=None, **kwargs): Struct.__init__(self, approx=approx, region_selects=region_selects, mat_pars=mat_pars, options=options, evp_options=evp_options, eigenmomenta_options=eigenmomenta_options, band_gaps_options=band_gaps_options, **kwargs) self.incwd = get_default(incwd, lambda x: x) self.conf = Struct() self.conf.filename_mesh = self.incwd(filename) output_dir = get_default(output_dir, self.incwd('output')) default = {'evp' : 'evp', 'corrs_rs' : 'corrs_rs'} self.corrs_save_names = get_default(corrs_save_names, default) io = MeshIO.any_from_filename(self.conf.filename_mesh) self.bbox, self.dim = io.read_bounding_box(ret_dim=True) rpc_axes = nm.eye(self.dim, dtype=nm.float64) \ * (self.bbox[1] - self.bbox[0]) self.conf.options = options self.conf.options.update({ 'output_dir' : output_dir, 'volume' : { 'value' : get_lattice_volume(rpc_axes), }, 'coefs' : 'coefs', 'requirements' : 'requirements', 'coefs_filename' : coefs_save_name, }) self.conf.mat_pars = mat_pars self.conf.solvers = self.define_solvers() self.conf.regions = self.define_regions() self.conf.materials = self.define_materials() self.conf.fields = self.define_fields() self.conf.variables = self.define_variables() (self.conf.ebcs, self.conf.epbcs, self.conf.lcbcs, self.all_periodic) = self.define_bcs() self.conf.functions = self.define_functions() self.conf.integrals = self.define_integrals() self.equations, self.expr_coefs = self.define_equations() self.conf.coefs = self.define_coefs() self.conf.requirements = self.define_requirements()
def __init__(self, name, nodes, region, field, dof_names, filename=None): Struct.__init__(self, name=name, nodes=nodes, dof_names=dof_names) dim = field.shape[0] assert_(len(dof_names) == dim) normals = compute_nodal_normals(nodes, region, field) if filename is not None: _save_normals(filename, normals, region, field.domain.mesh) ii = nm.abs(normals).argmax(1) n_nod, dim = normals.shape irs = set(range(dim)) data = [] rows = [] cols = [] for idim in xrange(dim): ic = nm.where(ii == idim)[0] if len(ic) == 0: continue ## print ic ## print idim ir = list(irs.difference([idim])) nn = nm.empty((len(ic), dim - 1), dtype=nm.float64) for ik, il in enumerate(ir): nn[:, ik] = -normals[ic, il] / normals[ic, idim] irn = dim * ic + idim ics = [(dim - 1) * ic + ik for ik in xrange(dim - 1)] for ik in xrange(dim - 1): rows.append(irn) cols.append(ics[ik]) data.append(nn[:, ik]) ones = nm.ones((nn.shape[0], ), dtype=nm.float64) for ik, il in enumerate(ir): rows.append(dim * ic + il) cols.append(ics[ik]) data.append(ones) ## print rows ## print cols ## print data rows = nm.concatenate(rows) cols = nm.concatenate(cols) data = nm.concatenate(data) n_np_dof = n_nod * (dim - 1) mtx = sp.coo_matrix((data, (rows, cols)), shape=(n_nod * dim, n_np_dof)) self.n_dof = n_np_dof self.mtx = mtx.tocsr()
def __init__( self, name, problem, kwargs ): Struct.__init__( self, name = name, problem = problem, **kwargs ) self.problem.clear_equations() self.set_default_attr('requires', []) self.set_default_attr('is_linear', False) self.set_default_attr('dtype', nm.float64) self.set_default_attr('term_mode', None) self.set_default_attr('set_volume', 'total')
def __init__(self, name): Struct.__init__(self, name=name) self.n_var = 0 self.var_names = [] self.n_dof = {} self.ptr = [0] self.indx = {} self.details = {}
def __init__(self, name, nodes, region, field, dof_names, filename=None): Struct.__init__(self, name=name, nodes=nodes, dof_names=dof_names) dim = field.shape[0] assert_(len(dof_names) == dim) normals = compute_nodal_normals(nodes, region, field) if filename is not None: _save_normals(filename, normals, region, field.domain.mesh) ii = nm.abs(normals).argmax(1) n_nod, dim = normals.shape irs = set(range(dim)) data = [] rows = [] cols = [] for idim in xrange(dim): ic = nm.where(ii == idim)[0] if len(ic) == 0: continue ## print ic ## print idim ir = list(irs.difference([idim])) nn = nm.empty((len(ic), dim - 1), dtype=nm.float64) for ik, il in enumerate(ir): nn[:,ik] = - normals[ic,il] / normals[ic,idim] irn = dim * ic + idim ics = [(dim - 1) * ic + ik for ik in xrange(dim - 1)] for ik in xrange(dim - 1): rows.append(irn) cols.append(ics[ik]) data.append(nn[:,ik]) ones = nm.ones( (nn.shape[0],), dtype = nm.float64 ) for ik, il in enumerate(ir): rows.append(dim * ic + il) cols.append(ics[ik]) data.append(ones) ## print rows ## print cols ## print data rows = nm.concatenate(rows) cols = nm.concatenate(cols) data = nm.concatenate(data) n_np_dof = n_nod * (dim - 1) mtx = sp.coo_matrix((data, (rows, cols)), shape=(n_nod * dim, n_np_dof)) self.n_dof = n_np_dof self.mtx = mtx.tocsr()
def __init__(self, name, regions, dof_names, dof_map_fun, variables, functions=None): Struct.__init__(self, name=name, region=regions[0], dof_names=dof_names[0]) self._setup_dof_names(variables) self.eq_map = variables[self.var_name].eq_map self.field = variables[self.var_name].field self.mdofs = self.field.get_dofs_in_region(self.region, merge=True) self.n_sdof = 0
def __init__(self, t0, t1, dt=None, n_step=None, step=None, **kwargs): Struct.__init__(self, t0=t0, t1=t1, dt=dt, n_step=n_step, step=step) self.n_digit, self.format, self.suffix = get_print_info( self.n_step)
def __init__(self, igs, n_total=0, is_uniform=True): Struct.__init__(self, igs=igs, n_total=n_total, indx={}, rindx={}, n_per_group={}, shape={}, values={}, is_uniform=is_uniform) for ig in self.igs: self.indx[ig] = slice(None) self.rindx[ig] = slice(None) self.n_per_group[ig] = 0 self.shape[ig] = (0, 0, 0) self.values[ig] = nm.empty(self.shape[ig], dtype=nm.float64)
def __init__(self, igs, n_total=0, is_uniform=True): Struct.__init__(self, igs=igs, n_total=n_total, indx={}, rindx={}, n_per_group={}, shape={}, values={}, is_uniform=is_uniform) for ig in self.igs: self.indx[ig] = slice(None) self.rindx[ig] = slice(None) self.n_per_group[ig] = 0 self.shape[ig] = (0, 0, 0) self.values[ig] = nm.empty(self.shape[ig], dtype=nm.float64)
def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a Field. name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector'. The field shape determines the shape of the FE base functions and can be different from a FieldVariable instance shape. (TODO) region : Region The region where the field is defined. approx_order : int/str The FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble). Notes ----- Assumes one cell type for the whole region! """ if isinstance(shape, basestr): try: shape = {'scalar' : (1,), 'vector' : (region.domain.shape.dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, int): shape = (shape,) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self.igs = self.region.igs self.clear_dof_conns() self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._create_interpolant() self._setup_approximations() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True)
def __init__(self, knots, degrees, cps, weights, cs, conn): Struct.__init__(self, name='nurbs', knots=knots, degrees=degrees, cps=cps, weights=weights, cs=cs, conn=conn) self.n_els = [len(ii) for ii in cs] self.dim = len(self.n_els)
def __init__(self, knots, degrees, cps, weights, cs, conn): degrees = nm.asarray(degrees, dtype=nm.int32) cs = [nm.asarray(cc, dtype=nm.float64) for cc in cs] if cs[0].ndim == 3: cs = [nm.ascontiguousarray(cc[:, None, ...]) for cc in cs] Struct.__init__(self, name='nurbs', knots=knots, degrees=degrees, cps=cps, weights=weights, cs=cs, conn=conn) self.n_els = [len(ii) for ii in cs] self.dim = len(self.n_els)
def __init__(self, name, problem, kwargs): Struct.__init__(self, name=name, problem=problem, **kwargs) self.problem.clear_equations() self.set_default('requires', []) self.set_default('is_linear', False) self.set_default('dtype', nm.float64) self.set_default('term_mode', None) self.set_default('set_volume', 'total') # Application-specific options. self.app_options = self.process_options()
def __init__(self, name, regions, dof_names, dof_map_fun, variables, functions=None): Struct.__init__(self, name=name, region=regions[0], dof_names=dof_names[0]) self._setup_dof_names(variables) self.eq_map = variables[self.var_name].eq_map self.field = variables[self.var_name].field self.mdofs = self.field.get_dofs_in_region(self.region, merge=True) self.n_sdof = 0
def __init__(self, name, problem, kwargs): Struct.__init__(self, name=name, problem=problem, **kwargs) self.problem.clear_equations() self.set_default('requires', []) self.set_default('is_linear', False) self.set_default('dtype', nm.float64) self.set_default('term_mode', None) self.set_default('set_volume', 'total') # Application-specific options. self.app_options = self.process_options()
def __init__(self, name, dtype, shape, region, approx_order=None, **kwargs): """ Create a Bezier element isogeometric analysis field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : str or tuple, optional The field approximation order string or tuple with the first component in the form 'iga+<nonnegative int>'. Other components are ignored. The nonnegative int corresponds to the number of times the degree is elevated by one w.r.t. the domain NURBS description. **kwargs : dict Additional keyword arguments. """ shape = parse_shape(shape, region.domain.shape.dim) if approx_order is None: elevate_times = 0 else: if isinstance(approx_order, basestr): approx_order = (approx_order,) elevate_times = parse_approx_order(approx_order[0]) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region, elevate_times=elevate_times) self.domain = self.region.domain self.nurbs = self.domain.nurbs.elevate(elevate_times) self._setup_kind() self.n_components = nm.prod(self.shape) self.val_shape = self.shape self.n_nod = self.nurbs.weights.shape[0] self.n_efun = nm.prod(self.nurbs.degrees + 1) self.approx_order = self.nurbs.degrees.max() self.mappings = {} self.is_surface = False
def __init__(self, name, dtype, shape, region, approx_order=None, **kwargs): """ Create a Bezier element isogeometric analysis field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : str or tuple, optional The field approximation order string or tuple with the first component in the form 'iga+<nonnegative int>'. Other components are ignored. The nonnegative int corresponds to the number of times the degree is elevated by one w.r.t. the domain NURBS description. **kwargs : dict Additional keyword arguments. """ shape = parse_shape(shape, region.domain.shape.dim) if approx_order is None: elevate_times = 0 else: if isinstance(approx_order, basestr): approx_order = (approx_order,) elevate_times = parse_approx_order(approx_order[0]) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region, elevate_times=elevate_times) self.domain = self.region.domain self.nurbs = self.domain.nurbs.elevate(elevate_times) self._setup_kind() self.n_components = nm.prod(self.shape) self.val_shape = self.shape self.n_nod = self.nurbs.weights.shape[0] self.n_efun = nm.prod(self.nurbs.degrees + 1) self.approx_order = self.nurbs.degrees.max() self.mappings = {} self.is_surface = False
def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None
def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None
def __init__(self, name, mesh, verbose=False): """Create a Domain. Parameters ---------- name : str Object name. mesh : Mesh A mesh defining the domain. """ geom_els = {} for ig, desc in enumerate(mesh.descs): gel = GeometryElement(desc) # Create geometry elements of dimension - 1. gel.create_surface_facet() geom_els[desc] = gel interps = {} for gel in geom_els.itervalues(): key = gel.get_interpolation_name() gel.interp = interps.setdefault(key, fea.Interpolant(key, gel)) gel = gel.surface_facet if gel is not None: key = gel.get_interpolation_name() gel.interp = interps.setdefault(key, fea.Interpolant(key, gel)) Struct.__init__(self, name=name, mesh=mesh, geom_els=geom_els, geom_interps=interps) self.mat_ids_to_i_gs = {} for ig, mat_id in enumerate(mesh.mat_ids): self.mat_ids_to_i_gs[mat_id[0]] = ig self.setup_groups() self.fix_element_orientation() self.reset_regions() self.clear_surface_groups() from sfepy.fem.geometry_element import create_geometry_elements from sfepy.fem.extmods.cmesh import CMesh self.cmesh = CMesh.from_mesh(mesh) gels = create_geometry_elements() self.cmesh.set_local_entities(gels) self.cmesh.setup_entities() self.shape.tdim = self.cmesh.tdim
def __init__(self, region, integral, geo, state): # Uses field connectivity (higher order nodes). sd = state.field.surface_data[region.name] ISN = state.field.efaces.T.copy() nsd = region.dim ngp = geo.n_qp nsn = ISN.shape[0] fis = region.get_facet_indices() elementID = fis[:, 0].copy() segmentID = fis[:, 1].copy() # geo.bf corresponds to the field approximation. H = nm.asfortranarray(geo.bf[0, :, 0, :]) gname = state.field.gel.name ib = 3 if gname == '3_8' else 0 bqpkey = (integral.order, sd.bkey) state.field.create_bqp(region.name, integral) bqp = state.field.qp_coors[bqpkey] basis = state.field.create_basis_context() bfg3d = basis.evaluate(bqp.vals[ib], diff=True) bfg = bfg3d[:, :region.tdim - 1, state.field.efaces[ib]] if gname == '3_4': bfg = bfg[:, [1, 0], :] dH = nm.asfortranarray(bfg.ravel().reshape(((nsd - 1) * ngp, nsn))) GPs = nm.empty((len(elementID) * ngp, 2 * nsd + 6), dtype=nm.float64, order='F') Struct.__init__(self, name='contact_info_%s' % region.name, sd=sd, nsd=nsd, ngp=ngp, neq=state.n_dof, nsn=nsn, npd=region.tdim - 1, elementID=elementID, segmentID=segmentID, IEN=state.field.econn, ISN=ISN, gw=bqp.weights, H=H, dH=dH, GPs=GPs)
def __init__(self, name, dof_names, var_di): Struct.__init__(self, name=name, dof_names=dof_names, var_di=var_di) self.dpn = len(self.dof_names) self.eq = nm.arange(var_di.n_dof, dtype=nm.int32) self.n_dg_ebc = 0 self.dg_ebc_names = {} self.dg_ebc = {} self.dg_ebc_val = {} self.n_dg_epbc = 0 self.dg_epbc_names = [] self.dg_epbc = []
def __init__(self, name, nodes, region, field, dof_names, filename=None): Struct.__init__(self, name=name, nodes=nodes, dof_names=dof_names) dpn = len(dof_names) n_nod = nodes.shape[0] data = nm.ones((n_nod * dpn, )) rows = nm.arange(data.shape[0]) cols = nm.zeros((data.shape[0], )) mtx = sp.coo_matrix((data, (rows, cols)), shape=(n_nod * dpn, dpn)) self.n_dof = dpn self.mtx = mtx.tocsr()
def __init__(self, name, nodes, region, field, dof_names): Struct.__init__(self, name=name, nodes=nodes, dof_names=dof_names) dpn = len(dof_names) n_nod = nodes.shape[0] data = nm.ones((n_nod * dpn,)) rows = nm.arange(data.shape[0]) cols = nm.zeros((data.shape[0],)) mtx = sp.coo_matrix((data, (rows, cols)), shape=(n_nod * dpn, dpn)) self.n_dof = dpn self.mtx = mtx.tocsr()
def __init__(self, name, mesh=None, nurbs=None, bmesh=None, regions=None, verbose=False): Struct.__init__(self, name=name, mesh=mesh, nurbs=nurbs, bmesh=bmesh, regions=regions, verbose=verbose)
def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a Field. name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ if isinstance(shape, basestr): try: shape = {"scalar": (1,), "vector": (region.domain.shape.dim,)}[shape] except KeyError: raise ValueError("unsupported field shape! (%s)", shape) elif isinstance(shape, int): shape = (shape,) if not self._check_region(region): raise ValueError("unsuitable region for field %s! (%s)" % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self.igs = self.region.igs self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self._create_interpolant() self._setup_approximations() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True)
def __init__(self, name, mesh, verbose=False): """Create a Domain. Parameters ---------- name : str Object name. mesh : Mesh A mesh defining the domain. """ geom_els = {} for ig, desc in enumerate(mesh.descs): gel = GeometryElement(desc) # Create geometry elements of dimension - 1. gel.create_surface_facet() geom_els[desc] = gel interps = {} for gel in geom_els.itervalues(): key = gel.get_interpolation_name() gel.interp = interps.setdefault(key, fea.Interpolant(key, gel)) gel = gel.surface_facet if gel is not None: key = gel.get_interpolation_name() gel.interp = interps.setdefault(key, fea.Interpolant(key, gel)) Struct.__init__(self, name=name, mesh=mesh, geom_els=geom_els, geom_interps=interps) self.mat_ids_to_i_gs = {} for ig, mat_id in enumerate(mesh.mat_ids): self.mat_ids_to_i_gs[mat_id[0]] = ig self.setup_groups() self.fix_element_orientation() self.reset_regions() self.clear_surface_groups() from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem.extmods.cmesh import CMesh self.cmesh = CMesh.from_mesh(mesh) gels = create_geometry_elements() self.cmesh.set_local_entities(gels) self.cmesh.setup_entities() self.shape.tdim = self.cmesh.tdim self.cell_offsets = self.mesh.el_offsets
def __init__(self, name, nodes, region, field, dof_names, filename=None): Struct.__init__(self, name=name, nodes=nodes, dof_names=dof_names) dim = field.shape[0] assert_(len(dof_names) == dim) n_nod = nodes.shape[0] data = nm.ones((n_nod * dim,)) rows = nm.arange(data.shape[0]) cols = nm.zeros((data.shape[0],)) mtx = sp.coo_matrix((data, (rows, cols)), shape=(n_nod * dim, dim)) self.n_dof = dim self.mtx = mtx.tocsr()