Ar function used to estimate mean and variance.

@param survivalFunction
@param r
@return
501076
private static double ar(AssociativeArray2D survivalFunction, int r) {
        if(survivalFunction.isEmpty()) {
            throw new IllegalArgumentException("The provided collection can't be empty.");
        }
        
        AssociativeArray2D survivalFunctionCopy = survivalFunction;
        
        //check if last one is censored and close it
        Map.Entry<Object, AssociativeArray> lastRowEntry = null;
        for(Map.Entry<Object, AssociativeArray> currentRowEntry : survivalFunction.entrySet()) {
            lastRowEntry=currentRowEntry;
        }
        
        if(lastRowEntry==null) {
            throw new IllegalArgumentException("The last observation can't be censored.");
        }
        
        AssociativeArray lastRow = lastRowEntry.getValue();
        if(lastRow.get("Sti")==null) { //if the last record is censored we must close the line
            survivalFunctionCopy = survivalFunction.copy(); //copy internalData to avoid modifying the internalData
            
            Object lastRowKey = lastRowEntry.getKey();
            AssociativeArray lastRowValue = survivalFunctionCopy.remove(lastRowKey);
            
            String str = lastRowKey.toString();
            Double newLastRowKey = Double.valueOf(str.substring(0,str.length()-CENSORED_NUMBER_POSTFIX.length())); //remove censored postfix
            newLastRowKey = Math.floor(newLastRowKey)+1;
            
            survivalFunctionCopy.put2d(newLastRowKey, "i", lastRowValue.get("i"));
            survivalFunctionCopy.put2d(newLastRowKey, "r", lastRowValue.get("i"));
            survivalFunctionCopy.put2d(newLastRowKey, "Sti", 0.0);
            survivalFunctionCopy.put2d(newLastRowKey, "varianceSti", 0.0);
        }
        

        double Ar=0.0;
        double StiPrevious=1;
        double tiPrevious=0;
        for(Map.Entry<Object, AssociativeArray> entry : survivalFunctionCopy.entrySet()) {
            Object ti = entry.getKey();
            AssociativeArray row = entry.getValue();
            

            Double Sti = row.getDouble("Sti");
            
            if(Sti==null) {
                continue; //skip censored internalData
            }
            
            double tiCurrent = Double.valueOf(ti.toString());
            if(row.getDouble("r")>r) {
                Ar+=StiPrevious*(tiCurrent-tiPrevious);
            }
            StiPrevious=Sti;
            tiPrevious=tiCurrent;
        }

        return Ar;
    }
516738
function rpois(lambda) {
      var mode;

      mode = { val: Math.floor(lambda) };
      mode.prob = Math.exp(-lambda + mode.val * Math.log(lambda) -
         lgamma(mode.val + 1));

      return inverseCDF(
         function getMode() { return mode; },
         function updateLeft() {
            if (this.val === 0) { return false; }
            this.prob *= this.val / lambda;
            this.val -= 1;
            return true;
         },
         function updateRight() {
            this.val += 1;
            this.prob *= lambda / this.val;
            return true;
         }
      );
   }
1262870
public static ArrayList<String> addInteraction(String variable1, String variable2, ArrayList<SurvivalInfo> survivalInfoList) {
		ArrayList<String> variables = new ArrayList<String>();
		variables.add(variable1);
		variables.add(variable2);
		variables.add(variable1 + ":" + variable2);
		for (SurvivalInfo si : survivalInfoList) {
			Double value1 = si.getVariable(variable1);
			Double value2 = si.getVariable(variable2);
			Double value3 = value1 * value2;
			si.addContinuousVariable(variable1 + ":" + variable2, value3);
		}
		return variables;
	}
377347
def get_R_corr2(x_avg, y_avg, x_segment, y_segment): #
    
    xd = x_segment - x_avg # detrend x_segment
    yd = y_segment - y_avg # detrend y_segment
    if sum(xd**2) * sum(yd**2) == 0: # prevent divide by zero error
        return float('nan')
    rcorr = old_div(sum((xd * yd))**2, (sum(xd**2) * sum(yd**2)))
    return rcorr
1293581
def _func(a, p, r, v):
    
    # eq. 2.3
    f = a[0]*math.log(r-1.) + \
        a[1]*math.log(r-1.)**2 + \
        a[2]*math.log(r-1.)**3 + \
        a[3]*math.log(r-1.)**4

    # eq. 2.7 and 2.8 corrections
    if r == 3:
        f += -0.002 / (1. + 12. * _phi(p)**2)

        if v <= 4.364:
            f += 1./517. - 1./(312.*(v,1e38)[np.isinf(v)])
        else:
            f += 1./(191.*(v,1e38)[np.isinf(v)])

    return -f
