Ниже приведен пример использования операции GetMs для расчёта уравнения. В запросе передаются: экземпляр открытого контейнера моделирования, шаблон расчёта уравнения и параметры выполнения операции. В ответе приходит экземпляр модели, содержащей уравнение с результатами расчёта.
Для выполнения примера уравнение должно рассчитываться методом «Линейная регрессия».
{
"Envelope" :
{
"Body" :
{
"GetMs" :
{
"tMs" :
{
"id" : "S69!M!S!C1"
},
"tArg" :
{
"pattern" :
{
"obInst" : "false",
"all" : "false",
"item" :
{
"key" : "3653",
"model" :
{
"transform" :
{
"formulas" :
{
"method" :
{
"linearRegression" :
{
"explained" : "true",
"explanatories" : "true" }, "series" : "true" } } }
} } }, "execParams" :
{
"k" : "0",
"pdlIndex" : "1",
"scenarioKeys" : "",
"execMethod" : "true",
"execCoefficients" : "true",
"execEvaluateSeries" : "true", "execPairCorrelationMatrix" : "true", "execARMACoefficients" : "true", "execPDLStatCoefficients" : "true",
"execStatCoefficients" : "true" } } } } } }
{
"Envelope" :
{
"Body" :
{
"GetMsResult" :
{
"id" :
{
"id" : "S69!M!S!C1"
},
"meta" :
{
"item" :
{
"k" : "3653",
"id" : "OBJ3653",
"n" : "OutputVarable[t] = A0 + A1*InputVarable_1[t] + PDL(TS(InputVarable_1[t+1] * 8, Linear), 1, 1) + [AR(1)=A2]",
"vis" : "1",
"type" : "Model",
"modelMd" :
{
"transform" :
{
"formulas" :
{
"its" :
{
"it" :
[
{
"k" : "0",
"kind" : "LinearRegression",
"method" :
{
"linearRegression" :
{
"constantMode" : "ManualEstimate",
"constantValue" : "0.500000",
"confidenceLevel" : "0.850000",
"ARMA" :
{
"orderAR" :
{
"l" : "1"
},
"orderMA" : "",
"calcInitMode" : "Auto", "initAR" : "", "initMA" : "", "initIntercept" : "0", "estimationMethod" : "LevenbergMarquardt", "tolerance" : "0.000100",
"maxIteration" : "500",
"coefficientsAR" :
{
"estimate" : "",
"standardError" : "",
"tStatistic" : "",
"probability" : ""
},
"coefficientsMA" :
{
"estimate" : "", "standardError" : "", "tStatistic" : "", "probability" : ""
}, "diff" : "0", "diffSeas" : "1", "orderARSeas" : "", "orderMASeas" : "", "initARSeas" : "",
"initMASeas" : "",
"periodSeas" : "0",
"coefficientsARSeas" :
{
"estimate" : "", "standardError" : "", "tStatistic" : "", "probability" : "" }, "coefficientsMASeas" :
{
"estimate" : "",
"standardError" : "",
"tStatistic" : "",
"probability" : "" }, "useARMAasInstrums" : "1", "useAnalyticDeriv" : "1", "useBackCast" : "1" },
"missingData" :
{
"specifiedVector" : "",
"method" : "Casewise",
"methodParameter" : "5",
"specifiedValue" : "0"
},
"explained" :
{
"slice" :
{
"k" : "0",
"id" : "301",
"n" : "OutputVarable",
"vis" : "1",
"variableKey" : "3655",
"stubKey" : "3394",
"selections" :
{
"its" :
{
"Item" :
{
"id" :
{
"id" : "3407"
},
"variant" : "301"
}
}
},
"aggregator" : "None",
"parametrizedDimensions" :
{
"its" :
{
"Item" :
{
"dimension" : "0",
"parameter" : "0"
} } }, "unitInfo" :
{
"unit" : "4294967295",
"measure" : "4294967295",
"baseUnit" : "4294967295",
"unitsDimensionKey" : "0"
},
"level" : "None" }, "lag" : "", "key" : "0",
"termToText" : "{OutputVarable[t]}",
"termToInnerText" : "@_3655:0[]",
"termInfo" :
{
"k" : "4294967295",
"lag" : "0",
"inversion" :
{
"type" : "None",
"lag" : "PrecidingValue",
"previousLag" : "-1", "seasonality" : "None", "dependence" : "Linear", "K" : "3" } },
"unitInfo" :
{
"unit" : "4294967295",
"measure" : "4294967295",
"baseUnit" : "4294967295",
"unitsDimensionKey" : "0"
}
},
"explanatories" :
{
"its" :
{
"Item" :
[
{
"k" : "0",
"expression" : "@_3654:0[]",
"operands" :
{
"its" :
{
"Item" :
{
"k" : "0",
"slice" :
{
"k" : "0",
"id" : "299",
"n" : "InputVarable_1",
"vis" : "1",
"variableKey" : "3654",
"stubKey" : "3394",
"selections" :
{
"its" :
{
"Item" :
{
"id" :
{
"id" : "3407" }, "variant" : "299" }
}
},
"aggregator" : "None",
"parametrizedDimensions" :
{
"its" :
{
"Item" :
{
"dimension" : "0",
"parameter" : "0"
}
}
},
"unitInfo" :
{
"unit" : "4294967295", "measure" : "4294967295", "baseUnit" : "4294967295", "unitsDimensionKey" : "0"
},
"level" : "None"
},
"lag" : "0",
"key" : "1",
"termToText" : "{InputVarable_1[t]}",
"termToInnerText" : "@_3654:0[]",
"termInfo" :
{
"k" : "4294967295",
"lag" : "0",
"inversion" :
{
"type" : "None",
"lag" : "PrecidingValue",
"previousLag" : "-1",
"seasonality" : "None", "dependence" : "Linear", "K" : "3" }
},
"unitInfo" :
{
"unit" : "4294967295",
"measure" : "4294967295",
"baseUnit" : "4294967295",
"unitsDimensionKey" : "0" } } }
},
"expressionText" : "{InputVarable_1[t]}",
"aggregationAttrKey" : "4294967295",
"inversedExpressionText" : "{InputVarable_1[t]}",
"missingData" :
{
"specifiedVector" : "", "method" : "Casewise", "methodParameter" : "5", "specifiedValue" : "0"
},
"applyMissingData" : "0",
"customOptions" :
{
"isPDLTerm" : "0",
"lagLengthK" : "1",
"polinomialDegreeP" : "0", "pdlConstraint" : "None" }, "unitInfo" :
{
"unit" : "4294967295",
"measure" : "4294967295",
"baseUnit" : "4294967295",
"unitsDimensionKey" : "0"
},
"inversion" :
{
"type" : "None",
"lag" : "PrecidingValue",
"previousLag" : "-1", "seasonality" : "None", "dependence" : "Linear", "K" : "3" }, "included" : "1"
},
{
"k" : "1",
"expression" : "@_3654:0[1] * 8",
"operands" :
{
"its" :
{
"Item" :
{
"k" : "0",
"slice" :
{
"k" : "0",
"id" : "299", "n" : "InputVarable_1", "vis" : "1", "variableKey" : "3654", "stubKey" : "3394", "selections" :
{
"its" :
{
"Item" :
{
"id" :
{
"id" : "3407"
},
"variant" : "299"
} } }, "aggregator" : "None",
"parametrizedDimensions" :
{
"its" :
{
"Item" :
{
"dimension" : "0", "parameter" : "0" } }
},
"unitInfo" :
{
"unit" : "4294967295",
"measure" : "4294967295",
"baseUnit" : "4294967295",
"unitsDimensionKey" : "0" }, "level" : "None" },
"lag" : "1",
"key" : "1",
"termToText" : "{InputVarable_1[t+1]}",
"termToInnerText" : "@_3654:0[1]",
"termInfo" :
{
"k" : "4294967295",
"lag" : "1",
"inversion" :
{
"type" : "None", "lag" : "PrecidingValue", "previousLag" : "-1", "seasonality" : "None", "dependence" : "Linear", "K" : "3"
}
},
"unitInfo" :
{
"unit" : "4294967295", "measure" : "4294967295", "baseUnit" : "4294967295", "unitsDimensionKey" : "0" } }
}
},
"expressionText" : "{InputVarable_1[t+1]} * 8",
"aggregationAttrKey" : "0",
"inversedExpressionText" : "TS({InputVarable_1[t+1]} * 8, Linear)",
"missingData" :
{
"specifiedVector" : "",
"method" : "SampleAverage",
"methodParameter" : "5",
"specifiedValue" : "0" }, "applyMissingData" : "1", "customOptions" :
{
"isPDLTerm" : "1",
"lagLengthK" : "1",
"polinomialDegreeP" : "1",
"pdlConstraint" : "None"
},
"unitInfo" :
{
"unit" : "4294967295",
"measure" : "4294967295",
"baseUnit" : "4294967295",
"unitsDimensionKey" : "0"
},
"inversion" :
{
"type" : "TS",
"lag" : "PrecidingValue", "previousLag" : "-1", "seasonality" : "Multiplicative", "dependence" : "Linear",
"K" : "3" }, "included" : "1" } ] }
},
"coefficients" :
{
"d" :
[ "1.073118", "-0.116538", "0.166538", "0.154868", "0.500000"
]
},
"pairCorrelationMatrix" :
{
"data" :
{
"d" :
[
"1.000000",
"0.190656",
"-0.138934", "0.190656", "1.000000", "-0.299905",
"-0.138934", "-0.299905", "1.000000" ] } },
"armaCoefficients" :
{
"orderAR" :
{
"l" : "1"
},
"orderMA" : "",
"coefficientsAR" :
{
"estimate" :
{
"d" : "0.154868"
},
"standardError" :
{
"d" : "0.283316"
},
"tStatistic" :
{
"d" : "0.546626"
},
"probability" :
{
"d" : "0.595550"
}
},
"coefficientsMA" :
{
"estimate" : "",
"standardError" : "",
"tStatistic" : "", "probability" : "" }, "orderARSeas" : "",
"orderMASeas" : "",
"coefficientsARSeas" :
{
"estimate" : "",
"standardError" : "",
"tStatistic" : "",
"probability" : ""
},
"coefficientsMASeas" :
{
"estimate" : "", "standardError" : "", "tStatistic" : "", "probability" : "" } },
"pdlStatCoefficients" :
{
"estimatesSum" : "0.000000",
"stdErrSum" : "0.000000",
"tStatSum" : "3.956295"
},
"statCoefficients" :
{
"intercept" :
{
"mode" : "ManualEstimate", "estimate" : "0.500000", "standardError" : "NaN", "tStatistic" : "NaN",
"probability" : "NaN"
},
"coefficients" :
{
"estimate" :
{
"d" : [ "1.073118", "-0.116538",
"0.166538"
]
},
"standardError" :
{
"d" :
[ "0.079693", "0.031170", "0.038124"
]
},
"tStatistic" :
{
"d" :
[
"13.465671", "-3.738762", "4.368336" ]
},
"probability" :
{
"d" :
[
"0.000000",
"0.003273", "0.001121" ] }
}
}
},
"name" : "Y = 0.5000 + 1.0731*X1 + PDL(TS(X2, Linear), 1, 1) + [AR(1)=0.1549]",
"series" :
{
"input" :
{
"k" : "4294967295",
"lag" : "0",
"inversion" :
{
"type" : "None",
"lag" : "PrecidingValue",
"previousLag" : "-1",
"seasonality" : "None",
"dependence" : "Linear", "K" : "3" } },
"addFactor" :
{
"k" : "4294967295"
}
},
"evaluateSeries" :
{
"its" :
{
"Item" :
{
"scenarioKey" : "4294967295",
"fact" :
{
"d" :
[
"8.300699", "12.145734", "10.734266", "13.630210",
"9.700000", "8.446713", "6.073986", "8.836084", "13.897902", "11.342657",
"10.065035", "12.352587", "8.872587", "7.424615",
"9.700000", "9.018601", "13.374685" ] }, "modelling" :
{
"d" :
[
"NaN",
"NaN", "11.156665", "10.807225", "7.915668", "10.456328", "9.590067",
"8.602428", "10.357007", "11.323473", "10.177215",
"10.506445", "11.028858", "9.750784", "9.108428", "10.461192", "12.181492"
]
},
"forecast" :
{
"d" : [ "NaN", "NaN", "NaN", "NaN",
"NaN", "NaN", "NaN", "NaN",
"NaN", "NaN", "NaN", "NaN", "NaN", "NaN",
"NaN", "NaN", "NaN", "2.493871",
"0.808786", "0.547821", "0.507406" ] }, "residuals" :
{
"d" :
[
"NaN",
"NaN", "-0.422399", "2.822984", "1.784332", "-2.009615", "-3.516081",
"0.233656", "3.540895", "0.019185", "-0.112180",
"1.846142", "-2.156270", "-2.326169", "0.591572", "-1.442591", "1.193193"
]
},
"upperConfidenceLevel" :
{
"d" : [ "NaN", "NaN", "NaN", "NaN",
"NaN", "NaN", "NaN", "NaN",
"NaN", "NaN", "NaN", "NaN", "NaN", "NaN",
"NaN", "NaN", "NaN", "16.212589",
"12.557956", "13.888379", "14.580753" ] }, "lowerConfidenceLevel" :
{
"d" :
[
"NaN",
"NaN", "NaN", "NaN", "NaN", "NaN", "NaN",
"NaN", "NaN", "NaN", "NaN",
"NaN", "NaN", "NaN", "NaN", "NaN", "NaN",
"7.237759", "3.476137", "4.804009", "5.496323"
]
}
}
},
"dates" :
{
"it" : [ "1990A1", "1991A1",
"1992A1", "1993A1", "1994A1", "1995A1", "1996A1", "1997A1",
"1998A1", "1999A1", "2000A1", "2001A1",
"2002A1", "2003A1", "2004A1", "2005A1", "2006A1", "2007A1",
"2008A1", "2009A1", "2010A1" ]
}
},
"inversionInfo" :
{
"type" : "None",
"lag" : "PrecidingValue",
"previousLag" : "-1", "seasonality" : "None", "dependence" : "Linear", "K" : "3"
} }, "calendarLevel" : "Year", "outputSliceKey" : "0" } ]
} } }, "warnings" : ""
} } } } } } }
Функция GetMsLinearRegr рассчитывает указанное уравнение. Входные параметры: экземпляр контейнера моделирования; ключ рассчитываемого уравнения. В результате выполнения функция возвращает модель, содержащую рассчитанное уравнение. Результаты расчёта выводятся в окно консоли. Для вывода результатов используются вспомогательные процедуры: printPDL, PrintSeries описанные в данном разделе; PrintCoef, printARMA, PrintArray, PrintSeries, описанные в разделе «Расчёт уравнения».
public static MsItem GetMsLinearRegr(MsId ms, ulong eqKey)
{
var getMsOp = new GetMs();
// Задаём параметры выполнения операции
getMsOp.tMs = ms;
getMsOp.tArg = new GetMsArg()
{ // Задаём шаблон извлечения данных
pattern = new MsMdPattern()
{
obInst = false,
all = false,
item = new MsItemPattern()
{ // Указываем ключ рассчитываемого уравнения
key = eqKey,
model = new MsModelPattern()
{
transform = new MsFormulaTransformPattern()
{
formulas = new TsFormulaPattern()
{
method = new TsMethodPattern()
{
linearRegression = new TsLinearRegressionMethodPattern()
{
explained = true,
explanatories = true
},
series = true
}
}
}
}
}
}, // Задаём параметры расчёта уравнения
execParams = new MsMdExecParams()
{
k = 0,
execMethod = true,
execEvaluateSeries = true,
scenarioKeys = new long[] { },
execPDLStatCoefficients = true,
pdlIndex = 1, execPairCorrelationMatrix = true, execStatCoefficients = true, execCoefficients = true, execARMACoefficients = true } }; // Создаем прокси-объект для выполнения операции var somClient = new SomPortTypeClient(); GetMsResult getMsResult = somClient.GetMs(getMsOp);
MsItem model = getMsResult.meta.item;
// Выводим ошибки и предупреждения
MsModel eq = model.modelMd;
if (eq.warnings != null)
{
Console.WriteLine("-- Предупреждения --");
Console.WriteLine("".PadRight(3) + printArray(eq.warnings));
}
if (eq.error == null) //Проверяем, возникли ли ошибки при расчёте уравнения
{ // Уравнение рассчитано без ошибок, получаем результаты расчёта
TsFormula formula = eq.transform.formulas.its.GetValue(0) as TsFormula;
TsLinearRegressionMethod linR = formula.method.linearRegression;
Console.WriteLine("-- Значения коэффициентов уравнения --");
Console.WriteLine("".PadRight(3) + printArray(linR.coefficients));
// Получаем значения коэффициентов уравнения и выводим в окно консоли
PrintCoef(linR.statCoefficients);
// Получаем значения коэффициентов авторегрессии, скользящего среднего и выводим в окно консоли
printARMA(linR.armaCoefficients);
Console.WriteLine("-- Матрица корреляции --");
MsPairCorrelationMatrix pm = linR.pairCorrelationMatrix;
if (pm.error != null) { Console.WriteLine("".PadRight(3) + "ошибка: " + pm.error); }
Console.WriteLine("".PadRight(3) + printArray(pm.data));
Console.WriteLine("-- Коэффициенты лаговых переменных --");
MsPDLCoefficients pdl = linR.pdlStatCoefficients;
printPDL(pdl);
// Выводим ряды, которые были рассчитаны
Console.WriteLine("-- Доступные ряды данных --");
printSeries(formula.method.series);
// Получаем рассчитанные значения и выводим в окно консоли
MsEvaluateSeriesResult seriesRes = formula.method.evaluateSeries;
printSeries(seriesRes);
}
else // При расчёте уравнения возникли ошибки
{
Console.WriteLine("-- Ошибки --");
Console.WriteLine(eq.error);
}
// Возвращаем модель, содержащую уравнение
return model;
}
// Процедура вывода значений коэффициентов для лаговых переменных
public static void printPDL(MsPDLCoefficients pdl)
{
Console.WriteLine("".PadRight(3) + " - cумма коэффициентов: " + pdl.estimatesSum);
Console.WriteLine("".PadRight(3) + " - cумма стандартных ошибок: " + pdl.stdErrSum);
Console.WriteLine("".PadRight(3) + " - cумма t-статистик: " + pdl.tStatSum);
Console.WriteLine("".PadRight(3) + " - Коэффициенты -");
PrintStatCoef(6, pdl as StatCoefficients);
}
// Процедура вывода идентификаторов рассчитанных рядов
public static void printSeries(MsMethodSeries series)
{
if (series.input != null)
{Console.WriteLine("".PadRight(3) + " - входной ряд");};
if (series.fitted != null)
{ Console.WriteLine("".PadRight(3) + " - сглаженный ряд"); };
if (series.forecast != null)
{ Console.WriteLine("".PadRight(3) + " - прогнозный ряд"); };
if (series.residuals != null)
{ Console.WriteLine("".PadRight(3) + " - ряд остатков"); };
if (series.lowerConfidenceLevel != null)
{ Console.WriteLine("".PadRight(3) + " - нижняя доверительная граница"); };
if (series.upperConfidenceLevel != null)
{ Console.WriteLine("".PadRight(3) + " - верхняя доверительная граница"); };
if (series.dynamicLowerConfidenceLevel != null)
{ Console.WriteLine("".PadRight(3) + " - нижняя динамическая доверительная граница"); };
if (series.dynamicUpperConfidenceLevel != null)
{ Console.WriteLine("".PadRight(3) + " - верхняя динамическая доверительная граница"); };
if (series.addFactor != null)
{ Console.WriteLine("".PadRight(3) + " - фактор корректировки прогноза"); };
}
См. также:
Работа с контейнером моделирования | Метод «Линейная регрессия»
SOAP