def vary_incident_wave_dir( problem ): default_printer.prefix = 'vary_incident_wave_dir:' log_conf = { 'is_plot' : True, 'yscales' : ['linear'], 'xaxes' : ['incident wave angle [degrees]'], 'yaxes' : ['phase velocity [m/s]'], } dim = problem.domain.mesh.dim log = Log.from_conf( log_conf, ['phase velocity %d' % ii for ii in range( dim )] ) alphas = nm.linspace( 0.0, 360.0, 37 ) output( 'running for angles:', alphas ) pause() for ii, alpha in enumerate( alphas ): output( 'iteration %d: alpha %2f' % (ii, alpha) ) opts = problem.conf.options ra = nm.pi * alpha / 180.0 iwd = nm.zeros( (dim,), dtype = nm.float64 ) iwd[0:2] = [nm.cos( ra ), nm.sin( ra )] opts.incident_wave_dir = iwd out = [] yield problem, out #You have: sqrt( 10^10Pa / 10^4kg * m^3 ) #You want: #Definition: 1000 m / s convert_to_ms = 1000.0 phase_velocity = out[0] * convert_to_ms # to m/s. log( x = [alpha], *phase_velocity ) output( 'phase velocity [m/s]:', phase_velocity ) if opts.homogeneous: mat = problem.materials['matrix'] # dilatation wave: vp = \sqrt{ (\lambda + 2\mu) / \rho } vd = nm.sqrt( (mat.D[0,0]) / mat.density) * convert_to_ms # shear wave: vs = \sqrt{ \mu / \rho } vs = nm.sqrt( mat.D[-1,-1] / mat.density ) * convert_to_ms output( 'analytical dilatation: %f, shear: %f' % (vd, vs) ) # pause() yield None print log pause() if opts.homogeneous: name = 'homogeneous' else: name = 'perforated' fig_name = os.path.join( problem.output_dir, 'phase_velocity_%s%s' % (name, opts.fig_suffix) ) log( save_figure = fig_name, finished = True )
def main(): log_conf = { 'is_plot' : True, 'aggregate' : 200, 'yscales' : ['linear', 'log'], 'xaxes' : ['angle', None], 'yaxes' : [None, 'a function'], } log = Log.from_conf( log_conf, (['sin( x )', 'cos( x )'],['exp( x )']) ) for x in nm.linspace( 0, 4.0 * nm.pi, 200 ): output( 'x: ', x ) log( nm.sin( x ), nm.cos( x ), nm.exp( x ), x = [x, None] ) print log pause() log( finished = True )
def solve_navier_stokes(conf, options): opts = conf.options dpb = Problem.from_conf(conf, init_equations=False) equations = getattr(conf, '_'.join(('equations_direct', opts.problem))) dpb.set_equations(equations) ls_conf = dpb.get_solver_conf(opts.ls) nls_conf = dpb.get_solver_conf(opts.nls_direct) method = opts.direct_method if method == 'stationary': data = {} dpb.time_update(None) state_dp = dpb.solve(nls_conf=nls_conf) elif method == 'transient': ls = Solver.any_from_conf(ls_conf) ts_conf = dpb.get_solver_conf(opts.ts_direct) data = {'ts': Struct(dt=ts_conf.dt)} # Plug in mass term. mequations = {} for key, eq in equations.iteritems(): if 'dw_div_grad' in eq: eq = '+'.join((ts_conf.mass_term, eq)).replace('++', '+') mequations[key] = eq if ts_conf.stokes_init: state_dp0 = solve_stokes(dpb, conf.equations_direct_stokes, nls_conf) dpb.set_equations(mequations) else: dpb.set_equations(mequations) state_dp0 = dpb.create_state() dpb.time_update(None) state_dp0.apply_ebc() from sfepy.base.log import Log log = Log.from_conf(Struct(is_plot=True), ([r'$||u||$'], [r'$||p||$'])) output('Navier-Stokes...') ev = BasicEvaluator(dpb, ts=Struct(dt=ts_conf.dt)) nls = Solver.any_from_conf(nls_conf, evaluator=ev, lin_solver=ls) n_step = ts_conf.n_step step = 0 while 1: for ii in xrange(n_step): output(step) vec_u = state_dp0('w') vec_p = state_dp0('r') log(nm.linalg.norm(vec_u), nm.linalg.norm(vec_p)) dpb.variables.set_data_from_state('w_0', state_dp0(), 'w') vec_dp = nls(state_dp0()) step += 1 state_dp = state_dp0.copy() state_dp.set_reduced(vec_dp) state_dp0 = state_dp if ts_conf.interactive: try: n_step = int(raw_input('continue: ')) if n_step <= 0: break except: break vec_u = state_dp('w') vec_p = state_dp('r') log(nm.linalg.norm(vec_u), nm.linalg.norm(vec_p), finished=True) else: raise 'unknown Navier-Stokes solution method (%s)!' % method return dpb, state_dp, data
def solve_navier_stokes(conf, options): opts = conf.options dpb = ProblemDefinition.from_conf(conf, init_equations=False) equations = getattr(conf, "_".join(("equations_direct", opts.problem))) dpb.set_equations(equations) ls_conf = dpb.get_solver_conf(opts.ls) nls_conf = dpb.get_solver_conf(opts.nls_direct) method = opts.direct_method if method == "stationary": data = {} dpb.time_update(None) state_dp = dpb.solve(nls_conf=nls_conf) elif method == "transient": ls = Solver.any_from_conf(ls_conf) ts_conf = dpb.get_solver_conf(opts.ts_direct) data = {"ts": Struct(dt=ts_conf.dt)} # Plug in mass term. mequations = {} for key, eq in equations.iteritems(): if "dw_div_grad" in eq: eq = "+".join((ts_conf.mass_term, eq)).replace("++", "+") mequations[key] = eq if ts_conf.stokes_init: state_dp0 = solve_stokes(dpb, conf.equations_direct_stokes, nls_conf) dpb.set_equations(mequations) else: dpb.set_equations(mequations) state_dp0 = dpb.create_state() dpb.time_update(None) state_dp0.apply_ebc() from sfepy.base.log import Log log = Log.from_conf(Struct(is_plot=True), ([r"$||u||$"], [r"$||p||$"])) output("Navier-Stokes...") ev = BasicEvaluator(dpb, ts=Struct(dt=ts_conf.dt)) nls = Solver.any_from_conf(nls_conf, evaluator=ev, lin_solver=ls) n_step = ts_conf.n_step step = 0 while 1: for ii in xrange(n_step): output(step) vec_u = state_dp0("w") vec_p = state_dp0("r") log(nm.linalg.norm(vec_u), nm.linalg.norm(vec_p)) dpb.variables.set_data_from_state("w_0", state_dp0(), "w") vec_dp = nls(state_dp0()) step += 1 state_dp = state_dp0.copy() state_dp.set_reduced(vec_dp) state_dp0 = state_dp if ts_conf.interactive: try: n_step = int(raw_input("continue: ")) if n_step <= 0: break except: break vec_u = state_dp("w") vec_p = state_dp("r") log(nm.linalg.norm(vec_u), nm.linalg.norm(vec_p), finished=True) else: raise "unknown Navier-Stokes solution method (%s)!" % method return dpb, state_dp, data
def solve_eigen_problem_n( self ): opts = self.app_options pb = self.problem dim = pb.domain.mesh.dim pb.set_equations( pb.conf.equations ) pb.select_bcs( ebc_names = ['ZeroSurface'] ) output( 'assembling rhs...' ) tt = time.clock() mtx_b = pb.evaluate(pb.conf.equations['rhs'], mode='weak', auto_init=True, dw_mode='matrix') output( '...done in %.2f s' % (time.clock() - tt) ) assert_( nm.alltrue( nm.isfinite( mtx_b.data ) ) ) ## mtx_b.save( 'b.txt', format='%d %d %.12f\n' ) aux = pb.create_evaluable(pb.conf.equations['lhs'], mode='weak', dw_mode='matrix') mtx_a_equations, mtx_a_variables = aux if self.options.plot: log_conf = { 'is_plot' : True, 'aggregate' : 1, 'yscales' : ['linear', 'log'], } else: log_conf = { 'is_plot' : False, } log = Log.from_conf( log_conf, ([r'$|F(x)|$'], [r'$|F(x)-x|$']) ) file_output = Output('', opts.log_filename, combined = True) eig_conf = pb.get_solver_conf( opts.eigen_solver ) eig_solver = Solver.any_from_conf( eig_conf ) # Just to get the shape. Assumes one element group only!!! v_hxc_qp = pb.evaluate('dq_state_in_volume_qp.i1.Omega(Psi)') v_hxc_qp.fill(0.0) self.qp_shape = v_hxc_qp.shape vec_v_hxc = self._interp_to_nodes(v_hxc_qp) self.norm_v_hxc0 = nla.norm(vec_v_hxc) self.itercount = 0 aux = wrap_function(self.iterate, (eig_solver, mtx_a_equations, mtx_a_variables, mtx_b, log, file_output)) ncalls, times, nonlin_v, results = aux # Create and call the DFT solver. dft_conf = pb.get_solver_conf(opts.dft_solver) dft_status = {} dft_solver = Solver.any_from_conf(dft_conf, fun = nonlin_v, status = dft_status) v_hxc_qp = dft_solver(v_hxc_qp.ravel()) v_hxc_qp = nm.array(v_hxc_qp, dtype=nm.float64) v_hxc_qp.shape = self.qp_shape eigs, mtx_s_phi, vec_n, vec_v_h, v_ion_qp, v_xc_qp, v_hxc_qp = results output( 'DFT iteration time [s]:', dft_status['time_stats'] ) fun = pb.materials['mat_v'].function variable = self.problem.create_variables(['scalar'])['scalar'] vec_v_ion = fun(None, variable.field.get_coor(), mode='qp')['V_ion'].squeeze() vec_v_xc = self._interp_to_nodes(v_xc_qp) vec_v_hxc = self._interp_to_nodes(v_hxc_qp) vec_v_sum = self._interp_to_nodes(v_hxc_qp + v_ion_qp) coor = pb.domain.get_mesh_coors() r2 = norm_l2_along_axis(coor, squared=True) vec_nr2 = vec_n * r2 pb.select_bcs( ebc_names = ['ZeroSurface'] ) mtx_phi = self.make_full( mtx_s_phi ) out = {} update_state_to_output(out, pb, vec_n, 'n') update_state_to_output(out, pb, vec_nr2, 'nr2') update_state_to_output(out, pb, vec_v_h, 'V_h') update_state_to_output(out, pb, vec_v_xc, 'V_xc') update_state_to_output(out, pb, vec_v_ion, 'V_ion') update_state_to_output(out, pb, vec_v_hxc, 'V_hxc') update_state_to_output(out, pb, vec_v_sum, 'V_sum') self.save_results(eigs, mtx_phi, out=out) if self.options.plot: log( save_figure = opts.iter_fig_name ) pause() log(finished=True) return Struct( pb = pb, eigs = eigs, mtx_phi = mtx_phi, vec_n = vec_n, vec_nr2 = vec_nr2, vec_v_h = vec_v_h, vec_v_xc = vec_v_xc )
def solve_navier_stokes(conf, options): opts = conf.options dpb = ProblemDefinition.from_conf(conf, init_equations=False) equations = getattr(conf, '_'.join(('equations_direct', opts.problem))) dpb.set_equations(equations) ls_conf = dpb.get_solver_conf( opts.ls ) nls_conf = dpb.get_solver_conf(opts.nls_direct) method = opts.direct_method if method == 'stationary': data = {} dpb.time_update(None) vec_dp = dpb.solve(nls_conf=nls_conf) elif method == 'transient': ls = Solver.any_from_conf( ls_conf ) ts_conf = dpb.get_solver_conf( opts.ts_direct ) data = {'ts' : Struct( dt = ts_conf.dt )} # Plug in mass term. mequations = {} for key, eq in equations.iteritems(): if 'dw_div_grad' in eq: eq = '+'.join( (ts_conf.mass_term, eq) ).replace( '++', '+') mequations[key] = eq if ts_conf.stokes_init: vec_dp0 = solve_stokes( dpb, conf.equations_direct_stokes, nls_conf ) dpb.set_equations( mequations ) else: dpb.set_equations( mequations ) vec_dp0 = dpb.create_state_vector() dpb.time_update( None ) dpb.apply_ebc( vec_dp0 ) from sfepy.base.log import Log log = Log.from_conf( Struct( is_plot = True ), ([r'$||u||$'], [r'$||p||$']) ) output( 'Navier-Stokes...' ) ev = BasicEvaluator( dpb, ts = Struct( dt = ts_conf.dt ) ) nls = Solver.any_from_conf( nls_conf, evaluator = ev, lin_solver = ls ) n_step = ts_conf.n_step step = 0 while 1: for ii in xrange( n_step ): output( step ) vec_u = dpb.variables.get_state_part_view( vec_dp0, 'w' ) vec_p = dpb.variables.get_state_part_view( vec_dp0, 'r' ) log( nm.linalg.norm( vec_u ), nm.linalg.norm( vec_p ) ) dpb.variables.non_state_data_from_state( 'w_0', vec_dp0, 'w' ) vec_dp = nls( vec_dp0 ) step += 1 vec_dp0 = vec_dp.copy() if ts_conf.interactive: try: n_step = int( raw_input( 'continue: ' ) ) if n_step <= 0: break except: break vec_u = dpb.variables.get_state_part_view( vec_dp, 'w' ) vec_p = dpb.variables.get_state_part_view( vec_dp, 'r' ) log( nm.linalg.norm( vec_u ), nm.linalg.norm( vec_p ), finished = True ) else: raise 'unknown Navier-Stokes solution method (%s)!' % method return dpb, vec_dp, data
def solve_eigen_problem_n( conf, options ): pb = ProblemDefinition.from_conf( conf ) dim = pb.domain.mesh.dim pb.time_update() dummy = pb.create_state_vector() output( 'assembling rhs...' ) tt = time.clock() mtx_b = eval_term_op( dummy, conf.equations['rhs'], pb, dw_mode = 'matrix', tangent_matrix = pb.mtx_a.copy() ) output( '...done in %.2f s' % (time.clock() - tt) ) #mtxA.save( 'tmp/a.txt', format='%d %d %.12f\n' ) #mtxB.save( 'tmp/b.txt', format='%d %d %.12f\n' ) try: n_eigs = conf.options.n_eigs except AttributeError: n_eigs = mtx_a.shape[0] if n_eigs is None: n_eigs = mtx_a.shape[0] ## mtx_a.save( 'a.txt', format='%d %d %.12f\n' ) ## mtx_b.save( 'b.txt', format='%d %d %.12f\n' ) if options.plot: log_conf = { 'is_plot' : True, 'aggregate' : 1, 'yscales' : ['linear', 'log'], } else: log_conf = { 'is_plot' : False, } log = Log.from_conf( log_conf, ([r'$|F(x)|$'], [r'$|F(x)|$']) ) eig_conf = pb.get_solver_conf( conf.options.eigen_solver ) eig_solver = Solver.any_from_conf( eig_conf ) vec_vhxc = nm.zeros( (pb.variables.di.ptr[-1],), dtype = nm.float64 ) aux = wrap_function( iterate, (pb, conf, eig_solver, n_eigs, mtx_b, log) ) ncalls, times, nonlin_v = aux vec_vhxc = broyden3( nonlin_v, vec_vhxc, verbose = True ) out = iterate( vec_vhxc, pb, conf, eig_solver, n_eigs, mtx_b ) eigs, mtx_s_phi, vec_n, vec_vh, vec_vxc = out if options.plot: log( finished = True ) pause() coor = pb.domain.get_mesh_coors() r = coor[:,0]**2 + coor[:,1]**2 + coor[:,2]**2 vec_nr2 = vec_n * r n_eigs = eigs.shape[0] mtx_phi = nm.empty( (pb.variables.di.ptr[-1], mtx_s_phi.shape[1]), dtype = nm.float64 ) for ii in xrange( n_eigs ): mtx_phi[:,ii] = pb.variables.make_full_vec( mtx_s_phi[:,ii] ) save = get_default_attr( conf.options, 'save_eig_vectors', None ) out = {} for ii in xrange( n_eigs ): if save is not None: if (ii >= save[0]) and (ii < (n_eigs - save[1])): continue aux = pb.state_to_output( mtx_phi[:,ii] ) key = aux.keys()[0] out[key+'%03d' % ii] = aux[key] update_state_to_output( out, pb, vec_n, 'n' ) update_state_to_output( out, pb, vec_nr2, 'nr2' ) update_state_to_output( out, pb, vec_vh, 'vh' ) update_state_to_output( out, pb, vec_vxc, 'vxc' ) ofn_trunk = options.output_filename_trunk pb.domain.mesh.write( ofn_trunk + '.vtk', io = 'auto', out = out ) fd = open( ofn_trunk + '_eigs.txt', 'w' ) eigs.tofile( fd, ' ' ) fd.close() return Struct( pb = pb, eigs = eigs, mtx_phi = mtx_phi )
def __call__(self, x0, conf=None, obj_fun=None, obj_fun_grad=None, status=None, obj_args=None): # def fmin_sd( conf, x0, fn_of, fn_ofg, args = () ): conf = get_default(conf, self.conf) obj_fun = get_default(obj_fun, self.obj_fun) obj_fun_grad = get_default(obj_fun_grad, self.obj_fun_grad) status = get_default(status, self.status) obj_args = get_default(obj_args, self.obj_args) if conf.output: globals()["output"] = conf.output output("entering optimization loop...") nc_of, tt_of, fn_of = wrap_function(obj_fun, obj_args) nc_ofg, tt_ofg, fn_ofg = wrap_function(obj_fun_grad, obj_args) time_stats = {"of": tt_of, "ofg": tt_ofg, "check": []} if conf.log: log = Log.from_conf(conf, ([r"of"], [r"$||$ofg$||$"], [r"alpha"])) else: log = None ofg = None it = 0 xit = x0.copy() while 1: of = fn_of(xit) if it == 0: of0 = ofit0 = of_prev = of of_prev_prev = of + 5000.0 if ofg is None: # ofg = 1 ofg = fn_ofg(xit) if conf.check: tt = time.clock() check_gradient(xit, ofg, fn_of, conf.delta, conf.check) time_stats["check"].append(time.clock() - tt) ofg_norm = nla.norm(ofg, conf.norm) ret = conv_test(conf, it, of, ofit0, ofg_norm) if ret >= 0: break ofit0 = of ## # Backtrack (on errors). alpha = conf.ls0 can_ls = True while 1: xit2 = xit - alpha * ofg aux = fn_of(xit2) if aux is None: alpha *= conf.ls_red_warp can_ls = False output("warp: reducing step (%f)" % alpha) elif conf.ls and conf.ls_method == "backtracking": if aux < of * conf.ls_on: break alpha *= conf.ls_red output("backtracking: reducing step (%f)" % alpha) else: of_prev_prev = of_prev of_prev = aux break if alpha < conf.ls_min: if aux is None: raise RuntimeError, "giving up..." output("linesearch failed, continuing anyway") break # These values are modified by the line search, even if it fails of_prev_bak = of_prev of_prev_prev_bak = of_prev_prev if conf.ls and can_ls and conf.ls_method == "full": output("full linesearch...") alpha, fc, gc, of_prev, of_prev_prev, ofg1 = linesearch.line_search( fn_of, fn_ofg, xit, -ofg, ofg, of_prev, of_prev_prev, c2=0.4 ) if alpha is None: # line search failed -- use different one. alpha, fc, gc, of_prev, of_prev_prev, ofg1 = sopt.line_search( fn_of, fn_ofg, xit, -ofg, ofg, of_prev_bak, of_prev_prev_bak ) if alpha is None or alpha == 0: # This line search also failed to find a better solution. ret = 3 break output(" -> alpha: %.8e" % alpha) else: if conf.ls_method == "full": output("full linesearch off (%s and %s)" % (conf.ls, can_ls)) ofg1 = None if conf.log: log(of, ofg_norm, alpha) xit = xit - alpha * ofg if ofg1 is None: ofg = None else: ofg = ofg1.copy() for key, val in time_stats.iteritems(): if len(val): output("%10s: %7.2f [s]" % (key, val[-1])) it = it + 1 output("status: %d" % ret) output("initial value: %.8e" % of0) output("current value: %.8e" % of) output("iterations: %d" % it) output("function evaluations: %d in %.2f [s]" % (nc_of[0], nm.sum(time_stats["of"]))) output("gradient evaluations: %d in %.2f [s]" % (nc_ofg[0], nm.sum(time_stats["ofg"]))) if conf.log: log(of, ofg_norm, alpha, finished=True) if status is not None: status["log"] = log status["status"] = status status["of0"] = of0 status["of"] = of status["it"] = it status["nc_of"] = nc_of[0] status["nc_ofg"] = nc_ofg[0] status["time_stats"] = time_stats return xit