本文整理汇总了Python中numpy.isfortran方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.isfortran方法的具体用法?Python numpy.isfortran怎么用?Python numpy.isfortran使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.isfortran方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_trirefiner_fortran_contiguous_triangles
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
def test_trirefiner_fortran_contiguous_triangles():
# github issue 4180. Test requires two arrays of triangles that are
# identical except that one is C-contiguous and one is fortran-contiguous.
triangles1 = np.array([[2, 0, 3], [2, 1, 0]])
assert not np.isfortran(triangles1)
triangles2 = np.array(triangles1, copy=True, order='F')
assert np.isfortran(triangles2)
x = np.array([0.39, 0.59, 0.43, 0.32])
y = np.array([33.99, 34.01, 34.19, 34.18])
triang1 = mtri.Triangulation(x, y, triangles1)
triang2 = mtri.Triangulation(x, y, triangles2)
refiner1 = mtri.UniformTriRefiner(triang1)
refiner2 = mtri.UniformTriRefiner(triang2)
fine_triang1 = refiner1.refine_triangulation(subdiv=1)
fine_triang2 = refiner2.refine_triangulation(subdiv=1)
assert_array_equal(fine_triang1.triangles, fine_triang2.triangles)
示例2: hasFortranFlag
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
def hasFortranFlag(node):
"""Returns node value fortran flag."""
if node[1] is None:
return True
if node[1] == []:
return True
if isinstance(node[1], str):
return True # link
if not node[1].shape:
return True
if len(node[1].shape) == 1:
return True
return numpy.isfortran(node[1])
# --------------------------------------------------
示例3: _ndarray_representer
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
def _ndarray_representer(dumper, obj):
if not (obj.flags['C_CONTIGUOUS'] or obj.flags['F_CONTIGUOUS']):
obj = np.ascontiguousarray(obj)
if np.isfortran(obj):
obj = obj.T
order = 'F'
else:
order = 'C'
data_b64 = base64.b64encode(obj.tostring())
out = dict(buffer=data_b64,
dtype=str(obj.dtype),
shape=obj.shape,
order=order)
return dumper.represent_mapping('!numpy.ndarray', out)
示例4: strides
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
def strides(Z):
strides = [Z.itemsize]
# Fotran ordered array
if np.isfortran(Z):
for i in range(0, Z.ndim-1):
strides.append(strides[-1] * Z.shape[i])
return tuple(strides)
# C ordered array
else:
for i in range(Z.ndim-1, 0, -1):
strides.append(strides[-1] * Z.shape[i])
return tuple(strides[::-1])
# This work
示例5: test_polynomial_feature_array_order
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
def test_polynomial_feature_array_order():
X = np.arange(10).reshape(5, 2)
def is_c_contiguous(a):
return np.isfortran(a.T)
assert is_c_contiguous(PolynomialFeatures().fit_transform(X))
assert is_c_contiguous(PolynomialFeatures(order='C').fit_transform(X))
assert np.isfortran(PolynomialFeatures(order='F').fit_transform(X))
示例6: copyArray
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
def copyArray(a):
"""Copy a numpy.ndarray with flags"""
if not isinstance(a, numpy.ndarray):
return None # None, []
if numpy.isfortran(a):
b = numpy.array(a, order='Fortran', copy=True)
else:
b = numpy.array(a, copy=True)
return b
# --------------------------------------------------
示例7: toStringValue
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
def toStringValue(v):
"""ASCII pretty print of one node value."""
if v is None:
return None
ao = 'C'
if numpy.isfortran(v):
ao = 'F'
at = v.dtype.name
av = v.tolist()
return "numpy.array(%s,dtype='%s',order='%s')" % (av, at, ao)
# --------------------------------------------------
示例8: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
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")
示例9: _impose_f_order
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
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
示例10: info
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
def info(Z):
import sys
import numpy as np
endianness = {'=': 'native (%s)' % sys.byteorder,
'<': 'little',
'>': 'big',
'|': 'not applicable'}
print("------------------------------")
print("Interface (item)")
print(" shape: ", Z.shape)
print(" dtype: ", Z.dtype)
print(" length: ", len(Z))
print(" size: ", Z.size)
print(" endianness: ", endianness[Z.dtype.byteorder])
if np.isfortran(Z):
print(" order: ☐ C ☑ Fortran")
else:
print(" order: ☑ C ☐ Fortran")
print("")
print("Memory (byte)")
print(" item size: ", Z.itemsize)
print(" array size: ", Z.size*Z.itemsize)
print(" strides: ", Z.strides)
print("")
print("Properties")
if Z.flags["OWNDATA"]:
print(" own data: ☑ Yes ☐ No")
else:
print(" own data: ☐ Yes ☑ No")
if Z.flags["WRITEABLE"]:
print(" writeable: ☑ Yes ☐ No")
else:
print(" writeable: ☐ Yes ☑ No")
if np.isfortran(Z) and Z.flags["F_CONTIGUOUS"]:
print(" contiguous: ☑ Yes ☐ No")
elif not np.isfortran(Z) and Z.flags["C_CONTIGUOUS"]:
print(" contiguous: ☑ Yes ☐ No")
else:
print(" contiguous: ☐ Yes ☑ No")
if Z.flags["ALIGNED"]:
print(" aligned: ☑ Yes ☐ No")
else:
print(" aligned: ☐ Yes ☑ No")
print("------------------------------")
print()
示例11: isfortran
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
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
示例12: test_as_float_array
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
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)
X2 = as_float_array(X, copy=False)
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 as_float_array(X, False) is not X
assert_equal(X2.dtype, np.float64)
# Test int dtypes <= 32bit
tested_dtypes = [np.bool,
np.int8, np.int16, np.int32,
np.uint8, np.uint16, np.uint32]
for dtype in tested_dtypes:
X = X.astype(dtype)
X2 = as_float_array(X)
assert_equal(X2.dtype, np.float32)
# Test object dtype
X = X.astype(object)
X2 = as_float_array(X, copy=True)
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 as_float_array(X, copy=False) is X
# Test that if X is fortran ordered it stays
X = np.asfortranarray(X)
assert 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 not np.isnan(M).any()
示例13: isfortran
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
def isfortran(a):
"""Returns True if the array is Fortran contiguous but *not* C contiguous.
If you only want to check if an array is Fortran contiguous use
``a.flags.f_contiguous`` instead.
Args:
a (cupy.ndarray): Input array.
Returns:
bool: The return value, True if ``a`` is Fortran contiguous but not C
contiguous.
.. seealso::
:func:`~numpy.isfortran`
Examples
--------
cupy.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 = cupy.array([[1, 2, 3], [4, 5, 6]], order='C')
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> cupy.isfortran(a)
False
>>> b = cupy.array([[1, 2, 3], [4, 5, 6]], order='F')
>>> b
array([[1, 2, 3],
[4, 5, 6]])
>>> cupy.isfortran(b)
True
The transpose of a C-ordered array is a FORTRAN-ordered array.
>>> a = cupy.array([[1, 2, 3], [4, 5, 6]], order='C')
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> cupy.isfortran(a)
False
>>> b = a.T
>>> b
array([[1, 4],
[2, 5],
[3, 6]])
>>> cupy.isfortran(b)
True
C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
>>> cupy.isfortran(np.array([1, 2], order='F'))
False
"""
return a.flags.f_contiguous and not a.flags.c_contiguous
示例14: convert_to_ctypes
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
def convert_to_ctypes(args, func):
""" Converts an argument list to a ctype compatible list for our launcher function """
# pass numpy buffers using ctypes
cargs = []
try:
# Iterate over the args and convert
for arg in args:
# Check for supported types
if isinstance(arg, np.ndarray):
# Check for the array type
if not arg.dtype == np.float32:
raise ValueError(
'Input array of type {0} detected, Not supported.'.format(arg.dtype))
# Otherwise add the bounds
if len(arg.shape) > 4:
raise ValueError(
'Detected {0} dimensions. Halide supports only up to 4.'.format(
len(arg.shape)))
# Check if fortran array
if len(arg.shape) > 1 and not np.isfortran(arg):
print('Arg ', arg)
# Much faster and more natural halide code
raise ValueError('Currently supports only Fortran order')
# Add ctype
cargs.append(arg.ctypes.data_as(ctypes.c_void_p))
# Add bound w,h,x,y ...
for s in [1, 0, 2, 3]:
if s < len(arg.shape):
cargs.append(ctypes.c_int(np.int32(arg.shape[s])))
else:
cargs.append(ctypes.c_int(np.int32(1)))
elif isinstance(arg, float) or isinstance(arg, np.float32):
cargs.append(ctypes.c_float(arg))
elif isinstance(arg, int) or isinstance(arg, np.int32):
cargs.append(ctypes.c_int(arg))
else:
raise ValueError('Unsupported type.')
except Exception as e:
print('Error argument conversion: {0} in func {1}'.format(e.message, func), file=sys.stderr)
exit()
return cargs
示例15: concordance_td
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import isfortran [as 别名]
def concordance_td(durations, events, surv, surv_idx, method='adj_antolini'):
"""Time dependent concorance index from
Antolini, L.; Boracchi, P.; and Biganzoli, E. 2005. A timedependent discrimination
index for survival data. Statistics in Medicine 24:3927–3944.
If 'method' is 'antolini', the concordance from Antolini et al. is computed.
If 'method' is 'adj_antolini' (default) we have made a small modifications
for ties in predictions and event times.
We have followed step 3. in Sec 5.1. in Random Survial Forests paper, except for the last
point with "T_i = T_j, but not both are deaths", as that doesn't make much sense.
See '_is_concordant'.
Arguments:
durations {np.array[n]} -- Event times (or censoring times.)
events {np.array[n]} -- Event indicators (0 is censoring).
surv {np.array[n_times, n]} -- Survival function (each row is a duraratoin, and each col
is an individual).
surv_idx {np.array[n_test]} -- Mapping of survival_func s.t. 'surv_idx[i]' gives index in
'surv' corresponding to the event time of individual 'i'.
Keyword Arguments:
method {str} -- Type of c-index 'antolini' or 'adj_antolini' (default {'adj_antolini'}).
Returns:
float -- Time dependent concordance index.
"""
if np.isfortran(surv):
surv = np.array(surv, order='C')
assert durations.shape[0] == surv.shape[1] == surv_idx.shape[0] == events.shape[0]
assert type(durations) is type(events) is type(surv) is type(surv_idx) is np.ndarray
if events.dtype in ('float', 'float32'):
events = events.astype('int32')
if method == 'adj_antolini':
is_concordant = _is_concordant
is_comparable = _is_comparable
return (_sum_concordant_disc(surv, durations, events, surv_idx, is_concordant) /
_sum_comparable(durations, events, is_comparable))
elif method == 'antolini':
is_concordant = _is_concordant_antolini
is_comparable = _is_comparable_antolini
return (_sum_concordant_disc(surv, durations, events, surv_idx, is_concordant) /
_sum_comparable(durations, events, is_comparable))
return ValueError(f"Need 'method' to be e.g. 'antolini', got '{method}'.")