本文整理汇总了Python中warnings.showwarning函数的典型用法代码示例。如果您正苦于以下问题:Python showwarning函数的具体用法?Python showwarning怎么用?Python showwarning使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了showwarning函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: sigma_envelopes
def sigma_envelopes(self, steps = 1):
"""
Envelopes and twiss-functions from sigma-matrix mathod
"""
# initials
bx,ax,gx,epsx = PARAMS['twiss_x_i']()
by,ay,gy,epsy = PARAMS['twiss_y_i']()
bz,az,gz,epsz = PARAMS['twiss_z_i']()
twv0 = NP.array([bx,ax,gx,by,ay,gy,bz,az,gz]) # twiss vector IN lattice
sg0 = Sigma(twv0,epsx,epsy,epsz) # sigma object IN lattice
# sigma envelopes as function of distance s
sigma_fun = Functions(('s','bx','ax','gax','by','ay','gy','bz','az','gz'))
for node in iter(self): # loop nodes
# sigma-matrices for a single node
sigmas = node.sigma_beam(steps = steps, sg = sg0)
# prep plot list of ftn's
for sg,s in sigmas:
v = sg.twiss() # twiss from Sigma object
flist = v.tolist()
sigma_fun.append(s,tuple(flist))
sg0 = sg # loop back nodes
# aperture check
if FLAGS['useaper']:
nbsigma = PARAMS['nbsigma']
if node.aperture != None:
aperture = node.aperture
sigx, sigxp, sigy, sigyp = node['sigxy']
si,sm,sf = node.position
if(aperture < nbsigma*sigx or aperture < nbsigma*sigy):
warnings.showwarning(
'{} sigma aperture hit @ s={:.1f} [m]'.format(nbsigma,sm),
UserWarning,'lattice.py',
'sigma_functions()')
return sigma_fun
开发者ID:wdklotz,项目名称:simulinac,代码行数:35,代码来源:lattice.py
示例2: __init__
def __init__(self, pin=None, pull_up=False):
if pin in (2, 3) and not pull_up:
raise InputDeviceError(
'GPIO pins 2 and 3 are fitted with physical pull up '
'resistors; you cannot initialize them with pull_up=False'
)
# _pull_up should be assigned first as __repr__ relies upon it to
# support the case where __repr__ is called during debugging of an
# instance that has failed to initialize (due to an exception in the
# super-class __init__)
self._pull_up = pull_up
super(InputDevice, self).__init__(pin)
self._active_edge = GPIO.FALLING if pull_up else GPIO.RISING
self._inactive_edge = GPIO.RISING if pull_up else GPIO.FALLING
self._active_state = GPIO.LOW if pull_up else GPIO.HIGH
self._inactive_state = GPIO.HIGH if pull_up else GPIO.LOW
pull = GPIO.PUD_UP if pull_up else GPIO.PUD_DOWN
try:
# NOTE: catch_warnings isn't thread-safe but hopefully no-one's
# messing around with GPIO init within background threads...
with warnings.catch_warnings(record=True) as w:
GPIO.setup(pin, GPIO.IN, pull)
# The only warning we want to squash is a RuntimeWarning that is
# thrown when setting pins 2 or 3. Anything else should be replayed
for warning in w:
if warning.category != RuntimeWarning or pin not in (2, 3):
warnings.showwarning(
warning.message, warning.category, warning.filename,
warning.lineno, warning.file, warning.line
)
except:
self.close()
raise
开发者ID:tjguk,项目名称:python-gpiozero,代码行数:34,代码来源:input_devices.py
示例3: Normal
def Normal(**kwargs):
'''
Devuelve la instancia de Union de tipo JOIN
parametros => diccionario de tipo {'alias':ClaseOTD}
'''
import warnings
#advertencia de componente deprecado
warnings.showwarning('Union.Normal(): deprecado, recurrir directamente al constructor de la clase!'
, DeprecationWarning
, __file__
, 0
)
# si el parametro NO es un diccionario
if type(kwargs) is not dict:
raise Exception(Union.NOMBRE_CLASE
+ ".Normal: El parametro se debe pasar "
+ "{'alias':ClaseOTD}!"
)
return Union(cTipo = Union.NORMAL, **kwargs)
开发者ID:cdanielpy,项目名称:MoziAPI,代码行数:26,代码来源:union.py
示例4: test2
def test2(input_file):
print('---------------------------------TEST2')
with open(input_file,'r') as fileobject:
try:
indat = yaml.load(fileobject)
except Exception as ex:
warnings.showwarning(
'InputError: {} - STOP'.format(str(ex)),
UserWarning,
'lattice_generator.py',
'factory()',
)
sys.exit(1)
fileobject.close()
ky = indat.keys()
for k in ky:
print()
print(k)
klist = indat[k]
print(klist)
if not klist: continue
nlist = flatten(klist)
if k == 'LATTICE':
N = nlist[0]
plist = nlist[1:]
qlist = plist.copy()
for i in range(N-1):
qlist += plist
nlist=qlist
print(nlist)
开发者ID:wdklotz,项目名称:simulinac,代码行数:30,代码来源:lattice_generator.py
示例5: __init__
def __init__(self, pin=None, active_high=True, initial_value=False):
self._active_high = active_high
super(OutputDevice, self).__init__(pin)
self._active_state = GPIO.HIGH if active_high else GPIO.LOW
self._inactive_state = GPIO.LOW if active_high else GPIO.HIGH
try:
# NOTE: catch_warnings isn't thread-safe but hopefully no-one's
# messing around with GPIO init within background threads...
with warnings.catch_warnings(record=True) as w:
# This is horrid, but we can't specify initial=None with setup
if initial_value is None:
GPIO.setup(pin, GPIO.OUT)
else:
GPIO.setup(pin, GPIO.OUT, initial=
[self._inactive_state, self._active_state][bool(initial_value)])
GPIO.setup(pin, GPIO.OUT)
# The only warning we want to squash is a RuntimeWarning that is
# thrown when setting pins 2 or 3. Anything else should be replayed
for warning in w:
if warning.category != RuntimeWarning or pin not in (2, 3):
warnings.showwarning(
warning.message, warning.category, warning.filename,
warning.lineno, warning.file, warning.line
)
except:
self.close()
raise
开发者ID:calufrax,项目名称:python-gpiozero,代码行数:27,代码来源:output_devices.py
示例6: test_warnings
def test_warnings(self):
with warnings.catch_warnings():
logging.captureWarnings(True)
try:
warnings.filterwarnings("always", category=UserWarning)
file = io.StringIO()
h = logging.StreamHandler(file)
logger = logging.getLogger("py.warnings")
logger.addHandler(h)
warnings.warn("I'm warning you...")
logger.removeHandler(h)
s = file.getvalue()
h.close()
self.assertTrue(s.find("UserWarning: I'm warning you...\n") > 0)
#See if an explicit file uses the original implementation
file = io.StringIO()
warnings.showwarning("Explicit", UserWarning, "dummy.py", 42,
file, "Dummy line")
s = file.getvalue()
file.close()
self.assertEqual(s,
"dummy.py:42: UserWarning: Explicit\n Dummy line\n")
finally:
logging.captureWarnings(False)
开发者ID:henrywoo,项目名称:Python3.1.3-Linux,代码行数:25,代码来源:test_logging.py
示例7: ignore_deprecation_warnings
def ignore_deprecation_warnings():
with warnings.catch_warnings(record=True) as warning_list: # catch all warnings
yield
# rethrow all warnings that were not DeprecationWarnings
for w in warning_list:
if not issubclass(w.category, DeprecationWarning):
warnings.showwarning(message=w.message, category=w.category, filename=w.filename, lineno=w.lineno, file=w.file, line=w.line)
开发者ID:100Shapes,项目名称:wagtail,代码行数:8,代码来源:utils.py
示例8: new_func
def new_func(*args, **kwargs):
warnings.showwarning(
"Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning,
filename=func.__code__.co_filename,
lineno=func.__code__.co_firstlineno + 1
)
return func(*args, **kwargs)
开发者ID:3c7,项目名称:PyMISP,代码行数:8,代码来源:__init__.py
示例9: _handle_caught_warnings
def _handle_caught_warnings(caught_warnings, filename):
logger = logging.getLogger(__name__)
for warning in caught_warnings:
if warning.category == PILImage.DecompressionBombWarning:
logger.info('PILImage reported a possible DecompressionBomb'
' for file {}'.format(filename))
else:
warnings.showwarning(warning.message, warning.category,
warning.filename, warning.lineno)
开发者ID:t-animal,项目名称:sigal,代码行数:9,代码来源:image.py
示例10: _read_config
def _read_config(rcfile):
"""Read configuration information from a file"""
global config
defaults = {'enable_deprecation_warning': str(True),
'ncpus': str(multiprocessing.cpu_count()),
'qindenton_url': 'http://virbo.org/ftp/QinDenton/hour/merged/latest/WGhour-latest.d.zip',
'omni2_url': 'http://virbo.org/ftp/OMNI/OMNI2/merged/latest/OMNI_OMNI2-latest.cdf.zip',
'leapsec_url': 'http://maia.usno.navy.mil/ser7/tai-utc.dat',
'psddata_url': 'http://spacepy.lanl.gov/repository/psd_dat.sqlite',
'support_notice': str(True),
'apply_plot_styles': str(True),
}
#Functions to cast a config value; if not specified, value is a string
str2bool = lambda x: x.lower() in ('1', 'yes', 'true', 'on')
caster = {'enable_deprecation_warning': str2bool,
'ncpus': int,
'support_notice': str2bool,
'apply_plot_styles': str2bool,
}
#SafeConfigParser deprecated in 3.2. And this is hideous, but...
if hasattr(ConfigParser, 'SafeConfigParser'):
cp_class = ConfigParser.SafeConfigParser
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings(
'always', 'The SafeConfigParser class has been renamed.*',
DeprecationWarning,
'^spacepy$') #configparser lies about source of warnings
ConfigParser.SafeConfigParser()
for this_w in w:
if isinstance(this_w.message, DeprecationWarning):
cp_class = ConfigParser.ConfigParser
else:
warnings.showwarning(this_w.message, this_w.category,
this_w.filename, this_w.lineno,
this_w.file, this_w.line)
else:
cp_class = ConfigParser.ConfigParser
cp = cp_class(defaults)
try:
successful = cp.read([rcfile])
except ConfigParser.Error:
successful = []
if successful: #New file structure
config = dict(cp.items('spacepy'))
else: #old file structure, wipe it out
cp = cp_class()
cp.add_section('spacepy')
with open(rcfile, 'w') as cf:
cp.write(cf)
for k in defaults:
if not k in config:
config[k] = defaults[k]
_write_defaults(rcfile, defaults)
for k in caster:
config[k] = caster[k](config[k])
开发者ID:spacepy,项目名称:spacepy,代码行数:55,代码来源:__init__.py
示例11: ready
def ready(self):
""" Performs an DB engine check, as we maintain some engine specific queries. """
if (connection.vendor not in settings.DSMR_SUPPORTED_DB_VENDORS):
# Temporary for backwards compatibility
warnings.showwarning(
_(
'Unsupported database engine "{}" active, '
'some features might not work properly'.format(connection.vendor)
),
RuntimeWarning, __file__, 0
)
开发者ID:dennissiemensma,项目名称:dsmr-reader,代码行数:11,代码来源:apps.py
示例12: get_mandatory
def get_mandatory(attributes,key,item):
try:
res = attributes[key]
except KeyError:
warnings.showwarning(
'InputError: Mandatory attribute "{}" missing for element "{}" - STOP'.format(key,item),
UserWarning,
'lattice_generator.py',
'get_mandatory()',
)
sys.exit(1)
return res
开发者ID:wdklotz,项目名称:simulinac,代码行数:12,代码来源:lattice_generator.py
示例13: _read_image
def _read_image(file_path):
with warnings.catch_warnings(record=True) as caught_warnings:
im = PILImage.open(file_path)
for warning in caught_warnings:
if warning.category == PILImage.DecompressionBombWarning:
logger = logging.getLogger(__name__)
logger.info('PILImage reported a possible DecompressionBomb'
' for file {}'.format(file_path))
else:
warnings.showwarning(warning.message, warning.category,
warning.filename, warning.lineno)
return im
开发者ID:saimn,项目名称:sigal,代码行数:13,代码来源:image.py
示例14: __init__
def __init__(self, pin=None):
super(OutputDevice, self).__init__(pin)
# NOTE: catch_warnings isn't thread-safe but hopefully no-one's messing
# around with GPIO init within background threads...
with warnings.catch_warnings(record=True) as w:
GPIO.setup(pin, GPIO.OUT)
# The only warning we want to squash is a RuntimeWarning that is thrown
# when setting pins 2 or 3. Anything else should be replayed
for warning in w:
if warning.category != RuntimeWarning or pin not in (2, 3):
warnings.showwarning(
warning.message, warning.category, warning.filename,
warning.lineno, warning.file, warning.line
)
开发者ID:TheRinger,项目名称:python-gpiozero,代码行数:14,代码来源:output_devices.py
示例15: twiss_envelopes
def twiss_envelopes(self,steps=1):
"""
Calulate envelopes from initial twiss-vector with beta-matrices
"""
twfun = Functions(('s','bx','ax','gx','by','ay','gy','bz','az','gz'))
bx,ax,gx,epsx = PARAMS['twiss_x_i']()
by,ay,gy,epsy = PARAMS['twiss_y_i']()
bz,az,gz,epsz = PARAMS['twiss_z_i']()
twv0 = NP.array([bx,ax,gx,by,ay,gy,bz,az,gz]) # initial
B_matrix = NP.eye(9) # cumulated beta-matrix
for node in iter(self):
slices = node.make_slices(anz = steps)
means = []
s,sm,sf = node.position
for slice in slices:
beta_matrix = slice.beta_matrix()
B_matrix = NP.dot(beta_matrix,B_matrix)
twv = NP.dot(B_matrix,twv0) # track twiss-vector
s += slice.length
twfun.append(s,tuple(twv))
bx = twv[Ktw.bx]; ax = twv[Ktw.ax]; gx = twv[Ktw.gx]
by = twv[Ktw.by]; ay = twv[Ktw.ay]; gy = twv[Ktw.gy]
sigxy = (*sigmas(ax,bx,epsx),*sigmas(ay,by,epsy))
means.append(sigxy)
# means = NP.array(means)
means = NP.mean(means,axis=0)
# each node has its tuple of average sigmas
node['sigxy'] = tuple(means)
# aperture check
if FLAGS['useaper']:
nbsigma = PARAMS['nbsigma']
if node.aperture != None:
aperture = node.aperture
sigx, sigxp, sigy, sigyp = node['sigxy']
if(aperture < nbsigma*sigx or aperture < nbsigma*sigy):
warnings.showwarning(
'{} sigma aperture hit @ s={:.1f} [m]'.format(nbsigma,sm),
UserWarning,'lattice.py',
'twiss_functions()')
return twfun
开发者ID:wdklotz,项目名称:simulinac,代码行数:41,代码来源:lattice.py
示例16: test_import_error_in_warning_logging
def test_import_error_in_warning_logging():
"""
Regression test for https://github.com/astropy/astropy/issues/2671
This test actually puts a goofy fake module into ``sys.modules`` to test
this problem.
"""
class FakeModule(object):
def __getattr__(self, attr):
raise ImportError('_showwarning should ignore any exceptions '
'here')
log.enable_warnings_logging()
sys.modules['<test fake module>'] = FakeModule()
try:
warnings.showwarning(AstropyWarning('Regression test for #2671'),
AstropyWarning, '<this is only a test>', 1)
finally:
del sys.modules['<test fake module>']
开发者ID:rajul,项目名称:astropy,代码行数:21,代码来源:test_logger.py
示例17: instanciate_element
#.........这里部分代码省略.........
if fname not in PARAMS:
PARAMS[fname] = SFdata(fname,EzPeak=EzPeak)
EzAvg = PARAMS[fname].EzAvg
instance = ELM.RFG(EzAvg=EzAvg,PhiSoll=PhiSoll,fRF=freq,label=label,gap=gap,mapping=mapping,dWf=dWf,aperture=aperture,SFdata=PARAMS[fname])
pass
else:
EzPeak = EzAvg
instance = ELM.RFG(EzAvg=EzAvg,PhiSoll=PhiSoll,fRF=freq,label=label,gap=gap,mapping=mapping,dWf=dWf,aperture=aperture)
instance['EzAvg'] = EzAvg
instance['EzPeak'] = EzPeak
instance['label'] = label
instance['PhiSoll'] = PhiSoll
instance['freq'] = freq
instance['gap'] = gap
instance['aperture'] = aperture
instance['dWf'] = dWf
instance['mapping'] = mapping
elif key == 'RFC':
label = attributes['ID']
PhiSoll = radians(get_mandatory(attributes,"PhiSync",label))
freq = float(get_mandatory(attributes,"freq",label))
gap = get_mandatory(attributes,'gap',label)
aperture = get_mandatory(attributes,'aperture',label)
dWf = FLAGS['dWf']
length = get_mandatory(attributes,'length',label)
mapping = PARAMS['mapping']
EzPeak = get_mandatory(attributes,"EzPeak",label)
EzAvg = get_mandatory(attributes,"EzAvg",label)
if mapping == None:
mapping = 't3d'
EzPeak = EzAvg
if mapping == 'ttf' or mapping == 'dyn' or mapping == 'oxal': # SF-data
fname = get_mandatory(attributes,"SFdata",label)
if fname not in PARAMS:
PARAMS[fname] = SFdata(fname,EzPeak=EzPeak)
EzAvg = PARAMS[fname].EzAvg
instance = ELM.RFC(EzAvg=EzAvg,label=label,PhiSoll=PhiSoll,fRF=freq,gap=gap,aperture=aperture,dWf=dWf,length=length,mapping=mapping,SFdata=PARAMS[fname])
pass
else:
EzPeak = EzAvg
instance = ELM.RFC(EzAvg=EzAvg,label=label,PhiSoll=PhiSoll,fRF=freq,gap=gap,aperture=aperture,dWf=dWf,length=length,mapping=mapping)
instance['EzAvg'] = EzAvg
instance['EzPeak'] = EzPeak
instance['label'] = label
instance['PhiSoll'] = PhiSoll
instance['freq'] = freq
instance['gap'] = gap
instance['aperture'] = aperture
instance['dWf'] = dWf
instance['length'] = length
instance['mapping'] = mapping
elif key == 'GAP':
label = attributes['ID']
gap = get_mandatory(attributes,'gap',label)
EzAvg = get_mandatory(attributes,"EzAvg",label)
PhiSoll = radians(get_mandatory(attributes,"PhiSync",label))
freq = float(get_mandatory(attributes,"freq",label))
dWf = FLAGS['dWf']
aperture = get_mandatory(attributes,'aperture',label)
instance = ELM.GAP(EzAvg=EzAvg,PhiSoll=PhiSoll,fRF=freq,label=label,gap=gap,dWf=dWf,aperture=aperture)
instance['EzAvg'] = EzAvg
instance['EzPeak'] = EzAvg
instance['label'] = label
instance['gap'] = gap
instance['PhiSoll'] = PhiSoll
instance['freq'] = freq
instance['dWf'] = dWf
elif key == 'MRK':
label = attributes['ID']
action = get_mandatory(attributes,'action',label)
if 'scatter' == action:
prefix = attributes['prefix'] if 'prefix' in attributes else ''
abszisse = attributes['abscissa'] if 'abscissa' in attributes else 'z'
ordinate = attributes['ordinate'] if 'ordinate' in attributes else 'zp'
instance = MRK.PoincareAction(label=label, prefix=prefix, abszisse=abszisse, ordinate=ordinate)
instance['prefix'] = prefix
instance['abszisse'] = abszisse
instance['ordinate'] = ordinate
else:
instance = ELM.MRK(label=label,action=action)
instance['label'] = label
instance['action'] = action
else:
warnings.showwarning(
'InputError: Unknown element type encountered: "{}" - STOP'.format(key),
UserWarning,
'lattice_generator.py',
'instanciate_element()',
)
sys.exit(1)
try:
sec = attributes['sec'] #can fail because sections are not mandatory
except:
pass
else:
instance.section = sec
return (label,instance)
开发者ID:wdklotz,项目名称:simulinac,代码行数:101,代码来源:lattice_generator.py
示例18: __init__
except ValueError as e:
raise e
f.close()
default_settings.update(**settings_from_file)
class Settings:
def __init__(self):
for k, v in default_settings.items():
setattr(self, k, v)
settings = Settings()
if not settings.REMOTE_REPO:
warnings.showwarning(
'Missed remote repository parameter',
UserWarning,
settings_path,
1
)
sys.exit(1)
if not getattr(settings, 'REPO_PATH', None):
git_name = settings.REMOTE_REPO.split('/')[-1]
repo_name = git_name.split('.')[0]
settings.REPO_PATH = os.path.join(settings.PROCYON_PATH, repo_name)
sys.path.append(settings.REPO_PATH)
开发者ID:Gr1N,项目名称:procyon,代码行数:30,代码来源:__init__.py
示例19: solve_mbar_once
def solve_mbar_once(u_kn_nonzero, N_k_nonzero, f_k_nonzero, method="hybr", tol=1E-12, options=None):
"""Solve MBAR self-consistent equations using some form of equation solver.
Parameters
----------
u_kn_nonzero : np.ndarray, shape=(n_states, n_samples), dtype='float'
The reduced potential energies, i.e. -log unnormalized probabilities
for the nonempty states
N_k_nonzero : np.ndarray, shape=(n_states), dtype='int'
The number of samples in each state for the nonempty states
f_k_nonzero : np.ndarray, shape=(n_states), dtype='float'
The reduced free energies for the nonempty states
method : str, optional, default="hybr"
The optimization routine to use. This can be any of the methods
available via scipy.optimize.minimize() or scipy.optimize.root().
tol : float, optional, default=1E-14
The convergance tolerance for minimize() or root()
verbose: bool
Whether to print information about the solution method.
options: dict, optional, default=None
Optional dictionary of algorithm-specific parameters. See
scipy.optimize.root or scipy.optimize.minimize for details.
Returns
-------
f_k : np.ndarray
The converged reduced free energies.
results : dict
Dictionary containing entire results of optimization routine, may
be useful when debugging convergence.
Notes
-----
This function requires that N_k_nonzero > 0--that is, you should have
already dropped all the states for which you have no samples.
Internally, this function works in a reduced coordinate system defined
by subtracting off the first component of f_k and fixing that component
to be zero.
For fast but precise convergence, we recommend calling this function
multiple times to polish the result. `solve_mbar()` facilitates this.
"""
u_kn_nonzero, N_k_nonzero, f_k_nonzero = validate_inputs(u_kn_nonzero, N_k_nonzero, f_k_nonzero)
f_k_nonzero = f_k_nonzero - f_k_nonzero[0] # Work with reduced dimensions with f_k[0] := 0
u_kn_nonzero = precondition_u_kn(u_kn_nonzero, N_k_nonzero, f_k_nonzero)
pad = lambda x: np.pad(x, (1, 0), mode='constant') # Helper function inserts zero before first element
unpad_second_arg = lambda obj, grad: (obj, grad[1:]) # Helper function drops first element of gradient
# Create objective functions / nonlinear equations to send to scipy.optimize, fixing f_0 = 0
grad = lambda x: mbar_gradient(u_kn_nonzero, N_k_nonzero, pad(x))[1:] # Objective function gradient
grad_and_obj = lambda x: unpad_second_arg(*mbar_objective_and_gradient(u_kn_nonzero, N_k_nonzero, pad(x))) # Objective function gradient and objective function
hess = lambda x: mbar_hessian(u_kn_nonzero, N_k_nonzero, pad(x))[1:][:, 1:] # Hessian of objective function
with warnings.catch_warnings(record=True) as w:
if method in ["L-BFGS-B", "dogleg", "CG", "BFGS", "Newton-CG", "TNC", "trust-ncg", "SLSQP"]:
if method in ["L-BFGS-B", "CG"]:
hess = None # To suppress warning from passing a hessian function.
results = scipy.optimize.minimize(grad_and_obj, f_k_nonzero[1:], jac=True, hess=hess, method=method, tol=tol, options=options)
f_k_nonzero = pad(results["x"])
elif method == 'adaptive':
results = adaptive(u_kn_nonzero, N_k_nonzero, f_k_nonzero, tol=tol, options=options)
f_k_nonzero = results # they are the same for adaptive, until we decide to return more.
else:
results = scipy.optimize.root(grad, f_k_nonzero[1:], jac=hess, method=method, tol=tol, options=options)
f_k_nonzero = pad(results["x"])
# If there were runtime warnings, show the messages
if len(w) > 0:
can_ignore = True
for warn_msg in w:
if "Unknown solver options" in str(warn_msg.message):
continue
warnings.showwarning(warn_msg.message, warn_msg.category,
warn_msg.filename, warn_msg.lineno, warn_msg.file, "")
can_ignore = False # If any warning is not just unknown options, can ]not skip check
if not can_ignore:
# Ensure MBAR solved correctly
w_nk_check = mbar_W_nk(u_kn_nonzero, N_k_nonzero, f_k_nonzero)
check_w_normalized(w_nk_check, N_k_nonzero)
print("MBAR weights converged within tolerance, despite the SciPy Warnings. Please validate your results.")
return f_k_nonzero, results
开发者ID:choderalab,项目名称:pymbar,代码行数:83,代码来源:mbar_solvers.py
示例20: factory
#.........这里部分代码省略.........
sec_list = []
use_sections = True
try: ## can fail because sections are not mandatory
sec_list = in_data['SECTIONS']
sec_list = flatten(sec_list)
except:
use_sections = False
PARAMS['sections'] = sec_list
FLAGS['sections'] = use_sections
return sec_list
# --------
def read_parameters(in_data):
""" returns a dict of parameters """
parameter_list = in_data['PARAMETERS']
parameters = liofd2d(parameter_list)
if 'Tkin' in parameters: PARAMS['injection_energy'] = parameters['Tkin']
if 'phi_sync' in parameters: PARAMS['phisoll'] = parameters['phi_sync']
if 'gap' in parameters: PARAMS['gap'] = parameters['gap']
if 'cav_len' in parameters: PARAMS['cavity_laenge'] = parameters['cav_len']
if 'ql' in parameters: PARAMS['ql'] = parameters['ql']
if 'windings' in parameters: PARAMS['nbwindgs'] = parameters['windings']
if 'nbsigma' in parameters: PARAMS['nbsigma'] = parameters['nbsigma']
if 'aperture' in parameters: PARAMS['aperture'] = parameters['aperture']
if 'emitx_i' in parameters: PARAMS['emitx_i'] = parameters['emitx_i']
if 'emity_i' in parameters: PARAMS['emity_i'] = parameters['emity_i']
if 'betax_i' in parameters: PARAMS['betax_i'] = parameters['betax_i']
if 'betay_i' in parameters: PARAMS['betay_i'] = parameters['betay_i']
if 'alfax_i' in parameters: PARAMS['alfax_i'] = parameters['alfax_i']
if 'alfay_i' in parameters: PARAMS['alfay_i'] = parameters['alfay_i']
if 'mapping' in parameters: PARAMS['mapping'] = parameters['mapping']
if 'DT2T' in parameters: PARAMS['DT2T'] = parameters['DT2T']
if 'lattvers' in parameters: PARAMS['lattice_version'] = parameters['lattvers']
return parameters
#--------
def get_flattened_lattice_list(in_data):
""" read_and_flatten lattice from (in_data)."""
lattice_list = in_data['LATTICE']
lattice_list = flatten(lattice_list)
N = lattice_list[0] # Duplikator
plist = lattice_list[1:]
qlist = plist.copy()
for i in range(N-1):
qlist += plist
lattice_list=qlist
return lattice_list
#--------
def make_lattice(latticeList,in_data):
""" instanciate all elements from flattened node list"""
lattice = Lattice()
DEBUG_OFF('make_lattice for sollteilchen\n'+PARAMS['sollteilchen'].string())
elements = read_elements(in_data)
for ID in lattice_list:
element = elements[ID]
element = liofd2d(element)
elementClass = element['type']
elmItem = (elementClass,element)
# !!INSTANCIATE!!
(label,instance) = instanciate_element(elmItem)
section = instance.section if FLAGS['sections'] else '*'
DEBUG_MODULE('instance {} {} {}'.format(label,instance,section))
# add element instance to lattice
if isinstance(instance,ELM._Node):
lattice.add_element(instance)
# elif isinstance(instance,Lattice):
# lattice.concat(instance) # concatenate partial with lattice
return lattice # the complete lattice
## factory body --------
SUMMARY['input file'] = PARAMS['input_file'] = input_file
with open(input_file,'r') as fileobject:
try:
in_data = yaml.load(fileobject)
except Exception as ex:
warnings.showwarning(
'InputError: {} - STOP'.format(str(ex)),
UserWarning,
'lattice_generator.py',
'factory()',
)
sys.exit(1)
fileobject.close()
read_flags(in_data)
read_sections(in_data)
read_parameters(in_data)
DEBUG_MODULE('PARAMS after read_parameters()',PARAMS)
# lattice_list is a flat list of node IDs
lattice_list = get_flattened_lattice_list(in_data)
DEBUG_MODULE('latticeList in factory()',lattice_list)
# __call__ sollteilchen energy
PARAMS['sollteilchen'](tkin=PARAMS['injection_energy'])
lattice = make_lattice(lattice_list,in_data)
# DEBUG_MODULE('lattice_generator >>\n',lattice.string())
SUMMARY['lattice length [m]'] = PARAMS['lattice_length'] = lattice.length
DEBUG_OFF('SUMMARY in factory()',SUMMARY)
# end of factory(...)
return lattice
开发者ID:wdklotz,项目名称:simulinac,代码行数:101,代码来源:lattice_generator.py
注:本文中的warnings.showwarning函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论