Calculate the D^2_min norm of Falk and Langer
495819
def get_D_square_min(atoms_now, atoms_old, i_now, j_now, delta_plus_epsilon=None):
    
    nat = len(atoms_now)
    assert len(atoms_now) == len(atoms_old)

    pos_now = atoms_now.positions
    pos_old = atoms_old.positions

    # Compute current and old distance vectors. Note that current distance
    # vectors cannot be taken from the neighbor calculation, because neighbors
    # are calculated from the sheared cell while these distance need to come
    # from the unsheared cell. Taking the distance from the unsheared cell
    # make periodic boundary conditions (and flipping of cell) a lot easier.
    dr_now = mic(pos_now[i_now] - pos_now[j_now], atoms_now.cell)
    dr_old = mic(pos_old[i_now] - pos_old[j_now], atoms_old.cell)

    # Sanity check: Shape needs to be identical!
    assert dr_now.shape == dr_old.shape

    if delta_plus_epsilon is None:
        # Get minimum strain tensor
        delta_plus_epsilon = get_delta_plus_epsilon(nat, i_now, dr_now, dr_old)

    # Spread epsilon out for each neighbor index
    delta_plus_epsilon_n = delta_plus_epsilon[i_now]

    # Compute D^2_min
    d_sq_n = np.sum(
        (
        dr_now-
        np.sum(delta_plus_epsilon_n.reshape(-1,3,3)*dr_old.reshape(-1,1,3),
               axis=2)
        )**2,
        axis=1)

    # For each atom, sum over all neighbors
    d_sq = np.bincount(i_now, weights=d_sq_n)

    return delta_plus_epsilon, d_sq
148490
def strakos(n, l_min=0.1, l_max=100, rho=0.9):
    
    d = [l_min + (i-1)*1./(n-1)*(l_max-l_min)*(rho**(n-i))
         for i in range(1, n+1)]
    return numpy.diag(d)
73272
def bound_bboxes(bboxes):
    
    group_x0 = min(map(lambda l: l[x0], bboxes))
    group_y0 = min(map(lambda l: l[y0], bboxes))
    group_x1 = max(map(lambda l: l[x1], bboxes))
    group_y1 = max(map(lambda l: l[y1], bboxes))
    return (group_x0, group_y0, group_x1, group_y1)
850026
def yAxisIsMinor(self):
        '''
        
        '''
        return min(self.radius.x, self.radius.y) == self.radius.y
346565
def _get_norm(self):
        '''
        

        '''

        log.info('Computing the PLD normalization...')

        # Loop over all chunks
        mod = [None for b in self.breakpoints]
        for b, brkpt in enumerate(self.breakpoints):

            # Unmasked chunk
            c = self.get_chunk(b)

            # Masked chunk (original mask plus user transit mask)
            inds = np.array(
                list(set(np.concatenate([self.transitmask,
                                         self.recmask]))), dtype=int)
            M = np.delete(np.arange(len(self.time)), inds, axis=0)
            if b > 0:
                m = M[(M > self.breakpoints[b - 1] - self.bpad)
                      & (M <= self.breakpoints[b] + self.bpad)]
            else:
                m = M[M <= self.breakpoints[b] + self.bpad]

            # This block of the masked covariance matrix
            mK = GetCovariance(self.kernel, self.kernel_params,
                               self.time[m], self.fraw_err[m])

            # Get median
            med = np.nanmedian(self.fraw[m])

            # Normalize the flux
            f = self.fraw[m] - med

            # The X^2 matrices
            A = np.zeros((len(m), len(m)))
            B = np.zeros((len(c), len(m)))

            # Loop over all orders
            for n in range(self.pld_order):
                XM = self.X(n, m)
                XC = self.X(n, c)
                A += self.reclam[b][n] * np.dot(XM, XM.T)
                B += self.reclam[b][n] * np.dot(XC, XM.T)
                del XM, XC

            W = np.linalg.solve(mK + A, f)
            mod[b] = np.dot(B, W)
            del A, B, W

        # Join the chunks after applying the correct offset
        if len(mod) > 1:

            # First chunk
            model = mod[0][:-self.bpad]

            # Center chunks
            for m in mod[1:-1]:
                offset = model[-1] - m[self.bpad - 1]
                model = np.concatenate(
                    [model, m[self.bpad:-self.bpad] + offset])

            # Last chunk
            offset = model[-1] - mod[-1][self.bpad - 1]
            model = np.concatenate([model, mod[-1][self.bpad:] + offset])

        else:

            model = mod[0]

        # Subtract the global median
        model -= np.nanmedian(model)

        # Save the norm
        self._norm = self.fraw - model
1164074
def fn_min(self, a, axis=None):
        

        return numpy.nanmin(self._to_ndarray(a), axis=axis)
808732
def normnorm(self):
        

        n = self.norm()
        return V2(-self.y / n, self.x / n)
