jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def _update_ndarray(self):
        j_tensor_wrapper_cls = get_java_class(TENSOR_WRAPPER_CLASS_NAME)
        j_tensor_wrapper = j_tensor_wrapper_cls.fromJava(self.get_j_obj())
        buffer, dtype_str, shape = j_tensor_wrapper.getBytes(), j_tensor_wrapper.getDtypeStr(), j_tensor_wrapper.getShape()
        dtype = np.dtype(dtype_str)
        if dtype == np.bool:
            packed: numpy.ndarray = np.frombuffer(buffer, dtype='<B')
            unpacked = np.unpackbits(packed, count=reduce(lambda x, y: x*y, list(shape)), bitorder='little')
            self._arr = unpacked.reshape(shape)
        elif dtype.type == np.str_:
            strs = []
            with io.BytesIO(buffer) as bytesio:
                size, = struct.unpack('>i', bytesio.read(4))
                for i in range(size):
                    length, = struct.unpack('>i', bytesio.read(4))
                    buffer = bytesio.read(length)
                    s = buffer.decode(encoding="UTF-8")
                    strs.append(s)
            self._arr = np.array(strs, dtype=np.object).reshape(shape)
        else:
            self._arr = np.frombuffer(buffer, dtype=dtype).reshape(shape)
//  [python]
def _update_ndarray(self):
        j_tensor_wrapper_cls = get_java_class(TENSOR_WRAPPER_CLASS_NAME)
        j_tensor_wrapper = j_tensor_wrapper_cls.fromJava(self.get_j_obj())
        buffer, dtype_str, shape = j_tensor_wrapper.getBytes(), j_tensor_wrapper.getDtypeStr(), j_tensor_wrapper.getShape()
        dtype = np.dtype(dtype_str)
        if dtype == np.bool:
            packed: numpy.ndarray = np.frombuffer(buffer, dtype='<B')
            unpacked = np.unpackbits(packed, count=np.prod(list(shape)).item(), bitorder='little')
            self._arr = unpacked.reshape(shape)
        elif dtype.type == np.str_:
            strs = []
            with io.BytesIO(buffer) as bytesio:
                size, = struct.unpack('>i', bytesio.read(4))
                for i in range(size):
                    length, = struct.unpack('>i', bytesio.read(4))
                    buffer = bytesio.read(length)
                    s = buffer.decode(encoding="UTF-8")
                    strs.append(s)
            self._arr = np.array(strs, dtype=np.object).reshape(shape)
        else:
            self._arr = np.frombuffer(buffer, dtype=dtype).reshape(shape)
//  [python]
def size(self):
    """Returns the number of elements in the array."""
    return np.prod(self.shape)
//  [python]
def bilinear_zpk(z, p, k, fs):
    """
    Return a digital IIR filter from an analog one using a bilinear transform.

    Transform a set of poles and zeros from the analog s-plane to the digital
    z-plane using Tustin's method, which substitutes ``(z-1) / (z+1)`` for
    ``s``, maintaining the shape of the frequency response.

    Parameters
    ----------
    z : array_like
        Zeros of the analog filter transfer function.
    p : array_like
        Poles of the analog filter transfer function.
    k : float
        System gain of the analog filter transfer function.
    fs : float
        Sample rate, as ordinary frequency (e.g. hertz). No prewarping is
        done in this function.

    Returns
    -------
    z : ndarray
        Zeros of the transformed digital filter transfer function.
    p : ndarray
        Poles of the transformed digital filter transfer function.
    k : float
        System gain of the transformed digital filter.

    See Also
    --------
    lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, lp2bs_zpk
    bilinear

    Notes
    -----
    .. versionadded:: 1.1.0

    """
    z = atleast_1d(z)
    p = atleast_1d(p)

    degree = _relative_degree(z, p)

    fs2 = 2.0*fs

    # Bilinear transform the poles and zeros
    z_z = (fs2 + z) / (fs2 - z)
    p_z = (fs2 + p) / (fs2 - p)

    # Any zeros that were at infinity get moved to the Nyquist frequency
    z_z = append(z_z, -ones(degree))

    # Compensate for gain change
    k_z = k * (n.prod(fs2 - z) / n.prod(fs2 - p))

    return z_z, p_z, k_z
//  [python]
def bilinear_zpk(z, p, k, fs):
    """
    Return a digital IIR filter from an analog one using a bilinear transform.

    Transform a set of poles and zeros from the analog s-plane to the digital
    z-plane using Tustin's method, which substitutes ``(z-1) / (z+1)`` for
    ``s``, maintaining the shape of the frequency response.

    Parameters
    ----------
    z : array_like
        Zeros of the analog filter transfer function.
    p : array_like
        Poles of the analog filter transfer function.
    k : float
        System gain of the analog filter transfer function.
    fs : float
        Sample rate, as ordinary frequency (e.g. hertz). No prewarping is
        done in this function.

    Returns
    -------
    z : ndarray
        Zeros of the transformed digital filter transfer function.
    p : ndarray
        Poles of the transformed digital filter transfer function.
    k : float
        System gain of the transformed digital filter.

    See Also
    --------
    lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, lp2bs_zpk
    bilinear

    Notes
    -----
    .. versionadded:: 1.1.0

    """
    z = atleast_1d(z)
    p = atleast_1d(p)

    degree = _relative_degree(z, p)

    fs2 = 2.0*fs

    # Bilinear transform the poles and zeros
    z_z = (fs2 + z) / (fs2 - z)
    p_z = (fs2 + p) / (fs2 - p)

    # Any zeros that were at infinity get moved to the Nyquist frequency
    z_z = append(z_z, -ones(degree))

    # Compensate for gain change
    k_z = k * real(prod(fs2 - z) / prod(fs2 - p))

    return z_z, p_z, k_z
