lazyarray.py 文件源码

python
阅读 52 收藏 0 点赞 0 评论 0

项目:lazyarray 作者: NeuralEnsemble 项目源码 文件源码
def __init__(self, value, shape=None, dtype=None):
        """
        Create a new lazy array.

        `value` : may be an int, long, float, bool, NumPy array, iterator,
                  generator or a function, `f(i)` or `f(i,j)`, depending on the
                  dimensions of the array.

        `f(i,j)` should return a single number when `i` and `j` are integers,
        and a 1D array when either `i` or `j` or both is a NumPy array (in the
        latter case the two arrays must have equal lengths).
        """

        self.dtype = dtype
        self.operations = []
        if isinstance(value, basestring):
            raise TypeError("An larray cannot be created from a string")
        elif isinstance(value, larray):
            if shape is not None and value.shape is not None:
                assert shape == value.shape
            self._shape = shape or value.shape
            self.base_value = value.base_value
            self.dtype = dtype or value.dtype
            self.operations = value.operations  # should deepcopy?

        elif isinstance(value, collections.Sized):  # False for numbers, generators, functions, iterators
            if have_scipy and sparse.issparse(value):  # For sparse matrices
                self.dtype = dtype or value.dtype                           
            elif not isinstance(value, numpy.ndarray):  
                value = numpy.array(value, dtype=dtype)
            elif dtype is not None:
               assert numpy.can_cast(value.dtype, dtype, casting='safe')  # or could convert value to the provided dtype
            if shape and value.shape != shape:
                raise ValueError("Array has shape %s, value has shape %s" % (shape, value.shape))
            self._shape = value.shape
            self.base_value = value

        else:
            assert numpy.isreal(value)  # also True for callables, generators, iterators
            self._shape = shape
            if dtype is None or isinstance(value, dtype):
                self.base_value = value
            else:
                try:
                    self.base_value = dtype(value)
                except TypeError:
                    self.base_value = value
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号