本文整理汇总了Python中scipy.any函数的典型用法代码示例。如果您正苦于以下问题:Python any函数的具体用法?Python any怎么用?Python any使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了any函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _apply_percolation
def _apply_percolation(self, inv_val):
r"""
Determine which pores and throats are invaded at a given applied
capillary pressure. This method is called by ``run``.
"""
# Generate a list containing boolean values for throat state
Tinvaded = self['throat.entry_pressure'] <= inv_val
# Add residual throats, if any, to list of invaded throats
Tinvaded = Tinvaded + self['throat.residual']
# Find all pores that can be invaded at specified pressure
[pclusters, tclusters] = self._net.find_clusters2(mask=Tinvaded,
t_labels=True)
# Identify clusters connected to inlet sites
inv_clusters = sp.unique(pclusters[self['pore.inlets']])
inv_clusters = inv_clusters[inv_clusters >= 0]
# Find pores on the invading clusters
pmask = np.in1d(pclusters, inv_clusters)
# Store current applied pressure in newly invaded pores
pinds = (self['pore.inv_Pc'] == sp.inf) * (pmask)
self['pore.inv_Pc'][pinds] = inv_val
# Find throats on the invading clusters
tmask = np.in1d(tclusters, inv_clusters)
# Store current applied pressure in newly invaded throats
tinds = (self['throat.inv_Pc'] == sp.inf) * (tmask)
self['throat.inv_Pc'][tinds] = inv_val
# Set residual pores and throats, if any, to invaded
if sp.any(self['pore.residual']):
self['pore.inv_Pc'][self['pore.residual']] = 0
if sp.any(self['throat.residual']):
self['throat.inv_Pc'][self['throat.residual']] = 0
示例2: _check_bounds
def _check_bounds(self,x_new):
# If self.bounds_error = 1, we raise an error if any x_new values
# fall outside the range of x. Otherwise, we return an array indicating
# which values are outside the boundary region.
# !! Needs some work for multi-dimensional x !!
below_bounds = less(x_new,self.x[0])
above_bounds = greater(x_new,self.x[-1])
# Note: sometrue has been redefined to handle length 0 arrays
# !! Could provide more information about which values are out of bounds
# RHC -- Changed these ValueErrors to PyDSTool_BoundsErrors
if self.bounds_error and any(sometrue(below_bounds)):
## print "Input:", x_new
## print "Bound:", self.x[0]
## print "Difference input - bound:", x_new-self.x[0]
raise PyDSTool_BoundsError, " A value in x_new is below the"\
" interpolation range."
if self.bounds_error and any(sometrue(above_bounds)):
## print "Input:", x_new
## print "Bound:", self.x[-1]
## print "Difference input - bound:", x_new-self.x[-1]
raise PyDSTool_BoundsError, " A value in x_new is above the"\
" interpolation range."
# !! Should we emit a warning if some values are out of bounds.
# !! matlab does not.
out_of_bounds = logical_or(below_bounds,above_bounds)
return out_of_bounds
示例3: computePCsPython
def computePCsPython(out_dir,k,bfile,ffile):
""" reading in """
RV = plink_reader.readBED(bfile,useMAFencoding=True)
X = np.ascontiguousarray(RV['snps'])
""" normalizing markers """
print('Normalizing SNPs...')
p_ref = X.mean(axis=0)/2.
X -= 2*p_ref
with warnings.catch_warnings():
warnings.simplefilter("ignore")
X /= sp.sqrt(2*p_ref*(1-p_ref))
hasNan = sp.any(sp.isnan(X),axis=0)
if sp.any(hasNan):
print(('%d SNPs have a nan entry. Exluding them for computing the covariance matrix.'%hasNan.sum()))
X = X[:,~hasNan]
""" computing prinicipal components """
U,S,Vt = ssl.svds(X,k=k)
U -= U.mean(0)
U /= U.std(0)
U = U[:,::-1]
""" saving to output """
np.savetxt(ffile, U, delimiter='\t',fmt='%.6f')
示例4: crop_pts
def crop_pts(coords, box):
r'''
Drop all points lying outside the box
Parameters
----------
coords : array_like
An Np x ndims array off [x,y,z] coordinates
box : array_like
A 2 x ndims array of diametrically opposed corner coordintes
Returns
-------
coords : array_like
Inputs coordinates with outliers removed
Notes
-----
This needs to be made more general so that an arbitray cuboid with any
orientation can be supplied, using Np x 8 points
'''
coords = coords[_sp.any(coords < box[0], axis=1)]
coords = coords[_sp.any(coords > box[1], axis=1)]
return coords
示例5: process_file
def process_file(self, file_ind) :
params = self.params
file_middle = params['file_middles'][file_ind]
input_fname = (params['input_root'] + file_middle +
params['input_end'])
sub_input_fname = (params['subtracted_input_root'] + file_middle
+ params['input_end'])
output_fname = (params['output_root']
+ file_middle + params['output_end'])
sub_output_fname = (params['subtracted_output_root']
+ file_middle + params['output_end'])
Writer = fitsGBT.Writer(feedback=self.feedback)
SubWriter = fitsGBT.Writer(feedback=self.feedback)
# Read in the data, and loop over data blocks.
Reader = fitsGBT.Reader(input_fname, feedback=self.feedback)
SubReader = fitsGBT.Reader(sub_input_fname, feedback=self.feedback)
if (sp.any(Reader.scan_set != SubReader.scan_set)
or sp.any(Reader.IF_set != SubReader.IF_set)) :
raise ce.DataError("IFs and scans don't match signal subtracted"
" data.")
# Get the number of scans if asked for all of them.
scan_inds = params['scans']
if len(scan_inds) == 0 or scan_inds is None :
scan_inds = range(len(Reader.scan_set))
if_inds = params['IFs']
if len(if_inds) == 0 or scan_inds is None :
if_inds = range(len(Reader.IF_set))
if self.feedback > 1 :
print "New flags each block:",
# Loop over scans and IFs
for thisscan in scan_inds :
for thisIF in if_inds :
Data = Reader.read(thisscan, thisIF)
SubData = SubReader.read(thisscan, thisIF)
n_flags = ma.count_masked(Data.data)
# Now do the flagging.
flag(Data, SubData, params['thres'])
Data.add_history("Reflaged for outliers.", ("Used file: "
+ utils.abbreviate_file_path(sub_input_fname),))
SubData.add_history("Reflaged for outliers.")
Writer.add_data(Data)
SubWriter.add_data(SubData)
# Report the numbe of new flags.
n_flags = ma.count_masked(Data.data) - n_flags
if self.feedback > 1 :
print n_flags,
if self.feedback > 1 :
print ''
# Finally write the data back to file.
utils.mkparents(output_fname)
utils.mkparents(sub_output_fname)
Writer.write(output_fname)
SubWriter.write(sub_output_fname)
示例6: updateData
def updateData(self, array = Array(sp.zeros((0,2)),scale=[0,0], Type = 0), action = 1, Type = None):
""" Запис в тимчасовий файл даних з масиву
action = {-1, 0, 1, 2}
-1 : undo
0 : reset
1 : add
"""
if Type is None:
if sp.any(array):
Type = array.Type
#print(sp.shape(array),array.Type)
emit = False
#print(len(self.dataStack[Type]),action)
# Запис в історію
if action == 1:
if sp.any(array) and sp.shape(array)[1] == 2 and sp.shape(array)[0] > 1:
self.dataStack[Type].append(array)
emit = True
else: print('updateData: arrayError',sp.any(array) , sp.shape(array)[1] == 2 , sp.shape(array)[0] > 1)
# Видалення останнього запису
elif action == -1 and len(self.dataStack[Type])>=2:
self.dataStack[Type].pop()
emit = True
#self.setActiveLogScale( Type)
# Скидання історії, або запис першого елемента історії
elif action == 0:
print(0)
if sp.any(array) and sp.shape(array)[1] == 2 and sp.shape(array)[0] > 1 and len(self.dataStack[Type])>=1:
self.dataStack[Type][0:] = []
self.dataStack[Type].append(array)
emit = True
if not sp.any(array) and len(self.dataStack[Type])>=2:
self.dataStack[Type][1:] = []
emit = True
#self.setActiveLogScale( Type)
else:
print("updateData: Error0",len(self.dataStack[Type]))
print(sp.shape(self.getData(Type)))
try:
for i in self.dataStack[Type]: print(i.scaleX, i.scaleY, i.shape)
except:
pass
# Емітувати повідомлення про зміу даних
if emit:
self.data_signal.emit(Type, action)
self.Plot(self.getData(Type) )
示例7: test_ransohoff_snapoff_verts
def test_ransohoff_snapoff_verts(self):
ws = op.Workspace()
ws.clear()
bp = sp.array([[0.25, 0.25, 0.25], [0.25, 0.75, 0.25],
[0.75, 0.25, 0.25], [0.75, 0.75, 0.25],
[0.25, 0.25, 0.75], [0.25, 0.75, 0.75],
[0.75, 0.25, 0.75], [0.75, 0.75, 0.75]])
scale = 1e-4
sp.random.seed(1)
p = (sp.random.random([len(bp), 3])-0.5)/1000
bp += p
fiber_rad = 2e-6
bp = op.topotools.reflect_base_points(bp, domain_size=[1, 1, 1])
prj = op.materials.VoronoiFibers(fiber_rad=fiber_rad,
resolution=1e-6,
shape=[scale, scale, scale],
points=bp*scale,
name='test')
net = prj.network
del_geom = prj.geometries()['test_del']
vor_geom = prj.geometries()['test_vor']
f = op.models.physics.capillary_pressure.ransohoff_snap_off
water = op.phases.GenericPhase(network=net)
water['pore.surface_tension'] = 0.072
water['pore.contact_angle'] = 45
phys1 = op.physics.GenericPhysics(network=net,
geometry=del_geom,
phase=water)
phys1.add_model(propname='throat.snap_off',
model=f,
wavelength=fiber_rad)
phys1.add_model(propname='throat.snap_off_pair',
model=f,
wavelength=fiber_rad,
require_pair=True)
phys2 = op.physics.GenericPhysics(network=net,
geometry=vor_geom,
phase=water)
phys2.add_model(propname='throat.snap_off',
model=f,
wavelength=fiber_rad)
phys2.add_model(propname='throat.snap_off_pair',
model=f,
wavelength=fiber_rad,
require_pair=True)
ts = ~net['throat.interconnect']
assert ~sp.any(sp.isnan(water['throat.snap_off'][ts]))
assert sp.any(sp.isnan(water['throat.snap_off_pair'][ts]))
assert sp.any(~sp.isnan(water['throat.snap_off_pair'][ts]))
示例8: execute
def execute(self):
self.power_mat, self.thermal_expectation = self.full_calculation()
n_chan = self.power_mat.shape[1]
n_freq = self.power_mat.shape[0]
# Calculate the the mean channel correlations at low frequencies.
low_f_mat = sp.mean(self.power_mat[1:4 * n_chan + 1,:,:], 0).real
# Factorize it into preinciple components.
e, v = linalg.eigh(low_f_mat)
self.low_f_mode_values = e
# Make sure the eigenvalues are sorted.
if sp.any(sp.diff(e) < 0):
raise RuntimeError("Eigenvalues not sorted.")
self.low_f_modes = v
# Now subtract out the noisiest channel modes and see what is left.
n_modes_subtract = 10
mode_subtracted_power_mat = sp.copy(self.power_mat.real)
mode_subtracted_auto_power = sp.empty((n_modes_subtract, n_freq))
for ii in range(n_modes_subtract):
mode = v[:,-ii]
amp = sp.sum(mode[:,None] * mode_subtracted_power_mat, 1)
amp = sp.sum(amp * mode, 1)
to_subtract = amp[:,None,None] * mode[:,None] * mode
mode_subtracted_power_mat -= to_subtract
auto_power = mode_subtracted_power_mat.view()
auto_power.shape = (n_freq, n_chan**2)
auto_power = auto_power[:,::n_chan + 1]
mode_subtracted_auto_power[ii,:] = sp.mean(auto_power, -1)
self.subtracted_auto_power = mode_subtracted_auto_power
示例9: isherm
def isherm(Q):
"""Determines if given operator is Hermitian.
Parameters
----------
Q : qobj
Quantum object
Returns
-------
isherm : bool
True if operator is Hermitian, False otherwise.
Examples
--------
>>> a=destroy(4)
>>> isherm(a)
False
"""
if Q.dims[0]!=Q.dims[1]:
return False
else:
dat=Q.data
elems=(dat.transpose().conj()-dat).data
if any(abs(elems)>1e-15):
return False
else:
return True
示例10: straight
def straight(network,
geometry,
pore_diameter='pore.diameter',
L_negative = 1e-9,
**kwargs):
r"""
Calculate throat length
Parameters
----------
L_negative : float
The default throat length to use when negative lengths are found. The
default is 1 nm. To accept negative throat lengths, set this value to
``None``.
"""
#Initialize throat_property['length']
throats = network.throats(geometry.name)
pore1 = network['throat.conns'][:,0]
pore2 = network['throat.conns'][:,1]
C1 = network['pore.coords'][pore1]
C2 = network['pore.coords'][pore2]
E = _sp.sqrt(_sp.sum((C1-C2)**2,axis=1)) #Euclidean distance between pores
D1 = network[pore_diameter][pore1]
D2 = network[pore_diameter][pore2]
value = E-(D1+D2)/2.
value = value[throats]
if _sp.any(value<0) and (L_negative is not None):
print('Negative throat lengths are calculated. Arbitrary positive length assigned: '+str(L_negative))
Ts = _sp.where(value<0)[0]
value[Ts] = L_negative
return value
示例11: test_late_pore_and_throat_filling
def test_late_pore_and_throat_filling(self):
mip = op.algorithms.Porosimetry(network=self.net)
mip.setup(phase=self.hg)
mip.set_inlets(pores=self.net.pores('left'))
# Run without late pore filling
mip.run()
data_no_lpf = mip.get_intrusion_data()
# Now run with late pore filling
self.phys['pore.pc_star'] = 2/self.net['pore.diameter']
self.phys.add_model(propname='pore.partial_filling',
pressure='pore.pressure',
Pc_star='pore.pc_star',
model=op.models.physics.multiphase.late_filling)
mip.reset()
mip.set_inlets(pores=self.net.pores('left'))
mip.set_partial_filling(propname='pore.partial_filling')
mip.run()
self.phys.regenerate_models()
data_w_lpf = mip.get_intrusion_data()
assert sp.all(sp.array(data_w_lpf.Snwp) < sp.array(data_no_lpf.Snwp))
# Now run with late throat filling
self.phys['throat.pc_star'] = 2/self.net['throat.diameter']
self.phys.add_model(propname='throat.partial_filling',
pressure='throat.pressure',
Pc_star='throat.pc_star',
model=op.models.physics.multiphase.late_filling)
mip.reset()
mip.set_inlets(pores=self.net.pores('left'))
mip.set_partial_filling(propname='throat.partial_filling')
mip.run()
data_w_ltf = mip.get_intrusion_data()
assert sp.any(sp.array(data_w_ltf.Snwp) < sp.array(data_w_lpf.Snwp))
示例12: main
def main():
args = getArguments(getParser())
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# load input image
data_input, header_input = load(args.input)
# transform to uin8
data_input = data_input.astype(scipy.uint8)
# reduce to 3D, if larger dimensionality
if data_input.ndim > 3:
for _ in range(data_input.ndim - 3): data_input = data_input[...,0]
# iter over slices (2D) until first with content is detected
for plane in data_input:
if scipy.any(plane):
# set pixel spacing
spacing = list(header.get_pixel_spacing(header_input))
spacing = spacing[1:3]
__update_header_from_array_nibabel(header_input, plane)
header.set_pixel_spacing(header_input, spacing)
# save image
save(plane, args.output, header_input, args.force)
break
logger.info("Successfully terminated.")
示例13: generate_matrices
def generate_matrices(model, col_map, c, r, m, t):
noBrPointsPerEpoch = model.nbreakpoints
nleaves = model.nleaves
all_time_breakpoints, time_breakpoints = default_bps(model, c, r, t)
M = []
for e in xrange(len(noBrPointsPerEpoch)):
newM = identity(nleaves)
newM[:] = m[e]
M.append(newM)
pi, T, E = model.run(r, c, time_breakpoints, M, col_map=col_map)
assert not any(isnan(pi))
assert not any(isnan(T))
assert not any(isnan(E))
return pi, T, array(E)
示例14: dispersion_relation_extraordinary
def dispersion_relation_extraordinary(kx, ky, k, nO, nE, c):
"""Dispersion relation for the extraordinary wave.
NOTE
See eq. 16 in Glytsis, "Three-dimensional (vector) rigorous
coupled-wave analysis of anisotropic grating diffraction",
JOSA A, 7(8), 1990 Always give positive real or negative
imaginary.
"""
if kx.shape != ky.shape or c.size != 3:
raise ValueError('kx and ky must have the same length and c must have 3 components')
kz = S.empty_like(kx)
for ii in xrange(0, kx.size):
alpha = nE**2 - nO**2
beta = kx[ii]/k * c[0] + ky[ii]/k * c[1]
# coeffs
C = S.array([nO**2 + c[2]**2 * alpha, \
2. * c[2] * beta * alpha, \
nO**2 * (kx[ii]**2 + ky[ii]**2) / k**2 + alpha * beta**2 - nO**2 * nE**2])
# two solutions of type +x or -x, purely real or purely imag
tmp_kz = k * S.roots(C)
# get the negative imaginary part or the positive real one
if S.any(S.isreal(tmp_kz)):
kz[ii] = S.absolute(tmp_kz[0])
else:
kz[ii] = -1j * S.absolute(tmp_kz[0])
return kz
示例15: main
def main(npulse=100, functlist=['spectrums', 'radardata', 'fitting', 'analysis'],radar='pfisr'):
""" This function will call other functions to create the input data, config
file and run the radar data sim. The path for the simulation will be
created in the Testdata directory in the SimISR module. The new
folder will be called BasicTest. The simulation is a long pulse simulation
will the desired number of pulses from the user.
Inputs
npulse - Number of pulses for the integration period, default==100.
functlist - The list of functions for the SimISR to do.
"""
curloc = Path(__file__).resolve()
testpath = curloc.parent.parent/'Testdata'/'BasicTest'
if not testpath.is_dir():
testpath.mkdir(parents=True)
functlist_default = ['spectrums', 'radardata', 'fitting']
check_list = sp.array([i in functlist for i in functlist_default])
check_run = sp.any(check_list)
functlist_red = sp.array(functlist_default)[check_list].tolist()
config = testpath.joinpath('stats.yml')
if not config.exists():
configfilesetup(str(testpath), npulse, radar)
(_, simparams) = readconfigfile(str(config))
makedata(testpath, simparams['Tint'])
if check_run:
runsim(functlist_red, str(testpath), config, True)
if 'analysis' in functlist:
analysisdump(str(testpath), config)