SLOPE

Returns the slope of the linear regression line through data points in known_y's and known_x's.

@param    array of mixed        Data Series Y
@param    array of mixed        Data Series X
@return    float
196477
public static function SLOPE($yValues, $xValues)
    {
        if (!self::checkTrendArrays($yValues, $xValues)) {
            return PHPExcel_Calculation_Functions::VALUE();
        }
        $yValueCount = count($yValues);
        $xValueCount = count($xValues);

        if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
            return PHPExcel_Calculation_Functions::NA();
        } elseif ($yValueCount == 1) {
            return PHPExcel_Calculation_Functions::DIV0();
        }

        $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues);
        return $bestFitLinear->getSlope();
    }
142735
public double compute(double[] x, double[] grad) {
    
    double val = 0.0;

    switch (type) {
      case NULL:
        return val;

      case QUADRATIC:
        for (int i = 0; i < x.length; i++) {
          val += x[i] * x[i] / 2.0 / sigmaSq;
          grad[i] += x[i] / sigmaSq;
        }
        return val;

      case HUBER:
        // P.J. Huber. 1973. Robust regression: Asymptotics, conjectures and
        // Monte Carlo. The Annals of Statistics 1: 799-821.
        // See also:
        // P. J. Huber. Robust Statistics. John Wiley & Sons, New York, 1981.
        for (int i = 0; i < x.length; i++) {
          if (x[i] < -epsilon) {
            val += (-x[i] - epsilon / 2.0) / sigmaSq;
            grad[i] += -1.0 / sigmaSq;
          } else if (x[i] < epsilon) {
            val += x[i] * x[i] / 2.0 / epsilon / sigmaSq;
            grad[i] += x[i] / epsilon / sigmaSq;
          } else {
            val += (x[i] - epsilon / 2.0) / sigmaSq;
            grad[i] += 1.0 / sigmaSq;
          }
        }
        return val;

      case QUARTIC:
        for (int i = 0; i < x.length; i++) {
          val += (x[i] * x[i]) * (x[i] * x[i]) / 2.0 / sigmaQu;
          grad[i] += x[i] / sigmaQu;
        }
        return val;

      case ADAPT:
        double[] newX = ArrayMath.pairwiseSubtract(x, means);
        val += otherPrior.compute(newX, grad);
        return val;

      case COSH:
        double norm = ArrayMath.norm_1(x) / sigmaSq;
        double d;
        if (norm > 30.0) {
          val = norm - Math.log(2);
          d = 1.0 / sigmaSq;
        } else {
          val = Math.log(Math.cosh(norm));
          d = (2 * (1 / (Math.exp(-2.0 * norm) + 1)) - 1.0) / sigmaSq;
        }
        for (int i=0; i < x.length; i++) {
          grad[i] += Math.signum(x[i]) * d;
        }
        return val;
      case MULTIPLE_QUADRATIC:
//        for (int i = 0; i < x.length; i++) {
//          val += x[i] * x[i]* 1/2 * regularizationHyperparameters[i];
//          grad[i] += x[i] * regularizationHyperparameters[i];
//        }
        
        for (int i = 0; i < x.length; i++) {
          val += x[i] * x[i] / 2.0 / sigmaSqM[i];
          grad[i] += x[i] / sigmaSqM[i];
        }
        
        
        return val;
      default:
        throw new RuntimeException("LogPrior.valueAt is undefined for prior of type " + this);
    }
  }
548767
def mae(x_values, y_values, drop_missing = True):
    ''''''
    num_points = len(x_values)
    assert(num_points == len(y_values) and num_points > 0)
    return numpy.sum(numpy.apply_along_axis(numpy.abs, 0, numpy.subtract(x_values, y_values))) / float(num_points)
336385
public double max(double[] series) {
    double max = Double.MIN_VALUE;
    for (int i = 0; i < series.length; i++) {
      if (max < series[i]) {
        max = series[i];
      }
    }
    return max;
  }
1235772
public static double uncenteredCorrelation(double[] x, double[] y) {
    final int xdim = x.length, ydim = y.length;
    if(xdim != ydim) {
      throw new IllegalArgumentException("Invalid arguments: number vectors differ in dimensionality.");
    }
    double sumXX = 0., sumYY = 0., sumXY = 0.;
    for(int i = 0; i < xdim; i++) {
      final double xv = x[i], yv = y[i];
      sumXX += xv * xv;
      sumYY += yv * yv;
      sumXY += xv * yv;
    }
    // One or both series were constant:
    if(!(sumXX > 0. && sumYY > 0.)) {
      return (sumXX == sumYY) ? 1. : 0.;
    }
    return sumXY / FastMath.sqrt(sumXX * sumYY);
  }