//  [python]
def fromNdarray(arr: numpy.ndarray):
        j_tensor_wrapper_cls = get_java_class(TENSOR_WRAPPER_CLASS_NAME)
        if arr.dtype == np.bool:
            packed = np.packbits(arr, bitorder='little')
            j_tensor_wrapper = j_tensor_wrapper_cls.fromPy(packed.tobytes(), arr.dtype.str, arr.shape)
        elif arr.dtype.type == np.str_:
            size: int = arr.size
            with io.BytesIO() as bytesio:
                # Use big-endian, as bytes are read with DataInputStream in Java side
                bytesio.write(size.to_bytes(4, byteorder='big'))
                for s in arr.flatten():
                    bytesio.write(len(s).to_bytes(4, byteorder='big'))
                    bytesio.write(s.encode(encoding='UTF-8'))
                bytesio.flush()
                buffer = bytesio.getvalue()
            j_tensor_wrapper = j_tensor_wrapper_cls.fromPy(buffer, '<U', arr.shape)
        else:
            j_tensor_wrapper = j_tensor_wrapper_cls.fromPy(arr.tobytes(), arr.dtype.str, arr.shape)
        subclasses = get_all_subclasses(Tensor)
        subclasses.remove(NumericalTensor)
        j_tensor = j_tensor_wrapper.getJavaObject()
        for subclass in subclasses:
            # noinspection PyProtectedMember
            if is_java_instance(j_tensor, subclass._j_cls_name):
                return subclass(j_tensor)
//  [python]
def fromNdarray(arr: numpy.ndarray):
        j_tensor_wrapper_cls = get_java_class(TENSOR_WRAPPER_CLASS_NAME)
        if arr.dtype == np.bool:
            packed = np.packbits(arr, bitorder='little')
            j_tensor_wrapper = j_tensor_wrapper_cls.fromPy(packed.tobytes(), arr.dtype.str, arr.shape)
        elif arr.dtype.type == np.str_:
            size: int = np.prod(arr.shape).item()
            with io.BytesIO() as bytesio:
                # Use big-endian, as bytes are read with DataInputStream in Java side
                bytesio.write(size.to_bytes(4, byteorder='big'))
                for s in arr.flatten():
                    bytesio.write(len(s).to_bytes(4, byteorder='big'))
                    bytesio.write(s.encode(encoding='UTF-8'))
                bytesio.flush()
                buffer = bytesio.getvalue()
            j_tensor_wrapper = j_tensor_wrapper_cls.fromPy(buffer, '<U', arr.shape)
        else:
            j_tensor_wrapper = j_tensor_wrapper_cls.fromPy(arr.tobytes(), arr.dtype.str, arr.shape)
        subclasses = get_all_subclasses(Tensor)
        subclasses.remove(NumericalTensor)
        j_tensor = j_tensor_wrapper.getJavaObject()
        for subclass in subclasses:
            # noinspection PyProtectedMember
            if is_java_instance(j_tensor, subclass._j_cls_name):
                return subclass(j_tensor)
//  [python]
def init_stepsize(self, weights_shape, params):
        self.A = numpy.eye(numpy.multiply.reduce(weights_shape)) * self.delta
//  [python]
def init_stepsize(self, weights_shape, params):
        self.A = numpy.eye(numpy.prod(weights_shape)) * self.delta
//  [python]
def init_stepsize(self, weights_shape, params):
        """Initializes the step-size variables, in this case meaning the A matrix and b vector.

        Args:
            weights_shape: Shape of the weights array
            params: Additional parameters.
        """
        # Using step_sizes for b
        # Using traces for z
        self.A = numpy.zeros((n.prod(weights_shape),n.prod(weights_shape)))
        self.step_sizes = numpy.zeros((n.prod(weights_shape),))
        self.lstd_counter = 0
//  [python]
def init_stepsize(self, weights_shape, params):
        """Initializes the step-size variables, in this case meaning the A matrix and b vector.

        Args:
            weights_shape: Shape of the weights array
            params: Additional parameters.
        """
        # Using step_sizes for b
        # Using traces for z
        self.A = numpy.zeros((numpy.prod(weights_shape),numpy.prod(weights_shape)))
        self.step_sizes = numpy.zeros((numpy.prod(weights_shape),))
        self.lstd_counter = 0
//  [python]
def init_stepsize(self, weights_shape, params):
        """Initializes the step-size variables, in this case meaning the A matrix and b vector.

        Args:
            weights_shape: Shape of the weights array
            params: Additional parameters.
        """
        self.A = numpy.eye(n.prod(weights_shape))
        self.A += numpy.random.random(self.A.shape)*self.alpha
        self.step_sizes = numpy.zeros((n.prod(weights_shape),))
        self.lstd_counter = 0
//  [python]
def init_stepsize(self, weights_shape, params):
        """Initializes the step-size variables, in this case meaning the A matrix and b vector.

        Args:
            weights_shape: Shape of the weights array
            params: Additional parameters.
        """
        self.A = numpy.eye(numpy.prod(weights_shape))
        self.A += numpy.random.random(self.A.shape)*self.alpha
        self.step_sizes = numpy.zeros((numpy.prod(weights_shape),))
        self.lstd_counter = 0
//  [python]
def enumerate_plate_positions(self, plate):

        shape = self._raw_growth_data[plate].shape[:-1]
        for pos_tup in izip(*np.unravel_index(np.arange(reduce(lambda x, y: x*y, shape)), shape)):
            yield pos_tup
//  [python]
def enumerate_plate_positions(self, plate):

        shape = self._raw_growth_data[plate].shape[:-1]
        for pos_tup in izip(*np.unravel_index(np.arange(np.prod(shape)), shape)):
            yield pos_tup
//  [python]
def init_stepsize(self, weights_shape, params):
        """Initializes the step-size variables, in this case meaning the A matrix and b vector.

        Args:
            weights_shape: Shape of the weights array
            params: Additional parameters.
        """
        # Data samples should hold num_samples, and each sample should
        # contain phi_t (|weights_shape|), state_t+1 (numStates), discState_t+1 (1), and reward_t (1)
        self.samples = numpy.zeros((self.num_samples, n.prod(weights_shape) + self.numStates + 2))
        self.lstd_counter = 0
//  [python]
def init_stepsize(self, weights_shape, params):
        """Initializes the step-size variables, in this case meaning the A matrix and b vector.

        Args:
            weights_shape: Shape of the weights array
            params: Additional parameters.
        """
        # Data samples should hold num_samples, and each sample should
        # contain phi_t (|weights_shape|), state_t+1 (numStates), discState_t+1 (1), and reward_t (1)
        self.samples = numpy.zeros((self.num_samples, numpy.prod(weights_shape) + self.numStates + 2))
        self.lstd_counter = 0
