def setUp(self):
        data = sp.arange(30, dtype=float)
        data.shape = (5, 2, 3)
        self.vect = info_header.InfoArray(data)

        self.vect = vector.vect_array(self.vect, axis_names=('freq', 'a', 'b'))

        data = sp.arange(120, dtype=float)
        self.mat = info_header.InfoArray(data)
        self.mat.shape = (5, 4, 6)

        self.mat = matrix.mat_array(self.mat,
                                    row_axes=(0, 1),
                                    col_axes=(0, 2),
                                    axis_names=('freq', 'mode1', 'mode2'))
Exemple #2
0
    def expand(self):
        """Calculates expanded matrix in 2 dimensional form.

        Takes an arbitrary matrix and returns the expanded version of it,
        as matrix with internal array dimensions of shape(mat).  If the
        original matrix has efficiency from any block diagonal structure, this
        is lost in the returned matrix.
        """

        # XXX Obviouse improvement: Check if this matrix is already full
        # (ie not diagonal structure)
        # and if so, return a view.

        # Also verifies the validity of the matrix.
        shape = self.mat_shape()
        # Current algorithm assumes specific format.
        self.assert_axes_ordered()
        # Allocate memory.
        out_mat = sp.zeros(shape, dtype=self.dtype)
        out_mat = info_header.InfoArray(out_mat)
        out_mat = mat_array(out_mat)

        # Figure out how many axes are in both row and col (and therefore block
        # diagonal).
        n_blocks, block_shape = self.get_num_blocks(True, False)

        # Loop over the blocks and assign data.
        for ii, mat_block in enumerate(self.iter_blocks()):
            # Figure out where this block starts.
            row_start = ii * block_shape[0]
            col_start = ii * block_shape[1]
            out_mat[row_start:row_start + block_shape[0],
                    col_start:col_start + block_shape[1]] = mat_block

        return out_mat
 def test_from_info(self):
     arr = info_header.InfoArray(self.data)
     mat_arr = matrix.make_mat(arr, (0, 1), (0, 2))
     self.assertTrue(isinstance(mat_arr, matrix.MatrixObject))
     mem = info_header.InfoMemmap(self.memmap_data)
     vect_mem = vector.make_vect(mem)
     self.assertTrue(isinstance(vect_mem, vector.VectorObject))
