本文整理汇总了Python中sfepy.base.log.Log.plot_vlines方法的典型用法代码示例。如果您正苦于以下问题:Python Log.plot_vlines方法的具体用法?Python Log.plot_vlines怎么用?Python Log.plot_vlines使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sfepy.base.log.Log
的用法示例。
在下文中一共展示了Log.plot_vlines方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from sfepy.base.log import Log [as 别名]
# 或者: from sfepy.base.log.Log import plot_vlines [as 别名]
def main():
cwd = os.path.split(os.path.join(os.getcwd(), __file__))[0]
log = Log(
(["sin(x)", "cos(x)"], ["exp(x)"]),
yscales=["linear", "log"],
xlabels=["angle", None],
ylabels=[None, "a function"],
log_filename=os.path.join(cwd, "live_plot.log"),
)
log2 = Log(
[["x^3"]],
yscales=["linear"],
xlabels=["x"],
ylabels=["a cubic function"],
log_filename=os.path.join(cwd, "live_plot2.log"),
)
added = 0
for x in nm.linspace(0, 4.0 * nm.pi, 200):
output("x: ", x)
if x < (2.0 * nm.pi):
log(nm.sin(x), nm.cos(x), nm.exp(x), x=[x, None])
else:
if added:
log(nm.sin(x), nm.cos(x), nm.exp(x), x ** 2, x=[x, None, x])
else:
log.plot_vlines(color="r", linewidth=2)
log.add_group(["x^2"], "linear", "new x", "square", formats=["%+g"])
added += 1
if (added == 20) or (added == 50):
log.plot_vlines([2], color="g", linewidth=2)
log2(x * x * x, x=[x])
print log
print log2
pause()
log(finished=True)
log2(finished=True)
示例2: main
# 需要导入模块: from sfepy.base.log import Log [as 别名]
# 或者: from sfepy.base.log.Log import plot_vlines [as 别名]
def main():
cwd = os.path.split(os.path.join(os.getcwd(), __file__))[0]
log = Log((['sin(x) + i sin(x**2)', 'cos(x)'], ['exp(x)']),
yscales=['linear', 'log'],
xlabels=['angle', None], ylabels=[None, 'a function'],
log_filename=os.path.join(cwd, 'live_plot.log'))
log2 = Log([['x^3']],
yscales=['linear'],
xlabels=['x'], ylabels=['a cubic function'],
aggregate=50, sleep=0.05,
log_filename=os.path.join(cwd, 'live_plot2.log'),
formats=[['{:.5e}']])
added = 0
for x in nm.linspace(0, 4.0 * nm.pi, 200):
output('x: ', x)
if x < (2.0 * nm.pi):
log(nm.sin(x)+1j*nm.sin(x**2), nm.cos(x), nm.exp(x), x=[x, None])
else:
if added:
log(nm.sin(x)+1j*nm.sin(x**2), nm.cos(x), nm.exp(x), x**2,
x=[x, None, x])
else:
log.plot_vlines(color='r', linewidth=2)
log.add_group(['x^2'], yscale='linear', xlabel='new x',
ylabel='square', formats=['%+g'])
added += 1
if (added == 20) or (added == 50):
log.plot_vlines([2], color='g', linewidth=2)
log2(x*x*x, x=[x])
print(log)
print(log2)
pause()
log(finished=True)
log2(finished=True)
示例3: Newton
# 需要导入模块: from sfepy.base.log import Log [as 别名]
# 或者: from sfepy.base.log.Log import plot_vlines [as 别名]
#.........这里部分代码省略.........
iter_hook : function, optional
User-supplied function to call before each iteration.
status : dict-like, optional
The user-supplied object to hold convergence statistics.
Notes
-----
* The optional parameters except `iter_hook` and `status` need
to be given either here or upon `Newton` construction.
* Setting `conf.problem == 'linear'` means a pre-assembled and possibly
pre-solved matrix. This is mostly useful for linear time-dependent
problems.
"""
import sfepy.base.plotutils as plu
conf = get_default( conf, self.conf )
fun = get_default( fun, self.fun )
fun_grad = get_default( fun_grad, self.fun_grad )
lin_solver = get_default( lin_solver, self.lin_solver )
iter_hook = get_default(iter_hook, self.iter_hook)
status = get_default( status, self.status )
ls_eps_a, ls_eps_r = lin_solver.get_tolerance()
eps_a = get_default(ls_eps_a, 1.0)
eps_r = get_default(ls_eps_r, 1.0)
lin_red = conf.eps_a * conf.lin_red
time_stats = {}
vec_x = vec_x0.copy()
vec_x_last = vec_x0.copy()
vec_dx = None
if self.log is not None:
self.log.plot_vlines(color='r', linewidth=1.0)
err = err0 = -1.0
err_last = -1.0
it = 0
while 1:
if iter_hook is not None:
iter_hook(self, vec_x, it, err, err0)
ls = 1.0
vec_dx0 = vec_dx;
while 1:
tt = time.clock()
try:
vec_r = fun( vec_x )
except ValueError:
if (it == 0) or (ls < conf.ls_min):
output('giving up!')
raise
else:
ok = False
else:
ok = True
time_stats['rezidual'] = time.clock() - tt
if ok:
try:
err = nla.norm( vec_r )
except:
示例4: Oseen
# 需要导入模块: from sfepy.base.log import Log [as 别名]
# 或者: from sfepy.base.log.Log import plot_vlines [as 别名]
#.........这里部分代码省略.........
Oseen solver is problem-specific - it requires a Problem instance.
"""
import sfepy.base.plotutils as plu
conf = get_default( conf, self.conf )
fun = get_default( fun, self.fun )
fun_grad = get_default( fun_grad, self.fun_grad )
lin_solver = get_default( lin_solver, self.lin_solver )
status = get_default( status, self.status )
problem = get_default( problem, self.problem )
if problem is None:
msg = 'set solver option "needs_problem_instance" to True!'
raise ValueError(msg)
time_stats = {}
stabil = problem.get_materials()[conf.stabil_mat]
ns, ii = stabil.function.function.get_maps()
variables = problem.get_variables()
update_var = variables.set_data_from_state
make_full_vec = variables.make_full_vec
print 'problem size:'
print ' velocity: %s' % ii['us']
print ' pressure: %s' % ii['ps']
vec_x = vec_x0.copy()
vec_x_prev = vec_x0.copy()
vec_dx = None
if self.log is not None:
self.log.plot_vlines(color='r', linewidth=1.0)
err0 = -1.0
it = 0
while 1:
vec_x_prev_f = make_full_vec( vec_x_prev )
update_var( ns['b'], vec_x_prev_f, ns['u'] )
vec_b = vec_x_prev_f[ii['u']]
b_norm = nla.norm( vec_b, nm.inf )
print '|b|_max: %.12e' % b_norm
vec_x_f = make_full_vec( vec_x )
vec_u = vec_x_f[ii['u']]
u_norm = nla.norm( vec_u, nm.inf )
print '|u|_max: %.2e' % u_norm
stabil.function.set_extra_args(b_norm=b_norm)
stabil.time_update(None, problem.equations, mode='force',
problem=problem)
max_pars = stabil.reduce_on_datas( lambda a, b: max( a, b.max() ) )
print 'stabilization parameters:'
print ' gamma: %.12e' % max_pars[ns['gamma']]
print ' max( delta ): %.12e' % max_pars[ns['delta']]
print ' max( tau ): %.12e' % max_pars[ns['tau']]
if (not are_close( b_norm, 1.0 )) and conf.adimensionalize:
adimensionalize = True
else:
adimensionalize = False
tt = time.clock()
try:
示例5: Newton
# 需要导入模块: from sfepy.base.log import Log [as 别名]
# 或者: from sfepy.base.log.Log import plot_vlines [as 别名]
#.........这里部分代码省略.........
The linear solver for each nonlinear iteration.
iter_hook : function, optional
User-supplied function to call before each iteration.
status : dict-like, optional
The user-supplied object to hold convergence statistics.
Notes
-----
* The optional parameters except `iter_hook` and `status` need
to be given either here or upon `Newton` construction.
* Setting `conf.is_linear == True` means a pre-assembled and possibly
pre-solved matrix. This is mostly useful for linear time-dependent
problems.
"""
conf = get_default(conf, self.conf)
fun = get_default(fun, self.fun)
fun_grad = get_default(fun_grad, self.fun_grad)
lin_solver = get_default(lin_solver, self.lin_solver)
iter_hook = get_default(iter_hook, self.iter_hook)
status = get_default(status, self.status)
ls_eps_a, ls_eps_r = lin_solver.get_tolerance()
eps_a = get_default(ls_eps_a, 1.0)
eps_r = get_default(ls_eps_r, 1.0)
lin_red = conf.eps_a * conf.lin_red
time_stats = {}
vec_x = vec_x0.copy()
vec_x_last = vec_x0.copy()
vec_dx = None
if self.log is not None:
self.log.plot_vlines(color='r', linewidth=1.0)
err = err0 = -1.0
err_last = -1.0
it = 0
while 1:
if iter_hook is not None:
iter_hook(self, vec_x, it, err, err0)
ls = 1.0
vec_dx0 = vec_dx;
while 1:
tt = time.clock()
try:
vec_r = fun(vec_x)
except ValueError:
if (it == 0) or (ls < conf.ls_min):
output('giving up!')
raise
else:
ok = False
else:
ok = True
time_stats['rezidual'] = time.clock() - tt
if ok:
try:
err = nla.norm(vec_r)
except:
示例6: FMinSteepestDescent
# 需要导入模块: from sfepy.base.log import Log [as 别名]
# 或者: from sfepy.base.log.Log import plot_vlines [as 别名]
#.........这里部分代码省略.........
##
# Backtrack (on errors).
alpha = conf.ls0
can_ls = True
while 1:
xit2 = xit - alpha * ofg
aux = fn_of( xit2 )
if self.log is not None:
self.log(of, ofg_norm, alpha, it)
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 self.log is not None:
self.log.plot_vlines(color='g', linewidth=0.5)
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 self.log is not None:
self.log(of, ofg_norm, alpha, it)
if conf.log.plot is not None:
self.log(save_figure=conf.log.plot,
finished=True)
else:
self.log(finished=True)
if status is not None:
status['log'] = self.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
示例7: Newton
# 需要导入模块: from sfepy.base.log import Log [as 别名]
# 或者: from sfepy.base.log.Log import plot_vlines [as 别名]
#.........这里部分代码省略.........
iter_hook : function, optional
User-supplied function to call before each iteration.
status : dict-like, optional
The user-supplied object to hold convergence statistics.
Notes
-----
* The optional parameters except `iter_hook` and `status` need
to be given either here or upon `Newton` construction.
* Setting `conf.problem == 'linear'` means 1 iteration and no
rezidual check!
"""
import sfepy.base.plotutils as plu
conf = get_default(conf, self.conf)
fun = get_default(fun, self.fun)
fun_grad = get_default(fun_grad, self.fun_grad)
lin_solver = get_default(lin_solver, self.lin_solver)
iter_hook = get_default(iter_hook, self.iter_hook)
status = get_default(status, self.status)
ls_eps_a, ls_eps_r = lin_solver.get_tolerance()
eps_a = get_default(ls_eps_a, 1.0)
eps_r = get_default(ls_eps_r, 1.0)
lin_red = conf.eps_a * conf.lin_red
time_stats = {}
vec_x = vec_x0.copy()
vec_x_last = vec_x0.copy()
vec_dx = None
if self.log is not None:
self.log.plot_vlines(color="r", linewidth=1.0)
err = err0 = -1.0
err_last = -1.0
it = 0
while 1:
if iter_hook is not None:
iter_hook(self, vec_x, it, err, err0)
ls = 1.0
vec_dx0 = vec_dx
while 1:
tt = time.clock()
try:
vec_r = fun(vec_x)
except ValueError:
if (it == 0) or (ls < conf.ls_min):
output("giving up!")
raise
else:
ok = False
else:
ok = True
time_stats["rezidual"] = time.clock() - tt
if ok:
try:
err = nla.norm(vec_r)
except:
示例8: Oseen
# 需要导入模块: from sfepy.base.log import Log [as 别名]
# 或者: from sfepy.base.log.Log import plot_vlines [as 别名]
class Oseen(NonlinearSolver):
"""
The Oseen solver for Navier-Stokes equations.
"""
name = 'nls.oseen'
__metaclass__ = SolverMeta
_parameters = [
('stabil_mat', 'str', None, True,
'The name of stabilization material.'),
('adimensionalize', 'bool', False, False,
'If True, adimensionalize the problem (not implemented!).'),
('check_navier_stokes_rezidual', 'bool', False, False,
'If True, check the Navier-Stokes rezidual after the nonlinear loop.'),
('i_max', 'int', 1, False,
'The maximum number of iterations.'),
('eps_a', 'float', 1e-10, False,
'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'),
('eps_r', 'float', 1.0, False,
"""The relative tolerance for the residual, i.e. :math:`||f(x^i)|| /
||f(x^0)||`."""),
('macheps', 'float', nm.finfo(nm.float64).eps, False,
'The float considered to be machine "zero".'),
('lin_red', 'float', 1.0, False,
"""The linear system solution error should be smaller than (`eps_a` *
`lin_red`), otherwise a warning is printed."""),
('lin_precision', 'float or None', None, False,
"""If not None, the linear system solution tolerances are set in each
nonlinear iteration relative to the current residual norm by the
`lin_precision` factor. Ignored for direct linear solvers."""),
]
def __init__(self, conf, problem, **kwargs):
NonlinearSolver.__init__(self, conf, **kwargs)
conf = self.conf
log = get_logging_conf(conf)
conf.log = log = Struct(name='log_conf', **log)
conf.is_any_log = (log.text is not None) or (log.plot is not None)
conf.problem = problem
conf = self.conf
if conf.is_any_log:
self.log = Log([[r'$||r||$'], ['iteration'],
[r'$\gamma$', r'$\max(\delta)$', r'$\max(\tau)$']],
xlabels=['', '', 'all iterations'],
ylabels=[r'$||r||$', 'iteration', 'stabilization'],
yscales=['log', 'linear', 'log'],
is_plot=conf.log.plot is not None,
log_filename=conf.log.text,
formats=[['%.8e'], ['%d'],
['%.8e', '%.8e', '%.8e']])
else:
self.log = None
def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None,
lin_solver=None, status=None, problem=None):
"""
Oseen solver is problem-specific - it requires a Problem instance.
"""
conf = get_default(conf, self.conf)
fun = get_default(fun, self.fun)
fun_grad = get_default(fun_grad, self.fun_grad)
lin_solver = get_default(lin_solver, self.lin_solver)
status = get_default(status, self.status)
problem = get_default(problem, conf.problem,
'`problem` parameter needs to be set!')
time_stats = {}
stabil = problem.get_materials()[conf.stabil_mat]
ns, ii = stabil.function.function.get_maps()
variables = problem.get_variables()
update_var = variables.set_data_from_state
make_full_vec = variables.make_full_vec
output('problem size:')
output(' velocity: %s' % ii['us'])
output(' pressure: %s' % ii['ps'])
vec_x = vec_x0.copy()
vec_x_prev = vec_x0.copy()
vec_dx = None
if self.log is not None:
self.log.plot_vlines(color='r', linewidth=1.0)
err0 = -1.0
it = 0
while 1:
vec_x_prev_f = make_full_vec(vec_x_prev)
update_var(ns['b'], vec_x_prev_f, ns['u'])
vec_b = vec_x_prev_f[ii['u']]
b_norm = nla.norm(vec_b, nm.inf)
#.........这里部分代码省略.........
示例9: FMinSteepestDescent
# 需要导入模块: from sfepy.base.log import Log [as 别名]
# 或者: from sfepy.base.log.Log import plot_vlines [as 别名]
#.........这里部分代码省略.........
# Backtrack (on errors).
alpha = conf.ls0
can_ls = True
while 1:
xit2 = xit - alpha * ofg
aux = fn_of(xit2)
if self.log is not None:
self.log(of, ofg_norm, alpha, it)
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 self.log is not None:
self.log.plot_vlines(color='g', linewidth=0.5)
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 self.log is not None:
self.log(of, ofg_norm, alpha, it)
if conf.log.plot is not None:
self.log(save_figure=conf.log.plot, finished=True)
else:
self.log(finished=True)
if status is not None:
status['log'] = self.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
示例10: Newton
# 需要导入模块: from sfepy.base.log import Log [as 别名]
# 或者: from sfepy.base.log.Log import plot_vlines [as 别名]
class Newton( NonlinearSolver ):
name = 'nls.newton'
def process_conf( conf ):
"""
Missing items are set to default values for a linear problem.
Example configuration, all items::
solver_1 = {
'name' : 'newton',
'kind' : 'nls.newton',
'i_max' : 2,
'eps_a' : 1e-8,
'eps_r' : 1e-2,
'macheps' : 1e-16,
'lin_red' : 1e-2, # Linear system error < (eps_a * lin_red).
'ls_red' : 0.1,
'ls_red_warp' : 0.001,
'ls_on' : 0.99999,
'ls_min' : 1e-5,
'check' : 0,
'delta' : 1e-6,
'is_plot' : False,
'log' : None,
# 'nonlinear' or 'linear' (ignore i_max)
'problem' : 'nonlinear',
}
"""
get = conf.get_default_attr
i_max = get( 'i_max', 1 )
eps_a = get( 'eps_a', 1e-10 )
eps_r = get( 'eps_r', 1.0 )
macheps = get( 'macheps', nm.finfo( nm.float64 ).eps )
lin_red = get( 'lin_red', 1.0 )
ls_red = get( 'ls_red', 0.1 )
ls_red_warp = get( 'ls_red_warp', 0.001 )
ls_on = get( 'ls_on', 0.99999 )
ls_min = get( 'ls_min', 1e-5 )
check = get( 'check', 0 )
delta = get( 'delta', 1e-6)
is_plot = get( 'is_plot', False )
problem = get( 'problem', 'nonlinear' )
log = get_logging_conf(conf)
log = Struct(name='log_conf', **log)
is_any_log = (log.text is not None) or (log.plot is not None)
common = NonlinearSolver.process_conf( conf )
return Struct( **locals() ) + common
process_conf = staticmethod( process_conf )
def __init__(self, conf, **kwargs):
NonlinearSolver.__init__( self, conf, **kwargs )
conf = self.conf
if conf.is_any_log:
self.log = Log([[r'$||r||$'], ['iteration']],
xlabels=['', 'all iterations'],
ylabels=[r'$||r||$', 'iteration'],
yscales=['log', 'linear'],
is_plot=conf.log.plot is not None,
log_filename=conf.log.text,
formats=[['%.8e'], ['%d']])
else:
self.log = None
##
# c: 02.12.2005, r: 04.04.2008
# 10.10.2007, from newton()
def __call__( self, vec_x0, conf = None, fun = None, fun_grad = None,
lin_solver = None, status = None ):
"""setting conf.problem == 'linear' means 1 iteration and no rezidual
check!
"""
import sfepy.base.plotutils as plu
conf = get_default( conf, self.conf )
fun = get_default( fun, self.fun )
fun_grad = get_default( fun_grad, self.fun_grad )
lin_solver = get_default( lin_solver, self.lin_solver )
status = get_default( status, self.status )
time_stats = {}
vec_x = vec_x0.copy()
vec_x_last = vec_x0.copy()
vec_dx = None
if self.log is not None:
self.log.plot_vlines(color='r', linewidth=1.0)
err0 = -1.0
err_last = -1.0
it = 0
while 1:
ls = 1.0
#.........这里部分代码省略.........