Python numpy.logical_xor() Examples

The following are 30 code examples for showing how to use numpy.logical_xor(). 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: recruit   Author: Frank-qlu   File: test_ufunc.py    License: Apache License 2.0 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
Example 2
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 6 votes vote down vote up
def test_truth_table_logical(self):
        # 2, 3 and 4 serves as true values
        input1 = [0, 0, 3, 2]
        input2 = [0, 4, 0, 2]

        typecodes = (np.typecodes['AllFloat']
                     + np.typecodes['AllInteger']
                     + '?')     # boolean
        for dtype in map(np.dtype, typecodes):
            arg1 = np.asarray(input1, dtype=dtype)
            arg2 = np.asarray(input2, dtype=dtype)

            # OR
            out = [False, True, True, True]
            for func in (np.logical_or, np.maximum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # AND
            out = [False, False, False, True]
            for func in (np.logical_and, np.minimum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # XOR
            out = [False, True, True, False]
            for func in (np.logical_xor, np.not_equal):
                assert_equal(func(arg1, arg2).astype(bool), out) 
Example 3
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 6 votes vote down vote up
def test_reduce(self):
        none = np.array([0, 0, 0, 0], bool)
        some = np.array([1, 0, 1, 1], bool)
        every = np.array([1, 1, 1, 1], bool)
        empty = np.array([], bool)

        arrs = [none, some, every, empty]

        for arr in arrs:
            assert_equal(np.logical_and.reduce(arr), all(arr))

        for arr in arrs:
            assert_equal(np.logical_or.reduce(arr), any(arr))

        for arr in arrs:
            assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1) 
Example 4
Project: pycolab   Author: deepmind   File: extraterrestrial_marauders.py    License: Apache License 2.0 6 votes vote down vote up
def update(self, actions, board, layers, backdrop, things, the_plot):
    # Where are the laser bolts? Only bolts from the player kill a Marauder.
    bolts = np.logical_or.reduce([layers[c] for c in UPWARD_BOLT_CHARS], axis=0)
    hits = bolts & self.curtain                       # Any hits to Marauders?
    np.logical_xor(self.curtain, hits, self.curtain)  # If so, zap the marauder...
    the_plot.add_reward(np.sum(hits)*10)              # ...and supply a reward.
    # Save the identities of marauder-striking bolts in the Plot.
    the_plot['marauder_hitters'] = [chr(c) for c in board[hits]]

    # If no Marauders are left, or if any are sitting on row 10, end the game.
    if (not self.curtain.any()) or self.curtain[10, :].any():
      return the_plot.terminate_episode()  # i.e. return None.

    # We move faster if there are fewer Marauders. The odd divisor causes speed
    # jumps to align on the high sides of multiples of 8; so, speed increases as
    # the number of Marauders decreases to 32 (or 24 etc.), not 31 (or 23 etc.).
    if the_plot.frame % max(1, np.sum(self.curtain)//8.0000001): return
    # If any Marauder reaches either side of the screen, reverse horizontal
    # motion and advance vertically one row.
    if np.any(self.curtain[:, 0] | self.curtain[:, -1]):
      self._dx = -self._dx
      self.curtain[:] = np.roll(self.curtain, shift=1, axis=0)
    self.curtain[:] = np.roll(self.curtain, shift=self._dx, axis=1) 
Example 5
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_ufunc.py    License: MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
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_truth_table_logical(self):
        # 2, 3 and 4 serves as true values
        input1 = [0, 0, 3, 2]
        input2 = [0, 4, 0, 2]

        typecodes = (np.typecodes['AllFloat']
                     + np.typecodes['AllInteger']
                     + '?')     # boolean
        for dtype in map(np.dtype, typecodes):
            arg1 = np.asarray(input1, dtype=dtype)
            arg2 = np.asarray(input2, dtype=dtype)

            # OR
            out = [False, True, True, True]
            for func in (np.logical_or, np.maximum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # AND
            out = [False, False, False, True]
            for func in (np.logical_and, np.minimum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # XOR
            out = [False, True, True, False]
            for func in (np.logical_xor, np.not_equal):
                assert_equal(func(arg1, arg2).astype(bool), out) 
Example 7
Project: vnpy_crypto   Author: birforce   File: test_ufunc.py    License: MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example 8
Project: vnpy_crypto   Author: birforce   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_truth_table_logical(self):
        # 2, 3 and 4 serves as true values
        input1 = [0, 0, 3, 2]
        input2 = [0, 4, 0, 2]

        typecodes = (np.typecodes['AllFloat']
                     + np.typecodes['AllInteger']
                     + '?')     # boolean
        for dtype in map(np.dtype, typecodes):
            arg1 = np.asarray(input1, dtype=dtype)
            arg2 = np.asarray(input2, dtype=dtype)

            # OR
            out = [False, True, True, True]
            for func in (np.logical_or, np.maximum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # AND
            out = [False, False, False, True]
            for func in (np.logical_and, np.minimum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # XOR
            out = [False, True, True, False]
            for func in (np.logical_xor, np.not_equal):
                assert_equal(func(arg1, arg2).astype(bool), out) 
Example 9
Project: vnpy_crypto   Author: birforce   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_reduce(self):
        none = np.array([0, 0, 0, 0], bool)
        some = np.array([1, 0, 1, 1], bool)
        every = np.array([1, 1, 1, 1], bool)
        empty = np.array([], bool)

        arrs = [none, some, every, empty]

        for arr in arrs:
            assert_equal(np.logical_and.reduce(arr), all(arr))

        for arr in arrs:
            assert_equal(np.logical_or.reduce(arr), any(arr))

        for arr in arrs:
            assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1) 
Example 10
Project: nussl   Author: nussl   File: duet.py    License: MIT License 6 votes vote down vote up
def _compute_masks(self):
        """Receives the attenuation and delay peaks and computes a mask to be applied to the signal for source
        separation.

        """
        # compute masks for separation
        best_so_far = np.inf * np.ones_like(self.stft_ch0, dtype=float)

        for i in range(0, self.num_sources):
            mask_array = np.zeros_like(self.stft_ch0, dtype=bool)
            phase = np.exp(-1j * self.frequency_matrix * self.delay_peak[i])
            score = np.abs(self.atn_peak[i] * phase * self.stft_ch0 - self.stft_ch1) ** 2 / (1 + self.atn_peak[i] ** 2)
            mask = (score < best_so_far)
            mask_array[mask] = True
            background_mask = self.mask_type(np.array(mask_array))
            self.result_masks.append(background_mask)
            self.result_masks[0].mask = np.logical_xor(self.result_masks[i].mask, self.result_masks[0].mask)
            best_so_far[mask] = score[mask]

        # Compute first mask based on what the other masks left remaining
        self.result_masks[0].mask = np.logical_not(self.result_masks[0].mask)
        return self.result_masks 
Example 11
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_ufunc.py    License: MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
Example 12
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_truth_table_logical(self):
        # 2, 3 and 4 serves as true values
        input1 = [0, 0, 3, 2]
        input2 = [0, 4, 0, 2]

        typecodes = (np.typecodes['AllFloat']
                     + np.typecodes['AllInteger']
                     + '?')     # boolean
        for dtype in map(np.dtype, typecodes):
            arg1 = np.asarray(input1, dtype=dtype)
            arg2 = np.asarray(input2, dtype=dtype)

            # OR
            out = [False, True, True, True]
            for func in (np.logical_or, np.maximum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # AND
            out = [False, False, False, True]
            for func in (np.logical_and, np.minimum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # XOR
            out = [False, True, True, False]
            for func in (np.logical_xor, np.not_equal):
                assert_equal(func(arg1, arg2).astype(bool), out) 
Example 13
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_reduce(self):
        none = np.array([0, 0, 0, 0], bool)
        some = np.array([1, 0, 1, 1], bool)
        every = np.array([1, 1, 1, 1], bool)
        empty = np.array([], bool)

        arrs = [none, some, every, empty]

        for arr in arrs:
            assert_equal(np.logical_and.reduce(arr), all(arr))

        for arr in arrs:
            assert_equal(np.logical_or.reduce(arr), any(arr))

        for arr in arrs:
            assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1) 
Example 14
Project: LSM   Author: IGITUGraz   File: example.py    License: GNU General Public License v3.0 6 votes vote down vote up
def generate_stimulus_xor(stim_times, gen_burst, n_inputs=2):
    inp_states = np.random.randint(2, size=(n_inputs, np.size(stim_times)))
    inp_spikes = []

    for times in ma.masked_values(inp_states, 0) * stim_times:
        # for each input (neuron): generate spikes according to state (=1) and stimulus time-grid
        spikes = np.concatenate([t + gen_burst() for t in times.compressed()])

        # round to simulation precision
        spikes *= 10
        spikes = spikes.round() + 1.0
        spikes = spikes / 10.0

        inp_spikes.append(spikes)

    # astype(int) could be omitted, because False/True has the same semantics
    targets = np.logical_xor(*inp_states).astype(int)

    return inp_spikes, targets 
Example 15
Project: AugmentedAutoencoder   Author: DLR-RM   File: dataset.py    License: MIT License 6 votes vote down vote up
def augment_occlusion_mask(self, masks, verbose=False, min_trans = 0.2, max_trans=0.7, max_occl = 0.25,min_occl = 0.0):


        new_masks = np.zeros_like(masks,dtype=np.bool)
        occl_masks_batch = self.random_syn_masks[np.random.choice(len(self.random_syn_masks),len(masks))]
        for idx,mask in enumerate(masks):
            occl_mask = occl_masks_batch[idx]
            while True:
                trans_x = int(np.random.choice([-1,1])*(np.random.rand()*(max_trans-min_trans) + min_trans)*occl_mask.shape[0])
                trans_y = int(np.random.choice([-1,1])*(np.random.rand()*(max_trans-min_trans) + min_trans)*occl_mask.shape[1])
                M = np.float32([[1,0,trans_x],[0,1,trans_y]])

                transl_occl_mask = cv2.warpAffine(occl_mask,M,(occl_mask.shape[0],occl_mask.shape[1]))

                overlap_matrix = np.invert(mask.astype(np.bool)) * transl_occl_mask.astype(np.bool)
                overlap = len(overlap_matrix[overlap_matrix==True])/float(len(mask[mask==0]))

                if overlap < max_occl and overlap > min_occl:
                    new_masks[idx,...] = np.logical_xor(mask.astype(np.bool), overlap_matrix)
                    if verbose:
                        print('overlap is ', overlap)
                    break

        return new_masks 
Example 16
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_ufunc.py    License: MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example 17
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_truth_table_logical(self):
        # 2, 3 and 4 serves as true values
        input1 = [0, 0, 3, 2]
        input2 = [0, 4, 0, 2]

        typecodes = (np.typecodes['AllFloat']
                     + np.typecodes['AllInteger']
                     + '?')     # boolean
        for dtype in map(np.dtype, typecodes):
            arg1 = np.asarray(input1, dtype=dtype)
            arg2 = np.asarray(input2, dtype=dtype)

            # OR
            out = [False, True, True, True]
            for func in (np.logical_or, np.maximum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # AND
            out = [False, False, False, True]
            for func in (np.logical_and, np.minimum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # XOR
            out = [False, True, True, False]
            for func in (np.logical_xor, np.not_equal):
                assert_equal(func(arg1, arg2).astype(bool), out) 
Example 18
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_reduce(self):
        none = np.array([0, 0, 0, 0], bool)
        some = np.array([1, 0, 1, 1], bool)
        every = np.array([1, 1, 1, 1], bool)
        empty = np.array([], bool)

        arrs = [none, some, every, empty]

        for arr in arrs:
            assert_equal(np.logical_and.reduce(arr), all(arr))

        for arr in arrs:
            assert_equal(np.logical_or.reduce(arr), any(arr))

        for arr in arrs:
            assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1) 
Example 19
Project: deep_image_model   Author: tobegit3hub   File: cwise_ops_test.py    License: Apache License 2.0 6 votes vote down vote up
def testBCast(self):
    shapes = [
        ([1, 3, 2], [1]),
        ([1, 3, 2], [2]),
        ([1, 3, 2], [3, 2]),
        ([1, 3, 2], [3, 1]),
        ([1, 3, 2], [1, 3, 2]),
        ([1, 3, 2], [2, 3, 1]),
        ([1, 3, 2], [2, 1, 1]),
        ([1, 3, 2], [1, 3, 1]),
        ([2, 1, 5], [2, 3, 1]),
        ([2, 0, 5], [2, 0, 1]),
        ([2, 3, 0], [2, 3, 1]),
    ]
    for (xs, ys) in shapes:
      x = np.random.randint(0, 2, np.prod(xs)).astype(np.bool).reshape(xs)
      y = np.random.randint(0, 2, np.prod(ys)).astype(np.bool).reshape(ys)
      for use_gpu in [True, False]:
        self._compareBinary(x, y, np.logical_and, tf.logical_and, use_gpu)
        self._compareBinary(x, y, np.logical_or, tf.logical_or, use_gpu)
        self._compareBinary(x, y, np.logical_xor, tf.logical_xor, use_gpu) 
Example 20
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
Example 21
def test_truth_table_logical(self):
        # 2, 3 and 4 serves as true values
        input1 = [0, 0, 3, 2]
        input2 = [0, 4, 0, 2]

        typecodes = (np.typecodes['AllFloat']
                     + np.typecodes['AllInteger']
                     + '?')     # boolean
        for dtype in map(np.dtype, typecodes):
            arg1 = np.asarray(input1, dtype=dtype)
            arg2 = np.asarray(input2, dtype=dtype)

            # OR
            out = [False, True, True, True]
            for func in (np.logical_or, np.maximum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # AND
            out = [False, False, False, True]
            for func in (np.logical_and, np.minimum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # XOR
            out = [False, True, True, False]
            for func in (np.logical_xor, np.not_equal):
                assert_equal(func(arg1, arg2).astype(bool), out) 
Example 22
def test_reduce(self):
        none = np.array([0, 0, 0, 0], bool)
        some = np.array([1, 0, 1, 1], bool)
        every = np.array([1, 1, 1, 1], bool)
        empty = np.array([], bool)

        arrs = [none, some, every, empty]

        for arr in arrs:
            assert_equal(np.logical_and.reduce(arr), all(arr))

        for arr in arrs:
            assert_equal(np.logical_or.reduce(arr), any(arr))

        for arr in arrs:
            assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1) 
Example 23
Project: GNSS-DSP-tools   Author: pmonta   File: p.py    License: MIT License 6 votes vote down vote up
def last_x2(prn,start,len):
  idx = start + np.arange(len)
  idx_x2 = idx % 15345037

  idx_a = idx % 15345000
  hold = idx_a>=(15345000-1069)
  idx_x2_a = idx_x2.copy()
  idx_x2_a[hold] = 4091
  p_x2a = x2a[idx_x2_a % 4092]

  idx_b = idx % 15345000
  hold = idx_b>=(15345000-965)
  idx_x2_b = idx_x2.copy()
  idx_x2_b[hold] = 4092
  p_x2b = x2b[idx_x2_b % 4093]

  return np.logical_xor(p_x2a,p_x2b) 
Example 24
Project: pySINDy   Author: luckystarufo   File: test_ufunc.py    License: MIT License 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 
Example 25
Project: pySINDy   Author: luckystarufo   File: test_umath.py    License: MIT License 6 votes vote down vote up
def test_truth_table_logical(self):
        # 2, 3 and 4 serves as true values
        input1 = [0, 0, 3, 2]
        input2 = [0, 4, 0, 2]

        typecodes = (np.typecodes['AllFloat']
                     + np.typecodes['AllInteger']
                     + '?')     # boolean
        for dtype in map(np.dtype, typecodes):
            arg1 = np.asarray(input1, dtype=dtype)
            arg2 = np.asarray(input2, dtype=dtype)

            # OR
            out = [False, True, True, True]
            for func in (np.logical_or, np.maximum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # AND
            out = [False, False, False, True]
            for func in (np.logical_and, np.minimum):
                assert_equal(func(arg1, arg2).astype(bool), out)
            # XOR
            out = [False, True, True, False]
            for func in (np.logical_xor, np.not_equal):
                assert_equal(func(arg1, arg2).astype(bool), out) 
Example 26
Project: DOTA_models   Author: ringringyi   File: graph_utils.py    License: Apache License 2.0 5 votes vote down vote up
def convert_traversible_to_graph(traversible, ff_cost=1., fo_cost=1.,
                                 oo_cost=1., connectivity=4):
  assert(connectivity == 4 or connectivity == 8)

  sz_x = traversible.shape[1]
  sz_y = traversible.shape[0]
  g, nodes = generate_lattice(sz_x, sz_y)

  # Assign costs.
  edge_wts = g.new_edge_property('float')
  g.edge_properties['wts'] = edge_wts
  wts = np.ones(g.num_edges(), dtype=np.float32)
  edge_wts.get_array()[:] = wts

  if connectivity == 8:
    add_diagonal_edges(g, nodes, sz_x, sz_y, np.sqrt(2.))

  se = np.array([[int(e.source()), int(e.target())] for e in g.edges()])
  s_xy = nodes[se[:,0]]
  t_xy = nodes[se[:,1]]
  s_t = np.ravel_multi_index((s_xy[:,1], s_xy[:,0]), traversible.shape)
  t_t = np.ravel_multi_index((t_xy[:,1], t_xy[:,0]), traversible.shape)
  s_t = traversible.ravel()[s_t]
  t_t = traversible.ravel()[t_t]

  wts = np.zeros(g.num_edges(), dtype=np.float32)
  wts[np.logical_and(s_t == True, t_t == True)] = ff_cost
  wts[np.logical_and(s_t == False, t_t == False)] = oo_cost
  wts[np.logical_xor(s_t, t_t)] = fo_cost

  edge_wts = g.edge_properties['wts']
  for i, e in enumerate(g.edges()):
    edge_wts[e] = edge_wts[e] * wts[i]
  # d = edge_wts.get_array()*1.
  # edge_wts.get_array()[:] = d*wts 
  return g, nodes 
Example 27
Project: Deep-Feature-Flow-Segmentation   Author: tonysy   File: coco.py    License: MIT License 5 votes vote down vote up
def encodeMask(M):
        """
        Encode binary mask M using run-length encoding.
        :param   M (bool 2D array)  : binary mask to encode
        :return: R (object RLE)     : run-length encoding of binary mask
        """
        [h, w] = M.shape
        M = M.flatten(order='F')
        N = len(M)
        counts_list = []
        pos = 0
        # counts
        counts_list.append(1)
        diffs = np.logical_xor(M[0:N-1], M[1:N])
        for diff in diffs:
            if diff:
                pos +=1
                counts_list.append(1)
            else:
                counts_list[pos] += 1
        # if array starts from 1. start with 0 counts for 0
        if M[0] == 1:
            counts_list = [0] + counts_list
        return {'size':      [h, w],
               'counts':    counts_list ,
               } 
Example 28
Project: Deep-Feature-Flow-Segmentation   Author: tonysy   File: mask_voc2coco.py    License: MIT License 5 votes vote down vote up
def encodeMask(M):
    """
    Encode binary mask M using run-length encoding.
    :param   M (bool 2D array)  : binary mask to encode
    :return: R (object RLE)     : run-length encoding of binary mask
    """
    [h, w] = M.shape
    M = M.flatten(order='F')
    N = len(M)
    counts_list = []
    pos = 0
    # counts
    counts_list.append(1)
    diffs = np.logical_xor(M[0:N - 1], M[1:N])
    for diff in diffs:
        if diff:
            pos += 1
            counts_list.append(1)
        else:
            counts_list[pos] += 1
    # if array starts from 1. start with 0 counts for 0
    if M[0] == 1:
        counts_list = [0] + counts_list
    return {'size': [h, w],
            'counts': counts_list,
            } 
Example 29
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_logical_and_or_xor(self):
        assert_array_equal(self.t | self.t, self.t)
        assert_array_equal(self.f | self.f, self.f)
        assert_array_equal(self.t | self.f, self.t)
        assert_array_equal(self.f | self.t, self.t)
        np.logical_or(self.t, self.t, out=self.o)
        assert_array_equal(self.o, self.t)
        assert_array_equal(self.t & self.t, self.t)
        assert_array_equal(self.f & self.f, self.f)
        assert_array_equal(self.t & self.f, self.f)
        assert_array_equal(self.f & self.t, self.f)
        np.logical_and(self.t, self.t, out=self.o)
        assert_array_equal(self.o, self.t)
        assert_array_equal(self.t ^ self.t, self.f)
        assert_array_equal(self.f ^ self.f, self.f)
        assert_array_equal(self.t ^ self.f, self.t)
        assert_array_equal(self.f ^ self.t, self.t)
        np.logical_xor(self.t, self.t, out=self.o)
        assert_array_equal(self.o, self.f)

        assert_array_equal(self.nm & self.t, self.nm)
        assert_array_equal(self.im & self.f, False)
        assert_array_equal(self.nm & True, self.nm)
        assert_array_equal(self.im & False, self.f)
        assert_array_equal(self.nm | self.t, self.t)
        assert_array_equal(self.im | self.f, self.im)
        assert_array_equal(self.nm | True, self.t)
        assert_array_equal(self.im | False, self.im)
        assert_array_equal(self.nm ^ self.t, self.im)
        assert_array_equal(self.im ^ self.f, self.im)
        assert_array_equal(self.nm ^ True, self.im)
        assert_array_equal(self.im ^ False, self.im) 
Example 30
Project: 2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement   Author: Mingtzge   File: cityscapes.py    License: MIT License 5 votes vote down vote up
def make_boundaries(label, thickness=None):
        """
        Input is an image label, output is a numpy array mask encoding the boundaries of the objects
        Extract pixels at the true boundary by dilation - erosion of label.
        Don't just pick the void label as it is not exclusive to the boundaries.
        """
        assert(thickness is not None)
        import skimage.morphology as skm
        void = 255
        mask = np.logical_and(label > 0, label != void)[0]
        selem = skm.disk(thickness)
        boundaries = np.logical_xor(skm.dilation(mask, selem),
                                    skm.erosion(mask, selem))
        return boundaries