Exemple #4
0
def as_alg_like(array, obj):
    """Cast an array as an algebra object similar to the passed object.

    Parameters
    ----------
    array: numpy array
        Array to be cast
    obj: AlgObject
        Algebra object from which propertise should be copied.
    """

    if not isinstance(obj, base.AlgObject):
        raise TypeError("Object to mimic must be an `AlgObject`.")

    out = array
    out = info_header.InfoArray(out)
    out.info = dict(obj.info)

    if isinstance(obj, vector.VectorObject):
        out = vector.make_vect(out)
    elif isinstance(obj, matrix.MatrixObject):
        out = matrix.make_mat(out)
    else:
        raise TypeError("Expected `obj` to be an algebra mat or vect.")

    return out
    def test_slice_interpolate_cubic(self):
        # Construct a 3D array that is a quadratic function.
        data = sp.arange(140, dtype=float)
        data.shape = (5, 4, 7)
        vect = info_header.InfoArray(data)
        vect = vector.vect_array(vect, axis_names=('freq', 'a', 'b'))

        v = vect
        a = sp.arange(-2, 3)**2
        a.shape = (5, 1, 1)
        b = sp.arange(-1, 3)**2
        b.shape = (1, 4, 1)
        c = sp.arange(-1, 6)**2
        c.shape = (1, 1, 7)
        v[:, :, :] = a + b + c
        v.set_axis_info('freq', 0, 1)
        v.set_axis_info('a', 1, 1)
        v.set_axis_info('b', 2, 1)

        #### First test the weights.
        # Test cubic conv interpolations in multi D.
        points, weights = v.slice_interpolate_weights([0, 1, 2], [0, 0, 0],
                                                      'cubic')

        self.assertTrue(1. in weights)
        self.assertTrue(weights.tolist().count(0) == 63)
        self.assertTrue(points[sp.where(weights == 1)[0][0]][0] == 2)
        self.assertTrue(points[sp.where(weights == 1)[0][0]][1] == 1)
        self.assertTrue(points[sp.where(weights == 1)[0][0]][2] == 1)

        points, weights = v.slice_interpolate_weights([0, 1, 2], [1.5, 0.5, 0],
                                                      'cubic')

        self.assertTrue(points.shape[0] == 64)
        self.assertTrue(weights.shape[0] == 64)

        # Test full interpolation.
        out = v.slice_interpolate([0, 1, 2], [0, 0, 0], 'cubic')

        self.assertTrue(sp.allclose(out, 0.0))

        out = v.slice_interpolate([0, 1, 2], [-1.34, 0.55, 0.86], 'cubic')

        self.assertTrue(sp.allclose(out, 2.8377))

        # Test partial interpolation.
        out = v.slice_interpolate([0, 2], [1.4, -0.3], 'cubic')

        out1 = v.slice_interpolate([0, 1, 2], [1.4, -1, -0.3], 'cubic')

        out2 = v.slice_interpolate([0, 1, 2], [1.4, 0, -0.3], 'cubic')

        out3 = v.slice_interpolate([0, 1, 2], [1.4, 1, -0.3], 'cubic')

        out4 = v.slice_interpolate([0, 1, 2], [1.4, 2, -0.3], 'cubic')

        self.assertTrue(sp.allclose(out, [out1, out2, out3, out4]))
 def test_from_memory(self):
     # Works if constructed from array.
     data = sp.empty((5, 6, 6))
     data[:] = 4.0
     Mat = info_header.InfoArray(data, {'a': 'b'})
     self.assertEqual(Mat.shape, (5, 6, 6))
     self.assertEqual(Mat.info['a'], 'b')
     self.assertTrue(sp.allclose(Mat, 4.0))
     # Check that the dictionary is there and empty if uninitialized.
     Mat4 = info_header.InfoArray(data)
     self.assertEqual(Mat4.info, {})
     # Works if constructed from a slice.
     Mat2 = Mat[1:2, :, :]
     self.assertEqual(Mat2.shape, (1, 6, 6))
     self.assertEqual(Mat2.info['a'], 'b')
     # Works if constructed from a view.
     Mat3 = data.view(info_header.InfoArray)
     self.assertEqual(Mat3.shape, (5, 6, 6))
     Mat3.info['a'] = 'b'
Exemple #7
0
def load(file, metafile=None):
    """Open a .npy file and load it into memory as an info_aray.

    Similar to the numpy.load function.  Does not support memory
    mapping (use open_memmap).

    Parameters
    ----------
    file: file handle or str
        .npy file or file name to read the array from.
    metafile: str
        File name for which the `info` attribute of the returned InfoArray
        will be read from. Default is None, where the it is
        assumed to be the file name associated with `file` with ".meta"
        appended. If the file does not exist, the info attribute is initialized
        to an empty dictionary.

    Returns
    -------
    iarray: InfoArray object
    """

    # Load the data from .npy format.
    array = sp.load(file)

    # Figure out what the filename for the meta data should be.
    if metafile is None:
        try:
            fname = file.name
        except AttributeError:
            fname = file
        metafile = fname + ".meta"

    # Read the meta data.
    if os.path.isfile(metafile):
        info_fid = open(metafile, 'r')
        try:
            infostring = info_fid.readline()
        finally:
            info_fid.close()
        info = safe_eval(infostring)
    else:
        info = {}

    # Construct the infor array.
    array = info_header.InfoArray(array, info)

    return array
 def test_assert_info(self):
     """Test the assert_info function."""
     # info_memaps should pass.
     data = npfor.open_memmap('temp.npy', mode='w+', shape=(4, 3, 3))
     data[:] = 5.0
     Mat = info_header.InfoMemmap(data)
     info_header.assert_info(Mat)
     del Mat
     os.remove('temp.npy')
     # info_arrays should pass.
     data = sp.empty((5, 6, 6))
     data[:] = 4.0
     Mat = info_header.InfoArray(data)
     info_header.assert_info(Mat)
     # arrays should fail.
     self.assertRaises(TypeError, info_header.assert_info, data)
