Map between numpy and state dtypes
321538
def _setup_dtype(self):
        """"""
        if self._dtype is not None:
            return self._dtype

        dtype = []  # Convert struct data types to numpy data type
        for i, typ in enumerate(self.typlist):
            if typ in self.NUMPY_TYPE_MAP:
                dtype.append(('s' + str(i), self.byteorder +
                              self.NUMPY_TYPE_MAP[typ]))
            else:
                dtype.append(('s' + str(i), 'S' + str(typ)))
        dtype = np.dtype(dtype)
        self._dtype = dtype

        return self._dtype
372713
def _generate_states_report(sorted_data):
    '''
    
    '''
    states = []
    for state, data in sorted_data:
        module, stateid, name, function = state.split('_|-')
        module_function = '.'.join((module, function))
        result = data.get('result', '')
        single = [
            {'function': module_function},
            {'name': name},
            {'result': result},
            {'duration': data.get('duration', 0.0)},
            {'comment': data.get('comment', '')}
        ]

        if not result:
            style = 'failed'
        else:
            changes = data.get('changes', {})
            if changes and isinstance(changes, dict):
                single.append({'changes': _dict_to_name_value(changes)})
                style = 'changed'
            else:
                style = 'unchanged'

        started = data.get('start_time', '')
        if started:
            single.append({'started': started})

        states.append({stateid: single, '__style__': style})
    return states
405197
def dtyping(*args):
    
    args = list(args)

    for idx, arg in enumerate(args):

        if isinstance(arg, Poly):
            args[idx] = Poly

        elif isinstance(arg, numpy.generic):
            args[idx] = numpy.asarray(arg).dtype

        elif isinstance(arg, (float, int)):
            args[idx] = type(arg)

    for type_ in DATATYPES:
        if type_ in args:
            return type_

    raise ValueError(
        "dtypes not recognised " + str([str(_) for _ in args]))
1130699
def serialize_dtype(o):
    
    if len(o) == 0:
        return dict(
            _type='np.dtype',
            descr=str(o))
    return dict(
        _type='np.dtype',
        descr=o.descr)
289392
def type_map(gtype, fn):
    """"""

    cb = ffi.callback('VipsTypeMap2Fn', fn)
    return vips_lib.vips_type_map(gtype, cb, ffi.NULL, ffi.NULL)
812869
def create_output_dictionary_for_state(state):
        
        from rafcon.core.states.library_state import LibraryState
        result_dict = {}
        for key, data_port in state.output_data_ports.items():
            if isinstance(state, LibraryState) and state.use_runtime_value_output_data_ports[key]:
                result_dict[data_port.name] = copy.copy(state.output_data_port_runtime_values[key])
            else:
                result_dict[data_port.name] = copy.copy(data_port.default_value)
        return result_dict
213588
def dtype_contract(input_dtype=None, output_dtype=None):
    """"""
    def wrap(function):
        @wraps(function)
        def wrapped_function(*args, **kwargs):
            if input_dtype is not None:
                check_dtype(args[0], input_dtype)
            array = function(*args, **kwargs)
            if output_dtype is not None:
                check_dtype(array, output_dtype)
            return array
        return wrapped_function
    return wrap
1285601
def map_init(interface, params):
    """"""
    import numpy as np
    import random
    np.random.seed(params['seed'])
    random.seed(params['seed'])
    return params
94451
def savestate(self, state):
        """"""
        oldstate = np.get_printoptions()
        np.set_printoptions(threshold=1e6)
        try:
            with open(os.path.join(self._directory, 'state.txt'), 'w') as f:
                print_(state, file=f)
        finally:
            np.set_printoptions(**oldstate)
