Gradient estimation via Jordan's algorithm (10.1103/PhysRevLett.95.050501).

    :param f_h: Oracle output at perturbation h.
    :param precision: Bit precision of gradient.
    :return: Quil program to estimate gradient of f.
323399
def gradient_program(f_h: float, precision: int) -> Program:
    

    # encode oracle values into phase
    phase_factor = np.exp(1.0j * 2 * np.pi * abs(f_h))
    U = np.array([[phase_factor, 0],
                  [0, phase_factor]])
    p_gradient = phase_estimation(U, precision)

    return p_gradient
888741
def newton_update(x, a, c, step=1.0):
    
    return x - step*np.linalg.inv(hessian(x, a)).dot(gradient(x, a, c))
208437
def get_corrector_f(rinput, meta, ins, datamodel):
    """"""
    from emirdrp.processing.flatfield import FlatFieldCorrector
    flat_info = meta['master_flat']
    with rinput.master_flat.open() as hdul:
        _logger.info('loading intensity flat')
        _logger.debug('flat info: %s', flat_info)
        mflat = hdul[0].data
        # Check NaN and Ceros
        mask1 = mflat < 0
        mask2 = ~numpy.isfinite(mflat)
        if numpy.any(mask1):
            _logger.warning('flat has %d values below 0', mask1.sum())
        if numpy.any(mask2):
            _logger.warning('flat has %d NaN', mask2.sum())
        flat_corrector = FlatFieldCorrector(mflat,
                                            datamodel=datamodel,
                                            calibid=datamodel.get_imgid(hdul))

    return flat_corrector
711534
def gradient(self, mu, dist):
        
        return dist.levels/(mu*(dist.levels - mu))
726356
def doubleprox_dc_simple(x, y, f, phi, g, K, niter, gamma, mu):
    
    for _ in range(niter):
        f.proximal(gamma)(x + gamma * K.adjoint(y) -
                          gamma * phi.gradient(x), out=x)
        g.convex_conj.proximal(mu)(y + mu * K(x), out=y)
768058
def fgrad_y(self, y, return_precalc=False):
        
        d = self.d
        mpsi = self.psi

        # vectorized version
        S = (mpsi[:,1] * (y[:,:,None] + mpsi[:,2])).T
        R = np.tanh(S)
        D = 1 - (R ** 2)

        GRAD = (d + (mpsi[:,0:1][:,:,None] * mpsi[:,1:2][:,:,None] * D).sum(axis=0)).T

        if return_precalc:
            return GRAD, S, R, D

        return GRAD
1004396
def _nfw_func(self, x):
        

        c = 0.000001

        if isinstance(x, np.ndarray):
            x[np.where(x<c)] = c
            nfwvals = np.ones_like(x)
            inds1 = np.where(x < 1)
            inds2 = np.where(x > 1)

            nfwvals[inds1] = (1 - x[inds1] ** 2) ** -.5 * np.arctanh((1 - x[inds1] ** 2) ** .5)
            nfwvals[inds2] = (x[inds2] ** 2 - 1) ** -.5 * np.arctan((x[inds2] ** 2 - 1) ** .5)

            return nfwvals

        elif isinstance(x, float) or isinstance(x, int):
            x = max(x, c)
            if x == 1:
                return 1
            if x < 1:
                return (1 - x ** 2) ** -.5 * np.arctanh((1 - x ** 2) ** .5)
            else:
                return (x ** 2 - 1) ** -.5 * np.arctan((x ** 2 - 1) ** .5)
435777
def gauss_gradient( sigma, direction, max_error = 1.0 / 0x100 )
      filter_type = DFLOAT.align typecode
      gradient =
        Sequence[ *Array.gauss_gradient_filter( sigma, max_error / dimension ) ].
        to_type filter_type
      blur =
        Sequence[ *Array.gauss_blur_filter( sigma, max_error / dimension ) ].
        to_type filter_type
      ( dimension - 1 ).downto( 0 ).inject self do |retval,i|
        filter = i == direction ? gradient : blur
        retval.convolve filter
      end.force
    end
