Python numpy.invert() Examples

The following are 30 code examples for showing how to use numpy.invert(). 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: sato   Author: megagonlabs   File: train_CRF_LC.py    License: Apache License 2.0 6 votes vote down vote up
def eval_batch(table_batch, label_batch, mask_batch):
    # reshap (table_batch * table_size * features)
    for f_g in table_batch:
        table_batch[f_g] = table_batch[f_g].view(batch_size * MAX_COL_COUNT, -1)

    emissions = classifier(table_batch).view(batch_size, MAX_COL_COUNT, -1)
    pred = model.decode(emissions, mask_batch)

    pred = np.concatenate(pred)
    labels = label_batch.view(-1).cpu().numpy()
    masks = mask_batch.view(-1).cpu().numpy()
    invert_masks = np.invert(masks==1)
    
    return pred, ma.array(labels, mask=invert_masks).compressed()

# randomly shuffle the orders of columns in a table batch 
Example 2
Project: recruit   Author: Frank-qlu   File: test_mem_overlap.py    License: Apache License 2.0 6 votes vote down vote up
def test_ufunc_at_manual(self):
        def check(ufunc, a, ind, b=None):
            a0 = a.copy()
            if b is None:
                ufunc.at(a0, ind.copy())
                c1 = a0.copy()
                ufunc.at(a, ind)
                c2 = a.copy()
            else:
                ufunc.at(a0, ind.copy(), b.copy())
                c1 = a0.copy()
                ufunc.at(a, ind, b)
                c2 = a.copy()
            assert_array_equal(c1, c2)

        # Overlap with index
        a = np.arange(10000, dtype=np.int16)
        check(np.invert, a[::-1], a)

        # Overlap with second data array
        a = np.arange(100, dtype=np.int16)
        ind = np.arange(0, 100, 2, dtype=np.int16)
        check(np.add, a, ind, a[25:75]) 
Example 3
Project: deep-smoke-machine   Author: CMU-CREATE-Lab   File: metrics.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def map_charades(y_true, y_pred):
    """ Returns mAP """
    m_aps = []
    n_classes = y_pred.shape[1]
    for oc_i in range(n_classes):
        pred_row = y_pred[:, oc_i]
        sorted_idxs = np.argsort(-pred_row)
        true_row = y_true[:, oc_i]
        tp = true_row[sorted_idxs] == 1
        fp = np.invert(tp)
        n_pos = tp.sum()
        if n_pos < 0.1:
            m_aps.append(float('nan'))
            continue
        f_pcs = np.cumsum(fp)
        t_pcs = np.cumsum(tp)
        prec = t_pcs / (f_pcs + t_pcs).astype(float)
        avg_prec = 0
        for i in range(y_pred.shape[0]):
            if tp[i]:
                avg_prec += prec[i]
        m_aps.append(avg_prec / n_pos.astype(float))
    m_aps = np.array(m_aps)
    m_ap = np.mean(m_aps)
    return m_ap 
Example 4
Project: timeception   Author: noureldien   File: metrics.py    License: GNU General Public License v3.0 6 votes vote down vote up
def map_charades(y_true, y_pred):
    """ Returns mAP """
    m_aps = []
    n_classes = y_pred.shape[1]
    for oc_i in range(n_classes):
        pred_row = y_pred[:, oc_i]
        sorted_idxs = np.argsort(-pred_row)
        true_row = y_true[:, oc_i]
        tp = true_row[sorted_idxs] == 1
        fp = np.invert(tp)
        n_pos = tp.sum()
        if n_pos < 0.1:
            m_aps.append(float('nan'))
            continue
        f_pcs = np.cumsum(fp)
        t_pcs = np.cumsum(tp)
        prec = t_pcs / (f_pcs + t_pcs).astype(float)
        avg_prec = 0
        for i in range(y_pred.shape[0]):
            if tp[i]:
                avg_prec += prec[i]
        m_aps.append(avg_prec / n_pos.astype(float))
    m_aps = np.array(m_aps)
    m_ap = np.mean(m_aps)
    return m_ap 
Example 5
Project: rattlesnake   Author: loehnertz   File: rattlesnake.py    License: MIT License 6 votes vote down vote up
def invert(data):
    """
    Inverts the byte data it received utilizing an XOR operation.

    :param data: A chunk of byte data
    :return inverted: The same size of chunked data inverted bitwise
    """

    # Convert the bytestring into an integer
    intwave = np.fromstring(data, np.int32)
    # Invert the integer
    intwave = np.invert(intwave)
    # Convert the integer back into a bytestring
    inverted = np.frombuffer(intwave, np.byte)
    # Return the inverted audio data
    return inverted 