1056618
def _compute_mean(self, C, mag, rrup):
        
        # see table 3, page 14
        R1 = 90.
        R2 = 150.
        # see equation 19, page 32
        m_ref = mag - 4
        r1 = R1 + C['c8'] * m_ref
        r2 = R2 + C['c11'] * m_ref
        assert r1 > 0
        assert r2 > 0
        g0 = np.log10(
            np.sqrt(np.minimum(rrup, r1) ** 2 + (1 + C['c5'] * m_ref) ** 2)
        )
        g1 = np.maximum(np.log10(rrup / r1), 0)
        g2 = np.maximum(np.log10(rrup / r2), 0)

        mean = (C['c0'] + C['c1'] * m_ref + C['c2'] * m_ref ** 2 +
                (C['c3'] + C['c4'] * m_ref) * g0 +
                (C['c6'] + C['c7'] * m_ref) * g1 +
                (C['c9'] + C['c10'] * m_ref) * g2)

        # convert from log10 to ln and units from cm/s2 to g
        mean = np.log((10 ** mean) * 1e-2 / g)

        return mean
277094
@Override
  public MarginalSet computeMarginals(FactorGraph factorGraph) {
    VariableNumMap variables = factorGraph.getVariables();
    Preconditions.checkArgument(variables.getDiscreteVariables().size() == variables.size());

    // Initialize the mean field distribution to the uniform distribution over
    // all variables.
    long curTime = System.currentTimeMillis();
    System.out.println("init: " + (System.currentTimeMillis() - curTime)); 
    int numVars = variables.size();
    IndexedList<Integer> variableNums = new IndexedList<Integer>(variables.getVariableNums());
    List<DiscreteVariable> variableTypes = variables.getDiscreteVariables();
    List<Tensor> variableMarginals = Lists.newArrayListWithCapacity(numVars);
    for (int i = 0; i < numVars; i++) {
      int[] dimensions = new int[] { variableNums.get(i) };
      int[] sizes = new int[] { variableTypes.get(i).numValues() };
      variableMarginals.add(DenseTensor.constant(dimensions, sizes, 1.0 / sizes[0]));
    }
    System.out.println("logweights: "  + (System.currentTimeMillis() - curTime));
    // Get the log weights for each factor in the original factor graph.
    List<Tensor> logWeights = Lists.newArrayList();
    for (Factor factor : factorGraph.getFactors()) {
      logWeights.add(factor.coerceToDiscrete().getWeights().elementwiseLog());
    }
    System.out.println("done: " +  + (System.currentTimeMillis() - curTime)); 

    double updateL2 = Double.POSITIVE_INFINITY;
    int numIterations = 0;
    while (updateL2 > CONVERGENCE_DELTA) {
      updateL2 = 0.0;
      for (int i = 0; i < numVars; i++) {
        int curVarNum = variableNums.get(i);
        // Accumulate the messages from each factor containing this variable.
        DenseTensorBuilder messageAccumulator = new DenseTensorBuilder(
            variableMarginals.get(i).getDimensionNumbers(), variableMarginals.get(i).getDimensionSizes());
        Set<Integer> factorIndexes = factorGraph.getFactorsWithVariable(curVarNum);
        // System.out.println(i + " " + curVarNum + ": " + factorIndexes);
        for (int factorIndex : factorIndexes) {
          Tensor factorMessage = getFactorMessage(curVarNum, logWeights.get(factorIndex),
              variableMarginals, variableNums);
          // System.out.println("factorMessage: " +
          // Arrays.toString(factorMessage.getDimensionNumbers()));
          // System.out.println("messageAccumulator: " +
          // Arrays.toString(messageAccumulator.getDimensionNumbers()));
          messageAccumulator.increment(factorMessage);
        }

        // Update the marginal based on the inbound messages, setting
        // marginal equal to the logistic function of the accumulated messages.
        messageAccumulator.exp();
        double normalizingConstant = messageAccumulator.getTrace();
        messageAccumulator.multiply(1.0 / normalizingConstant);
        Tensor newMarginal = messageAccumulator.buildNoCopy();

        // Compute the convergence criteria
        Tensor delta = newMarginal.elementwiseAddition(
            variableMarginals.get(i).elementwiseProduct(SparseTensor.getScalarConstant(-1.0)));
        updateL2 += delta.getL2Norm();

        variableMarginals.set(i, newMarginal);
      }
      numIterations++;
      System.out.println("update L2: " + updateL2);
    }
    
    System.out.println("iterations:" + numIterations);
    // Format output as factors.
    List<Factor> marginals = Lists.newArrayList();
    for (int i = 0; i < numVars; i++) {
      marginals.add(new TableFactor(variables.intersection(variableNums.get(i)),
          variableMarginals.get(i)));
    }

    System.out.println("really done: " +  + (System.currentTimeMillis() - curTime));
    return new FactorMarginalSet(marginals, 1.0, factorGraph.getConditionedVariables(),
        factorGraph.getConditionedValues());
  }
