Python numpy.ushort() Examples

The following are 18 code examples for showing how to use numpy.ushort(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: mars   Author: mars-project   File: histogram.py    License: Apache License 2.0 6 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:  # pragma: no cover
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example 2
Project: lambda-packs   Author: ryfeus   File: histograms.py    License: MIT License 6 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example 3
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: histograms.py    License: MIT License 6 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example 4
Project: GraphicDesignPatternByPython   Author: Relph1119   File: histograms.py    License: MIT License 6 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example 5
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example 6
Project: pySINDy   Author: luckystarufo   File: histograms.py    License: MIT License 6 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example 7
Project: coffeegrindsize   Author: jgagneastro   File: histograms.py    License: MIT License 6 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example 8
Project: Carnets   Author: holzschu   File: histograms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example 9
Project: Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda   Author: PacktPublishing   File: histograms.py    License: MIT License 6 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example 10
Project: twitter-stock-recommendation   Author: alvarobartt   File: histograms.py    License: MIT License 6 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example 11
Project: recruit   Author: Frank-qlu   File: histograms.py    License: Apache License 2.0 5 votes vote down vote up
def _unsigned_subtract(a, b):
    """
    Subtract two values where a >= b, and produce an unsigned result

    This is needed when finding the difference between the upper and lower
    bound of an int16 histogram
    """
    # coerce to a single type
    signed_to_unsigned = {
        np.byte: np.ubyte,
        np.short: np.ushort,
        np.intc: np.uintc,
        np.int_: np.uint,
        np.longlong: np.ulonglong
    }
    dt = np.result_type(a, b)
    try:
        dt = signed_to_unsigned[dt.type]
    except KeyError:
        return np.subtract(a, b, dtype=dt)
    else:
        # we know the inputs are integers, and we are deliberately casting
        # signed to unsigned
        return np.subtract(a, b, casting='unsafe', dtype=dt) 
Example 12
Project: tick   Author: X-DataInitiative   File: cox_regression.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _all_safe(self, features: np.ndarray, times: np.array,
                  censoring: np.array):
        if not set(np.unique(censoring)).issubset({0, 1}):
            raise ValueError('``censoring`` must only have values in {0, 1}')
        # All times must be positive
        if not np.all(times >= 0):
            raise ValueError('``times`` array must contain only non-negative '
                             'entries')
        features = safe_array(features)
        times = safe_array(times)
        censoring = safe_array(censoring, np.ushort)
        return features, times, censoring 
Example 13
Project: tick   Author: X-DataInitiative   File: model_coxreg_partial_lik.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _set_data(self, features: np.ndarray, times: np.array,
                  censoring: np.array):  #

        if self.dtype is None:
            self.dtype = features.dtype
            if self.dtype != times.dtype:
                raise ValueError("Features and labels differ in data types")

        n_samples, n_features = features.shape
        if n_samples != times.shape[0]:
            raise ValueError(("Features has %i samples while times "
                              "have %i" % (n_samples, times.shape[0])))
        if n_samples != censoring.shape[0]:
            raise ValueError(("Features has %i samples while censoring "
                              "have %i" % (n_samples, censoring.shape[0])))

        features = safe_array(features, dtype=self.dtype)
        times = safe_array(times, dtype=self.dtype)
        censoring = safe_array(censoring, np.ushort)

        self._set("features", features)
        self._set("times", times)
        self._set("censoring", censoring)
        self._set("n_samples", n_samples)
        self._set("n_features", n_features)
        self._set(
            "_model", dtype_class_mapper[self.dtype](self.features, self.times,
                                                     self.censoring)) 
Example 14
Project: tick   Author: X-DataInitiative   File: simu_coxreg.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _simulate(self):
        # The features matrix already exists, and is created by the
        # super class
        features = self.features
        n_samples, n_features = features.shape
        u = features.dot(self.coeffs)
        # Simulation of true times
        E = np.random.exponential(scale=1., size=n_samples)
        E *= np.exp(-u)
        scale = self.scale
        shape = self.shape
        if self.times_distribution == "weibull":
            T = 1. / scale * E ** (1. / shape)
        else:
            # There is not point in this test, but let's do it like that
            # since we're likely to implement other distributions
            T = 1. / scale * E ** (1. / shape)
        m = T.mean()
        # Simulation of the censoring
        c = self.censoring_factor
        C = np.random.exponential(scale=c * m, size=n_samples)
        # Observed time
        self._set("times", np.minimum(T, C).astype(self.dtype))
        # Censoring indicator: 1 if it is a time of failure, 0 if it's
        #   censoring. It is as int8 and not bool as we might need to
        #   construct a memory access on it later
        censoring = (T <= C).astype(np.ushort)
        self._set("censoring", censoring)
        return self.features, self.times, self.censoring 
Example 15
Project: tick   Author: X-DataInitiative   File: simu_coxreg_test.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_SimuCoxReg(self):
        """...Test simulation of a Cox Regression
        """
        # Simulate a Cox model with specific seed
        n_samples = 10
        n_features = 3
        idx = np.arange(n_features)
        # Parameters of the Cox simu
        coeffs = np.exp(-idx / 10.)
        coeffs[::2] *= -1

        seed = 123
        simu = SimuCoxReg(coeffs, n_samples=n_samples, seed=seed,
                          verbose=False)
        features_, times_, censoring_ = simu.simulate()

        times = np.array([
            1.5022119, 5.93102441, 6.82837051, 0.50940341, 0.14859682,
            30.22922996, 3.54945974, 0.8671229, 1.4228358, 0.11483298
        ])

        censoring = np.array([1, 0, 1, 1, 1, 1, 1, 1, 0, 1], dtype=np.ushort)

        features = np.array([[1.4912667, 0.80881799, 0.26977298], [
            1.23227551, 0.50697013, 1.9409132
        ], [1.8891494, 1.49834791,
            2.41445794], [0.19431319, 0.80245126, 1.02577552], [
                                 -1.61687582, -1.08411865, -0.83438387
                             ], [2.30419894, -0.68987056,
                                 -0.39750262],
                             [-0.28826405, -1.23635074, -0.76124386], [
                                 -1.32869473, -1.8752391, -0.182537
                             ], [0.79464218, 0.65055633, 1.57572506],
                             [0.71524202, 1.66759831, 0.88679047]])

        np.testing.assert_almost_equal(features, features_)
        np.testing.assert_almost_equal(times, times_)
        np.testing.assert_almost_equal(censoring, censoring_) 
Example 16
Project: eliot   Author: itamarst   File: test_json.py    License: Apache License 2.0 5 votes vote down vote up
def test_numpy(self):
        """NumPy objects get serialized to readable JSON."""
        l = [
            np.float32(12.5),
            np.float64(2.0),
            np.float16(0.5),
            np.bool(True),
            np.bool(False),
            np.bool_(True),
            np.unicode_("hello"),
            np.byte(12),
            np.short(12),
            np.intc(-13),
            np.int_(0),
            np.longlong(100),
            np.intp(7),
            np.ubyte(12),
            np.ushort(12),
            np.uintc(13),
            np.ulonglong(100),
            np.uintp(7),
            np.int8(1),
            np.int16(3),
            np.int32(4),
            np.int64(5),
            np.uint8(1),
            np.uint16(3),
            np.uint32(4),
            np.uint64(5),
        ]
        l2 = [l, np.array([1, 2, 3])]
        roundtripped = loads(dumps(l2, cls=EliotJSONEncoder))
        self.assertEqual([l, [1, 2, 3]], roundtripped) 
Example 17
Project: mhd_utils   Author: yanlend   File: __init__.py    License: MIT License 4 votes vote down vote up
def write_mhd_file(filename: PathLike, data: np.ndarray, **meta_dict):
    """
    Write a meta file and the raw file.
    The byte order of the raw file will always be in the byte order of the system. 

    :param filename: file to write
    :param meta_dict: dictionary of meta data in MetaImage format
    """
    assert filename[-4:] == '.mhd' 
    meta_dict['ObjectType'] = 'Image'
    meta_dict['BinaryData'] = 'True'
    meta_dict['BinaryDataByteOrderMSB'] = 'False' if sys.byteorder == 'little' else 'True'
    if data.dtype == np.float32:
        meta_dict['ElementType'] = 'MET_FLOAT'
    elif data.dtype == np.double or data.dtype == np.float64:
        meta_dict['ElementType'] = 'MET_DOUBLE'
    elif data.dtype == np.byte:
        meta_dict['ElementType'] = 'MET_CHAR'
    elif data.dtype == np.uint8 or data.dtype == np.ubyte:
        meta_dict['ElementType'] = 'MET_UCHAR'
    elif data.dtype == np.short or data.dtype == np.int16:
        meta_dict['ElementType'] = 'MET_SHORT'
    elif data.dtype == np.ushort or data.dtype == np.uint16:
        meta_dict['ElementType'] = 'MET_USHORT'
    elif data.dtype == np.int32:
        meta_dict['ElementType'] = 'MET_INT'
    elif data.dtype == np.uint32:
        meta_dict['ElementType'] = 'MET_UINT'
    else:
        raise NotImplementedError("ElementType " + str(data.dtype) + " not implemented.")
    dsize = list(data.shape)
    if 'ElementNumberOfChannels' in meta_dict.keys():
        element_channels = int(meta_dict['ElementNumberOfChannels'])
        assert(dsize[-1] == element_channels)
        dsize = dsize[:-1]
    else:
        element_channels = 1
    dsize.reverse()
    meta_dict['NDims'] = str(len(dsize))
    meta_dict['DimSize'] = dsize
    meta_dict['ElementDataFile'] = str(Path(filename).name).replace('.mhd', '.raw')
    print(str(Path(filename).name).replace('.mhd', '.raw'))

    # Tags that need conversion of list to string
    tags = ['ElementSpacing', 'Offset', 'DimSize', 'CenterOfRotation', 'TransformMatrix']
    for tag in tags:
        if tag in meta_dict.keys() and not isinstance(meta_dict[tag], str):
            meta_dict[tag] = ' '.join([str(i) for i in meta_dict[tag]])
    write_meta_header(filename, meta_dict)

    # Compute absolute path to write to
    pwd = Path(filename).parents[0].resolve()
    data_file = Path(meta_dict['ElementDataFile'])
    if not data_file.is_absolute():
        data_file = pwd / data_file

    # Dump raw data
    data = data.reshape(dsize[0], -1, element_channels)
    with open(data_file, 'wb') as f:
        data.tofile(f) 
Example 18
Project: tick   Author: X-DataInitiative   File: simu_coxreg_test.py    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_SimuCoxRegWithCutPoints(self):
        """...Test simulation of a Cox Regression with cut-points
        """
        # Simulate a Cox model with cut-points with specific seed
        n_samples = 10
        n_features = 3
        n_cut_points = 2
        cov_corr = .5
        sparsity = .2

        seed = 123
        simu = SimuCoxRegWithCutPoints(n_samples=n_samples,
                                       n_features=n_features,
                                       seed=seed, verbose=False,
                                       n_cut_points=n_cut_points,
                                       shape=2, scale=.1, cov_corr=cov_corr,
                                       sparsity=sparsity)
        features_, times_, censoring_, cut_points_, coeffs_binarized_, S_ = simu.simulate()

        times = np.array([6.12215425, 6.74403919, 5.2148425, 5.42903238,
                          2.42953933, 9.50705158, 18.49545933, 19.7929349,
                          0.39267278, 1.24799812])

        censoring = np.array([1, 0, 0, 1, 0, 1, 1, 1, 0, 1], dtype=np.ushort)

        features = np.array([[1.4912667, 0.80881799, 0.26977298],
                             [1.23227551, 0.50697013, 1.9409132],
                             [1.8891494, 1.49834791, 2.41445794],
                             [0.19431319, 0.80245126, 1.02577552],
                             [-1.61687582, -1.08411865, -0.83438387],
                             [2.30419894, -0.68987056, -0.39750262],
                             [-0.28826405, -1.23635074, -0.76124386],
                             [-1.32869473, -1.8752391, -0.182537],
                             [0.79464218, 0.65055633, 1.57572506],
                             [0.71524202, 1.66759831, 0.88679047]])

        cut_points = {'0': np.array([-np.inf, -0.28826405, 0.79464218, np.inf]),
                      '1': np.array([-np.inf, -1.23635074, 0.50697013, np.inf]),
                      '2': np.array([-np.inf, -0.182537, 0.88679047, np.inf])}

        coeffs_binarized = np.array([-1.26789642, 1.31105319, -0.04315676, 0.,
                                     0., 0., 0.01839684, 0.4075832,
                                     -0.42598004])

        S = np.array([1])

        np.testing.assert_almost_equal(features, features_)
        np.testing.assert_almost_equal(times, times_)
        np.testing.assert_almost_equal(censoring, censoring_)
        np.testing.assert_almost_equal(cut_points_['0'], cut_points['0'])
        np.testing.assert_almost_equal(cut_points_['1'], cut_points['1'])
        np.testing.assert_almost_equal(cut_points_['2'], cut_points['2'])
        np.testing.assert_almost_equal(coeffs_binarized, coeffs_binarized_)
        np.testing.assert_almost_equal(S, S_)