1226512
public static boolean gradient( FunctionNtoS func , FunctionNtoN gradient ,
									double param[] , double tol )
	{
		return gradient(func, gradient, param, tol, Math.sqrt(UtilEjml.EPS));
	}
850086
protected DoubleMatrix1D getGradF0(DoubleMatrix1D X) {
		return F1.make(request.getF0().gradient(X.toArray()));
	}
461528
def _MStep(self, l, K, x, z_h1, pi_h1, p_h1, p_h, delta_i_j_s):
        
        for k in range(K):
            normconst = 0
            if l == 0: # only need to compute pi at first MM iteration
                pi_h1[k] = np.sum(z_h1.T[k]) / len(z_h1)
            for j in range(self.m):
                omega_k_j = EMMMixPLAggregator.omega(k, j, z_h1, x) # numerator
                denom_sum = 0
                for i in range(self.n):
                    sum1 = 0
                    for t in range(len(x[i])):
                        sum2 = 0
                        sum3 = 0
                        for s in range(t, self.m):
                            sum2 += p_h[k][EMMMixPLAggregator.c(x[i], s)]
                        for s in range(t, self.m + 1):
                            sum3 += delta_i_j_s[i][j][s]
                        sum1 += z_h1[i][k] * (sum2 ** -1) * sum3
                    denom_sum += sum1
                p_h1[k][j] = omega_k_j / denom_sum
                normconst += p_h1[k][j]
            for j in range(self.m):
                p_h1[k][j] /= normconst
1229211
def newton(f,c,tol=0.0001,restrict=None):
    
    #print(c)
    if restrict:
        lo,hi = restrict
        if c < lo or c > hi:
            print(c)
            c = random*(hi-lo)+lo

    if fuzzyequals(f(c),0,tol):
        return c
    else:
        try:
            return newton(f,c-f(c)/deriv(f,c,tol),tol,restrict)
        except:
            return None
167702
def _get_gradient_log_pdf(self):
        
        sub_vec = self.variable_assignments - self.model.mean.flatten()
        grad = - np.dot(self.model.precision_matrix, sub_vec)
        log_pdf = 0.5 * np.dot(sub_vec, grad)

        return grad, log_pdf
28396
def atanh(x, context=None):
    
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_atanh,
        (BigFloat._implicit_convert(x),),
        context,
    )
1113352
def gradients_X(self, dL_dK, X, X2, target):
        """"""
        self._K_computations(X, X2)
        arg = self._K_poly_arg
        if X2 is None:
            target += 2*self.weight_variance*self.degree*self.variance*(((X[None,:, :])) *(arg**(self.degree-1))[:, :, None]*dL_dK[:, :, None]).sum(1)
        else:
            target += self.weight_variance*self.degree*self.variance*(((X2[None,:, :])) *(arg**(self.degree-1))[:, :, None]*dL_dK[:, :, None]).sum(1)
143555
def cv_gradient(self,z):
        
        gradient = np.zeros(np.sum(self.approx_param_no))
        z_t = z.T      
        log_q = self.normal_log_q(z.T)
        log_p = self.log_p(z.T)
        grad_log_q = self.grad_log_q(z)
        gradient = grad_log_q*(log_p-log_q)

        alpha0 = alpha_recursion(np.zeros(np.sum(self.approx_param_no)), grad_log_q, gradient, np.sum(self.approx_param_no))           

        vectorized = gradient - ((alpha0/np.var(grad_log_q,axis=1))*grad_log_q.T).T

        return np.mean(vectorized,axis=1)
1196879
def gradients_X(self, dL_dK, X, X2=None):
        
        if use_stationary_cython:
            return self._gradients_X_cython(dL_dK, X, X2)
        else:
            return self._gradients_X_pure(dL_dK, X, X2)