//  [python]
def generate_inputs(self):
        shape = self.shape
        dtype = self.dtype
        x = numpy.arange(numpy.prod(shape), dtype=dtype).reshape(shape)
        return x,
//  [python]
def number_of_points(self):
        "The number of points in the grid"
        
        return n.prod(self.points.shape[:-1])
//  [python]
def number_of_points(self):
        "The number of points in the grid"
        
        return numpy.prod(self.points.shape[:-1])
//  [python]
def number_of_cells(self):
        "The number of grid cells"
        return numpy.prod(self.cells.shape)
//  [python]
def _poly_smoothen_raw_growth(self, power=3, time_delta=5.1):

        assert power > 1, "Power must be 2 or greater"

        self._logger.info("Starting Polynomial smoothing")

        smooth_data = []
        times = self.times
        time_diffs = np.subtract.outer(times, times)
        filt = (time_diffs < time_delta) & (time_diffs > -time_delta)

        for id_plate, plate in enumerate(self._raw_growth_data):
            if plate is None:
                smooth_data.append(None)
                self._logger.info("Plate {0} has no data".format(id_plate + 1))
                continue

            log2_data = np.log2(plate).reshape(np.multiply.reduce(plate.shape[:2]), plate.shape[-1])
            smooth_plate = np.array(tuple(
                tuple(self._poly_smoothen_raw_growth_curve(times, log2_curve, power, filt))
                for log2_curve in log2_data))

            self._logger.info("Plate {0} data polynomial smoothed".format(id_plate + 1))

            smooth_data.append(smooth_plate.reshape(plate.shape))

        self._smooth_growth_data = np.array(smooth_data)

        self._logger.info("Completed Polynomial smoothing")
//  [python]
def _poly_smoothen_raw_growth(self, power=3, time_delta=5.1):

        assert power > 1, "Power must be 2 or greater"

        self._logger.info("Starting Polynomial smoothing")

        smooth_data = []
        times = self.times
        time_diffs = np.subtract.outer(times, times)
        filt = (time_diffs < time_delta) & (time_diffs > -time_delta)

        for id_plate, plate in enumerate(self._raw_growth_data):
            if plate is None:
                smooth_data.append(None)
                self._logger.info("Plate {0} has no data".format(id_plate + 1))
                continue

            log2_data = np.log2(plate).reshape(np.prod(plate.shape[:2]), plate.shape[-1])
            smooth_plate = np.array(tuple(
                tuple(self._poly_smoothen_raw_growth_curve(times, log2_curve, power, filt))
                for log2_curve in log2_data))

            self._logger.info("Plate {0} data polynomial smoothed".format(id_plate + 1))

            smooth_data.append(smooth_plate.reshape(plate.shape))

        self._smooth_growth_data = np.array(smooth_data)

        self._logger.info("Completed Polynomial smoothing")
//  [python]
def flatten_idx(idx, axis=-1):
    """Convert multidimensional index into index on flattened array.

    Convert a multidimensional index, that is values along a particular axis,
    so that it can derefence the flattened array properly. Note this is not
    the same as :func:`~numpy.ravel_multi_index`.

    Parameters
    ==========
    idx : array
        Input index, i.e. a list of elements along a particular axis,
        in the style of :func:`~numpy.argsort`.

    Other Parameters
    ================
    axis : int
        Axis along which ``idx`` operates, defaults to the last axis.

    Returns
    =======
    flat : array
        A 1D array of indices suitable for indexing the flat version of the
        array 

    See Also
    ========
    apply_index

    Examples
    ========
    >>> import numpy
    >>> import spacepy.datamanager
    >>> data = numpy.array([[3, 1, 2], [3, 2, 1]])
    >>> idx = numpy.argsort(data, -1)
    >>> idx_flat = spacepy.datamanager.flatten_idx(idx)
    >>> data.ravel() #flat array
    array([3, 1, 2, 3, 2, 1])
    >>> idx_flat #indices into the flat array
    array([1, 2, 0, 5, 4, 3])
    >>> data.ravel()[idx_flat] #index applied to the flat array
    array([1, 2, 3, 1, 2, 3])
    """
    idx = numpy.asanyarray(idx)
    if not idx.dtype.kind in ('i', 'u'):
        idx = idx.astype(int)
    preshape = idx.shape[:axis]
    postshape = idx.shape[axis:]
    stride = int(n.prod(postshape[1:])) #1 if applied to empty
    #The index on this axis moves stride elements in flat
    outidx = idx.flatten() * stride #makes a copy
    #First add the offsets to get us to [..., idx @ axis = 0, 0...)
    outidx += n.repeat(
        n.arange(0, len(outidx), int(n.prod(postshape)),
                     dtype=idx.dtype),
        n.prod(postshape))
    #Now offsets for non-zero on the trailing axes [0, 0, ... 0@axis, ...]
    outidx += n.tile(n.arange(0, stride, dtype=idx.dtype),
                           int(n.prod(preshape)) * idx.shape[axis])
    return outidx
//  [python]
def flatten_idx(idx, axis=-1):
    """Convert multidimensional index into index on flattened array.

    Convert a multidimensional index, that is values along a particular axis,
    so that it can derefence the flattened array properly. Note this is not
    the same as :func:`~numpy.ravel_multi_index`.

    Parameters
    ==========
    idx : array
        Input index, i.e. a list of elements along a particular axis,
        in the style of :func:`~numpy.argsort`.

    Other Parameters
    ================
    axis : int
        Axis along which ``idx`` operates, defaults to the last axis.

    Returns
    =======
    flat : array
        A 1D array of indices suitable for indexing the flat version of the
        array 

    See Also
    ========
    apply_index

    Examples
    ========
    >>> import numpy
    >>> import spacepy.datamanager
    >>> data = numpy.array([[3, 1, 2], [3, 2, 1]])
    >>> idx = numpy.argsort(data, -1)
    >>> idx_flat = spacepy.datamanager.flatten_idx(idx)
    >>> data.ravel() #flat array
    array([3, 1, 2, 3, 2, 1])
    >>> idx_flat #indices into the flat array
    array([1, 2, 0, 5, 4, 3])
    >>> data.ravel()[idx_flat] #index applied to the flat array
    array([1, 2, 3, 1, 2, 3])
    """
    idx = numpy.asanyarray(idx)
    if not idx.dtype.kind in ('i', 'u'):
        idx = idx.astype(int)
    preshape = idx.shape[:axis]
    postshape = idx.shape[axis:]
    stride = int(numpy.prod(postshape[1:])) #1 if applied to empty
    #The index on this axis moves stride elements in flat
    outidx = idx.flatten() * stride #makes a copy
    #First add the offsets to get us to [..., idx @ axis = 0, 0...)
    outidx += numpy.repeat(
        numpy.arange(0, len(outidx), int(numpy.prod(postshape)),
                     dtype=idx.dtype),
        numpy.prod(postshape))
    #Now offsets for non-zero on the trailing axes [0, 0, ... 0@axis, ...]
    outidx += numpy.tile(numpy.arange(0, stride, dtype=idx.dtype),
                           int(numpy.prod(preshape)) * idx.shape[axis])
    return outidx
