numpy.ones_like

Here are the examples of the python api numpy.ones_like taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1256 Examples 7

3 Source : augmentation.py
with Apache License 2.0
from 610265158

def Img_dropout(src,max_pattern_ratio=0.05):
    pattern=np.ones_like(src)
    width_ratio = random.uniform(0, max_pattern_ratio)
    height_ratio = random.uniform(0, max_pattern_ratio)
    width=src.shape[1]
    height=src.shape[0]
    block_width=width*width_ratio
    block_height=height*height_ratio
    width_start=int(random.uniform(0,width-block_width))
    width_end=int(width_start+block_width)
    height_start=int(random.uniform(0,height-block_height))
    height_end=int(height_start+block_height)
    pattern[height_start:height_end,width_start:width_end,:]=0
    img=src*pattern
    return img

def Fill_img(img_raw,target_height,target_width,label=None):

3 Source : visual_augmentation.py
with Apache License 2.0
from 610265158

def Img_dropout(src,max_pattern_ratio=0.05):
    pattern=np.ones_like(src)
    width_ratio = random.uniform(0, max_pattern_ratio)
    height_ratio = random.uniform(0, max_pattern_ratio)
    width=src.shape[1]
    height=src.shape[0]
    block_width=width*width_ratio
    block_height=height*height_ratio
    width_start=int(random.uniform(0,width-block_width))
    width_end=int(width_start+block_width)
    height_start=int(random.uniform(0,height-block_height))
    height_end=int(height_start+block_height)
    pattern[height_start:height_end,width_start:width_end,:]=0
    img=src*pattern
    return img



def blur_heatmap(src, ksize=(3, 3)):

3 Source : numpy_routines.py
with GNU General Public License v3.0
from ad12

def ones_like(a, dtype=None, order="K", subok=True, shape=None):
    """See :func:`numpy.ones_like`."""
    vol = np.ones_like(a.A, dtype=dtype, order=order, subok=subok, shape=shape)
    return a._partial_clone(volume=vol)


@implements(np.shares_memory)

3 Source : test_bsplines.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_rndm_unity(self):
        b = _make_random_spline()
        b.c = np.ones_like(b.c)
        xx = np.linspace(b.t[b.k], b.t[-b.k-1], 100)
        assert_allclose(b(xx), 1.)

    def test_vectorization(self):

3 Source : test_bsplines.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_weights(self):
        # weights = 1 is same as None
        x, y, t, k = self.x, self.y, self.t, self.k
        w = np.ones_like(x)

        b = make_lsq_spline(x, y, t, k)
        b_w = make_lsq_spline(x, y, t, k, w=w)

        assert_allclose(b.t, b_w.t, atol=1e-14)
        assert_allclose(b.c, b_w.c, atol=1e-14)
        assert_equal(b.k, b_w.k)

    def test_multiple_rhs(self):

3 Source : minpack.py
with GNU General Public License v3.0
from adityaprakash-bobby

def _initialize_feasible(lb, ub):
    p0 = np.ones_like(lb)
    lb_finite = np.isfinite(lb)
    ub_finite = np.isfinite(ub)

    mask = lb_finite & ub_finite
    p0[mask] = 0.5 * (lb[mask] + ub[mask])

    mask = lb_finite & ~ub_finite
    p0[mask] = lb[mask] + 1

    mask = ~lb_finite & ub_finite
    p0[mask] = ub[mask] - 1

    return p0


def curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False,

3 Source : test_optimize.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_bfgs_nan(self):
        # Test corner case where nan is fed to optimizer.  See gh-2067.
        func = lambda x: x
        fprime = lambda x: np.ones_like(x)
        x0 = [np.nan]
        with np.errstate(over='ignore', invalid='ignore'):
            x = optimize.fmin_bfgs(func, x0, fprime, disp=False)
            assert_(np.isnan(func(x)))

    def test_bfgs_nan_return(self):

3 Source : test_ltisys.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_05(self):
        # Simple integrator: x'(t) = u(t)
        system = ([1.0], [1.0,0.0])
        tout, y = self.func(system)
        expected_y = np.ones_like(tout)
        assert_almost_equal(y, expected_y)

    def test_06(self):

3 Source : test_windows.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_boxcar(self):
        w = windows.get_window('boxcar', 12)
        assert_array_equal(w, np.ones_like(w))

        # window is a tuple of len 1
        w = windows.get_window(('boxcar',), 16)
        assert_array_equal(w, np.ones_like(w))

    def test_cheb_odd(self):

