def get_parametrized_conf(filename, args): import importlib prefix = "" problem_module_name = filename.replace(".py", "").strip("\\.") \ .replace("\\", ".").replace("/", ".") if not problem_module_name.startswith(prefix): problem_module_name = prefix + problem_module_name problem_module = importlib.import_module(problem_module_name) dg_args = { dg_par_name: args.__dict__[dg_par_name] for dg_par_name in param_names + ["mesh_file", "order"] if args.__dict__[dg_par_name] is not None } if hasattr(problem_module, "define"): mod = sys.modules[problem_module_name] # noinspection PyCallingNonCallable problem_conf = ProblemConf.from_dict(problem_module.define(**dg_args), mod, verbose=args.verbose) if args.mesh_file is not None: problem_conf.options.absolute_mesh_path = True else: output("Problem file is not parametrized, arguments ignored") problem_conf = ProblemConf.from_file(filename, verbose=False) problem_conf.verbose = args.verbose return problem_conf
def main(): parser = OptionParser(usage=usage, version="%prog " + sfepy.__version__) parser.add_option("-o", "", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=help['filename']) (options, args) = parser.parse_args() if (len(args) == 1): filename_in = args[0] else: parser.print_help(), return required, other = get_standard_keywords() required.remove('equations') conf = ProblemConf.from_file(filename_in, required, other) app = HomogenizationApp(conf, options, 'homogen:') opts = conf.options if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) app()
def test_solution(self): from sfepy.base.base import Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications import solve_pde, assign_standard_hooks import numpy as nm import os.path as op solutions = {} ok = True for hp, pb_filename in six.iteritems(input_names): required, other = get_standard_keywords() input_name = op.join(op.dirname(__file__), pb_filename) test_conf = ProblemConf.from_file(input_name, required, other) name = output_name_trunk + hp solver_options = Struct(output_filename_trunk=name, output_format='vtk', save_ebc=False, save_ebc_nodes=False, save_regions=False, save_regions_as_groups=False, save_field_meshes=False, solve_not=False) assign_standard_hooks(self, test_conf.options.get, test_conf) self.report( 'hyperelastic formulation: %s' % (hp, ) ) status = NLSStatus(conditions=[]) pb, state = solve_pde(test_conf, solver_options, status=status, output_dir=self.options.out_dir, step_hook=self.step_hook, post_process_hook=self.post_process_hook, post_process_hook_final=self.post_process_hook_final) converged = status.nls_status.condition == 0 ok = ok and converged solutions[hp] = state.get_parts()['u'] self.report('%s solved' % input_name) rerr = 1.0e-3 aerr = nm.linalg.norm(solutions['TL'], ord=None) * rerr self.report('allowed error: rel = %e, abs = %e' % (rerr, aerr)) ok = ok and self.compare_vectors(solutions['TL'], solutions['UL'], label1='TLF', label2='ULF', allowed_error=rerr) ok = ok and self.compare_vectors(solutions['UL'], solutions['ULM'], label1='ULF', label2='ULF_mixed', allowed_error=rerr) return ok
def test_solution(self): from sfepy.base.base import Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications import solve_pde, assign_standard_hooks import numpy as nm import os.path as op solutions = {} ok = True for hp, pb_filename in input_names.iteritems(): required, other = get_standard_keywords() input_name = op.join(op.dirname(__file__), pb_filename) test_conf = ProblemConf.from_file(input_name, required, other) name = output_name_trunk + hp solver_options = Struct(output_filename_trunk=name, output_format='vtk', save_ebc=False, save_ebc_nodes=False, save_regions=False, save_regions_as_groups=False, save_field_meshes=False, solve_not=False) assign_standard_hooks(self, test_conf.options.get, test_conf) self.report( 'hyperelastic formulation: %s' % (hp, ) ) status = NLSStatus(conditions=[]) pb, state = solve_pde(test_conf, solver_options, nls_status=status, output_dir=self.options.out_dir, step_hook=self.step_hook, post_process_hook=self.post_process_hook, post_process_hook_final=self.post_process_hook_final) converged = status.condition == 0 ok = ok and converged solutions[hp] = state.get_parts()['u'] self.report('%s solved' % input_name) rerr = 1.0e-3 aerr = nm.linalg.norm(solutions['TL'], ord=None) * rerr self.report('allowed error: rel = %e, abs = %e' % (rerr, aerr)) ok = ok and self.compare_vectors(solutions['TL'], solutions['UL'], label1='TLF', label2='ULF', allowed_error=rerr) ok = ok and self.compare_vectors(solutions['UL'], solutions['ULM'], label1='ULF', label2='ULF_mixed', allowed_error=rerr) return ok
def main(): parser = OptionParser(usage=usage, version="%prog " + sfepy.__version__) parser.add_option( "-s", "--server", action="store_true", dest="server_mode", default=False, help=help["server_mode"] ) parser.add_option("-a", "--adjoint", action="store_true", dest="adjoint", default=False, help=help["adjoint"]) parser.add_option("-d", "--direct", action="store_true", dest="direct", default=False, help=help["direct"]) parser.add_option( "-t", "--test", type=int, metavar="idsg", action="store", dest="test", default=None, help=help["test"] ) parser.add_option( "", "--dump", metavar="filename", action="store", dest="dump_filename", default=None, help=help["dump"] ) parser.add_option( "", "--pert-mesh", metavar="filename", action="store", dest="pert_mesh_filename", default=None, help=help["pert"], ) parser.add_option("-f", "--full", action="store_true", dest="optimize", default=False, help=help["optimize"]) options, args = parser.parse_args() if options.test is not None: options.adjoint = options.direct = True if options.optimize: options.adjoint = options.direct = False if (len(args) == 1) and (options.direct or options.adjoint or options.optimize): filename_in = args[0] else: parser.print_help(), return required, other = get_standard_keywords() required.remove("equations") if options.adjoint: required += ["equations_adjoint_.*", "filename_vp", "equations_direct_.*"] options.direct = True elif options.direct: required += ["equations_direct_.*"] elif options.optimize: required += ["equations_direct_.*", "equations_adjoint_.*", "equations_sensitivity_.*", "filename_vp"] conf = ProblemConf.from_file(filename_in, required, other) if options.direct: dpb, state_dp, data = solve_direct(conf, options) else: dpb, state_dp, data = None, None, None if options.adjoint: solve_adjoint(conf, options, dpb, state_dp, data) if options.optimize: solve_optimize(conf, options)
def get_examples(table): term_use = dict_from_keys_init(table.keys(), set) required, other = get_standard_keywords() for filename in locate_files('*py', get_paths('examples/')[0]): try: conf = ProblemConf.from_file(filename, required, other, verbose=False) except: continue ebase = filename.split('examples/')[1] lbase = os.path.splitext(ebase)[0] label = lbase.replace('/', '-') pyfile_name = ebase.split('/')[1] if pyfile_name in omits: continue use = conf.options.get('use_equations', 'equations') eqs_conf = getattr(conf, use) for key, eq_conf in six.iteritems(eqs_conf): term_descs = parse_definition(eq_conf) for td in term_descs: term_use[td.name].add(label) return term_use
def from_conf(conf, options, cls=None): from sfepy.base.base import Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications import assign_standard_hooks required, other = get_standard_keywords() input_name = op.join(op.dirname(__file__), conf.input_name) test_conf = ProblemConf.from_file(input_name, required, other) if cls is None: cls = TestInput test = cls(test_conf=test_conf, conf=conf, options=options) assign_standard_hooks(test, test_conf.options.get, test_conf) name = test.get_output_name_trunk() test.solver_options = Struct(output_filename_trunk=name, output_format='vtk', save_ebc=False, save_ebc_nodes=False, save_regions=False, save_regions_as_groups=False, save_field_meshes=False, solve_not=False) return test
def create_app(filename, is_homog=False, **kwargs): from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.applications import PDESolverApp required, other = get_standard_keywords() if is_homog: required.remove('equations') conf = ProblemConf.from_file(filename, required, other, define_args=kwargs) options = Struct(output_filename_trunk=None, save_ebc=False, save_ebc_nodes=False, save_regions=False, save_regions_as_groups=False, save_field_meshes=False, solve_not=False) if is_homog: app = HomogenizationApp(conf, options, 'material_opt_micro:') else: app = PDESolverApp(conf, options, 'material_opt_macro:') app.conf.opt_data = {} opts = conf.options if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) return app
def from_conf(conf, options, cls=None): from sfepy.base.base import Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications.simple_app import assign_standard_hooks required, other = get_standard_keywords() input_name = op.join(op.dirname(__file__), conf.input_name) test_conf = ProblemConf.from_file(input_name, required, other) if cls is None: cls = TestInput test = cls(test_conf=test_conf, conf=conf, options=options) assign_standard_hooks(test, test_conf.options.get_default_attr, test_conf.funmod) name = op.join(test.options.out_dir, test.get_output_name_trunk()) test.solver_options = Struct(output_filename_trunk = name, output_format ='vtk', save_ebc = False, save_regions = False, save_regions_as_groups = False, save_field_meshes = False, save_region_field_meshes = False, solve_not = False) return test
def pde_solve(conf_filename, options=None, **app_options): required, other = get_standard_keywords() conf = ProblemConf.from_file(conf_filename, required, other) opts = conf.options = dict_to_struct(app_options, flag=(1,)) + conf.options output_prefix = opts.get_default_attr('output_prefix', None) if output_prefix is None: output_prefix = output.prefix if options is None: options = Struct(output_filename_trunk = None, save_ebc = False, save_regions = False, save_field_meshes = False, save_region_field_meshes = False, save_regions_as_groups = False, solve_not = False) app = SimpleApp(conf, options, output_prefix) if hasattr( opts, 'parametric_hook' ): # Parametric study. parametric_hook = getattr(conf, opts.parametric_hook) app.parametrize(parametric_hook) return app()
def main(): parser = ArgumentParser() parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument("-o", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=helps['filename']) parser.add_argument('filename_in') options = parser.parse_args() if options.debug: from sfepy.base.base import debug_on_error; debug_on_error() filename_in = options.filename_in required, other = get_standard_keywords() required.remove('equations') conf = ProblemConf.from_file(filename_in, required, other) app = HomogenizationApp(conf, options, 'homogen:') opts = conf.options if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) app()
def main(): parser = OptionParser(usage=usage, version='%prog') parser.add_option('-c', '--counts', action='store_true', dest='counts', default=False, help=helps['counts']) parser.add_option('-u', '--unused', action='store_true', dest='unused', default=False, help=helps['unused']) options, args = parser.parse_args() if len(args) > 0: pdf_dir = os.path.realpath(args[0]) else: parser.print_help(), return required, other = get_standard_keywords() terms_use = dict_from_keys_init(term_table.keys(), set) for filename in locate_files('*.py', pdf_dir): base = filename.replace(pdf_dir, '').lstrip(os.path.sep) output('trying "%s"...' % base) try: conf = ProblemConf.from_file(filename, required, other, verbose=False) except: output('...failed') continue use = conf.options.get('use_equations', 'equations') eqs_conf = getattr(conf, use) for key, eq_conf in eqs_conf.iteritems(): term_descs = parse_definition(eq_conf) for td in term_descs: terms_use[td.name].add(base) output('...ok') output('...done') if options.unused: output('unused terms:') unused = [name for name in terms_use.keys() if len(terms_use[name]) == 0] for name in sorted(unused): output(' ' + name) output('total: %d' % len(unused)) else: output('terms use:') for name, ex_names in ordered_iteritems(terms_use): output('%s: %d' % (name, len(ex_names))) if not options.counts: for ex_name in sorted(ex_names): output(' ' + ex_name)
def main(): from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.fem import ProblemDefinition from sfepy.applications import solve_evolutionary output.prefix = 'therel:' required, other = get_standard_keywords() conf = ProblemConf.from_file(__file__, required, other) problem = ProblemDefinition.from_conf(conf, init_equations=False) # Setup output directory according to options above. problem.setup_default_output() # First solve the stationary electric conduction problem. problem.set_equations({'eq' : conf.equations['1']}) problem.time_update() state_el = problem.solve() problem.save_state(problem.get_output_name(suffix = 'el'), state_el) # Then solve the evolutionary heat conduction problem, using state_el. problem.set_equations({'eq' : conf.equations['2']}) phi_var = problem.get_variables()['phi_known'] phi_var.data_from_any(state_el()) solve_evolutionary(problem) output('results saved in %s' % problem.get_output_name(suffix = '*'))
def main(): from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.discrete import Problem output.prefix = "therel:" required, other = get_standard_keywords() conf = ProblemConf.from_file(__file__, required, other) problem = Problem.from_conf(conf, init_equations=False) # Setup output directory according to options above. problem.setup_default_output() # First solve the stationary electric conduction problem. problem.set_equations({"eq": conf.equations["1"]}) problem.time_update() state_el = problem.solve() problem.save_state(problem.get_output_name(suffix="el"), state_el) # Then solve the evolutionary heat conduction problem, using state_el. problem.set_equations({"eq": conf.equations["2"]}) phi_var = problem.get_variables()["phi_known"] phi_var.set_data(state_el()) time_solver = problem.get_time_solver() time_solver() output("results saved in %s" % problem.get_output_name(suffix="*"))
def main(): from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.fem import ProblemDefinition from sfepy.base.plotutils import plt parser = OptionParser(usage=usage, version='%prog') parser.add_option('-n', '--no-plot', action="store_true", dest='no_plot', default=False, help=helps['no_plot']) options, args = parser.parse_args() required, other = get_standard_keywords() # Use this file as the input file. conf = ProblemConf.from_file( __file__, required, other ) # Create problem instance, but do not set equations. problem = ProblemDefinition.from_conf( conf, init_equations = False ) # Solve the problem. Output is ignored, results stored by using the # step_hook. u_t = solve_branch(problem, linear_tension) u_c = solve_branch(problem, linear_compression) # Get pressure load by calling linear_*() for each time step. ts = problem.get_timestepper() load_t = nm.array([linear_tension(ts, nm.array([[0.0]]), 'qp')['val'] for aux in ts.iter_from( 0 )], dtype=nm.float64).squeeze() load_c = nm.array([linear_compression(ts, nm.array([[0.0]]), 'qp')['val'] for aux in ts.iter_from( 0 )], dtype=nm.float64).squeeze() # Join the branches. displacements = {} for key in u_t.keys(): displacements[key] = nm.r_[u_c[key][::-1], u_t[key]] load = nm.r_[load_c[::-1], load_t] if plt is None: print 'matplotlib cannot be imported, printing raw data!' print displacements print load else: legend = [] for key, val in displacements.iteritems(): plt.plot( load, val ) legend.append( key ) plt.legend( legend, loc = 2 ) plt.xlabel( 'tension [kPa]' ) plt.ylabel( 'displacement [mm]' ) plt.grid( True ) plt.gcf().savefig( 'pressure_displacement.png' ) if not options.no_plot: plt.show()
def run_test(conf_name, options): from sfepy.base.ioutils import ensure_path ensure_path(op.join(options.out_dir, 'any')) if options.filter_none or options.raise_on_error: of = None elif options.filter_less: of = OutputFilter(['<<<', '>>>', '...', '!!!', '+++', '---']) elif options.filter_more: of = OutputFilter(['+++', '---']) else: of = OutputFilter(['<<<', '+++', '---']) print('<<< %s' % conf_name) _required, other = get_standard_keywords() required = ['Test'] num = 1 test_time = 0.0 try: conf = ProblemConf.from_file(conf_name, required, _required + other) test = conf.funmod.Test.from_conf(conf, options) num = test.get_number() ok = True print('>>> test instance prepared (%d test(s))' % num) except KeyboardInterrupt: print('>>> interrupted') sys.exit(0) except: print('--- test instance creation failed') if options.raise_on_error: raise ok, n_fail, n_total = False, num, num if ok: try: tt = time.clock() ok, n_fail, n_total = test.run(options.raise_on_error) test_time = time.clock() - tt except KeyboardInterrupt: print('>>> interrupted') sys.exit(0) except Exception as e: print('>>> %s' % e.__class__) if options.raise_on_error: raise ok, n_fail, n_total = False, num, num if ok: print('>>> all passed in %.2f s' % test_time) else: print('!!! %s test failed' % n_fail) if of is not None: of.stop() return n_fail, n_total, test_time
def main(): from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.discrete import Problem from sfepy.base.plotutils import plt parser = OptionParser(usage=usage, version='%prog') parser.add_option('-n', '--no-plot', action="store_true", dest='no_plot', default=False, help=helps['no_plot']) options, args = parser.parse_args() required, other = get_standard_keywords() # Use this file as the input file. conf = ProblemConf.from_file(__file__, required, other) # Create problem instance, but do not set equations. problem = Problem.from_conf(conf, init_equations=False) # Solve the problem. Output is ignored, results stored by using the # step_hook. u_t = solve_branch(problem, linear_tension) u_c = solve_branch(problem, linear_compression) # Get pressure load by calling linear_*() for each time step. ts = problem.get_timestepper() load_t = nm.array([linear_tension(ts, nm.array([[0.0]]), 'qp')['val'] for aux in ts.iter_from(0)], dtype=nm.float64).squeeze() load_c = nm.array([linear_compression(ts, nm.array([[0.0]]), 'qp')['val'] for aux in ts.iter_from(0)], dtype=nm.float64).squeeze() # Join the branches. displacements = {} for key in u_t.keys(): displacements[key] = nm.r_[u_c[key][::-1], u_t[key]] load = nm.r_[load_c[::-1], load_t] if plt is None: output('matplotlib cannot be imported, printing raw data!') output(displacements) output(load) else: legend = [] for key, val in six.iteritems(displacements): plt.plot(load, val) legend.append(key) plt.legend(legend, loc = 2) plt.xlabel('tension [kPa]') plt.ylabel('displacement [mm]') plt.grid(True) plt.gcf().savefig('pressure_displacement.png') if not options.no_plot: plt.show()
def assemble_matrices(define, mod, pars, set_wave_dir, options, wdir=None): """ Assemble the blocks of dispersion eigenvalue problem matrices. """ define_dict = define(filename_mesh=options.mesh_filename, pars=pars, approx_order=options.order, refinement_level=options.refine, solver_conf=options.solver_conf, plane=options.plane, post_process=options.post_process, **options.define_kwargs) conf = ProblemConf.from_dict(define_dict, mod) pb = Problem.from_conf(conf) pb.dispersion_options = options pb.set_output_dir(options.output_dir) dim = pb.domain.shape.dim # Set the normalized wave vector direction to the material(s). if wdir is None: wdir = nm.asarray(options.wave_dir[:dim], dtype=nm.float64) wdir = wdir / nm.linalg.norm(wdir) set_wave_dir(pb, wdir) bbox = pb.domain.mesh.get_bounding_box() size = (bbox[1] - bbox[0]).max() scaling0 = apply_unit_multipliers([1.0], ['length'], options.unit_multipliers)[0] scaling = scaling0 if options.mesh_size is not None: scaling *= options.mesh_size / size output('scaling factor of periodic cell mesh coordinates:', scaling) output('new mesh size with applied unit multipliers:', scaling * size) pb.domain.mesh.coors[:] *= scaling pb.set_mesh_coors(pb.domain.mesh.coors, update_fields=True) bzone = 2.0 * nm.pi / (scaling * size) output('1. Brillouin zone size:', bzone * scaling0) output('1. Brillouin zone size with applied unit multipliers:', bzone) pb.time_update() pb.update_materials() # Assemble the matrices. mtxs = {} for key, eq in pb.equations.iteritems(): mtxs[key] = mtx = pb.mtx_a.copy() mtx = eq.evaluate(mode='weak', dw_mode='matrix', asm_obj=mtx) mtx.eliminate_zeros() output_array_stats(mtx.data, 'nonzeros in %s' % key) output('symmetry checks:') output('%s - %s^T:' % (key, key), max_diff_csr(mtx, mtx.T)) output('%s - %s^H:' % (key, key), max_diff_csr(mtx, mtx.H)) return pb, wdir, bzone, mtxs
def test_stokes_slip_bc(self): import scipy.sparse as sp from sfepy.base.conf import ProblemConf from sfepy.discrete import Problem import examples.navier_stokes.stokes_slip_bc as ssb conf = ProblemConf.from_module(ssb) pb = Problem.from_conf(conf, init_solvers=False) pb.time_update() variables = pb.get_variables() adi = variables.adi lcdi = variables.lcdi mtx = variables.mtx_lcbc ok = adi.var_names == lcdi.var_names self.report('same adi-lcdi ordering:', ok) ublock = mtx[adi.indx['u']] ir, ic = ublock.nonzero() ir += adi.indx['u'].start i0, i1 = adi.indx['u'].start, adi.indx['u'].stop _ok0 = (i0 <= ir).all() and (ir < i1).all() self.report('u block rows in [%d %d[: %s' % (i0, i1, _ok0)) i0, i1 = lcdi.indx['u'].start, lcdi.indx['u'].stop _ok1 = (i0 <= ic).all() and (ic < i1).all() self.report('u block cols in [%d %d[: %s' % (i0, i1, _ok1)) ok = ok and _ok0 and _ok1 pblock = mtx[adi.indx['p']] ir, ic, iv = sp.find(pblock) ir += adi.indx['p'].start i0, i1 = adi.indx['p'].start, adi.indx['p'].stop _ok0 = (i0 <= ir).all() and (ir < i1).all() self.report('p block rows in [%d %d[: %s' % (i0, i1, _ok0)) i0, i1 = lcdi.indx['p'].start, lcdi.indx['p'].stop _ok1 = (i0 <= ic).all() and (ic < i1).all() self.report('p block cols in [%d %d[: %s' % (i0, i1, _ok1)) ok = ok and _ok0 and _ok1 _ok0 = (len(ir) == adi.n_dof['p']) self.report('p block size correct:', _ok0) _ok1 = ((ir - adi.indx['p'].start) == (ic - lcdi.indx['p'].start)).all() self.report('p block diagonal:', _ok1) _ok2 = (iv == 1.0).all() self.report('p block identity:', _ok2) ok = ok and _ok0 and _ok1 and _ok2 return ok
def main(): version = open( op.join( init_sfepy.install_dir, 'VERSION' ) ).readlines()[0][:-1] parser = OptionParser( usage = usage, version = "%prog " + version ) 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 = "vtk", help = help['output_format'] ) 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-field-meshes", action = "store_true", dest = "save_field_meshes", default = False, help = help['save_field_meshes'] ) parser.add_option( "", "--save-region-field-meshes", action = "store_true", dest = "save_region_field_meshes", default = False, help = help['save_region_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() # print options; pause() if (len( args ) == 1): filename_in = args[0]; else: if options._list == 'terms': print_terms() else: parser.print_help(), return 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( filename_in, required, other ) 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 = getattr( conf, opts.parametric_hook ) app.parametrize( parametric_hook ) app()
def assemble_matrices(define, mod, pars, set_wave_dir, options): """ Assemble the blocks of dispersion eigenvalue problem matrices. """ define_problem = functools.partial(define, filename_mesh=options.mesh_filename, pars=pars, approx_order=options.order, refinement_level=options.refine, solver_conf=options.solver_conf, plane=options.plane, post_process=options.post_process) conf = ProblemConf.from_dict(define_problem(), mod) pb = Problem.from_conf(conf) pb.dispersion_options = options pb.set_output_dir(options.output_dir) dim = pb.domain.shape.dim # Set the normalized wave vector direction to the material(s). wdir = nm.asarray(options.wave_dir[:dim], dtype=nm.float64) wdir = wdir / nm.linalg.norm(wdir) set_wave_dir(pb, wdir) bbox = pb.domain.mesh.get_bounding_box() size = (bbox[1] - bbox[0]).max() scaling0 = apply_unit_multipliers([1.0], ['length'], options.unit_multipliers)[0] scaling = scaling0 if options.mesh_size is not None: scaling *= options.mesh_size / size output('scaling factor of periodic cell mesh coordinates:', scaling) output('new mesh size with applied unit multipliers:', scaling * size) pb.domain.mesh.coors[:] *= scaling pb.set_mesh_coors(pb.domain.mesh.coors, update_fields=True) bzone = 2.0 * nm.pi / (scaling * size) output('1. Brillouin zone size:', bzone * scaling0) output('1. Brillouin zone size with applied unit multipliers:', bzone) pb.time_update() pb.update_materials() # Assemble the matrices. mtxs = {} for key, eq in pb.equations.iteritems(): mtxs[key] = mtx = pb.mtx_a.copy() mtx = eq.evaluate(mode='weak', dw_mode='matrix', asm_obj=mtx) mtx.eliminate_zeros() output_array_stats(mtx.data, 'nonzeros in %s' % key) output('symmetry checks:') output('%s - %s^T:' % (key, key), max_diff_csr(mtx, mtx.T)) output('%s - %s^H:' % (key, key), max_diff_csr(mtx, mtx.H)) return pb, wdir, bzone, mtxs
def get_homog_coefs_linear(ts, coor, mode, micro_filename=None, regenerate=False, coefs_filename=None, define_args=None): oprefix = output.prefix output.prefix = 'micro:' required, other = get_standard_keywords() required.remove( 'equations' ) conf = ProblemConf.from_file(micro_filename, required, other, verbose=False, define_args=define_args) if coefs_filename is None: coefs_filename = conf.options.get('coefs_filename', 'coefs') coefs_filename = op.join(conf.options.get('output_dir', '.'), coefs_filename) + '.h5' if not regenerate: if op.exists( coefs_filename ): if not pt.is_hdf5_file( coefs_filename ): regenerate = True else: regenerate = True if regenerate: options = Struct( output_filename_trunk = None ) app = HomogenizationApp( conf, options, 'micro:' ) coefs = app() if type(coefs) is tuple: coefs = coefs[0] coefs.to_file_hdf5( coefs_filename ) else: coefs = Coefficients.from_file_hdf5( coefs_filename ) out = {} if mode == None: for key, val in six.iteritems(coefs.__dict__): out[key] = val elif mode == 'qp': for key, val in six.iteritems(coefs.__dict__): if type( val ) == nm.ndarray or type(val) == nm.float64: out[key] = nm.tile( val, (coor.shape[0], 1, 1) ) elif type(val) == dict: for key2, val2 in six.iteritems(val): if type(val2) == nm.ndarray or type(val2) == nm.float64: out[key+'_'+key2] = \ nm.tile(val2, (coor.shape[0], 1, 1)) else: out = None output.prefix = oprefix return out
def get_homog_coefs_nonlinear(ts, coor, mode, mtx_f=None, term=None, problem=None, iteration=None, **kwargs): if not (mode == 'qp'): return oprefix = output.prefix output.prefix = 'micro:' if not hasattr(problem, 'homogen_app'): required, other = get_standard_keywords() required.remove( 'equations' ) micro_file = problem.conf.options.micro_filename conf = ProblemConf.from_file(micro_file, required, other, verbose=False) options = Struct(output_filename_trunk = None) problem.homogen_app = HomogenizationApp(conf, options, 'micro:', n_micro=coor.shape[0], update_micro_coors=True) app = problem.homogen_app def_grad = mtx_f(problem, term) if callable(mtx_f) else mtx_f if hasattr(problem, 'def_grad_prev'): rel_def_grad = la.dot_sequences(def_grad, nm.linalg.inv(problem.def_grad_prev), 'AB') else: rel_def_grad = def_grad.copy() problem.def_grad_prev = def_grad.copy() app.setup_macro_deformation(rel_def_grad) coefs, deps = app(ret_all=True, itime=ts.step, iiter=iteration) if type(coefs) is tuple: coefs = coefs[0] out = {} for key, val in six.iteritems(coefs.__dict__): if isinstance(val, list): out[key] = nm.array(val) elif isinstance(val, dict): for key2, val2 in six.iteritems(val): out[key+'_'+key2] = nm.array(val2) for key in six.iterkeys(out): shape = out[key].shape if len(shape) == 1: out[key] = out[key].reshape(shape + (1, 1)) elif len(shape) == 2: out[key] = out[key].reshape(shape + (1,)) output.prefix = oprefix return out
def from_conf( conf, options, cls = None ): from sfepy.base.conf import ProblemConf, get_standard_keywords required, other = get_standard_keywords() test_conf = ProblemConf.from_file( conf.input_name, required, other ) if cls is None: cls = TestInput test = cls( test_conf = test_conf, conf = conf, options = options ) return test
def one_simulation(material_type, define_args, coef_tension=0.25, coef_compression=-0.25, plot_mesh_bool=False, return_load=False): #parser = ArgumentParser(description=__doc__, # formatter_class=RawDescriptionHelpFormatter) #parser.add_argument('--version', action='version', version='%(prog)s') #options = parser.parse_args() output.set_output(filename='sfepy_log.txt', quiet=True) required, other = get_standard_keywords() # Use this file as the input file. conf = ProblemConf.from_file(__file__, required, other, define_args=define_args) # Create problem instance, but do not set equations. problem = Problem.from_conf(conf, init_equations=False) if plot_mesh_bool: plot_mesh(problem) # Solve the problem. Output is ignored, results stored by using the # step_hook. linear_tension = partial(linear_pressure, coef=coef_tension) u_t = solve_branch(problem, linear_tension, material_type) linear_compression = partial(linear_pressure, coef=coef_compression) u_c = solve_branch(problem, linear_compression, material_type) # Get pressure load by calling linear_*() for each time step. ts = problem.get_timestepper() load_t = np.array([ linear_tension(ts, np.array([[0.0]]), 'qp')['val'] for aux in ts.iter_from(0) ], dtype=np.float64).squeeze() load_c = np.array([ linear_compression(ts, np.array([[0.0]]), 'qp')['val'] for aux in ts.iter_from(0) ], dtype=np.float64).squeeze() # Join the branches. displacements = np.r_[u_c[::-1], u_t] load = np.r_[load_c[::-1], load_t] if return_load: return displacements, load else: return displacements
def solve_pde(conf, options=None, status=None, **app_options): """ Solve a system of partial differential equations (PDEs). This function is a convenience wrapper that creates and runs an instance of :class:`PDESolverApp`. Parameters ---------- conf : str or ProblemConf instance Either the name of the problem description file defining the PDEs, or directly the ProblemConf instance. options : options The command-line options. status : dict-like The object for storing the solver return status. app_options : kwargs The keyword arguments that can override application-specific options. """ if not isinstance(conf, ProblemConf): required, other = get_standard_keywords() conf = ProblemConf.from_file(conf, required, other) opts = conf.options = (dict_to_struct(app_options, flag=(1,), constructor=type(conf.options)) + conf.options) output_prefix = opts.get('output_prefix', None) if output_prefix is None: output_prefix = output.prefix if options is None: options = Struct(output_filename_trunk=None, save_ebc=False, save_ebc_nodes=False, save_regions=False, save_field_meshes=False, save_regions_as_groups=False, solve_not=False) if conf.options.get('evps') is None: app = PDESolverApp(conf, options, output_prefix) else: from .evp_solver_app import EVPSolverApp app = EVPSolverApp(conf, options, output_prefix) if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) return app(status=status)
def solve_pde(conf, options=None, status=None, **app_options): """ Solve a system of partial differential equations (PDEs). This function is a convenience wrapper that creates and runs an instance of :class:`PDESolverApp`. Parameters ---------- conf : str or ProblemConf instance Either the name of the problem description file defining the PDEs, or directly the ProblemConf instance. options : options The command-line options. status : dict-like The object for storing the solver return status. app_options : kwargs The keyword arguments that can override application-specific options. """ if not isinstance(conf, ProblemConf): required, other = get_standard_keywords() conf = ProblemConf.from_file(conf, required, other) opts = conf.options = (dict_to_struct( app_options, flag=(1, ), constructor=type(conf.options)) + conf.options) output_prefix = opts.get('output_prefix', None) if output_prefix is None: output_prefix = output.prefix if options is None: options = Struct(output_filename_trunk=None, save_ebc=False, save_ebc_nodes=False, save_regions=False, save_field_meshes=False, save_regions_as_groups=False, solve_not=False) if conf.options.get('evps') is None: app = PDESolverApp(conf, options, output_prefix) else: from .evp_solver_app import EVPSolverApp app = EVPSolverApp(conf, options, output_prefix) if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) return app(status=status)
def main(): from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.fem import ProblemDefinition from sfepy.base.plotutils import pylab required, other = get_standard_keywords() # Use this file as the input file. conf = ProblemConf.from_file( __file__, required, other ) # Create problem instance, but do not set equations. problem = ProblemDefinition.from_conf( conf, init_equations = False ) options = Struct( output_filename_trunk = None ) # Solve the problem. Output is ignored, results stored by using the # step_hook. u_t = solve_branch( problem, options, linear_tension ) u_c = solve_branch( problem, options, linear_compression ) # Get pressure load by calling linear_*() for each time step. ts = problem.get_timestepper() load_t = nm.array( [linear_tension( ts, nm.array( [[0.0]] ) )['val'] for aux in ts.iter_from( 0 )], dtype = nm.float64 ).squeeze() load_c = nm.array( [linear_compression( ts, nm.array( [[0.0]] ) )['val'] for aux in ts.iter_from( 0 )], dtype = nm.float64 ).squeeze() # Join the branches. displacements = {} for key in u_t.keys(): displacements[key] = nm.r_[u_c[key][::-1], u_t[key]] load = nm.r_[load_c[::-1], load_t] if pylab is None: print 'pylab cannot be imported, printing raw data!' print displacements print load else: legend = [] for key, val in displacements.iteritems(): pylab.plot( load, val ) legend.append( key ) pylab.legend( legend, loc = 2 ) pylab.xlabel( 'tension [kPa]' ) pylab.ylabel( 'displacement [mm]' ) pylab.grid( True ) pylab.gcf().savefig( 'pressure_displacement.png' ) pylab.show()
def from_conf_file( conf_filename, required=None, other=None, init_fields=True, init_equations=True, init_solvers=True ): _required, _other = get_standard_keywords() if required is None: required = _required if other is None: other = _other conf = ProblemConf.from_file(conf_filename, required, other) obj = Problem.from_conf(conf, init_fields=init_fields, init_equations=init_equations, init_solvers=init_solvers) return obj
def main(): parser = ArgumentParser() parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument("-o", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=helps['filename']) parser.add_argument("-b", "--band-gaps", action="store_true", dest="detect_band_gaps", default=False, help=helps['detect_band_gaps']) parser.add_argument("-d", "--dispersion", action="store_true", dest="analyze_dispersion", default=False, help=helps['analyze_dispersion']) parser.add_argument("-p", "--plot", action="store_true", dest="plot", default=False, help=helps['plot']) parser.add_argument("--phase-velocity", action="store_true", dest="phase_velocity", default=False, help=helps['phase_velocity']) parser.add_argument("filename_in") options = parser.parse_args() if options.debug: from sfepy.base.base import debug_on_error; debug_on_error() if options.plot: if plt is None: output('matplotlib.pyplot cannot be imported, ignoring option -p!') options.plot = False elif options.analyze_dispersion == False: options.detect_band_gaps = True required, other = get_standard_keywords() required.remove('equations') if not options.analyze_dispersion: required.remove('solver_[0-9]+|solvers') if options.phase_velocity: required.remove('ebc_[0-9]+|ebcs') conf = ProblemConf.from_file(options.filename_in, required, other) app = AcousticBandGapsApp(conf, options, 'phonon:') opts = conf.options if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) app()
def from_conf_file(conf_filename, required=None, other=None, init_fields=True, init_equations=True, init_solvers=True): _required, _other = get_standard_keywords() if required is None: required = _required if other is None: other = _other conf = ProblemConf.from_file(conf_filename, required, other) obj = Problem.from_conf(conf, init_fields=init_fields, init_equations=init_equations, init_solvers=init_solvers) return obj
def __init__( self, dims, center_location, cell_sizes=np.array([2, 2]), prob_file="C:\\Users\\wbald\\sfepythings\\blocks\\fem\\prob_desc_2d.py", put_mesh="C:\\Users\\wbald\\sfepythings"): """ dims: array, dimensions of rectangle [x,y] center_location: array, centre of rectangle [x,y] cell sizes: array, x and y side length of FEM rectangular elements stretch: default distance by which to displace the upper y axis edge. prob_file: problem description file put_mesh: where to save the mesh file """ assert (dims.shape[0] == 2) assert (cell_sizes.shape[0] == 2) # assume linear elasticity. Fix strain of rectangle to 0.001 and query # at different strains by scaling linearly self.dims = dims self.prob_file = prob_file self.FEM_model_strain = 0.001 self.elongation = self.FEM_model_strain * self.dims[1] nums = np.divide(dims, cell_sizes) nums = np.around(nums).astype(int) + np.array([1, 1]) blockmesh = gen_block_mesh(dims, nums, center_location) blockmesh.write(put_mesh + '\\mesh.vtk') conf = ProblemConf.from_file(prob_file) # 'region_ylower__1' holds the edge to be fixed # 'region_yupper__2' holds the edge to be displaced conf.regions['region_ylower__1'].select = 'vertices in (y < ' + str( 0.01) + ')' conf.regions['region_yupper__2'].select = 'vertices in (y > ' + str( dims[1] - 0.01) + ')' conf.ebcs['ebc_Displaced__1'].dofs['u.1'] = self.elongation self.prob = Problem.from_conf(conf) # for reshaping sfepy output into xyz displacements self.reshape_tuple = ((self.prob.fields['displacement'].n_nod, self.prob.fields['displacement'].n_components))
def main(): parser = OptionParser(usage=usage, version="%prog " + sfepy.__version__) parser.add_option("-o", "", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=help['filename']) parser.add_option("-b", "--band-gaps", action="store_true", dest="detect_band_gaps", default=False, help=help['detect_band_gaps']) parser.add_option("-d", "--dispersion", action="store_true", dest="analyze_dispersion", default=False, help=help['analyze_dispersion']) parser.add_option("-p", "--plot", action="store_true", dest="plot", default=False, help=help['plot']) parser.add_option("--phase-velocity", action="store_true", dest="phase_velocity", default=False, help=help['phase_velocity']) options, args = parser.parse_args() if options.plot: if plt is None: output('matplotlib.pyplot cannot be imported, ignoring option -p!') options.plot = False elif options.analyze_dispersion == False: options.detect_band_gaps = True if (len(args) == 1): filename_in = args[0]; else: parser.print_help(), return required, other = get_standard_keywords() required.remove('equations') if not options.analyze_dispersion: required.remove('solver_[0-9]+|solvers') if options.phase_velocity: required.remove('ebc_[0-9]+|ebcs') conf = ProblemConf.from_file(filename_in, required, other) app = AcousticBandGapsApp(conf, options, 'phonon:') opts = conf.options if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) app()
def get_homog_coefs_linear( ts, coor, mode, region, ig, micro_filename = None, regenerate = False ): oprefix = output.prefix output.prefix = 'micro:' required, other = get_standard_keywords() required.remove( 'equations' ) conf = ProblemConf.from_file(micro_filename, required, other, verbose=False) coefs_filename = conf.options.get_default_attr('coefs_filename', 'coefs.h5') if not regenerate: if op.exists( coefs_filename ): if not pt.isHDF5File( coefs_filename ): regenerate = True else: regenerate = True if regenerate: options = Struct( output_filename_trunk = None ) app = HomogenizationApp( conf, options, 'micro:' ) coefs = app() coefs.to_file_hdf5( coefs_filename ) else: coefs = Coefficients.from_file_hdf5( coefs_filename ) out = {} if mode == None: for key, val in coefs.__dict__.iteritems(): out[key] = val elif mode == 'qp': for key, val in coefs.__dict__.iteritems(): if type( val ) == nm.ndarray: out[key] = nm.tile( val, (coor.shape[0], 1, 1) ) else: out = None output.prefix = oprefix return out
def eval_homogenized_coefs( self ): if self.cached_coefs is not None: return self.cached_coefs opts = self.app_options if opts.homogeneous: rtm = opts.region_to_material mat_region = rtm.keys()[0] mat_name = rtm[mat_region] self.problem.update_materials() mat = self.problem.materials[mat_name] coefs = mat.get_data( mat_region, 0, opts.tensor_names ) else: dc = opts.dispersion_conf dconf = ProblemConf.from_dict( dc['input'], dc['module'] ) dconf.materials = self.conf.materials dconf.fe = self.conf.fe dconf.regions.update( self.conf.regions ) dconf.options['output_dir'] = self.problem.output_dir volume = opts.volume(self.problem, 'Y') problem = ProblemDefinition.from_conf(dconf, init_equations=False) he = HomogenizationEngine( problem, self.options, volume = volume ) coefs = he() ## print coefs ## pause() output.prefix = self.output_prefix self.cached_coefs = coefs return coefs
def main(): parser = ArgumentParser() parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=help['debug']) parser.add_argument("-o", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=help['filename']) parser.add_argument('filename_in') options = parser.parse_args() if options.debug: from sfepy.base.base import debug_on_error debug_on_error() filename_in = options.filename_in required, other = get_standard_keywords() required.remove('equations') conf = ProblemConf.from_file(filename_in, required, other) app = HomogenizationApp(conf, options, 'homogen:') opts = conf.options if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) app()
def main(): import os from sfepy.base.base import spause, output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.fem import ProblemDefinition import sfepy.homogenization.coefs_base as cb parser = OptionParser(usage=usage, version='%prog') parser.add_option('-n', '--no-pauses', action="store_true", dest='no_pauses', default=False, help=help['no_pauses']) options, args = parser.parse_args() if options.no_pauses: def spause(*args): output(*args) nm.set_printoptions( precision = 3 ) spause( r""">>> First, this file will be read in place of an input (problem description) file. Press 'q' to quit the example, press any other key to continue...""" ) required, other = get_standard_keywords() required.remove( 'equations' ) # Use this file as the input file. conf = ProblemConf.from_file( __file__, required, other ) print conf.to_dict().keys() spause( r""">>> ...the read input as a dict (keys only for brevity). ['q'/other key to quit/continue...]""" ) spause( r""">>> Now the input will be used to create a ProblemDefinition instance. ['q'/other key to quit/continue...]""" ) problem = ProblemDefinition.from_conf(conf, init_equations=False) # The homogenization mini-apps need the output_dir. output_dir = os.path.join(os.path.split(__file__)[0], 'output') if not os.path.exists(output_dir): os.makedirs(output_dir) problem.output_dir = output_dir print problem spause( r""">>> ...the ProblemDefinition instance. ['q'/other key to quit/continue...]""" ) spause( r""">>> The homogenized elastic coefficient $E_{ijkl}$ is expressed using $\Pi$ operators, computed now. In fact, those operators are permuted coordinates of the mesh nodes. ['q'/other key to quit/continue...]""" ) req = conf.requirements['pis'] mini_app = cb.ShapeDimDim( 'pis', problem, req ) pis = mini_app() print pis spause( r""">>> ...the $\Pi$ operators. ['q'/other key to quit/continue...]""" ) spause( r""">>> Next, $E_{ijkl}$ needs so called steady state correctors $\bar{\omega}^{rs}$, computed now. ['q'/other key to quit/continue...]""" ) req = conf.requirements['corrs_rs'] save_name = req.get( 'save_name', '' ) name = os.path.join( output_dir, save_name ) mini_app = cb.CorrDimDim('steady rs correctors', problem, req) mini_app.setup_output(save_format='vtk', file_per_var=False) corrs_rs = mini_app( data = {'pis': pis} ) print corrs_rs spause( r""">>> ...the $\bar{\omega}^{rs}$ correctors. The results are saved in: %s.%s Try to display them with: python postproc.py %s.%s ['q'/other key to quit/continue...]""" % (2 * (name, problem.output_format)) ) spause( r""">>> Then the volume of the domain is needed. ['q'/other key to quit/continue...]""" ) volume = problem.evaluate('d_volume.i3.Y( uc )') print volume spause( r""">>> ...the volume. ['q'/other key to quit/continue...]""" ) spause( r""">>> Finally, $E_{ijkl}$ can be computed. ['q'/other key to quit/continue...]""" ) mini_app = cb.CoefSymSym('homogenized elastic tensor', problem, conf.coefs['E']) c_e = mini_app(volume, data={'pis': pis, 'corrs_rs' : corrs_rs}) print r""">>> The homogenized elastic coefficient $E_{ijkl}$, symmetric storage with rows, columns in 11, 22, 12 ordering:""" print c_e
def main(): parser = OptionParser(usage=usage, version="%prog " + sfepy.__version__) parser.add_option("-o", "", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=help['filename']) parser.add_option("-b", "--band-gaps", action="store_true", dest="detect_band_gaps", default=False, help=help['detect_band_gaps']) parser.add_option("-d", "--dispersion", action="store_true", dest="analyze_dispersion", default=False, help=help['analyze_dispersion']) parser.add_option("-p", "--plot", action="store_true", dest="plot", default=False, help=help['plot']) parser.add_option("--phase-velocity", action="store_true", dest="phase_velocity", default=False, help=help['phase_velocity']) options, args = parser.parse_args() if options.plot: if plt is None: output('matplotlib.pyplot cannot be imported, ignoring option -p!') options.plot = False elif options.analyze_dispersion == False: options.detect_band_gaps = True if (len(args) == 1): filename_in = args[0] else: parser.print_help(), return required, other = get_standard_keywords() required.remove('equations') if not options.analyze_dispersion: required.remove('solver_[0-9]+|solvers') if options.phase_velocity: required.remove('ebc_[0-9]+|ebcs') conf = ProblemConf.from_file(filename_in, required, other) app = AcousticBandGapsApp(conf, options, 'phonon:') opts = conf.options if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) app()
def test_solution(self): from sfepy.base.base import Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.homogen_app import HomogenizationApp #import numpy as nm import os.path as op ok = True required, other = get_standard_keywords() required.remove('equations') print(input_name) full_name = op.join(op.dirname(__file__), input_name) test_conf = ProblemConf.from_file(full_name, required, other) options = Struct(output_filename_trunk=None, save_ebc=False, save_ebc_nodes=False, save_regions=False, save_field_meshes=False, save_regions_as_groups=False, solve_not=False) test_conf.options['output_dir'] = './output-tests' app = HomogenizationApp(test_conf, options, 'homogen:' ) coefs = app() aerr = 1.0e-9 self.report('allowed error: abs = %e' % (aerr, )) # G^A = G^B ? ok = ok and self.compare_scalars(coefs.GA, coefs.GB,\ 'G^A', 'G^B', aerr) # F^{A+} + F^{B+} = -1/h \int_{\partial_+Y_m} ? aux = 1.0 / test_conf.param_h * coefs.volume['bYMp'] ok = ok and self.compare_scalars(coefs.FpA + coefs.FpB, -aux, 'F^{A+} + F^{B+}', '-bYM^+', aerr) # F^{A-} + F^{B-} = -1/h \int_{\partial_-Y_m} ? aux = 1.0 / test_conf.param_h * coefs.volume['bYMm'] ok = ok and self.compare_scalars(coefs.FmA + coefs.FmB, -aux, 'F^{A-} + F^{B-}', '-bYM^-', aerr) # symmetry of H ? ok = ok and self.compare_scalars(coefs.Hpm, coefs.Hmp, 'H^{+-}', 'H^{-+}', aerr) # E = -F ? ok = ok and self.compare_scalars(coefs.EmA, -coefs.FmA, 'E^{A-}', '-F^{A-}',aerr) ok = ok and self.compare_scalars(coefs.EpA, -coefs.FpA, 'E^{A+}', '-F^{A+}',aerr) ok = ok and self.compare_scalars(coefs.EmB, -coefs.FmB, 'E^{B-}', '-F^{B-}',aerr) ok = ok and self.compare_scalars(coefs.EpB, -coefs.FpB, 'E^{B+}', '-F^{B+}',aerr) # S = S_test ? coefsd = coefs.to_dict() compare = [] for ii in six.iterkeys(coefsd): if 'S_test' in ii: ch = ii[6] io = ii[-1] compare.append((ii, 'S%s_%s' % (ch, io))) for s1, s2 in compare: ok = ok and self.compare_vectors(coefsd[s1], -coefsd[s2], label1='S_test', label2='S', allowed_error=aerr) return ok
def __call__(self): return ProblemConf.from_dict(self.conf.__dict__, import_file(__file__))
def get_homog_coefs_nonlinear(ts, coor, mode, mtx_f=None, term=None, problem=None, iteration=None, **kwargs): if not (mode == 'qp'): return oprefix = output.prefix output.prefix = 'micro:' if not hasattr(problem, 'homogen_app'): required, other = get_standard_keywords() required.remove('equations') micro_file = problem.conf.options.micro_filename conf = ProblemConf.from_file(micro_file, required, other, verbose=False) options = Struct(output_filename_trunk=None) app = HomogenizationApp(conf, options, 'micro:', n_micro=coor.shape[0], update_micro_coors=True) problem.homogen_app = app if hasattr(app.app_options, 'use_mpi') and app.app_options.use_mpi: multiproc, multiproc_mode = multi.get_multiproc(mpi=True) multi_mpi = multiproc if multiproc_mode == 'mpi' else None else: multi_mpi = None app.multi_mpi = multi_mpi if multi_mpi is not None: multi_mpi.master_send_task('init', (micro_file, coor.shape[0])) else: app = problem.homogen_app multi_mpi = app.multi_mpi def_grad = mtx_f(problem, term) if callable(mtx_f) else mtx_f if hasattr(problem, 'def_grad_prev'): rel_def_grad = la.dot_sequences(def_grad, nm.linalg.inv(problem.def_grad_prev), 'AB') else: rel_def_grad = def_grad.copy() problem.def_grad_prev = def_grad.copy() app.setup_macro_deformation(rel_def_grad) if multi_mpi is not None: multi_mpi.master_send_task('calculate', (rel_def_grad, ts, iteration)) coefs, deps = app(ret_all=True, itime=ts.step, iiter=iteration) if type(coefs) is tuple: coefs = coefs[0] out = {} for key, val in six.iteritems(coefs.__dict__): if isinstance(val, list): out[key] = nm.array(val) elif isinstance(val, dict): for key2, val2 in six.iteritems(val): out[key+'_'+key2] = nm.array(val2) for key in six.iterkeys(out): shape = out[key].shape if len(shape) == 1: out[key] = out[key].reshape(shape + (1, 1)) elif len(shape) == 2: out[key] = out[key].reshape(shape + (1,)) output.prefix = oprefix return out
def recover_micro_hook_eps(micro_filename, region, eval_var, nodal_values, const_values, eps0, recovery_file_tag='', define_args=None, verbose=False): # Create a micro-problem instance. required, other = get_standard_keywords() required.remove('equations') conf = ProblemConf.from_file(micro_filename, required, other, verbose=False, define_args=define_args) coefs_filename = conf.options.get('coefs_filename', 'coefs') output_dir = conf.options.get('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 = conf.options.get('recovery_hook', None) if recovery_hook is not None: recovery_hook = conf.get_function(recovery_hook) pb = Problem.from_conf(conf, init_equations=False, init_solvers=False) # Get tiling of a given region rcoors = region.domain.mesh.coors[region.get_entities(0), :] rcmin = nm.min(rcoors, axis=0) rcmax = nm.max(rcoors, axis=0) nn = nm.round((rcmax - rcmin) / eps0) if nm.prod(nn) == 0: output('inconsistency in recovery region and microstructure size!') return cs = [] for ii, n in enumerate(nn): cs.append(nm.arange(n) * eps0 + rcmin[ii]) x0 = nm.empty((int(nm.prod(nn)), nn.shape[0]), dtype=nm.float64) for ii, icoor in enumerate(nm.meshgrid(*cs, indexing='ij')): x0[:, ii] = icoor.flatten() mesh = pb.domain.mesh coors, conn, outs, ndoffset = [], [], [], 0 # Recover region mic_coors = (mesh.coors - mesh.get_bounding_box()[0, :]) * eps0 evfield = eval_var.field output('recovering microsctructures...') tt = time.clock() output_fun = output.output_function output_level = output.level for ii, c0 in enumerate(x0): local_macro = {'eps0': eps0} local_coors = mic_coors + c0 # Inside recovery region? v = nm.ones((evfield.region.entities[0].shape[0], 1)) v[evfield.vertex_remap[region.entities[0]]] = 0 no = nm.sum(v) aux = evfield.evaluate_at(local_coors, v) if (nm.sum(aux) / no) > 1e-3: continue output.level = output_level output('micro: %d' % ii) for k, v in six.iteritems(nodal_values): local_macro[k] = evfield.evaluate_at(local_coors, v) for k, v in six.iteritems(const_values): local_macro[k] = v output.set_output(quiet=not(verbose)) outs.append(recovery_hook(pb, corrs, local_macro)) output.output_function = output_fun coors.append(local_coors) conn.append(mesh.get_conn(mesh.descs[0]) + ndoffset) ndoffset += mesh.n_nod output('...done in %.2f s' % (time.clock() - tt)) # Collect output variables outvars = {} for k, v in six.iteritems(outs[0]): if v.var_name in outvars: outvars[v.var_name].append(k) else: outvars[v.var_name] = [k] # Split output by variables/regions pvs = pb.create_variables(outvars.keys()) outregs = {k: pvs[k].field.region.get_entities(-1) for k in outvars.keys()} nrve = len(coors) coors = nm.vstack(coors) ngroups = nm.tile(mesh.cmesh.vertex_groups.squeeze(), (nrve,)) conn = nm.vstack(conn) cgroups = nm.tile(mesh.cmesh.cell_groups.squeeze(), (nrve,)) # Get region mesh and data for k, cidxs in six.iteritems(outregs): gcidxs = nm.hstack([cidxs + mesh.n_el * ii for ii in range(nrve)]) rconn = conn[gcidxs] remap = -nm.ones((coors.shape[0],), dtype=nm.int32) remap[rconn] = 1 vidxs = nm.where(remap > 0)[0] remap[vidxs] = nm.arange(len(vidxs)) rconn = remap[rconn] rcoors = coors[vidxs, :] out = {} for ifield in outvars[k]: data = [outs[ii][ifield].data for ii in range(nrve)] out[ifield] = Struct(name='output_data', mode=outs[0][ifield].mode, dofs=None, var_name=k, data=nm.vstack(data)) micro_name = pb.get_output_name(extra='recovered%s_%s' % (recovery_file_tag, k)) filename = op.join(output_dir, op.basename(micro_name)) mesh_out = Mesh.from_data('recovery_%s' % k, rcoors, ngroups[vidxs], [rconn], [cgroups[gcidxs]], [mesh.descs[0]]) mesh_out.write(filename, io='auto', out=out)
def main(): # Aluminium and epoxy. default_pars = '70e9,0.35,2.799e3, 3.8e9,0.27,1.142e3' default_solver_conf = ("kind='eig.scipy',method='eigh',tol=1.0e-5," "maxiter=1000,which='LM',sigma=0.0") parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--pars', metavar='young1,poisson1,density1' ',young2,poisson2,density2', action='store', dest='pars', default=default_pars, help=helps['pars']) parser.add_argument('--conf', metavar='filename', action='store', dest='conf', default=None, help=helps['conf']) parser.add_argument('--mesh-size', type=float, metavar='float', action='store', dest='mesh_size', default=None, help=helps['mesh_size']) parser.add_argument('--unit-multipliers', metavar='c_time,c_length,c_mass', action='store', dest='unit_multipliers', default='1.0,1.0,1.0', help=helps['unit_multipliers']) parser.add_argument('--plane', action='store', dest='plane', choices=['strain', 'stress'], default='strain', help=helps['plane']) parser.add_argument('--wave-dir', metavar='float,float[,float]', action='store', dest='wave_dir', default='1.0,0.0,0.0', help=helps['wave_dir']) parser.add_argument('--mode', action='store', dest='mode', choices=['omega', 'kappa'], default='omega', help=helps['mode']) parser.add_argument('--range', metavar='start,stop,count', action='store', dest='range', default='10,100,10', help=helps['range']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-n', '--n-eigs', metavar='int', type=int, action='store', dest='n_eigs', default=6, help=helps['n_eigs']) parser.add_argument('--eigs-only', action='store_true', dest='eigs_only', default=False, help=helps['eigs_only']) parser.add_argument('--solver-conf', metavar='dict-like', action='store', dest='solver_conf', default=default_solver_conf, help=helps['solver_conf']) parser.add_argument('--save-materials', action='store_true', dest='save_materials', default=False, help=helps['save_materials']) parser.add_argument('--log-std-waves', action='store_true', dest='log_std_waves', default=False, help=helps['log_std_waves']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('-c', '--clear', action='store_true', dest='clear', default=False, help=helps['clear']) parser.add_argument('-o', '--output-dir', metavar='path', action='store', dest='output_dir', default='output', help=helps['output_dir']) parser.add_argument('mesh_filename', default='', help=helps['mesh_filename']) options = parser.parse_args() output_dir = options.output_dir output.set_output(filename=os.path.join(output_dir, 'output_log.txt'), combined=options.silent == False) if options.conf is not None: mod = import_file(options.conf) apply_units = mod.apply_units define = mod.define set_wave_dir = mod.set_wave_dir else: apply_units = apply_units_le define = define_le set_wave_dir = set_wave_dir_le options.pars = [float(ii) for ii in options.pars.split(',')] options.unit_multipliers = [ float(ii) for ii in options.unit_multipliers.split(',') ] options.wave_dir = [float(ii) for ii in options.wave_dir.split(',')] aux = options.range.split(',') options.range = [float(aux[0]), float(aux[1]), int(aux[2])] options.solver_conf = dict_from_string(options.solver_conf) if options.clear: remove_files_patterns(output_dir, ['*.h5', '*.vtk', '*.txt'], ignores=['output_log.txt'], verbose=True) filename = os.path.join(output_dir, 'options.txt') ensure_path(filename) save_options(filename, [('options', vars(options))]) pars = apply_units(options.pars, options.unit_multipliers) output('material parameters with applied unit multipliers:') output(pars) if options.mode == 'omega': rng = copy(options.range) rng[:2] = apply_unit_multipliers(options.range[:2], ['wave_number', 'wave_number'], options.unit_multipliers) output('wave number range with applied unit multipliers:', rng) else: rng = copy(options.range) rng[:2] = apply_unit_multipliers(options.range[:2], ['frequency', 'frequency'], options.unit_multipliers) output('frequency range with applied unit multipliers:', rng) define_problem = functools.partial(define, filename_mesh=options.mesh_filename, pars=pars, approx_order=options.order, refinement_level=options.refine, solver_conf=options.solver_conf, plane=options.plane) conf = ProblemConf.from_dict(define_problem(), sys.modules[__name__]) pb = Problem.from_conf(conf) dim = pb.domain.shape.dim if dim != 2: options.plane = 'strain' wdir = nm.asarray(options.wave_dir[:dim], dtype=nm.float64) wdir = wdir / nm.linalg.norm(wdir) stepper = TimeStepper(rng[0], rng[1], dt=None, n_step=rng[2]) bbox = pb.domain.mesh.get_bounding_box() size = (bbox[1] - bbox[0]).max() scaling0 = apply_unit_multipliers([1.0], ['length'], options.unit_multipliers)[0] scaling = scaling0 if options.mesh_size is not None: scaling *= options.mesh_size / size output('scaling factor of periodic cell mesh coordinates:', scaling) output('new mesh size with applied unit multipliers:', scaling * size) pb.domain.mesh.coors[:] *= scaling pb.set_mesh_coors(pb.domain.mesh.coors, update_fields=True) bzone = 2.0 * nm.pi / (scaling * size) output('1. Brillouin zone size:', bzone * scaling0) output('1. Brillouin zone size with applied unit multipliers:', bzone) pb.time_update() pb.update_materials() if options.save_materials or options.log_std_waves: stiffness = pb.evaluate('ev_integrate_mat.2.Omega(m.D, u)', mode='el_avg', copy_materials=False, verbose=False) young, poisson = mc.youngpoisson_from_stiffness(stiffness, plane=options.plane) density = pb.evaluate('ev_integrate_mat.2.Omega(m.density, u)', mode='el_avg', copy_materials=False, verbose=False) if options.save_materials: out = {} out['young'] = Struct(name='young', mode='cell', data=young[..., None, None]) out['poisson'] = Struct(name='poisson', mode='cell', data=poisson[..., None, None]) out['density'] = Struct(name='density', mode='cell', data=density) materials_filename = os.path.join(output_dir, 'materials.vtk') pb.save_state(materials_filename, out=out) # Set the normalized wave vector direction to the material(s). set_wave_dir(pb.get_materials(), wdir) conf = pb.solver_confs['eig'] eig_solver = Solver.any_from_conf(conf) # Assemble the matrices. mtx_m = pb.mtx_a.copy() eq_m = pb.equations['M'] mtx_m = eq_m.evaluate(mode='weak', dw_mode='matrix', asm_obj=mtx_m) mtx_m.eliminate_zeros() mtx_k = pb.mtx_a.copy() eq_k = pb.equations['K'] mtx_k = eq_k.evaluate(mode='weak', dw_mode='matrix', asm_obj=mtx_k) mtx_k.eliminate_zeros() mtx_s = pb.mtx_a.copy() eq_s = pb.equations['S'] mtx_s = eq_s.evaluate(mode='weak', dw_mode='matrix', asm_obj=mtx_s) mtx_s.eliminate_zeros() mtx_r = pb.mtx_a.copy() eq_r = pb.equations['R'] mtx_r = eq_r.evaluate(mode='weak', dw_mode='matrix', asm_obj=mtx_r) mtx_r.eliminate_zeros() output('symmetry checks of real blocks:') output('M - M^T:', _max_diff_csr(mtx_m, mtx_m.T)) output('K - K^T:', _max_diff_csr(mtx_k, mtx_k.T)) output('S - S^T:', _max_diff_csr(mtx_s, mtx_s.T)) output('R + R^T:', _max_diff_csr(mtx_r, -mtx_r.T)) n_eigs = options.n_eigs if options.n_eigs > mtx_k.shape[0]: options.n_eigs = mtx_k.shape[0] n_eigs = None if options.mode == 'omega': eigenshapes_filename = os.path.join( output_dir, 'frequency-eigenshapes-%s.vtk' % stepper.suffix) extra = [] extra_plot_kwargs = [] if options.log_std_waves: lam, mu = mc.lame_from_youngpoisson(young, poisson, plane=options.plane) alam = nm.average(lam) amu = nm.average(mu) adensity = nm.average(density) cp = nm.sqrt((alam + 2.0 * amu) / adensity) cs = nm.sqrt(amu / adensity) output('average p-wave speed:', cp) output('average shear wave speed:', cs) extra = [r'$\omega_p$', r'$\omega_s$'] extra_plot_kwargs = [{ 'ls': '--', 'color': 'k' }, { 'ls': '--', 'color': 'gray' }] log = Log( [[r'$\lambda_{%d}$' % ii for ii in range(options.n_eigs)], [r'$\omega_{%d}$' % ii for ii in range(options.n_eigs)] + extra], plot_kwargs=[{}, [{}] * options.n_eigs + extra_plot_kwargs], yscales=['linear', 'linear'], xlabels=[r'$\kappa$', r'$\kappa$'], ylabels=[r'eigenvalues $\lambda_i$', r'frequencies $\omega_i$'], log_filename=os.path.join(output_dir, 'frequencies.txt'), aggregate=1000, sleep=0.1) for iv, wmag in stepper: output('step %d: wave vector %s' % (iv, wmag * wdir)) mtx_a = mtx_k + wmag**2 * mtx_s + (1j * wmag) * mtx_r mtx_b = mtx_m output('A - A^H:', _max_diff_csr(mtx_a, mtx_a.H)) if options.eigs_only: eigs = eig_solver(mtx_a, mtx_b, n_eigs=n_eigs, eigenvectors=False) svecs = None else: eigs, svecs = eig_solver(mtx_a, mtx_b, n_eigs=options.n_eigs, eigenvectors=True) omegas = nm.sqrt(eigs) output('eigs, omegas:\n', nm.c_[eigs, omegas]) out = tuple(eigs) + tuple(omegas) if options.log_std_waves: out = out + (cp * wmag, cs * wmag) log(*out, x=[wmag, wmag]) save_eigenvectors(eigenshapes_filename % iv, svecs, pb) log(save_figure=os.path.join(output_dir, 'frequencies.png')) log(finished=True) else: import scipy.sparse as sps from sksparse.cholmod import cholesky eigenshapes_filename = os.path.join( output_dir, 'wave-number-eigenshapes-%s.vtk' % stepper.suffix) factor = cholesky(mtx_s) perm = factor.P() ir = nm.arange(len(perm)) mtx_p = sps.coo_matrix((nm.ones_like(perm), (ir, perm))) mtx_l = mtx_p.T * factor.L() mtx_eye = sps.eye(mtx_l.shape[0], dtype=nm.float64) output('S - LL^T:', _max_diff_csr(mtx_s, mtx_l * mtx_l.T)) log = Log([[r'$\kappa_{%d}$' % ii for ii in range(options.n_eigs)]], plot_kwargs=[{ 'ls': 'None', 'marker': 'o' }], yscales=['linear'], xlabels=[r'$\omega$'], ylabels=[r'wave numbers $\kappa_i$'], log_filename=os.path.join(output_dir, 'wave-numbers.txt'), aggregate=1000, sleep=0.1) for io, omega in stepper: output('step %d: frequency %s' % (io, omega)) mtx_a = sps.bmat([[mtx_k - omega**2 * mtx_m, None], [None, mtx_eye]]) mtx_b = sps.bmat([[1j * mtx_r, mtx_l], [mtx_l.T, None]]) output('A - A^T:', _max_diff_csr(mtx_a, mtx_a.T)) output('A - A^H:', _max_diff_csr(mtx_a, mtx_a.T)) output('B - B^H:', _max_diff_csr(mtx_b, mtx_b.H)) if options.eigs_only: eigs = eig_solver(mtx_a, mtx_b, n_eigs=n_eigs, eigenvectors=False) svecs = None else: eigs, svecs = eig_solver(mtx_a, mtx_b, n_eigs=options.n_eigs, eigenvectors=True) kappas = eigs output('kappas:\n', kappas[:, None]) out = tuple(kappas) log(*out, x=[omega]) save_eigenvectors(eigenshapes_filename % io, svecs, pb) log(save_figure=os.path.join(output_dir, 'wave-numbers.png')) log(finished=True)
quadratic=False, tetgenpath=tetgen_path) m = Mesh.from_file("tmp/t.1.node") m.write(mesh_filename, io="auto") output("...mesh written to %s" % mesh_filename) return else: parser.print_help() return else: parser.print_help() return required, other = get_standard_keywords() conf = ProblemConf.from_file_and_options(filename_in, options, required, other) if options.mesh: from sfepy.fem.mesh_generators import gen_mesh_from_string conf.filename_mesh = gen_mesh_from_string(options.mesh, options.mesh_dir) elif auto_mesh_name and not sfepy.in_source_tree: conf.filename_mesh = mesh_filename conf.options.absolute_mesh_path = True app = SchroedingerApp(conf, options, 'schroedinger:') opts = conf.options if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook)
def main(): parser = OptionParser(usage=usage, version='%prog') parser.add_option('-c', '--counts', action='store_true', dest='counts', default=False, help=helps['counts']) parser.add_option('-u', '--unused', action='store_true', dest='unused', default=False, help=helps['unused']) options, args = parser.parse_args() if len(args) > 0: pdf_dir = os.path.realpath(args[0]) else: parser.print_help(), return required, other = get_standard_keywords() terms_use = dict_from_keys_init(term_table.keys(), set) for filename in locate_files('*.py', pdf_dir): base = filename.replace(pdf_dir, '').lstrip(os.path.sep) output('trying "%s"...' % base) try: conf = ProblemConf.from_file(filename, required, other, verbose=False) except: output('...failed') continue use = conf.options.get('use_equations', 'equations') eqs_conf = getattr(conf, use) for key, eq_conf in eqs_conf.iteritems(): term_descs = parse_definition(eq_conf) for td in term_descs: terms_use[td.name].add(base) output('...ok') output('...done') if options.unused: output('unused terms:') unused = [ name for name in terms_use.keys() if len(terms_use[name]) == 0 ] for name in sorted(unused): output(' ' + name) output('total: %d' % len(unused)) else: output('terms use:') for name, ex_names in ordered_iteritems(terms_use): output('%s: %d' % (name, len(ex_names))) if not options.counts: for ex_name in sorted(ex_names): output(' ' + ex_name)
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 = opts.get_('output_dir', '.') filename_results = os.path.join(output_dir, filename_results) output('results in: %s' % filename_results) io = MeshIO.any_from_filename(filename_results) step = options.step if options.step >= 0 else io.read_last_step() all_data = io.read_data(step) output('loaded:', list(all_data.keys())) output('from step:', step) if options.only_names is None: data = all_data else: data = {} for key, val in six.iteritems(all_data): if key in options.only_names: data[key] = val if problem is None: problem = Problem.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 six.iteritems(probe_hooks): 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 six.iteritems(fig): 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') write_results(txt_filename, probe, results) output('data ->', os.path.normpath(txt_filename))
def main(): parser = ArgumentParser() parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=help['debug']) parser.add_argument("-s", "--server", action="store_true", dest="server_mode", default=False, help=help['server_mode']) parser.add_argument("-a", "--adjoint", action="store_true", dest="adjoint", default=False, help=help['adjoint']) parser.add_argument("-d", "--direct", action="store_true", dest="direct", default=False, help=help['direct']) parser.add_argument("-t", "--test", type=int, metavar='idsg', action="store", dest="test", default=None, help=help['test']) parser.add_argument("--dump", metavar='filename', action="store", dest="dump_filename", default=None, help=help['dump']) parser.add_argument("--pert-mesh", metavar='filename', action="store", dest="pert_mesh_filename", default=None, help=help['pert']) parser.add_argument("-f", "--full", action="store_true", dest="optimize", default=False, help=help['optimize']) parser.add_argument('filename_in') options = parser.parse_args() if options.debug: from sfepy.base.base import debug_on_error debug_on_error() if options.test is not None: options.adjoint = options.direct = True if options.optimize: options.adjoint = options.direct = False if (options.direct or options.adjoint or options.optimize): filename_in = options.filename_in else: parser.print_help(), return required, other = get_standard_keywords() required.remove('equations') if options.adjoint: required += [ 'equations_adjoint_.*', 'filename_vp', 'equations_direct_.*' ] options.direct = True elif options.direct: required += ['equations_direct_.*'] elif options.optimize: required += [ 'equations_direct_.*', 'equations_adjoint_.*', 'equations_sensitivity_.*', 'filename_vp' ] conf = ProblemConf.from_file(filename_in, required, other) if options.direct: dpb, state_dp, data = solve_direct(conf, options) else: dpb, state_dp, data = None, None, None if options.adjoint: solve_adjoint(conf, options, dpb, state_dp, data) if options.optimize: solve_optimize(conf, options)
def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s ' + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument('-c', '--conf', metavar='"key : value, ..."', action='store', dest='conf', type=str, default=None, help= helps['conf']) parser.add_argument('-O', '--options', metavar='"key : value, ..."', action='store', dest='app_options', type=str, default=None, help=helps['options']) parser.add_argument('-o', metavar='filename', action='store', dest='output_filename_trunk', default=None, help=helps['filename']) group = parser.add_mutually_exclusive_group() group.add_argument('--oscillator', action='store_true', dest='oscillator', default=False, help=helps['oscillator']) group.add_argument('--well', action='store_true', dest='well', default=False, help=helps['well']) group.add_argument('--hydrogen', action='store_true', dest='hydrogen', default=False, help=helps['hydrogen']) group.add_argument('--boron', action='store_true', dest='boron', default=False, help=helps['boron']) parser.add_argument('-n', '--n-eigs', type=int, metavar='int', action='store', dest='n_eigs', default=None, help=helps['n_eigs']) parser.add_argument('-t', '--tau', type=float, metavar='float', action='store', dest='tau', default=None, help=helps['tau']) parser.add_argument('filename_in', nargs='?') options = parser.parse_args() if options.debug: from sfepy.base.base import debug_on_error; debug_on_error() filename_in = options.filename_in if not filename_in: if options.oscillator: filename_in = fix_path("examples/quantum/oscillator.py") elif options.well: filename_in = fix_path("examples/quantum/well.py") elif options.hydrogen: filename_in = fix_path("examples/quantum/hydrogen.py") elif options.boron: filename_in = fix_path("examples/quantum/boron.py") else: parser.print_help() return define_args = {} if options.n_eigs is not None: define_args['n_eigs'] = options.n_eigs if options.tau is not None: define_args['tau'] = options.tau required, other = get_standard_keywords() conf = ProblemConf.from_file_and_options(filename_in, options, required, other, define_args=define_args) app = SchroedingerApp(conf, options, 'schroedinger:') opts = conf.options if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) app()
def main(): parser = OptionParser(usage=usage, version="%prog " + sfepy.__version__) parser.add_option("-s", "--server", action="store_true", dest="server_mode", default=False, help=help['server_mode']) parser.add_option("-a", "--adjoint", action="store_true", dest="adjoint", default=False, help=help['adjoint']) parser.add_option("-d", "--direct", action="store_true", dest="direct", default=False, help=help['direct']) parser.add_option("-t", "--test", type=int, metavar='idsg', action="store", dest="test", default=None, help=help['test']) parser.add_option("", "--dump", metavar='filename', action="store", dest="dump_filename", default=None, help=help['dump']) parser.add_option("", "--pert-mesh", metavar='filename', action="store", dest="pert_mesh_filename", default=None, help=help['pert']) parser.add_option("-f", "--full", action="store_true", dest="optimize", default=False, help=help['optimize']) options, args = parser.parse_args() if options.test is not None: options.adjoint = options.direct = True if options.optimize: options.adjoint = options.direct = False if ((len(args) == 1) and (options.direct or options.adjoint or options.optimize)): filename_in = args[0] else: parser.print_help(), return required, other = get_standard_keywords() required.remove('equations') if options.adjoint: required += [ 'equations_adjoint_.*', 'filename_vp', 'equations_direct_.*' ] options.direct = True elif options.direct: required += ['equations_direct_.*'] elif options.optimize: required += [ 'equations_direct_.*', 'equations_adjoint_.*', 'equations_sensitivity_.*', 'filename_vp' ] conf = ProblemConf.from_file(filename_in, required, other) if options.direct: dpb, state_dp, data = solve_direct(conf, options) else: dpb, state_dp, data = None, None, None if options.adjoint: solve_adjoint(conf, options, dpb, state_dp, data) if options.optimize: solve_optimize(conf, options)
def __init__(self, conf, problem, **kwargs): from sfepy.discrete.state import State from sfepy.discrete import Problem from sfepy.base.conf import ProblemConf, get_standard_keywords from scipy.spatial import cKDTree as KDTree ScipyDirect.__init__(self, conf, **kwargs) # init subproblems pb_vars = problem.get_variables() # get "master" DofInfo and last index pb_adi_indx = problem.equations.variables.adi.indx self.adi_indx = pb_adi_indx.copy() last_indx = -1 for ii in self.adi_indx.itervalues(): last_indx = nm.max([last_indx, ii.stop]) # coupling variables self.cvars_to_pb = {} for jj in conf.coupling_variables: self.cvars_to_pb[jj] = [None, None] if jj in pb_vars.names: if pb_vars[jj].dual_var_name is not None: self.cvars_to_pb[jj][0] = -1 else: self.cvars_to_pb[jj][1] = -1 # init subproblems self.subpb = [] required, other = get_standard_keywords() master_prefix = output.get_output_prefix() for ii, ifname in enumerate(conf.others): sub_prefix = master_prefix[:-1] + '-sub%d:' % (ii + 1) output.set_output_prefix(sub_prefix) kwargs['master_problem'] = problem confi = ProblemConf.from_file(ifname, required, other, define_args=kwargs) pbi = Problem.from_conf(confi, init_equations=True) sti = State(pbi.equations.variables) pbi.equations.set_data(None, ignore_unknown=True) pbi.time_update() pbi.update_materials() sti.apply_ebc() pbi_vars = pbi.get_variables() output.set_output_prefix(master_prefix) self.subpb.append([pbi, sti, None]) # append "slave" DofInfo for jj in pbi_vars.names: if not(pbi_vars[jj].is_state()): continue didx = pbi.equations.variables.adi.indx[jj] ndof = didx.stop - didx.start if jj in self.adi_indx: if ndof != \ (self.adi_indx[jj].stop - self.adi_indx[jj].start): raise ValueError('DOFs do not match!') else: self.adi_indx.update({ jj: slice(last_indx, last_indx + ndof, None)}) last_indx += ndof for jj in conf.coupling_variables: if jj in pbi_vars.names: if pbi_vars[jj].dual_var_name is not None: self.cvars_to_pb[jj][0] = ii else: self.cvars_to_pb[jj][1] = ii self.subpb.append([problem, None, None]) self.cvars_to_pb_map = {} for varname, pbs in self.cvars_to_pb.iteritems(): # match field nodes coors = [] for ii in pbs: pbi = self.subpb[ii][0] pbi_vars = pbi.get_variables() fcoors = pbi_vars[varname].field.coors dc = nm.abs(nm.max(fcoors, axis=0)\ - nm.min(fcoors, axis=0)) ax = nm.where(dc > 1e-9)[0] coors.append(fcoors[:,ax]) if len(coors[0]) != len(coors[1]): raise ValueError('number of nodes does not match!') kdtree = KDTree(coors[0]) map_12 = kdtree.query(coors[1])[1] pbi1 = self.subpb[pbs[0]][0] pbi1_vars = pbi1.get_variables() eq_map_1 = pbi1_vars[varname].eq_map pbi2 = self.subpb[pbs[1]][0] pbi2_vars = pbi2.get_variables() eq_map_2 = pbi2_vars[varname].eq_map dpn = eq_map_2.dpn nnd = map_12.shape[0] map_12_nd = nm.zeros((nnd * dpn,), dtype=nm.int32) if dpn > 1: for ii in range(dpn): map_12_nd[ii::dpn] = map_12 * dpn + ii else: map_12_nd = map_12 idx = nm.where(eq_map_2.eq >= 0)[0] self.cvars_to_pb_map[varname] = eq_map_1.eq[map_12[idx]]
def main(): # if multi_mpi.cpu_count() < 2: # raise ValueError('MPI mode - the number of nodes is less then 2!') if multi_mpi.mpi_rank == multi_mpi.mpi_master: # MPI master node - solve problem at macro scale parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument('--debug_mpi', action='store_true', dest='debug_mpi', default=False, help=helps['debug_mpi']) parser.add_argument('-c', '--conf', metavar='"key : value, ..."', action='store', dest='conf', type=str, default=None, help=helps['conf']) parser.add_argument('-O', '--options', metavar='"key : value, ..."', action='store', dest='app_options', type=str, default=None, help=helps['options']) parser.add_argument('-d', '--define', metavar='"key : value, ..."', action='store', dest='define_args', type=str, default=None, help=helps['define']) parser.add_argument('-o', metavar='filename', action='store', dest='output_filename_trunk', default=None, help=helps['filename']) parser.add_argument('--format', metavar='format', action='store', dest='output_format', default=None, help=helps['output_format']) parser.add_argument('--log', metavar='file', action='store', dest='log', default=None, help=helps['log']) parser.add_argument('-q', '--quiet', action='store_true', dest='quiet', default=False, help=helps['quiet']) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('filename_in', nargs='?') options = parser.parse_args() for k in ['save_ebc', 'save_ebc_nodes', 'save_regions', 'save_regions_as_groups', 'save_field_meshes', 'solve_not']: setattr(options, k, False) if options.debug: from sfepy.base.base import debug_on_error; debug_on_error() if options.debug_mpi: multi_mpi.set_logging_level('debug') filename_in = options.filename_in output.set_output(filename=options.log, quiet=options.quiet, combined=options.log is not None) required, other = get_standard_keywords() conf = ProblemConf.from_file_and_options(filename_in, options, required, other, define_args=options.define_args) opts = conf.options nslaves = multi_mpi.cpu_count() - 1 opts.n_mpi_homog_slaves = nslaves output_prefix = opts.get('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() multi_mpi.master_send_task('finalize', None) else: # MPI slave mode - calculate homogenized coefficients homogen_app = None done = False rank = multi_mpi.mpi_rank while not done: task, data = multi_mpi.slave_get_task('main slave loop') if task == 'init': # data: micro_file, n_micro output.set_output(filename='homog_app_mpi_%d.log' % rank, quiet=True) micro_file, n_micro = data[:2] required, other = get_standard_keywords() required.remove('equations') conf = ProblemConf.from_file(micro_file, required, other, verbose=False) options = Struct(output_filename_trunk=None) homogen_app = HomogenizationApp(conf, options, 'micro:', n_micro=n_micro, update_micro_coors=True) elif task == 'calculate': # data: rel_def_grad, ts, iteration rel_def_grad, ts, iteration = data[:3] homogen_app.setup_macro_deformation(rel_def_grad) homogen_app(ret_all=True, itime=ts.step, iiter=iteration) elif task == 'finalize': done = True
def main(): parser = ArgumentParser() parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument("-o", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=helps['filename']) parser.add_argument("-b", "--band-gaps", action="store_true", dest="detect_band_gaps", default=False, help=helps['detect_band_gaps']) parser.add_argument("-d", "--dispersion", action="store_true", dest="analyze_dispersion", default=False, help=helps['analyze_dispersion']) parser.add_argument("-p", "--plot", action="store_true", dest="plot", default=False, help=helps['plot']) parser.add_argument("--phase-velocity", action="store_true", dest="phase_velocity", default=False, help=helps['phase_velocity']) parser.add_argument("filename_in") options = parser.parse_args() if options.debug: from sfepy.base.base import debug_on_error debug_on_error() if options.plot: if plt is None: output('matplotlib.pyplot cannot be imported, ignoring option -p!') options.plot = False elif options.analyze_dispersion == False: options.detect_band_gaps = True required, other = get_standard_keywords() required.remove('equations') if not options.analyze_dispersion: required.remove('solver_[0-9]+|solvers') if options.phase_velocity: required.remove('ebc_[0-9]+|ebcs') conf = ProblemConf.from_file(options.filename_in, required, other) app = AcousticBandGapsApp(conf, options, 'phonon:') opts = conf.options if hasattr(opts, 'parametric_hook'): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize(parametric_hook) app()
def init_subproblems(self, conf, **kwargs): from sfepy.discrete.state import State from sfepy.discrete import Problem from sfepy.base.conf import ProblemConf, get_standard_keywords from scipy.spatial import cKDTree as KDTree # init subproblems problem = self.context pb_vars = problem.get_variables() # get "master" DofInfo and last index pb_adi_indx = problem.equations.variables.adi.indx self.adi_indx = pb_adi_indx.copy() last_indx = -1 for ii in six.itervalues(self.adi_indx): last_indx = nm.max([last_indx, ii.stop]) # coupling variables self.cvars_to_pb = {} for jj in conf.coupling_variables: self.cvars_to_pb[jj] = [None, None] if jj in pb_vars.names: if pb_vars[jj].dual_var_name is not None: self.cvars_to_pb[jj][0] = -1 else: self.cvars_to_pb[jj][1] = -1 # init subproblems self.subpb = [] required, other = get_standard_keywords() master_prefix = output.get_output_prefix() for ii, ifname in enumerate(conf.others): sub_prefix = master_prefix[:-1] + '-sub%d:' % (ii + 1) output.set_output_prefix(sub_prefix) kwargs['master_problem'] = problem confi = ProblemConf.from_file(ifname, required, other, define_args=kwargs) pbi = Problem.from_conf(confi, init_equations=True) sti = State(pbi.equations.variables) pbi.equations.set_data(None, ignore_unknown=True) pbi.time_update() pbi.update_materials() sti.apply_ebc() pbi_vars = pbi.get_variables() output.set_output_prefix(master_prefix) self.subpb.append([pbi, sti, None]) # append "slave" DofInfo for jj in pbi_vars.names: if not (pbi_vars[jj].is_state()): continue didx = pbi.equations.variables.adi.indx[jj] ndof = didx.stop - didx.start if jj in self.adi_indx: if ndof != \ (self.adi_indx[jj].stop - self.adi_indx[jj].start): raise ValueError('DOFs do not match!') else: self.adi_indx.update( {jj: slice(last_indx, last_indx + ndof, None)}) last_indx += ndof for jj in conf.coupling_variables: if jj in pbi_vars.names: if pbi_vars[jj].dual_var_name is not None: self.cvars_to_pb[jj][0] = ii else: self.cvars_to_pb[jj][1] = ii self.subpb.append([problem, None, None]) self.cvars_to_pb_map = {} for varname, pbs in six.iteritems(self.cvars_to_pb): # match field nodes coors = [] for ii in pbs: pbi = self.subpb[ii][0] pbi_vars = pbi.get_variables() fcoors = pbi_vars[varname].field.coors dc = nm.abs(nm.max(fcoors, axis=0)\ - nm.min(fcoors, axis=0)) ax = nm.where(dc > 1e-9)[0] coors.append(fcoors[:, ax]) if len(coors[0]) != len(coors[1]): raise ValueError('number of nodes does not match!') kdtree = KDTree(coors[0]) map_12 = kdtree.query(coors[1])[1] pbi1 = self.subpb[pbs[0]][0] pbi1_vars = pbi1.get_variables() eq_map_1 = pbi1_vars[varname].eq_map pbi2 = self.subpb[pbs[1]][0] pbi2_vars = pbi2.get_variables() eq_map_2 = pbi2_vars[varname].eq_map dpn = eq_map_2.dpn nnd = map_12.shape[0] map_12_nd = nm.zeros((nnd * dpn, ), dtype=nm.int32) if dpn > 1: for ii in range(dpn): map_12_nd[ii::dpn] = map_12 * dpn + ii else: map_12_nd = map_12 idx = nm.where(eq_map_2.eq >= 0)[0] self.cvars_to_pb_map[varname] = eq_map_1.eq[map_12[idx]]