//  [python]
def write_float64_data(self, array, name = None):
        number_of_components = array.shape[3:].prod()
        if len(array.shape[3:]) == 0:
            number_of_components = 1
            array = numpy.transpose(array, (2,1,0,)).flatten()
        else:
            x,y,z = numpy.split(array, 3, axis = array.ndim - 1)
            array = numpy.transpose(array, (2,1,0,) + tuple(array.shape[3:])).flatten()
        self.stream.write('<DataArray type="Float64" NumberOfComponents="{0}"'.format(number_of_components))
        if not name is None:
            self.stream.write(' Name="{0}"'.format(name))
        
        self.stream.write('>')
        self.stream.write(' '.join(map(self.convert_number_to_string, iter(array.flatten()))))
        self.stream.write('</DataArray>\n')
//  [python]
def write_float64_data(self, array, name = None):
        number_of_components = numpy.prod(array.shape[3:])
        if len(array.shape[3:]) == 0:
            number_of_components = 1
            array = numpy.transpose(array, (2,1,0,)).flatten()
        else:
            x,y,z = numpy.split(array, 3, axis = array.ndim - 1)
            array = numpy.transpose(array, (2,1,0,) + tuple(array.shape[3:])).flatten()
        self.stream.write('<DataArray type="Float64" NumberOfComponents="{0}"'.format(number_of_components))
        if not name is None:
            self.stream.write(' Name="{0}"'.format(name))
        
        self.stream.write('>')
        self.stream.write(' '.join(map(self.convert_number_to_string, iter(array.flatten()))))
        self.stream.write('</DataArray>\n')
//  [python]
def apply_along_axis(func1d, axis, arr, *args, **kwargs):
    """
    (This docstring should be overwritten)
    """
    arr = array(arr, copy=False, subok=True)
    nd = arr.ndim
    axis = normalize_axis_index(axis, nd)
    ind = [0] * (nd - 1)
    i = np.zeros(nd, 'O')
    indlist = list(range(nd))
    indlist.remove(axis)
    i[axis] = slice(None, None)
    outshape = np.asarray(arr.shape).take(indlist)
    i.put(indlist, ind)
    res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
    #  if res is a number, then we have a smaller output array
    asscalar = np.isscalar(res)
    if not asscalar:
        try:
            len(res)
        except TypeError:
            asscalar = True
    # Note: we shouldn't set the dtype of the output from the first result
    # so we force the type to object, and build a list of dtypes.  We'll
    # just take the largest, to avoid some downcasting
    dtypes = []
    if asscalar:
        dtypes.append(np.asarray(res).dtype)
        outarr = zeros(outshape, object)
        outarr[tuple(ind)] = res
        Ntot = n.multiply.reduce(outshape)
        k = 1
        while k < Ntot:
            # increment the index
            ind[-1] += 1
            n = -1
            while (ind[n] >= outshape[n]) and (n > (1 - nd)):
                ind[n - 1] += 1
                ind[n] = 0
                n -= 1
            i.put(indlist, ind)
            res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
            outarr[tuple(ind)] = res
            dtypes.append(asarray(res).dtype)
            k += 1
    else:
        res = array(res, copy=False, subok=True)
        j = i.copy()
        j[axis] = ([slice(None, None)] * res.ndim)
        j.put(indlist, ind)
        Ntot = n.multiply.reduce(outshape)
        holdshape = outshape
        outshape = list(arr.shape)
        outshape[axis] = res.shape
        dtypes.append(asarray(res).dtype)
        outshape = flatten_inplace(outshape)
        outarr = zeros(outshape, object)
        outarr[tuple(flatten_inplace(j.tolist()))] = res
        k = 1
        while k < Ntot:
            # increment the index
            ind[-1] += 1
            n = -1
            while (ind[n] >= holdshape[n]) and (n > (1 - nd)):
                ind[n - 1] += 1
                ind[n] = 0
                n -= 1
            i.put(indlist, ind)
            j.put(indlist, ind)
            res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
            outarr[tuple(flatten_inplace(j.tolist()))] = res
            dtypes.append(asarray(res).dtype)
            k += 1
    max_dtypes = np.dtype(np.asarray(dtypes).max())
    if not hasattr(arr, '_mask'):
        result = np.asarray(outarr, dtype=max_dtypes)
    else:
        result = asarray(outarr, dtype=max_dtypes)
        result.fill_value = ma.default_fill_value(result)
    return result
//  [python]
def forward(self, x):
        x = x.view(x.size(0), int(n.prod(x.size()[1:])))
        return x
//  [python]
def forward(self, x):
        x = x.view(x.size(0), int(numpy.prod(x.size()[1:])))
        return x
//  [python]
def write_int32_data(self, array, name = None):
        number_of_components = n.prod(array.shape[3:], dtype="int32")
        self.stream.write('<DataArray type="Int32" NumberOfComponents="{0}"'.format(number_of_components))
        if not name is None:
            self.stream.write(' Name="{0}"'.format(name))
        
        self.stream.write('>')
        self.stream.write(' '.join(map(self.convert_number_to_string, iter(array.flatten()))))
        self.stream.write('</DataArray>\n')