Example 6
Project: vnpy_crypto   Author: birforce   File: test_mem_overlap.py    License: MIT License 6 votes vote down vote up
def test_ufunc_at_manual(self):
        def check(ufunc, a, ind, b=None):
            a0 = a.copy()
            if b is None:
                ufunc.at(a0, ind.copy())
                c1 = a0.copy()
                ufunc.at(a, ind)
                c2 = a.copy()
            else:
                ufunc.at(a0, ind.copy(), b.copy())
                c1 = a0.copy()
                ufunc.at(a, ind, b)
                c2 = a.copy()
            assert_array_equal(c1, c2)

        # Overlap with index
        a = np.arange(10000, dtype=np.int16)
        check(np.invert, a[::-1], a)

        # Overlap with second data array
        a = np.arange(100, dtype=np.int16)
        ind = np.arange(0, 100, 2, dtype=np.int16)
        check(np.add, a, ind, a[25:75]) 
Example 7
Project: stylecloud   Author: minimaxir   File: stylecloud.py    License: MIT License 6 votes vote down vote up
def gen_mask_array(icon_dir: str, invert_mask: bool, size: int):
    """Generates a numpy array of an icon mask."""
    icon = Image.open(os.path.join(icon_dir, "icon.png"))

    if isinstance(size, int):
        size = (size, size)

    # https://stackoverflow.com/a/2563883
    icon_w, icon_h = icon.size
    icon_mask = Image.new("RGBA", icon.size, (255, 255, 255, 255))
    icon_mask.paste(icon, icon)
    mask = Image.new("RGBA", size, (255, 255, 255, 255))
    mask_w, mask_h = mask.size
    offset = ((mask_w - icon_w) // 2, (mask_h - icon_h) // 2)
    mask.paste(icon_mask, offset)
    mask_array = np.array(mask, dtype="uint8")

    if invert_mask:
        mask_array = np.invert(mask_array)

    return mask_array 
Example 8
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_mem_overlap.py    License: MIT License 6 votes vote down vote up
def test_ufunc_at_manual(self):
        def check(ufunc, a, ind, b=None):
            a0 = a.copy()
            if b is None:
                ufunc.at(a0, ind.copy())
                c1 = a0.copy()
                ufunc.at(a, ind)
                c2 = a.copy()
            else:
                ufunc.at(a0, ind.copy(), b.copy())
                c1 = a0.copy()
                ufunc.at(a, ind, b)
                c2 = a.copy()
            assert_array_equal(c1, c2)

        # Overlap with index
        a = np.arange(10000, dtype=np.int16)
        check(np.invert, a[::-1], a)

        # Overlap with second data array
        a = np.arange(100, dtype=np.int16)
        ind = np.arange(0, 100, 2, dtype=np.int16)
        check(np.add, a, ind, a[25:75]) 
Example 9
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 10
Project: isp   Author: mushfiqulalam   File: utility.py    License: MIT License 6 votes vote down vote up
def degamma_srgb(self, clip_range=[0, 65535]):

        # bring data in range 0 to 1
        data = np.clip(self.data, clip_range[0], clip_range[1])
        data = np.divide(data, clip_range[1])

        data = np.asarray(data)
        mask = data > 0.04045

        # basically, if data[x, y, c] > 0.04045, data[x, y, c] = ( (data[x, y, c] + 0.055) / 1.055 ) ^ 2.4
        #            else, data[x, y, c] = data[x, y, c] / 12.92
        data[mask] += 0.055
        data[mask] /= 1.055
        data[mask] **= 2.4

        data[np.invert(mask)] /= 12.92

        # rescale
        return np.clip(data * clip_range[1], clip_range[0], clip_range[1]) 
Example 11
Project: isp   Author: mushfiqulalam   File: utility.py    License: MIT License 6 votes vote down vote up
def gamma_srgb(self, clip_range=[0, 65535]):

        # bring data in range 0 to 1
        data = np.clip(self.data, clip_range[0], clip_range[1])
        data = np.divide(data, clip_range[1])

        data = np.asarray(data)
        mask = data > 0.0031308

        # basically, if data[x, y, c] > 0.0031308, data[x, y, c] = 1.055 * ( var_R(i, j) ^ ( 1 / 2.4 ) ) - 0.055
        #            else, data[x, y, c] = data[x, y, c] * 12.92
        data[mask] **= 0.4167
        data[mask] *= 1.055
        data[mask] -= 0.055

        data[np.invert(mask)] *= 12.92

        # rescale
        return np.clip(data * clip_range[1], clip_range[0], clip_range[1]) 
Example 12
Project: isp   Author: mushfiqulalam   File: utility.py    License: MIT License 6 votes vote down vote up
def xyz2lab(self, cie_version="1931", illuminant="d65"):

        xyz_reference = helpers().get_xyz_reference(cie_version, illuminant)

        data = self.data
        data[:, :, 0] = data[:, :, 0] / xyz_reference[0]
        data[:, :, 1] = data[:, :, 1] / xyz_reference[1]
        data[:, :, 2] = data[:, :, 2] / xyz_reference[2]

        data = np.asarray(data)

        # if data[x, y, c] > 0.008856, data[x, y, c] = data[x, y, c] ^ (1/3)
        # else, data[x, y, c] = 7.787 * data[x, y, c] + 16/116
        mask = data > 0.008856
        data[mask] **= 1./3.
        data[np.invert(mask)] *= 7.787
        data[np.invert(mask)] += 16./116.

        data = np.float32(data)
        output = np.empty(np.shape(self.data), dtype=np.float32)
        output[:, :, 0] = 116. * data[:, :, 1] - 16.
        output[:, :, 1] = 500. * (data[:, :, 0] - data[:, :, 1])
        output[:, :, 2] = 200. * (data[:, :, 1] - data[:, :, 2])

        return output 
Example 13
Project: isp   Author: mushfiqulalam   File: utility.py    License: MIT License 6 votes vote down vote up
def lab2xyz(self, cie_version="1931", illuminant="d65"):

        output = np.empty(np.shape(self.data), dtype=np.float32)

        output[:, :, 1] = (self.data[:, :, 0] + 16.) / 116.
        output[:, :, 0] = (self.data[:, :, 1] / 500.) + output[:, :, 1]
        output[:, :, 2] = output[:, :, 1] - (self.data[:, :, 2] / 200.)

        # if output[x, y, c] > 0.008856, output[x, y, c] ^ 3
        # else, output[x, y, c] = ( output[x, y, c] - 16/116 ) / 7.787
        output = np.asarray(output)
        mask = output > 0.008856
        output[mask] **= 3.
        output[np.invert(mask)] -= 16/116
        output[np.invert(mask)] /= 7.787

        xyz_reference = helpers().get_xyz_reference(cie_version, illuminant)

        output = np.float32(output)
        output[:, :, 0] = output[:, :, 0] * xyz_reference[0]
        output[:, :, 1] = output[:, :, 1] * xyz_reference[1]
        output[:, :, 2] = output[:, :, 2] * xyz_reference[2]

        return output 
Example 14
Project: srnn   Author: marcofraccaro   File: timit_for_srnn.py    License: MIT License 6 votes vote down vote up
def create_test_set(x_lst):
    n = len(x_lst)
    x_lens = np.array(map(len, x_lst))
    max_len = max(map(len, x_lst)) - 1
    u_out = np.zeros((n, max_len, OUTDIM), dtype='float32')*np.nan
    x_out = np.zeros((n, max_len, OUTDIM), dtype='float32')*np.nan
    for row, vec in enumerate(x_lst):
        l = len(vec) - 1
        u = vec[:-1]  # all but last element
        x = vec[1:]   # all but first element

        x_out[row, :l] = x
        u_out[row, :l] = u

    mask = np.invert(np.isnan(x_out))
    x_out[np.isnan(x_out)] = 0
    u_out[np.isnan(u_out)] = 0
    mask = mask[:, :, 0]
    assert np.all((mask.sum(axis=1)+1) == x_lens)
    return u_out, x_out, mask.astype('float32') 
Example 15
Project: DOTA_models   Author: ringringyi   File: map_utils.py    License: Apache License 2.0 5 votes vote down vote up
def get_map_to_predict(src_locs, src_x_axiss, src_y_axiss, map, map_size,
                       interpolation=cv2.INTER_LINEAR):
  fss = []
  valids = []

  center = (map_size-1.0)/2.0
  dst_theta = np.pi/2.0
  dst_loc = np.array([center, center])
  dst_x_axis = np.array([np.cos(dst_theta), np.sin(dst_theta)])
  dst_y_axis = np.array([np.cos(dst_theta+np.pi/2), np.sin(dst_theta+np.pi/2)])

  def compute_points(center, x_axis, y_axis):
    points = np.zeros((3,2),dtype=np.float32)
    points[0,:] = center
    points[1,:] = center + x_axis
    points[2,:] = center + y_axis
    return points

  dst_points = compute_points(dst_loc, dst_x_axis, dst_y_axis)
  for i in range(src_locs.shape[0]):
    src_loc = src_locs[i,:]
    src_x_axis = src_x_axiss[i,:]
    src_y_axis = src_y_axiss[i,:]
    src_points = compute_points(src_loc, src_x_axis, src_y_axis)
    M = cv2.getAffineTransform(src_points, dst_points)

    fs = cv2.warpAffine(map, M, (map_size, map_size), None, flags=interpolation,
                        borderValue=np.NaN)
    valid = np.invert(np.isnan(fs))
    valids.append(valid)
    fss.append(fs)
  return fss, valids 
Example 16
Project: brainforge   Author: csxeba   File: extreme_learning_machine.py    License: GNU General Public License v3.0 5 votes vote down vote up
def solve_with_covariance_matrices(self, Z, Y):
        A = np.cov(Z.T)
        B = np.cov(Z.T, Y.T)
        W = np.invert(A) @ B
        self.layers[-1].set_weights([W, np.array([0] * self.layers[-1].neurons)], fold=False) 
Example 17
Project: sato   Author: megagonlabs   File: feature_importance.py    License: Apache License 2.0 5 votes vote down vote up
def eval_batch(classifier, model, val_dataset, batch_size, device, n_worker, MAX_COL_COUNT):


    validation = datasets.generate_batches(val_dataset,
                                           batch_size=batch_size,
                                           shuffle=False, 
                                           drop_last=True,
                                           device=device,
                                           n_workers=n_worker)
    y_pred, y_true = [], []
    for table_batch, label_batch, mask_batch in tqdm(validation):
        #pred, labels = eval_batch(table_batch, label_batch, mask_batch)
            
        # reshap (table_batch * table_size * features)
        for f_g in table_batch:
            table_batch[f_g] = table_batch[f_g].view(batch_size * MAX_COL_COUNT, -1)

        emissions = classifier(table_batch).view(batch_size, MAX_COL_COUNT, -1)
        pred = model.decode(emissions, mask_batch)

        pred = np.concatenate(pred)
        labels = label_batch.view(-1).cpu().numpy()
        masks = mask_batch.view(-1).cpu().numpy()
        invert_masks = np.invert(masks==1)
        
        y_pred.extend(pred)
        y_true.extend(ma.array(labels, mask=invert_masks).compressed())

    val_acc = classification_report(y_true, y_pred, output_dict=True)
    return val_acc 
Example 18
Project: recruit   Author: Frank-qlu   File: arraysetops.py    License: Apache License 2.0 5 votes vote down vote up
def _in1d_dispatcher(ar1, ar2, assume_unique=None, invert=None):
    return (ar1, ar2) 
Example 19
Project: recruit   Author: Frank-qlu   File: arraysetops.py    License: Apache License 2.0 5 votes vote down vote up
def _isin_dispatcher(element, test_elements, assume_unique=None, invert=None):
    return (element, test_elements) 
Example 20
Project: recruit   Author: Frank-qlu   File: test_arraysetops.py    License: Apache License 2.0 5 votes vote down vote up
def test_in1d_invert(self):
        "Test in1d's invert parameter"
        # We use two different sizes for the b array here to test the
        # two different paths in in1d().
        for mult in (1, 10):
            a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5])
            b = [2, 3, 4] * mult
            assert_array_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True)) 
