Python numpy.remainder() Examples

The following are 30 code examples for showing how to use numpy.remainder(). 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: NeuroKit   Author: neuropsychology   File: ecg_simulate.py    License: MIT License 6 votes vote down vote up
def _ecg_simulate_derivsecgsyn(t, x, rr, ti, sfint, ai, bi):

    ta = math.atan2(x[1], x[0])
    r0 = 1
    a0 = 1.0 - np.sqrt(x[0] ** 2 + x[1] ** 2) / r0

    ip = np.floor(t * sfint).astype(int)
    w0 = 2 * np.pi / rr[min(ip, len(rr) - 1)]
    # w0 = 2*np.pi/rr[ip[ip <= np.max(rr)]]

    fresp = 0.25
    zbase = 0.005 * np.sin(2 * np.pi * fresp * t)

    dx1dt = a0 * x[0] - w0 * x[1]
    dx2dt = a0 * x[1] + w0 * x[0]

    # matlab rem and numpy rem are different
    # dti = np.remainder(ta - ti, 2*np.pi)
    dti = (ta - ti) - np.round((ta - ti) / 2 / np.pi) * 2 * np.pi
    dx3dt = -np.sum(ai * dti * np.exp(-0.5 * (dti / bi) ** 2)) - 1 * (x[2] - zbase)

    dxdt = np.array([dx1dt, dx2dt, dx3dt])
    return dxdt 
Example 2
Project: deepchem   Author: deepchem   File: transformers.py    License: MIT License 6 votes vote down vote up
def get_cdf_values(array, bins):
  # array = np.transpose(array)
  n_rows = array.shape[0]
  n_cols = array.shape[1]
  array_t = np.zeros((n_rows, n_cols))
  parts = n_rows / bins
  hist_values = np.zeros(n_rows)
  sorted_hist_values = np.zeros(n_rows)
  for row in range(n_rows):
    if np.remainder(bins, 2) == 1:
      hist_values[row] = np.floor(np.divide(row, parts)) / (bins - 1)
    else:
      hist_values[row] = np.floor(np.divide(row, parts)) / bins
  for col in range(n_cols):
    order = np.argsort(array[:, col], axis=0)
    sorted_hist_values = hist_values[order]
    array_t[:, col] = sorted_hist_values

  return array_t 
Example 3
Project: PADME   Author: simonfqy   File: transformers.py    License: MIT License 6 votes vote down vote up
def get_cdf_values(array, bins):
  # array = np.transpose(array)
  n_rows = array.shape[0]
  n_cols = array.shape[1]
  array_t = np.zeros((n_rows, n_cols))
  parts = n_rows / bins
  hist_values = np.zeros(n_rows)
  sorted_hist_values = np.zeros(n_rows)
  for row in range(n_rows):
    if np.remainder(bins, 2) == 1:
      hist_values[row] = np.floor(np.divide(row, parts)) / (bins - 1)
    else:
      hist_values[row] = np.floor(np.divide(row, parts)) / bins
  for col in range(n_cols):
    order = np.argsort(array[:, col], axis=0)
    sorted_hist_values = hist_values[order]
    array_t[:, col] = sorted_hist_values

  return array_t 
Example 4
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_remainder_basic(self):
        dt = np.typecodes['AllInteger'] + np.typecodes['Float']
        for dt1, dt2 in itertools.product(dt, dt):
            for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
                if sg1 == -1 and dt1 in np.typecodes['UnsignedInteger']:
                    continue
                if sg2 == -1 and dt2 in np.typecodes['UnsignedInteger']:
                    continue
                fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s'
                msg = fmt % (dt1, dt2, sg1, sg2)
                a = np.array(sg1*71, dtype=dt1)
                b = np.array(sg2*19, dtype=dt2)
                div = np.floor_divide(a, b)
                rem = np.remainder(a, b)
                assert_equal(div*b + rem, a, err_msg=msg)
                if sg2 == -1:
                    assert_(b < rem <= 0, msg)
                else:
                    assert_(b > rem >= 0, msg) 