697645
function constrainedMDSGradient(x, fxprime, distances, constraints) {
        var loss = 0, i;
        for (i = 0; i < fxprime.length; ++i) {
            fxprime[i] = 0;
        }

        for (i = 0; i < distances.length; ++i) {
            var xi = x[2 * i], yi = x[2 * i + 1];
            for (var j = i + 1; j < distances.length; ++j) {
                var xj = x[2 * j], yj = x[2 * j + 1],
                    dij = distances[i][j],
                    constraint = constraints[i][j];

                var squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi),
                    distance$$1 = Math.sqrt(squaredDistance),
                    delta = squaredDistance - dij * dij;

                if (((constraint > 0) && (distance$$1 <= dij)) ||
                    ((constraint < 0) && (distance$$1 >= dij))) {
                    continue;
                }

                loss += 2 * delta * delta;

                fxprime[2*i]     += 4 * delta * (xi - xj);
                fxprime[2*i + 1] += 4 * delta * (yi - yj);

                fxprime[2*j]     += 4 * delta * (xj - xi);
                fxprime[2*j + 1] += 4 * delta * (yj - yi);
            }
        }
        return loss;
    }
4204
def inv_std_norm_cdf(x):
    
    z = 2*x -1
    ln1z2 = np.log(1-z**2)
    a = 8*(np.pi -3)/(3*np.pi*(4-np.pi))
    b = 2/(np.pi * a) + ln1z2/2
    inv_erf = np.sign(z) * np.sqrt( np.sqrt(b**2 - ln1z2/a) - b )
    return np.sqrt(2) * inv_erf
17782
def l2_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None):
  """"""
  if filters is None:
    filters = shape_list(x)[-1]
  with tf.variable_scope(name, default_name="l2_norm", values=[x], reuse=reuse):
    scale = tf.get_variable(
        "l2_norm_scale", [filters], initializer=tf.ones_initializer())
    bias = tf.get_variable(
        "l2_norm_bias", [filters], initializer=tf.zeros_initializer())
    epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]]
    mean = tf.reduce_mean(x, axis=[-1], keepdims=True)
    l2norm = tf.reduce_sum(
        tf.squared_difference(x, mean), axis=[-1], keepdims=True)
    norm_x = (x - mean) * tf.rsqrt(l2norm + epsilon)
    return norm_x * scale + bias
834245
def calculate_squared_differences(image_tile_dict, transformed_array, template, sq_diff_tolerance=0.1):
    
    template_norm_squared = np.sum(template**2)
    image_norms_squared = {(x,y):np.sum(image_tile_dict[(x,y)]**2) for (x,y) in image_tile_dict.keys()}
    match_points = image_tile_dict.keys()
    # for correlation, then need to transofrm back to get correct value for division
    h, w = template.shape
    image_matches_normalised = {match_points[i]:-2*transformed_array[match_points[i][0], match_points[i][1]] + image_norms_squared[match_points[i]] + template_norm_squared for i in range(len(match_points))}
    #print image_matches_normalised
    cutoff = h*w*255**2*sq_diff_tolerance
    normalised_matches = {key:value for key, value in image_matches_normalised.items() if np.round(value, decimals=3) <= cutoff}
    return normalised_matches.keys()
303228
def _norm_default(x):
    """"""
    # Lazy import to improve `import odl` time
    import scipy.linalg

    if _blas_is_applicable(x.data):
        nrm2 = scipy.linalg.blas.get_blas_funcs('nrm2', dtype=x.dtype)
        norm = partial(nrm2, n=native(x.size))
    else:
        norm = np.linalg.norm
    return norm(x.data.ravel())
942549
def d2Sbr_dV2(Cbr, Ybr, V, lam):
    
    nb = len(V)

    diaglam = spdiag(lam)
    diagV = spdiag(V)

    A = Ybr.H * diaglam * Cbr
    B = conj(diagV) * A * diagV
    D = spdiag(mul((A*V), conj(V)))
    E = spdiag(mul((A.T * conj(V)), V))
    F = B + B.T
    G = spdiag(div(matrix(1.0, (nb, 1)), abs(V)))

    Haa = F - D - E
    Hva = 1j * G * (B - B.T - D + E)
    Hav = Hva.T
    Hvv = G * F * G

    return Haa, Hav, Hva, Hvv
996483
def l2_norm(arr):
    
    arr = np.asarray(arr)
    return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))
356004
def min(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent':
        '''
        '''
        return cls._binary_op(x, y, tf.minimum, tf.float32)
271692
def _calc_norm_coeff(h, J, bias_range, quadratic_range, ignored_variables,
                     ignored_interactions):
    """"""

    if ignored_variables is None or ignored_interactions is None:
        raise ValueError('ignored interactions or variables cannot be None')

    def parse_range(r):
        if isinstance(r, Number):
            return -abs(r), abs(r)
        return r

    def min_and_max(iterable):
        if not iterable:
            return 0, 0
        return min(iterable), max(iterable)

    if quadratic_range is None:
        linear_range, quadratic_range = bias_range, bias_range
    else:
        linear_range = bias_range

    lin_range, quad_range = map(parse_range, (linear_range,
                                              quadratic_range))

    lin_min, lin_max = min_and_max([v for k, v in h.items()
                                    if k not in ignored_variables])
    quad_min, quad_max = min_and_max([v for k, v in J.items()
                                      if not check_isin(k,
                                                        ignored_interactions)])

    inv_scalar = max(lin_min / lin_range[0], lin_max / lin_range[1],
                     quad_min / quad_range[0], quad_max / quad_range[1])

    if inv_scalar != 0:
        return 1. / inv_scalar
    else:
        return 1.
345060
def get_DRAT(delta_x_prime, delta_y_prime, max_ptrm_check):
    
    L = numpy.sqrt(delta_x_prime**2 + delta_y_prime**2)
    DRAT = (old_div(max_ptrm_check, L)) * 100
    return DRAT, L