Exemplo n.º 1
0
def test_array_reshape():
    """Test array reshaping with size adaption."""

    a = np.arange(10)
    out = num.array1d_to_meshgrid(a, (4, 4))
    assert out.shape == (4, 4)
    assert num.arrays_equal(out, np.append(a, 6 * [None]).reshape(4, 4))

    a = np.arange(10).astype(complex)
    out = num.array1d_to_meshgrid(a, (4, 4))
    assert out.shape == (4, 4)
    assert num.arrays_equal(out, np.append(a, 6 * [np.nan]).reshape(4, 4))

    a = np.arange(10).astype(float)
    out = num.array1d_to_meshgrid(a, (3, 3))
    assert out.shape == (3, 3)
    assert num.arrays_equal(out, a[:9].reshape(3, 3))
Exemplo n.º 2
0
def datadict_to_meshgrid(data: DataDict,
                         target_shape: Union[Tuple[int, ...], None] = None,
                         inner_axis_order: Union[None, List[str]] = None,
                         use_existing_shape: bool = False) \
        -> MeshgridDataDict:
    """
    Try to make a meshgrid from a dataset.

    :param data: input DataDict.
    :param target_shape: target shape. if ``None`` we use
                         ``guess_shape_from_datadict`` to infer.
    :param inner_axis_order: if axes of the datadict are not specified in the
                             'C' order (1st the slowest, last the fastest axis)
                             then the 'true' inner order can be specified as
                             a list of axes names, which has to match the
                             specified axes in all but order.
                             The data is then transposed to conform to the
                             specified order.
    :param use_existing_shape: if ``True``, simply use the shape that the data
                               already has. For numpy-array data, this might
                               already be present.
                               if ``False``, flatten and reshape.
    :return: the generated ``MeshgridDataDict``.
    """

    # if the data is empty, return empty MeshgridData
    if len([k for k, _ in data.data_items()]) == 0:
        return MeshgridDataDict()

    if not data.axes_are_compatible():
        raise ValueError('Non-compatible axes, cannot grid that.')

    if not use_existing_shape and data.is_expandable():
        data = data.expand()
    elif use_existing_shape:
        target_shape = data.dependents()[0].shape

    # guess what the shape likely is.
    if target_shape is None:
        shp_specs = guess_shape_from_datadict(data)
        shps = [shape for (order, shape) in shp_specs.values()]
        if len(set(shps)) > 1:
            raise ValueError('Cannot determine unique shape for all data.')

        ret = list(shp_specs.values())[0]
        if ret is None:
            raise ValueError('Shape could not be inferred.')

        # the guess-function returns both axis order as well as shape.
        inner_axis_order, target_shape = ret

    # construct new data
    newdata = MeshgridDataDict(**data.structure(add_shape=False))
    axlist = data.axes(data.dependents()[0])

    for k, v in data.data_items():
        vals = num.array1d_to_meshgrid(v['values'], target_shape, copy=True)

        # if an inner axis order is given, we transpose to transform from that
        # to the specified order.
        if inner_axis_order is not None:
            transpose_idxs = misc.reorder_indices(inner_axis_order, axlist)
            vals = vals.transpose(transpose_idxs)

        newdata[k]['values'] = vals

    newdata = newdata.sanitize()
    newdata.validate()
    return newdata