Incomplete method to fit experimental values to a curve. It is very
        hard to get good initial guesses, which are really required for this.
        Differential evolution is promissing. This API is likely to change in
        the future.
197406
def fit(self, x0=None, distribution='lognormal', n=None, **kwargs):
        '''
        '''
        dist = {'lognormal': PSDLognormal, 
                'GGS': PSDGatesGaudinSchuhman, 
                'RR': PSDRosinRammler}[distribution]
        
        if distribution == 'lognormal':
            if x0 is None:
                d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)])
                s = 0.4
                x0 = [d_characteristic, s]
        elif distribution == 'GGS':
            if x0 is None:
                d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)])
                m = 1.5
                x0 = [d_characteristic, m]
        elif distribution == 'RR':
            if x0 is None:
                x0 = [5E-6, 1e-2]
        from scipy.optimize import minimize
        return minimize(self._fit_obj_function, x0, args=(dist, n), **kwargs)
71396
def stdDev(self):
        '''
        
        '''
        if self._corrPsf is None:
            self.psf()
        p = self._corrPsf.copy()
        mn = p.min()
        p[p<0.05*p.max()] = mn
        p-=mn
        p/=p.sum()
        
        x,y = self._psfGridCoords()
        x = x.flatten()
        y = y.flatten()

        guess = (1,1,0)

        param, _ = curve_fit(self._fn, (x,y), p.flatten(), guess)

        self._fitParam = param 
        stdx,stdy =  param[:2]
        self._std = (stdx+stdy) / 2
        
        return self._std
316913
def fit(self, X, truncated=3):
        
        self.n_sample, self.n_var = X.shape
        self.columns = X.columns
        self.tau_mat = X.corr(method='kendall').values
        self.u_matrix = np.empty([self.n_sample, self.n_var])

        self.truncated = truncated
        self.depth = self.n_var - 1
        self.trees = []

        self.unis, self.ppfs = [], []
        for i, col in enumerate(X):
            uni = self.model()
            uni.fit(X[col])
            self.u_matrix[:, i] = uni.cumulative_distribution(X[col])
            self.unis.append(uni)
            self.ppfs.append(uni.percent_point)

        self.train_vine(self.vine_type)
        self.fitted = True
534152
void lpc_to_curve(float[] curve, float[] lpc, float amp){

    for(int i=0; i<ln*2; i++)
      curve[i]=0.0f;

    if(amp==0)
      return;

    for(int i=0; i<m; i++){
      curve[i*2+1]=lpc[i]/(4*amp);
      curve[i*2+2]=-lpc[i]/(4*amp);
    }

    fft.backward(curve);

    {
      int l2=ln*2;
      float unit=(float)(1./amp);
      curve[0]=(float)(1./(curve[0]*2+unit));
      for(int i=1; i<ln; i++){
        float real=(curve[i]+curve[l2-i]);
        float imag=(curve[i]-curve[l2-i]);

        float a=real+unit;
        curve[i]=(float)(1.0/FAST_HYPOT(a, imag));
      }
    }
  }
1201929
def apply_fit(xy,coeffs):
    
    x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1]
    y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1]

    return x_new,y_new
697824
@Override protected void toJavaUnifyPreds(SBPrintStream body) {
    // Preds are filled in from the trees, but need to be adjusted according to
    // the loss function.
    if( _parms._distribution == DistributionFamily.bernoulli
        || _parms._distribution == DistributionFamily.quasibinomial
        || _parms._distribution == DistributionFamily.modified_huber
        ) {
      body.ip("preds[2] = preds[1] + ").p(_output._init_f).p(";").nl();
      body.ip("preds[2] = " + new Distribution(_parms).linkInvString("preds[2]") + ";").nl();
      body.ip("preds[1] = 1.0-preds[2];").nl();
      if (_parms._balance_classes)
        body.ip("hex.genmodel.GenModel.correctProbabilities(preds, PRIOR_CLASS_DISTRIB, MODEL_CLASS_DISTRIB);").nl();
      body.ip("preds[0] = hex.genmodel.GenModel.getPrediction(preds, PRIOR_CLASS_DISTRIB, data, " + defaultThreshold() + ");").nl();
      return;
    }
    if( _output.nclasses() == 1 ) { // Regression
      body.ip("preds[0] += ").p(_output._init_f).p(";").nl();
      body.ip("preds[0] = " + new Distribution(_parms).linkInvString("preds[0]") + ";").nl();
      return;
    }
    if( _output.nclasses()==2 ) { // Kept the initial prediction for binomial
      body.ip("preds[1] += ").p(_output._init_f).p(";").nl();
      body.ip("preds[2] = - preds[1];").nl();
    }
    body.ip("hex.genmodel.GenModel.GBM_rescale(preds);").nl();
    if (_parms._balance_classes)
      body.ip("hex.genmodel.GenModel.correctProbabilities(preds, PRIOR_CLASS_DISTRIB, MODEL_CLASS_DISTRIB);").nl();
    body.ip("preds[0] = hex.genmodel.GenModel.getPrediction(preds, PRIOR_CLASS_DISTRIB, data, " + defaultThreshold() + ");").nl();
  }
