def faceColors(self, indexed=None):
"""
Return an array (Nf, 4) of face colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4) (note this is just the same array with each color
repeated three times).
"""
if indexed is None:
return self._faceColors
elif indexed == 'faces':
if self._faceColorsIndexedByFaces is None and self._faceColors is not None:
Nf = self._faceColors.shape[0]
self._faceColorsIndexedByFaces = np.empty((Nf, 3, 4), dtype=self._faceColors.dtype)
self._faceColorsIndexedByFaces[:] = self._faceColors.reshape(Nf, 1, 4)
return self._faceColorsIndexedByFaces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
python类empty()的实例源码
def readQImage(self):
"""
Read the current buffer pixels out as a QImage.
"""
w = self.width()
h = self.height()
self.repaint()
pixels = np.empty((h, w, 4), dtype=np.ubyte)
pixels[:] = 128
pixels[...,0] = 50
pixels[...,3] = 255
glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels)
# swap B,R channels for Qt
tmp = pixels[...,0].copy()
pixels[...,0] = pixels[...,2]
pixels[...,2] = tmp
pixels = pixels[::-1] # flip vertical
img = fn.makeQImage(pixels, transpose=False)
return img
def solve3DTransform(points1, points2):
"""
Find a 3D transformation matrix that maps points1 onto points2.
Points must be specified as either lists of 4 Vectors or
(4, 3) arrays.
"""
import numpy.linalg
pts = []
for inp in (points1, points2):
if isinstance(inp, np.ndarray):
A = np.empty((4,4), dtype=float)
A[:,:3] = inp[:,:3]
A[:,3] = 1.0
else:
A = np.array([[inp[i].x(), inp[i].y(), inp[i].z(), 1] for i in range(4)])
pts.append(A)
## solve 3 sets of linear equations to determine transformation matrix elements
matrix = np.zeros((4,4))
for i in range(3):
## solve Ax = B; x is one row of the desired transformation matrix
matrix[i] = numpy.linalg.solve(pts[0], pts[1][:,i])
return matrix
def map(self, data):
data = data[self.fieldName]
colors = np.empty((len(data), 4))
default = np.array(fn.colorTuple(self['Default'])) / 255.
colors[:] = default
for v in self.param('Values'):
mask = data == v.maskValue
c = np.array(fn.colorTuple(v.value())) / 255.
colors[mask] = c
#scaled = np.clip((data-self['Min']) / (self['Max']-self['Min']), 0, 1)
#cmap = self.value()
#colors = cmap.map(scaled, mode='float')
#mask = np.isnan(data) | np.isinf(data)
#nanColor = self['NaN']
#nanColor = (nanColor.red()/255., nanColor.green()/255., nanColor.blue()/255., nanColor.alpha()/255.)
#colors[mask] = nanColor
return colors
def suggestDType(x):
"""Return a suitable dtype for x"""
if isinstance(x, list) or isinstance(x, tuple):
if len(x) == 0:
raise Exception('can not determine dtype for empty list')
x = x[0]
if hasattr(x, 'dtype'):
return x.dtype
elif isinstance(x, float):
return float
elif isinstance(x, int):
return int
#elif isinstance(x, basestring): ## don't try to guess correct string length; use object instead.
#return '<U%d' % len(x)
else:
return object
def build_test_data(self, variable='v'):
metadata = {
'size': NCELLS,
'first_index': 0,
'first_id': 0,
'n': 505,
'variable': variable,
'last_id': NCELLS - 1,
'last_index': NCELLS - 1,
'dt': 0.1,
'label': "population0",
}
if variable == 'v':
metadata['units'] = 'mV'
elif variable == 'spikes':
metadata['units'] = 'ms'
data = np.empty((505, 2))
for i in range(NCELLS):
# signal
data[i*101:(i+1)*101, 0] = np.arange(i, i+101, dtype=float)
# index
data[i*101:(i+1)*101, 1] = i*np.ones((101,), dtype=float)
return data, metadata
def generatePath(self, x, y):
if self.opts['stepMode']:
## each value in the x/y arrays generates 2 points.
x2 = np.empty((len(x),2), dtype=x.dtype)
x2[:] = x[:,np.newaxis]
if self.opts['fillLevel'] is None:
x = x2.reshape(x2.size)[1:-1]
y2 = np.empty((len(y),2), dtype=y.dtype)
y2[:] = y[:,np.newaxis]
y = y2.reshape(y2.size)
else:
## If we have a fill level, add two extra points at either end
x = x2.reshape(x2.size)
y2 = np.empty((len(y)+2,2), dtype=y.dtype)
y2[1:-1] = y[:,np.newaxis]
y = y2.reshape(y2.size)[1:-1]
y[0] = self.opts['fillLevel']
y[-1] = self.opts['fillLevel']
path = fn.arrayToQPath(x, y, connect=self.opts['connect'])
return path
def dataType(obj):
if hasattr(obj, '__len__') and len(obj) == 0:
return 'empty'
if isinstance(obj, dict):
return 'dictOfLists'
elif isSequence(obj):
first = obj[0]
if (hasattr(obj, 'implements') and obj.implements('MetaArray')):
return 'MetaArray'
elif isinstance(obj, np.ndarray):
if obj.ndim == 1:
if obj.dtype.names is None:
return 'listOfValues'
else:
return 'recarray'
elif obj.ndim == 2 and obj.dtype.names is None and obj.shape[1] == 2:
return 'Nx2array'
else:
raise Exception('array shape must be (N,) or (N,2); got %s instead' % str(obj.shape))
elif isinstance(first, dict):
return 'listOfDicts'
else:
return 'listOfValues'
def getSymbolCoords(self, opts):
"""
Given a list of spot records, return an object representing the coordinates of that symbol within the atlas
"""
sourceRect = np.empty(len(opts), dtype=object)
keyi = None
sourceRecti = None
for i, rec in enumerate(opts):
key = (rec[3], rec[2], id(rec[4]), id(rec[5])) # TODO: use string indexes?
if key == keyi:
sourceRect[i] = sourceRecti
else:
try:
sourceRect[i] = self.symbolMap[key]
except KeyError:
newRectSrc = QtCore.QRectF()
newRectSrc.pen = rec['pen']
newRectSrc.brush = rec['brush']
self.symbolMap[key] = newRectSrc
self.atlasValid = False
sourceRect[i] = newRectSrc
keyi = key
sourceRecti = newRectSrc
return sourceRect
def renderShapeMask(self, width, height):
"""Return an array of 0.0-1.0 into which the shape of the item has been drawn.
This can be used to mask array selections.
"""
if width == 0 or height == 0:
return np.empty((width, height), dtype=float)
# QImage(width, height, format)
im = QtGui.QImage(width, height, QtGui.QImage.Format_ARGB32)
im.fill(0x0)
p = QtGui.QPainter(im)
p.setPen(fn.mkPen(None))
p.setBrush(fn.mkBrush('w'))
shape = self.shape()
bounds = shape.boundingRect()
p.scale(im.width() / bounds.width(), im.height() / bounds.height())
p.translate(-bounds.topLeft())
p.drawPath(shape)
p.end()
mask = fn.imageToArray(im, transpose=True)[:,:,0].astype(float) / 255.
return mask
def faceNormals(self, indexed=None):
"""
Return an array (Nf, 3) of normal vectors for each face.
If indexed='faces', then instead return an indexed array
(Nf, 3, 3) (this is just the same array with each vector
copied three times).
"""
if self._faceNormals is None:
v = self.vertexes(indexed='faces')
self._faceNormals = np.cross(v[:,1]-v[:,0], v[:,2]-v[:,0])
if indexed is None:
return self._faceNormals
elif indexed == 'faces':
if self._faceNormalsIndexedByFaces is None:
norms = np.empty((self._faceNormals.shape[0], 3, 3))
norms[:] = self._faceNormals[:,np.newaxis,:]
self._faceNormalsIndexedByFaces = norms
return self._faceNormalsIndexedByFaces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
def faceColors(self, indexed=None):
"""
Return an array (Nf, 4) of face colors.
If indexed=='faces', then instead return an indexed array
(Nf, 3, 4) (note this is just the same array with each color
repeated three times).
"""
if indexed is None:
return self._faceColors
elif indexed == 'faces':
if self._faceColorsIndexedByFaces is None and self._faceColors is not None:
Nf = self._faceColors.shape[0]
self._faceColorsIndexedByFaces = np.empty((Nf, 3, 4), dtype=self._faceColors.dtype)
self._faceColorsIndexedByFaces[:] = self._faceColors.reshape(Nf, 1, 4)
return self._faceColorsIndexedByFaces
else:
raise Exception("Invalid indexing mode. Accepts: None, 'faces'")
def solve3DTransform(points1, points2):
"""
Find a 3D transformation matrix that maps points1 onto points2.
Points must be specified as either lists of 4 Vectors or
(4, 3) arrays.
"""
import numpy.linalg
pts = []
for inp in (points1, points2):
if isinstance(inp, np.ndarray):
A = np.empty((4,4), dtype=float)
A[:,:3] = inp[:,:3]
A[:,3] = 1.0
else:
A = np.array([[inp[i].x(), inp[i].y(), inp[i].z(), 1] for i in range(4)])
pts.append(A)
## solve 3 sets of linear equations to determine transformation matrix elements
matrix = np.zeros((4,4))
for i in range(3):
## solve Ax = B; x is one row of the desired transformation matrix
matrix[i] = numpy.linalg.solve(pts[0], pts[1][:,i])
return matrix
def map(self, data):
data = data[self.fieldName]
colors = np.empty((len(data), 4))
default = np.array(fn.colorTuple(self['Default'])) / 255.
colors[:] = default
for v in self.param('Values'):
mask = data == v.maskValue
c = np.array(fn.colorTuple(v.value())) / 255.
colors[mask] = c
#scaled = np.clip((data-self['Min']) / (self['Max']-self['Min']), 0, 1)
#cmap = self.value()
#colors = cmap.map(scaled, mode='float')
#mask = np.isnan(data) | np.isinf(data)
#nanColor = self['NaN']
#nanColor = (nanColor.red()/255., nanColor.green()/255., nanColor.blue()/255., nanColor.alpha()/255.)
#colors[mask] = nanColor
return colors
def __init__(self, data=None, info=None, dtype=None, file=None, copy=False, **kwargs):
object.__init__(self)
#self._infoOwned = False
self._isHDF = False
if file is not None:
self._data = None
self.readFile(file, **kwargs)
if kwargs.get("readAllData", True) and self._data is None:
raise Exception("File read failed: %s" % file)
else:
self._info = info
if (hasattr(data, 'implements') and data.implements('MetaArray')):
self._info = data._info
self._data = data.asarray()
elif isinstance(data, tuple): ## create empty array with specified shape
self._data = np.empty(data, dtype=dtype)
else:
self._data = np.array(data, dtype=dtype, copy=copy)
## run sanity checks on info structure
self.checkInfo()
def build_test_data(self, variable='v'):
metadata = {
'size': NCELLS,
'first_index': 0,
'first_id': 0,
'n': 505,
'variable': variable,
'last_id': NCELLS - 1,
'last_index': NCELLS - 1,
'dt': 0.1,
'label': "population0",
}
if variable == 'v':
metadata['units'] = 'mV'
elif variable == 'spikes':
metadata['units'] = 'ms'
data = np.empty((505, 2))
for i in range(NCELLS):
# signal
data[i*101:(i+1)*101, 0] = np.arange(i, i+101, dtype=float)
# index
data[i*101:(i+1)*101, 1] = i*np.ones((101,), dtype=float)
return data, metadata
def get_waveform_data(self, episode, electrode_id):
"""
Return waveforms corresponding to the specified
spike channel. This function is triggered when the
``waveforms`` property of an :class:`Spike` descriptor
instance is accessed.
"""
block = self.episode_block(episode)
times, databytes = self.load_encoded_waveforms(episode, electrode_id)
n_events, = databytes.shape
wf_samples = databytes['waveform'].shape[1]
dtype = [
('time', float),
('electrode_id', int),
('unit_id', int),
('waveform', float, (wf_samples, 2))
]
data = np.empty(n_events, dtype=dtype)
data['electrode_id'] = databytes['channel_id'][:, 0]
data['unit_id'] = databytes['unit_id'][:, 0]
data['time'] = databytes['elphy_time'][:, 0] * block.ep_block.dX
data['waveform'][:, :, 0] = times * block.ep_block.dX
data['waveform'][:, :, 1] = databytes['waveform'] * block.ep_block.dY_wf + block.ep_block.Y0_wf
return data
def array2d(surface):
"""pygame.numpyarray.array2d(Surface): return array
copy pixels into a 2d array
Copy the pixels from a Surface into a 2D array. The bit depth of the
surface will control the size of the integer values, and will work
for any type of pixel format.
This function will temporarily lock the Surface as pixels are copied
(see the Surface.lock - lock the Surface memory for pixel access
method).
"""
bpp = surface.get_bytesize()
try:
dtype = (numpy.uint8, numpy.uint16, numpy.int32, numpy.int32)[bpp - 1]
except IndexError:
raise ValueError("unsupported bit depth %i for 2D array" % (bpp * 8,))
size = surface.get_size()
array = numpy.empty(size, dtype)
surface_to_array(array, surface)
return array
def array3d(surface):
"""pygame.numpyarray.array3d(Surface): return array
copy pixels into a 3d array
Copy the pixels from a Surface into a 3D array. The bit depth of the
surface will control the size of the integer values, and will work
for any type of pixel format.
This function will temporarily lock the Surface as pixels are copied
(see the Surface.lock - lock the Surface memory for pixel access
method).
"""
w, h = surface.get_size()
array = numpy.empty((w, h, 3), numpy.uint8)
surface_to_array(array, surface)
return array
def array_alpha(surface):
"""pygame.numpyarray.array_alpha(Surface): return array
copy pixel alphas into a 2d array
Copy the pixel alpha values (degree of transparency) from a Surface
into a 2D array. This will work for any type of Surface
format. Surfaces without a pixel alpha will return an array with all
opaque values.
This function will temporarily lock the Surface as pixels are copied
(see the Surface.lock - lock the Surface memory for pixel access
method).
"""
size = surface.get_size()
array = numpy.empty(size, numpy.uint8)
surface_to_array(array, surface, 'A')
return array