3 Source : _discrete_distns.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def _pmf(self, k, low, high):
        # randint.pmf(k) = 1./(high - low)
        p = np.ones_like(k) / (high - low)
        return np.where((k >= low) & (k   <   high), p, 0.)

    def _cdf(self, x, low, high):

3 Source : imitation_learning.py
with MIT License
from ahq1993

    def _insert_next_state(paths, pad_val=0.0):
        for path in paths:
            if 'observations_next' in path:
                continue
            nobs = path['observations'][1:]
            nact = path['actions'][1:]
            nobs = np.r_[nobs, pad_val*np.expand_dims(np.ones_like(nobs[0]), axis=0)]
            nact = np.r_[nact, pad_val*np.expand_dims(np.ones_like(nact[0]), axis=0)]
            path['observations_next'] = nobs
            path['actions_next'] = nact
        return paths

    @staticmethod

3 Source : evaluate_squad.py
with MIT License
from aimakerspace

def histogram_na_prob(na_probs, qid_list, image_dir, name):
    if not qid_list:
        return
    x = [na_probs[k] for k in qid_list]
    weights = np.ones_like(x) / float(len(x))
    plt.hist(x, weights=weights, bins=20, range=(0.0, 1.0))
    plt.xlabel("Model probability of no-answer")
    plt.ylabel("Proportion of dataset")
    plt.title("Histogram of no-answer probability: %s" % name)
    plt.savefig(os.path.join(image_dir, "na_prob_hist_%s.png" % name))
    plt.clf()


def find_best_thresh(preds, scores, na_probs, qid_to_has_ans):

3 Source : renderer.py
with BSD 3-Clause "New" or "Revised" License
from akanazawa

def append_alpha(imtmp):
    alpha = np.ones_like(imtmp[:, :, 0]).astype(imtmp.dtype)
    if np.issubdtype(imtmp.dtype, np.uint8):
        alpha = alpha * 255
    b_channel, g_channel, r_channel = cv2.split(imtmp)
    im_RGBA = cv2.merge((b_channel, g_channel, r_channel, alpha))
    return im_RGBA