335512
def quadratic_2d(data):
    
    arg_data_max = np.argmax(data)
    i, j = np.unravel_index(arg_data_max, data.shape)
    z_ = data[i-1:i+2, j-1:j+2]
    # our quadratic function is defined as
    # f(x, y | a, b, c, d, e, f) := a + b * x + c * y + d * x^2 + e * xy + f * y^2
    # therefore, the best fit coeffiecients are given as
    # note that they are unique and the uncertainty in each of them (#TODO) can be
    # computed following the derivations done by Vakili & Hogg (2016) and
    # Teague & Foreman-Mackey (2018)
    try:
        a = (-z_[0,0] + 2*z_[0,1] - z_[0,2] + 2*z_[1,0] + 5*z_[1,1] + 2*z_[1,2] -
             z_[2,0] + 2*z_[2,1] - z_[2,2]) / 9
        b = (-z_[0,0] - z_[0,1] - z_[0,2] + z_[2,0] + z_[2,1] + z_[2,2]) / 6
        c = (-z_[0,0] + z_[0,2] - z_[1,0] + z_[1,2] - z_[2,0] + z_[2,2]) / 6
        d = (z_[0,0] + z_[0,1] + z_[0,2] - z_[1,0]*2 - z_[1,1]*2 - z_[1,2]*2 +
             z_[2,0] + z_[2,1] + z_[2,2])/6
        e = (z_[0,0] - z_[0,2] - z_[2,0] + z_[2,2]) * .25
        f = (z_[0,0] - 2 * z_[0,1] + z_[0,2] + z_[1,0] - 2 * z_[1,1] + z_[1,2] +
             z_[2,0] - 2 * z_[2,1] + z_[2,2]) / 6
    except IndexError:
        return (i, j)

    # see https://en.wikipedia.org/wiki/Quadratic_function
    det = 4 * d * f - e ** 2
    xm = - (2 * f * b - c * e) / det
    ym = - (2 * d * c - b * e) / det
    return (i+xm, j+ym)
1078254
function xinterp (points) {
        // Scale the data.
        var f = [xscale(config.xlim[1]) - xscale(config.xlim[0]),
                 yscale(config.ylim[1]) - yscale(config.ylim[0])],
            z = [xscale(config.xlim[0]),
                 yscale(config.ylim[0])],
            scaled = points.map(function (p) {
                return [(p[0] - z[0]) / f[0], (p[1] - z[1]) / f[1]];
            });

        // Compute the distance along the path using a map-reduce.
        var dists = scaled.map(function (d, i) {
            if (i == 0) return 0.0;
            var dx = d[0] - scaled[i - 1][0],
                dy = d[1] - scaled[i - 1][1];
            return Math.sqrt(dx * dx + dy * dy);
        }),
            dist = dists.reduce(function (curr, d) { return d + curr; }, 0.0);

        // Choose the number of interpolation points based on this distance.
        var N = Math.round(200 * dist);

        // Re-sample the line.
        var resampled = [];
        dists.map(function (d, i) {
            if (i == 0) return;
            var n = Math.max(3, Math.round(d / dist * N)),
                spline = d3.interpolate(scaled[i - 1][1], scaled[i][1]),
                delta = (scaled[i][0] - scaled[i - 1][0]) / (n - 1);
            for (var j = 0, x = scaled[i - 1][0]; j < n; ++j, x += delta)
                resampled.push([x, spline(j / (n - 1))]);
        });

        // Compute the gradients.
        var gradients = resampled.map(function (a, i, d) {
            if (i == 0) return [d[1][0] - d[0][0], d[1][1] - d[0][1]];
            if (i == resampled.length - 1)
                return [d[i][0] - d[i - 1][0], d[i][1] - d[i - 1][1]];
            return [0.5 * (d[i + 1][0] - d[i - 1][0]),
                    0.5 * (d[i + 1][1] - d[i - 1][1])];
        });

        // Normalize the gradient vectors to be unit vectors.
        gradients = gradients.map(function (d) {
            var len = Math.sqrt(d[0] * d[0] + d[1] * d[1]);
            return [d[0] / len, d[1] / len];
        });

        // Generate some perturbations.
        var perturbations = smooth(resampled.map(d3.random.normal()), 3);

        // Add in the perturbations and re-scale the re-sampled curve.
        var result = resampled.map(function (d, i) {
            var p = perturbations[i],
                g = gradients[i];
            return [(d[0] + config.magnitude * g[1] * p) * f[0] + z[0],
                    (d[1] - config.magnitude * g[0] * p) * f[1] + z[1]];
        });

        return result.join("L");
    }
