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 = 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 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 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 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 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 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 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 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') 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.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(): 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 " + 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 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 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 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 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 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 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 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 recover_micro_hook(micro_filename, region, macro, naming_scheme='step_iel', recovery_file_tag=''): # Create a micro-problem instance. required, other = get_standard_keywords() required.remove('equations') pb = ProblemDefinition.from_conf_file(micro_filename, required=required, other=other, init_equations=False, init_solvers=False) coefs_filename = pb.conf.options.get_default_attr('coefs_filename', 'coefs') output_dir = pb.conf.options.get_default_attr('output_dir', '.') coefs_filename = op.join(output_dir, coefs_filename) + '.h5' # Coefficients and correctors coefs = Coefficients.from_file_hdf5(coefs_filename) corrs = get_correctors_from_file(dump_names=coefs.dump_names) recovery_hook = get_default_attr(pb.conf.options, 'recovery_hook', None) if recovery_hook is not None: recovery_hook = pb.conf.get_function(recovery_hook) aux = max(pb.domain.shape.n_gr, 2) format = get_print_info( aux, fill = '0' )[1] \ + '_' + get_print_info( pb.domain.mesh.n_el, fill = '0' )[1] for ig, ii, iel in region.iter_cells(): print 'ig: %d, ii: %d, iel: %d' % (ig, ii, iel) local_macro = {} for k, v in macro.iteritems(): local_macro[k] = v[ii, 0] out = recovery_hook(pb, corrs, local_macro) # save data suffix = format % (ig, iel) micro_name = pb.get_output_name(extra='recovered_'\ + recovery_file_tag + suffix) filename = op.join(output_dir, op.basename(micro_name)) fpv = pb.conf.options.get_default_attr('file_per_var', False) pb.save_state(filename, out=out, file_per_var=fpv)
def 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 recover_micro_hook( micro_filename, region, macro, naming_scheme = 'step_iel', recovery_file_tag='' ): # Create a micro-problem instance. required, other = get_standard_keywords() required.remove( 'equations' ) pb = ProblemDefinition.from_conf_file(micro_filename, required=required, other=other, init_equations=False, init_solvers=False) coefs_filename = pb.conf.options.get_default_attr('coefs_filename', 'coefs') output_dir = pb.conf.options.get_default_attr('output_dir', '.') coefs_filename = op.join(output_dir, coefs_filename) + '.h5' # Coefficients and correctors coefs = Coefficients.from_file_hdf5( coefs_filename ) corrs = get_correctors_from_file( dump_names = coefs.dump_names ) recovery_hook = get_default_attr( pb.conf.options, 'recovery_hook', None ) if recovery_hook is not None: recovery_hook = getattr( pb.conf.funmod, recovery_hook ) aux = max(pb.domain.shape.n_gr, 2) format = get_print_info( aux, fill = '0' )[1] \ + '_' + get_print_info( pb.domain.mesh.n_el, fill = '0' )[1] for ig, ii, iel in region.iter_cells(): print 'ig: %d, ii: %d, iel: %d' % (ig, ii, iel) local_macro = {} for k, v in macro.iteritems(): local_macro[k] = v[ii,0] out = recovery_hook( pb, corrs, local_macro ) # save data suffix = format % (ig, iel) micro_name = pb.get_output_name(extra='recovered_'\ + recovery_file_tag + suffix) filename = op.join(output_dir, op.basename(micro_name)) fpv = pb.conf.options.get_default_attr('file_per_var', False) pb.save_state(filename, out=out, file_per_var=fpv)
def from_conf_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 = 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 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(): parser = OptionParser(usage=usage, version='%prog ' + sfepy.__version__) parser.add_option('-c', '--conf', metavar='"key : value, ..."', action='store', dest='conf', type='string', default=None, help=help['conf']) parser.add_option('-O', '--options', metavar='"key : value, ..."', action='store', dest='app_options', type='string', default=None, help=help['options']) parser.add_option('-o', '', metavar='filename', action='store', dest='output_filename_trunk', default=None, help=help['filename']) parser.add_option('--oscillator', action='store_true', dest='oscillator', default=False, help=help['oscillator']) parser.add_option('--well', action='store_true', dest='well', default=False, help=help['well']) parser.add_option('--hydrogen', action='store_true', dest='hydrogen', default=False, help=help['hydrogen']) parser.add_option('--boron', action='store_true', dest='boron', default=False, help=help['boron']) parser.add_option('-n', '--n-eigs', type='int', metavar='int', action='store', dest='n_eigs', default=None, help=help['n_eigs']) parser.add_option('-t', '--tau', type='float', metavar='float', action='store', dest='tau', default=None, help=help['tau']) options, args = parser.parse_args() if len(args) == 1: filename_in = args[0] elif len(args) == 0: 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 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 = 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 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 = OptionParser(usage = usage, version = "%prog " + sfepy.__version__) parser.add_option('-c', '--conf', metavar='"key : value, ..."', action='store', dest='conf', type='string', default=None, help= help['conf']) parser.add_option('-O', '--options', metavar='"key : value, ..."', action='store', dest='app_options', type='string', default=None, help=help['options']) parser.add_option('-d', '--define', metavar='"key : value, ..."', action='store', dest='define_args', type='string', default=None, help=help['define']) parser.add_option( "-o", "", metavar = 'filename', action = "store", dest = "output_filename_trunk", default = None, help = help['filename'] ) parser.add_option( "", "--format", metavar = 'format', action = "store", dest = "output_format", default = None, help = help['output_format'] ) parser.add_option( "", "--log", metavar = 'file', action = "store", dest = "log", default = None, help = help['log'] ) parser.add_option( "-q", "--quiet", action = "store_true", dest = "quiet", default = False, help = help['quiet'] ) parser.add_option( "", "--save-ebc", action = "store_true", dest = "save_ebc", default = False, help = help['save_ebc'] ) parser.add_option( "", "--save-regions", action = "store_true", dest = "save_regions", default = False, help = help['save_regions'] ) parser.add_option( "", "--save-regions-as-groups", action = "store_true", dest = "save_regions_as_groups", default = False, help = help['save_regions_as_groups'] ) parser.add_option( "", "--save-field-meshes", action = "store_true", dest = "save_field_meshes", default = False, help = help['save_field_meshes'] ) parser.add_option( "", "--solve-not", action = "store_true", dest = "solve_not", default = False, help = help['solve_not'] ) parser.add_option( "", "--list", metavar = 'what', action = "store", dest = "_list", default = None, help = help['list'] ) options, args = parser.parse_args() if (len( args ) == 1): filename_in = args[0]; else: if options._list == 'terms': print_terms() else: parser.print_help(), return output.set_output(filename=options.log, quiet=options.quiet, combined=options.log is not None) required, other = get_standard_keywords() if options.solve_not: required.remove( 'equations' ) required.remove( 'solver_[0-9]+|solvers' ) other.extend( ['equations'] ) conf = ProblemConf.from_file_and_options(filename_in, options, required, other, define_args=options.define_args) opts = conf.options output_prefix = get_default_attr( opts, 'output_prefix', 'sfepy:' ) app = SimpleApp( conf, options, output_prefix ) if hasattr( opts, 'parametric_hook' ): # Parametric study. parametric_hook = conf.get_function(opts.parametric_hook) app.parametrize( parametric_hook ) app()
geom.runtetgen("tmp/t.poly", a=0.03, Q=1.0, 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
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:', all_data.keys()) output('from step:', step) if options.only_names is None: data = all_data else: data = {} for key, val in all_data.iteritems(): if key in options.only_names: data[key] = val if problem is None: problem = ProblemDefinition.from_conf(conf, init_equations=False, init_solvers=False) if probes is None: gen_probes = conf.get_function(conf.options.gen_probes) probes, labels = gen_probes(problem) if probe_hooks is None: probe_hooks = {None : conf.get_function(conf.options.probe_hook)} if options.output_filename_trunk is None: options.output_filename_trunk = problem.ofn_trunk filename_template = options.output_filename_trunk \ + ('_%%d.%s' % options.output_format) if options.same_dir: filename_template = os.path.join(os.path.dirname(filename_results), filename_template) output_dir = os.path.dirname(filename_results) for ip, probe in enumerate(probes): output(ip, probe.name) probe.set_options(close_limit=options.close_limit) for key, probe_hook in probe_hooks.iteritems(): out = probe_hook(data, probe, labels[ip], problem) if out is None: continue if isinstance(out, tuple): fig, results = out else: fig = out if key is not None: filename = filename_template % (key, ip) else: filename = filename_template % ip if fig is not None: if isinstance(fig, dict): for fig_name, fig_fig in fig.iteritems(): fig_filename = edit_filename(filename, suffix='_' + fig_name) fig_fig.savefig(fig_filename) output('figure ->', os.path.normpath(fig_filename)) else: fig.savefig(filename) output('figure ->', os.path.normpath(filename)) if results is not None: txt_filename = edit_filename(filename, new_ext='.txt') write_results(txt_filename, probe, results) output('data ->', os.path.normpath(txt_filename))
def recover_micro_hook(micro_filename, region, macro, naming_scheme='step_iel', 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) format = get_print_info(pb.domain.mesh.n_el, fill='0')[1] output('recovering microsctructures...') tt = time.clock() output_fun = output.output_function output_level = output.level for ii, iel in enumerate(region.cells): output.level = output_level output('micro: %d (el=%d)' % (ii, iel)) local_macro = {} for k, v in six.iteritems(macro): local_macro[k] = v[ii, 0] output.set_output(quiet=not(verbose)) out = recovery_hook(pb, corrs, local_macro) output.output_function = output_fun if ii == 0: new_keys = [] new_data = {} new_idxs = [] for k in six.iterkeys(local_macro): if k not in macro: new_keys.append(k) new_data[k] = [] new_idxs.append(ii) for jj in new_keys: new_data[jj].append(local_macro[jj]) # save data if out is not None: suffix = format % iel micro_name = pb.get_output_name(extra='recovered_' + recovery_file_tag + suffix) filename = op.join(output_dir, op.basename(micro_name)) fpv = pb.conf.options.get('file_per_var', False) pb.save_state(filename, out=out, file_per_var=fpv) output('...done in %.2f s' % (time.clock() - tt)) for jj in new_keys: lout = new_data[jj] macro[jj] = nm.zeros((nm.max(new_idxs) + 1, 1) + lout[0].shape, dtype=lout[0].dtype) out = macro[jj] for kk, ii in enumerate(new_idxs): out[ii, 0] = lout[kk]
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(): import os from sfepy.base.base import spause, output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.discrete import Problem import sfepy.homogenization.coefs_base as cb parser = ArgumentParser(description=__doc__) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-n', '--no-pauses', action="store_true", dest='no_pauses', default=False, help=helps['no_pauses']) options = 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(list(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 Problem instance. ['q'/other key to quit/continue...]""") problem = Problem.from_conf(conf, init_equations=False) # The homogenization mini-apps need the output_dir. output_dir = '' problem.output_dir = output_dir print(problem) spause(r""">>> ...the Problem 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(): 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 = 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('-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('--save-restart', metavar='mode', type=int, action='store', dest='save_restart', default=None, help=helps['save_restart']) parser.add_argument('--load-restart', metavar='filename', action='store', dest='load_restart', default=None, help=helps['load_restart']) 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']) parser.add_argument('--save-ebc', action='store_true', dest='save_ebc', default=False, help=helps['save_ebc']) parser.add_argument('--save-ebc-nodes', action='store_true', dest='save_ebc_nodes', default=False, help=helps['save_ebc_nodes']) parser.add_argument('--save-regions', action='store_true', dest='save_regions', default=False, help=helps['save_regions']) parser.add_argument('--save-regions-as-groups', action='store_true', dest='save_regions_as_groups', default=False, help=helps['save_regions_as_groups']) parser.add_argument('--save-field-meshes', action='store_true', dest='save_field_meshes', default=False, help=helps['save_field_meshes']) parser.add_argument('--solve-not', action='store_true', dest='solve_not', default=False, help=helps['solve_not']) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--list', metavar='what', action='store', dest='_list', default=None, help=helps['list']) group.add_argument('filename_in', nargs='?') options, petsc_opts = parser.parse_known_args() if options._list is not None: if options._list == 'terms': print_terms() elif options._list == 'solvers': print_solvers() return if options.debug: from sfepy.base.base import debug_on_error debug_on_error() 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() if options.solve_not: required.remove('equations') required.remove('solver_[0-9]+|solvers') other.extend(['equations']) conf = ProblemConf.from_file_and_options(filename_in, options, required, other, define_args=options.define_args) opts = conf.options output_prefix = opts.get('output_prefix', 'sfepy:') opts.save_restart = options.save_restart opts.load_restart = options.load_restart if conf.options.get('evps') is None: app = PDESolverApp(conf, options, output_prefix) else: 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) app()
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 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(): # 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 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 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]]
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(): # 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) elif task == 'calculate': # data: rel_def_grad, ts, iteration macro_data, ts, iteration = data[:3] homogen_app.setup_macro_data(macro_data) homogen_app(ret_all=True, itime=ts.step, iiter=iteration) elif task == 'finalize': done = True
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 run_test(conf_name, options): try: os.makedirs(options.out_dir) except OSError as e: if e.errno != 17: # [Errno 17] File exists raise if options.filter_none or options.debug: 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.debug: raise ok, n_fail, n_total = False, num, num if ok: try: tt = time.clock() ok, n_fail, n_total = test.run(options.debug) test_time = time.clock() - tt except KeyboardInterrupt: print('>>> interrupted') sys.exit(0) except Exception as e: print('>>> %s' % e.__class__) if options.debug: 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(): 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 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 __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]]