def from_outer_instance_inner_type_spec(cls, outer_y, inner_type_spec=None, order="F"): """Instantiate from concrete instance of the outer type, and an inner type-spec. The inner type spec can be either be fully specified, or be more general (i.e. to facilitate the situation in which a solver needs a 1d array). Accepted general data types: - {'type': 'array'} - {'type': 'array', 'ndim': 1} Args: outer_y (array): concrete outer data type inner_type_spec (dict): inner, potentially general, type spec order (str): order argument to be used in array reshaping. Returns: StateTypeConverter: type converter as specified by args Raises: Exception: if inner_type_spec is not properly specified or is not a handled type """ # if no inner_type_spec given just instantiate both inner # and outer to the outer_y if inner_type_spec is None: return cls.from_instances(outer_y, order=order) inner_type = inner_type_spec.get("type") if inner_type is None: raise Exception("inner_type_spec needs a 'type' key.") if inner_type == "array": outer_y_as_array = Array(outer_y) # if a specific shape is given attempt to instantiate from a # reshaped outer_y shape = inner_type_spec.get("shape") if shape is not None: return cls.from_instances( outer_y_as_array.reshape(shape, order=order), outer_y, order=order ) # handle the case that ndim == 1 is given ndim = inner_type_spec.get("ndim") if ndim == 1: return cls.from_instances( outer_y_as_array.flatten(order=order), outer_y, order=order ) # if neither shape nor ndim is given, assume it can be an array # of any shape return cls.from_instances(outer_y_as_array, outer_y, order=order) raise Exception("inner_type_spec not a handled type.")
def convert_state(y: Array, type_spec: dict, order="F"): """Convert the de state y into the type specified by type_spec. Accepted values of type_spec are given at the beginning of the file. Args: y: the state to convert. type_spec (dict): the type description to convert to. order (str): order argument for any array reshaping function. Returns: Array: converted state. """ new_y = None if type_spec["type"] == "array": # default array data type to complex new_y = Array(y, dtype=type_spec.get("dtype", "complex")) shape = type_spec.get("shape") if shape is not None: new_y = new_y.reshape(shape, order=order) return new_y