Convert an ND4J array to a numpy array
    :param nd4j_array:
    :return:
347129
def to_numpy(nd4j_array):
    
    buff = nd4j_array.data()
    address = buff.pointer().address()
    type_name = java_classes.DataTypeUtil.getDtypeFromContext()
    data_type = java_classes.DataTypeUtil.getDTypeForName(type_name)
    mapping = {
        'double': ctypes.c_double,
        'float': ctypes.c_float
    }
    Pointer = ctypes.POINTER(mapping[data_type])
    pointer = ctypes.cast(address, Pointer)
    np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape()))
    return np_array
578881
def ndarray_to_imagedatadict(nparr):
    
    ret = {}
    dm_type = None
    for k, v in iter(dm_image_dtypes.items()):
        if v[1] == nparr.dtype.type:
            dm_type = k
            break
    if dm_type is None and nparr.dtype == numpy.uint8 and nparr.shape[-1] in (3, 4):
        ret["DataType"] = 23
        ret["PixelDepth"] = 4
        if nparr.shape[2] == 4:
            rgb_view = nparr.view(numpy.int32).reshape(nparr.shape[:-1])  # squash the color into uint32
        else:
            assert nparr.shape[2] == 3
            rgba_image = numpy.empty(nparr.shape[:-1] + (4,), numpy.uint8)
            rgba_image[:,:,0:3] = nparr
            rgba_image[:,:,3] = 255
            rgb_view = rgba_image.view(numpy.int32).reshape(rgba_image.shape[:-1])  # squash the color into uint32
        ret["Dimensions"] = list(rgb_view.shape[::-1])
        ret["Data"] = parse_dm3.array.array(platform_independent_char(rgb_view.dtype), rgb_view.flatten())
    else:
        ret["DataType"] = dm_type
        ret["PixelDepth"] = nparr.dtype.itemsize
        ret["Dimensions"] = list(nparr.shape[::-1])
        if nparr.dtype.type in np_to_structarray_map:
            types = np_to_structarray_map[nparr.dtype.type]
            ret["Data"] = parse_dm3.structarray(types)
            ret["Data"].raw_data = bytes(numpy.array(nparr, copy=False).data)
        else:
            ret["Data"] = parse_dm3.array.array(platform_independent_char(nparr.dtype), numpy.array(nparr, copy=False).flatten())
    return ret
774858
def fromNumpy(cls, data):
        
        assert np is not None
        if isinstance(data, np.ndarray):
            index = []
            if len(data.shape) == 1:
                columns = [('value', data.tolist())]
            elif len(data.shape) == 2:
                columns = [
                    ('c{}'.format(i), col)
                    for i, col in enumerate(zip(*data.tolist()))
                ]
            else:
                raise TypeError
        else:
            raise TypeError
        return cls(index=index, columns=columns)
593040
def numpy_buffer(ndarray):
    """"""
    # Credits to: https://github.com/joblib/joblib/blob/04b001861e1dd03a857b7b419c336de64e05714c/joblib/hashing.py

    if isinstance(ndarray, (pd.Series, pd.DataFrame)):
        ndarray = ndarray.values

    if ndarray.flags.c_contiguous:
        obj_c_contiguous = ndarray
    elif ndarray.flags.f_contiguous:
        obj_c_contiguous = ndarray.T
    else:
        obj_c_contiguous = ndarray.flatten()

    obj_c_contiguous = obj_c_contiguous.view(np.uint8)

    if hasattr(np, 'getbuffer'):
        return np.getbuffer(obj_c_contiguous)
    else:
        return memoryview(obj_c_contiguous)
131722
def to_native_types(self, slicer=None, na_rep='', quoting=None, **kwargs):
        

        values = self.values
        if slicer is not None:
            # Categorical is always one dimension
            values = values[slicer]
        mask = isna(values)
        values = np.array(values, dtype='object')
        values[mask] = na_rep

        # we are expected to return a 2-d ndarray
        return values.reshape(1, len(values))