1010142
function (xData, yData, min, max) {
		var dataLength = xData.length,
			cropStart = 0,
			cropEnd = dataLength,
			cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
			i;

		// iterate up to find slice start
		for (i = 0; i < dataLength; i++) {
			if (xData[i] >= min) {
				cropStart = mathMax(0, i - cropShoulder);
				break;
			}
		}

		// proceed to find slice end
		for (; i < dataLength; i++) {
			if (xData[i] > max) {
				cropEnd = i + cropShoulder;
				break;
			}
		}

		return {
			xData: xData.slice(cropStart, cropEnd),
			yData: yData.slice(cropStart, cropEnd),
			start: cropStart,
			end: cropEnd
		};
	}
338715
def find_truncation_offset
      truncation = self.case.truncate_data
      slope_angle = self.case.truncate_data.slope_angle.abs
      time = self.case.compare_time.to_sym
      ms = analysis[time].elements.reverse
      offset = ms.size - 1
      @slopes = []
      ModuleFunctions.array_window(ms, truncation.window_size) do |data|
        lr = LinearRegression.new(data)
        a = lr.a
        @slopes << [ offset, a ]
        a.abs > slope_angle and break
        offset -= 1
      end
      offset < 0 ? 0 : offset
    end
464326
public double regress(DataPoint dp)
    {
        TreeNodeVisitor node = this;
        while(!node.isLeaf())
        {
            int path = node.getPath(dp);
            if(path < 0 )//missing value case
            {
                double sum = 0;
                double resultSum = 0;
                for(int child = 0; child < childrenCount(); child++)
                {
                    if(node.isPathDisabled(child))
                        continue;
                    double child_result = node.getChild(child).regress(dp);
                    sum += node.getPathWeight(child);
                    resultSum += node.getPathWeight(child)*child_result;
                }
                
                if(sum == 0)//all paths disabled?
                    break;//break out and do local classify
                if(sum < 1.0-1e-5)//re-normalize our result
                    resultSum /= (sum+1e-6);
                
                return resultSum;
            }
            if(node.isPathDisabled(path))//if missing value makes path < 0, return local regression dec
                break;
            node = node.getChild(path);
        }
        return node.localRegress(dp);
    }
349656
def get_slope(self):
        """"""
        # y1 = m*x1 + t
        # y2 = m*x2 + t => y1-y2 = m*(x1-x2) <=> m = (y1-y2)/(x1-x2)
        return ((self.p1.y-self.p2.y) / (self.p1.x-self.p2.x))
772431
def slope_statsample(xx, yy)
      sr = Statsample::Regression.simple(xx.to_scale, yy.to_scale)
      [sr.a, sr.b]
    end
1116065
def _slopes_directions(self, data, dX, dY, method='tarboton'):
        
        # %%
        if method == 'tarboton':
            return self._tarboton_slopes_directions(data, dX, dY)
        elif method == 'central':
            return self._central_slopes_directions(data, dX, dY)
504453
public double d(int[] x, int[] y) {
        if (x.length != y.length)
            throw new IllegalArgumentException(String.format("Arrays have different length: x[%d], y[%d]", x.length, y.length));

        double dist = 0.0;

        if (weight == null) {
            for (int i = 0; i < x.length; i++) {
                double d = Math.abs(x[i] - y[i]);
                dist += Math.pow(d, p);
            }
        } else {
            if (x.length != weight.length)
                throw new IllegalArgumentException(String.format("Input vectors and weight vector have different length: %d, %d", x.length, weight.length));

            for (int i = 0; i < x.length; i++) {
                double d = Math.abs(x[i] - y[i]);
                dist += weight[i] * Math.pow(d, p);
            }
        }

        return Math.pow(dist, 1.0/p);
    }
1358952
static public double xy(double[] x, double[] y) {
    double result = 0.0;
    for (int i = 0; i < x.length; i++) {
      result += (x[i] * y[i]);
    }

    return (result);
  }
574116
private double[] lineSearchBacktrack(Function func, double[] dir, double[] x,
      double[] newX, double[] grad, double lastValue)
      throws MaxEvaluationsExceeded {

    double normGradInDir = ArrayMath.innerProduct(dir, grad);
    say("(" + nf.format(normGradInDir) + ")");
    if (normGradInDir > 0) {
      say("{WARNING--- direction of positive gradient chosen!}");
    }

    // c1 can be anything between 0 and 1, exclusive (usu. 1/10 - 1/2)
    double step, c1;

    // for first few steps, we have less confidence in our initial step-size a
    // so scale back quicker
    if (its <= 2) {
      step = 0.1;
      c1 = 0.1;
    } else {
      step = 1.0;
      c1 = 0.1;
    }

    // should be small e.g. 10^-5 ... 10^-1
    double c = 0.01;

    // double v = func.valueAt(x);
    // c = c * mult(grad, dir);
    c = c * normGradInDir;

    double[] newPoint = new double[3];

    while ((newPoint[f] = func.valueAt((plusAndConstMult(x, dir, step, newX)))) > lastValue
        + c * step) {
      fevals += 1;
      if (newPoint[f] < lastValue) {
        // an improvement, but not good enough... suspicious!
        say("!");
      } else {
        say(".");
      }
      step = c1 * step;
    }

    newPoint[a] = step;
    fevals += 1;
    if (fevals > maxFevals) {
      throw new MaxEvaluationsExceeded(
          " Exceeded during linesearch() Function ");
    }

    return newPoint;
  }