Example 21
Project: recruit   Author: Frank-qlu   File: test_extras.py    License: Apache License 2.0 5 votes vote down vote up
def test_in1d_invert(self):
        # Test in1d's invert parameter
        a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1])
        b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1])
        assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))

        a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1])
        b = array([1, 5, -1], mask=[0, 0, 1])
        assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))

        assert_array_equal([], in1d([], [], invert=True)) 
Example 22
Project: recruit   Author: Frank-qlu   File: test_mem_overlap.py    License: Apache License 2.0 5 votes vote down vote up
def test_unary_ufunc_where_same(self):
        # Check behavior at wheremask overlap
        ufunc = np.invert

        def check(a, out, mask):
            c1 = ufunc(a, out=out.copy(), where=mask.copy())
            c2 = ufunc(a, out=out, where=mask)
            assert_array_equal(c1, c2)

        # Check behavior with same input and output arrays
        x = np.arange(100).astype(np.bool_)
        check(x, x, x)
        check(x, x.copy(), x)
        check(x, x, x.copy()) 
Example 23
Project: interactive-deep-colorization   Author: junyanz   File: lab_gamut.py    License: MIT License 5 votes vote down vote up
def update_gamut(self, l_in):
        warnings.filterwarnings("ignore")
        thresh = 1.0
        pts_lab = np.concatenate((l_in + np.zeros((self.A, self.B, 1)), self.pts_full_grid), axis=2)
        self.pts_rgb = (255 * np.clip(color.lab2rgb(pts_lab), 0, 1)).astype('uint8')
        pts_lab_back = color.rgb2lab(self.pts_rgb)
        pts_lab_diff = np.linalg.norm(pts_lab - pts_lab_back, axis=2)

        self.mask = pts_lab_diff < thresh
        mask3 = np.tile(self.mask[..., np.newaxis], [1, 1, 3])
        self.masked_rgb = self.pts_rgb.copy()
        self.masked_rgb[np.invert(mask3)] = 255
        return self.masked_rgb, self.mask 