10341
function rnbinom(size, prob) {
      var rg;

      if (size <= 0 || prob <= 0 || prob > 1) {
         return function() { return NaN; };
      }
      if (prob === 1) { return function() { return 0; }; }
      rg = rgamma(size, (1 - prob) / prob);
      return function() { return rpois(rg())(); };
   }
738455
def cont_r(self, percent=0.9, N=None):
		""""""

		if not hasattr(self, 'F'):
			self.fs_r(N=self.rank)  # generate F
		return apply_along_axis(lambda _: _/self.L[:N], 1,
			   apply_along_axis(lambda _: _*self.r, 0, self.F[:, :N]**2))
781402
def confidence_interval_survival_function_(self):
        
        return self._compute_confidence_bounds_of_transform(self._survival_function, self.alpha, self._ci_labels)
229964
def rbf(ra, coeff, mag):
    
    a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd, a2ce = gc(coeff, mag)
    term1 = a1ca + a1cb * mag + a1cc * np.log(ra + a1cd*np.exp(a1ce*mag))
    term2 = a2ca + a2cb * mag
    term3 = a2cd*np.exp(a2ce*mag)
    return np.exp((term1 - term2) / a2cc) - term3
1003215
def lspearmanr(x,y):
    
    TINY = 1e-30
    if len(x) != len(y):
        raise ValueError('Input values not paired in spearmanr.  Aborting.')
    n = len(x)
    rankx = rankdata(x)
    ranky = rankdata(y)
    dsq = sumdiffsquared(rankx,ranky)
    rs = 1 - 6*dsq / float(n*(n**2-1))
    t = rs * math.sqrt((n-2) / ((rs+1.0)*(1.0-rs)))
    df = n-2
    probrs = betai(0.5*df,0.5,df/(df+t*t))  # t already a float
# probability values for rs are from part 2 of the spearman function in
# Numerical Recipies, p.510.  They are close to tables, but not exact. (?)
    return rs, probrs
1222562
function variance (arr) {
    let mean = avg(arr);
    return avg(arr.map(num => (num - mean) ** 2));
}
684077
def r_squared(model, fit_result, data):
    
    # First filter out the dependent vars
    y_is = [data[var] for var in model if var in data]
    x_is = [value for var, value in data.items() if var.name in model.__signature__.parameters]
    y_bars = [np.mean(y_i) if y_i is not None else None for y_i in y_is]
    f_is = model(*x_is, **fit_result.params)
    SS_res = np.sum([np.sum((y_i - f_i)**2) for y_i, f_i in zip(y_is, f_is) if y_i is not None])
    SS_tot = np.sum([np.sum((y_i - y_bar)**2) for y_i, y_bar in zip(y_is, y_bars) if y_i is not None])
    return 1 - SS_res/SS_tot
951207
def plot_survival_function(self, **kwargs):
        """"""
        return _plot_estimate(
            self,
            estimate=self.survival_function_,
            confidence_intervals=self.confidence_interval_survival_function_,
            **kwargs
        )
740103
public SDVariable rarg() {
        val args = args();
        if(args == null || args.length != 2)
            throw new ND4JIllegalStateException("In order to use this function, the number of arguments for this function must be 2.");
        return args[1];
    }
494509
def rarlognormal(a, sigma, rho, size=1):
    
    """
    f = utils.ar1
    if np.isscalar(a):
        r = f(rho, 0, sigma, size)
    else:
        n = len(a)
        r = [f(rho, 0, sigma, n) for i in range(size)]
        if size == 1:
            r = r[0]
    return a * np.exp(r)