Exemple #9
0
def make_mat(array, row_axes=None, col_axes=None, axis_names=None):
    """Do what ever it takes to make a mat out of an array.

    Convert any class that can be converted to a mat (array, InfoArray,
    memmap, InfoMemmap) to the appropriate mat object (mat_array or
    mat_memmap).

    This convieiance function just simplifies the constructor heirarchy.
    Normally to get an mat out of an array, you would need to construct an
    intermediate InfoArray object.  This bypasses that step.

    Parameters
    ----------
    array: array_like
        Array to be converted to mat object (if possible).
    row_axes: tuple of ints
        Sequence contains the axis numbers of the array to identify as
        varying over the matrix rows. This sequence is stored in the
        `rows` attribute.  This parameter is ignored if
        `input_array`'s info attribute already contains the rows.
    col_axis: tuple of ints
        Sequence contains the axis numbers of the array to identify as
        varying over the matrix columns. This sequence is stored in the
        `cols` attribute.  This parameter is ignored if
        `input_array`'s info attribute already contains the cols.
    axis_names: tuple of strings, optional
        The sequence contains the name of each axis.  This sequence will be
        stored in the `axes` attribute.  This parameter is ignored if
        `input_array`'s info attribute already contains the axis names.

    Returns
    -------
    mat_arr: mat_array or mat_memmap
        A view of `array` converted to a mat object.
    """
    if isinstance(array, sp.memmap):
        if not isinstance(array, info_header.InfoMemmap):
            array = info_header.InfoMemmap(array)
        return mat_memmap(array, row_axes, col_axes, axis_names)
    elif isinstance(array, sp.ndarray):
        if not isinstance(array, info_header.InfoArray):
            array = info_header.InfoArray(array)
        return mat_array(array, row_axes, col_axes, axis_names)
    else:
        raise TypeError("Object cannot be converted to a matrix.")
Exemple #10
0
def make_vect(array, axis_names=None):
    """Do whatever it takes to make a vect out of an array.

    Convert any class that can be converted to a vect (array, InfoArray,
    memmap, InfoMemmap) to the appropriate vect object (vect_array,
    vect_memmap).

    This convenience function just simplifies the constructor hierarchy.
    Normally to get a vect out of an array, you would need to construct an
    intermediate InfoArray object.  This bypasses that step.

    Parameters
    ----------
    array: array_like
        Array to be converted to vect object (if possible).
    axis_names: tuple of strings, optional
        The sequence contains the name of each axis.  This sequence will be
        stored in the `axes` attribute.  This parameter is ignored if
        `input_array`'s info attribute already contains the axis names.

    Returns
    -------
    vect_arr: vect_array or vect_memmap
        A view of `array` converted to a vect object.

    """

    if isinstance(array, sp.memmap):
        if not isinstance(array, info_header.InfoMemmap):
            array = info_header.InfoMemmap(array)
        return vect_memmap(array, axis_names)
    elif isinstance(array, sp.ndarray):
        if not isinstance(array, info_header.InfoArray):
            array = info_header.InfoArray(array)
        return vect_array(array, axis_names)
    else:
        raise TypeError("Object cannot be converted to a vector.")
 def setUp(self):
     info = {'a': 42, 'b': 'a string', 'c': 3.14159}
     data = sp.arange(80).reshape((2, 8, 5))
     self.Mat = info_header.InfoArray(data, info)
 def setUp(self):
     data = sp.arange(60, dtype=float)
     data.shape = (2, 5, 6)
     self.array = info_header.InfoArray(data)