Implementaton of :func:`scipy.linalg.cho_factor` using
    a function supported in cupy.
189945
def _cho_factor(A, lower=True, check_finite=True):
    """"""

    return cp.linalg.cholesky(A), True
148616
def _compute_f2_factor(self, rrup):
        
        # f2 = max(log10(rrup/R2),0)
        f2 = np.log10(rrup / self.COEFFS_IMT_INDEPENDENT['R2'])
        f2[f2 < 0] = 0.0

        return f2
891587
def __computeDecomp(self):
        
        primeNumbers = [getPrimeFactors(d) for d in self.globalDims]

        ns = [len(pns) for pns in primeNumbers]
        validDecomps = []
        self.validProcs = []
        for it in MultiArrayIter(ns):
            inds = it.getIndices()
            decomp = [primeNumbers[d][inds[d]] for d in range(self.ndims)]
            self.validProcs.append(reduce(operator.mul, decomp, 1))
            if reduce(operator.mul, decomp, 1) == self.nprocs:
                validDecomps.append(decomp)

        # sort and remove duplicates
        self.validProcs.sort()
        vprocs = []
        for vp in self.validProcs:
            if len(vprocs) == 0 or (len(vprocs) >= 1 and vp != vprocs[-1]):
                vprocs.append(vp)
        self.validProcs = vprocs

        if len(validDecomps) == 0:
            # no solution
            return

        # find the optimal decomp among all valid decomps
        minCost = float('inf')
        bestDecomp = validDecomps[0]
        for decomp in validDecomps:
            sizes = [self.globalDims[d]//decomp[d] for d in range(self.ndims)]
            volume = reduce(operator.mul, sizes, 1)
            surface = 0
            for d in range(self.ndims):
                surface += 2*reduce(operator.mul, sizes[:d], 1) * \
                    reduce(operator.mul, sizes[d+1:], 1)
            cost = surface / float(volume)
            if cost < minCost:
                bestDecomp = decomp
                minCost = cost
        self.decomp = bestDecomp

        # ok, we have a valid decomp, now build the sub-domain iterator
        self.mit = MultiArrayIter(self.decomp, rowMajor=self.rowMajor)

        # fill in the proc to index set map
        procId = 0
        self.proc2IndexSet = {}
        numCellsPerProc = [self.globalDims[d]//self.decomp[d]
                           for d in range(self.ndims)]
        for it in self.mit:
            nps = it.getIndices()
            self.proc2IndexSet[procId] = []
            for d in range(self.ndims):
                sbeg = nps[d]*numCellsPerProc[d]
                send = (nps[d] + 1)*numCellsPerProc[d]
                self.proc2IndexSet[procId].append(slice(sbeg, send))
            procId += 1
1160323
def ts_func(f):
    
    def wrap_func(df, *args):
        # TODO: should vectorize to apply over all columns?
        return Chromatogram(f(df.values, *args), df.index, df.columns)
    return wrap_func
867662
def sg_sugar_func(func):
    

    """
    @wraps(func)
    def wrapper(tensor, **kwargs):
        # call sugar function
        out = func(tensor, tf.sg_opt(kwargs))
        # save node info for reuse
        out._sugar = tf.sg_opt(func=func, arg=tf.sg_opt(kwargs)+sg_get_context(), prev=tensor)
        # inject reuse function
        out.sg_reuse = types.MethodType(sg_reuse, out)
        return out

    return wrapper
51537
def _make_ufunc(func, index=Ellipsis, **kwargs):  # noqa: D202
    """"""

    def _ufunc(ary):
        target = np.empty(ary.shape[:-2])
        for idx in np.ndindex(target.shape):
            target[idx] = np.asarray(func(ary[idx].ravel(), **kwargs))[index]
        return target

    return _ufunc
1004899
def factorize_groupby_cols(self, groupby_cols):
        
        # first check if the factorized arrays already exist
        # unless we need to refresh the cache
        factor_list = []
        values_list = []

        # factorize the groupby columns
        for col in groupby_cols:

            if self.auto_cache or self.cache_valid(col):
                # create factorization cache if needed
                if not self.cache_valid(col):
                    self.cache_factor([col])

                col_rootdir = self[col].rootdir
                col_factor_rootdir = col_rootdir + '.factor'
                col_values_rootdir = col_rootdir + '.values'
                col_carray_factor = \
                    bcolz.carray(rootdir=col_factor_rootdir, mode='r')
                col_carray_values = \
                    bcolz.carray(rootdir=col_values_rootdir, mode='r')
            else:
                col_carray_factor, values = ctable_ext.factorize(self[col])
                col_carray_values = \
                    bcolz.carray(np.fromiter(values.values(), dtype=self[col].dtype))

            factor_list.append(col_carray_factor)
            values_list.append(col_carray_values)

        return factor_list, values_list
703558
def smpar(C):
    """"""
    m2 = C['m2'].real
    Lambda = C['Lambda'].real
    v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) /
         (sqrt(2) * Lambda**(5 / 2)) * C['phi'])
    GF = 1 / (sqrt(2) * v**2)  # TODO
    Mh2 = 2 * m2 * (1 - m2 / Lambda * (3 * C['phi'] - 4 * Lambda * C['phiBox'] +
                                       Lambda * C['phiD']))
    eps = C['phiWB'] * (v**2)
    gb = (C['g'] / (1 - C['phiW'] * (v**2))).real
    gpb = (C['gp'] / (1 - C['phiB'] * (v**2))).real
    gsb = (C['gs'] / (1 - C['phiG'] * (v**2))).real
    MW = gb * v / 2
    ZG0 = 1 + C['phiD'] * (v**2) / 4
    MZ = (sqrt(gb**2 + gpb**2) / 2 * v
          * (1 + eps * gb * gpb / (gb**2 + gpb**2)) * ZG0)
    Mnup = -(v**2) * C['llphiphi']
    Mep = v / sqrt(2) * (C['Ge'] - C['ephi'] * (v**2) / 2)
    Mup = v / sqrt(2) * (C['Gu'] - C['uphi'] * (v**2) / 2)
    Mdp = v / sqrt(2) * (C['Gd'] - C['dphi'] * (v**2) / 2)
    UeL, Me, UeR = ckmutil.diag.msvd(Mep)
    UuL, Mu, UuR = ckmutil.diag.msvd(Mup)
    UdL, Md, UdR = ckmutil.diag.msvd(Mdp)
    UnuL, Mnu = ckmutil.diag.mtakfac(Mnup)
    eb = (gb * gpb / sqrt(gb**2 + gpb**2) *
          (1 - eps * gb * gpb / (gb**2 + gpb**2)))
    K = UuL.conj().T @ UdL
    # U = UeL.conj().T @ UnuL
    sm = {}
    sm['GF'] = GF
    sm['alpha_e'] = eb**2 / (4 * pi)
    sm['alpha_s'] = gsb**2 / (4 * pi)
    sm['Vub'] = abs(K[0, 2])
    sm['Vcb'] = abs(K[1, 2])
    sm['Vus'] = abs(K[0, 1])
    sm['delta'] = phase(-K[0, 0] * K[0, 2].conj()
                        / (K[1, 0] * K[1, 2].conj()))
    # sm['U'] = Uu
    sm['m_W'] = MW
    sm['m_Z'] = MZ
    sm['m_h'] = sqrt(abs(Mh2))
    sm['m_u'] = Mu[0]
    sm['m_c'] = Mu[1]
    sm['m_t'] = Mu[2]
    sm['m_d'] = Md[0]
    sm['m_s'] = Md[1]
    sm['m_b'] = Md[2]
    sm['m_e'] = Me[0]
    sm['m_mu'] = Me[1]
    sm['m_tau'] = Me[2]
    return  {k: v.real for k, v in sm.items()}
112842
def _get_pga_bc(self, f0, f1, f2, SC, mag, rrup, vs30, scale_fac):
        
        pga_bc = np.zeros_like(vs30)
        self._compute_mean(self.COEFFS_BC[PGA()], f0, f1, f2, SC, mag,
                           rrup, vs30 < 2000.0, pga_bc, scale_fac)

        return (10 ** pga_bc) * 1e-2 / g
719291
def create_group_column_factor(self, factor_list, groupby_cols, cache=False):
        
        if not self.rootdir:
            # in-memory scenario
            input_rootdir = None
            col_rootdir = None
            col_factor_rootdir = None
            col_values_rootdir = None
            col_factor_rootdir_tmp = None
            col_values_rootdir_tmp = None
        else:
            # temporary
            input_rootdir = tempfile.mkdtemp(prefix='bcolz-')
            col_factor_rootdir_tmp = tempfile.mkdtemp(prefix='bcolz-')
            col_values_rootdir_tmp = tempfile.mkdtemp(prefix='bcolz-')

        # create combination of groupby columns
        group_array = bcolz.zeros(0, dtype=np.int64, expectedlen=len(self), rootdir=input_rootdir, mode='w')
        factor_table = bcolz.ctable(factor_list, names=groupby_cols)
        ctable_iter = factor_table.iter(outcols=groupby_cols, out_flavor=tuple)
        ctable_ext.create_group_index(ctable_iter, len(groupby_cols), group_array)

        # now factorize the results
        carray_factor = \
            bcolz.carray([], dtype='int64', expectedlen=self.size, rootdir=col_factor_rootdir_tmp, mode='w')
        carray_factor, values = ctable_ext.factorize(group_array, labels=carray_factor)
        carray_factor.flush()

        carray_values = \
            bcolz.carray(np.fromiter(values.values(), dtype=np.int64), rootdir=col_values_rootdir_tmp, mode='w')
        carray_values.flush()

        del group_array
        if cache:
            # clean up the temporary file
            rm_file_or_dir(input_rootdir, ignore_errors=True)

        if cache:
            # official end destination
            col_rootdir = os.path.join(self.rootdir, self.create_group_base_name(groupby_cols))
            col_factor_rootdir = col_rootdir + '.factor'
            col_values_rootdir = col_rootdir + '.values'
            lock_file = col_rootdir + '.lock'

            # only works for linux
            if not os.path.exists(lock_file):
                uid = str(uuid.uuid4())
                try:
                    with open(lock_file, 'a+') as fn:
                        fn.write(uid + '\n')
                    with open(lock_file, 'r') as fn:
                        temp = fn.read().splitlines()
                    if temp[0] == uid:
                        lock = True
                    else:
                        lock = False
                    del temp
                except:
                    lock = False
            else:
                lock = False

            if lock:
                rm_file_or_dir(col_factor_rootdir, ignore_errors=False)
                shutil.move(col_factor_rootdir_tmp, col_factor_rootdir)
                carray_factor = bcolz.carray(rootdir=col_factor_rootdir, mode='r')

                rm_file_or_dir(col_values_rootdir, ignore_errors=False)
                shutil.move(col_values_rootdir_tmp, col_values_rootdir)
                carray_values = bcolz.carray(rootdir=col_values_rootdir, mode='r')
            else:
                # another process has a lock, we will work with our current files and clean up later
                self._dir_clean_list.append(col_factor_rootdir)
                self._dir_clean_list.append(col_values_rootdir)

        return carray_factor, carray_values
47410
def factor_kkt(U_S, R, d):
    
    nineq = R.size(0)
    U_S[-nineq:, -nineq:] = torch.potrf(R + torch.diag(1 / d.cpu()).type_as(d))
1326400
def from_dict(cls, copula_dict):
        """"""
        instance = cls()

        instance.fitted = copula_dict['fitted']
        instance.constant_value = copula_dict['constant_value']

        if instance.fitted and not instance.constant_value:
            instance.model = scipy.stats.gaussian_kde([-1, 0, 0])

            for key in ['dataset', 'covariance', 'inv_cov']:
                copula_dict[key] = np.array(copula_dict[key])

            attributes = ['d', 'n', 'dataset', 'covariance', 'factor', 'inv_cov']
            for name in attributes:
                setattr(instance.model, name, copula_dict[name])

        return instance
535421
def _get_YYTfactor(self, Y):
        
        N, D = Y.shape
        if (N>=D):
            return Y.view(np.ndarray)
        else:
            return jitchol(tdot(Y))
385455
def fit(self, X, y=None, categorical=None):
        
        if categorical is not None:
            assert isinstance(categorical, (int, list, tuple)), "The 'categorical' \
                argument needs to be an integer with the index of the categorical \
                column in your data, or a list or tuple of several of them, \
                but it is a {}.".format(type(categorical))

        X = pandas_to_numpy(X)

        random_state = check_random_state(self.random_state)
        # If self.gamma is None, gamma will be automatically determined from
        # the data. The function below returns its value.
        self._enc_cluster_centroids, self._enc_map, self.labels_, self.cost_,\
            self.n_iter_, self.gamma = k_prototypes(X,
                                                    categorical,
                                                    self.n_clusters,
                                                    self.max_iter,
                                                    self.num_dissim,
                                                    self.cat_dissim,
                                                    self.gamma,
                                                    self.init,
                                                    self.n_init,
                                                    self.verbose,
                                                    random_state,
                                                    self.n_jobs)
        return self
1037165
def cumprod(self, axis=0, *args, **kwargs):
        
        nv.validate_groupby_func('cumprod', args, kwargs,
                                 ['numeric_only', 'skipna'])
        if axis != 0:
            return self.apply(lambda x: x.cumprod(axis=axis, **kwargs))

        return self._cython_transform('cumprod', **kwargs)
212354
def _get_factors(self, element):
        
        xdim, ydim = element.dimensions()[:2]
        xvals, yvals = [element.dimension_values(i, False)
                        for i in range(2)]
        coords = tuple([v if vals.dtype.kind in 'SU' else dim.pprint_value(v) for v in vals]
                  for dim, vals in [(xdim, xvals), (ydim, yvals)])
        if self.invert_axes: coords = coords[::-1]
        return coords
866793
def _compute_f1_factor(self, rrup):
        
        # f1 = min(log10(rrup),log10(R1))
        f1 = np.log10(rrup)
        logR1 = np.log10(self.COEFFS_IMT_INDEPENDENT['R1'])
        f1[f1 > logR1] = logR1

        return f1