Example 5
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_float_remainder_exact(self):
        # test that float results are exact for small integers. This also
        # holds for the same integers scaled by powers of two.
        nlst = list(range(-127, 0))
        plst = list(range(1, 128))
        dividend = nlst + [0] + plst
        divisor = nlst + plst
        arg = list(itertools.product(dividend, divisor))
        tgt = list(divmod(*t) for t in arg)

        a, b = np.array(arg, dtype=int).T
        # convert exact integer results from Python to float so that
        # signed zero can be used, it is checked.
        tgtdiv, tgtrem = np.array(tgt, dtype=float).T
        tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv)
        tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem)

        for dt in np.typecodes['Float']:
            msg = 'dtype: %s' % (dt,)
            fa = a.astype(dt)
            fb = b.astype(dt)
            div = np.floor_divide(fa, fb)
            rem = np.remainder(fa, fb)
            assert_equal(div, tgtdiv, err_msg=msg)
            assert_equal(rem, tgtrem, err_msg=msg) 
Example 6
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_float_remainder_roundoff(self):
        # gh-6127
        dt = np.typecodes['Float']
        for dt1, dt2 in itertools.product(dt, dt):
            for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
                fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s'
                msg = fmt % (dt1, dt2, sg1, sg2)
                a = np.array(sg1*78*6e-8, dtype=dt1)
                b = np.array(sg2*6e-8, dtype=dt2)
                div = np.floor_divide(a, b)
                rem = np.remainder(a, b)
                # Equal assertion should hold when fmod is used
                assert_equal(div*b + rem, a, err_msg=msg)
                if sg2 == -1:
                    assert_(b < rem <= 0, msg)
                else:
                    assert_(b > rem >= 0, msg) 
Example 7
Project: dmc-net   Author: facebookresearch   File: video_sampler.py    License: MIT License 6 votes vote down vote up
def sampling(self, range_max, v_id=None, prev_failed=False):
        assert range_max > 0, \
            ValueError("range_max = {}".format(range_max))
        interval = self.rng.choice(self.interval)
        if self.num == 1:
            return [self.rng.choice(range(0, range_max))]
        # sampling
        speed_min = self.speed[0]
        speed_max = min(self.speed[1], (range_max-1)/((self.num-1)*interval))
        if speed_max < speed_min:
            return (np.remainder(np.arange(0, self.num * interval, interval), range_max)).tolist()
        random_interval = self.rng.uniform(speed_min, speed_max) * interval
        frame_range = (self.num-1) * random_interval
        clip_start = self.rng.uniform(0, (range_max-1) - frame_range)
        clip_end = clip_start + frame_range
        return np.linspace(clip_start, clip_end, self.num).astype(dtype=np.int).tolist() 
Example 8
Project: dmc-net   Author: facebookresearch   File: video_sampler.py    License: MIT License 6 votes vote down vote up
def sampling(self, range_max, v_id, prev_failed=False):
        assert range_max > 0, \
            ValueError("range_max = {}".format(range_max))
        num = self.num
        interval = self.rng.choice(self.interval)
        frame_range = (num - 1) * interval + 1
        # sampling clips
        if v_id not in self.memory:
            clips = list(range(0, range_max-(frame_range-1), frame_range))
            if self.shuffle:
                self.rng.shuffle(clips)
            self.memory[v_id] = [-1, clips]
        # pickup a clip
        cursor, clips = self.memory[v_id]
        if not clips:
            return (np.remainder(np.arange(0, self.num * interval, interval), range_max)).tolist()
        cursor = (cursor + 1) % len(clips)
        if prev_failed or not self.fix_cursor:
            self.memory[v_id][0] = cursor
        # sampling within clip
        idxs = range(clips[cursor], clips[cursor]+frame_range, interval)
        return idxs 
Example 9
Project: magphase   Author: CSTR-Edinburgh   File: magphase.py    License: Apache License 2.0 6 votes vote down vote up
def frame_to_state_mapping(shift_file, lab_file, fs, states_per_phone=5):
    #Read files:
    v_shift = lu.read_binfile(shift_file, dim=1)
    v_pm = la.shift_to_pm(v_shift)
    m_state_times = np.loadtxt(lab_file, usecols=(0,1))    
    
    # to miliseconds:
    v_pm_ms = 1000 * v_pm / fs
    m_state_times_ms = m_state_times / 10000.0    
    
    # Compare:
    nfrms = len(v_pm_ms)
    v_st = np.zeros(nfrms) - 1 # init
    for f in xrange(nfrms):
        vb_greater = (v_pm_ms[f] >= m_state_times_ms[:,0])  # * (v_pm_ms[f] <  m_state_times_ms[:,1])
        state_nx   = np.where(vb_greater)[0][-1]
        v_st[f]    = np.remainder(state_nx, states_per_phone)
    return v_st
    