758850
def fit(self, x, y):
        
        verbose = self.verbose
        # Create temporary files
        data_file = tempfile.NamedTemporaryFile("w+b", delete=False)
        label_file = tempfile.NamedTemporaryFile("w+b", delete=False)

        start = time.time()
        raw_rules = categorical2pysbrl_data(x, y, data_file.name, label_file.name, supp=self.min_support,
                                            zmin=self.min_rule_len, zmax=self.max_rule_len, method=self.fim_method)
        if verbose > 1:
            print("Info: sbrl data files saved to %s and %s temporarily" % (data_file.name, label_file.name))
        data_file.close()
        label_file.close()
        cat_time = time.time() - start
        if verbose:
            print("Info: time for rule mining: %.4fs" % cat_time)
        n_labels = int(np.max(y)) + 1
        start = time.time()
        _model = train_sbrl(data_file.name, label_file.name, self.lambda_, eta=self.eta,
                            max_iters=self.iters, n_chains=self.n_chains, seed=self.seed,
                            alpha=self.alpha, verbose=verbose)
        train_time = time.time() - start
        if verbose:
            print("Info: training time: %.4fs" % train_time)

        # update model parameters
        self._n_classes = n_labels
        self._n_features = x.shape[1]

        # convert the raw parameters to rules
        self.from_raw(_model[0], _model[1], raw_rules)
        self._supports = self.compute_support(x, y)

        # Close the temp files
        os.unlink(data_file.name)
        os.unlink(label_file.name)
974474
function X9ECParameters(curve, g, n, h) {
  this.curve = curve;
  this.g = g;
  this.n = n;
  this.h = h;
}
84243
@Override
   public Solution[] computeOptimizationProblem(SuitableOptions cloudOffers, QualityInformation requirements,
         Topology topology, int numPlansToGenerate) {

      // To findSolution method, we pass an Empty solution instead of a null
      // value to or create a new method that does not consider the current one.
      // This way may help for replanning, when even the first attempt for
      // solution will be based on the current deployment

      cloudOffers.sortDescendingPerformance();
      Solution[] bestSols = super.findInitialRandomSolutions(cloudOffers, numPlansToGenerate, topology);
      super.setFitnessOfSolutions(bestSols, requirements, topology, cloudOffers);
      if (logHill.isDebugEnabled()) {
         logHill.debug(
               "Start checking the presence of quality attached to solutions after the first generation HILLCLIMB");
         super.checkQualityAttachedToSolutions(bestSols);
      }
      super.sortSolutionsByFitnessAndReplaceNaN(bestSols);

      int numItersNoImprovement = 0;
      while (numItersNoImprovement < super.getMaxIterNoImprove()) { // each
                                                                    // iteration
                                                                    // finds a
                                                                    // peak

         Solution currentSol = super.findRandomSolution(cloudOffers, topology);
         currentSol.setSolutionFitness(super.fitness(currentSol, requirements, topology, cloudOffers));

         boolean neighborsImprove = true;
         int pathLengthTraversed = 0;
         while (neighborsImprove) {
            Solution[] candidates = super.findNeighbors(currentSol, cloudOffers, topology);
            if (candidates == null) {
               logHill.debug("New candidates not found");
               neighborsImprove = false;
               pathLengthTraversed = 0;
            } else {
               logHill.debug(
                     "Found " + candidates.length + " neighbors of the solution: Are " + Arrays.toString(candidates));

               super.setFitnessOfSolutions(candidates, requirements, topology, cloudOffers);
               Solution bestCandidate = super.getSolutionWithMaximumFitness(candidates);
               if (bestCandidate.getSolutionFitness() > currentSol.getSolutionFitness()) {
                  currentSol = bestCandidate;
                  pathLengthTraversed++;

                  if (pathLengthTraversed > 100) {
                     logHill.debug("Something weird is happening, iteration: " + pathLengthTraversed
                           + "without finding local maxima: Fitness: " + currentSol.getSolutionFitness() + " Solution: "
                           + currentSol.toString());
                  }

               } else {// there is not any better neighbor. See if this solution
                       // can be included among the set of best solutions
                  neighborsImprove = false;
                  pathLengthTraversed = 0;
               }
            }
         }

         // We have a local maxima in currentSol, let's see if it is better than
         // the previous maxima.
         if (super.solutionShouldBeIncluded(currentSol, bestSols)) {

            logHill.debug("After " + numItersNoImprovement
                  + " iterations we have found a local maxima solution that is going to be included: "
                  + currentSol.toString());

            super.insertOrdered(bestSols, currentSol);
            numItersNoImprovement = 0;

            if (logHill.isDebugEnabled()) {
               logHill.debug(
                     "Start checking the presence of quality attached to solutions after adding a solution in HILLCLIMB");
               super.checkQualityAttachedToSolutions(bestSols);
            }

         } else {

            logHill.debug("After " + numItersNoImprovement
                  + " iterations we have found a local maxima, but it will not be included: " + currentSol.toString());

            numItersNoImprovement++;
         }

      }

      if (logHill.isDebugEnabled()) {
         logHill.debug(
               "Start checking the presence of quality attached to solutions after adding a solution in HILLCLIMB");
         super.checkQualityAttachedToSolutions(bestSols);
      }

      return bestSols;

   }