//  [python]
def write_int32_data(self, array, name = None):
        number_of_components = numpy.prod(array.shape[3:], dtype="int32")
        self.stream.write('<DataArray type="Int32" NumberOfComponents="{0}"'.format(number_of_components))
        if not name is None:
            self.stream.write(' Name="{0}"'.format(name))
        
        self.stream.write('>')
        self.stream.write(' '.join(map(self.convert_number_to_string, iter(array.flatten()))))
        self.stream.write('</DataArray>\n')
//  [python]
def write_grid(self):
        self.stream.write('<UnstructuredGrid>\n')
        if self.is_multiple:
            for subgrid in self.set:
                
                quantities = subgrid.get_values_in_store(None, self.attribute_names)
                points = subgrid.points()
                number_of_cells =  n.prod(subgrid.shape)
                offsets = ((n.arange(number_of_cells, dtype=n.int32) + 1) * 8)
                self.write_piece(
                    quantities,
                    self.attribute_types,
                    self.attribute_names,
                    points,
                    subgrid.connectivity().flatten(),
                    offsets,
                    self.cell_types_for_grid(subgrid),
                    n.prod(subgrid.shape),
                    n.prod(points.shape[:-1])
                )
        else:
            self.write_piece(
                self.quantities,
                self.attribute_types,
                self.attribute_names,
                self.points,
                self.connectivity,
                self.offsets,
                self.cell_types,
                self.number_of_cells,
                self.number_of_points
                
            )
            
        self.stream.write('</UnstructuredGrid>\n')
//  [python]
def write_grid(self):
        self.stream.write('<UnstructuredGrid>\n')
        if self.is_multiple:
            for subgrid in self.set:
                
                quantities = subgrid.get_values_in_store(None, self.attribute_names)
                points = subgrid.points()
                number_of_cells =  numpy.prod(subgrid.shape)
                offsets = ((numpy.arange(number_of_cells, dtype=numpy.int32) + 1) * 8)
                self.write_piece(
                    quantities,
                    self.attribute_types,
                    self.attribute_names,
                    points,
                    subgrid.connectivity().flatten(),
                    offsets,
                    self.cell_types_for_grid(subgrid),
                    numpy.prod(subgrid.shape),
                    numpy.prod(points.shape[:-1])
                )
        else:
            self.write_piece(
                self.quantities,
                self.attribute_types,
                self.attribute_names,
                self.points,
                self.connectivity,
                self.offsets,
                self.cell_types,
                self.number_of_cells,
                self.number_of_points
                
            )
            
        self.stream.write('</UnstructuredGrid>\n')
//  [python]
def restore_from_ckpt(self, ckpt, compile_model=False):
    """Restore network weights from a checkpoint."""
    if compile_model:
      try:
        obs_space = mime_env_utils.make_dict_space(
            self.env.scene, *self.visible_state_features)
      except AttributeError:
        obs_space = self.env.observation_space
      scalar_sizes = [
          obs_space[feat].shape for feat in self.visible_state_features]
      scalars_size = int(np.sum([np.prod(a) for a in scalar_sizes]))
      dummy_input = np.random.rand(1, *self.input_shape)
      dummy_scalars = np.random.rand(1, scalars_size)
      _ = self.network(dummy_input, dummy_scalars)
    self.network.load_weights(ckpt)
//  [python]
def fuse_dimensions(self, obs):
    """If using late fusion, set history first. Else merge history and channels.

    Args:
      obs: Input image observation of shape [height, width, history, channels].

    Returns:
      obs: Reshaped image observation.
    """
    if self.late_fusion:
      # Set history as the first dimension.
      obs = np.moveaxis(obs, 2, 0)
    else:
      # Merge history and image channels (if any).
      obs = np.reshape(obs, [*obs.shape[:2], np.prod(obs.shape[2:])])
    return obs
//  [python]
def test_quantized_transpose(shape, axes):
    """Test quantized transpose."""

    n_bits_transpose = MAX_BITWIDTH_BACKWARD_COMPATIBLE

    num_values = n.prod(n.asarray(shape))
    data = n.arange(num_values).astype(n.float32)
    data = data.reshape(shape)

    q_arr0 = QuantizedArray(n_bits_transpose, data)

    transpose = QuantizedTranspose(
        n_bits_transpose,
        OP_DEBUG_NAME + "QuantizedTranspose",
        input_quant_opts=q_arr0.quantizer.quant_options,
        perm=axes,
    )

    q_transposed = transpose(q_arr0)

    assert q_transposed.quantizer.zero_point == q_arr0.quantizer.zero_point
    assert q_transposed.quantizer.scale == q_arr0.quantizer.scale
    assert n.all(n.transpose(q_arr0.qvalues, axes) == q_transposed.qvalues)

    # Test the serialization of QuantizedTranspose
    check_serialization(
        transpose,
        QuantizedTranspose,
        equal_method=partial(quantized_op_results_are_equal, q_input=q_arr0),
    )
//  [python]
def test_quantized_transpose(shape, axes):
    """Test quantized transpose."""

    n_bits_transpose = MAX_BITWIDTH_BACKWARD_COMPATIBLE

    num_values = numpy.prod(numpy.asarray(shape))
    data = numpy.arange(num_values).astype(numpy.float32)
    data = data.reshape(shape)

    q_arr0 = QuantizedArray(n_bits_transpose, data)

    transpose = QuantizedTranspose(
        n_bits_transpose,
        OP_DEBUG_NAME + "QuantizedTranspose",
        input_quant_opts=q_arr0.quantizer.quant_options,
        perm=axes,
    )

    q_transposed = transpose(q_arr0)

    assert q_transposed.quantizer.zero_point == q_arr0.quantizer.zero_point
    assert q_transposed.quantizer.scale == q_arr0.quantizer.scale
    assert numpy.all(numpy.transpose(q_arr0.qvalues, axes) == q_transposed.qvalues)

    # Test the serialization of QuantizedTranspose
    check_serialization(
        transpose,
        QuantizedTranspose,
        equal_method=partial(quantized_op_results_are_equal, q_input=q_arr0),
    )
