bool LeastSquares1D::SolveUnweighted() { assert(x.n == y.n); assert(x.n >= 2); Real sxx,syy,sxy; Real xmean = Mean(x); Real ymean = Mean(y); sxx = syy = sxy = 0; for(int i=0;i<x.n;i++) { sxx += Sqr(x(i) - xmean); syy += Sqr(y(i) - ymean); sxy += (x(i) - xmean)*(y(i) - ymean); } if(sxx == 0) { //vertical line! b = xmean; a = Inf; stda = stdb = 0; corrCoeff = 1; return true; } a = sxy / sxx; b = ymean - b*xmean; if(x.n == 2) { stda = stdb = 0; corrCoeff = 1; return true; } Real s = Sqrt((syy - b*sxy)/(x.n-2)); stda = s / Sqrt(sxx); stdb = s*Sqrt(One/(Real)x.n + Sqr(xmean)/sxx); return true; }
void MassUmbalances(OpenSMOKE_KPP_ReactorNetwork& network) { BzzVector umbalances(network.NumberOfReactors()); for(int k=1;k<=network.NumberOfReactors();k++) umbalances[k] = fabs(network.reactors(k).MassUmbalance()); BzzVector massFlowIn(network.NumberOfReactors()); for(int k=1;k<=network.NumberOfReactors();k++) massFlowIn[k] = fabs(network.reactors(k).MassFlowIn()); cout << endl; cout << "// *********************************************************** // " << endl; cout << "// UMBALANCE ANALYSIS // " << endl; cout << "// *********************************************************** // " << endl; cout << setw(20) << left << "Max umbalance:"; cout << setw(16) << left << umbalances.Max(); cout << endl; cout << setw(20) << left << "Mean umbalance:"; cout << setw(16) << left << Mean(umbalances); cout << endl; cout << setw(20) << left << "Max in flow:"; cout << setw(16) << left << massFlowIn.Max(); cout << endl; cout << setw(20) << left << "Min in flow:"; cout << setw(16) << left << massFlowIn.Min(); cout << endl; cout << setw(20) << left << "Mean in flow:"; cout << setw(16) << left << Mean(massFlowIn); cout << endl; }
bool LeastSquares1D::SolvePerpendicular() { //minimize sum_i { (yi - a*xi - b)^2 / (1+b^2) } assert(x.n == y.n); assert(x.n >= 2); Real sxx,syy,sxy; Real xmean = Mean(x); Real ymean = Mean(y); sxx = syy = sxy = 0; for(int i=0;i<x.n;i++) { sxx += Sqr(x(i) - xmean); syy += Sqr(y(i) - ymean); sxy += (x(i) - xmean)*(y(i) - ymean); } Real den = (x.n*xmean*ymean - dot(x,y)); if(FuzzyZero(den)) { cerr<<"Warning, denominator is close to zero"<<endl; } Real B = (syy - sxx) / den; a = -B + Sqrt(Sqr(B)+1); b = ymean - xmean*b; cerr<<"Warning, don't know how to calculate std errors for perpendicular least-squares"<<endl; stda = stdb = 0; corrCoeff = 1; return true; }
void FilterStream(FILTER *FIL, FILE *OUT){ int64_t n = 1; ENTP val = Mean(FIL, 0); int region = val < FIL->threshold ? LOW_REGION : HIGH_REGION, cmp = 0; uint64_t initPosition = 1; uint64_t lastPosition = n; for(n = 1 ; n < FIL->nEntries ; ++n){ if(n % FIL->drop == 0){ if((val = Mean(FIL, n)) >= FIL->threshold){ if(region == LOW_REGION){ region = HIGH_REGION; cmp = SelfSimilarity(FIL->bases, initPosition, n); fprintf(OUT, "%"PRIu64":%"PRIu64"\t%u\n", initPosition, n, cmp); } } else{ // val < threshold ====> LOW_REGION if(region == HIGH_REGION){ region = LOW_REGION; initPosition = n; } } lastPosition = n; } } if(region == LOW_REGION){ cmp = SelfSimilarity(FIL->bases, initPosition, n); fprintf(OUT, "%"PRIu64":%"PRIu64"\t%u\n", initPosition, lastPosition, cmp); } }
//This tells you how corrolated your x and y are. A straight line, at any non0 angle, give you a corrolation of 1. //If this is nonzero, it means the points vary more in one direction than in another. This number should be close to 0. double PearsonProductMomentCorrelation(double x[], double y[], int size) { //Base case if( size<=1 ) { return 0; } double ans; double xmean; double ymean; xmean = Mean(x, size); ymean=Mean(y, size); int i; double s; double xv; double yv; double t1; double t2; s = 0; xv = 0; yv = 0; for(i=0; i<size; i++) { t1 = abs(x[i]-xmean); t2 = abs(y[i]-ymean); xv = xv+sqrt(t1); yv = yv+sqrt(t2); s = s+t1*t2; } ans = s/sqrt(xv)*sqrt(yv); return ans; }
TEST(Util, NormalSampleTest) { VReal tmp; for (int i = 0; i < 1000000; i++) { tmp.push_back(NormalSample() / 100); } EXPECT_LT(std::abs(0.0 - Mean(tmp)), 0.00001); EXPECT_LT(std::abs(0.0001 - Var(tmp)), 0.00001); VVVReal tmp2; RandomInit(100, 100, 100, &tmp2); EXPECT_LT(std::abs(0.0 - Mean(tmp2)), 0.00001); EXPECT_LT(std::abs(0.0001 - Var(tmp2)), 0.00001); }
//Histogram *Unser(Image *img) float *Unser(Image *img) { Histogram *h = NULL; float sum[4][511], dif[4][511], *val=NULL; float mean, contrast, correlation; int i; val = (float*) calloc(SIZE,sizeof(float)); ComputeHistograms(img, sum, dif); for (i=0; i<4; i++){ mean = Mean(sum[i]); val[i * 8 + 0] = mean; contrast = Contrast(dif[i]); val[i * 8 + 1] = contrast;// / 255.0; correlation = Correlation(sum[i], mean, contrast); val[i * 8 + 2] = (correlation);// + 32512.5) / 255.0; val[i * 8 + 3] = Energy(sum[i], dif[i]);// * 255.0 ; val[i * 8 + 4] = Entropy(sum[i], dif[i]);// * 255.0 / 5.4168418; val[i * 8 + 5] = Homogeneity(dif[i]);// * 255.0; val[i * 8 + 6] = MaximalProbability(sum[i]);// * 255.0; val[i * 8 + 7] = StandardDeviation(contrast, correlation);// *sqrt(2); } //h = CreateHistogram(SIZE); //LinearNormalizeHistogram(h->v, val, 255.0, SIZE); //return(h); return(val); }
/*---------------------------------------------------------------------------*/ void PrintNormMatch(FILE *File, int NumParams, PROTOTYPE *Proto, FEATURE Feature) { /* ** Parameters: ** File open text file to dump match debug info to ** NumParams # of parameters in proto and feature ** Proto[] array of prototype parameters ** Feature[] array of feature parameters ** Globals: none ** Operation: This routine dumps out detailed normalization match info. ** Return: none ** Exceptions: none ** History: Wed Jan 2 09:49:35 1991, DSJ, Created. */ int i; FLOAT32 ParamMatch; FLOAT32 TotalMatch; for (i = 0, TotalMatch = 0.0; i < NumParams; i++) { ParamMatch = ((ParamOf (Feature, i) - Mean (Proto, i)) / StandardDeviation (Proto, i)); fprintf (File, " %6.1f", ParamMatch); if (i == CharNormY || i == CharNormRx) TotalMatch += ParamMatch * ParamMatch; } fprintf (File, " --> %6.1f (%4.2f)\n", TotalMatch, NormEvidenceOf (TotalMatch)); } /* PrintNormMatch */
/* Function Name :: StandarDeviation input :: pointer to bag return's :: float This function will take in a bag as input. This function will then calculate the standard deviation of the data in the bag. Using the formula for the standard deviation of a normal distribution. Return the standard deviation calculated. standard deviation = sqrt((sum of square of all deviation/(number of elemnts -1))) */ float StandardDeviation(bag *bg) { int length = getsize(bg); int i; float mean = Mean(bg); float sum = 0; float difference = 0; data *dat = NULL; for(i=0;i< length;i++) { dat = getItem(bg,i); difference = (mean - dat->val); if(difference < 0) { difference = (-1 * difference); } sum = sum + (difference *difference); } float deviation = (float)sum/(length-1); deviation = sqrtf(deviation); return (deviation); }
TEST(Util, MeanTest) { VReal tmp; tmp.push_back(1); tmp.push_back(2); tmp.push_back(3); EXPECT_DOUBLE_EQ(2, Mean(tmp)); }
/// <summary> /// Tests if the difference between two measurement histories is statistically significant to /// make a hill climbing decision. /// </summary> /// <remarks> /// A two sided test is used. /// </remarks> /// <param name="pMeasuredHistory"> /// The pointer to second measurement history. /// </param> /// <param name="significanceLevel"> /// The significance level in percent. Accepts 1 through 10. /// </param> /// <returns> /// -1 - second history is larger than this history /// 0 - statistically identical /// 1 - this history is larger than second history /// </returns> int HillClimbing::MeasuredHistory::SignificanceTest(MeasuredHistory * pMeasuredHistory, const int significanceLevel) { const int critSize = 10; double critArray[critSize] = { 2.576, 2.3263, 2.17, 2.05, 1.96, 1.88, 1.81, 1.75, 1.70, 1.64 }; double thisVariance = this->VarianceMean(); double thisMean = Mean(); double secondVariance = pMeasuredHistory->VarianceMean(); double secondMean = pMeasuredHistory->Mean(); _CONCRT_ASSERT(significanceLevel > 0 && significanceLevel <= 10); // Invalid significance level int result = (int) sign(thisMean - secondMean); if (thisVariance > 0 && secondVariance > 0) { double pooledVar = thisVariance / Count() + secondVariance / pMeasuredHistory->Count(); double testStatistic = (thisMean - secondMean) / sqrt(pooledVar); double critVal = critArray[significanceLevel-1]; double absVal = abs(testStatistic); if (absVal < critVal) { result = 0; } } return result; }
void plot_data (int color) { int pix_num,bckgrd_satus; double bckgrd_val; GetCtrlVal (ERG_panel, ERG_panel_bckgrd_sub, &bckgrd_satus); if (bckgrd_satus==1) { GetCtrlVal (ERG_panel, ERG_panel_bckgrd, &pix_num); Mean (&data2fit[pix_num-50], 100, &bckgrd_val); j=0; while (j<10000) { buffer[j] = data2fit[j]-bckgrd_val; j++; } } else { j=0; while (j<10000) { buffer[j] = data2fit[j]; j++; } } PlotY (ERG_panel, ERG_panel_scope, buffer, 10000,VAL_DOUBLE , VAL_THIN_LINE, VAL_EMPTY_SQUARE, VAL_SOLID, 1, MakeColor(color,color,color)); }
void Net::ReadLabels(const mxArray *mx_labels) { std::vector<size_t> labels_dim = mexGetDimensions(mx_labels); mexAssert(labels_dim.size() == 2, "The label array must have 2 dimensions"); size_t samples_num = labels_dim[0]; size_t classes_num = labels_dim[1]; mexAssert(classes_num == layers_.back()->length_, "Labels and last layer must have equal number of classes"); MatCPU labels_norm; // order_ == false mexGetMatrix(mx_labels, labels_norm); if (params_.balance_) { MatCPU labels_mean(1, classes_num); Mean(labels_norm, labels_mean, 1); mexAssert(!labels_mean.hasZeros(), "Balancing impossible: one of the classes is not presented"); MatCPU cpucoeffs(1, classes_num); cpucoeffs.assign(1); cpucoeffs /= labels_mean; classcoefs_.resize(1, classes_num); classcoefs_ = cpucoeffs; classcoefs_ /= (ftype) classes_num; } labels_.resize(samples_num, classes_num); labels_.reorder(true, false); // order_ == true; labels_ = labels_norm; }
inline const std::vector<T> ICR::EnsembleLearning::DeterministicNode<Model,T>::GetMean() { std::vector<T> Mean(1, m_Moments[0]); return Mean; }
double ChiRand::Skewness() const { double mu = Mean(); double sigmaSq = Variance(); double skew = mu * (1 - 2 * sigmaSq); skew /= std::pow(sigmaSq, 1.5); return skew; }
static void chanfunc_CalcStatistics (channelPtr chan) { double mean, std_dev, variance, rms, moment, median, mode, min, max; int err, order, min_i, max_i, intervals; char newnote[256]; Fmt (chanfunc.note, ""); err = MaxMin1D (chan->readings, chan->pts, &max, &max_i, &min, &min_i); SetInputMode (chanfunc.p, STATISTICS_MIN, !err); SetCtrlVal (chanfunc.p, STATISTICS_MIN, min); SetInputMode (chanfunc.p, STATISTICS_MAX, !err); SetCtrlVal (chanfunc.p, STATISTICS_MAX, max); if (err == NoErr) { Fmt (chanfunc.note, "%s<Min: %f[e2p5]\n", min); Fmt (chanfunc.note, "%s[a]<Max: %f[e2p5]\n", max); } err = Mean (chan->readings, chan->pts, &mean); SetInputMode (chanfunc.p, STATISTICS_MEAN, !err); SetCtrlVal (chanfunc.p, STATISTICS_MEAN, mean); if (err == NoErr) Fmt (chanfunc.note, "%s[a]<Mean: %f[e2p5]\n", mean); err = StdDev (chan->readings, chan->pts, &mean, &std_dev); SetInputMode (chanfunc.p, STATISTICS_STDDEV, !err); SetCtrlVal (chanfunc.p, STATISTICS_STDDEV, std_dev); if (err == NoErr) Fmt (chanfunc.note, "%s[a]<StdDev: %f[e2p5]\n", std_dev); err = Variance (chan->readings, chan->pts, &mean, &variance); SetInputMode (chanfunc.p, STATISTICS_VAR, !err); SetCtrlVal (chanfunc.p, STATISTICS_VAR, variance); if (err == NoErr) Fmt (chanfunc.note, "%s[a]<Variance: %f[e2p5]\n", variance); err = RMS (chan->readings, chan->pts, &rms); SetInputMode (chanfunc.p, STATISTICS_RMS, !err); SetCtrlVal (chanfunc.p, STATISTICS_RMS, rms); if (err == NoErr) Fmt (chanfunc.note, "%s[a]<RMS: %f[e2p5]\n", rms); GetCtrlVal (chanfunc.p, STATISTICS_ORDER, &order); err = Moment (chan->readings, chan->pts, order, &moment); SetInputMode (chanfunc.p, STATISTICS_MOMENT, !err); SetInputMode (chanfunc.p, STATISTICS_ORDER, !err); SetCtrlVal (chanfunc.p, STATISTICS_MOMENT, moment); if (err == NoErr) Fmt (chanfunc.note, "%s[a]<Moment: %f[e2p5] (order: %i)\n", moment, order); err = Median (chan->readings, chan->pts, &median); SetInputMode (chanfunc.p, STATISTICS_MEDIAN, !err); SetCtrlVal (chanfunc.p, STATISTICS_MEDIAN, median); if (err == NoErr) Fmt (chanfunc.note, "%s[a]<Median: %f[e2p5]\n", median); GetCtrlVal (chanfunc.p, STATISTICS_INTERVAL, &intervals); err = Mode (chan->readings, chan->pts, min, max, intervals, &mode); SetInputMode (chanfunc.p, STATISTICS_INTERVAL, !err); SetInputMode (chanfunc.p, STATISTICS_MODE, !err); SetCtrlVal (chanfunc.p, STATISTICS_INTERVAL, intervals); SetCtrlVal (chanfunc.p, STATISTICS_MODE, mode); if (err == NoErr) Fmt (chanfunc.note, "%s[a]<Mode: %f[e2p5] (intervals: %i)\n", mode, intervals); }
CReal CTimeWiener::ModLinRegr(CComplexVector& veccCorrEst) { /* Modified linear regression to estimate the "sigma" of the Gaussian correlation function */ /* Get vector length */ int iVecLen = Size(veccCorrEst); /* Init vectors and variables */ CReal rSigmaRet; CRealVector Tau(iVecLen); CRealVector Z(iVecLen); CRealVector W(iVecLen); CRealVector Wmrem(iVecLen); CReal Wm, Zm; CReal A1; /* Generate the tau vector */ for (int i = 0; i < iVecLen; i++) Tau[i] = (CReal) (i * iScatPilTimeInt); /* Linearize acf equation: y = a * exp(-b * x^2) z = ln(y); w = x^2 -> z = a0 + a1 * w */ Z = Log(Abs(veccCorrEst)); W = Tau * Tau; Wm = Mean(W); Zm = Mean(Z); Wmrem = W - Wm; /* Remove mean of W */ A1 = Sum(Wmrem * (Z - Zm)) / Sum(Wmrem * Wmrem); /* Final sigma calculation from estimation and assumed Gaussian model */ rSigmaRet = (CReal) 0.5 / crPi * sqrt((CReal) -2.0 * A1) / Ts; /* Bound estimated sigma value */ if (rSigmaRet > rSigmaMax) rSigmaRet = rSigmaMax; if (rSigmaRet < LOW_BOUND_SIGMA) rSigmaRet = LOW_BOUND_SIGMA; return rSigmaRet; }
double NakagamiDistribution::Skewness() const { double thirdMoment = lgammaShapeRatio; thirdMoment -= 1.5 * Y.GetLogRate(); thirdMoment = (m + 0.5) * std::exp(thirdMoment); double mean = Mean(); double variance = Variance(); return (thirdMoment - mean * (3 * variance + mean * mean)) / std::pow(variance, 1.5); }
double Statistics::StdDev(Image& Source, double& mean) { mean = Mean(Source); Kernel(reduce_stddev, In(Source), Out(), *m_PartialResultBuffer, Source.Step(), Source.Width(), Source.Height(), float(mean)); m_PartialResultBuffer->Read(true); return sqrt(ReduceMean(m_PartialResult)); }
double UnivariateDistribution<T>::ThirdMoment() const { double mean = Mean(); double variance = Variance(); double skewness = Skewness(); double moment = skewness * std::sqrt(variance) * variance; moment += mean * mean * mean; moment += 3 * mean * variance; return moment; }
double StandardDeviation(std::vector<double> vars) { double stddev = 0; double mean = Mean(vars); for (unsigned int i=0; i<vars.size(); ++i) { stddev += Square(vars.at(i) - mean); } stddev = stddev/vars.size(); return sqrt(stddev); }
double ChiRand::ExcessKurtosis() const { double mu = Mean(); double sigmaSq = Variance(); double sigma = std::sqrt(sigmaSq); double skew = Skewness(); double kurt = 1.0 - mu * sigma * skew; kurt /= sigmaSq; --kurt; return 2 * kurt; }
int main() { double scores[MaxJudges]; int nJudges; printf("Enter the number of judges: "); nJudges=GetInteger(); if(nJudges>MaxJudges) Error("Too many judges"); ReadAllScores(scores,nJudges); printf("The average score is %.2f\n",Mean(scores,nJudges)); }
// Only the diagonal of the covariance matrix. Vector3f SensorFilter::Variance() const { Vector3f mean = Mean(); Vector3f total = Vector3f(0.0f, 0.0f, 0.0f); for (int i = 0; i < Count; i++) { total.x += (Elements[i].x - mean.x) * (Elements[i].x - mean.x); total.y += (Elements[i].y - mean.y) * (Elements[i].y - mean.y); total.z += (Elements[i].z - mean.z) * (Elements[i].z - mean.z); } return total / (float) Count; }
double NakagamiDistribution::ExcessKurtosis() const { double mean = Mean(); double secondMoment = SecondMoment(); double thirdMoment = ThirdMoment(); double fourthMoment = FourthMoment(); double meanSq = mean * mean; double variance = secondMoment - meanSq; double numerator = fourthMoment - 4 * thirdMoment * mean + 6 * secondMoment * meanSq - 3 * meanSq * meanSq; double denominator = variance * variance; return numerator / denominator - 3.0; }
void MyOpenSMOKE_SolidRegression::Prepare() { ChangeDimensions(numTotal, &temperatures_global); ChangeDimensions(numTotal, &utemperatures_global); ChangeDimensions(numTotal, &pressures_Gas_global); int k=1; for(int i=1;i<=nCases;i++) { for(int j=1;j<=experiments[i].nPoints;j++) { temperatures_global[k] = experiments[i].temperature; utemperatures_global[k] = 1./temperatures_global[k]; pressures_Gas_global[k] = experiments[i].pressure; k++; } } TMeanGlobal = Mean(temperatures_global); PGasMeanGlobal = Mean(pressures_Gas_global); C2 = -1./TMeanGlobal; C3 = pressures_Gas_global.Norm2(); BzzVector auxiliar_vector = utemperatures_global; for(k=1;k<=numTotal;k++) auxiliar_vector[k] += C2; C1 = 1./auxiliar_vector.Norm2(); cout << "Tmin: " << temperatures_global.Min() << " K" << endl; cout << "Tmax: " << temperatures_global.Max() << " K" << endl; cout << "Tmean: " << TMeanGlobal << " K" << endl; cout << "PGasmin: " << pressures_Gas_global.Min() << " atm" << endl; cout << "PGasmax: " << pressures_Gas_global.Max() << " atm" << endl; cout << "PGasmean: " << PGasMeanGlobal << " atm" << endl; cout << "C1: " << C1 << " K" << endl; cout << "C2: " << C2 << " 1/K" << endl; cout << "C3: " << C3 << " atm" << endl; }
void RunningStats::Print(FILE * pFile, const char * header) const { fprintf (pFile, "\n%s\n", header); fprintf (pFile, "NumDataValues: %ld\n", NumDataValues()); fprintf (pFile, "Mean: %f\n", Mean()); fprintf (pFile, "Variance: %f\n", Variance()); fprintf (pFile, "StandardDeviation: %f\n", StandardDeviation()); fprintf (pFile, "Skewness: %f\n", Skewness()); fprintf (pFile, "Kurtosis: %f\n", Kurtosis()); fprintf (pFile, "Maximum: %f\n", Maximum()); fprintf (pFile, "Minimum: %f\n", Minimum()); return; }
double CBlob::StdDev( IplImage *image ) { // it is calculated? /* if( m_stdDevGray != -1 ) { return m_stdDevGray; } */ // call mean calculation (where also standard deviation is calculated) Mean( image ); return m_stdDevGray; }
/******************************************************************************\ * Phase lock loop (PLL) * \******************************************************************************/ void CPLL::Process(CRealVector& vecrIn /* in/out */) { /* Mix it down to zero frequency */ cvecLow = vecrIn; Mixer.Process(cvecLow); /* Complex loop filter */ rvecRealTmp = Filter(rvecB, rvecA, Real(cvecLow), rvecZReal); rvecImagTmp = Filter(rvecB, rvecA, Imag(cvecLow), rvecZImag); /* Calculate current phase for GUI */ rCurPhase = Angle(CComplex(Mean(rvecRealTmp), Mean(rvecImagTmp))); /* Average over entire block (only real part) */ const CReal rOffsEst = Mean(rvecRealTmp); /* Close loop */ rNormCurFreqOffsetAdd = PLL_LOOP_GAIN * rOffsEst; /* Update mixer */ Mixer.SetMixFreq(rNormCurFreqOffset + rNormCurFreqOffsetAdd); }
// Standard deviation of a set of probabilities static double Sigma(ub4 minx,ub4 maxs) { register ub4 i,dv; double m, t=0.0; double d[MODU]; dv = maxs-minx+1; m = Mean(minx,maxs); for (i=minx; i<=maxs; i++) d[i] = pow((prob[i]-m),2); // variance for (i=minx; i<=maxs; i++) t += d[i]; m = (double) t/dv; return sqrt(m); }