#============================================================================== 
Example 10
Project: mhfp   Author: reymond-group   File: encoder.py    License: MIT License 6 votes vote down vote up
def from_molecular_shingling(self, tokens):
        """Creates the hash set for a string array and returns it without changing the hash values of
    this instance.
    
    Arguments:
      a {numpy.ndarray} -- A string array.
    
    Returns:
      numpy.ndarray -- An array containing the hash values.
    """

        hash_values = np.zeros([self.n_permutations, 1], dtype=np.uint32)
        hash_values.fill(MHFPEncoder.max_hash)

        for t in tokens:
            t_h = struct.unpack("<I", sha1(t).digest()[:4])[0]
            hashes = np.remainder(
                np.remainder(
                    self.permutations_a * t_h + self.permutations_b, MHFPEncoder.prime
                ),
                self.max_hash,
            )
            hash_values = np.minimum(hash_values, hashes)

        return hash_values.reshape((1, self.n_permutations))[0] 
Example 11
Project: mhfp   Author: reymond-group   File: encoder.py    License: MIT License 6 votes vote down vote up
def from_sparse_array(self, array):
        """Creates the hash set for a sparse binary array and returns it without changing the hash
    values of this instance. This is useful when a molecular shingling is already hashed.
    
    Arguments:
      s {numpy.ndarray} -- A sparse binary array.
    
    Returns:
      numpy.ndarray -- An array containing the hash values.
    """

        hash_values = np.zeros([self.n_permutations, 1], dtype=np.uint32)
        hash_values.fill(MHFPEncoder.max_hash)

        for i in array:
            hashes = np.remainder(
                np.remainder(
                    self.permutations_a * i + self.permutations_b, MHFPEncoder.prime
                ),
                self.max_hash,
            )
            hash_values = np.minimum(hash_values, hashes)

        return hash_values.reshape((1, self.n_permutations))[0] 
Example 12
Project: mhfp   Author: reymond-group   File: encoder.py    License: MIT License 6 votes vote down vote up
def from_binary_array(self, array):
        """Creates the hash set for a binary array and returns it without changing the hash
    values of this instance. This is useful to minhash a folded fingerprint.
    
    Arguments:
      s {numpy.ndarray} -- A sparse binary array.
    
    Returns:
      numpy.ndarray -- A binary array.
    """

        hash_values = np.zeros([self.n_permutations, 1], dtype=np.uint32)
        hash_values.fill(MHFPEncoder.max_hash)

        for i, v in enumerate(array):
            if v == 1:
                hashes = np.remainder(
                    np.remainder(
                        self.permutations_a * i + self.permutations_b, MHFPEncoder.prime
                    ),
                    self.max_hash,
                )
                hash_values = np.minimum(hash_values, hashes)

        return hash_values.reshape((1, self.n_permutations))[0] 
Example 13
Project: feets   Author: quatrope   File: ext_signature.py    License: MIT License 5 votes vote down vote up
def fit(self, magnitude, time, PeriodLS, Amplitude, phase_bins, mag_bins):
        first_period = PeriodLS[0]
        lc_yaxis = (magnitude - np.min(magnitude)) / np.float(Amplitude)

        # SHIFT TO BEGIN AT MINIMUM
        loc = np.argmin(lc_yaxis)
        lc_phase = np.remainder(time - time[loc], first_period) / first_period

        bins = (phase_bins, mag_bins)
        signature = np.histogram2d(lc_phase, lc_yaxis, bins=bins, normed=True)[
            0
        ]

        return {"SignaturePhMag": signature} 
Example 14
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 5 votes vote down vote up
def floor_divide_and_remainder(x, y):
    return (np.floor_divide(x, y), np.remainder(x, y)) 