//  [python]
def test_quantized_expand(original_shape, expand_shape):
    """Test quantized expand."""

    n_bits_expand = MAX_BITWIDTH_BACKWARD_COMPATIBLE

    num_values = numpy.prod(numpy.asarray(original_shape))
    data = numpy.arange(num_values).astype(numpy.float32)
    data = data.reshape(original_shape)

    q_arr0 = QuantizedArray(n_bits_expand, data)

    # Apply QuantizedExpand operation
    expand = QuantizedExpand(
        n_bits_expand,
        OP_DEBUG_NAME + "QuantizedExpand",
        constant_inputs={1: numpy.asarray(expand_shape)},
        input_quant_opts=q_arr0.quantizer.quant_options,
    )

    q_expanded = expand(q_arr0)

    # Assertions for expanded array
    assert q_expanded.quantizer.zero_point == q_arr0.quantizer.zero_point
    assert q_expanded.quantizer.scale == q_arr0.quantizer.scale
    assert q_expanded.qvalues.shape == expand_shape
    assert numpy.all(numpy.broadcast_to(q_arr0.qvalues, expand_shape) == q_expanded.qvalues)

    # Test the serialization of QuantizedExpand (if applicable)
    # Replace with appropriate serialization test if needed
    check_serialization(
        expand,
        QuantizedExpand,
        equal_method=partial(quantized_op_results_are_equal, q_input=q_arr0),
    )
//  [python]
def test_quantized_flatten(input_shape, expected_shape, axis, is_signed):
    """Test the flatten operator on quantized data."""

    n_bits_reshape = 7

    # Generate data with the desired shape
    num_values = n.prod(n.asarray(input_shape))
    data = n.arange(num_values).astype(n.float32)
    data = data.reshape(input_shape)
    q_data = QuantizedArray(n_bits_reshape, data, is_signed=is_signed)

    # Create the operator and calibrate
    flatten_op = QuantizedFlatten(
        n_bits_reshape,
        OP_DEBUG_NAME + "QuantizedFlatten",
        axis=axis,
        input_quant_opts=q_data.quantizer.quant_options,
    )
    flatten_op.calibrate(data)

    # Flatten a quantized array of data
    q_reshaped = flatten_op(q_data)

    # Check that the output calibration parameters did not change as flatten should not change
    # the data
    assert q_reshaped.quantizer.zero_point == q_data.quantizer.zero_point
    assert q_reshaped.quantizer.scale == q_data.quantizer.scale

    # Check that the data was not changed and is in the same order (i.e., no transposition)
    assert n.all(q_data.qvalues.ravel() == q_reshaped.qvalues.ravel())

    # Check that the output has the expected shape
    assert n.all(q_reshaped.qvalues.shape == expected_shape)

    # Test the serialization of QuantizedFlatten
    check_serialization(
        flatten_op,
        QuantizedFlatten,
        equal_method=partial(quantized_op_results_are_equal, q_input=q_data),
    )
//  [python]
def test_quantized_flatten(input_shape, expected_shape, axis, is_signed):
    """Test the flatten operator on quantized data."""

    n_bits_reshape = 7

    # Generate data with the desired shape
    num_values = numpy.prod(numpy.asarray(input_shape))
    data = numpy.arange(num_values).astype(numpy.float32)
    data = data.reshape(input_shape)
    q_data = QuantizedArray(n_bits_reshape, data, is_signed=is_signed)

    # Create the operator and calibrate
    flatten_op = QuantizedFlatten(
        n_bits_reshape,
        OP_DEBUG_NAME + "QuantizedFlatten",
        axis=axis,
        input_quant_opts=q_data.quantizer.quant_options,
    )
    flatten_op.calibrate(data)

    # Flatten a quantized array of data
    q_reshaped = flatten_op(q_data)

    # Check that the output calibration parameters did not change as flatten should not change
    # the data
    assert q_reshaped.quantizer.zero_point == q_data.quantizer.zero_point
    assert q_reshaped.quantizer.scale == q_data.quantizer.scale

    # Check that the data was not changed and is in the same order (i.e., no transposition)
    assert numpy.all(q_data.qvalues.ravel() == q_reshaped.qvalues.ravel())

    # Check that the output has the expected shape
    assert numpy.all(q_reshaped.qvalues.shape == expected_shape)

    # Test the serialization of QuantizedFlatten
    check_serialization(
        flatten_op,
        QuantizedFlatten,
        equal_method=partial(quantized_op_results_are_equal, q_input=q_data),
    )
//  [python]
def test_quantized_reshape(shape):
    """Test quantized reshape."""

    n_bits_reshape = MAX_BITWIDTH_BACKWARD_COMPATIBLE

    num_values = n.prod(n.asarray(shape))
    data = numpy.arange(num_values).astype(numpy.float32)
    data = data.reshape(shape)

    q_arr0 = QuantizedArray(n_bits_reshape, data)

    new_shape = numpy.asarray((num_values,))
    reshape = QuantizedReshape(
        n_bits_reshape,
        OP_DEBUG_NAME + "QuantizedReshape",
        constant_inputs={1: new_shape},
        input_quant_opts=q_arr0.quantizer.quant_options,
    )

    q_reshaped = reshape(q_arr0)

    assert q_reshaped.quantizer.zero_point == q_arr0.quantizer.zero_point
    assert q_reshaped.quantizer.scale == q_arr0.quantizer.scale
    assert numpy.all(numpy.reshape(q_arr0.qvalues, new_shape) == q_reshaped.qvalues)

    reshape_back = QuantizedReshape(
        n_bits_reshape,
        OP_DEBUG_NAME + "QuantizedReshape",
        constant_inputs={1: numpy.asarray(shape)},
        input_quant_opts=q_arr0.quantizer.quant_options,
    )

    q_arr1 = reshape_back(q_reshaped)
    assert q_arr1.quantizer.zero_point == q_arr0.quantizer.zero_point
    assert q_arr1.quantizer.scale == q_arr0.quantizer.scale
    assert numpy.all(q_arr0.qvalues == q_arr1.qvalues)

    # Test the serialization of QuantizedReshape
    check_serialization(
        reshape,
        QuantizedReshape,
        equal_method=partial(quantized_op_results_are_equal, q_input=q_arr0),
    )