562062
def to_numpy(X):
    
    if isinstance(X, np.ndarray):
        return X

    if is_pandas_ndframe(X):
        return X.values

    if not is_torch_data_type(X):
        raise TypeError("Cannot convert this data type to a numpy array.")

    if X.is_cuda:
        X = X.cpu()

    if X.requires_grad:
        X = X.detach()

    return X.numpy()
973702
def to_np(v):
    ''''''
    if isinstance(v, float): return np.array(v)
    if isinstance(v, (np.ndarray, np.generic)): return v
    if isinstance(v, (list,tuple)): return [to_np(o) for o in v]
    if isinstance(v, Variable): v=v.data
    if torch.cuda.is_available():
        if is_half_tensor(v): v=v.float()
    if isinstance(v, torch.FloatTensor): v=v.float()
    return v.cpu().numpy()
925156
def to_dict(self):
        
        def _json_safe(v):
            if isinstance(v, np.ndarray):
                return v.tolist()
            elif is_unit(v)[0]:
                return v.to_string()
            else:
                return v
        d = {k:_json_safe(v) for k,v in self._descriptors.items()}
        d['nparray'] = self.__class__.__name__.lower()
        return d
944432
def from_array(array):
        
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        data = {}
        data['point'] = u(array.get('point'))
        data['x_shift'] = float(array.get('x_shift'))
        data['y_shift'] = float(array.get('y_shift'))
        data['scale'] = float(array.get('scale'))
        data['_raw'] = array
        return MaskPosition(**data)
1056267
def unbroadcast_numpy_to(array, shape):
  
  axis = create_unbroadcast_axis(shape, numpy.shape(array))
  return numpy.reshape(numpy.sum(array, axis=axis), shape)
735538
def to_vector(np_array):
    
    if len(np_array.shape) == 1:
        return Vectors.dense(np_array)
    else:
        raise Exception("An MLLib Vector can only be created from a one-dimensional " +
                        "numpy array, got {}".format(len(np_array.shape)))
991814
def _to_array(self, itaper, normalization='4pi', csphase=1):
        
        coeffs = _shtools.SHVectorToCilm(self.tapers[:, itaper])

        if normalization == 'schmidt':
            for l in range(self.lwin + 1):
                coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
        elif normalization == 'ortho':
            coeffs *= _np.sqrt(4.0 * _np.pi)

        if csphase == -1:
            for m in range(self.lwin + 1):
                if m % 2 == 1:
                    coeffs[:, :, m] = - coeffs[:, :, m]

        return coeffs
1050554
def _coerce_to_ndarray(self):
        

        # TODO(jreback) make this better
        data = self._data.astype(object)
        data[self._mask] = self._na_value
        return data
492780
def as_2d_array(theta):
    
    v = theta.view(np.float)
    N = theta.shape[0]
    v.shape = (N, - 1)
    # raise an error if v cannot be reshaped without creating a copy
    return v
858086
def sumai(array):
    
    n = ctypes.c_int(len(array))
    array = stypes.toIntVector(array)
    return libspice.sumai_c(array, n)
1188969
def network_from_array(self, array):
        
        if len(array.shape) == 2:
            array = np.array(array, ndmin=3).transpose([1, 2, 0])
        teneto.utils.check_TemporalNetwork_input(array, 'array')
        uvals = np.unique(array)
        if len(uvals) == 2 and 1 in uvals and 0 in uvals:
            i, j, t = np.where(array == 1)
            self.network = pd.DataFrame(data={'i': i, 'j': j, 't': t})
        else:
            i, j, t = np.where(array != 0)
            w = array[array != 0]
            self.network = pd.DataFrame(
                data={'i': i, 'j': j, 't': t, 'weight': w})
        self.N = int(array.shape[0])
        self.T = int(array.shape[-1])
        self._update_network()
616054
def json_numpy_obj_hook(dct):
    
    if isinstance(dct, dict) and '__ndarray__' in dct:
        data = np.asarray(dct['__ndarray__'], dtype=dct['dtype'])
        return data.reshape(dct['shape'])
    return dct