Example 15
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 5 votes vote down vote up
def test_float_remainder_corner_cases(self):
        # Check remainder magnitude.
        for dt in np.typecodes['Float']:
            b = np.array(1.0, dtype=dt)
            a = np.nextafter(np.array(0.0, dtype=dt), -b)
            rem = np.remainder(a, b)
            assert_(rem <= b, 'dt: %s' % dt)
            rem = np.remainder(-a, -b)
            assert_(rem >= -b, 'dt: %s' % dt)

        # Check nans, inf
        with suppress_warnings() as sup:
            sup.filter(RuntimeWarning, "invalid value encountered in remainder")
            for dt in np.typecodes['Float']:
                fone = np.array(1.0, dtype=dt)
                fzer = np.array(0.0, dtype=dt)
                finf = np.array(np.inf, dtype=dt)
                fnan = np.array(np.nan, dtype=dt)
                rem = np.remainder(fone, fzer)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
                # MSVC 2008 returns NaN here, so disable the check.
                #rem = np.remainder(fone, finf)
                #assert_(rem == fone, 'dt: %s, rem: %s' % (dt, rem))
                rem = np.remainder(fone, fnan)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
                rem = np.remainder(finf, fone)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) 
Example 16
Project: lambda-packs   Author: ryfeus   File: common.py    License: MIT License 5 votes vote down vote up
def reflective_transformation(y, lb, ub):
    """Compute reflective transformation and its gradient."""
    if in_bounds(y, lb, ub):
        return y, np.ones_like(y)

    lb_finite = np.isfinite(lb)
    ub_finite = np.isfinite(ub)

    x = y.copy()
    g_negative = np.zeros_like(y, dtype=bool)

    mask = lb_finite & ~ub_finite
    x[mask] = np.maximum(y[mask], 2 * lb[mask] - y[mask])
    g_negative[mask] = y[mask] < lb[mask]

    mask = ~lb_finite & ub_finite
    x[mask] = np.minimum(y[mask], 2 * ub[mask] - y[mask])
    g_negative[mask] = y[mask] > ub[mask]

    mask = lb_finite & ub_finite
    d = ub - lb
    t = np.remainder(y[mask] - lb[mask], 2 * d[mask])
    x[mask] = lb[mask] + np.minimum(t, 2 * d[mask] - t)
    g_negative[mask] = t > d[mask]

    g = np.ones_like(y)
    g[g_negative] = -1

    return x, g


# Functions to display algorithm's progress. 
Example 17
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_float_remainder_corner_cases(self):
        # Check remainder magnitude.
        for dt in np.typecodes['Float']:
            b = np.array(1.0, dtype=dt)
            a = np.nextafter(np.array(0.0, dtype=dt), -b)
            rem = np.remainder(a, b)
            assert_(rem <= b, 'dt: %s' % dt)
            rem = np.remainder(-a, -b)
            assert_(rem >= -b, 'dt: %s' % dt)

        # Check nans, inf
        with warnings.catch_warnings():
            warnings.simplefilter('always')
            warnings.simplefilter('ignore', RuntimeWarning)
            for dt in np.typecodes['Float']:
                fone = np.array(1.0, dtype=dt)
                fzer = np.array(0.0, dtype=dt)
                finf = np.array(np.inf, dtype=dt)
                fnan = np.array(np.nan, dtype=dt)
                rem = np.remainder(fone, fzer)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
                # MSVC 2008 returns NaN here, so disable the check.
                #rem = np.remainder(fone, finf)
                #assert_(rem == fone, 'dt: %s, rem: %s' % (dt, rem))
                rem = np.remainder(fone, fnan)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
                rem = np.remainder(finf, fone)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) 
Example 18
Project: vnpy_crypto   Author: birforce   File: test_umath.py    License: MIT License 5 votes vote down vote up
def floor_divide_and_remainder(x, y):
    return (np.floor_divide(x, y), np.remainder(x, y)) 