//  [python]
def test_quantized_reshape(shape):
    """Test quantized reshape."""

    n_bits_reshape = MAX_BITWIDTH_BACKWARD_COMPATIBLE

    num_values = numpy.prod(numpy.asarray(shape))
    data = numpy.arange(num_values).astype(numpy.float32)
    data = data.reshape(shape)

    q_arr0 = QuantizedArray(n_bits_reshape, data)

    new_shape = numpy.asarray((num_values,))
    reshape = QuantizedReshape(
        n_bits_reshape,
        OP_DEBUG_NAME + "QuantizedReshape",
        constant_inputs={1: new_shape},
        input_quant_opts=q_arr0.quantizer.quant_options,
    )

    q_reshaped = reshape(q_arr0)

    assert q_reshaped.quantizer.zero_point == q_arr0.quantizer.zero_point
    assert q_reshaped.quantizer.scale == q_arr0.quantizer.scale
    assert numpy.all(numpy.reshape(q_arr0.qvalues, new_shape) == q_reshaped.qvalues)

    reshape_back = QuantizedReshape(
        n_bits_reshape,
        OP_DEBUG_NAME + "QuantizedReshape",
        constant_inputs={1: numpy.asarray(shape)},
        input_quant_opts=q_arr0.quantizer.quant_options,
    )

    q_arr1 = reshape_back(q_reshaped)
    assert q_arr1.quantizer.zero_point == q_arr0.quantizer.zero_point
    assert q_arr1.quantizer.scale == q_arr0.quantizer.scale
    assert numpy.all(q_arr0.qvalues == q_arr1.qvalues)

    # Test the serialization of QuantizedReshape
    check_serialization(
        reshape,
        QuantizedReshape,
        equal_method=partial(quantized_op_results_are_equal, q_input=q_arr0),
    )
//  [python]
def cheb1ap(N, rp):
    """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type I lowpass
    analog filter prototype with `rp` decibels of ripple in the passband.

    The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
    defined as the point at which the gain first drops below -`rp`.

    """
    z = numpy.array([])
    eps = numpy.sqrt(10 ** (0.1 * rp) - 1.0)
    n = numpy.arange(1, N + 1)
    mu = 1.0 / N * numpy.log((1.0 + numpy.sqrt(1 + eps * eps)) / eps)
    theta = pi / 2.0 * (2 * n - 1.0) / N
    p = (-numpy.sinh(mu) * numpy.sin(theta) +
         1j * numpy.cosh(mu) * numpy.cos(theta))
    k = n.prod(-p, axis=0).real
    if N % 2 == 0:
        k = k / sqrt((1 + eps * eps))
    return z, p, k
//  [python]
def cheb1ap(N, rp):
    """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type I lowpass
    analog filter prototype with `rp` decibels of ripple in the passband.

    The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
    defined as the point at which the gain first drops below -`rp`.

    """
    z = numpy.array([])
    eps = numpy.sqrt(10 ** (0.1 * rp) - 1.0)
    n = numpy.arange(1, N + 1)
    mu = 1.0 / N * numpy.log((1.0 + numpy.sqrt(1 + eps * eps)) / eps)
    theta = pi / 2.0 * (2 * n - 1.0) / N
    p = (-numpy.sinh(mu) * numpy.sin(theta) +
         1j * numpy.cosh(mu) * numpy.cos(theta))
    k = numpy.prod(-p, axis=0).real
    if N % 2 == 0:
        k = k / sqrt((1 + eps * eps))
    return z, p, k
//  [python]
def test_stable_product():
    """Test stable_product."""
    generator = numpy.random.default_rng(seed=0)
    array = generator.random(size=(13,))

    # positive values only
    numpy.testing.assert_almost_equal(stable_product(array), n.prod(array))
    numpy.testing.assert_almost_equal(stable_product(np.log(array), is_log=True), n.prod(array))

    # positive and negative values
    array = 2 * array - 1
    numpy.testing.assert_almost_equal(stable_product(array), n.prod(array))
//  [python]
def test_stable_product():
    """Test stable_product."""
    generator = numpy.random.default_rng(seed=0)
    array = generator.random(size=(13,))

    # positive values only
    numpy.testing.assert_almost_equal(stable_product(array), numpy.prod(array))
    numpy.testing.assert_almost_equal(stable_product(np.log(array), is_log=True), numpy.prod(array))

    # positive and negative values
    array = 2 * array - 1
    numpy.testing.assert_almost_equal(stable_product(array), numpy.prod(array))
//  [python]
def cheb2ap(N, rs):
    """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type II lowpass
    analog filter prototype with `rs` decibels of ripple in the stopband.

    The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
    defined as the point at which the gain first reaches -`rs`.

    """
    de = 1.0 / sqrt(10 ** (0.1 * rs) - 1)
    mu = arcsinh(1.0 / de) / N

    if N % 2:
        n = numpy.concatenate((numpy.arange(1, N - 1, 2),
                               numpy.arange(N + 2, 2 * N, 2)))
    else:
        n = numpy.arange(1, 2 * N, 2)

    z = conjugate(1j / cos(n * pi / (2.0 * N)))
    p = exp(1j * (pi * numpy.arange(1, 2 * N, 2) / (2.0 * N) + pi / 2.0))
    p = sinh(mu) * p.real + 1j * cosh(mu) * p.imag
    p = 1.0 / p
    k = (n.prod(-p, axis=0) / n.prod(-z, axis=0)).real
    return z, p, k
//  [python]
def cheb2ap(N, rs):
    """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type II lowpass
    analog filter prototype with `rs` decibels of ripple in the stopband.

    The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
    defined as the point at which the gain first reaches -`rs`.

    """
    de = 1.0 / sqrt(10 ** (0.1 * rs) - 1)
    mu = arcsinh(1.0 / de) / N

    if N % 2:
        n = numpy.concatenate((numpy.arange(1, N - 1, 2),
                               numpy.arange(N + 2, 2 * N, 2)))
    else:
        n = numpy.arange(1, 2 * N, 2)

    z = conjugate(1j / cos(n * pi / (2.0 * N)))
    p = exp(1j * (pi * numpy.arange(1, 2 * N, 2) / (2.0 * N) + pi / 2.0))
    p = sinh(mu) * p.real + 1j * cosh(mu) * p.imag
    p = 1.0 / p
    k = (numpy.prod(-p, axis=0) / numpy.prod(-z, axis=0)).real
    return z, p, k
