Python numpy.darray() Examples

The following are 10 code examples of numpy.darray(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: typeconv.py    From python-weka-wrapper3 with GNU General Public License v3.0 6 votes vote down vote up
def double_matrix_to_ndarray(m):
    """
    Turns the Java matrix (2-dim array) of doubles into a numpy 2-dim array.

    :param m: the double matrix
    :type: JB_Object
    :return: Numpy array
    :rtype: numpy.darray
    """
    rows = javabridge.get_env().get_object_array_elements(m)
    num_rows = len(rows)
    num_cols = javabridge.get_env().get_array_length(rows[0])
    result = numpy.zeros(num_rows * num_cols).reshape((num_rows, num_cols))
    i = 0
    for row in rows:
        elements = javabridge.get_env().get_double_array_elements(row)
        n = 0
        for element in elements:
            result[i][n] = element
            n += 1
        i += 1
    return result 
Example #2
Source File: types.py    From python-weka-wrapper with GNU General Public License v3.0 6 votes vote down vote up
def double_matrix_to_ndarray(m):
    """
    Turns the Java matrix (2-dim array) of doubles into a numpy 2-dim array.

    :param m: the double matrix
    :type: JB_Object
    :return: Numpy array
    :rtype: numpy.darray
    """
    rows = javabridge.get_env().get_object_array_elements(m)
    num_rows = len(rows)
    num_cols = javabridge.get_env().get_array_length(rows[0])
    result = numpy.zeros(num_rows * num_cols).reshape((num_rows, num_cols))
    i = 0
    for row in rows:
        elements = javabridge.get_env().get_double_array_elements(row)
        n = 0
        for element in elements:
            result[i][n] = element
            n += 1
        i += 1
    return result 
Example #3
Source File: hawkes_basis_kernels.py    From tick with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fit(self, events, end_times=None, baseline_start=None,
            amplitudes_start=None, basis_kernels_start=None):
        """Fit the model according to the given training data.

        Parameters
        ----------
        events : `list` of `list` of `np.ndarray`
            List of Hawkes processes realizations.
            Each realization of the Hawkes process is a list of n_node for
            each component of the Hawkes. Namely `events[i][j]` contains a
            one-dimensional `numpy.array` of the events' timestamps of
            component j of realization i.
            If only one realization is given, it will be wrapped into a list

        end_times : `np.ndarray` or `float`, default = None
            List of end time of all hawkes processes that will be given to the
            model. If None, it will be set to each realization's latest time.
            If only one realization is provided, then a float can be given.

        baseline_start : `None` or `np.ndarray`, shape=(n_nodes)
            Used to force start values for baseline attribute
            If `None` starts with uniform 1 values

        amplitudes_start : `None` or `np.ndarray`, shape=(n_nodes,n_nodes,D)
            Used to force start values for amplitude parameter
            If `None` starts with random values uniformly sampled between
            0.5 and 0.9

        basis_kernels_start : `None` or `np.darray`, shape=(D,kernel_size)
            Used to force start values for the basis kernels
            If `None` starts with random values uniformly sampled between
            0 and 0.1
        """
        LearnerHawkesNoParam.fit(self, events, end_times=end_times)
        self.solve(baseline_start=baseline_start,
                   amplitudes_start=amplitudes_start,
                   basis_kernels_start=basis_kernels_start)
        return self 
Example #4
Source File: paramserver.py    From hfsoftmax with MIT License 5 votes vote down vote up
def _check_order(self, mid):
        for key in self.mtable[mid]:
            if not self.mtable[mid][key].flags['C_CONTIGUOUS']:
                raise TypeError('np.darray should be C order!') 
Example #5
Source File: converters.py    From python-weka-wrapper3 with GNU General Public License v3.0 4 votes vote down vote up
def ndarray_to_instances(array, relation, att_template="Att-#", att_list=None):
    """
    Converts the numpy matrix into an Instances object and returns it.

    :param array: the numpy ndarray to convert
    :type array: numpy.darray
    :param relation: the name of the dataset
    :type relation: str
    :param att_template: the prefix to use for the attribute names, "#" is the 1-based index,
                         "!" is the 0-based index, "@" the relation name
    :type att_template: str
    :param att_list: the list of attribute names to use
    :type att_list: list
    :return: the generated instances object
    :rtype: Instances
    """
    if len(numpy.shape(array)) != 2:
        raise Exception("Number of array dimensions must be 2!")
    rows, cols = numpy.shape(array)

    # header
    atts = []
    if att_list is not None:
        if len(att_list) != cols:
            raise Exception(
                "Number columns and provided attribute names differ: " + str(cols) + " != " + len(att_list))
        for name in att_list:
            att = Attribute.create_numeric(name)
            atts.append(att)
    else:
        for i in range(cols):
            name = att_template.replace("#", str(i+1)).replace("!", str(i)).replace("@", relation)
            att = Attribute.create_numeric(name)
            atts.append(att)
    result = Instances.create_instances(relation, atts, rows)

    # data
    for i in range(rows):
        inst = Instance.create_instance(array[i])
        result.add_instance(inst)

    return result 
Example #6
Source File: converters.py    From python-weka-wrapper with GNU General Public License v3.0 4 votes vote down vote up
def ndarray_to_instances(array, relation, att_template="Att-#", att_list=None):
    """
    Converts the numpy matrix into an Instances object and returns it.

    :param array: the numpy ndarray to convert
    :type array: numpy.darray
    :param relation: the name of the dataset
    :type relation: str
    :param att_template: the prefix to use for the attribute names, "#" is the 1-based index,
                         "!" is the 0-based index, "@" the relation name
    :type att_template: str
    :param att_list: the list of attribute names to use
    :type att_list: list
    :return: the generated instances object
    :rtype: Instances
    """
    if len(numpy.shape(array)) != 2:
        raise Exception("Number of array dimensions must be 2!")
    rows, cols = numpy.shape(array)

    # header
    atts = []
    if att_list is not None:
        if len(att_list) != cols:
            raise Exception(
                "Number columns and provided attribute names differ: " + str(cols) + " != " + len(att_list))
        for name in att_list:
            att = Attribute.create_numeric(name)
            atts.append(att)
    else:
        for i in xrange(cols):
            name = att_template.replace("#", str(i+1)).replace("!", str(i)).replace("@", relation)
            att = Attribute.create_numeric(name)
            atts.append(att)
    result = Instances.create_instances(relation, atts, rows)

    # data
    for i in xrange(rows):
        inst = Instance.create_instance(array[i])
        result.add_instance(inst)

    return result 
Example #7
Source File: util.py    From byob with GNU General Public License v3.0 4 votes vote down vote up
def png(image):
    """
    Transforms raw image data into a valid PNG data

    `Required`
    :param image:   `numpy.darray` object OR `PIL.Image` object

    Returns raw image data in PNG format

    """
    import sys
    import zlib
    import numpy
    import struct

    try:
        from StringIO import StringIO  # Python 2
    except ImportError:
        from io import StringIO        # Python 3

    if isinstance(image, numpy.ndarray):
        width, height = (image.shape[1], image.shape[0])
        data = image.tobytes()
    elif hasattr(image, 'width') and hasattr(image, 'height') and hasattr(image, 'rgb'):
        width, height = (image.width, image.height)
        data = image.rgb
    else:
        raise TypeError("invalid input type: {}".format(type(image)))

    line = width * 3
    png_filter = struct.pack('>B', 0)
    scanlines = b"".join([png_filter + data[y * line:y * line + line] for y in range(height)])
    magic = struct.pack('>8B', 137, 80, 78, 71, 13, 10, 26, 10)

    ihdr = [b"", b'IHDR', b"", b""]
    ihdr[2] = struct.pack('>2I5B', width, height, 8, 2, 0, 0, 0)
    ihdr[3] = struct.pack('>I', zlib.crc32(b"".join(ihdr[1:3])) & 0xffffffff)
    ihdr[0] = struct.pack('>I', len(ihdr[2]))

    idat = [b"", b'IDAT', zlib.compress(scanlines), b""]
    idat[3] = struct.pack('>I', zlib.crc32(b"".join(idat[1:3])) & 0xffffffff)
    idat[0] = struct.pack('>I', len(idat[2]))

    iend = [b"", b'IEND', b"", b""]
    iend[3] = struct.pack('>I', zlib.crc32(iend[1]) & 0xffffffff)
    iend[0] = struct.pack('>I', len(iend[2]))

    fileh = StringIO()
    fileh.write(str(magic))
    fileh.write(str(b"".join(ihdr)))
    fileh.write(str(b"".join(idat)))
    fileh.write(str(b"".join(iend)))
    fileh.seek(0)
    output = fileh.getvalue()
    if sys.version_info[0] > 2:
        output = output.encode('utf-8') # python3 compatibility
    return output 
Example #8
Source File: util.py    From byob with GNU General Public License v3.0 4 votes vote down vote up
def png(image):
    """
    Transforms raw image data into a valid PNG data

    `Required`
    :param image:   `numpy.darray` object OR `PIL.Image` object

    Returns raw image data in PNG format

    """
    import sys
    import zlib
    import numpy
    import struct

    try:
        from StringIO import StringIO  # Python 2
    except ImportError:
        from io import StringIO        # Python 3

    if isinstance(image, numpy.ndarray):
        width, height = (image.shape[1], image.shape[0])
        data = image.tobytes()
    elif hasattr(image, 'width') and hasattr(image, 'height') and hasattr(image, 'rgb'):
        width, height = (image.width, image.height)
        data = image.rgb
    else:
        raise TypeError("invalid input type: {}".format(type(image)))

    line = width * 3
    png_filter = struct.pack('>B', 0)
    scanlines = b"".join([png_filter + data[y * line:y * line + line] for y in range(height)])
    magic = struct.pack('>8B', 137, 80, 78, 71, 13, 10, 26, 10)

    ihdr = [b"", b'IHDR', b"", b""]
    ihdr[2] = struct.pack('>2I5B', width, height, 8, 2, 0, 0, 0)
    ihdr[3] = struct.pack('>I', zlib.crc32(b"".join(ihdr[1:3])) & 0xffffffff)
    ihdr[0] = struct.pack('>I', len(ihdr[2]))

    idat = [b"", b'IDAT', zlib.compress(scanlines), b""]
    idat[3] = struct.pack('>I', zlib.crc32(b"".join(idat[1:3])) & 0xffffffff)
    idat[0] = struct.pack('>I', len(idat[2]))

    iend = [b"", b'IEND', b"", b""]
    iend[3] = struct.pack('>I', zlib.crc32(iend[1]) & 0xffffffff)
    iend[0] = struct.pack('>I', len(iend[2]))

    fileh = StringIO()
    fileh.write(str(magic))
    fileh.write(str(b"".join(ihdr)))
    fileh.write(str(b"".join(idat)))
    fileh.write(str(b"".join(iend)))
    fileh.seek(0)
    output = fileh.getvalue()
    if sys.version_info[0] > 2:
        output = output.encode('utf-8') # python3 compatibility
    return output 
Example #9
Source File: util.py    From byob with GNU General Public License v3.0 4 votes vote down vote up
def png(image):
    """
    Transforms raw image data into a valid PNG data

    `Required`
    :param image:   `numpy.darray` object OR `PIL.Image` object

    Returns raw image data in PNG format

    """
    import sys
    import zlib
    import numpy
    import struct

    try:
        from StringIO import StringIO  # Python 2
    except ImportError:
        from io import StringIO        # Python 3

    if isinstance(image, numpy.ndarray):
        width, height = (image.shape[1], image.shape[0])
        data = image.tobytes()
    elif hasattr(image, 'width') and hasattr(image, 'height') and hasattr(image, 'rgb'):
        width, height = (image.width, image.height)
        data = image.rgb
    else:
        raise TypeError("invalid input type: {}".format(type(image)))

    line = width * 3
    png_filter = struct.pack('>B', 0)
    scanlines = b"".join([png_filter + data[y * line:y * line + line] for y in range(height)])
    magic = struct.pack('>8B', 137, 80, 78, 71, 13, 10, 26, 10)

    ihdr = [b"", b'IHDR', b"", b""]
    ihdr[2] = struct.pack('>2I5B', width, height, 8, 2, 0, 0, 0)
    ihdr[3] = struct.pack('>I', zlib.crc32(b"".join(ihdr[1:3])) & 0xffffffff)
    ihdr[0] = struct.pack('>I', len(ihdr[2]))

    idat = [b"", b'IDAT', zlib.compress(scanlines), b""]
    idat[3] = struct.pack('>I', zlib.crc32(b"".join(idat[1:3])) & 0xffffffff)
    idat[0] = struct.pack('>I', len(idat[2]))

    iend = [b"", b'IEND', b"", b""]
    iend[3] = struct.pack('>I', zlib.crc32(iend[1]) & 0xffffffff)
    iend[0] = struct.pack('>I', len(iend[2]))

    fileh = StringIO()
    fileh.write(str(magic))
    fileh.write(str(b"".join(ihdr)))
    fileh.write(str(b"".join(idat)))
    fileh.write(str(b"".join(iend)))
    fileh.seek(0)
    output = fileh.getvalue()
    if sys.version_info[0] > 2:
        output = output.encode('utf-8') # python3 compatibility
    return output 
Example #10
Source File: util.py    From byob with GNU General Public License v3.0 4 votes vote down vote up
def png(image):
    """
    Transforms raw image data into a valid PNG data

    `Required`
    :param image:   `numpy.darray` object OR `PIL.Image` object

    Returns raw image data in PNG format

    """
    import sys
    import zlib
    import numpy
    import struct

    try:
        from StringIO import StringIO  # Python 2
    except ImportError:
        from io import StringIO        # Python 3

    if isinstance(image, numpy.ndarray):
        width, height = (image.shape[1], image.shape[0])
        data = image.tobytes()
    elif hasattr(image, 'width') and hasattr(image, 'height') and hasattr(image, 'rgb'):
        width, height = (image.width, image.height)
        data = image.rgb
    else:
        raise TypeError("invalid input type: {}".format(type(image)))

    line = width * 3
    png_filter = struct.pack('>B', 0)
    scanlines = b"".join([png_filter + data[y * line:y * line + line] for y in range(height)])
    magic = struct.pack('>8B', 137, 80, 78, 71, 13, 10, 26, 10)

    ihdr = [b"", b'IHDR', b"", b""]
    ihdr[2] = struct.pack('>2I5B', width, height, 8, 2, 0, 0, 0)
    ihdr[3] = struct.pack('>I', zlib.crc32(b"".join(ihdr[1:3])) & 0xffffffff)
    ihdr[0] = struct.pack('>I', len(ihdr[2]))

    idat = [b"", b'IDAT', zlib.compress(scanlines), b""]
    idat[3] = struct.pack('>I', zlib.crc32(b"".join(idat[1:3])) & 0xffffffff)
    idat[0] = struct.pack('>I', len(idat[2]))

    iend = [b"", b'IEND', b"", b""]
    iend[3] = struct.pack('>I', zlib.crc32(iend[1]) & 0xffffffff)
    iend[0] = struct.pack('>I', len(iend[2]))

    fileh = StringIO()
    fileh.write(str(magic))
    fileh.write(str(b"".join(ihdr)))
    fileh.write(str(b"".join(idat)))
    fileh.write(str(b"".join(iend)))
    fileh.seek(0)
    output = fileh.getvalue()
    if sys.version_info[0] > 2:
        output = output.encode('utf-8') # python3 compatibility
    return output