Example 19
Project: vnpy_crypto   Author: birforce   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_float_remainder_corner_cases(self):
        # Check remainder magnitude.
        for dt in np.typecodes['Float']:
            b = np.array(1.0, dtype=dt)
            a = np.nextafter(np.array(0.0, dtype=dt), -b)
            rem = np.remainder(a, b)
            assert_(rem <= b, 'dt: %s' % dt)
            rem = np.remainder(-a, -b)
            assert_(rem >= -b, 'dt: %s' % dt)

        # Check nans, inf
        with suppress_warnings() as sup:
            sup.filter(RuntimeWarning, "invalid value encountered in remainder")
            for dt in np.typecodes['Float']:
                fone = np.array(1.0, dtype=dt)
                fzer = np.array(0.0, dtype=dt)
                finf = np.array(np.inf, dtype=dt)
                fnan = np.array(np.nan, dtype=dt)
                rem = np.remainder(fone, fzer)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
                # MSVC 2008 returns NaN here, so disable the check.
                #rem = np.remainder(fone, finf)
                #assert_(rem == fone, 'dt: %s, rem: %s' % (dt, rem))
                rem = np.remainder(fone, fnan)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
                rem = np.remainder(finf, fone)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) 
Example 20
Project: pingouin   Author: raphaelvallat   File: circular.py    License: GNU General Public License v3.0 5 votes vote down vote up
def circ_axial(angles, n):
    """Transforms n-axial data to a common scale.

    Parameters
    ----------
    angles : array
        Sample of angles in radians
    n : int
        Number of modes

    Returns
    -------
    angles : float
        Transformed angles

    Notes
    -----
    Tranform data with multiple modes (known as axial data) to a unimodal
    sample, for the purpose of certain analysis such as computation of a
    mean resultant vector (see Berens 2009).

    Examples
    --------
    Transform degrees to unimodal radians in the Berens 2009 neuro dataset.

    >>> import numpy as np
    >>> from pingouin import read_dataset
    >>> from pingouin.circular import circ_axial
    >>> df = read_dataset('circular')
    >>> angles = df['Orientation'].to_numpy()
    >>> angles = circ_axial(np.deg2rad(angles), 2)
    """
    angles = np.asarray(angles)
    return np.remainder(angles * n, 2 * np.pi)


###############################################################################
# DESCRIPTIVE STATISTICS
############################################################################### 
Example 21
Project: Ensemble-Bayesian-Optimization   Author: zi-w   File: representation.py    License: MIT License 5 votes vote down vote up
def __call__(self, indices):
        if self.wrap:
            indices = np.remainder(indices, self.dims)
        else:
            indices = np.clip(indices, 0, self.dims - 1)
        return np.sum(indices * self.dim_offset, axis=1)


################## END OF TILE CODING IMPLEMENTATION #########################


################## RBF IMPLEMENTATION ######################################## 
Example 22
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_umath.py    License: MIT License 5 votes vote down vote up
def floor_divide_and_remainder(x, y):
    return (np.floor_divide(x, y), np.remainder(x, y)) 
Example 23
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_float_remainder_corner_cases(self):
        # Check remainder magnitude.
        for dt in np.typecodes['Float']:
            b = np.array(1.0, dtype=dt)
            a = np.nextafter(np.array(0.0, dtype=dt), -b)
            rem = np.remainder(a, b)
            assert_(rem <= b, 'dt: %s' % dt)
            rem = np.remainder(-a, -b)
            assert_(rem >= -b, 'dt: %s' % dt)

        # Check nans, inf
        with suppress_warnings() as sup:
            sup.filter(RuntimeWarning, "invalid value encountered in remainder")
            for dt in np.typecodes['Float']:
                fone = np.array(1.0, dtype=dt)
                fzer = np.array(0.0, dtype=dt)
                finf = np.array(np.inf, dtype=dt)
                fnan = np.array(np.nan, dtype=dt)
                rem = np.remainder(fone, fzer)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
                # MSVC 2008 returns NaN here, so disable the check.
                #rem = np.remainder(fone, finf)
                #assert_(rem == fone, 'dt: %s, rem: %s' % (dt, rem))
                rem = np.remainder(fone, fnan)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
                rem = np.remainder(finf, fone)
                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) 
Example 24
Project: pyziabm   Author: JackBenny39   File: runner2017mpi_r3.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_providers(self, step):
        providers = self.provider_array[np.remainder(step, self.t_delta_p)==0]
        np.random.shuffle(providers)
        return providers 