376957
def build_loss_curve_dt(curve_resolution, insured_losses=False):
    
    lc_list = []
    for lt in sorted(curve_resolution):
        C = curve_resolution[lt]
        pairs = [('losses', (F32, C)), ('poes', (F32, C))]
        lc_dt = numpy.dtype(pairs)
        lc_list.append((str(lt), lc_dt))
    if insured_losses:
        for lt in sorted(curve_resolution):
            C = curve_resolution[lt]
            pairs = [('losses', (F32, C)), ('poes', (F32, C))]
            lc_dt = numpy.dtype(pairs)
            lc_list.append((str(lt) + '_ins', lc_dt))
    loss_curve_dt = numpy.dtype(lc_list) if lc_list else None
    return loss_curve_dt
368104
private static double incompleteFractionSummation(double alpha, double beta, double x) {
        final int MAXITER = 500;
        final double EPS = 3.0E-7;

        double aplusb = alpha + beta;
        double aplus1 = alpha + 1.0;
        double aminus1 = alpha - 1.0;
        double c = 1.0;
        double d = 1.0 - aplusb * x / aplus1;
        if (Math.abs(d) < FPMIN) {
            d = FPMIN;
        }
        d = 1.0 / d;
        double h = d;
        double aa = 0.0;
        double del = 0.0;
        int i = 1, i2 = 0;
        boolean test = true;
        while (test) {
            i2 = 2 * i;
            aa = i * (beta - i) * x / ((aminus1 + i2) * (alpha + i2));
            d = 1.0 + aa * d;
            if (Math.abs(d) < FPMIN) {
                d = FPMIN;
            }
            c = 1.0 + aa / c;
            if (Math.abs(c) < FPMIN) {
                c = FPMIN;
            }
            d = 1.0 / d;
            h *= d * c;
            aa = -(alpha + i) * (aplusb + i) * x / ((alpha + i2) * (aplus1 + i2));
            d = 1.0 + aa * d;
            if (Math.abs(d) < FPMIN) {
                d = FPMIN;
            }
            c = 1.0 + aa / c;
            if (Math.abs(c) < FPMIN) {
                c = FPMIN;
            }
            d = 1.0 / d;
            del = d * c;
            h *= del;
            i++;
            if (Math.abs(del - 1.0) < EPS) {
                test = false;
            }
            if (i > MAXITER) {
                test = false;
                logger.error("Beta.incompleteFractionSummation: Maximum number of iterations wes exceeded");
            }
        }
        return h;
    }
