public void FitsToBestLineThroughOrigin() { // Mathematica: Fit[{{1,4.986},{2,2.347},{3,2.061},{4,-2.995},{5,-2.352},{6,-5.782}}, {x}, x] // -> -0.467791 x var x = Enumerable.Range(1, 6).Select(Convert.ToDouble).ToArray(); var y = new[] { 4.986, 2.347, 2.061, -2.995, -2.352, -5.782 }; var resp = Fit.LineThroughOrigin(x, y); Assert.AreEqual(-0.467791, resp, 1e-4); var resf = Fit.LineThroughOriginFunc(x, y); foreach (var z in Enumerable.Range(-3, 10)) { Assert.AreEqual(-0.467791 * z, resf(z), 1e-4); } var respSeq = SimpleRegression.FitThroughOrigin(Generate.Map2(x, y, Tuple.Create)); Assert.AreEqual(-0.467791, respSeq, 1e-4); }
private List <AccordResult> CalculateLinearRegression(List <BalancePointPair> allBalancePointPairs, WthNormalParams normalParamsKey) { var allBalancePointGroups = allBalancePointPairs.GroupBy(s => new { s.CoolingBalancePoint, s.HeatingBalancePoint }); List <AccordResult> accordResults = new List <AccordResult>(); List <AccordResult> rejectedAccords = new List <AccordResult>(); foreach (var group in allBalancePointGroups) { try { List <BalancePointPair> IdenticalBalancePointPairsForAllReadings = group.ToList(); BalancePointPair _pointPair = IdenticalBalancePointPairsForAllReadings.First(); int readingsCount = IdenticalBalancePointPairsForAllReadings.Count; double[] fullYData = new double[readingsCount]; double[] fullYDataDailyAvg = new double[readingsCount]; double[][] hcddMatrix = new double[readingsCount][]; double[][] hcddMatrixNonDaily = new double[readingsCount][]; foreach (BalancePointPair balancePointPair in IdenticalBalancePointPairsForAllReadings) { fullYData[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] = (balancePointPair.ActualUsage); fullYDataDailyAvg[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] = (balancePointPair.ActualUsage / balancePointPair.DaysInReading); hcddMatrix[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] = new double[] { (balancePointPair.HeatingDegreeDays / balancePointPair.DaysInReading), (balancePointPair.CoolingDegreeDays / balancePointPair.DaysInReading) }; } double[] avgHddsForEachReadingInYear = new double[readingsCount]; double[] avgCddsForEachReadingInYear = new double[readingsCount]; for (int i = 0; i < readingsCount; i++) { avgHddsForEachReadingInYear[i] = hcddMatrix[i][0]; avgCddsForEachReadingInYear[i] = hcddMatrix[i][1]; } double[] modelParams = new double[3]; modelParams[0] = 0; modelParams[1] = 0; modelParams[2] = 0; if (fullYData.Sum() == 0) { AccordResult empty = new AccordResult { bpPair = _pointPair }; accordResults.Add(empty); } else if (_pointPair.HeatingBalancePoint == 0 && _pointPair.CoolingBalancePoint == 0) { double[] onesVector = new double[readingsCount]; for (int i = 0; i < readingsCount; i++) { onesVector[i] = 1; } modelParams[0] = Fit.LineThroughOrigin(onesVector, fullYDataDailyAvg); OrdinaryLeastSquares ols = new OrdinaryLeastSquares() { UseIntercept = false }; SimpleLinearRegression regressionAccord = ols.Learn(onesVector, fullYDataDailyAvg); //double[] predictedAccord = regressionAccord.Transform(onesVector); double r2 = MathNet.Numerics.GoodnessOfFit.CoefficientOfDetermination(onesVector.Select(x => x * modelParams[0]), fullYDataDailyAvg); //double mean = fullYDataDailyAvg.Mean(); //if (mean != modelParams[0] || mean != regressionAccord.Slope) //{ // Console.WriteLine("Hey!"); //} //double r2Accord = regressionAccord.CoefficientOfDetermination(onesVector, fullYDataDailyAvg); //double sxx = onesVector.Subtract(onesVector.Mean()).Pow(2).Sum(); //double hypothesizedValue = 0; //try //{ // TTest test = new TTest( // estimatedValue: regressionAccord.Slope, standardError: sxx, degreesOfFreedom: _pointPair.ReadingsInNormalYear - 2, // hypothesizedValue: hypothesizedValue, alternate: OneSampleHypothesis.ValueIsDifferentFromHypothesis // ); // if (test.Significant) // { AccordResult accordResult = new AccordResult() { SimpleLinearRegression = regressionAccord, R2Accord = r2, IsSimpleSingleRegression = true, HeatingBP = _pointPair.HeatingBalancePoint, CoolingBP = _pointPair.CoolingBalancePoint, Intercept = regressionAccord.Slope, bpPair = _pointPair }; accordResults.Add(accordResult); // } //} //catch (Exception e) //{ // Console.WriteLine(e.Message + e.StackTrace); //} } else if (_pointPair.CoolingBalancePoint != 0 && _pointPair.HeatingBalancePoint != 0) { //modelParams = MultipleRegression.QR(hcddMatrix, fullYDataDailyAvg, intercept: true); //Accord //var ols = new OrdinaryLeastSquares() //{ // UseIntercept = true //}; try { MultipleLinearRegressionAnalysis mlra = new MultipleLinearRegressionAnalysis(intercept: true); mlra.Learn(hcddMatrix, fullYDataDailyAvg); // //MultipleLinearRegression regressionAccord = ols.Learn(hcddMatrix, fullYDataDailyAvg); var regressionAccord = mlra.Regression; double[] predicted = regressionAccord.Transform(hcddMatrix); double r2Accord = new RSquaredLoss(numberOfInputs: 2, expected: fullYDataDailyAvg) { Adjust = false }.Loss(predicted); double r2Coeff = regressionAccord.CoefficientOfDetermination(hcddMatrix, fullYDataDailyAvg, adjust: false); //double r2Math = MathNet.Numerics.GoodnessOfFit.CoefficientOfDetermination(hcddMatrix.Select( // x => (x[0] * regressionAccord.Weights[0]) + (x[1] * regressionAccord.Weights[1]) + regressionAccord.Intercept //), fullYDataDailyAvg); //double r2MathPred = MathNet.Numerics.GoodnessOfFit.CoefficientOfDetermination(predicted, fullYDataDailyAvg); AccordResult accordResult = new AccordResult() { //MultipleRegression = regressionAccord, R2Accord = r2Accord, R2Coeff = r2Coeff, HeatingBP = _pointPair.HeatingBalancePoint, CoolingBP = _pointPair.CoolingBalancePoint, IsSimpleSingleRegression = false, MLRA = mlra, Intercept = regressionAccord.Intercept, bpPair = _pointPair, IsMultipleLinearRegression = true }; if (mlra.Coefficients.All(x => x.TTest.Significant)) { accordResults.Add(accordResult); } else { rejectedAccords.Add(accordResult); } } catch (Exception e) { Console.WriteLine(e.Message + " " + e.StackTrace); } } else if (_pointPair.HeatingBalancePoint > 0) { // Tuple<double, double> heatingTuple = Fit.Line(avgHddsForEachReadingInYear, fullYDataDailyAvg); // modelParams[0] = heatingTuple.Item1; // modelParams[1] = heatingTuple.Item2; // double r = MathNet.Numerics.GoodnessOfFit.CoefficientOfDetermination( // avgHddsForEachReadingInYear.Select(x => heatingTuple.Item1 + heatingTuple.Item2 * x), fullYDataDailyAvg); OrdinaryLeastSquares ols = new OrdinaryLeastSquares() { UseIntercept = true }; SimpleLinearRegression regressionAccord = ols.Learn(avgHddsForEachReadingInYear, fullYDataDailyAvg); double[] predictedAccord = regressionAccord.Transform(avgHddsForEachReadingInYear); double rAccord = new RSquaredLoss(1, fullYDataDailyAvg).Loss(predictedAccord); //double rAccord2 = regressionAccord.CoefficientOfDetermination(avgHddsForEachReadingInYear, fullYDataDailyAvg, adjust: false); //double r2Math = MathNet.Numerics.GoodnessOfFit.CoefficientOfDetermination(avgHddsForEachReadingInYear.Select( // x => (x * regressionAccord.Slope) + regressionAccord.Intercept // ), fullYDataDailyAvg); //double r2 = MathNet.Numerics.GoodnessOfFit.CoefficientOfDetermination(predictedAccord, fullYDataDailyAvg); int degreesOfFreedom = _pointPair.ReadingsInNormalYear - 2; double ssx = Math.Sqrt((avgHddsForEachReadingInYear.Subtract(avgHddsForEachReadingInYear.Mean())).Pow(2).Sum()); double s = Math.Sqrt(((fullYDataDailyAvg.Subtract(predictedAccord).Pow(2)).Sum()) / degreesOfFreedom); double error = regressionAccord.GetStandardError(avgHddsForEachReadingInYear, fullYDataDailyAvg); double seSubB = s / ssx; double hypothesizedValue = 0; TTest tTest = new TTest( estimatedValue: regressionAccord.Slope, standardError: seSubB, degreesOfFreedom: degreesOfFreedom, hypothesizedValue: hypothesizedValue, alternate: OneSampleHypothesis.ValueIsDifferentFromHypothesis ); AccordResult accordResult = new AccordResult() { SimpleLinearRegression = regressionAccord, R2Accord = rAccord, IsSimpleSingleRegression = true, HeatingBP = _pointPair.HeatingBalancePoint, CoolingBP = _pointPair.CoolingBalancePoint, TTest = tTest, Intercept = regressionAccord.Intercept, bpPair = _pointPair }; if (tTest.Significant) { accordResults.Add(accordResult); } else { rejectedAccords.Add(accordResult); } } else if (_pointPair.CoolingBalancePoint > 0) { //Tuple<double, double> coolingTuple = Fit.Line(avgCddsForEachReadingInYear, fullYDataDailyAvg); //modelParams[0] = coolingTuple.Item1; //modelParams[2] = coolingTuple.Item2; OrdinaryLeastSquares ols = new OrdinaryLeastSquares() { UseIntercept = true }; SimpleLinearRegression regressionAccord = ols.Learn(avgCddsForEachReadingInYear, fullYDataDailyAvg); double[] predictedAccord = regressionAccord.Transform(avgCddsForEachReadingInYear); double rAccord = new RSquaredLoss(1, fullYDataDailyAvg).Loss(predictedAccord); //double r2Math = MathNet.Numerics.GoodnessOfFit.CoefficientOfDetermination(avgCddsForEachReadingInYear.Select( // x => (x * regressionAccord.Slope) + regressionAccord.Intercept // ), fullYDataDailyAvg); //double r2 = MathNet.Numerics.GoodnessOfFit.CoefficientOfDetermination(predictedAccord, fullYDataDailyAvg); int degreesOfFreedom = _pointPair.ReadingsInNormalYear - 2; double ssx = Math.Sqrt(avgCddsForEachReadingInYear.Subtract(avgCddsForEachReadingInYear.Mean()).Pow(2).Sum()); double s = Math.Sqrt(((fullYDataDailyAvg.Subtract(predictedAccord).Pow(2)).Sum()) / degreesOfFreedom); double seSubB = s / ssx; double hypothesizedValue = 0; double myT = seSubB / regressionAccord.Slope; TTest tTest = new TTest( estimatedValue: regressionAccord.Slope, standardError: seSubB, degreesOfFreedom: degreesOfFreedom, hypothesizedValue: hypothesizedValue, alternate: OneSampleHypothesis.ValueIsDifferentFromHypothesis ); AccordResult accordResult = new AccordResult() { SimpleLinearRegression = regressionAccord, R2Accord = rAccord, IsSimpleSingleRegression = true, HeatingBP = _pointPair.HeatingBalancePoint, CoolingBP = _pointPair.CoolingBalancePoint, TTest = tTest, Intercept = regressionAccord.Intercept, bpPair = _pointPair }; if (tTest.Significant) { accordResults.Add(accordResult); } else { rejectedAccords.Add(accordResult); } } ; } catch (Exception e) { Console.WriteLine(normalParamsKey.AccID + " " + normalParamsKey.UtilID + " " + normalParamsKey.UnitID + " " + e.Message + e.StackTrace); } } //rejectedAccords = rejectedAccords.OrderByDescending(s => s.R2Accord).ToList(); //accordResults = accordResults.OrderByDescending(s => s.R2Accord).ToList(); return(accordResults); }
private AccordResult CalculateLinearRegression(List <BalancePointPair> allBalancePointPairs, WthNormalParams normalParamsKey) { var allBalancePointGroups = allBalancePointPairs.GroupBy(s => new { s.CoolingBalancePoint, s.HeatingBalancePoint }); List <AccordResult> accordResults = new List <AccordResult>(); foreach (var group in allBalancePointGroups) { try { List <BalancePointPair> IdenticalBalancePointPairsFromAllReadings = group.ToList(); BalancePointPair _pointPair = IdenticalBalancePointPairsFromAllReadings.First(); int readingsCount = IdenticalBalancePointPairsFromAllReadings.Count; double[] fullYData = new double[readingsCount]; double[] fullYDataDailyAvg = new double[readingsCount]; double[][] hcddMatrix = new double[readingsCount][]; double[][] hcddMatrixNonDaily = new double[readingsCount][]; foreach (BalancePointPair balancePointPair in IdenticalBalancePointPairsFromAllReadings) { fullYData[IdenticalBalancePointPairsFromAllReadings.IndexOf(balancePointPair)] = (balancePointPair.ActualUsage); fullYDataDailyAvg[IdenticalBalancePointPairsFromAllReadings.IndexOf(balancePointPair)] = (balancePointPair.ActualUsage / balancePointPair.DaysInReading); hcddMatrix[IdenticalBalancePointPairsFromAllReadings.IndexOf(balancePointPair)] = new double[] { (balancePointPair.HeatingDegreeDays / balancePointPair.DaysInReading), (balancePointPair.CoolingDegreeDays / balancePointPair.DaysInReading) }; } if (!(fullYData.Sum() > 0)) { return(new AccordResult()); } double[] avgHddsForEachReadingInYear = new double[readingsCount]; double[] avgCddsForEachReadingInYear = new double[readingsCount]; for (int i = 0; i < readingsCount; i++) { avgHddsForEachReadingInYear[i] = hcddMatrix[i][0]; avgCddsForEachReadingInYear[i] = hcddMatrix[i][1]; } double[] modelParams = new double[3]; modelParams[0] = 0; modelParams[1] = 0; modelParams[2] = 0; if (_pointPair.HeatingBalancePoint == 0 && _pointPair.CoolingBalancePoint == 0) { double[] onesVector = new double[readingsCount]; for (int i = 0; i < readingsCount; i++) { onesVector[i] = 1; } modelParams[0] = Fit.LineThroughOrigin(onesVector, fullYDataDailyAvg); OrdinaryLeastSquares ols = new OrdinaryLeastSquares() { UseIntercept = false }; double r2 = MathNet.Numerics.GoodnessOfFit.CoefficientOfDetermination( onesVector.Select(x => x * modelParams[0]), fullYDataDailyAvg); AccordResult accordResult = new AccordResult() { IsSimpleSingleRegression = true, HeatingBP = _pointPair.HeatingBalancePoint, CoolingBP = _pointPair.CoolingBalancePoint, Intercept = modelParams[0], R2Accord = r2, //R2Accord = 0 }; accordResults.Add(accordResult); } else if (_pointPair.CoolingBalancePoint != 0 && _pointPair.HeatingBalancePoint != 0) { try { MultipleLinearRegressionAnalysis mlra = new MultipleLinearRegressionAnalysis(intercept: true); mlra.Learn(hcddMatrix, fullYDataDailyAvg); var regressionAccord = mlra.Regression; double[] predictedAccord = regressionAccord.Transform(hcddMatrix); double r2Accord = new RSquaredLoss(numberOfInputs: 2, expected: fullYDataDailyAvg) { Adjust = false }.Loss(predictedAccord); double r2Coeff = regressionAccord.CoefficientOfDetermination(hcddMatrix, fullYDataDailyAvg, adjust: false); bool FTestFailed = !mlra.FTest.Significant; AccordResult accordResult = new AccordResult() { IsMultipleLinearRegression = true, HeatingBP = _pointPair.HeatingBalancePoint, CoolingBP = _pointPair.CoolingBalancePoint, Intercept = regressionAccord.Intercept, B2 = regressionAccord.Weights[0], B4 = regressionAccord.Weights[1], R2Accord = r2Accord, FTestFailed = FTestFailed }; //int degreesOfFreedom = normalParamsKey.MoCt - 3; double degreesOfFreedomAsDouble = mlra.Regression.GetDegreesOfFreedom(readingsCount); int degreesOfFreedom = Convert.ToInt32(degreesOfFreedomAsDouble); //if (degreesOfFreedom != 9) //{ // Log.Warning($"Multivariable regression. DOF expected to be 9. is: {degreesOfFreedom}"); //} //if (degreesOfFreedom != dof) //{ // Console.WriteLine($"dof different. mlra.dof = {dof} expected = {degreesOfFreedom}"); //} double s = Math.Sqrt(fullYDataDailyAvg.Subtract(predictedAccord).Pow(2).Sum() / degreesOfFreedom); double ssxHdd = Math.Sqrt((avgHddsForEachReadingInYear.Subtract(avgHddsForEachReadingInYear.Mean())).Pow(2).Sum()); double ssxCdd = Math.Sqrt((avgCddsForEachReadingInYear.Subtract(avgCddsForEachReadingInYear.Mean())).Pow(2).Sum()); double seSubHdd = s / ssxHdd; double seSubCdd = s / ssxCdd; double tStatisticHdd = regressionAccord.Weights[0] / seSubHdd; double tStatisticCdd = regressionAccord.Weights[1] / seSubCdd; double tCriticalFivePercent = 2.262156; double tCriticalTenPercent = 1.833113; bool myTestHdd = Math.Abs(tStatisticHdd) >= tCriticalTenPercent; bool myTestCdd = Math.Abs(tStatisticCdd) >= tCriticalTenPercent; //if (myTestHdd != mlra.Coefficients[0].TTest.Significant && degreesOfFreedom != 9) //{ // Console.WriteLine($"nope. mystat - {tStatisticHdd} accordstat - {mlra.Coefficients[0].TTest.Statistic} " + // $"accordCritical - {mlra.Coefficients[0].TTest.CriticalValue}"); //} //if (myTestCdd != mlra.Coefficients[1].TTest.Significant && degreesOfFreedom != 9) //{ // Console.WriteLine($"nope. mystat - {tStatisticCdd} accordstat - {mlra.Coefficients[1].TTest.Statistic} " + // $"accordCritical - {mlra.Coefficients[1].TTest.CriticalValue}"); //} //if (mlra.Coefficients.All(x => x.TTest.Significant) && // mlra.Coefficients.All(x => x.Value > 0) && // mlra.Regression.Intercept > 0 && // r2Accord >= 0.7500) //{ // accordResults.Add(accordResult); //} if ( myTestHdd && myTestCdd && mlra.Coefficients.All(x => x.Value > 0) && mlra.Regression.Intercept > 0 //&& accordResult.R2Accord >= 0.75 ) { accordResults.Add(accordResult); } } catch (Exception e) { Log.Debug($"AccID/UtilID/UnitID: {normalParamsKey.AccID}/{normalParamsKey.UtilID}/{normalParamsKey.UnitID} >> " + $"MultipleLinearRegressionAnalysis Exception: {e.Message}"); } } else if (_pointPair.HeatingBalancePoint > 0) { OrdinaryLeastSquares ols = new OrdinaryLeastSquares() { UseIntercept = true }; SimpleLinearRegression regressionAccord = ols.Learn(avgHddsForEachReadingInYear, fullYDataDailyAvg); double[] predictedAccord = regressionAccord.Transform(avgHddsForEachReadingInYear); double r2Accord = new RSquaredLoss(1, fullYDataDailyAvg).Loss(predictedAccord); //int degreesOfFreedom = normalParamsKey.MoCt - 2; double degreesOfFreedomAsDouble = regressionAccord.GetDegreesOfFreedom(readingsCount); int degreesOfFreedom = Convert.ToInt32(degreesOfFreedomAsDouble); //if (degreesOfFreedom != 10) //{ // Log.Warning($"Single variable regression. DOF expected to be 10. is: {degreesOfFreedom}"); //} double ssx = Math.Sqrt((avgHddsForEachReadingInYear.Subtract(avgHddsForEachReadingInYear.Mean())).Pow(2).Sum()); double s = Math.Sqrt(fullYDataDailyAvg.Subtract(predictedAccord).Pow(2).Sum() / degreesOfFreedom); double error = regressionAccord.GetStandardError(avgHddsForEachReadingInYear, fullYDataDailyAvg); double seSubB = s / ssx; double hypothesizedValue = 0; double tStatistic = regressionAccord.Slope / seSubB; double tCriticalFivePercent = 2.228138; double tCriticalTenPercent = 1.812461; bool myTest = Math.Abs(tStatistic) >= tCriticalTenPercent; //TTest tTest = new TTest( // estimatedValue: regressionAccord.Slope, standardError: seSubB, degreesOfFreedom: degreesOfFreedom, // hypothesizedValue: hypothesizedValue, alternate: OneSampleHypothesis.ValueIsDifferentFromHypothesis // ); //if (myTest != tTest.Significant) //{ // Console.WriteLine($"nope. mystat - {tStatistic} accordstat - {tTest.Statistic} accordCritical - {tTest.CriticalValue}"); //} AccordResult accordResult = new AccordResult() { IsSimpleSingleRegression = true, HeatingBP = _pointPair.HeatingBalancePoint, Intercept = regressionAccord.Intercept, B2 = regressionAccord.Slope, R2Accord = r2Accord }; //if (tTest.Significant && accordResult.B2 > 0 && r2Accord >= 0.7500) //{ // accordResults.Add(accordResult); //} if (myTest && accordResult.B2 > 0 && accordResult.Intercept > 0 //&& r2Accord >= 0.7500 ) { accordResults.Add(accordResult); } } else if (_pointPair.CoolingBalancePoint > 0) { OrdinaryLeastSquares ols = new OrdinaryLeastSquares() { UseIntercept = true }; SimpleLinearRegression regressionAccord = ols.Learn(avgCddsForEachReadingInYear, fullYDataDailyAvg); double[] predictedAccord = regressionAccord.Transform(avgCddsForEachReadingInYear); double r2Accord = new RSquaredLoss(1, fullYDataDailyAvg).Loss(predictedAccord); //int degreesOfFreedom = normalParamsKey.MoCt - 2; double degreesOfFreedomAsDouble = regressionAccord.GetDegreesOfFreedom(readingsCount); int degreesOfFreedom = Convert.ToInt32(degreesOfFreedomAsDouble); //if (degreesOfFreedom != 10) //{ // Log.Warning($"Single variable regression. DOF expected to be 10. is: {degreesOfFreedom}"); //} double ssx = Math.Sqrt(avgCddsForEachReadingInYear.Subtract(avgCddsForEachReadingInYear.Mean()).Pow(2).Sum()); double s = Math.Sqrt(fullYDataDailyAvg.Subtract(predictedAccord).Pow(2).Sum() / degreesOfFreedom); double seSubB = s / ssx; double hypothesizedValue = 0; double tStatistic = regressionAccord.Slope / seSubB; double tCriticalFivePercent = 2.22813885198627; double tCriticalTenPercent = 1.812461; bool myTest = Math.Abs(tStatistic) >= tCriticalTenPercent; //TTest tTest = new TTest( // estimatedValue: regressionAccord.Slope, standardError: seSubB, degreesOfFreedom: degreesOfFreedom, // hypothesizedValue: hypothesizedValue, alternate: OneSampleHypothesis.ValueIsDifferentFromHypothesis // ); //if (myTest != tTest.Significant) //{ // Console.WriteLine($"nope. mystat - {tStatistic} accordstat - {tTest.Statistic} accordCritical - {tTest.CriticalValue}"); //} AccordResult accordResult = new AccordResult() { IsSimpleSingleRegression = true, CoolingBP = _pointPair.CoolingBalancePoint, Intercept = regressionAccord.Intercept, B4 = regressionAccord.Slope, R2Accord = r2Accord }; //if (tTest.Significant && accordResult.B4 > 0 && r2Accord >= 0.7500) //{ // accordResults.Add(accordResult); //} if ( myTest && accordResult.B4 > 0 //&& r2Accord >= 0.7500 ) { accordResults.Add(accordResult); } } } catch (Exception e) { Log.Debug($"AccID/UtilID/UnitID: {normalParamsKey.AccID}/{normalParamsKey.UtilID}/{normalParamsKey.UnitID} >> {e.Message} {e.StackTrace}"); } } AccordResult accordWinner = accordResults .Where(s => s.Intercept >= 0) .OrderByDescending(s => s.R2Accord).ToList().FirstOrDefault(); return(accordWinner); }
private AccordResult CalculateLinearRegression(List <BalancePointPair> allBalancePointPairs, WthNormalParams normalParamsKey) { var allBalancePointGroups = allBalancePointPairs.GroupBy(s => new { s.CoolingBalancePoint, s.HeatingBalancePoint }); List <AccordResult> accordResults = new List <AccordResult>(); foreach (var group in allBalancePointGroups) { try { List <BalancePointPair> IdenticalBalancePointPairsFromAllReadings = group.ToList(); BalancePointPair _pointPair = IdenticalBalancePointPairsFromAllReadings.First(); int readingsCount = IdenticalBalancePointPairsFromAllReadings.Count; double[] fullYData = new double[readingsCount]; double[] fullYDataDailyAvg = new double[readingsCount]; double[][] hcddMatrix = new double[readingsCount][]; double[][] hcddMatrixNonDaily = new double[readingsCount][]; foreach (BalancePointPair balancePointPair in IdenticalBalancePointPairsFromAllReadings) { fullYData[IdenticalBalancePointPairsFromAllReadings.IndexOf(balancePointPair)] = (balancePointPair.ActualUsage); fullYDataDailyAvg[IdenticalBalancePointPairsFromAllReadings.IndexOf(balancePointPair)] = (balancePointPair.ActualUsage / balancePointPair.DaysInReading); hcddMatrix[IdenticalBalancePointPairsFromAllReadings.IndexOf(balancePointPair)] = new double[] { (balancePointPair.HeatingDegreeDays / balancePointPair.DaysInReading), (balancePointPair.CoolingDegreeDays / balancePointPair.DaysInReading) }; } double[] avgHddsForEachReadingInYear = new double[readingsCount]; double[] avgCddsForEachReadingInYear = new double[readingsCount]; for (int i = 0; i < readingsCount; i++) { avgHddsForEachReadingInYear[i] = hcddMatrix[i][0]; avgCddsForEachReadingInYear[i] = hcddMatrix[i][1]; } double[] modelParams = new double[3]; modelParams[0] = 0; modelParams[1] = 0; modelParams[2] = 0; if (_pointPair.HeatingBalancePoint == 0 && _pointPair.CoolingBalancePoint == 0) { double[] onesVector = new double[readingsCount]; for (int i = 0; i < readingsCount; i++) { onesVector[i] = 1; } modelParams[0] = Fit.LineThroughOrigin(onesVector, fullYDataDailyAvg); OrdinaryLeastSquares ols = new OrdinaryLeastSquares() { UseIntercept = false }; double r2 = MathNet.Numerics.GoodnessOfFit.CoefficientOfDetermination( onesVector.Select(x => x * modelParams[0]), fullYDataDailyAvg); AccordResult accordResult = new AccordResult() { IsSimpleSingleRegression = true, HeatingBP = _pointPair.HeatingBalancePoint, CoolingBP = _pointPair.CoolingBalancePoint, Intercept = modelParams[0], R2Accord = r2, }; accordResults.Add(accordResult); } else if (_pointPair.CoolingBalancePoint != 0 && _pointPair.HeatingBalancePoint != 0) { try { MultipleLinearRegressionAnalysis mlra = new MultipleLinearRegressionAnalysis(intercept: true); mlra.Learn(hcddMatrix, fullYDataDailyAvg); var regressionAccord = mlra.Regression; double[] predicted = regressionAccord.Transform(hcddMatrix); double r2Accord = new RSquaredLoss(numberOfInputs: 2, expected: fullYDataDailyAvg) { Adjust = false }.Loss(predicted); double r2Coeff = regressionAccord.CoefficientOfDetermination(hcddMatrix, fullYDataDailyAvg, adjust: false); bool FTestFailed = !mlra.FTest.Significant; AccordResult accordResult = new AccordResult() { IsMultipleLinearRegression = true, HeatingBP = _pointPair.HeatingBalancePoint, CoolingBP = _pointPair.CoolingBalancePoint, Intercept = regressionAccord.Intercept, B2 = regressionAccord.Weights[0], B4 = regressionAccord.Weights[1], R2Accord = r2Accord, FTestFailed = FTestFailed }; if (mlra.Coefficients.All(x => x.TTest.Significant)) { accordResults.Add(accordResult); } } catch (Exception e) { Log.Debug(normalParamsKey.AccID + " " + normalParamsKey.UtilID + " " + normalParamsKey.UnitID + " " + e.Message + " " + e.StackTrace); } } else if (_pointPair.HeatingBalancePoint > 0) { OrdinaryLeastSquares ols = new OrdinaryLeastSquares() { UseIntercept = true }; SimpleLinearRegression regressionAccord = ols.Learn(avgHddsForEachReadingInYear, fullYDataDailyAvg); double[] predictedAccord = regressionAccord.Transform(avgHddsForEachReadingInYear); double r2Accord = new RSquaredLoss(1, fullYDataDailyAvg).Loss(predictedAccord); int degreesOfFreedom = normalParamsKey.MoCt - 2; double ssx = Math.Sqrt((avgHddsForEachReadingInYear.Subtract(avgHddsForEachReadingInYear.Mean())).Pow(2).Sum()); double s = Math.Sqrt(((fullYDataDailyAvg.Subtract(predictedAccord).Pow(2)).Sum()) / degreesOfFreedom); double error = regressionAccord.GetStandardError(avgHddsForEachReadingInYear, fullYDataDailyAvg); double seSubB = s / ssx; double hypothesizedValue = 0; TTest tTest = new TTest( estimatedValue: regressionAccord.Slope, standardError: seSubB, degreesOfFreedom: degreesOfFreedom, hypothesizedValue: hypothesizedValue, alternate: OneSampleHypothesis.ValueIsDifferentFromHypothesis ); AccordResult accordResult = new AccordResult() { IsSimpleSingleRegression = true, HeatingBP = _pointPair.HeatingBalancePoint, Intercept = regressionAccord.Intercept, B2 = regressionAccord.Slope, R2Accord = r2Accord }; if (tTest.Significant) { accordResults.Add(accordResult); } } else if (_pointPair.CoolingBalancePoint > 0) { OrdinaryLeastSquares ols = new OrdinaryLeastSquares() { UseIntercept = true }; SimpleLinearRegression regressionAccord = ols.Learn(avgCddsForEachReadingInYear, fullYDataDailyAvg); double[] predictedAccord = regressionAccord.Transform(avgCddsForEachReadingInYear); double rAccord = new RSquaredLoss(1, fullYDataDailyAvg).Loss(predictedAccord); int degreesOfFreedom = normalParamsKey.MoCt - 2; double ssx = Math.Sqrt(avgCddsForEachReadingInYear.Subtract(avgCddsForEachReadingInYear.Mean()).Pow(2).Sum()); double s = Math.Sqrt(((fullYDataDailyAvg.Subtract(predictedAccord).Pow(2)).Sum()) / degreesOfFreedom); double seSubB = s / ssx; double hypothesizedValue = 0; double myT = seSubB / regressionAccord.Slope; TTest tTest = new TTest( estimatedValue: regressionAccord.Slope, standardError: seSubB, degreesOfFreedom: degreesOfFreedom, hypothesizedValue: hypothesizedValue, alternate: OneSampleHypothesis.ValueIsDifferentFromHypothesis ); AccordResult accordResult = new AccordResult() { IsSimpleSingleRegression = true, CoolingBP = _pointPair.CoolingBalancePoint, Intercept = regressionAccord.Intercept, B4 = regressionAccord.Slope, R2Accord = rAccord }; if (tTest.Significant) { accordResults.Add(accordResult); } } ; } catch (Exception e) { Log.Debug(normalParamsKey.AccID + " " + normalParamsKey.UtilID + " " + normalParamsKey.UnitID + " " + e.Message + e.StackTrace); } } AccordResult accordWinner = accordResults .Where(s => s.Intercept >= 0) .OrderByDescending(s => s.R2Accord).ToList().FirstOrDefault(); return(accordWinner); }
private List <BalancePointPair> CalculateLinearRegression(List <BalancePointPair> allBalancePointPairs, WthNormalParams normalParamsKey) { var updatedBalancePointPairs = new List <BalancePointPair>(); var allBalancePointGroups = allBalancePointPairs.GroupBy(s => new { s.CoolingBalancePoint, s.HeatingBalancePoint }); foreach (var group in allBalancePointGroups) { List <BalancePointPair> IdenticalBalancePointPairsForAllReadings = group.ToList(); int readingsCount = IdenticalBalancePointPairsForAllReadings.Count; BalancePointPair _pointPair = IdenticalBalancePointPairsForAllReadings.First(); bool NonWeatherDependant = (normalParamsKey.B2_Original == 0 && normalParamsKey.B4_Original == 0); //List<double> expUsageDaily = new List<double>(); //List<double> hddsDaily = new List<double>(); //List<double> cddsDaily = new List<double>(); //List<double> actualUsageDaily = new List<double>(); double[] fullXData = new double[readingsCount]; //double[] fullXData_Original = new double[12 * balancePointPairGroup.Count]; double[] xDays = new double[readingsCount]; double[] fullYData = new double[readingsCount]; double[] fullYDataAvg = new double[readingsCount]; //double?[] hddsDaily = new double?[readingsCount * _pointPair.DaysInNormalYear]; //double?[] cddsDaily = new double?[readingsCount * _pointPair.DaysInNormalYear]; //double[][] hcddMatrix = new double[2][]; //hcddMatrix[0] = new double[readingsCount]; //hcddMatrix[1] = new double[readingsCount]; double[][] hcddMatrix = new double[readingsCount][]; foreach (BalancePointPair balancePointPair in IdenticalBalancePointPairsForAllReadings) { //double[] hddsDailyAvgInReading = new double[readingsCount]; //double[] cddsDailyAvgInReading = new double[readingsCount]; //expUsageDaily.Add(Convert.ToDouble(balancePointPair.ExpUsage) / balancePointPair.Days); //hddsDaily.Add(balancePointPair.HeatingDegreeDays / balancePointPair.Days); //cddsDaily.Add(balancePointPair.CoolingDegreeDays / balancePointPair.Days); //actualUsageDaily.Add(balancePointPair.ActualUsage / balancePointPair.Days); fullXData[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] = Convert.ToDouble(balancePointPair.ExpUsage_New); xDays[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] = balancePointPair.DaysInReading; fullYData[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] = (balancePointPair.ActualUsage); fullYDataAvg[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] = (balancePointPair.ActualUsage / balancePointPair.DaysInReading); //hddsDaily[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair) * ] // = balancePointPair.HddList[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)]; //cddsDaily[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] // = balancePointPair.CddList[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)]; //hddsDailyAvgInReading[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] // = (balancePointPair.HeatingDegreeDays / balancePointPair.DaysInReading); //cddsDailyAvgInReading[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] // = (balancePointPair.CoolingDegreeDays / balancePointPair.DaysInReading); hcddMatrix[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] = new double[] { (balancePointPair.HeatingDegreeDays / balancePointPair.DaysInReading), (balancePointPair.CoolingDegreeDays / balancePointPair.DaysInReading) }; //hcddMatrix[0][IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] = (balancePointPair.HeatingDegreeDays / balancePointPair.DaysInReading); //hcddMatrix[1][IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] = (balancePointPair.CoolingDegreeDays / balancePointPair.DaysInReading); } double[] avgHddsForEachReadingInYear = new double[readingsCount]; double[] avgCddsForEachReadingInYear = new double[readingsCount]; for (int i = 0; i < readingsCount; i++) { avgHddsForEachReadingInYear[i] = hcddMatrix[i][0]; avgCddsForEachReadingInYear[i] = hcddMatrix[i][1]; } //double[] expUsageByDay = new double[daysInYear]; //double[] fullYDataDaiy = new double[daysInYear]; //List<double> expUsageByDay = new List<double>(); //List<double> fullYDataByDay = new List<double>(); //foreach (BalancePointPair balancePointPair in IdenticalBalancePointPairsForAllReadings) //{ // double dailyExpusage = 0; // dailyExpusage += normalParamsKey.B3 * balancePointPair.HddList[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)].Value; // dailyExpusage += normalParamsKey.B5 * balancePointPair.CddList[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)].Value; // expUsageByDay.Add(dailyExpusage); // fullYDataByDay.Add(balancePointPair.ActualUsage / balancePointPair.DaysInReading); //} //double[] hddsDailyArr = hddsDaily.ToArray(); //double[] cddsDailyArr = cddsDaily.ToArray(); //double[][] xy = new double[cddsDailyArr.Length][]; //for (int i = 0; i < cddsDailyArr.Length; i++) //{ // double[] row = new double[2]; // xy[i] = row; //} //for (int i = 0; i < hddsDailyArr.Length; i++) //{ // xy[i][0] = hddsDailyArr[i]; // xy[i][1] = cddsDailyArr[i]; //} //double[] p = Fit.LinearMultiDim(hcddMatrix, fullYDataAvg, // d => 1.0, // d => d[0], // d => d[1]); //Matrix<double>.Build.DenseOfColumnArrays(hcddMatrix); //Tuple<double, double> pSingular; double[] p = new double[3]; p[0] = 0; p[1] = 0; p[2] = 0; if (_pointPair.HeatingBalancePoint == 0 && _pointPair.CoolingBalancePoint == 0) { double[] onesVector = new double[readingsCount]; for (int i = 0; i < readingsCount; i++) { onesVector[i] = 1; } p[0] = Fit.LineThroughOrigin(onesVector, fullYDataAvg); } else if (_pointPair.CoolingBalancePoint != 0 && _pointPair.HeatingBalancePoint != 0) { p = MultipleRegression.QR(hcddMatrix, fullYDataAvg, intercept: true); } else if (_pointPair.CoolingBalancePoint == 0) { Tuple <double, double> heatingTuple = Fit.Line(avgHddsForEachReadingInYear, fullYDataAvg); p[0] = heatingTuple.Item1; p[1] = heatingTuple.Item2; } else if (_pointPair.HeatingBalancePoint == 0) { Tuple <double, double> coolingTuple = Fit.Line(avgCddsForEachReadingInYear, fullYDataAvg); p[0] = coolingTuple.Item1; p[2] = coolingTuple.Item2; } //double[] p = Fit.MultiDim(hcddMatrix, fullYDataAvg, intercept: true); //double[] fullXData_NewFit = new double[fullYDataAvg.Length]; double[] fullXData_NewFit = new double[readingsCount]; foreach (BalancePointPair balancePointPair in IdenticalBalancePointPairsForAllReadings) { double t1 = 0; if (IsDoubleNotNaNOrInfinity(p[0])) { t1 = p[0] * balancePointPair.DaysInReading; } double t2 = 0; if (IsDoubleNotNaNOrInfinity(p[1])) { t2 = p[1] * balancePointPair.HeatingDegreeDays; } double t3 = 0; if (IsDoubleNotNaNOrInfinity(p[2])) { t3 = p[2] * balancePointPair.CoolingDegreeDays; } fullXData_NewFit[IdenticalBalancePointPairsForAllReadings.IndexOf(balancePointPair)] = t1 + t2 + t3; } //double rBest = GoodnessOfFit.CoefficientOfDetermination( // hcddMatrix.Select(x => p[0] + (p[1] * x[0]) + (p[2] * x[1])), // fullYDataAvg); double rBest = GoodnessOfFit.CoefficientOfDetermination(fullXData_NewFit, fullYData); //double[,] comma = new double[hddsDailyArr.Length, hddsDailyArr.Length]; //for(int i = 0; i < hddsDailyArr.Length; i++) //{ // double left = xy[i / 2][0]; // double right = xy[i / 2][1]; // comma[i, i] = [left, right]; //} //double RSquared = GoodnessOfFit.CoefficientOfDetermination(xy.Select((x, y) => p[0], +(p[1] * xy[0]) + (p[2] * y)), ydata); //double RSquared = GoodnessOfFit.CoefficientOfDetermination(comma => p[0], +(p[1] * xy[0]) + (p[2] * y))), ydata); BalancePointPair groupLeader = _pointPair; double rSquared = GoodnessOfFit.CoefficientOfDetermination(fullXData, fullYData); //double rSquaredDaily = GoodnessOfFit.CoefficientOfDetermination(expUsageByDay, fullYDataByDay); double standardError_New = MathNet.Numerics.GoodnessOfFit.StandardError(fullXData, fullYData, groupLeader.ReadingsInNormalYear - 2); groupLeader.StandardError = standardError_New; if (!Double.IsNaN(rBest) && !Double.IsInfinity(rBest)) { groupLeader.RSquared_New = rBest; } else { groupLeader.RSquared_New = null; } groupLeader.B1_New = decimal.Round(Convert.ToDecimal(p[0]), 9, MidpointRounding.AwayFromZero); groupLeader.B2_New = decimal.Round(Convert.ToDecimal(p[1]), 9, MidpointRounding.AwayFromZero); groupLeader.B4_New = decimal.Round(Convert.ToDecimal(p[2]), 9, MidpointRounding.AwayFromZero); //if (NonWeatherDependant) //{ // groupLeader.RSquared = 0; // groupLeader.NewRSquaredNonWeather = 0; //double b = Fit.LineThroughOrigin(xDays, fullYData); //double[] newXData = new double[xDays.Length]; //for (int i = 0; i < newXData.Length; i++) //{ // newXData[i] = xDays[i] * b; //} //double NewRSquaredNonWeather = GoodnessOfFit.CoefficientOfDetermination(newXData, fullYData); //if (!Double.IsNaN(NewRSquaredNonWeather) && !Double.IsInfinity(NewRSquaredNonWeather)) //{ // groupLeader.NewRSquaredNonWeather = GoodnessOfFit.CoefficientOfDetermination(newXData, fullYData); // groupLeader.B1_New = decimal.Round(Convert.ToDecimal(b), 9, MidpointRounding.AwayFromZero); //} //else //{ // groupLeader.NewRSquaredNonWeather = null; // groupLeader.B1_New = null; //} //} updatedBalancePointPairs.Add(groupLeader); } return(updatedBalancePointPairs); }