857653
public static double coefficient(double[] x, double[] y) {
    final int xdim = x.length;
    final int ydim = y.length;
    if(xdim != ydim) {
      throw new IllegalArgumentException("Invalid arguments: arrays differ in length.");
    }
    if(xdim == 0) {
      throw new IllegalArgumentException("Empty vector.");
    }
    // Inlined computation of Pearson correlation, to avoid allocating objects!
    // This is a numerically stabilized version, avoiding sum-of-squares.
    double sumXX = 0., sumYY = 0., sumXY = 0.;
    double sumX = x[0], sumY = y[0];
    int i = 1;
    while(i < xdim) {
      final double xv = x[i], yv = y[i];
      // Delta to previous mean
      final double deltaX = xv * i - sumX;
      final double deltaY = yv * i - sumY;
      // Increment count first
      final double oldi = i; // Convert to double!
      ++i;
      final double f = 1. / (i * oldi);
      // Update
      sumXX += f * deltaX * deltaX;
      sumYY += f * deltaY * deltaY;
      // should equal deltaY * neltaX!
      sumXY += f * deltaX * deltaY;
      // Update sums
      sumX += xv;
      sumY += yv;
    }
    // One or both series were constant:
    if(!(sumXX > 0. && sumYY > 0.)) {
      return (sumXX == sumYY) ? 1. : 0.;
    }
    return sumXY / FastMath.sqrt(sumXX * sumYY);
  }
110921
def calc_slopes_directions(self, plotflag=False):
        
        
        # TODO minimum filter behavior with nans?
        
        # fill/interpolate flats first
        if self.fill_flats:
            data = np.ma.filled(self.data.astype('float64'), np.nan)
            filled = data.copy()
            
            edge = np.ones_like(data, bool)
            edge[1:-1, 1:-1] = False

            if self.fill_flats_below_sea: sea_mask = data != 0
            else: sea_mask = data > 0
            flat = (spndi.minimum_filter(data, (3, 3)) >= data) & sea_mask

            flats, n = spndi.label(flat, structure=FLATS_KERNEL3)
            objs = spndi.find_objects(flats)

            for i, _obj in enumerate(objs):
                obj = grow_obj(_obj, data.shape)
                self._fill_flat(data[obj], filled[obj], flats[obj]==i+1, edge[obj])

            self.data = np.ma.masked_array(filled, mask=np.isnan(filled)).astype(self.data.dtype)

        # %% Calculate the slopes and directions based on the 8 sections from
        # Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf
        if self.data.shape[0] <= self.chunk_size_slp_dir and \
                self.data.shape[1] <= self.chunk_size_slp_dir:
            print "starting slope/direction calculation"
            self.mag, self.direction = self._slopes_directions(
                self.data, self.dX, self.dY, 'tarboton')
            # Find the flat regions. This is mostly simple (look for mag < 0),
            # but the downstream pixel at the edge of a flat will have a
            # calcuable angle which will not be accurate. We have to also find
            # these edges and set their magnitude to -1 (that is, the flat_id)

            self.find_flats()
        else:
            self.direction = np.full(self.data.shape, FLAT_ID_INT, 'float64')
            self.mag = np.full(self.data.shape, FLAT_ID_INT, 'float64')
            self.flats = np.zeros(self.data.shape, bool)
            top_edge, bottom_edge = \
                self._get_chunk_edges(self.data.shape[0],
                                      self.chunk_size_slp_dir,
                                      self.chunk_overlap_slp_dir)
            left_edge, right_edge = \
                self._get_chunk_edges(self.data.shape[1],
                                      self.chunk_size_slp_dir,
                                      self.chunk_overlap_slp_dir)
            ovr = self.chunk_overlap_slp_dir
            count = 1
            for te, be in zip(top_edge, bottom_edge):
                for le, re in zip(left_edge, right_edge):
                    print "starting slope/direction calculation for chunk", \
                        count, "[%d:%d, %d:%d]" % (te, be, le, re)
                    count += 1
                    mag, direction = \
                        self._slopes_directions(self.data[te:be, le:re],
                                                self.dX[te:be-1],
                                                self.dY[te:be-1])

                    flats = self._find_flats_edges(self.data[te:be, le:re],
                                                   mag, direction)

                    direction[flats] = FLAT_ID_INT
                    mag[flats] = FLAT_ID_INT
                    self._assign_chunk(self.data, self.mag, mag,
                                       te, be, le, re, ovr)
                    self._assign_chunk(self.data, self.direction, direction,
                                       te, be, le, re, ovr)
                    self._assign_chunk(self.data, self.flats, flats,
                                       te, be, le, re, ovr)

        if plotflag:
            self._plot_debug_slopes_directions()

        gc.collect()  # Just in case
        return self.mag, self.direction
1102310
private static double smoothed(int x, double slope, double intercept) {
        return Math.exp(intercept + slope * Math.log(x));
    }