Example 25
Project: pyziabm   Author: JackBenny39   File: runner2017mpi_r3.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_both(self, step):
        providers_mask = np.remainder(step, self.t_delta_p)==0
        takers_mask = np.remainder(step, self.t_delta_t)==0
        marketmakers_mask = np.remainder(step, self.t_delta_m)==0
        providers = np.vstack((self.provider_array, providers_mask)).T
        takers = np.vstack((self.taker_array, takers_mask)).T
        marketmakers = np.vstack((self.marketmaker_array, marketmakers_mask)).T
        traders = np.vstack((providers, marketmakers, takers[takers_mask]))
        np.random.shuffle(traders)
        return traders 
Example 26
Project: pyziabm   Author: JackBenny39   File: runner2017mpi_r3.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_mcs(self, prime1):
        top_of_book = self.exchange.report_top_of_book(prime1)
        for current_time in range(prime1, self.run_steps):
            for row in self.make_both(current_time):
                if row[0].trader_type == 'Provider':
                    if row[1]:
                        row[0].process_signal(current_time, top_of_book, self.q_provide, self.lambda_t[current_time])
                        self.exchange.process_order(row[0].quote_collector[-1])
                        top_of_book = self.exchange.report_top_of_book(current_time)
                    row[0].bulk_cancel(current_time)
                    if row[0].cancel_collector: # <---- Check permission versus forgiveness here and elsewhere - move to methods?
                        for c in row[0].cancel_collector:
                            self.exchange.process_order(c)
                            if self.exchange.confirm_modify_collector: # <---- Check permission versus forgiveness here and elsewhere - move to methods?
                                row[0].confirm_cancel_local(self.exchange.confirm_modify_collector[0])
                        top_of_book = self.exchange.report_top_of_book(current_time)
                elif row[0].trader_type == 'MarketMaker':
                    if row[1]:
                        row[0].process_signal(current_time, top_of_book, self.q_provide)
                        for q in row[0].quote_collector:
                            self.exchange.process_order(q)
                        top_of_book = self.exchange.report_top_of_book(current_time)
                    row[0].bulk_cancel(current_time)
                    if row[0].cancel_collector: # <---- Check permission versus forgiveness here and elsewhere - move to methods?
                        for c in row[0].cancel_collector:
                            self.exchange.process_order(c)
                            if self.exchange.confirm_modify_collector: # <---- Check permission versus forgiveness here and elsewhere - move to methods?
                                row[0].confirm_cancel_local(self.exchange.confirm_modify_collector[0])
                        top_of_book = self.exchange.report_top_of_book(current_time)
                else:
                    row[0].process_signal(current_time, self.q_take[current_time])
                    self.exchange.process_order(row[0].quote_collector[-1])
                    if self.exchange.traded: # <---- Check permission versus forgiveness here and elsewhere - move to methods?
                        for c in self.exchange.confirm_trade_collector:
                            trader = self.trader_dict[c['trader']]
                            trader.confirm_trade_local(c)
                        top_of_book = self.exchange.report_top_of_book(current_time)
            if not np.remainder(current_time, 2000):
                self.exchange.order_history_to_h5(self.h5filename)
                self.exchange.sip_to_h5(self.h5filename) 
Example 27
Project: pyziabm   Author: JackBenny39   File: runner2017mpi_r4.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_providers(self, step):
        providers = self.provider_array[np.remainder(step, self.t_delta_p)==0]
        np.random.shuffle(providers)
        return providers 