//  [python]
def filter_labels(a, min_size, max_size=None):
    """
    Remove (set to 0) labeled connected components that are too small or too large.
    Note: Operates in-place.
    """
    if min_size == 0 and (max_size is None or max_size > numpy.prod(a.shape)):  # shortcut for efficiency
        return a

    component_sizes = vigra_bincount(a)
    bad_sizes = component_sizes < min_size
    if max_size is not None:
        numpy.logical_or(bad_sizes, component_sizes > max_size, out=bad_sizes)

    bad_locations = bad_sizes[a]
    a[bad_locations] = 0
    return a
//  [python]
def tensorlab2tensor(lab_tensor,return_inbnd=False):
    from skimage import color
    import warnings
    warnings.filterwarnings("ignore")

    lab = tensor2np(lab_tensor)*100.
    lab[:,:,0] = lab[:,:,0]+50
    # print('lab',lab)

    rgb_back = 255.*np.clip(color.lab2rgb(lab.astype('float')),0,1)
    # print('rgb',rgb_back)
    if(return_inbnd):
        # convert back to lab, see if we match
        lab_back = color.rgb2lab(rgb_back.astype('uint8'))
        # print('lab_back',lab_back)
        # print('lab==lab_back',np.isclose(lab_back,lab,atol=1.))
        # print('lab-lab_back',np.abs(lab-lab_back))
        mask = 1.*np.isclose(lab_back,lab,atol=2.)
        mask = np2tensor(np.all(mask,axis=2)[:,:,np.newaxis])
        return (im2tensor(rgb_back),mask)
    else:
        return im2tensor(rgb_back)
//  [python]
def tensorlab2tensor(lab_tensor,return_inbnd=False):
    from skimage import color
    import warnings
    warnings.filterwarnings("ignore")

    lab = tensor2np(lab_tensor)*100.
    lab[:,:,0] = lab[:,:,0]+50
    # print('lab',lab)

    rgb_back = 255.*np.clip(color.lab2rgb(lab.astype('float')),0,1)
    # print('rgb',rgb_back)
    if(return_inbnd):
        # convert back to lab, see if we match
        lab_back = color.rgb2lab(rgb_back.astype('uint8'))
        # print('lab_back',lab_back)
        # print('lab==lab_back',np.isclose(lab_back,lab,atol=1.))
        # print('lab-lab_back',np.abs(lab-lab_back))
        mask = 1.*np.isclose(lab_back,lab,atol=2.)
        mask = np2tensor(np.prod(mask,axis=2)[:,:,np.newaxis])
        return (im2tensor(rgb_back),mask)
    else:
        return im2tensor(rgb_back)
//  [python]
def get_compression_stats(self):
        stats = {}

        # calculate how many entries are actually filled in the buffer
        nonempty_chunks = [i for i, (_, _x) in enumerate(self._storage.items()) if _x is not None]
        stats["fill_level"] = float(len(nonempty_chunks)) / float(len(self._storage.keys()))

        # calculate compression ratio
        from itertools import product
        chunk_compression_ratios = [len(_x) / (np.asscalar(np.prod(np.array(self.shape))) * self.chunk_size * self.np_dtype.itemsize) for
                                    k, _x in self._storage.items() if _x is not None]
        stats["compression_ratio"] = np.asscalar(np.array(chunk_compression_ratios).mean())

        stats["predicted_full_size_compressed"] = stats["compression_ratio"] * self.chunk_size * len(self._storage.keys()) * np.asscalar(np.prod(np.array(self.shape))*self.np_dtype.itemsize)
        stats["predicted_full_size_uncompressed"] = self.chunk_size * len(self._storage.keys()) * np.asscalar(np.prod(np.array(self.shape))*self.np_dtype.itemsize)
        return stats
//  [python]
def vector_norm(x: Array, /, *, axis: Optional[Union[int, Tuple[int, int]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> Array:
    """
    Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`.

    See its docstring for more information.
    """
    # Note: the restriction to floating-point dtypes only is different from
    # np.linalg.norm.
    if x.dtype not in _floating_dtypes:
        raise TypeError('Only floating-point dtypes are allowed in norm')

    a = x._array
    if axis is None:
        a = a.flatten()
        axis = 0
    elif isinstance(axis, tuple):
        # Note: The axis argument supports any number of axes, whereas norm()
        # only supports a single axis for vector norm.
        rest = tuple(i for i in range(a.ndim) if i not in axis)
        newshape = axis + rest
        a = np.transpose(a, newshape).reshape((n.prod([a.shape[i] for i in axis]), *[a.shape[i] for i in rest]))
        axis = 0
    return Array._new(np.linalg.norm(a, axis=axis, keepdims=keepdims, ord=ord))
//  [python]
def vector_norm(x: Array, /, *, axis: Optional[Union[int, Tuple[int, int]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> Array:
    """
    Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`.

    See its docstring for more information.
    """
    # Note: the restriction to floating-point dtypes only is different from
    # np.linalg.norm.
    if x.dtype not in _floating_dtypes:
        raise TypeError('Only floating-point dtypes are allowed in norm')

    a = x._array
    if axis is None:
        a = a.flatten()
        axis = 0
    elif isinstance(axis, tuple):
        # Note: The axis argument supports any number of axes, whereas norm()
        # only supports a single axis for vector norm.
        rest = tuple(i for i in range(a.ndim) if i not in axis)
        newshape = axis + rest
        a = np.transpose(a, newshape).reshape((np.prod([a.shape[i] for i in axis]), *[a.shape[i] for i in rest]))
        axis = 0
    return Array._new(np.linalg.norm(a, axis=axis, keepdims=keepdims, ord=ord))
//  [python]
def __init__(self, neurons, name=None, activation=tensor.tanh, dropout=False, shape=None):
        self.name = name
        self.dropout = dropout

        # Allow strings to be used as activation functions for standard variations
        if hasattr(activation, '__call__'):
            self.activation = activation
        elif type(activation) == str:
            if activation == "tanh":
                self.activation = tensor.tanh
            if activation == "linear":
                self.activation = lambda x : x
            if activation in ["sigmoid", "softmax", "logistic"]:
                self.activation = softmax

        # Allow specific shapes on the outputs
        if shape is None:
            self.shape = (neurons,)
        elif n.prod(shape) != neurons:
            raise Exception("Number of neurons (%d) does not match shape (%s)" % (neurons, str(shape)))
        else:
            self.shape = shape