Computes the PLD flux normalization array.

        ..note :: `iPLD` model **only**.
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
1154557
def _check_normalization(self):
        
        lastDistance = None
        distance     = None
        for idx in xrange(len(self) - 1):
            distance = self[idx+1][0] - self[idx][0]

            # first run
            if lastDistance is None:
                lastDistance = distance
                continue

            if lastDistance != distance:
                return False

            lastDistance = distance

        return True
551274
function getNormalizeRotations(start, end) {
  // normalize both rotations
  var normStart = normalizeRotation(start)
  var normEnd = normalizeRotation(end)
  // find the shortest arc for each rotation
  Object.keys(start).forEach(function(axis) {
    if (normEnd[axis] - normStart[axis] > 180) normEnd[axis] -= 360
  })
  return { start: normStart, end: normEnd }
}
689739
def _backprop_gradient_pure(dL, L):
    
    dL_dK = np.tril(dL).copy()
    N = L.shape[0]
    for k in range(N - 1, -1, -1):
        for j in range(k + 1, N):
            for i in range(j, N):
                dL_dK[i, k] -= dL_dK[i, j] * L[j, k]
                dL_dK[j, k] -= dL_dK[i, j] * L[i, k]
        for j in range(k + 1, N):
            dL_dK[j, k] /= L[k, k]
            dL_dK[k, k] -= L[j, k] * dL_dK[j, k]
        dL_dK[k, k] /= (2 * L[k, k])
    return dL_dK
1301510
def _extract_array(self, kwargs_list):
        
        if self._solver_type == 'PROFILE_SHEAR':
            e1 = kwargs_list[1]['e1']
            e2 = kwargs_list[1]['e2']
            phi_ext, gamma_ext = param_util.ellipticity2phi_gamma(e1, e2)
        else:
            phi_ext = 0
        lens_model = self._lens_mode_list[0]
        if lens_model in ['SPEP', 'SPEMD', 'SIE', 'NIE']:
            e1 = kwargs_list[0]['e1']
            e2 = kwargs_list[0]['e2']
            center_x = kwargs_list[0]['center_x']
            center_y = kwargs_list[0]['center_y']
            theta_E = kwargs_list[0]['theta_E']
            x = [theta_E, e1, e2, center_x, center_y, phi_ext]
        elif lens_model in ['NFW_ELLIPSE']:
            e1 = kwargs_list[0]['e1']
            e2 = kwargs_list[0]['e2']
            center_x = kwargs_list[0]['center_x']
            center_y = kwargs_list[0]['center_y']
            theta_Rs = kwargs_list[0]['theta_Rs']
            x = [theta_Rs, e1, e2, center_x, center_y, phi_ext]
        elif lens_model in ['SHAPELETS_CART']:
            coeffs = list(kwargs_list[0]['coeffs'])
            [c10, c01, c20, c11, c02] = coeffs[1: 6]
            x = [c10, c01, c20, c11, c02, phi_ext]
        else:
            raise ValueError("Lens model %s not supported for 4-point solver!" % lens_model)
        return x
1332125
def normalization(self):
        
        norm_r = self.normalization_range()        
        return quad(self, norm_r[0]*self._j_ref, norm_r[1]*self._j_ref)[0]
397411
def _parameter_net(self, theta, kernel_shape=9):
        
        with argscope(FullyConnected, nl=tf.nn.leaky_relu):
            net = FullyConnected('fc1', theta, 64)
            net = FullyConnected('fc2', net, 128)

        pred_filter = FullyConnected('fc3', net, kernel_shape ** 2, nl=tf.identity)
        pred_filter = tf.reshape(pred_filter, [BATCH, kernel_shape, kernel_shape, 1], name="pred_filter")
        logger.info('Parameter net output: {}'.format(pred_filter.get_shape().as_list()))
        return pred_filter
61098
def rsdl_rn(self, AX, Y):
        """"""

        # The primal residual normalisation term is
        # max( ||A x^(k)||_2, ||B y^(k)||_2 ) and B = -(I I I ...)^T.
        # The scaling by sqrt(Nb) of the l2 norm of Y accounts for the
        # block replication introduced by multiplication by B
        return max((np.linalg.norm(AX), np.sqrt(self.Nb) * np.linalg.norm(Y)))
428465
public static void computeNormalizationLL(List<List<Point2D_F64>> points, NormalizationPoint2D normalize )
	{
		double meanX = 0;
		double meanY = 0;

		int count = 0;

		for (int i = 0; i < points.size(); i++) {
			List<Point2D_F64> l = points.get(i);
			for (int j = 0; j < l.size(); j++) {
				Point2D_F64 p = l.get(j);
				meanX += p.x;
				meanY += p.y;
			}
			count += l.size();
		}

		meanX /= count;
		meanY /= count;

		double stdX = 0;
		double stdY = 0;

		for (int i = 0; i < points.size(); i++) {
			List<Point2D_F64> l = points.get(i);
			for (int j = 0; j < l.size(); j++) {
				Point2D_F64 p = l.get(j);
				double dx = p.x - meanX;
				double dy = p.y - meanY;
				stdX += dx*dx;
				stdY += dy*dy;
			}
		}

		normalize.meanX = meanX;
		normalize.meanY = meanY;

		normalize.stdX = Math.sqrt(stdX/count);
		normalize.stdY = Math.sqrt(stdY/count);
	}