Example 24
Project: pre-training   Author: hendrycks   File: test.py    License: Apache License 2.0 5 votes vote down vote up
def get_ood_scores(loader, in_dist=False):
    _score = []
    _right_score = []
    _wrong_score = []

    with torch.no_grad():
        for batch_idx, (data, target) in enumerate(loader):
            if batch_idx >= ood_num_examples // args.test_bs and in_dist is False:
                break

            data = data.cuda()

            output = net(data)
            # output = output/torch.norm(output, 2, -1, keepdim=True)
            smax = to_np(F.softmax(output, dim=1))

            if args.use_xent:
                _score.append(to_np((output.mean(1) - torch.logsumexp(output, dim=1))))
            else:
                _score.append(-np.max(smax, axis=1))

            if in_dist:
                preds = np.argmax(smax, axis=1)
                targets = target.numpy().squeeze()
                right_indices = preds == targets
                wrong_indices = np.invert(right_indices)

                if args.use_xent:
                    _right_score.append(to_np((output.mean(1) - torch.logsumexp(output, dim=1)))[right_indices])
                    _wrong_score.append(to_np((output.mean(1) - torch.logsumexp(output, dim=1)))[wrong_indices])
                else:
                    _right_score.append(-np.max(smax[right_indices], axis=1))
                    _wrong_score.append(-np.max(smax[wrong_indices], axis=1))

    if in_dist:
        return concat(_score).copy(), concat(_right_score).copy(), concat(_wrong_score).copy()
    else:
        return concat(_score)[:ood_num_examples].copy() 
