- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
施加np.ndarray
周期性边界条件,如下所示
np.ndarray
的索引包裹在 n
维度n
维环面的周期性边界条件下面给出一个例子和反例:
a = np.arange(27).reshape(3,3,3)
b = Periodic_Lattice(a) # A theoretical class
# example: returning a scalar that shouldn't be accessible
print b[3,3,3] == b[0,0,0] # returns a scalar so invokes wrapping condition
try: a[3,3,3] # the value is out of bounds in the original np.ndarray
except: print 'error'
# counter example: returning a slice
try: b[3,3] # this returns a slice and so shouldn't invoke the wrap
except: print 'error'
应该给出输出:
True
error
error
我预计我应该在 np.ndarray
中重载 __getitem__
和 __setitem__
但是如何进行这个并不完全清楚并且有SO 上的许多实现在许多测试用例中都失败了。
最佳答案
一个简单的函数可以用 mod
函数,%
在基本 python 中编写,并泛化为对给定的 n
维元组进行操作特定的形状。
def latticeWrapIdx(index, lattice_shape):
"""returns periodic lattice index
for a given iterable index
Required Inputs:
index :: iterable :: one integer for each axis
lattice_shape :: the shape of the lattice to index to
"""
if not hasattr(index, '__iter__'): return index # handle integer slices
if len(index) != len(lattice_shape): return index # must reference a scalar
if any(type(i) == slice for i in index): return index # slices not supported
if len(index) == len(lattice_shape): # periodic indexing of scalars
mod_index = tuple(( (i%s + s)%s for i,s in zip(index, lattice_shape)))
return mod_index
raise ValueError('Unexpected index: {}'.format(index))
测试如下:
arr = np.array([[ 11., 12., 13., 14.],
[ 21., 22., 23., 24.],
[ 31., 32., 33., 34.],
[ 41., 42., 43., 44.]])
test_vals = [[(1,1), 22.], [(3,3), 44.], [( 4, 4), 11.], # [index, expected value]
[(3,4), 41.], [(4,3), 14.], [(10,10), 33.]]
passed = all([arr[latticeWrapIdx(idx, (4,4))] == act for idx, act in test_vals])
print "Iterating test values. Result: {}".format(passed)
并给出输出,
Iterating test values. Result: True
包装函数可以合并到子类 np.ndarray
中,如 here 所述:
class Periodic_Lattice(np.ndarray):
"""Creates an n-dimensional ring that joins on boundaries w/ numpy
Required Inputs
array :: np.array :: n-dim numpy array to use wrap with
Only currently supports single point selections wrapped around the boundary
"""
def __new__(cls, input_array, lattice_spacing=None):
"""__new__ is called by numpy when and explicit constructor is used:
obj = MySubClass(params) otherwise we must rely on __array_finalize
"""
# Input array is an already formed ndarray instance
# We first cast to be our class type
obj = np.asarray(input_array).view(cls)
# add the new attribute to the created instance
obj.lattice_shape = input_array.shape
obj.lattice_dim = len(input_array.shape)
obj.lattice_spacing = lattice_spacing
# Finally, we must return the newly created object:
return obj
def __getitem__(self, index):
index = self.latticeWrapIdx(index)
return super(Periodic_Lattice, self).__getitem__(index)
def __setitem__(self, index, item):
index = self.latticeWrapIdx(index)
return super(Periodic_Lattice, self).__setitem__(index, item)
def __array_finalize__(self, obj):
""" ndarray.__new__ passes __array_finalize__ the new object,
of our own class (self) as well as the object from which the view has been taken (obj).
See
http://docs.scipy.org/doc/numpy/user/basics.subclassing.html#simple-example-adding-an-extra-attribute-to-ndarray
for more info
"""
# ``self`` is a new object resulting from
# ndarray.__new__(Periodic_Lattice, ...), therefore it only has
# attributes that the ndarray.__new__ constructor gave it -
# i.e. those of a standard ndarray.
#
# We could have got to the ndarray.__new__ call in 3 ways:
# From an explicit constructor - e.g. Periodic_Lattice():
# 1. obj is None
# (we're in the middle of the Periodic_Lattice.__new__
# constructor, and self.info will be set when we return to
# Periodic_Lattice.__new__)
if obj is None: return
# 2. From view casting - e.g arr.view(Periodic_Lattice):
# obj is arr
# (type(obj) can be Periodic_Lattice)
# 3. From new-from-template - e.g lattice[:3]
# type(obj) is Periodic_Lattice
#
# Note that it is here, rather than in the __new__ method,
# that we set the default value for 'spacing', because this
# method sees all creation of default objects - with the
# Periodic_Lattice.__new__ constructor, but also with
# arr.view(Periodic_Lattice).
#
# These are in effect the default values from these operations
self.lattice_shape = getattr(obj, 'lattice_shape', obj.shape)
self.lattice_dim = getattr(obj, 'lattice_dim', len(obj.shape))
self.lattice_spacing = getattr(obj, 'lattice_spacing', None)
pass
def latticeWrapIdx(self, index):
"""returns periodic lattice index
for a given iterable index
Required Inputs:
index :: iterable :: one integer for each axis
This is NOT compatible with slicing
"""
if not hasattr(index, '__iter__'): return index # handle integer slices
if len(index) != len(self.lattice_shape): return index # must reference a scalar
if any(type(i) == slice for i in index): return index # slices not supported
if len(index) == len(self.lattice_shape): # periodic indexing of scalars
mod_index = tuple(( (i%s + s)%s for i,s in zip(index, self.lattice_shape)))
return mod_index
raise ValueError('Unexpected index: {}'.format(index))
测试正确地演示了晶格重载,
arr = np.array([[ 11., 12., 13., 14.],
[ 21., 22., 23., 24.],
[ 31., 32., 33., 34.],
[ 41., 42., 43., 44.]])
test_vals = [[(1,1), 22.], [(3,3), 44.], [( 4, 4), 11.], # [index, expected value]
[(3,4), 41.], [(4,3), 14.], [(10,10), 33.]]
periodic_arr = Periodic_Lattice(arr)
passed = (periodic_arr == arr).all()
passed *= all([periodic_arr[idx] == act for idx, act in test_vals])
print "Iterating test values. Result: {}".format(passed)
并给出输出,
Iterating test values. Result: True
最后,使用初始问题中提供的代码我们得到:
True
error
error
关于python - 具有周期性边界条件的 np.ndarray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38066785/
有时评估积分非常困难,但很容易验证解是否正确。在我看来它至少应该是 np,但我对这个概念的理解是有限的,我可能会遗漏一些东西 编辑:为了清楚起见,我很好奇算法的复杂性,该算法找到函数的反导数以解决不定
我对这三个类别的理解是否正确? 要证明问题 X 是 NP: 表明 X 可以在多项式时间内确定性地得到验证(或者X 可以使用 NTM 解决) 要证明问题 X 是 NP 完全的: 表明 X 可以在多项式时
有什么区别NP , NP-完全和 NP-Hard ? 我知道网上有很多资源。我想阅读你的解释,原因是它们可能与外面的不同,或者有一些我不知道的东西。 最佳答案 我假设您正在寻找直观的定义,因为技术定义
我正在寻找一种方法来检查 numpy 数组是 np.float64 还是 np.float32。这适用于 np.float64: a = np.random.rand(10) if not issub
我知道 np.nanargmin 找到列表中不是 NaN 的最小数字。但是,如果调用数组 [np.nan, np.inf],它会产生 0,这是一个 NaN。我发现这种行为很奇怪,我只是想知道以这种方式
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎与 help center 中定义的范围内的编程无关。 . 关闭 8 年前。 Improve
我很好奇使用 np.empty 到底有多大不同?而不是 np.zeros ,以及关于 np.ones 的区别.我运行这个小脚本来对每个创建大型数组所花费的时间进行基准测试: import numpy
在操作矩阵的时候,不同的接口对于矩阵的输入维度要求不同,输入可能为1-D,2-D,3-D等等。下面介绍一下使用Numpy进行矩阵维度变更的相关方法。主要包括以下几种: 1、np.newaxis扩充
除了使用一组 or 语句之外 isinstance( x, np.float64 ) 或 isinstance( x, np.float32 ) 或 isinstance( np.float16 )
我尝试了以下代码,但没有发现 np.dot 和 np.multiply 与 np.sum 之间的区别 这里是 np.dot 代码 logprobs = np.dot(Y, (np.log(A2)).T
我编写了一些程序来更新 numpy在每次迭代中列出并对其进行一些操作。迭代次数取决于时间。例如在 1 秒内,可能有 1000 到 2500 次迭代。这意味着 numpy 列表中的项目对于运行程序 1
我有以下两个数据框: a = pd.DataFrame([[1,2, 3],[4,3,6], [np.nan, 2, np.nan]]) 0 1 2 0 1.0 2 3.0 1
我有一个包含很多非零值的数组。当我使用以下方法计算非零项目总数时,我得到了 2 个不同的结果: 1) non_zero_weights = np.any(np.not_equal(lr_l1.coef
我对这么多int有点挣扎cython 中的数据类型。 np.int, np.int_, np.int_t, int 我猜 int在纯python中相当于np.int_ , 那么 np.int 在哪里来
如果您要选择以下三种初始化零数组的方法之一,您会选择哪一种以及为什么? my_arr_1 = np.full(size, 0) 或 my_arr_2 = np.zeros(size) 或 my_arr
我正在使用 np.select 根据应用于其他列的多个条件创建一个新列。这是一个简单的例子: df = pd.DataFrame({'A': [0, 3, 4], 'B': [10, 0, 2]})
我正在使用 np.select 根据应用于其他列的多个条件创建一个新列。这是一个简单的例子: df = pd.DataFrame({'A': [0, 3, 4], 'B': [10, 0, 2]})
我正在读这个code ,用于从头开始实现线性回归: # convert from data frames to numpy matrices X = np.matrix(X.values) y = n
我正在解压缩具有许多不同数据类型的大型二进制文件 (~1GB)。我正处于创建循环以隐藏每个字节的早期阶段。我一直在使用 struct.unpack,但最近认为如果我使用 numpy 它会运行得更快。然
我需要从依存分析树中提取形式为 NP-VP-NP 的三元组,作为 Stanford Parser 中词汇化分析的输出。 执行此操作的最佳方法是什么。例如如果解析树如下: (ROOT (S
我是一名优秀的程序员,十分优秀!