def render_model(verts,

3 Source : clustering_models.py
with Apache License 2.0
from allenai

    def make_mask(self, embedding, objectness, action, threshold):
        margin_threshold = self.config.margin_threshold[threshold > -10000]
        center = embedding[:, action[0], action[1]][:, None, None]
        distances = self.distance_function(embedding, center)
        mask = distances   <   self.config.threshold
        center = embedding[:, mask].mean(axis=1)[:, None, None]
        distances = self.distance_function(embedding, center)
        mask = distances  <  self.config.threshold
        if self.config.threshold != margin_threshold:
            mask2 = distances  <  margin_threshold
        else:
            mask2 = mask
        objectness[mask2] = threshold - 1
        if not self.config.overlapping_objects:
            embedding[:, mask2] = self.config.reset_value * np.ones_like(embedding[:, mask2])
        return mask

    @staticmethod

3 Source : clustering_models.py
with Apache License 2.0
from allenai

    def make_mask(self, embedding, objectness, action, threshold):
        margin_threshold = self.config.margin_threshold[threshold > -10000]
        center = embedding[:, action[0], action[1]][:, None, None]
        distances = self.distance_function(embedding, center)
        mask = distances   <   self.config.threshold
        center = embedding[:, mask].mean(axis=1)[:, None, None]
        distances = self.distance_function(embedding, center)
        mask = distances  <  self.config.threshold
        if self.config.threshold != margin_threshold:
            mask2 = distances  <  margin_threshold
        else:
            mask2 = mask
        objectness[mask2] = threshold - 1
        if not self.config.overlapping_objects:
            embedding[:, mask2] = self.config.reset_value * np.ones_like(embedding[:, mask2])
        return mask

    def compute_mass_logits(self, z, targets):

3 Source : utils_squad_evaluate.py
with MIT License
from allenai

def histogram_na_prob(na_probs, qid_list, image_dir, name):
  if not qid_list:
    return
  x = [na_probs[k] for k in qid_list]
  weights = np.ones_like(x) / float(len(x))
  plt.hist(x, weights=weights, bins=20, range=(0.0, 1.0))
  plt.xlabel('Model probability of no-answer')
  plt.ylabel('Proportion of dataset')
  plt.title('Histogram of no-answer probability: %s' % name)
  plt.savefig(os.path.join(image_dir, 'na_prob_hist_%s.png' % name))
  plt.clf()

def find_best_thresh(preds, scores, na_probs, qid_to_has_ans):

3 Source : data_interface.py
with MIT License
from AllenWLynch

    def project_indices(self, indices, bin_map):

        input_hits = sparse.csc_matrix(
            (np.ones_like(indices), indices, [0, len(indices)]),
        )

        input_hits = self.project_sparse_matrix(input_hits, bin_map, None)

        return input_hits.tocoo().row

    @staticmethod

3 Source : data_interface.py
with MIT License
from AllenWLynch

    def project_sparse_matrix(input_hits, bin_map, num_bins, binarize = False):

        index_converted = input_hits.tocsc()[bin_map[:,0], :].tocoo()

        input_hits = sparse.coo_matrix(
            (index_converted.data, (bin_map[index_converted.row, 1], index_converted.col)), 
            shape = (num_bins, input_hits.shape[1]) if not num_bins is None else None 
        ).tocsr()

        if binarize:
            input_hits.data = np.ones_like(input_hits.data)

        return input_hits


    #___ BINDING FACTOR DATA _____
    def get_factor_hit_path(self, technology, dataset_id):

3 Source : utils.py
with MIT License
from AllenWLynch

def indices_list_to_sparse_array(indices_list, num_bins):
    return sparse.vstack([
        sparse.csr_matrix(
            (np.ones_like(ind), ind, [0, len(ind)]),
            shape = (1, num_bins)
        )
        for ind in indices_list
    ])

class LoadingBar:

3 Source : ridge.py
with MIT License
from alvarobartt

    def _pre_compute(self, X, y, centered_kernel=True):
        # even if X is very sparse, K is usually very dense
        K = safe_sparse_dot(X, X.T, dense_output=True)
        # the following emulates an additional constant regressor
        # corresponding to fit_intercept=True
        # but this is done only when the features have been centered
        if centered_kernel:
            K += np.ones_like(K)
        v, Q = linalg.eigh(K)
        QT_y = np.dot(Q.T, y)
        return v, Q, QT_y

    def _decomp_diag(self, v_prime, Q):

3 Source : test_split.py
with MIT License
from alvarobartt

def test_stratified_shuffle_split_overlap_train_test_bug():
    # See https://github.com/scikit-learn/scikit-learn/issues/6121 for
    # the original bug report
    y = [0, 1, 2, 3] * 3 + [4, 5] * 5
    X = np.ones_like(y)

    sss = StratifiedShuffleSplit(n_splits=1,
                                 test_size=0.5, random_state=0)

    train, test = next(sss.split(X=X, y=y))

    # no overlap
    assert_array_equal(np.intersect1d(train, test), [])

    # complete partition
    assert_array_equal(np.union1d(train, test), np.arange(len(y)))


def test_stratified_shuffle_split_multilabel():

3 Source : align.py
with GNU General Public License v3.0
from andrewdcampbell

def warp_im(im, M, dshape, prev):
    output_im = cv2.warpAffine(
        im, M, (dshape[1], dshape[0]),
        flags=cv2.INTER_CUBIC,
        borderMode=cv2.BORDER_REFLECT_101 if prev is not None else cv2.BORDER_CONSTANT,
    )

    if prev is not None:
        # overlay the image on the previous images
        mask = cv2.warpAffine(
            np.ones_like(im, dtype='float32'), M, 
            (dshape[1], dshape[0]), flags=cv2.INTER_CUBIC,
        )
        output_im = mask * output_im + (1-mask) * prev

    return output_im


def align_images(impath1, impath2, border, prev=None):

3 Source : 01_single_plasma_simulation.py
with GNU General Public License v3.0
from AngelFP

def density_profile(z):
    """ Define plasma density as a function of ``z``. """
    # Allocate relative density array.
    n = np.ones_like(z)
    # Add upramp.
    n = np.where(
        z   <   ramp_up, 1 / (1 + (ramp_up - z) / ramp_decay_length)**2, n)
    # Add downramp.
    n = np.where(
        (z > ramp_up + plateau) & (z  < = ramp_up + plateau + ramp_down),
        1 / (1 + (z - ramp_up - plateau) / ramp_decay_length)**2, n)
    # Make zero after downramp.
    n = np.where( z > ramp_up + plateau + ramp_down, 0, n)
    # Return absolute density.
    return n * np0


# Plot density profile.
z_prof = np.linspace(0, L_plasma, 1000)

3 Source : plasma_stage.py
with GNU General Public License v3.0
from AngelFP

    def _get_density_profile(self, density):
        """ Get density profile function """
        if isinstance(density, float):
            def uniform_density(z):
                return np.ones_like(z) * density
            return uniform_density
        elif callable(density):
            return density
        else:
            raise ValueError(
                'Type {} not supported for density.'.format(type(density)))

    def _get_wakefield(self, model, model_params):

3 Source : wakefield.py
with GNU General Public License v3.0
from AngelFP

    def _get_parabolic_coefficient_fn(self, parabolic_coefficient):
        """ Get parabolic_coefficient profile function """
        if isinstance(parabolic_coefficient, float):
            def uniform_parabolic_coefficient(z):
                return np.ones_like(z) * parabolic_coefficient
            return uniform_parabolic_coefficient
        elif callable(parabolic_coefficient):
            return parabolic_coefficient
        else:
            raise ValueError(
                'Type {} not supported for parabolic_coefficient.'.format(
                    type(parabolic_coefficient)))

3 Source : mkqa_eval_util.py
with Apache License 2.0
from apple

def plot_na_prob_histogram(no_answer_probs, qid_list, outdir, name):
    x = [no_answer_probs[k] for k in qid_list]
    weights = np.ones_like(x) / float(len(x))
    plt.hist(x, weights=weights, bins=20, range=(0.0, 1.0))
    plt.xlabel("No Answer Probability")
    plt.ylabel("Proportion of Dataset")
    plt.title(f"No Answer Probability Histogram: {name}")
    plt.savefig(os.path.join(outdir, f"na_prob_histogram_{name}.png"))
    plt.clf()

3 Source : core.py
with GNU General Public License v3.0
from arcadelab

def _to_homogeneous(x: np.ndarray, is_point: bool = True) -> np.ndarray:
    """Convert an array to homogeneous points or vectors.

    Args:
        x (np.ndarray): array with objects on the last axis.
        is_point (bool, optional): if True, the array represents a point, otherwise it represents a vector. Defaults to True.

    Returns:
        np.ndarray: array containing the homogeneous point/vector(s).
    """
    if is_point:
        return np.concatenate([x, np.ones_like(x[..., -1:])], axis=-1)
    else:
        return np.concatenate([x, np.zeros_like(x[..., -1:])], axis=-1)


def _from_homogeneous(x: np.ndarray, is_point: bool = True) -> np.ndarray:

3 Source : pseudotime_velocity.py
with BSD 3-Clause "New" or "Revised" License
from aristoteleo

def laplacian(E, convention="graph"):
    if issparse(E):
        A = E.copy()
        A.data = np.ones_like(A.data)
        L = diags(A.sum(0).A1, 0) - A
    else:
        A = np.sign(E)
        L = np.diag(np.sum(A, 0)) - A
    if convention == "diffusion":
        L = -L

    L = csr_matrix(L)

    return L


def pseudotime_transition(E, pseudotime, laplace_weight=10):

3 Source : convert_to_bvh.py
with MIT License
from Arthur151

  def __init__(self, global_trans, axis_angles):
    """Initialize with joints location and axis angle."""
    self.global_trans = global_trans
    self.axis_angles = axis_angles.reshape([-1, 3])
    self.euler_angles = np.ones_like(self.axis_angles)
    for index, axis_angle in enumerate(self.axis_angles):
      self.euler_angles[index] = aa2rotmat(axis_angle)


class BVHWriter(object):

3 Source : util.py
with MIT License
from Arthur151

def get_kp2d_on_org_img(kp2d, offset):
    assert kp2d.shape[1]>=2, print('Espected shape of kp2d is Kx2, while get {}'.formt(kp2d.shape))
    if torch.is_tensor(offset):
        offset = offset.detach().cpu().numpy()
    pad_size_h,pad_size_w, lt_h,rb_h,lt_w,rb_w,offset_h,size_h,offset_w,size_w,length = offset
    kp2d_onorg = np.ones_like(kp2d)
    kp2d_onorg[:,0] = (kp2d[:,0]+1)/2 * pad_size_w - offset_w+lt_w
    kp2d_onorg[:,1] = (kp2d[:,1]+1)/2 * pad_size_h - offset_h+lt_w
    return kp2d_onorg
    

class AverageMeter_Dict(object):

3 Source : data_processing.py
with BSD 3-Clause "New" or "Revised" License
from ash-shar

def load_train_data(csv_file, n_items):
	tp = pd.read_csv(csv_file)
	n_users = tp['uid'].max() + 1

	rows, cols = tp['uid'], tp['sid']

	
	data = sparse.csr_matrix((np.ones_like(rows),
							 (rows, cols)), dtype='float32',
							 shape=(n_users, n_items))

	return data, tp['uid'].min()


def load_tr_te_data(csv_file_tr, csv_file_te, n_items):

3 Source : functional.py
with Apache License 2.0
from ashutosh1919

def refresh_valid(img, coor, force=False):
    if coor.shape[1] == 2:
        if force:
            coor = np.concatenate([coor, np.ones_like(coor[:, 0])], axis=1)
        else:
            return img, coor
    assert coor.shape[1] == 3, 'Support only (x, y, valid) or (x, y) typed coordinates.'
    out = []
    for x, y, v in coor:
        valid = (v == 1) and (x >= 0) and (x   <   img.width) and (y >= 0) and (y  <  img.height)
        if valid:
            out.append((x, y, v))
        else:
            out.append((0., 0., 0.))
    return img, np.array(out, dtype='float32')


def rotate(img, coor, angle, resample, crop_, expand, center=None, translate=None):

3 Source : normal.py
with GNU Affero General Public License v3.0
from astrogilda

    def metric(self):
        I = np.c_[
            2 * np.ones_like(self.var),
            np.zeros_like(self.var),
            np.zeros_like(self.var),
            self.var,
        ]
        I = I.reshape((self.var.shape[0], 2, 2))
        I = 1 / (2 * np.sqrt(np.pi)) * I
        return I


class Normal(RegressionDistn):

3 Source : normal.py
with GNU Affero General Public License v3.0
from astrogilda

    def metric(self):
        I = np.c_[2 * np.ones_like(self.var)]
        I = I.reshape((self.var.shape[0], 1, 1))
        I = 1 / (2 * np.sqrt(np.pi)) * I
        return I


class NormalFixedVar(Normal):

3 Source : normal.py
with GNU Affero General Public License v3.0
from astrogilda

    def __init__(self, params):
        self.loc = params[0]
        self.var = np.ones_like(self.loc)
        self.scale = np.ones_like(self.loc)
        self.shape = self.loc.shape
        self.dist = dist(loc=self.loc, scale=self.scale)

    def fit(Y):

3 Source : relative_humidity.py
with MIT License
from atmtools

    def __call__(self, atmosphere, **kwargs):
        if self._rh_cache is None:
            p = atmosphere["plev"]
            self._rh_cache = self.rh_surface * np.ones_like(p)

        return self._rh_cache


class Manabe67(RelativeHumidityModel):

3 Source : recipe.py
with Apache License 2.0
from awslabs

    def __call__(self, x, length, *args, **kwargs):
        other = resolve(self.other, x, length, **kwargs)
        return np.ones_like(other)


class LinearTrend(Lifted):

3 Source : test_pyfield.py
with MIT License
from bdshieh

def test_calc_scat(field, linear_array, points):
    amplitudes = np.ones_like(points)
    scat, t0 = field.calc_scat(linear_array, linear_array, points, amplitudes)
    assert scat.ndim == 1
    assert t0 > 0


def calc_scat_all(linear_array, points):

3 Source : test_pyfield.py
with MIT License
from bdshieh

def calc_scat_multi(linear_array, points):
    amplitudes = np.ones_like(points)
    scat, t0 = field.calc_scat_multi(linear_array, linear_array, points,
                                     amplitudes)
    assert scat.shape[1] == 10
    assert t0 > 0


def calc_h(linear_array, points):

3 Source : tools.py
with MIT License
from benmaier

def get_sparse_matrix_from_rows_and_cols(N, rows, cols):

    A = sprs.csc_matrix((np.ones_like(rows),(rows,cols)), shape=(N,N),dtype=float)

    return A

def get_random_walk_eigenvalue_gap(A,maxiter=10000):

3 Source : experiment_utils.py
with MIT License
from benrhodes26

def jensen_shannon_fn(e1, e2, logz):
    m1 = np.stack([e1, np.ones_like(e1)*logz], axis=1)
    m2 = np.stack([e2, np.ones_like(e2)*logz], axis=1)

    term1 = np.log(2) + np.mean(e1) - np.mean(logsumexp(m1, axis=1))
    term2 = np.log(2) + logz - np.mean(logsumexp(m2, axis=1))

    return 0.5 * (term1 + term2)


def plot_chains_main(chains, name, save_dir, dp, config, vminmax = (0, 1), max_n_states=10):

3 Source : simulations.py
with BSD 3-Clause "New" or "Revised" License
from biocore

def Heteroscedastic(X_noise, intensity):
    """ non-uniform normally dist. noise """
    err = intensity * np.ones_like(X_noise)
    i = rand.randint(0, err.shape[0], 5000)
    j = rand.randint(0, err.shape[1], 5000)
    err[i, j] = intensity
    X_noise = abs(rand.normal(X_noise, err))

    return X_noise


def Subsample(X_noise, spar, num_samples):

3 Source : patch_samplers.py
with MIT License
from biomedia-mira

    def __call__(self, image, target, mask=None):
        # ensure that the mask has at least one point
        mask = np.ones_like(target) if mask is None else mask
        if np.sum(mask) == 0:
            raise ValueError('Empty sampling mask')

        center = self.sample_patch_center(target, mask)
        image_patch, target_patch, mask_patch = self.get_patches(center, image, target, mask)
        for augmentation in self.augmentation:
            image_patch, target_patch, mask_patch = augmentation(image_patch, target_patch, mask_patch)
        return image_patch, target_patch, mask_patch


class StochasticPatchSampler(PatchSampler):

3 Source : test_link.py
with MIT License
from birforce

def test_invlogit_stability():
    z = [1123.4910007309222, 1483.952316802719, 1344.86033748641,
         706.339159002542, 1167.9986375146532, 663.8345826933115,
         1496.3691686913917, 1563.0763842182257, 1587.4309332296314,
         697.1173174974248, 1333.7256198289665, 1388.7667560586933,
         819.7605431778434, 1479.9204150555015, 1078.5642245164856,
         480.10338454985896, 1112.691659145772, 534.1061908007274,
         918.2011296406588, 1280.8808515887802, 758.3890788775948,
         673.503699841035, 1556.7043357878208, 819.5269028006679,
         1262.5711060356423, 1098.7271535253608, 1482.811928490097,
         796.198809756532, 893.7946963941745, 470.3304989319786,
         1427.77079226037, 1365.2050226373822, 1492.4193201661922,
         871.9922191949931, 768.4735925445908, 732.9222777654679,
         812.2382651982667, 495.06449978924525]
    zinv = logit.inverse(z)
    assert_equal(zinv, np.ones_like(z))

if __name__=="__main__":

3 Source : test_regression.py
with MIT License
from birforce

    def test_qr_normalized_cov_params(self):
        # todo: need assert_close
        assert_almost_equal(np.ones_like(self.res1.normalized_cov_params),
                            self.res1.normalized_cov_params /
                            self.res_qr.normalized_cov_params, 5)

    def test_missing(self):

3 Source : densityorthopoly.py
with MIT License
from birforce

    def __call__(self, x):
        if self.order == 0:
            return np.ones_like(x)
        else:
            return sqr2 * np.cos(np.pi * self.order * x)

class F2Poly(object):

3 Source : densityorthopoly.py
with MIT License
from birforce

    def __call__(self, x):
        if self.order == 0:
            return np.ones_like(x) / np.sqrt(np.pi)
        else:
            return sqr2 * np.cos(self.order * x) / np.sqrt(np.pi)

class ChebyTPoly(object):

3 Source : densityorthopoly.py
with MIT License
from birforce

    def __call__(self, x):
        if self.order == 0:
            return np.ones_like(x) / (1-x**2)**(1/4.) /np.sqrt(np.pi)

        else:
            return self.poly(x) / (1-x**2)**(1/4.) /np.sqrt(np.pi) *np.sqrt(2)



from scipy.misc import factorial

3 Source : test_arima.py
with MIT License
from birforce

    def test_information_criteria(self):
        # This test is invalid since the ICs differ due to df_model differences
        # between OLS and ARIMA
        res = self.arma_00_res
        y = self.y
        ols_res = OLS(y, np.ones_like(y)).fit(disp=-1)
        ols_ic = np.array([ols_res.aic, ols_res.bic])
        arma_ic = np.array([res.aic, res.bic])
        assert_almost_equal(ols_ic, arma_ic, DECIMAL_4)

    def test_arma_00_nc(self):

3 Source : test_arima.py
with MIT License
from birforce

    def test_css(self):
        arma = ARMA(self.y, order=(0, 0))
        fit = arma.fit(method='css', disp=-1)
        predictions = fit.predict()
        assert_almost_equal(self.y.mean() * np.ones_like(predictions), predictions)

    def test_arima(self):

See More Examples