Example 25
Project: pre-training   Author: hendrycks   File: test.py    License: Apache License 2.0 5 votes vote down vote up
def get_ood_scores(loader, in_dist=False):
    _score = []
    _right_score = []
    _wrong_score = []

    with torch.no_grad():
        for batch_idx, (data, target) in enumerate(loader):
            if batch_idx >= ood_num_examples // args.test_bs and in_dist is False:
                break

            data = data.cuda()

            output = net(data)
            smax = to_np(F.softmax(output, dim=1))

            if args.use_xent:
                _score.append(to_np((output.mean(1) - torch.logsumexp(output, dim=1))))
            else:
                _score.append(-np.max(smax, axis=1))

            if in_dist:
                preds = np.argmax(smax, axis=1)
                targets = target.numpy().squeeze()
                right_indices = preds == targets
                wrong_indices = np.invert(right_indices)

                if args.use_xent:
                    _right_score.append(to_np((output.mean(1) - torch.logsumexp(output, dim=1)))[right_indices])
                    _wrong_score.append(to_np((output.mean(1) - torch.logsumexp(output, dim=1)))[wrong_indices])
                else:
                    _right_score.append(-np.max(smax[right_indices], axis=1))
                    _wrong_score.append(-np.max(smax[wrong_indices], axis=1))

    if in_dist:
        return concat(_score).copy(), concat(_right_score).copy(), concat(_wrong_score).copy()
    else:
        return concat(_score)[:ood_num_examples].copy() 
