def __init__(self, equations, setup=True, make_virtual=False, verbose=True): Container.__init__(self, equations) self.variables = Variables(self.collect_variables()) self.materials = Materials(self.collect_materials()) self.domain = self.get_domain() self.active_bcs = set() if setup: self.setup(make_virtual=make_virtual, verbose=verbose)
def __init__(self, equations): Container.__init__(self, equations) self.variables = Variables(self.collect_variables()) self.materials = Materials(self.collect_materials()) self.domain = self.get_domain() self.active_bcs = set() self.collect_conn_info()
def make_term_args(arg_shapes, arg_kinds, arg_types, ats_mode, domain): from sfepy.base.base import basestr from sfepy.fem import Field, FieldVariable, Material, Variables, Materials from sfepy.mechanics.tensors import dim2sym omega = domain.regions['Omega'] dim = domain.shape.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'S': return sym elif sh == 'N': # General number ;) return 5 else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return [_parse_scalar_shape(ii.strip()) for ii in sh.split(',')] else: return (int(sh), ) args = {} str_args = [] materials = [] variables = [] for ii, arg_kind in enumerate(arg_kinds): if ats_mode is not None: extended_ats = arg_types[ii] + ('/%s' % ats_mode) else: extended_ats = arg_types[ii] try: sh = arg_shapes[arg_types[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) field = Field.from_args('f%d' % ii, nm.float64, shape, omega, approx_order=1) if arg_kind == 'virtual_variable': if sh[1] is not None: istate = arg_types.index(sh[1]) else: # Only virtual variable in arguments. istate = -1 # -> Make fake variable. var = FieldVariable('u-1', 'unknown', field, shape) var.set_constant(0.0) variables.append(var) var = FieldVariable('v', 'test', field, shape, primary_var_name='u%d' % istate) elif arg_kind == 'state_variable': var = FieldVariable('u%d' % ii, 'unknown', field, shape) var.set_constant(0.0) elif arg_kind == 'parameter_variable': var = FieldVariable('p%d' % ii, 'parameter', field, shape, primary_var_name='(set-to-None)') var.set_constant(0.0) variables.append(var) str_args.append(var.name) args[var.name] = var elif arg_kind.endswith('material'): if sh is None: # Switched-off opt_material. continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux shape = _parse_tuple_shape(sh) if (len(shape) > 1) or (shape[0] > 1): # Array. values = { '%sc%d' % (prefix, ii): nm.ones(shape, dtype=nm.float64) } elif (len(shape) == 1) and (shape[0] == 1): # Single scalar as a special value. values = {'.c%d' % ii: 1.0} else: raise ValueError('wrong material shape! (%s)' % shape) mat = Material('m%d' % ii, values=values) materials.append(mat) str_args.append(mat.name + '.' + 'c%d' % ii) args[mat.name] = mat else: str_args.append('user%d' % ii) args[str_args[-1]] = None materials = Materials(materials) variables = Variables(variables) return args, str_args, materials, variables
def iterate(self, v_hxc_qp, eig_solver, mtx_a_equations, mtx_a_variables, mtx_b, log, file_output, n_electron=None): from sfepy.physics import dft self.itercount += 1 pb = self.problem opts = self.app_options n_electron = get_default( n_electron, opts.n_electron ) sh = self.qp_shape v_hxc_qp = nm.array(v_hxc_qp, dtype=nm.float64) v_hxc_qp.shape = (sh[0] * sh[1],) + sh[2:] mat_v = Materials(mtx_a_equations.collect_materials())['mat_v'] mat_v.set_extra_args(vhxc=v_hxc_qp) mat_v.time_update(None, pb.domain, mtx_a_equations) v_hxc_qp.shape = sh v_ion_qp = mat_v.get_data(('Omega', 'i1'), 0, 'V_ion') output( 'assembling lhs...' ) tt = time.clock() mtx_a = eval_equations(mtx_a_equations, mtx_a_variables, mode='weak', dw_mode='matrix') output( '...done in %.2f s' % (time.clock() - tt) ) assert_( nm.alltrue( nm.isfinite( mtx_a.data ) ) ) output( 'computing the Ax=Blx Kohn-Sham problem...' ) tt = time.clock() eigs, mtx_s_phi = eig_solver( mtx_a, mtx_b, opts.n_eigs, eigenvectors = True ) output( '...done in %.2f s' % (time.clock() - tt) ) n_eigs_ok = len(eigs) output( 'setting-up smearing...' ) e_f, smear_tuned = setup_smearing( eigs, n_electron ) output( 'Fermi energy:', e_f ) if e_f is None: raise Exception("cannot find Fermi energy - exiting.") weights = smear_tuned(eigs) output( '...done' ) if (weights[-1] > 1e-12): output("last smearing weight is nonzero (%s eigs ok)!" % n_eigs_ok) output( "saving solutions, iter=%d..." % self.itercount ) out = {} var_name = mtx_a_variables.get_names(kind='state')[0] for ii in xrange( n_eigs_ok ): vec_phi = mtx_a_variables.make_full_vec(mtx_s_phi[:,ii]) update_state_to_output( out, pb, vec_phi, var_name+'%03d' % ii ) name = op.join( opts.output_dir, "iter%d" % self.itercount ) pb.save_state('.'.join((name, opts.output_format)), out=out) output( "...solutions saved" ) output('computing total charge...') tt = time.clock() aux = pb.create_evaluable('dq_state_in_volume_qp.i1.Omega(Psi)') psi_equations, psi_variables = aux var = psi_variables['Psi'] n_qp = nm.zeros_like(v_hxc_qp) for ii in xrange( n_eigs_ok ): vec_phi = mtx_a_variables.make_full_vec(mtx_s_phi[:,ii]) var.data_from_any(vec_phi) phi_qp = eval_equations(psi_equations, psi_variables) n_qp += weights[ii] * (phi_qp ** 2) output('...done in %.2f s' % (time.clock() - tt)) ap, vg = var.get_approximation(('i1', 'Omega', 0), 'Volume') det = vg.variable(1) charge = (det * n_qp).sum() ## Same as above. ## out = nm.zeros((n_qp.shape[0], 1, 1, 1), dtype=nm.float64) ## vg.integrate(out, n_qp) ## charge = out.sum() vec_n = self._interp_to_nodes(n_qp) var.data_from_any(vec_n) charge_n = pb.evaluate('di_volume_integrate.i1.Omega(Psi)', Psi=var) ## # V_xc in quadrature points. v_xc_qp = nm.zeros((nm.prod(self.qp_shape),), dtype=nm.float64) for ii, val in enumerate(n_qp.flat): ## print ii, val v_xc_qp[ii] = dft.getvxc(val, 0) assert_(nm.isfinite(v_xc_qp).all()) v_xc_qp.shape = self.qp_shape mat_key = mat_v.datas.keys()[0] pb.set_equations( pb.conf.equations_vh ) pb.select_bcs( ebc_names = ['VHSurface'] ) pb.update_materials() output( "solving Ax=b Poisson equation" ) pb.materials['mat_n'].reset() pb.materials['mat_n'].set_all_data({mat_key : {0: {'N' : n_qp}}}) vec_v_h = pb.solve() var.data_from_any(vec_v_h) v_h_qp = pb.evaluate('dq_state_in_volume_qp.i1.Omega(Psi)', Psi=var) v_hxc_qp = v_h_qp + v_xc_qp norm = nla.norm(v_hxc_qp.ravel()) dnorm = abs(norm - self.norm_v_hxc0) log(norm, max(dnorm,1e-20)) # logplot of pure 0 fails. file_output( '%d: F(x) = |VH + VXC|: %f, abs(F(x) - F(x_prev)): %e'\ % (self.itercount, norm, dnorm) ) file_output("-"*70) file_output('Fermi energy:', e_f) file_output("----------------------------------------") file_output(" # | eigs | smearing") file_output("----|-----------------|-----------------") for ii in xrange( n_eigs_ok ): file_output("% 3d | %-15s | %-15s" % (ii+1, eigs[ii], weights[ii])) file_output("----------------------------------------") file_output("charge_qp: ", charge) file_output("charge_n: ", charge_n) file_output("----------------------------------------") file_output("|N|: ", nla.norm(n_qp.ravel())) file_output("|V_H|: ", nla.norm(v_h_qp.ravel())) file_output("|V_XC|: ", nla.norm(v_xc_qp.ravel())) file_output("|V_HXC|: ", norm) if self.iter_hook is not None: # User postprocessing. pb.select_bcs(ebc_names=['ZeroSurface']) mtx_phi = self.make_full(mtx_s_phi) data = Struct(iteration = self.itercount, eigs = eigs, weights = weights, mtx_s_phi = mtx_s_phi, mtx_phi = mtx_phi, vec_n = vec_n, vec_v_h = vec_v_h, n_qp = n_qp, v_ion_qp = v_ion_qp, v_h_qp = v_h_qp, v_xc_qp = v_xc_qp, file_output = file_output) self.iter_hook(self.problem, data = data) file_output("-"*70) self.norm_v_hxc0 = norm return eigs, mtx_s_phi, vec_n, vec_v_h, v_ion_qp, v_xc_qp, v_hxc_qp
class Equations( Container ): @staticmethod def from_conf(conf, variables, regions, materials, integrals, setup=True, user=None, make_virtual=False, verbose=True): objs = OneTypeList(Equation) conf = copy(conf) ii = 0 for name, desc in conf.iteritems(): if verbose: output('equation "%s":' % name) output(desc) eq = Equation.from_desc(name, desc, variables, regions, materials, integrals, user=user) objs.append(eq) ii += 1 obj = Equations(objs, setup=setup, make_virtual=make_virtual, verbose=verbose) return obj def __init__(self, equations, setup=True, make_virtual=False, verbose=True): Container.__init__(self, equations) self.variables = Variables(self.collect_variables()) self.materials = Materials(self.collect_materials()) self.domain = self.get_domain() self.active_bcs = set() if setup: self.setup(make_virtual=make_virtual, verbose=verbose) def get_domain(self): domain = None for eq in self: for term in eq.terms: if term.has_region: domain = term.region.domain return domain def setup(self, make_virtual=False, verbose=True): self.collect_conn_info() # This uses the conn_info created above. self.dof_conns = {} setup_dof_conns(self.conn_info, dof_conns=self.dof_conns, make_virtual=make_virtual, verbose=verbose) def collect_materials(self): """ Collect materials present in the terms of all equations. """ materials = [] for eq in self: materials.extend(eq.collect_materials()) # Make the list items unique. materials = list(set(materials)) return materials def reset_materials(self): """ Clear material data so that next materials.time_update() is performed even for stationary materials. """ self.materials.reset() def collect_variables(self): """ Collect variables present in the terms of all equations. """ variables = [] for eq in self: variables.extend(eq.collect_variables()) # Make the list items unique. variables = list(set(variables)) return variables def get_variable(self, name): var = self.variables.get(name, msg_if_none='unknown variable! (%s)' % name) return var def collect_conn_info(self): """ Collect connectivity information as defined by the equations. """ self.conn_info = {} for eq in self: eq.collect_conn_info(self.conn_info) ## print_structs(self.conn_info) ## pause() return self.conn_info def get_variable_names( self ): """Return the list of names of all variables used in equations.""" vns = set() for eq in self: for term in eq.terms: vns.update( term.get_variable_names() ) return list( vns ) def invalidate_term_caches(self): """ Invalidate evaluate caches of variables present in equations. """ for var in self.variables: var.invalidate_evaluate_cache() def print_terms(self): """ Print names of equations and their terms. """ output('equations:') for eq in self: output(' %s:' % eq.name) for term in eq.terms: output(' %+.2e * %s.%d.%s(%s)' % (term.sign, term.name, term.integral.order, term.region.name, term.arg_str)) def time_update(self, ts, ebcs=None, epbcs=None, lcbcs=None, functions=None, problem=None, verbose=True): """ Update the equations for current time step. The update involves creating the mapping of active DOFs from/to all DOFs for all state variables, the setup of linear combination boundary conditions operators and the setup of active DOF connectivities. Parameters ---------- ts : TimeStepper instance The time stepper. ebcs : Conditions instance, optional The essential (Dirichlet) boundary conditions. epbcs : Conditions instance, optional The periodic boundary conditions. lcbcs : Conditions instance, optional The linear combination boundary conditions. functions : Functions instance, optional The user functions for boundary conditions, materials, etc. problem : ProblemDefinition instance, optional The problem that can be passed to user functions as a context. verbose : bool If False, reduce verbosity. Returns ------- graph_changed : bool The flag set to True if the current time step set of active boundary conditions differs from the set of the previous time step. """ self.variables.time_update(ts, functions, verbose=verbose) active_bcs = self.variables.equation_mapping(ebcs, epbcs, ts, functions, problem=problem) graph_changed = active_bcs != self.active_bcs self.active_bcs = active_bcs self.variables.setup_lcbc_operators(lcbcs, ts, functions) self.variables.setup_adof_conns() for eq in self: for term in eq.terms: term.time_update(ts) return graph_changed def time_update_materials(self, ts, mode='normal', problem=None, verbose=True): """ Update data materials for current time and possibly also state. Parameters ---------- ts : TimeStepper instance The time stepper. mode : 'normal', 'update' or 'force' The update mode, see :func:`sfepy.fem.materials.Material.time_update()`. problem : ProblemDefinition instance, optional The problem that can be passed to user functions as a context. verbose : bool If False, reduce verbosity. """ self.materials.time_update(ts, self, mode=mode, problem=problem, verbose=verbose) def setup_initial_conditions(self, ics, functions): self.variables.setup_initial_conditions(ics, functions) def get_graph_conns(self, any_dof_conn=False, rdcs=None, cdcs=None): """ Get DOF connectivities needed for creating tangent matrix graph. Parameters ---------- any_dof_conn : bool By default, only volume DOF connectivities are used, with the exception of trace surface DOF connectivities. If True, any kind of DOF connectivities is allowed. rdcs, cdcs : arrays, optional Additional row and column DOF connectivities, corresponding to the variables used in the equations. Returns ------- rdcs, cdcs : arrays The row and column DOF connectivities defining the matrix graph blocks. """ if rdcs is None: rdcs = [] cdcs = [] elif cdcs is None: cdcs = copy(rdcs) else: assert_(len(rdcs) == len(cdcs)) if rdcs is cdcs: # Make sure the lists are not the same object. rdcs = copy(rdcs) adcs = self.variables.adof_conns # Only volume dof connectivities are used, with the exception of trace # surface dof connectivities. shared = set() for key, ii, info in iter_dict_of_lists(self.conn_info, return_keys=True): rvar, cvar = info.virtual, info.state if (rvar is None) or (cvar is None): continue is_surface = rvar.is_surface or cvar.is_surface dct = info.dc_type.type if not (dct in ('volume', 'scalar') or is_surface or info.is_trace or any_dof_conn): continue rreg_name = info.get_region_name(can_trace=False) creg_name = info.get_region_name() for rig, cig in info.iter_igs(): rname = rvar.get_primary_name() rkey = (rname, rreg_name, dct, rig, False) ckey = (cvar.name, creg_name, dct, cig, info.is_trace) dc_key = (rkey, ckey) ## print dc_key if not dc_key in shared: try: rdcs.append(adcs[rkey]) cdcs.append(adcs[ckey]) except: debug() shared.add(dc_key) return rdcs, cdcs def create_matrix_graph(self, any_dof_conn=False, rdcs=None, cdcs=None, shape=None): """ Create tangent matrix graph, i.e. preallocate and initialize the sparse storage needed for the tangent matrix. Order of DOF connectivities is not important. Parameters ---------- any_dof_conn : bool By default, only volume DOF connectivities are used, with the exception of trace surface DOF connectivities. If True, any kind of DOF connectivities is allowed. rdcs, cdcs : arrays, optional Additional row and column DOF connectivities, corresponding to the variables used in the equations. shape : tuple, optional The required shape, if it is different from the shape determined by the equations variables. This may be needed if additional row and column DOF connectivities are passed in. Returns ------- matrix : csr_matrix The matrix graph in the form of a CSR matrix with preallocated structure and zero data. """ if not self.variables.has_virtuals(): output('no matrix (no test variables)!') return None shape = get_default(shape, self.variables.get_matrix_shape()) output( 'matrix shape:', shape ) if nm.prod( shape ) == 0: output( 'no matrix (zero size)!' ) return None rdcs, cdcs = self.get_graph_conns(any_dof_conn=any_dof_conn, rdcs=rdcs, cdcs=cdcs) if not len(rdcs): output('no matrix (empty dof connectivities)!') return None output( 'assembling matrix graph...' ) tt = time.clock() nnz, prow, icol = create_mesh_graph(shape[0], shape[1], len(rdcs), rdcs, cdcs) output( '...done in %.2f s' % (time.clock() - tt) ) output( 'matrix structural nonzeros: %d (%.2e%% fill)' \ % (nnz, float( nnz ) / nm.prod( shape ) ) ) ## print ret, prow, icol, nnz data = nm.zeros( (nnz,), dtype = self.variables.dtype ) matrix = sp.csr_matrix( (data, icol, prow), shape ) ## matrix.save( 'matrix', format = '%d %d %e\n' ) ## pause() return matrix ## # c: 02.04.2008, r: 02.04.2008 def init_time( self, ts ): pass ## # 08.06.2007, c def advance( self, ts ): for eq in self: for term in eq.terms: term.advance(ts) self.variables.advance(ts) ## # Interface to self.variables. def create_state_vector(self): return self.variables.create_state_vector() def create_stripped_state_vector(self): return self.variables.create_stripped_state_vector() def strip_state_vector(self, vec, follow_epbc=False): """ Strip a full vector by removing EBC dofs. Notes ----- If 'follow_epbc' is True, values of EPBC master dofs are not simply thrown away, but added to the corresponding slave dofs, just like when assembling. For vectors with state (unknown) variables it should be set to False, for assembled vectors it should be set to True. """ return self.variables.strip_state_vector(vec, follow_epbc=follow_epbc) def make_full_vec(self, svec, force_value=None): """ Make a full DOF vector satisfying E(P)BCs from a reduced DOF vector. """ return self.variables.make_full_vec(svec, force_value) def set_variables_from_state(self, vec, step=0): """ Set data (vectors of DOF values) of variables. Parameters ---------- data : array The state vector. step : int The time history step, 0 (default) = current. """ self.variables.set_data(vec, step=step) def get_state_parts(self, vec=None): """ Return parts of a state vector corresponding to individual state variables. Parameters ---------- vec : array, optional The state vector. If not given, then the data stored in the variables are returned instead. Returns ------- out : dict The dictionary of the state parts. """ return self.variables.get_state_parts(vec) def set_data(self, data, step=0, ignore_unknown=False): """ Set data (vectors of DOF values) of variables. Parameters ---------- data : array The dictionary of {variable_name : data vector}. step : int, optional The time history step, 0 (default) = current. ignore_unknown : bool, optional Ignore unknown variable names if `data` is a dict. """ self.variables.set_data(data, step=step, ignore_unknown=ignore_unknown) def apply_ebc(self, vec, force_values=None): """ Apply essential (Dirichlet) boundary conditions to a state vector. """ self.variables.apply_ebc(vec, force_values=force_values) def apply_ic(self, vec, force_values=None): """ Apply initial conditions to a state vector. """ self.variables.apply_ic(vec, force_values=force_values) def state_to_output(self, vec, fill_value=None, var_info=None, extend=True): return self.variables.state_to_output(vec, fill_value=fill_value, var_info=var_info, extend=extend) def get_lcbc_operator(self): return self.variables.get_lcbc_operator() def evaluate(self, mode='eval', dw_mode='vector', term_mode=None, asm_obj=None): """ Parameters ---------- mode : one of 'eval', 'el_avg', 'qp', 'weak' The evaluation mode. """ if mode == 'weak': out = asm_obj else: out = {} for eq in self: eout = eq.evaluate(mode=mode, dw_mode=dw_mode, term_mode=term_mode, asm_obj=asm_obj) if mode != 'weak': out[eq.name] = eout if (len(self) == 1) and (mode != 'weak'): out = out.popitem()[1] return out def eval_residuals(self, state, by_blocks=False, names=None): """ Evaluate (assemble) residual vectors. Parameters ---------- state : array The vector of DOF values. Note that it is needed only in nonlinear terms. by_blocks : bool If True, return the individual blocks composing the whole residual vector. Each equation should then correspond to one required block and should be named as `'block_name, test_variable_name, unknown_variable_name'`. names : list of str, optional Optionally, select only blocks with the given `names`, if `by_blocks` is True. Returns ------- out : array or dict of array The assembled residual vector. If `by_blocks` is True, a dictionary is returned instead, with keys given by `block_name` part of the individual equation names. """ self.set_variables_from_state(state) if by_blocks: names = get_default(names, self.names) out = {} get_indx = self.variables.get_indx for name in names: eq = self[name] key, rname, cname = [aux.strip() for aux in name.split(',')] ir = get_indx(rname, stripped=True, allow_dual=True) residual = self.create_stripped_state_vector() eq.evaluate(mode='weak', dw_mode='vector', asm_obj=residual) out[key] = residual[ir] else: out = self.create_stripped_state_vector() self.evaluate(mode='weak', dw_mode='vector', asm_obj=out) return out def eval_tangent_matrices(self, state, tangent_matrix, by_blocks=False, names=None): """ Evaluate (assemble) tangent matrices. Parameters ---------- state : array The vector of DOF values. Note that it is needed only in nonlinear terms. tangent_matrix : csr_matrix The preallocated CSR matrix with zero data. by_blocks : bool If True, return the individual blocks composing the whole matrix. Each equation should then correspond to one required block and should be named as `'block_name, test_variable_name, unknown_variable_name'`. names : list of str, optional Optionally, select only blocks with the given `names`, if `by_blocks` is True. Returns ------- out : csr_matrix or dict of csr_matrix The assembled matrix. If `by_blocks` is True, a dictionary is returned instead, with keys given by `block_name` part of the individual equation names. """ self.set_variables_from_state(state) if by_blocks: names = get_default(names, self.names) out = {} get_indx = self.variables.get_indx for name in names: eq = self[name] key, rname, cname = [aux.strip() for aux in eq.name.split(',')] ir = get_indx(rname, stripped=True, allow_dual=True) ic = get_indx(cname, stripped=True, allow_dual=True) tangent_matrix.data[:] = 0.0 eq.evaluate(mode='weak', dw_mode='matrix', asm_obj=tangent_matrix) out[key] = tangent_matrix[ir, ic] else: tangent_matrix.data[:] = 0.0 self.evaluate(mode='weak', dw_mode='matrix', asm_obj=tangent_matrix) out = tangent_matrix return out