Wrap numpy.ndarray as Value
166733
def wrap(self, value):
        
        attrib = getattr(value, 'attrib', {})

        S, NS = divmod(time.time(), 1.0)
        value = numpy.asarray(value) # loses any special/augmented attributes
        dims = list(value.shape)
        dims.reverse() # inner-most sent as left

        if 'ColorMode' not in attrib:
            # attempt to infer color mode from shape
            if value.ndim==2:
                attrib['ColorMode'] = 0 # gray

            elif value.ndim==3:
                for idx,dim in enumerate(dims):
                    if dim==3: # assume it's a color
                        attrib['ColorMode'] = 2 + idx  # 2 - RGB1, 3 - RGB2, 4 - RGB3
                        break # assume that the first is color, and any subsequent dim=3 is a thin ROI

        dataSize = value.nbytes

        return Value(self.type, {
            'value': (self._code2u[value.dtype.char], value.flatten()),
            'compressedSize': dataSize,
            'uncompressedSize': dataSize,
            'uniqueId': 0,
            'timeStamp': {
                'secondsPastEpoch': S,
                'nanoseconds': NS * 1e9,
            },
            'attribute': [{'name': K, 'value': V} for K, V in attrib.items()],
            'dimension': [{'size': N,
                           'offset': 0,
                           'fullSize': N,
                           'binning': 1,
                           'reverse': False} for N in dims],
        })
272537
function ndarrayLike( v ) {
	return v !== null &&
		typeof v === 'object' &&
		typeof v.data === 'object' &&
		typeof v.shape === 'object' &&
		typeof v.strides === 'object' &&
		typeof v.offset === 'number' &&
		typeof v.dtype === 'string' &&
		typeof v.length === 'number';
}
1034617
def fn_int32(self, value):
        

        if is_ndarray(value) or isinstance(value, (list, tuple)):
            return self._to_ndarray(value).astype(numpy.int32)
        else:
            return int(value)
1185602
def _to_ndarray(self, a):
        """"""

        if isinstance(a, (list, tuple)):
            a = numpy.array(a)

        if not is_ndarray(a):
            raise TypeError("Expected an ndarray but got object of type '{}' instead".format(type(a)))

        return a
296672
def paramsarray(self, value):
        """"""
        nparams = len(self._index_to_param)
        assert (isinstance(value, scipy.ndarray) and value.ndim == 1), (
                "paramsarray must be 1-dim ndarray")
        assert len(value) == nparams, ("Assigning paramsarray to ndarray "
                "of the wrong length.")
        if (self._paramsarray is not None) and all(value == self._paramsarray):
            return # do not need to do anything if value has not changed
        # build `newvalues` to pass to `updateParams`
        newvalues = {}
        vectorized_params = {}
        for (i, param) in self._index_to_param.items():
            if isinstance(param, str):
                newvalues[param] = float(value[i])
            elif isinstance(param, tuple):
                (iparam, iparamindex) = param
                if iparam in vectorized_params:
                    assert iparamindex not in vectorized_params[iparam]
                    vectorized_params[iparam][iparamindex] = float(value[i])
                else:
                    vectorized_params[iparam] = {iparamindex:float(value[i])}
            else:
                raise ValueError("Invalid param type")
        for (param, paramd) in vectorized_params.items():
            assert set(paramd.keys()) == set(range(len(paramd)))
            newvalues[param] = scipy.array([paramd[i] for i in range(len(paramd))],
                    dtype='float')
        self.updateParams(newvalues)
        self._paramsarray = self.paramsarray
81982
def wrapping(self):
        
        value = self._wrapping
        return value[0] if all([v == value[0] for v in value]) else value
1286626
def normalize_attr_array(a: Any) -> np.ndarray:
	
	if type(a) is np.ndarray:
		return a
	elif type(a) is np.matrix:
		if a.shape[0] == 1:
			return np.array(a)[0, :]
		elif a.shape[1] == 1:
			return np.array(a)[:, 0]
		else:
			raise ValueError("Attribute values must be 1-dimensional.")
	elif type(a) is list or type(a) is tuple:
		return np.array(a)
	elif sparse.issparse(a):
		return normalize_attr_array(a.todense())
	else:
		raise ValueError("Argument must be a list, tuple, numpy matrix, numpy ndarray or sparse matrix.")
430908
def _ndarray_assoc(arr, k, v):
    ''
    arr = np.array(arr)
    arr[k] = v
    arr.setflags(write=False)
    return arr
1065233
def c_array(ctype, values):
    """"""
    if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):
        return (ctype * len(values)).from_buffer_copy(values)
    return (ctype * len(values))(*values)
153665
def preserve_channel_dim(func):
    """"""
    @wraps(func)
    def wrapped_function(img, *args, **kwargs):
        shape = img.shape
        result = func(img, *args, **kwargs)
        if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2:
            result = np.expand_dims(result, axis=-1)
        return result

    return wrapped_function
43733
def serialize_ndarray_readable(o):
    
    return dict(
        _type='np.ndarray',
        dtype=o.dtype,
        value=hint_tuples(o.tolist()))
427810
def mat_to_numpy_arr(self):
  '''  '''
  import numpy as np
  self.dat['mat'] = np.asarray(self.dat['mat'])
215138
def c_float_array(data):
    """"""
    if is_1d_list(data):
        data = np.array(data, copy=False)
    if is_numpy_1d_array(data):
        data = convert_from_sliced_object(data)
        assert data.flags.c_contiguous
        if data.dtype == np.float32:
            ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
            type_data = C_API_DTYPE_FLOAT32
        elif data.dtype == np.float64:
            ptr_data = data.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
            type_data = C_API_DTYPE_FLOAT64
        else:
            raise TypeError("Expected np.float32 or np.float64, met type({})"
                            .format(data.dtype))
    else:
        raise TypeError("Unknown type({})".format(type(data).__name__))
    return (ptr_data, type_data, data)
514440
def cfloat32_array_to_numpy(cptr, length):
    """"""
    if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
        return np.fromiter(cptr, dtype=np.float32, count=length)
    else:
        raise RuntimeError('Expected float pointer')
790971
def fn_float(self, value):
        

        if is_ndarray(value) or isinstance(value, (list, tuple)):
            return self._to_ndarray(value).astype('float')
        else:
            return float(value)
729514
def fn_get_mask(self, value):
        

        value = self._to_ndarray(value)

        if numpy.ma.is_masked(value):
            return value.mask
        else:
            return numpy.zeros(value.shape).astype(bool)
1124849
def to_np(*args):
    
    if len(args) > 1:
        return (cp.asnumpy(x) for x in args)
    else:
        return cp.asnumpy(args[0])