Example 26
Project: stock-analysis   Author: stefmolin   File: stock_visualizer.py    License: MIT License 5 votes vote down vote up
def open_to_close(self, figsize=(10, 4)):
        """
        Visualize the daily change from open to close price.

        Parameters:
            - figsize: A tuple of (width, height) for the plot dimensions.

        Returns:
            A matplotlib Figure object.
        """
        is_higher = self.data.close - self.data.open > 0

        fig = plt.figure(figsize=figsize)

        for exclude_mask, color, label in zip(
            (is_higher, np.invert(is_higher)),
            ('g', 'r'),
            ('price rose', 'price fell')
        ):
            plt.fill_between(
                self.data.index,
                self.data.open,
                self.data.close,
                figure=fig,
                where=exclude_mask,
                color=color,
                label=label
            )
        plt.suptitle('Daily price change (open to close)')
        plt.xlabel('date')
        plt.ylabel('price')
        plt.legend()
        plt.close()
        return fig 
Example 27
Project: stock-analysis   Author: stefmolin   File: stock_visualizer.py    License: MIT License 5 votes vote down vote up
def fill_between_other(self, other_df, figsize=(10, 4)):
        """
        Visualize the difference in closing price between assets.

        Parameters:
            - other_df: The dataframe with the other asset's data.
            - figsize: A tuple of (width, height) for the plot dimensions.

        Returns:
            A matplotlib Figure object.
        """
        is_higher = self.data.close - other_df.close > 0

        fig = plt.figure(figsize=figsize)

        for exclude_mask, color, label in zip(
            (is_higher, np.invert(is_higher)),
            ('g', 'r'),
            ('asset is higher', 'asset is lower')
        ):
            plt.fill_between(
                self.data.index,
                self.data.close,
                other_df.close,
                figure=fig,
                where=exclude_mask,
                color=color,
                label=label
            )
        plt.suptitle(
            'Differential between asset closing price (this - other)'
        )
        plt.legend()
        plt.ylabel('price')
        plt.close()
        return fig 
Example 28
Project: lambda-packs   Author: ryfeus   File: arraysetops.py    License: MIT License 5 votes vote down vote up
def setdiff1d(ar1, ar2, assume_unique=False):
    """
    Find the set difference of two arrays.

    Return the sorted, unique values in `ar1` that are not in `ar2`.

    Parameters
    ----------
    ar1 : array_like
        Input array.
    ar2 : array_like
        Input comparison array.
    assume_unique : bool
        If True, the input arrays are both assumed to be unique, which
        can speed up the calculation.  Default is False.

    Returns
    -------
    setdiff1d : ndarray
        Sorted 1D array of values in `ar1` that are not in `ar2`.

    See Also
    --------
    numpy.lib.arraysetops : Module with a number of other functions for
                            performing set operations on arrays.

    Examples
    --------
    >>> a = np.array([1, 2, 3, 2, 4, 1])
    >>> b = np.array([3, 4, 5, 6])
    >>> np.setdiff1d(a, b)
    array([1, 2])

    """
    if assume_unique:
        ar1 = np.asarray(ar1).ravel()
    else:
        ar1 = unique(ar1)
        ar2 = unique(ar2)
    return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)] 
Example 29
Project: lambda-packs   Author: ryfeus   File: arraysetops.py    License: MIT License 5 votes vote down vote up
def setdiff1d(ar1, ar2, assume_unique=False):
    """
    Find the set difference of two arrays.

    Return the sorted, unique values in `ar1` that are not in `ar2`.

    Parameters
    ----------
    ar1 : array_like
        Input array.
    ar2 : array_like
        Input comparison array.
    assume_unique : bool
        If True, the input arrays are both assumed to be unique, which
        can speed up the calculation.  Default is False.

    Returns
    -------
    setdiff1d : ndarray
        Sorted 1D array of values in `ar1` that are not in `ar2`.

    See Also
    --------
    numpy.lib.arraysetops : Module with a number of other functions for
                            performing set operations on arrays.

    Examples
    --------
    >>> a = np.array([1, 2, 3, 2, 4, 1])
    >>> b = np.array([3, 4, 5, 6])
    >>> np.setdiff1d(a, b)
    array([1, 2])

    """
    if assume_unique:
        ar1 = np.asarray(ar1).ravel()
    else:
        ar1 = unique(ar1)
        ar2 = unique(ar2)
    return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)] 
Example 30
Project: lambda-packs   Author: ryfeus   File: test_arraysetops.py    License: MIT License 5 votes vote down vote up
def test_in1d_invert(self):
        "Test in1d's invert parameter"
        # We use two different sizes for the b array here to test the
        # two different paths in in1d().
        for mult in (1, 10):
            a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5])
            b = [2, 3, 4] * mult
            assert_array_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))