1249526
def array(shape, dtype=_np.float64, autolock=False):
    """"""
    assert _NP_AVAILABLE, "To use the shared array object, numpy must be available!"
    if not isinstance(dtype, _np.dtype):
        dtype = _np.dtype(dtype)
    # Not bothering to translate the numpy dtypes to ctype types directly,
    # because they're only partially supported. Instead, create a byte ctypes
    # array of the right size and use a view of the appropriate datatype.
    shared_arr = _multiprocessing.Array(
        "b", int(_np.prod(shape) * dtype.alignment), lock=autolock
    )
    with _warnings.catch_warnings():
        # For more information on why this is necessary, see
        # https://www.reddit.com/r/Python/comments/j3qjb/parformatlabpool_replacement
        _warnings.simplefilter("ignore", RuntimeWarning)
        data = _np.ctypeslib.as_array(shared_arr).view(dtype).reshape(shape)
    return data
242434
def get_np_dtype(nd4j_dtype):
    
    mapping = {
        'double': np.float64,
        'float': np.float32,
        'half': np.float16
    }
    np_dtype = mapping.get(nd4j_dtype)
    if not np_dtype:
        raise Exception('Invalid nd4j data type : ' + nd4j_dtype)
    return np_dtype
195521
def _interleaved_dtype(
        blocks: List[Block]
) -> Optional[Union[np.dtype, ExtensionDtype]]:
    
    if not len(blocks):
        return None

    return find_common_type([b.dtype for b in blocks])
1188565
def get_numpy_dtype(obj):
    """"""
    if ndarray is not FakeObject:
        # NumPy is available
        import numpy as np
        if isinstance(obj, np.generic) or isinstance(obj, np.ndarray):
        # Numpy scalars all inherit from np.generic.
        # Numpy arrays all inherit from np.ndarray.
        # If we check that we are certain we have one of these
        # types then we are less likely to generate an exception below.
            try:
                return obj.dtype.type
            except (AttributeError, RuntimeError):
                #  AttributeError: some NumPy objects have no dtype attribute
                #  RuntimeError: happens with NetCDF objects (Issue 998)
                return
629393
def initial_state(self, batch_size, dtype=tf.float32, trainable=False,
                    trainable_initializers=None, trainable_regularizers=None,
                    name=None):
    """"""
    return self._core.initial_state(
        batch_size, dtype=dtype, trainable=trainable,
        trainable_initializers=trainable_initializers,
        trainable_regularizers=trainable_regularizers, name=name)
743924
def _fix_tbit_dtype(self, array, colnums):
        
        descr = array.dtype.descr
        for i, colnum in enumerate(colnums):
            npy_type, isvar, istbit = self._get_tbl_numpy_dtype(colnum)
            if (istbit):
                coldescr = list(descr[i])
                coldescr[1] = '?'
                descr[i] = tuple(coldescr)

        return array.view(descr)
1256042
function PossibleStates(...allStates) {
  if (!allStates.length === 0) {
    throw Error('No values passed when constructing a new PossibleStates')
  }

  const containsData = typeDefinition => typeDefinition.match(/<.*>/)

  if (allStates[0].match(/<.*>/)) {
    throw Error('The initial state cannot contain data')
  }

  const parsedStates = allStates.map(state => {
    if (!containsData(state)) {
      return {name: state, data: []}
    }

    const [name, typeDefs] = state.match(/^(.*)<(.*)>$/).slice(1)

    return {name, data: typeDefs.split(',').map(def => def.trim())}
  })

  return PossibleStatesContainer({current: parsedStates[0], allStates: parsedStates})
}
1183517
def np2gdal_dtype(d):
    
    dt_dict = gdal_array.codes        
    if isinstance(d, (np.ndarray, np.generic)):
        d = d.dtype
    #This creates dtype from another built-in type
    #d = np.dtype(d)
    if isinstance(d, np.dtype):
        if d.name == 'int8':
            gdal_dt = 1
        elif d.name == 'bool':
            #Write out as Byte
            gdal_dt = 1 
        else:
            gdal_dt = list(dt_dict.keys())[list(dt_dict.values()).index(d)]
    else:
        print("Input must be NumPy array or NumPy dtype")
        gdal_dt = None
    return gdal_dt