Example 28
Project: pyziabm   Author: JackBenny39   File: runner2017mpi_r4.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_mcs(self, prime1):
        top_of_book = self.exchange.report_top_of_book(prime1)
        for current_time in range(prime1, self.run_steps):
            for row in self.make_both(current_time):
                if row[0].trader_type == 'Provider':
                    if row[1]:
                        row[0].process_signal(current_time, top_of_book, self.q_provide, self.lambda_t[current_time])
                        self.exchange.process_order(row[0].quote_collector[-1])
                        top_of_book = self.exchange.report_top_of_book(current_time)
                    row[0].bulk_cancel(current_time)
                    if row[0].cancel_collector: # <---- Check permission versus forgiveness here and elsewhere - move to methods?
                        for c in row[0].cancel_collector:
                            self.exchange.process_order(c)
                            if self.exchange.confirm_modify_collector: # <---- Check permission versus forgiveness here and elsewhere - move to methods?
                                row[0].confirm_cancel_local(self.exchange.confirm_modify_collector[0])
                        top_of_book = self.exchange.report_top_of_book(current_time)
                elif row[0].trader_type == 'MarketMaker':
                    if row[1]:
                        row[0].process_signal(current_time, top_of_book, self.q_provide)
                        for q in row[0].quote_collector:
                            self.exchange.process_order(q)
                        top_of_book = self.exchange.report_top_of_book(current_time)
                    row[0].bulk_cancel(current_time)
                    if row[0].cancel_collector: # <---- Check permission versus forgiveness here and elsewhere - move to methods?
                        for c in row[0].cancel_collector:
                            self.exchange.process_order(c)
                            if self.exchange.confirm_modify_collector: # <---- Check permission versus forgiveness here and elsewhere - move to methods?
                                row[0].confirm_cancel_local(self.exchange.confirm_modify_collector[0])
                        top_of_book = self.exchange.report_top_of_book(current_time)
                else:
                    row[0].process_signal(current_time, self.q_take[current_time])
                    self.exchange.process_order(row[0].quote_collector[-1])
                    if self.exchange.traded: # <---- Check permission versus forgiveness here and elsewhere - move to methods?
                        for c in self.exchange.confirm_trade_collector:
                            trader = self.trader_dict[c['trader']]
                            trader.confirm_trade_local(c)
                        top_of_book = self.exchange.report_top_of_book(current_time)
            if not np.remainder(current_time, 2000):
                self.exchange.order_history_to_h5(self.h5filename)
                self.exchange.sip_to_h5(self.h5filename) 
Example 29
Project: pyziabm   Author: JackBenny39   File: testTrader2017_r3.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_choose_price_from_exp(self):
        # mpi == 1
        sell_price = self.p1._choose_price_from_exp('bid', 75000, -100)
        self.assertLess(sell_price, 75000)
        buy_price = self.p1._choose_price_from_exp('ask', 25000, -100)
        self.assertGreater(buy_price, 25000)
        self.assertEqual(np.remainder(buy_price,self.p1._mpi),0)
        self.assertEqual(np.remainder(sell_price,self.p1._mpi),0)
        # mpi == 5        
        sell_price = self.p5._choose_price_from_exp('bid', 75000, -100)
        self.assertLess(sell_price, 75000)
        buy_price = self.p5._choose_price_from_exp('ask', 25000, -100)
        self.assertGreater(buy_price, 25000)
        self.assertEqual(np.remainder(buy_price,self.p5._mpi),0)
        self.assertEqual(np.remainder(sell_price,self.p5._mpi),0) 
Example 30
Project: GCA-Matting   Author: Yaoyi-Li   File: data_generator.py    License: MIT License 5 votes vote down vote up
def __call__(self, sample):
        fg, alpha = sample['fg'], sample['alpha']
        # if alpha is all 0 skip
        if np.all(alpha==0):
            return sample
        # convert to HSV space, convert to float32 image to keep precision during space conversion.
        fg = cv2.cvtColor(fg.astype(np.float32)/255.0, cv2.COLOR_BGR2HSV)
        # Hue noise
        hue_jitter = np.random.randint(-40, 40)
        fg[:, :, 0] = np.remainder(fg[:, :, 0].astype(np.float32) + hue_jitter, 360)
        # Saturation noise
        sat_bar = fg[:, :, 1][alpha > 0].mean()
        sat_jitter = np.random.rand()*(1.1 - sat_bar)/5 - (1.1 - sat_bar) / 10
        sat = fg[:, :, 1]
        sat = np.abs(sat + sat_jitter)
        sat[sat>1] = 2 - sat[sat>1]
        fg[:, :, 1] = sat
        # Value noise
        val_bar = fg[:, :, 2][alpha > 0].mean()
        val_jitter = np.random.rand()*(1.1 - val_bar)/5-(1.1 - val_bar) / 10
        val = fg[:, :, 2]
        val = np.abs(val + val_jitter)
        val[val>1] = 2 - val[val>1]
        fg[:, :, 2] = val
        # convert back to BGR space
        fg = cv2.cvtColor(fg, cv2.COLOR_HSV2BGR)
        sample['fg'] = fg*255

        return sample