Python numpy 模块,isfortran() 实例源码
我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用numpy.isfortran()。
def write_waveform_numpy(self, waveform):
'''write_waveform
Writes waveform to the driver
Args:
waveform (numpy array of float64): Waveform data.
'''
import numpy
if type(waveform) is not numpy.ndarray:
raise TypeError('waveform must be {0}, is {1}'.format(numpy.ndarray, type(waveform)))
if numpy.isfortran(waveform) is True:
raise TypeError('waveform must be in C-order')
if waveform.dtype is not numpy.dtype('float64'):
raise TypeError('waveform must be numpy.ndarray of dtype=float64, is ' + str(waveform.dtype))
vi_ctype = visatype.ViSession(self._vi) # case 1
number_of_samples_ctype = visatype.ViInt32(0 if waveform is None else len(waveform)) # case 6
waveform_ctype = numpy.ctypeslib.as_ctypes(waveform) # case 13.5
error_code = self._library.niFake_WriteWaveform(vi_ctype, number_of_samples_ctype, waveform_ctype)
errors.handle_error(self, error_code, ignore_warnings=False, is_error_handling=False)
return
def calcDocTopicCount_c(
activeDocs, docIndices, word_count,
Prior, Lik,
sumR=None, DocTopicCount=None):
if not doUseLib:
raise NotImplementedError('Library not found. Please recompile.')
A = activeDocs.size
D, K = Prior.shape
N, K2 = Lik.shape
assert K == K2
if sumR is None:
sumR = np.zeros(N)
if DocTopicCount is None:
print 'HERE!!'
DocTopicCount = np.zeros((D, K), order='F')
if not np.isfortran(DocTopicCount):
raise NotImplementedError('NEED FORTRAN ORDER')
lib.CalcDocTopicCount(N, D, K, A,
activeDocs, docIndices,
word_count, Prior, Lik,
sumR, DocTopicCount)
return sumR, DocTopicCount
def get_connectivity_matrix_nodiag(self):
"""
Returns a similar matrix as in Ontology.get_connectivity_matrix(),
but the diagonal of the matrix is 0.
Note: !!!!!!!!!!!!!!!!!!!!!!!!
d[a, a] == 0 instead of 1
"""
if not hasattr(self, 'd_nodiag'):
d = self.get_connectivity_matrix()
self.d_nodiag = d.copy()
self.d_nodiag[np.diag_indices(self.d_nodiag.shape[0])] = 0
assert not np.isfortran(self.d_nodiag)
return self.d_nodiag
def __init__(self, data, block_length=1, use_blocks=None, offsets=None):
"""
data can be a numpy array (in C order), a tuple of such arrays, or a list of such tuples or arrays
"""
self.files = list()
if isinstance(data, list): #Several files
for file in data:
if isinstance(file, tuple):
for d in file:
assert(isinstance(d, np.ndarray) and not np.isfortran(d))
self.files.append(file)
elif isinstance(data, tuple): #Just one file
for d in data:
assert(isinstance(d, np.ndarray) and d.ndim == 2 and not np.isfortran(d))
self.files.append(data)
elif isinstance(data, np.ndarray): #One file with one kind of element only (not input-output)
assert(isinstance(data, np.ndarray) and not np.isfortran(data))
self.files.append(tuple([data]))
# Support for block datapoints
self.block_length = block_length
if block_length == 1:
self.block_lengths = [np.int(1)] * self.get_arity()
self.offsets = [np.int(0)] * self.get_arity()
elif block_length > 1:
self.block_lengths = [np.int(block_length) if ub else np.int(1) for ub in use_blocks] # np.asarray(dtype=np.int) and [np.int(x)] have elements with diff type. Careful!
self.offsets = [np.int(off) for off in offsets]
for ub, off in zip(use_blocks, offsets):
if off != 0 and ub:
raise Exception("Can't have both a block size greater than 1 and an offset.")
else:
raise Exception("Block size must be positive")
def fetch_waveform_into(self, waveform_data):
'''fetch_waveform
Returns waveform data.
Args:
waveform_data (numpy array of float64): Samples fetched from the device. Array should be numberOfSamples big.
Returns:
waveform_data (numpy array of float64): Samples fetched from the device. Array should be numberOfSamples big.
actual_number_of_samples (int): Number of samples actually fetched.
'''
import numpy
if type(waveform_data) is not numpy.ndarray:
raise TypeError('waveform_data must be {0}, is {1}'.format(numpy.ndarray, type(waveform_data)))
if numpy.isfortran(waveform_data) is True:
raise TypeError('waveform_data must be in C-order')
if waveform_data.dtype is not numpy.dtype('float64'):
raise TypeError('waveform_data must be numpy.ndarray of dtype=float64, is ' + str(waveform_data.dtype))
number_of_samples = len(waveform_data)
vi_ctype = visatype.ViSession(self._vi) # case 1
number_of_samples_ctype = visatype.ViInt32(number_of_samples) # case 8
waveform_data_ctype = numpy.ctypeslib.as_ctypes(waveform_data) # case 13.5
actual_number_of_samples_ctype = visatype.ViInt32() # case 14
error_code = self._library.niFake_FetchWaveform(vi_ctype, number_of_samples_ctype, waveform_data_ctype, ctypes.pointer(actual_number_of_samples_ctype))
errors.handle_error(self, error_code, ignore_warnings=False, is_error_handling=False)
return
def calcDocTopicCount_numpy(
activeDocs, docIndices, word_count,
Prior, Lik,
sumR=None, DocTopicCount=None):
if sumR is None:
sumR = np.zeros(N)
if DocTopicCount is None:
DocTopicCount = np.zeros((D, K), order='C')
if np.isfortran(DocTopicCount):
print 'here!!!!'
DocTopicCount = np.ascontiguousarray(DocTopicCount)
for d in activeDocs:
start = docIndices[d]
stop = docIndices[d + 1]
Lik_d = Lik[start:stop]
np.dot(Lik_d, Prior[d], out=sumR[start:stop])
np.dot(word_count[start:stop] / sumR[start:stop],
Lik_d,
out=DocTopicCount[d, :]
)
DocTopicCount[activeDocs] *= Prior[activeDocs]
return sumR, DocTopicCount
def sum_squared(X):
"""Compute norm of an array
Parameters
----------
X : array
Data whose norm must be found
Returns
-------
value : float
Sum of squares of the input array X
"""
X_flat = X.ravel(order='F' if np.isfortran(X) else 'C')
return np.dot(X_flat, X_flat)
def test_as_float_array():
# Test function for as_float_array
X = np.ones((3, 10), dtype=np.int32)
X = X + np.arange(10, dtype=np.int32)
# Checks that the return type is ok
X2 = as_float_array(X, copy=False)
np.testing.assert_equal(X2.dtype, np.float32)
# Another test
X = X.astype(np.int64)
X2 = as_float_array(X, copy=True)
# Checking that the array wasn't overwritten
assert_true(as_float_array(X, False) is not X)
# Checking that the new type is ok
np.testing.assert_equal(X2.dtype, np.float64)
# Here, X is of the right type, it shouldn't be modified
X = np.ones((3, 2), dtype=np.float32)
assert_true(as_float_array(X, copy=False) is X)
# Test that if X is fortran ordered it stays
X = np.asfortranarray(X)
assert_true(np.isfortran(as_float_array(X, copy=True)))
# Test the copy parameter with some matrices
matrices = [
np.matrix(np.arange(5)),
sp.csc_matrix(np.arange(5)).toarray(),
sparse_random_matrix(10, 10, density=0.10).toarray()
]
for M in matrices:
N = as_float_array(M, copy=True)
N[0, 0] = np.nan
assert_false(np.isnan(M).any())
def _impose_f_order(X):
"""Helper Function"""
# important to access flags instead of calling np.isfortran,
# this catches corner cases.
if X.flags.c_contiguous:
return check_array(X.T, copy=False, order='F'), True
else:
return check_array(X, copy=False, order='F'), False
def isfortran(a):
"""
Returns True if the array is Fortran contiguous but *not* C contiguous.
This function is obsolete and, because of changes due to relaxed stride
checking, its return value for the same array may differ for versions
of NumPy >= 1.10.0 and previous versions. If you only want to check if an
array is Fortran contiguous use ``a.flags.f_contiguous`` instead.
Parameters
----------
a : ndarray
Input array.
Examples
--------
np.array allows to specify whether the array is written in C-contiguous
order (last index varies the fastest), or FORTRAN-contiguous order in
memory (first index varies the fastest).
>>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> np.isfortran(a)
False
>>> b = np.array([[1, 2, 3], [4, 5, 6]], order='FORTRAN')
>>> b
array([[1, 2, 3],
[4, 5, 6]])
>>> np.isfortran(b)
True
The transpose of a C-ordered array is a FORTRAN-ordered array.
>>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> np.isfortran(a)
False
>>> b = a.T
>>> b
array([[1, 4],
[2, 5],
[3, 6]])
>>> np.isfortran(b)
True
C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
>>> np.isfortran(np.array([1, 2], order='FORTRAN'))
False
"""
return a.flags.fnc
def _create_waveform_f64_numpy(self, waveform_data_array):
'''_create_waveform_f64
Creates an onboard waveform from binary F64 (floating point double) data
for use in Arbitrary Waveform output mode or Arbitrary Sequence output
mode. The **waveformHandle** returned can later be used for setting the
active waveform, changing the data in the waveform, building sequences
of waveforms, or deleting the waveform when it is no longer needed.
Note:
You must call the nifgen_ConfigureOutputMode function to set the
**outputMode** parameter to NIFGEN_VAL_OUTPUT_ARB or
NIFGEN_VAL_OUTPUT_SEQ before calling this function.
Tip:
This method requires repeated capabilities (usually channels). If called directly on the
nifgen.Session object, then the method will use all repeated capabilities in the session.
You can specify a subset of repeated capabilities using the Python index notation on an
nifgen.Session instance, and calling this method on the result.:
session['0,1']._create_waveform_f64(waveform_data_array)
Args:
waveform_data_array (numpy array of float64): Specifies the array of data you want to use for the new arbitrary
waveform. The array must have at least as many elements as the value
that you specify in **waveformSize**.
You must normalize the data points in the array to be between –1.00 and
+1.00.
**Default Value**: None
Returns:
waveform_handle (int): The handle that identifies the new waveform. This handle is used later
when referring to this waveform.
'''
import numpy
if type(waveform_data_array) is not numpy.ndarray:
raise TypeError('waveform_data_array must be {0}, is {1}'.format(numpy.ndarray, type(waveform_data_array)))
if numpy.isfortran(waveform_data_array) is True:
raise TypeError('waveform_data_array must be in C-order')
if waveform_data_array.dtype is not numpy.dtype('float64'):
raise TypeError('waveform_data_array must be numpy.ndarray of dtype=float64, is ' + str(waveform_data_array.dtype))
vi_ctype = visatype.ViSession(self._vi) # case 1
channel_name_ctype = ctypes.create_string_buffer(self._repeated_capability.encode(self._encoding)) # case 2
waveform_size_ctype = visatype.ViInt32(0 if waveform_data_array is None else len(waveform_data_array)) # case 6
waveform_data_array_ctype = numpy.ctypeslib.as_ctypes(waveform_data_array) # case 13.5
waveform_handle_ctype = visatype.ViInt32() # case 14
error_code = self._library.niFgen_CreateWaveformF64(vi_ctype, channel_name_ctype, waveform_size_ctype, waveform_data_array_ctype, ctypes.pointer(waveform_handle_ctype))
errors.handle_error(self, error_code, ignore_warnings=False, is_error_handling=False)
return int(waveform_handle_ctype.value)
def _create_waveform_i16_numpy(self, waveform_data_array):
'''_create_waveform_i16
Creates an onboard waveform from binary 16-bit signed integer (I16) data
for use in Arbitrary Waveform or Arbitrary Sequence output mode. The
**waveformHandle** returned can later be used for setting the active
waveform, changing the data in the waveform, building sequences of
waveforms, or deleting the waveform when it is no longer needed.
Note:
You must call the nifgen_ConfigureOutputMode function to set the
**outputMode** parameter to NIFGEN_VAL_OUTPUT_ARB or
NIFGEN_VAL_OUTPUT_SEQ before calling this function.
Tip:
This method requires repeated capabilities (usually channels). If called directly on the
nifgen.Session object, then the method will use all repeated capabilities in the session.
You can specify a subset of repeated capabilities using the Python index notation on an
nifgen.Session instance, and calling this method on the result.:
session['0,1']._create_waveform_i16(waveform_data_array)
Args:
waveform_data_array (numpy array of int16): Specify the array of data that you want to use for the new arbitrary
waveform. The array must have at least as many elements as the value
that you specify in the Waveform Size parameter.
You must normalize the data points in the array to be between -32768 and
+32767.
****Default Value**:** None
Returns:
waveform_handle (int): The handle that identifies the new waveform. This handle is used later
when referring to this waveform.
'''
import numpy
if type(waveform_data_array) is not numpy.ndarray:
raise TypeError('waveform_data_array must be {0}, is {1}'.format(numpy.ndarray, type(waveform_data_array)))
if numpy.isfortran(waveform_data_array) is True:
raise TypeError('waveform_data_array must be in C-order')
if waveform_data_array.dtype is not numpy.dtype('int16'):
raise TypeError('waveform_data_array must be numpy.ndarray of dtype=int16, is ' + str(waveform_data_array.dtype))
vi_ctype = visatype.ViSession(self._vi) # case 1
channel_name_ctype = ctypes.create_string_buffer(self._repeated_capability.encode(self._encoding)) # case 2
waveform_size_ctype = visatype.ViInt32(0 if waveform_data_array is None else len(waveform_data_array)) # case 6
waveform_data_array_ctype = numpy.ctypeslib.as_ctypes(waveform_data_array) # case 13.5
waveform_handle_ctype = visatype.ViInt32() # case 14
error_code = self._library.niFgen_CreateWaveformI16(vi_ctype, channel_name_ctype, waveform_size_ctype, waveform_data_array_ctype, ctypes.pointer(waveform_handle_ctype))
errors.handle_error(self, error_code, ignore_warnings=False, is_error_handling=False)
return int(waveform_handle_ctype.value)
def _write_binary16_waveform_numpy(self, waveform_handle, data):
'''_write_binary16_waveform
Writes binary data to the waveform in onboard memory. The waveform
handle passed must have been created by a call to the
nifgen_AllocateWaveform or the nifgen_CreateWaveformI16 function.
By default, the subsequent call to the _write_binary16_waveform
function continues writing data from the position of the last sample
written. You can set the write position and offset by calling the
nifgen_SetWaveformNextWritePosition function. If streaming is enabled,
you can write more data than the allocated waveform size in onboard
memory. Refer to the
`Streaming <REPLACE_DRIVER_SPECIFIC_URL_2(streaming)>`__ topic for more
information about streaming data.
Tip:
This method requires repeated capabilities (usually channels). If called directly on the
nifgen.Session object, then the method will use all repeated capabilities in the session.
You can specify a subset of repeated capabilities using the Python index notation on an
nifgen.Session instance, and calling this method on the result.:
session['0,1']._write_binary16_waveform(waveform_handle, data)
Args:
waveform_handle (int): Specifies the handle of the arbitrary waveform previously allocated with
the nifgen_AllocateWaveform function.
data (numpy array of int16): Specifies the array of data to load into the waveform. The array must
have at least as many elements as the value in **size**. The binary data
is left-justified.
'''
import numpy
if type(data) is not numpy.ndarray:
raise TypeError('data must be {0}, is {1}'.format(numpy.ndarray, type(data)))
if numpy.isfortran(data) is True:
raise TypeError('data must be in C-order')
if data.dtype is not numpy.dtype('int16'):
raise TypeError('data must be numpy.ndarray of dtype=int16, is ' + str(data.dtype))
vi_ctype = visatype.ViSession(self._vi) # case 1
channel_name_ctype = ctypes.create_string_buffer(self._repeated_capability.encode(self._encoding)) # case 2
waveform_handle_ctype = visatype.ViInt32(waveform_handle) # case 9
size_ctype = visatype.ViInt32(0 if data is None else len(data)) # case 6
data_ctype = numpy.ctypeslib.as_ctypes(data) # case 13.5
error_code = self._library.niFgen_WriteBinary16Waveform(vi_ctype, channel_name_ctype, waveform_handle_ctype, size_ctype, data_ctype)
errors.handle_error(self, error_code, ignore_warnings=False, is_error_handling=False)
return
def _write_named_waveform_f64_numpy(self, waveform_name, data):
'''_write_named_waveform_f64
Writes floating-point data to the waveform in onboard memory. The
waveform handle passed in must have been created by a call to the
nifgen_AllocateWaveform function or to one of the following niFgen
Create Waveform functions:
- nifgen_CreateWaveformF64
- nifgen_CreateWaveformI16
- nifgen_CreateWaveformFromFileI16
- nifgen_CreateWaveformFromFileF64
- nifgen_CreateWaveformFromFileHWS
By default, the subsequent call to the _write_named_waveform_f64
function continues writing data from the position of the last sample
written. You can set the write position and offset by calling the
nifgen_SetNamedWaveformNextWritePosition function. If streaming is
enabled, you can write more data than the allocated waveform size in
onboard memory. Refer to the
`Streaming <REPLACE_DRIVER_SPECIFIC_URL_2(streaming)>`__ topic for more
information about streaming data.
Tip:
This method requires repeated capabilities (usually channels). If called directly on the
nifgen.Session object, then the method will use all repeated capabilities in the session.
You can specify a subset of repeated capabilities using the Python index notation on an
nifgen.Session instance, and calling this method on the result.:
session['0,1']._write_named_waveform_f64(waveform_name, data)
Args:
waveform_name (string): Specifies the name to associate with the allocated waveform.
data (numpy array of float64): Specifies the array of data to load into the waveform. The array must
have at least as many elements as the value in **size**.
'''
import numpy
if type(data) is not numpy.ndarray:
raise TypeError('data must be {0}, is {1}'.format(numpy.ndarray, type(data)))
if numpy.isfortran(data) is True:
raise TypeError('data must be in C-order')
if data.dtype is not numpy.dtype('float64'):
raise TypeError('data must be numpy.ndarray of dtype=float64, is ' + str(data.dtype))
vi_ctype = visatype.ViSession(self._vi) # case 1
channel_name_ctype = ctypes.create_string_buffer(self._repeated_capability.encode(self._encoding)) # case 2
waveform_name_ctype = ctypes.create_string_buffer(waveform_name.encode(self._encoding)) # case 3
size_ctype = visatype.ViInt32(0 if data is None else len(data)) # case 6
data_ctype = numpy.ctypeslib.as_ctypes(data) # case 13.5
error_code = self._library.niFgen_WriteNamedWaveformF64(vi_ctype, channel_name_ctype, waveform_name_ctype, size_ctype, data_ctype)
errors.handle_error(self, error_code, ignore_warnings=False, is_error_handling=False)
return
def _write_named_waveform_i16_numpy(self, waveform_name, data):
'''_write_named_waveform_i16
Writes binary data to the named waveform in onboard memory.
By default, the subsequent call to the _write_named_waveform_i16
function continues writing data from the position of the last sample
written. You can set the write position and offset by calling the
nifgen_SetNamedWaveformNextWritePosition function. If streaming is
enabled, you can write more data than the allocated waveform size in
onboard memory. Refer to the
`Streaming <REPLACE_DRIVER_SPECIFIC_URL_2(streaming)>`__ topic for more
information about streaming data.
Tip:
This method requires repeated capabilities (usually channels). If called directly on the
nifgen.Session object, then the method will use all repeated capabilities in the session.
You can specify a subset of repeated capabilities using the Python index notation on an
nifgen.Session instance, and calling this method on the result.:
session['0,1']._write_named_waveform_i16(waveform_name, data)
Args:
waveform_name (string): Specifies the name to associate with the allocated waveform.
data (numpy array of int16): Specifies the array of data to load into the waveform. The array must
have at least as many elements as the value in **size**.
'''
import numpy
if type(data) is not numpy.ndarray:
raise TypeError('data must be {0}, is {1}'.format(numpy.ndarray, type(data)))
if numpy.isfortran(data) is True:
raise TypeError('data must be in C-order')
if data.dtype is not numpy.dtype('int16'):
raise TypeError('data must be numpy.ndarray of dtype=int16, is ' + str(data.dtype))
vi_ctype = visatype.ViSession(self._vi) # case 1
channel_name_ctype = ctypes.create_string_buffer(self._repeated_capability.encode(self._encoding)) # case 2
waveform_name_ctype = ctypes.create_string_buffer(waveform_name.encode(self._encoding)) # case 3
size_ctype = visatype.ViInt32(0 if data is None else len(data)) # case 6
data_ctype = numpy.ctypeslib.as_ctypes(data) # case 13.5
error_code = self._library.niFgen_WriteNamedWaveformI16(vi_ctype, channel_name_ctype, waveform_name_ctype, size_ctype, data_ctype)
errors.handle_error(self, error_code, ignore_warnings=False, is_error_handling=False)
return
def fetch_waveform_into(self, waveform_array, maximum_time=-1):
'''fetch_waveform
For the NI 4080/4081/4082 and the NI 4070/4071/4072, returns an array of
values from a previously initiated waveform acquisition. You must call
_initiate before calling this function.
Args:
waveform_array (numpy array of float64): **Waveform Array** is an array of measurement values stored in waveform
data type.
maximum_time (int): Specifies the **maximum_time** allowed for this function to complete in
milliseconds. If the function does not complete within this time
interval, the function returns the NIDMM_ERROR_MAX_TIME_EXCEEDED
error code. This may happen if an external trigger has not been
received, or if the specified timeout is not long enough for the
acquisition to complete.
The valid range is 0–86400000. The default value is
NIDMM_VAL_TIME_LIMIT_AUTO (-1). The DMM calculates the timeout
automatically.
Returns:
waveform_array (numpy array of float64): **Waveform Array** is an array of measurement values stored in waveform
data type.
actual_number_of_points (int): Indicates the number of measured values actually retrieved from the DMM.
'''
import numpy
if type(waveform_array) is not numpy.ndarray:
raise TypeError('waveform_array must be {0}, is {1}'.format(numpy.ndarray, type(waveform_array)))
if numpy.isfortran(waveform_array) is True:
raise TypeError('waveform_array must be in C-order')
if waveform_array.dtype is not numpy.dtype('float64'):
raise TypeError('waveform_array must be numpy.ndarray of dtype=float64, is ' + str(waveform_array.dtype))
array_size = len(waveform_array)
vi_ctype = visatype.ViSession(self._vi) # case 1
maximum_time_ctype = visatype.ViInt32(maximum_time) # case 9
array_size_ctype = visatype.ViInt32(array_size) # case 8
waveform_array_ctype = numpy.ctypeslib.as_ctypes(waveform_array) # case 13.5
actual_number_of_points_ctype = visatype.ViInt32() # case 14
error_code = self._library.niDMM_FetchWaveform(vi_ctype, maximum_time_ctype, array_size_ctype, waveform_array_ctype, ctypes.pointer(actual_number_of_points_ctype))
errors.handle_error(self, error_code, ignore_warnings=False, is_error_handling=False)
return