631635
def _to_array(self, itaper, normalization='4pi', csphase=1):
        
        if self.coeffs is None:
            coeffs = _np.copy(self._taper2coeffs(itaper))
        else:
            if itaper > self.nwinrot - 1:
                raise ValueError('itaper must be less than or equal to ' +
                                 'nwinrot - 1. itaper = {:d}, nwinrot = {:d}'
                                 .format(itaper, self.nwinrot))
            coeffs = _shtools.SHVectorToCilm(self.coeffs[:, itaper])

        if normalization == 'schmidt':
            for l in range(self.lwin + 1):
                coeffs[:, l, :l+1] *= _np.sqrt(2.0 * l + 1.0)
        elif normalization == 'ortho':
            coeffs *= _np.sqrt(4.0 * _np.pi)

        if csphase == -1:
            for m in range(self.lwin + 1):
                if m % 2 == 1:
                    coeffs[:, :, m] = - coeffs[:, :, m]

        return coeffs
1228214
def _run_mplp(self, no_iterations):
        
        for niter in range(no_iterations):
            # We take the clusters in the order they were added in the model and update messages for all factors whose
            # scope is greater than 1
            for factor in self.model.get_factors():
                if len(factor.scope()) > 1:
                    self._update_message(self.cluster_set[frozenset(factor.scope())])
            # Find an integral solution by locally maximizing the single node beliefs
            self._local_decode()
            # If mplp converges to a global/local optima, we break.
            if self._is_converged(self.dual_threshold, self.integrality_gap_threshold) and niter >= 16:
                break
1196483
def npd_to_pmf(nodal_plane_dist, use_default=False):
    
    if isinstance(nodal_plane_dist, PMF):
        # Aready in PMF format - return
        return nodal_plane_dist
    else:
        if use_default:
            return PMF([(1.0, NodalPlane(0.0, 90.0, 0.0))])
        else:
            raise ValueError('Nodal Plane distribution not defined')
887032
def _normalize(mat: np.ndarray):
    """"""
    return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)
84636
def vertex_normals(vertices, faces):
    """"""

    def normalize_v3(arr):
        ''' Normalize a numpy array of 3 component vectors shape=(n,3) '''
        lens = np.sqrt(arr[:, 0]**2 + arr[:, 1]**2 + arr[:, 2]**2)
        arr /= lens[:, np.newaxis]

    tris = vertices[faces]
    facenorms = np.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0])
    normalize_v3(facenorms)

    norm = np.zeros(vertices.shape, dtype=vertices.dtype)
    norm[faces[:, 0]] += facenorms
    norm[faces[:, 1]] += facenorms
    norm[faces[:, 2]] += facenorms
    normalize_v3(norm)
    return norm
341886
def _get_mps_od_net(input_image_shape, batch_size, output_size, anchors,
                    config, weights={}):
    
    network = _MpsGraphAPI(network_id=_MpsGraphNetworkType.kODGraphNet)

    c_in, h_in, w_in =  input_image_shape
    c_out = output_size
    h_out = h_in // 32
    w_out = w_in // 32

    c_view = c_in
    h_view = h_in
    w_view = w_in

    network.init(batch_size, c_in, h_in, w_in, c_out, h_out, w_out,
                 weights=weights, config=config)
    return network
1047550
def _evaluate(self, indices, norm_distances, out=None):
        """"""
        # slice for broadcasting over trailing dimensions in self.values
        vslice = (slice(None),) + (None,) * (self.values.ndim - len(indices))

        if out is None:
            out_shape = out_shape_from_meshgrid(norm_distances)
            out_dtype = self.values.dtype
            out = np.zeros(out_shape, dtype=out_dtype)
        else:
            out[:] = 0.0

        # Weights and indices (per axis)
        low_weights, high_weights, edge_indices = _create_weight_edge_lists(
            indices, norm_distances, self.schemes, self.nn_variants)

        # Iterate over all possible combinations of [i, i+1] for each
        # axis, resulting in a loop of length 2**ndim
        for lo_hi, edge in zip(product(*([['l', 'h']] * len(indices))),
                               product(*edge_indices)):
            weight = 1.0
            # TODO: determine best summation order from array strides
            for lh, w_lo, w_hi in zip(lo_hi, low_weights, high_weights):

                # We don't multiply in-place to exploit the cheap operations
                # in the beginning: sizes grow gradually as following:
                # (n, 1, 1, ...) -> (n, m, 1, ...) -> ...
                # Hence, it is faster to build up the weight array instead
                # of doing full-size operations from the beginning.
                if lh == 'l':
                    weight = weight * w_lo
                else:
                    weight = weight * w_hi
            out += np.asarray(self.values[edge]) * weight[vslice]
        return np.array(out, copy=False, ndmin=1)
978372
def cannon_normalize(spec_raw):
    
    spec = np.array([spec_raw])
    wl = np.arange(0, spec.shape[1])
    w = continuum_normalization.gaussian_weight_matrix(wl, L=50)
    ivar = np.ones(spec.shape)*0.5
    cont = continuum_normalization._find_cont_gaussian_smooth(
            wl, spec, ivar, w)
    norm_flux, norm_ivar = continuum_normalization._cont_norm(
            spec, ivar, cont)
    return norm_flux[0]