412702
def demo_err():
    
    max_order = 7
    n = 20
    l = 0.25
    fmt1 = '{0: <5s}\t{1: <21s}\t{2: >21s}\t{3: >21s}\t{4: >21s}'
    fmt2 = '{0: <5d}\t{1:20.18f}\t{2: >21.18f}\t{3: >21.18f}\t{4: >21.18f}'
    x = np.cumsum(np.random.rand(n)*l)
    x = np.concatenate((x[::-1]*-1, x))
    lst = []
    derivs = np.zeros(n)
    for order in range(max_order+1):
        print('Order', order)
        for m in range(1+order//2, n+1):
            sub_x = x[n-m:n+m]
            derivs[m-1] = derivatives_at_point_by_finite_diff(
                sub_x, np.exp(sub_x), 0, order)[order]
        print(fmt1.format('m', 'val', 'diff', 'analytical error',
                          'diff/analytical'))
        for m in range(1, n):
            print(fmt2.format(
                (m+1)*2, derivs[m], derivs[m]-derivs[m-1],
                derivs[m]-1, (derivs[m]-derivs[m-1])/(derivs[m]-1)))
        lst.append((derivs[-1], abs(derivs[-1]-derivs[-2])))
    print(np.array(lst))
1150485
def adapt(self, d, x):
        
        # create input matrix and target vector
        self.x_mem[:,1:] = self.x_mem[:,:-1]
        self.x_mem[:,0] = x
        self.d_mem[1:] = self.d_mem[:-1]
        self.d_mem[0] = d
        # estimate output and error
        self.y_mem = np.dot(self.x_mem.T, self.w)
        self.e_mem = self.d_mem - self.y_mem
        # update
        dw_part1 = np.dot(self.x_mem.T, self.x_mem) + self.ide_eps
        dw_part2 = np.linalg.solve(dw_part1, self.ide)
        dw = np.dot(self.x_mem, np.dot(dw_part2, self.e_mem))
        self.w += self.mu * dw
253038
private boolean adjustParam(DenseMatrix64F X, DenseMatrix64F Y,
                                double prevCost) {
        // lambda adjusts how big of a step it takes
        double lambda = initialLambda;
        // the difference between the current and previous cost
        double difference = 1000;

        for( int iter = 0; iter < iter1 && difference > maxDifference ; iter++ ) {
            // compute some variables based on the gradient
            computeDandH(param,X,Y);

            // try various step sizes and see if any of them improve the
            // results over what has already been done
            boolean foundBetter = false;
            for( int i = 0; i < iter2; i++ ) {
                computeA(A,H,lambda);

                if( !solve(A,d,negDelta) ) {
                    return false;
                }
                // compute the candidate parameters
                subtract(param, negDelta, tempParam);

                double cost = cost(tempParam,X,Y);
                if( cost < prevCost ) {
                    // the candidate parameters produced better results so use it
                    foundBetter = true;
                    param.set(tempParam);
                    difference = prevCost - cost;
                    prevCost = cost;
                    lambda /= 10.0;
                } else {
                    lambda *= 10.0;
                }
            }

            // it reached a point where it can't improve so exit
            if( !foundBetter )
                break;
        }
        finalCost = prevCost;
        return true;
    }
91068
def fit_theta(self):
        
        x = range(1, self.point_num + 1)
        y = self.trial_history
        for i in range(NUM_OF_FUNCTIONS):
            model = curve_combination_models[i]
            try:
                # The maximum number of iterations to fit is 100*(N+1), where N is the number of elements in `x0`.
                if model_para_num[model] == 2:
                    a, b = optimize.curve_fit(all_models[model], x, y)[0]
                    model_para[model][0] = a
                    model_para[model][1] = b
                elif model_para_num[model] == 3:
                    a, b, c = optimize.curve_fit(all_models[model], x, y)[0]
                    model_para[model][0] = a
                    model_para[model][1] = b
                    model_para[model][2] = c
                elif model_para_num[model] == 4:
                    a, b, c, d = optimize.curve_fit(all_models[model], x, y)[0]
                    model_para[model][0] = a
                    model_para[model][1] = b
                    model_para[model][2] = c
                    model_para[model][3] = d
            except (RuntimeError, FloatingPointError, OverflowError, ZeroDivisionError):
                # Ignore exceptions caused by numerical calculations
                pass
            except Exception as exception:
                logger.critical("Exceptions in fit_theta:", exception)