public void ComputationShouldWaitOnCompletion() { Computation<int> computation = new Computation<int>((x) => { Console.WriteLine(++x); }); int state = 0; computation.Run(state); computation.WaitForCompletion(); Assert.IsTrue(computation.Cookie.WasWaitingForCompletion); Assert.IsTrue(computation.Cookie.Completed); }
public void ComputationShouldRun() { Computation<int> computation = new Computation<int>((x) => { Thread.Sleep(100); Console.WriteLine(x); }); int state = 0; computation.Run(state); Assert.IsFalse(computation.Cookie.WasWaitingForCompletion); Assert.IsFalse(computation.Cookie.Completed); Thread.Sleep(200); Assert.IsTrue(computation.Cookie.Completed); }
public void ComputationShouldRunWithExceptionAndHandleIt() { Computation<int> computation = new Computation<int>((x) => { int zero = 0; int res = x / zero; Console.WriteLine(res); }); try { int state = 0; computation.Run(state); } catch (ComputationException ex) { Assert.IsTrue(computation.Cookie.IsException); Assert.AreEqual(computation.Cookie.Exception, ex); Assert.IsInstanceOfType(ex.InnerException, typeof(DivideByZeroException)); } }
/** * Constructs a bind computation with the given sub-computation and * function to produce the next sub-computation. * * @param m the first sub-computation. * @param f the function to produce the second sub-computation. */ public Bind(Computation c, IComputationFactory f) { this.c = c; this.f = f; }
public void SetModelBuilderState(bool includeBuilder) { AssertIsForeground(); Computation.ChainTaskAndNotifyControllerWhenFinished(model => SetModelBuilderStateInBackground(model, includeBuilder)); }
/// <summary> /// Reads the contents of all binary files in an Azure directory into a Naiad stream. /// </summary> /// <typeparam name="R">Type of records stored in the blobs</typeparam> /// <param name="manager">Graph manager</param> /// <param name="container">Azure container</param> /// <param name="prefix">Azure blob prefix</param> /// <param name="reader">Decoding function from a binary reader to a sequence of records</param> /// <returns>Naiad stream containing the records extracted from files in the Azure directory</returns> public static Stream <R, Epoch> ReadCustomBinaryFromAzureBlobs <R>(this Computation manager, CloudBlobContainer container, string prefix, Func <System.IO.BinaryReader, IEnumerable <R> > reader) { return(manager.ReadFromAzureBlobs <R>(container, prefix, s => reader(new System.IO.BinaryReader(s)))); }
protected override void HandleReadyComputation(Computation computation) { parent.CreateLeftToRightSynchronization(true, (SynchronizationComputation <TLeft, TRight>)computation); }
void Start() { camera = GameObject.FindWithTag("MainCamera"); script = camera.GetComponent <Computation>(); }
public static void DemoPH() { Console.WriteLine("Демонстрация работы с классом PH"); double mu1 = 2; double mu2 = 2; double mu3 = 2; double mu4 = 2; double mu5 = 2; double mu6 = 2; double[,] A1 = { { -mu1 } }; double[] alpha1 = { 1 }; double[,] A2 = { { -mu2, 0.5 * mu2, 0 }, { 0, -mu4, 0.5 * mu4 }, { 0, mu5, -mu5 } }; double[] alpha2 = { 1, 0, 0 }; double[,] A3 = { { -mu2, mu2, 0 }, { 0, -mu4, 0.2 * mu4 }, { 0, 0.7 * mu5, -mu5 } }; double[] alpha3 = { 1, 0, 0 }; double[,] A4 = { { -mu5, 0.7 * mu5 }, { 0.2 * mu4, -mu4 } }; double[] alpha4 = { 1, 0 }; double[,] A5 = { { -mu3, 0.7 * mu3, 0, 0 }, { 0, -mu2, mu2, 0 }, { 0, 0, -mu4, 0.2 * mu4 }, { 0, 0, 0.7 * mu5, -mu5 } }; double[] alpha5 = { 1, 0, 0, 0 }; PhaseTypeVarible A1PH = new PhaseTypeVarible(new Matrix(A1), alpha1); PhaseTypeVarible A2PH = new PhaseTypeVarible(new Matrix(A2), alpha2); PhaseTypeVarible A3PH = new PhaseTypeVarible(new Matrix(A3), alpha3); PhaseTypeVarible A4PH = new PhaseTypeVarible(new Matrix(A4), alpha4); PhaseTypeVarible A5PH = new PhaseTypeVarible(new Matrix(A5), alpha5); // calculate PH Matrix of maximum of times for D1->S1 and D1->S2 PhaseTypeVarible B12 = PHOperations.Max(A1PH, A2PH); PhaseTypeVarible B34 = PHOperations.Max(A3PH, A4PH); // PH B345 = PHOperations.Max({ B34, A5PH); PhaseTypeVarible[] variable = { A3PH, A4PH, A5PH }; PhaseTypeVarible B345 = PHOperations.Max(variable); Matrix gamma12 = new Matrix(1, B12.NumberOfPhases); for (int i = 0; i < B12.NumberOfPhases; i++) { gamma12[0, i] = B12.InitialDistribution[i]; } Matrix gamma345 = new Matrix(1, B345.NumberOfPhases); for (int i = 0; i < B345.NumberOfPhases; i++) { gamma345[0, i] = B345.InitialDistribution[i]; } Matrix tau12 = -gamma12 * (B12.SubGenerator.Inv()) * Computation.OnesColumn(B12.NumberOfPhases); Matrix tau345 = -gamma345 * (B345.SubGenerator.Inv()) * Computation.OnesColumn(B345.NumberOfPhases); Matrix tau = 0.5 * tau12 + 0.5 * tau345; double t = tau[0, 0] + 1 / mu6; Console.WriteLine("{0:f6} ", t); }
public TModel WaitForController() { AssertIsForeground(); return(Computation.WaitForController()); }
public bool TryEvaluateExpression(Entry value, Store context, out Entry result) { //list if (value.Type == TermType.Function && value.ArgsCount == 1 && value.Text == "list") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); TNumber tmp = Computation.NumericCalculation(arg1, context); TDouble n = (TDouble)tmp.obj; //List<string> vector = new List<string>(Utilites.EntryMatrix2ArrStr(tmp.obj)); //vector.RemoveAt(vector.Count - 1); //vector.RemoveAt(vector.Count - 1); //List<string> distinct = vector.Distinct().ToList(); List <Term> answer = new List <Term>(); if (n.D <= 0) { answer.AddRange(TermsConverter.ToTerms(0.ToString())); } else { for (int i = 0; i < n.D; i++) { answer.AddRange(TermsConverter.ToTerms("0")); } answer.AddRange(TermsConverter.ToTerms(n.D.ToString())); } answer.AddRange(TermsConverter.ToTerms(1.ToString())); answer.Add(new Term(Functions.Mat, TermType.Function, 2 + (int)n.D)); result = Entry.Create(answer.ToArray()); return(true); } //listLength if (value.Type == TermType.Function && value.ArgsCount == 1 && value.Text == "listLength") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); List <string> vector = new List <string>(Utilites.EntryMatrix2ArrStr(arg1)); List <Term> answer = new List <Term>(); if (vector.Count <= 2) { answer.AddRange(TermsConverter.ToTerms("0")); } else { answer.AddRange(TermsConverter.ToTerms(vector[vector.Count - 2])); } result = Entry.Create(answer.ToArray()); return(true); } //listDistinct if (value.Type == TermType.Function && value.ArgsCount == 1 && value.Text == "listDistinct") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); TNumber tmp = Computation.NumericCalculation(arg1, context); List <string> vector = new List <string>(Utilites.EntryMatrix2ArrStr(tmp.obj)); //vector.RemoveAt(vector.Count - 1); //vector.RemoveAt(vector.Count - 1); List <string> distinct = vector.Distinct().ToList(); List <Term> answer = new List <Term>(); foreach (string item in distinct) { answer.AddRange(TermsConverter.ToTerms(item)); } answer.AddRange(TermsConverter.ToTerms(distinct.Count.ToString())); answer.AddRange(TermsConverter.ToTerms(1.ToString())); answer.Add(new Term(Functions.Mat, TermType.Function, 2 + distinct.Count)); result = Entry.Create(answer.ToArray()); return(true); } //listSortAsText if (value.Type == TermType.Function && value.ArgsCount == 1 && value.Text == "listSortAsText") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); TNumber tmp = Computation.NumericCalculation(arg1, context); BaseEntry be = tmp.obj; Term[] res = be.ToTerms(16, 16, FractionsType.Decimal, true); tmp = Computation.NumericCalculation(Entry.Create(res), context); List <string> vector = new List <string>(Utilites.EntryMatrix2ArrStr(tmp.obj)); if (be.Type == BaseEntryType.Matrix) { vector.RemoveAt(vector.Count - 1); vector.RemoveAt(vector.Count - 1); vector.Sort(); } List <Term> answer = new List <Term>(); foreach (string item in vector) { answer.AddRange(TermsConverter.ToTerms(item)); } answer.AddRange(TermsConverter.ToTerms(vector.Count.ToString())); answer.AddRange(TermsConverter.ToTerms(1.ToString())); answer.Add(new Term(Functions.Mat, TermType.Function, 2 + vector.Count)); result = Entry.Create(answer.ToArray()); return(true); } //listAdd if (value.Type == TermType.Function && value.ArgsCount == 2 && value.Text == "listAdd") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); TNumber tmp, tmp1; TMatrix m; try { tmp = Computation.NumericCalculation(arg1, context); tmp1 = Computation.NumericCalculation(arg2, context); TNumber count = tmp.Rows(); m = tmp.Stack(new TNumber[] { new TNumber(0, 1) }); m[count.ToInt32(), 0] = tmp1; } catch { tmp1 = Computation.NumericCalculation(arg2, context); m = new TMatrix(new TNumber[, ] { }); m[0, 0] = tmp1; } result = Entry.Create(m.ToTerms()); return(true); } //listNonZeros if (value.Type == TermType.Function && value.ArgsCount == 1 && value.Text == "listNonZeros") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); TNumber tmp = Computation.NumericCalculation(arg1, context); List <string> vector = new List <string>(Utilites.EntryMatrix2ArrStr(tmp.obj)); vector.RemoveAt(vector.Count - 1); vector.RemoveAt(vector.Count - 1); IEnumerable <string> select = from t in vector // определяем каждый объект из teams как t where t != "0" //фильтрация по критерию select t; // выбираем объект List <string> nonZeros = new List <string>(select); List <Term> answer = new List <Term>(); foreach (string item in nonZeros) { answer.AddRange(TermsConverter.ToTerms(item)); } answer.AddRange(TermsConverter.ToTerms(nonZeros.Count.ToString())); answer.AddRange(TermsConverter.ToTerms(1.ToString())); answer.Add(new Term(Functions.Mat, TermType.Function, 2 + nonZeros.Count)); result = Entry.Create(answer.ToArray()); return(true); } //if (value.Type == TermType.Function && value.ArgsCount == 2 && value.Text == "listDistinct") //{ // Entry arg1 = Computation.Preprocessing(value.Items[0], context); // Entry arg2 = Computation.Preprocessing(value.Items[1], context); // int dir = Utilites.Entry2Int(arg2); // TNumber tmp = Computation.NumericCalculation(arg1, context); // List<string> vector = new List<string>(Utilites.EntryMatrix2ArrStr(tmp.obj)); // vector.RemoveAt(vector.Count - 1); // vector.RemoveAt(vector.Count - 1); // List<string> distinct = vector.Distinct().ToList(); // //string res = "null"; // List<Term> answer = new List<Term>(); // foreach (string item in distinct) // { // answer.AddRange(TermsConverter.ToTerms(item)); // } // if (dir==0) // { // answer.AddRange(TermsConverter.ToTerms(distinct.Count.ToString())); // answer.AddRange(TermsConverter.ToTerms(1.ToString())); // answer.Add(new Term(Functions.Mat, TermType.Function, 2 + distinct.Count)); // } // else // { // answer.AddRange(TermsConverter.ToTerms(1.ToString())); // answer.AddRange(TermsConverter.ToTerms(distinct.Count.ToString())); // answer.Add(new Term(Functions.Mat, TermType.Function, 2 + distinct.Count)); // } // result = Entry.Create(answer.ToArray()); // return true; //} if (value.Type == TermType.Function && value.ArgsCount == 2 && value.Text == "listRemoveAt") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); BaseEntry be1 = tmp1.obj; BaseEntry be2 = tmp2.obj; List <string> vector = new List <string>(Utilites.EntryMatrix2ArrStr(be1)); if (be1.Type == BaseEntryType.Matrix) { vector.RemoveAt(vector.Count - 1); vector.RemoveAt(vector.Count - 1); vector.RemoveAt((int)be2.ToDouble() - 1); } List <Term> answer = new List <Term>(); foreach (string item in vector) { answer.AddRange(TermsConverter.ToTerms(item)); } answer.AddRange(TermsConverter.ToTerms(vector.Count.ToString())); answer.AddRange(TermsConverter.ToTerms(1.ToString())); answer.Add(new Term(Functions.Mat, TermType.Function, 2 + vector.Count)); result = Entry.Create(answer.ToArray()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 3 && value.Text == "listRemoveRange") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); Entry arg3 = Computation.Preprocessing(value.Items[2], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); TNumber tmp3 = Computation.NumericCalculation(arg3, context); BaseEntry be1 = tmp1.obj; BaseEntry be2 = tmp2.obj; BaseEntry be3 = tmp3.obj; List <string> vector = new List <string>(Utilites.EntryMatrix2ArrStr(be1)); if (be1.Type == BaseEntryType.Matrix) { vector.RemoveAt(vector.Count - 1); vector.RemoveAt(vector.Count - 1); vector.RemoveRange((int)be2.ToDouble() - 1, (int)be3.ToDouble()); } List <Term> answer = new List <Term>(); foreach (string item in vector) { answer.AddRange(TermsConverter.ToTerms(item)); } answer.AddRange(TermsConverter.ToTerms(vector.Count.ToString())); answer.AddRange(TermsConverter.ToTerms(1.ToString())); answer.Add(new Term(Functions.Mat, TermType.Function, 2 + vector.Count)); result = Entry.Create(answer.ToArray()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 3 && value.Text == "listInsert") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); Entry arg3 = Computation.Preprocessing(value.Items[2], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); TNumber tmp3 = Computation.NumericCalculation(arg3, context); BaseEntry be1 = tmp1.obj; BaseEntry be2 = tmp2.obj; BaseEntry be3 = tmp3.obj; List <string> vector = new List <string>(Utilites.EntryMatrix2ArrStr(be1)); if (be1.Type == BaseEntryType.Matrix) { vector.RemoveAt(vector.Count - 1); vector.RemoveAt(vector.Count - 1); vector.Insert((int)be2.ToDouble() - 1, be3.ToString()); } List <Term> answer = new List <Term>(); foreach (string item in vector) { answer.AddRange(TermsConverter.ToTerms(item)); } answer.AddRange(TermsConverter.ToTerms(vector.Count.ToString())); answer.AddRange(TermsConverter.ToTerms(1.ToString())); answer.Add(new Term(Functions.Mat, TermType.Function, 2 + vector.Count)); result = Entry.Create(answer.ToArray()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 3 && value.Text == "listInsertRange") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); Entry arg3 = Computation.Preprocessing(value.Items[2], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); TNumber tmp3 = Computation.NumericCalculation(arg3, context); BaseEntry be1 = tmp1.obj; BaseEntry be2 = tmp2.obj; BaseEntry be3 = tmp3.obj; List <string> vector = new List <string>(Utilites.EntryMatrix2ArrStr(be1)); List <string> vector1 = new List <string>(Utilites.EntryMatrix2ArrStr(be3)); if (be1.Type == BaseEntryType.Matrix) { vector.RemoveAt(vector.Count - 1); vector.RemoveAt(vector.Count - 1); vector1.RemoveAt(vector.Count - 1); vector1.RemoveAt(vector.Count - 1); vector.InsertRange((int)be2.ToDouble() - 1, vector1); } List <Term> answer = new List <Term>(); foreach (string item in vector) { answer.AddRange(TermsConverter.ToTerms(item)); } answer.AddRange(TermsConverter.ToTerms(vector.Count.ToString())); answer.AddRange(TermsConverter.ToTerms(1.ToString())); answer.Add(new Term(Functions.Mat, TermType.Function, 2 + vector.Count)); result = Entry.Create(answer.ToArray()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 3 && value.Text == "insertRows") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); Entry arg3 = Computation.Preprocessing(value.Items[2], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); TNumber tmp3 = Computation.NumericCalculation(arg3, context); MatrixL <TNumber> matrixL = Utilites.TMatrixToMatrixL(tmp1); for (int i = 0; i < tmp3.ToInt32(); i++) { matrixL.InsertRow(tmp2.ToInt32() - 1); } TMatrix m = Utilites.MatrixLToTMatrix(matrixL); result = Entry.Create(m.ToTerms()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 3 && value.Text == "insertRow") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); Entry arg3 = Computation.Preprocessing(value.Items[2], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); TNumber tmp3 = Computation.NumericCalculation(arg3, context); MatrixL <TNumber> matrixL = Utilites.TMatrixToMatrixL(tmp1); List <TNumber> vectorL = Utilites.TMatrixToMatrixL(tmp3).ToList(); matrixL.InsertRow(tmp2.ToInt32() - 1, vectorL); TMatrix m = Utilites.MatrixLToTMatrix(matrixL); result = Entry.Create(m.ToTerms()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 3 && value.Text == "insertCols") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); Entry arg3 = Computation.Preprocessing(value.Items[2], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); TNumber tmp3 = Computation.NumericCalculation(arg3, context); MatrixL <TNumber> matrixL = Utilites.TMatrixToMatrixL(tmp1); for (int i = 0; i < tmp3.ToInt32(); i++) { matrixL.InsertCol(tmp2.ToInt32() - 1); } TMatrix m = Utilites.MatrixLToTMatrix(matrixL); result = Entry.Create(m.ToTerms()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 3 && value.Text == "insertCol") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); Entry arg3 = Computation.Preprocessing(value.Items[2], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); TNumber tmp3 = Computation.NumericCalculation(arg3, context); MatrixL <TNumber> matrixL = Utilites.TMatrixToMatrixL(tmp1); List <TNumber> vectorL = Utilites.TMatrixToMatrixL(tmp3).ToList(); matrixL.InsertCol(tmp2.ToInt32() - 1, vectorL); TMatrix m = Utilites.MatrixLToTMatrix(matrixL); result = Entry.Create(m.ToTerms()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 3 && value.Text == "removeRows") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); Entry arg3 = Computation.Preprocessing(value.Items[2], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); TNumber tmp3 = Computation.NumericCalculation(arg3, context); MatrixL <TNumber> matrixL = Utilites.TMatrixToMatrixL(tmp1); for (int i = 0; i < tmp3.ToInt32(); i++) { matrixL.RemoveRowAt(tmp2.ToInt32() - 1); } TMatrix m = Utilites.MatrixLToTMatrix(matrixL); result = Entry.Create(m.ToTerms()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 3 && value.Text == "removeCols") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); Entry arg3 = Computation.Preprocessing(value.Items[2], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); TNumber tmp3 = Computation.NumericCalculation(arg3, context); MatrixL <TNumber> matrixL = Utilites.TMatrixToMatrixL(tmp1); for (int i = 0; i < tmp3.ToInt32(); i++) { matrixL.RemoveColAt(tmp2.ToInt32() - 1); } TMatrix m = Utilites.MatrixLToTMatrix(matrixL); result = Entry.Create(m.ToTerms()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 1 && value.Text == "nonZerosRows") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); MatrixL <TNumber> matrixL = Utilites.TMatrixToMatrixL(tmp1); List <int> indexes = new List <int>(matrixL.R); List <TNumber> row; List <double> rowD; int j = 0; for (int i = 0; i < matrixL.R; i++) { row = matrixL.Row(i); rowD = new List <double>(matrixL.C); foreach (TNumber item in row) { if (item.obj.Type != BaseEntryType.Double) { break; } //if (item.obj.ToDouble() != 0) break; try { rowD.Add(item.obj.ToDouble()); } catch { break; } } rowD = rowD.Distinct().ToList(); if (rowD.Count == 1 && rowD[0] == 0) { indexes.Add(i - j); j++; } } if (indexes.Count > 0) { foreach (int item in indexes) { matrixL.RemoveRowAt(item); } } TMatrix m = Utilites.MatrixLToTMatrix(matrixL); result = Entry.Create(m.ToTerms()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 1 && value.Text == "nonZerosRowsCols") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); MatrixL <TNumber> matrixL = Utilites.TMatrixToMatrixL(tmp1); List <int> indexes = new List <int>(matrixL.R); List <TNumber> row; List <double> rowD; int j = 0; for (int i = 0; i < matrixL.R; i++) { row = matrixL.Row(i); rowD = new List <double>(matrixL.C); foreach (TNumber item in row) { if (item.obj.Type != BaseEntryType.Double) { break; } //if (item.obj.ToDouble() != 0) break; try { rowD.Add(item.obj.ToDouble()); } catch { break; } } rowD = rowD.Distinct().ToList(); if (rowD.Count == 1 && rowD[0] == 0) { indexes.Add(i - j); j++; } } if (indexes.Count > 0) { foreach (int item in indexes) { matrixL.RemoveRowAt(item); } } indexes = new List <int>(matrixL.C); List <TNumber> col; List <double> colD; j = 0; for (int i = 0; i < matrixL.C; i++) { col = matrixL.Col(i); colD = new List <double>(matrixL.R); foreach (TNumber item in col) { if (item.obj.Type != BaseEntryType.Double) { break; } //if (item.obj.ToDouble() != 0) break; try { colD.Add(item.obj.ToDouble()); } catch { break; } } colD = colD.Distinct().ToList(); if (colD.Count == 1 && colD[0] == 0) { indexes.Add(i - j); j++; } } if (indexes.Count > 0) { foreach (int item in indexes) { matrixL.RemoveColAt(item); } } TMatrix m = Utilites.MatrixLToTMatrix(matrixL); result = Entry.Create(m.ToTerms()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 1 && value.Text == "nonZerosCols") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); MatrixL <TNumber> matrixL = Utilites.TMatrixToMatrixL(tmp1); List <int> indexes = new List <int>(matrixL.C); List <TNumber> col; List <double> colD; int j = 0; for (int i = 0; i < matrixL.C; i++) { col = matrixL.Col(i); colD = new List <double>(matrixL.R); foreach (TNumber item in col) { if (item.obj.Type != BaseEntryType.Double) { break; } //if (item.obj.ToDouble() != 0) break; try { colD.Add(item.obj.ToDouble()); } catch { break; } } colD = colD.Distinct().ToList(); if (colD.Count == 1 && colD[0] == 0) { indexes.Add(i - j); j++; } } if (indexes.Count > 0) { foreach (int item in indexes) { matrixL.RemoveColAt(item); } } TMatrix m = Utilites.MatrixLToTMatrix(matrixL); result = Entry.Create(m.ToTerms()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 4 && value.Text == "putMatrix") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); Entry arg3 = Computation.Preprocessing(value.Items[2], context); Entry arg4 = Computation.Preprocessing(value.Items[3], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); TNumber tmp3 = Computation.NumericCalculation(arg3, context); TNumber tmp4 = Computation.NumericCalculation(arg4, context); if (tmp3.ToInt32() < 1 || tmp4.ToInt32() < 1) { throw new ArgumentException("Неверно задана индексация"); } int adressR = tmp3.ToInt32() - 1; int adressC = tmp4.ToInt32() - 1; MatrixL <TNumber> matrixL1 = Utilites.TMatrixToMatrixL(tmp1); MatrixL <TNumber> matrixL2 = Utilites.TMatrixToMatrixL(tmp2); int n = matrixL1.R - adressR; int m = matrixL1.C - adressC; if (n > matrixL2.R) { n = matrixL2.R; } if (m > matrixL2.C) { m = matrixL2.C; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrixL1[adressR + i, adressC + j] = matrixL2[i, j]; } } TMatrix mat = Utilites.MatrixLToTMatrix(matrixL1); result = Entry.Create(mat.ToTerms()); return(true); } if (value.Type == TermType.Function && value.ArgsCount == 4 && value.Text == "insertMatrix") { Entry arg1 = Computation.Preprocessing(value.Items[0], context); Entry arg2 = Computation.Preprocessing(value.Items[1], context); Entry arg3 = Computation.Preprocessing(value.Items[2], context); Entry arg4 = Computation.Preprocessing(value.Items[3], context); TNumber tmp1 = Computation.NumericCalculation(arg1, context); TNumber tmp2 = Computation.NumericCalculation(arg2, context); TNumber tmp3 = Computation.NumericCalculation(arg3, context); TNumber tmp4 = Computation.NumericCalculation(arg4, context); if (tmp3.ToInt32() < 1 || tmp4.ToInt32() < 1) { throw new ArgumentException("Неверно задана индексация"); } int adressR = tmp3.ToInt32() - 1; int adressC = tmp4.ToInt32() - 1; MatrixL <TNumber> matrixL1 = Utilites.TMatrixToMatrixL(tmp1); MatrixL <TNumber> matrixL2 = Utilites.TMatrixToMatrixL(tmp2); for (int i = 0; i < matrixL2.R; i++) { matrixL1.InsertRow(adressR); } for (int i = 0; i < matrixL2.C; i++) { matrixL1.InsertCol(adressC); } int n = matrixL1.R - adressR; int m = matrixL1.C - adressC; if (n > matrixL2.R) { n = matrixL2.R; } if (m > matrixL2.C) { m = matrixL2.C; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrixL1[adressR + i, adressC + j] = matrixL2[i, j]; } } TMatrix mat = Utilites.MatrixLToTMatrix(matrixL1); result = Entry.Create(mat.ToTerms()); return(true); } result = null; return(false); }
public ActionResult Index(double?firstNumber, double?secondNumber, string expression) { var computations = new List <Computation>(); using (var db = new CalculatorContext()) { computations.AddRange(db.Computations); } if (firstNumber.HasValue && secondNumber.HasValue) { OperationType type; double result; switch (expression) { case "*": result = firstNumber.Value * secondNumber.Value; type = OperationType.Multiplication; break; case "/": if (secondNumber.Value == 0) { this.ViewBag.Result = "Error"; return(this.View(computations)); } type = OperationType.Divide; result = firstNumber.Value / secondNumber.Value; break; case "+": type = OperationType.Addition; result = firstNumber.Value + secondNumber.Value; break; case "-": type = OperationType.Divison; result = firstNumber.Value - secondNumber.Value; break; default: this.ViewBag.Result = "Error"; return(this.View(computations)); } var host = Dns.GetHostEntry(Dns.GetHostName()); var ip = host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork)?.ToString(); using (var db = new CalculatorContext()) { var computation = new Computation { Date = DateTime.Now, Ip = ip, Operation = type, Result = result }; db.Computations.Add(computation); db.SaveChanges(); } return(RedirectToAction("Index")); } return(this.View(computations)); }
/// <summary> /// Wraps the given computation into a typed wrapping structure /// </summary> /// <param name="inner">The computation that is to be wrapped</param> public InPlaceComputationWrapper(Computation inner) { this.c = inner; }
public PrefixExtender <TPrefix, TValue> CreateExtender <TPrefix>(Computation computation, Func <TPrefix, TKey> prefixKeySelector) { return(new Extender <TPrefix>(computation.NewInput(result.NewDataSource()), prefixKeySelector)); }
/// <summary> /// Wraps the given computation into a typed wrapping structure /// </summary> /// <param name="inner">The computation that is to be wrapped</param> public TransformationComputationWrapper(Computation inner) { this.c = inner; }
// in Form_Load the panel and all shapes should be created // and initialized. private void Form1_Load(object sender, EventArgs e) { // the ILPanel is created ... m_panel = ILPanel.Create(); // and added to the Controls collection of the form Controls.Add(m_panel); // a scene graph will hold our shapes ILSceneGraph scene = m_panel.Graphs.AddSceneGraph(); // data for the shapes are best created in the Computation // helper - keeping the GUI code clean ILCell data = Computation.CreatePendulaWeight(); // setup the first polygon. For creation we do // not specify vertex data yet. This will be done // later in the UpdateShapes function m_poly1 = new ILLitPolygon(m_panel, data[0].Dimensions[1]); m_poly1.Border.Width = 2; m_poly1.Border.Color = Color.Gray; m_poly1.Opacity = 180; m_poly1.CustomCenter = new ILPoint3Df(0, 0, 1); m_poly1.Label.Text = ""; // and add it to the scene. We create an individual node // for the weight' shapes. ILSceneGraphInnerNode weightNode = new ILSceneGraphInnerNode(m_panel); scene.AddNode(weightNode); weightNode.Add(m_poly1); // setup the 2nd polygon. The same size is here used as // for the first polygon. m_poly2 = new ILLitPolygon(m_panel, data[0].Dimensions[1]); m_poly2.Border.Width = 2; m_poly2.Border.Color = Color.Gray; m_poly2.Opacity = 180; m_poly2.Label.Text = ""; m_poly2.CustomCenter = new ILPoint3Df(0, 0, 1); weightNode.Add(m_poly2); // the same for the quads: only give the number // of vertices needed. Data are updated later m_quads = new ILLitQuads(m_panel, data[0].Dimensions[1] * 2); m_quads.FillColor = Color.Red; m_quads.Opacity = 180; m_quads.Label.Text = ""; m_quads.CustomCenter = new ILPoint3Df(0, 0, 1); // add the quads to the scene weightNode.Add(m_quads); // create the scale below the pendula weight ILCell lData = Computation.CreateScale(); ILArray <double> vert = lData[0] as ILArray <double>; ILArray <double> maps = lData[1] as ILArray <double>; m_lines = new ILLines(m_panel, vert[0.0, null], vert[1.0, null], vert[2.0, null], maps); m_lines.Label.Text = ""; m_lines.Properties.Color = Color.Black; m_lines.Shading = ShadingStyles.Flat; // the scale lines we put directly in the root node // (no need to create an extra inner node for them) scene.AddNode(m_lines); // initialize the shapes UpdateShapes(data); // Experiment with these panel settings! They get clear than! //m_panel.PlotBoxScreenSizeMode = PlotBoxScreenSizeMode.StrictOptimal; // default: Optimal //m_panel.AutoZoomContent = false; // (default: true) m_panel.AspectRatio = AspectRatioMode.MaintainRatios; //m_panel.Projection = Projection.Perspective; m_panel.InteractiveMode = InteractiveModes.Rotating; // setup the timer control m_timer = new Timer(); m_timer.Interval = 40; m_timer.Tick += new EventHandler(m_timer_Tick); m_timer.Start(); }
// in the event handler, new data are created on every tick void m_timer_Tick(object sender, EventArgs e) { UpdateShapes(Computation.CreatePendulaWeight()); // do not to forget to refresh the panel after all updates are done m_panel.Refresh(); }
public bool ProcessMacro(int macroId, long affiliateId) { var qry = Queries.Affiliate_MacroeconomicVariable(affiliateId); var dt = DataAccess.i.GetData(qry); foreach (DataRow dr in dt.Rows) { affM.Add(DataAccess.i.ParseDataToObject(new AffiliateMacroEconomicVariableOffsets(), dr)); } var lstMacroData = GeneratesaveMacroData(affiliateId, macroId); ProcessMacroAnalysis(affiliateId, macroId); //return true; // Read Eingen final to determine the comp to consider var EingenFinalPath = Path.Combine(AppSettings.MacroModelPath, affiliateId.ToString(), "ETI_Eingen_Final.csv"); var all_Eingen = File.ReadAllLines(EingenFinalPath); var eIngenValues = new List <double>(); for (int i = 1; i < all_Eingen.Count(); i++) { eIngenValues.Add(double.Parse(all_Eingen[i].Split(',')[1])); if (i == 5) { break; } } // Read loading final to determine the comp to consider var LoadingFinalPath = Path.Combine(AppSettings.MacroModelPath, affiliateId.ToString(), "ETI_Loadings_Final.csv"); var all_loadingFinal = File.ReadAllLines(LoadingFinalPath); var dataLoaded = new List <List <double> >(); var macvarCol = new List <string>(); var colCount = 0; for (int i = 0; i < all_loadingFinal.Length; i++) { if (i == 0) { continue; } var splitted = all_loadingFinal[i].Split(','); macvarCol.Add(splitted[0]); splitted = splitted.Skip(1).ToArray(); colCount = splitted.Count(); var _joined = string.Join(",", splitted); dataLoaded.Add(_joined.Split(',').Select(r => Convert.ToDouble(r)).ToArray().ToList()); } var loadingOutputResult = new List <List <double> >(); var finalMaxIndex = new List <int>(); var actual_macvar = new List <AffiliateMacroEconomicVariableOffsets>(); for (int i = 0; i < colCount; i++) { var tempResult = new List <double>(); foreach (var ln in dataLoaded) { var val = ln[i]; if (val < 0) { val = val * -1; } tempResult.Add(val); } var _indx = tempResult.Select((n, j) => (Number: n, Index: j)).Max().Index; var tkVal = affM.Count >= 4 ? 4 : affM.Count; if (colCount < tkVal) { tkVal = colCount; } if (!loadingOutputResult.Contains(dataLoaded[_indx].Take(tkVal).ToList())) { var varTitle = macvarCol[_indx]; varTitle = varTitle.Replace(" ", "").Replace("\"", ""); var indexAndBackLag = varTitle.Replace("Var", "").Split('-'); var aff = affM.FirstOrDefault(); //************************************** try { aff = affM[int.Parse(indexAndBackLag[0]) - 1]; } catch { }; aff.varTitle = varTitle.Split('-')[0].Trim(); aff.BackwardOffset = 0; if (indexAndBackLag.Length > 1) { aff.BackwardOffset = int.Parse(indexAndBackLag[1]); } else { aff.BackwardOffset = 0; } if (!actual_macvar.Contains(aff)) { actual_macvar.Add(aff); loadingOutputResult.Add(dataLoaded[_indx].Take(tkVal).ToList()); } else { if (actual_macvar.Count == 3) { break; } } } if (loadingOutputResult.Count == tkVal) { break; } } loadingOutputResult = loadingOutputResult.Distinct().ToList(); var maxBackLag = actual_macvar.Max(o => o.BackwardOffset); var macrodataHeader = lstMacroData[0].Split(',').ToList(); // find and pick columsn to consider var positionsToHold = new List <int>(); for (int i = 0; i < actual_macvar.Count; i++) { for (int j = 0; j < macrodataHeader.Count(); j++) { if (macrodataHeader[j] == actual_macvar[i].varTitle) { positionsToHold.Add(j); } } } //Get the actualMacroData for Analysis sheet var firstPick = true; var allLineData = new List <List <string> >(); var actual_filtered_lineData = new List <List <string> >(); for (int i = 1; i < lstMacroData.Count; i++) { var _lineData = lstMacroData[i].Split(','); var lineData = new List <string>(); lineData.Add(_lineData[0]); for (int m = 0; m < positionsToHold.Count; m++) { lineData.Add(_lineData[positionsToHold[m]]); } var npl = _lineData.Last(); lineData.Add(npl); allLineData.Add(lineData); if (!string.IsNullOrWhiteSpace(npl) && !string.IsNullOrEmpty(npl)) { try { //if (double.Parse(npl.Trim()) > 0) //{ if (firstPick) { actual_filtered_lineData.AddRange(allLineData.Skip(i - maxBackLag - 1).Take(maxBackLag).ToList()); firstPick = false; } actual_filtered_lineData.Add(lineData); //} } catch { } } } ///i have gotten the data on sheet 1 actual_filtered_lineData var groupMacroData = GenerateGroupMacroData(actual_filtered_lineData); ///the principal component will come from the score final sheet var scoreFinalPath = Path.Combine(AppSettings.MacroModelPath, affiliateId.ToString(), "ETI_scores_Final.csv"); var all_score = File.ReadAllLines(scoreFinalPath); var startPeriod = groupMacroData.FirstOrDefault(o => o.NPL > 0).period; var endPeriod = groupMacroData.LastOrDefault(o => o.NPL > 0).period; var scoreValues = new List <double>(); var mcPrincipalComponent = new List <MacroResult_PrincipalComponent>(); var started = false; var startPos = lstMacroData.Count() - all_score.Count() + 1; // one is to exlude the header // var allDataStartPeriod = lstMacroData[startPos].Split(',')[0]; for (int i = 1; i < all_score.Count(); i++) { var _singleLine = all_score[i].Split(','); var posData = lstMacroData[startPos].Split(',')[0]; if (posData == startPeriod)//allDataStartPeriod { started = true; } if (started) { var mp = new MacroResult_PrincipalComponent(); try { mp.PrincipalComponent1 = double.Parse(_singleLine[1].Trim()); } catch { mp.PrincipalComponent1 = 0; } try{ mp.PrincipalComponent2 = double.Parse(_singleLine[2].Trim()); } catch { mp.PrincipalComponent2 = 0; } try{ mp.PrincipalComponent3 = double.Parse(_singleLine[3].Trim()); } catch { mp.PrincipalComponent3 = 0; } try{ mp.PrincipalComponent4 = double.Parse(_singleLine[4].Trim()); } catch { mp.PrincipalComponent4 = 0; } mcPrincipalComponent.Add(mp); } if (posData == endPeriod) { started = false; break; } startPos++; // allDataStartPeriod = GetNextPeriod(allDataStartPeriod, i); } //Continue Principal Component //////////////////////////Remove IT/////////////////////////////// mcPrincipalComponent = mcPrincipalComponent.Take(mcPrincipalComponent.Count - 2).ToList(); //removeit //////////////////////////Remove IT/////////////////////////////// // Principal Component SUmmary result var groupDataStartPos = groupMacroData.IndexOf(groupMacroData.FirstOrDefault(o => o.period == startPeriod)); var lstPrinSummary = new List <MacroResult_PrincipalComponentSummary>(); for (int i = 0; i < loadingOutputResult.Count; i++) { var selectedVariable = actual_macvar[i]; var _extractForPrinCompSummary = groupMacroData.Skip(groupDataStartPos - selectedVariable.BackwardOffset).Take(mcPrincipalComponent.Count).ToList(); var sum = new MacroResult_PrincipalComponentSummary(); sum.PrincipalComponentIdA = 1; sum.PrincipalComponentIdB = 4 + i; sum.PricipalComponentLabelA = "Mean"; sum.PricipalComponentLabelB = $"PrinComp{i + 1}"; sum.MacroId = macroId; var sum1 = new MacroResult_PrincipalComponentSummary(); sum1.PrincipalComponentIdA = 2; sum1.PrincipalComponentIdB = 4 + i; sum1.PricipalComponentLabelA = "std.Dev"; sum1.PricipalComponentLabelB = $"PrinComp{i + 1}"; sum1.MacroId = macroId; if (i == 0) { sum.Value = _extractForPrinCompSummary.Average(o => o.MacroValue1); sum1.Value = Computation.GetStandardDeviationS(_extractForPrinCompSummary.Select(o => o.MacroValue1)); } if (i == 1) { sum.Value = _extractForPrinCompSummary.Average(o => o.MacroValue2); sum1.Value = Computation.GetStandardDeviationS(_extractForPrinCompSummary.Select(o => o.MacroValue2)); } if (i == 2) { sum.Value = _extractForPrinCompSummary.Average(o => o.MacroValue3); sum1.Value = Computation.GetStandardDeviationS(_extractForPrinCompSummary.Select(o => o.MacroValue3)); } if (i == 3) { sum.Value = _extractForPrinCompSummary.Average(o => o.MacroValue4); sum1.Value = Computation.GetStandardDeviationS(_extractForPrinCompSummary.Select(o => o.MacroValue4)); } lstPrinSummary.Add(sum); lstPrinSummary.Add(sum1); sum = new MacroResult_PrincipalComponentSummary(); sum.PrincipalComponentIdA = 3; sum.PrincipalComponentIdB = 4 + i; sum.PricipalComponentLabelA = "EigenValues"; sum.PricipalComponentLabelB = $"PrinComp{i + 1}"; sum.MacroId = macroId; sum.Value = eIngenValues[i]; lstPrinSummary.Add(sum); for (int j = 0; j < loadingOutputResult[i].Count; j++) { sum = new MacroResult_PrincipalComponentSummary(); sum.PrincipalComponentIdA = 4 + j; sum.PrincipalComponentIdB = 4 + i; sum.PricipalComponentLabelA = $"PrinComp{j + 1}"; sum.PricipalComponentLabelB = $"PrinComp{i + 1}"; sum.MacroId = macroId; sum.Value = loadingOutputResult[i][j]; lstPrinSummary.Add(sum); } } // Get Statistical Data var statistics = new MacroResult_Statistics(); try { statistics.IndexWeight1 = eIngenValues[0] < 1 ? 0 : eIngenValues[0]; } catch { statistics.IndexWeight1 = 0; } try{ statistics.IndexWeight2 = eIngenValues[1] < 1 ? 0 : eIngenValues[1]; } catch { statistics.IndexWeight2 = 0; } try{ statistics.IndexWeight3 = eIngenValues[2] < 1 ? 0 : eIngenValues[2]; } catch { statistics.IndexWeight3 = 0; } try{ statistics.IndexWeight4 = eIngenValues[3] < 1 ? 0 : eIngenValues[3]; } catch { statistics.IndexWeight4 = 0; } statistics.IndexWeight3 = 0; statistics.IndexWeight4 = 0; // Get Index Data var indxData = new List <MacroResult_IndexData>(); for (int i = 0; i < mcPrincipalComponent.Count; i++) { var mcp = mcPrincipalComponent[i]; var indx = new MacroResult_IndexData(); // if(extractForPrinCompSummary.Count>(i + maxBackLag)) // { var extractForPrinCompSummary = groupMacroData.Skip(groupDataStartPos).Take(mcPrincipalComponent.Count).ToList(); indx.MacroId = macroId; indx.Period = extractForPrinCompSummary[i].period; indx.BfNpl = extractForPrinCompSummary[i].NPL; mcPrincipalComponent[i].PrincipalComponent1 = mcPrincipalComponent[i].PrincipalComponent1 ?? 0; mcPrincipalComponent[i].PrincipalComponent2 = mcPrincipalComponent[i].PrincipalComponent2 ?? 0; mcPrincipalComponent[i].PrincipalComponent3 = mcPrincipalComponent[i].PrincipalComponent3 ?? 0; mcPrincipalComponent[i].PrincipalComponent4 = mcPrincipalComponent[i].PrincipalComponent4 ?? 0; statistics.IndexWeight1 = statistics.IndexWeight1 ?? 0; statistics.IndexWeight2 = statistics.IndexWeight2 ?? 0; statistics.IndexWeight3 = statistics.IndexWeight3 ?? 0; statistics.IndexWeight4 = statistics.IndexWeight4 ?? 0; indx.Index = (mcPrincipalComponent[i].PrincipalComponent1.Value * statistics.IndexWeight1.Value) + (mcPrincipalComponent[i].PrincipalComponent2.Value * statistics.IndexWeight2.Value) + (mcPrincipalComponent[i].PrincipalComponent3.Value * statistics.IndexWeight3.Value) + (mcPrincipalComponent[i].PrincipalComponent4.Value * statistics.IndexWeight4.Value); indxData.Add(indx); // } } statistics.StandardDev = 0; statistics.Average = 0; statistics.Correlation = 0; statistics.TTC_PD = 0; try { statistics.StandardDev = Computation.GetStandardDeviationP(indxData.Select(o => o.Index).ToList()); } catch { } try{ statistics.Average = indxData.Average(o => o.Index); } catch { } try{ statistics.TTC_PD = indxData.Average(o => o.BfNpl); } catch { } for (int i = 0; i < indxData.Count; i++) { indxData[i].StandardIndex = 0; try { indxData[i].StandardIndex = (indxData[i].Index - statistics.Average.Value) / statistics.StandardDev.Value; } catch { } } var arry1 = indxData.Select(o => o.StandardIndex).ToArray(); var arry2 = indxData.Select(o => o.StandardIndex).ToArray(); var fitResult = new FitResult(); statistics.Correlation = fitResult.ComputeCoeff(arry1, arry2); // Get CorMat var macV1 = groupMacroData.Select(o => o.MacroValue1).ToList(); var macV2 = groupMacroData.Select(o => o.MacroValue2).ToList(); var macV3 = groupMacroData.Select(o => o.MacroValue3).ToList(); var macV4 = groupMacroData.Select(o => o.MacroValue4).ToList(); var allMacV = new List <List <double> > { macV1, macV2, macV3, macV4 }; var lstCorMat = new List <MacroResult_CorMat>(); for (int i = 0; i < actual_macvar.Count; i++) { for (int j = 0; j < actual_macvar.Count; j++) { var sum = new MacroResult_CorMat(); sum.MacroEconomicIdA = 0; sum.MacroEconomicIdB = 0; sum.MacroEconomicLabelA = ""; sum.MacroEconomicLabelB = ""; sum.Value = 0; try { sum.MacroEconomicIdA = actual_macvar[i].MacroeconomicVariableId; } catch { } try { sum.MacroEconomicIdB = actual_macvar[j].MacroeconomicVariableId; } catch { } try { sum.MacroEconomicLabelA = $"{actual_macvar[i].varTitle}-{actual_macvar[i].BackwardOffset}"; } catch { } try { sum.MacroEconomicLabelB = $"{actual_macvar[j].varTitle}-{actual_macvar[j].BackwardOffset}"; } catch { } sum.MacroId = macroId; try { sum.Value = MathNet.Numerics.Statistics.Correlation.Pearson(allMacV[i], allMacV[j]); } catch { } lstCorMat.Add(sum); } } //Delete all affiliate macroData qry = Queries.DeleteAffiliateMacroData(macroId, affiliateId); DataAccess.i.ExecuteQuery(qry); var sb = new StringBuilder(); // Save Principal Component Result to DB foreach (var prinC in mcPrincipalComponent) { sb.Append(Queries.MacroResult_PrinC(macroId, prinC.PrincipalComponent1, prinC.PrincipalComponent2, prinC.PrincipalComponent3, prinC.PrincipalComponent4)); } qry = sb.ToString().Replace("NaN", "0"); DataAccess.i.ExecuteQuery(qry); sb = new StringBuilder(); // Save Index Result to DB foreach (var mId in indxData) { sb.Append(Queries.MacroResult_IndxResult(macroId, mId.Period, mId.Index, mId.StandardIndex, mId.BfNpl)); } qry = sb.ToString().Replace("NaN", "0"); DataAccess.i.ExecuteQuery(qry); sb = new StringBuilder(); // Save Statistics Index Result to DB sb.Append(Queries.MacroResult_StatisticalIndex(macroId, statistics.IndexWeight1, statistics.IndexWeight2, statistics.IndexWeight3, statistics.IndexWeight4, statistics.StandardDev, statistics.Average, statistics.Correlation, statistics.TTC_PD)); qry = sb.ToString().Replace("NaN", "0"); DataAccess.i.ExecuteQuery(qry); sb = new StringBuilder(); // Save Correlation Mat Index Result to DB foreach (var corMar in lstCorMat) { sb.Append(Queries.MacroResult_CorMat(macroId, corMar.MacroEconomicIdA, corMar.MacroEconomicIdB, corMar.MacroEconomicLabelA, corMar.MacroEconomicLabelB, corMar.Value)); } qry = sb.ToString().Replace("NaN", "0"); DataAccess.i.ExecuteQuery(qry); // Save Principal Component Result to DB sb = new StringBuilder(); foreach (var pcs in lstPrinSummary) { sb.Append(Queries.MacroResult_PrincipalComponent(macroId, pcs.PrincipalComponentIdA, pcs.PrincipalComponentIdB, pcs.PricipalComponentLabelA, pcs.PricipalComponentLabelB, pcs.Value)); } qry = sb.ToString().Replace("NaN", "0"); DataAccess.i.ExecuteQuery(qry); //Actual Selected MacroEconomic Variable sb = new StringBuilder(); foreach (var itm in actual_macvar) { sb.Append(Queries.MacroResult_SelectedMacroEconomicVariables(itm.BackwardOffset, itm.AffiliateId, itm.MacroeconomicVariableId)); } qry = sb.ToString().Replace("NaN", "0"); DataAccess.i.ExecuteQuery(qry); return(true); }
/// <summary> /// Creates a new <see cref="InputCollection{TRecord}"/> in the given computation. /// </summary> /// <typeparam name="TRecord">The type of records in the collection.</typeparam> /// <param name="computation">The graph manager for the computation.</param> /// <returns>The new <see cref="InputCollection{TRecord}"/>.</returns> public static InputCollection <TRecord> NewInputCollection <TRecord>(this Computation computation) where TRecord : IEquatable <TRecord> { return(new IncrementalCollection <TRecord>(computation)); }
public void SetModelIsHardSelection(bool isHardSelection) { AssertIsForeground(); Computation.ChainTaskAndNotifyControllerWhenFinished(model => model?.WithHardSelection(isHardSelection)); }
public void Test_Caching_With_Write_Delay() { if (Environment.GetEnvironmentVariable("APPVEYOR") == "True") { return; } var clock = new OffsetClock("2017-04-25", "2017-04-25"); var cache = new StringCacheMem(); // Populate cache { var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock) { Cache = cache }; MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, LicenseStrings.EliteSubscriptionRemote, null); var conf = new Config(); conf.Plugins.LicenseScope = LicenseAccess.Local; conf.Plugins.Install(new LicensedPlugin(mgr, clock, "R_Elite", "R4Elite")); conf.Plugins.AddLicense(LicenseStrings.EliteSubscriptionPlaceholder); Assert.Equal(1, mgr.WaitForTasks()); var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true); Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain"))); Assert.Empty(mgr.GetIssues()); Assert.NotNull(conf.GetLicensesPage()); } // Use cache { var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock) { Cache = cache }; var conf = new Config(); conf.Plugins.LicenseScope = LicenseAccess.Local; conf.Plugins.Install(new LicensedPlugin(mgr, clock, "R_Elite", "R4Elite")); conf.Plugins.AddLicense(LicenseStrings.EliteSubscriptionPlaceholder); mgr.Heartbeat(); Assert.Equal(0, mgr.WaitForTasks()); var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true); Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain"))); Assert.NotNull(conf.GetDiagnosticsPage()); Assert.NotNull(conf.GetLicensesPage()); Assert.Equal(0, mgr.GetIssues().Count()); MockHttpHelpers.MockRemoteLicenseException(mgr, WebExceptionStatus.NameResolutionFailure); while (!mgr.AllowFetching()) { mgr.Heartbeat(); } mgr.WaitForTasks(); result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true); Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain"))); Assert.Equal(1, mgr.GetIssues().Count()); } }
protected override void HandleReadyComputation(Computation computation) { parent.HandleRightToLeftDependency(computation); }
public ComputationResult Calculate(Computation computation) { return(new ComputationResult()); }
public static LinkedListNode <Computation> RearrangeComputations(IEnumerable <Computation> computations, Computation origin) { var linked = new LinkedList <Computation>(); var originNode = new LinkedListNode <Computation>(origin); linked.AddFirst(originNode); var changed = true; while (changed) { changed = false; foreach (var c in computations) { if (c.TransformationRule.BaseRule == linked.Last.Value.TransformationRule) { linked.AddLast(c); changed = true; } else if (linked.First.Value.TransformationRule.BaseRule == c.TransformationRule) { linked.AddFirst(c); changed = true; } } } return(originNode); }
public PrintResult(TaskMaster task_master, Computation source, string output_filename) { this.task_master = task_master; this.source = source; this.output_filename = output_filename; }
protected override void HandleReadyComputation(Computation computation) { parent.CreateRightToLeftSynchronization(false, (SynchronizationComputation <TRight, TLeft>)computation); }
private void SetExampleScene(IILPanelForm panel) { if (m_cleanUpExample != null) { m_cleanUpExample(); m_cleanUpExample = null; } ILScene scene = new ILScene(); try { ILLabel.DefaultFont = new System.Drawing.Font("Helvetica", 8); //ilPanel1.Driver = RendererTypes.GDI; #region upper left plot // prepare some data ILArray <float> P = 1, x = ILMath.linspace <float>(-2, 2, 40), y = ILMath.linspace <float>(2, -2, 40); ILArray <float> F = ILMath.meshgrid(x, y, P); // a simple RBF ILArray <float> Z = ILMath.exp(-(1.2f * F * F + P * P)); // surface expects a single matrix Z[":;:;2"] = F; Z[":;:;1"] = P; // add a plot cube var pc = scene.Add(new ILPlotCube { // shrink viewport to upper left quadrant ScreenRect = new RectangleF(0.05f, 0, 0.4f, 0.5f), // 3D rotation TwoDMode = false, Children = { // add surface new ILSurface(Z) { // disable mouse hover marking Fill = { Markable = false }, Wireframe ={ Markable = false }, // make it shiny UseLighting = true, Children = { new ILColorbar() } }, //ILLinePlot.CreateXPlots(Z["1:10;:;0"], markers: new List<MarkerStyle>() { // MarkerStyle.None,MarkerStyle.None,MarkerStyle.None,MarkerStyle.None,MarkerStyle.Circle, MarkerStyle.Cross, MarkerStyle.Plus, MarkerStyle.TriangleDown }), //new ILLegend("hi","n","ku","zs","le", "blalblalblalblalb\\color{red} hier gehts rot") }, Rotation = Matrix4.Rotation(new Vector3(1.1f, -0.4f, -0.69f), 1.3f) }); #endregion #region top right plot // create a gear shape var gear = new ILGear(toothCount: 30, inR: 0.5f, outR: 0.9f) { Fill = { Markable = false, Color = Color.DarkGreen } }; // group with right clipping plane var clipgroup = new ILGroup() { Clipping = new ILClipParams() { Plane0 = new Vector4(1, 0, 0, 0) }, Children = { // a camera holding the (right) clipped gear new ILCamera() { // shrink viewport to upper top quadrant ScreenRect = new RectangleF(0.5f, 0, 0.5f, 0.5f), // populate interactive changes back to the global scene IsGlobal = true, // adds the gear to the camera Children ={ gear }, Position = new Vector3(0, 0, -15) } } }; // setup the scene var gearGroup = scene.Add(new ILGroup { clipgroup, clipgroup // <- second time: group is cloned }); gearGroup.First <ILCamera>().Parent.Clipping = new ILClipParams() { Plane0 = new Vector4(-1, 0, 0, 0) }; // make the left side transparent green gearGroup.First <ILTriangles>().Color = Color.FromArgb(100, Color.Green); // synchronize both cameras; source: left side gearGroup.First <ILCamera>().PropertyChanged += (s, arg) => { gearGroup.Find <ILCamera>().ElementAt(1).CopyFrom(s as ILCamera, false); }; #endregion #region left bottom plot // start value int nrBalls = 10; bool addBalls = true; var balls = new ILPoints("balls") { Positions = ILMath.tosingle(ILMath.randn(3, nrBalls)), Colors = ILMath.tosingle(ILMath.rand(3, nrBalls)), Color = null, Markable = false }; var leftBottomCam = scene.Add(new ILCamera { ScreenRect = new RectangleF(0, 0.5f, 0.5f, 0.5f), Projection = Projection.Perspective, Children = { balls } }); // funny label string harmony = @"\color{red}H\color{blue}a\color{green}r\color{yellow}m\color{magenta}o\color{cyan}n\color{black}y\reset "; var ballsLabel = scene.Add(new ILLabel(tag: "harmony") { Text = harmony, Fringe = { Color = Color.FromArgb(240, 240, 240) }, Position = new Vector3(-0.75f, -0.25f, 0) }); long oldFPS = 1; PointF currentMousePos = new PointF(); // setup the swarm. Start with a few balls, increase number // until framerate drops below 60 fps. ILArray <float> velocity = ILMath.tosingle(ILMath.randn(3, nrBalls)); EventHandler <ILRenderEventArgs> updateBallsRenderFrame = (s, arg) => { // transform viewport coords into 3d scene coords Vector3 mousePos = new Vector3(currentMousePos.X * 2 - 1, currentMousePos.Y * -2 + 1, 0); // framerate dropped? -> stop adding balls if (panel.Panel.FPS < oldFPS && panel.Panel.FPS < 60) { addBalls = false; } oldFPS = panel.Panel.FPS; Computation.UpdateBalls(mousePos, balls, velocity, addBalls); // balls buffers have been changed -> must call configure() to publish balls.Configure(); // update balls label ballsLabel.Text = harmony + "(" + balls.Positions.DataCount.ToString() + " balls)"; }; // saving the mouse position in MouseMove is easier for // transforming the coordinates into the viewport leftBottomCam.MouseMove += (s, arg) => { // save the mouse position currentMousePos = arg.LocationF; }; panel.Panel.BeginRenderFrame += updateBallsRenderFrame; m_cleanUpExample = () => { leftBottomCam.MouseMove -= (s, arg) => { // save the mouse position currentMousePos = arg.LocationF; }; panel.Panel.BeginRenderFrame -= updateBallsRenderFrame; }; #endregion panel.Panel.Scene = scene; } catch (Exception exc) { System.Diagnostics.Trace.WriteLine("ILPanel_Load Error:"); System.Diagnostics.Trace.WriteLine("===================="); System.Diagnostics.Trace.WriteLine(exc.ToString()); System.Windows.Forms.MessageBox.Show(exc.ToString()); } }
public void AddLicense(string license) { licenses.Add(license); LicensingChange?.Invoke(this, this); cache = null; }
public virtual void VisitComputationInstruction(Computation computation) => Default(computation);
/// <summary> /// Reads the contents of all files in an Azure directory into a Naiad stream. /// /// The serialization format is the same as WriteBinaryToAzureBlobs, and based on the Naiad message format. /// </summary> /// <typeparam name="TRecord">Type of records stored in the blobs</typeparam> /// <param name="manager">Graph manager</param> /// <param name="container">Azure container</param> /// <param name="prefix">Azure blob prefix</param> /// <returns>Naiad stream containing the records extracted from files in the Azure directory</returns> public static Stream <TRecord, Epoch> ReadBinaryFromAzureBlobs <TRecord>(this Computation manager, CloudBlobContainer container, string prefix) { return(manager.ReadFromAzureBlobs <TRecord>(container, prefix, stream => Utils.GetNaiadReaderEnumerable <TRecord>(stream))); }
/// <summary> /// Reads the contents of all text files in an Azure directory into a Naiad stream. /// </summary> /// <param name="manager">Graph manager</param> /// <param name="container">Azure container</param> /// <param name="prefix">Azure blob prefix</param> /// <returns>Naiad stream containing the lines extracted from files in the Azure directory</returns> public static Stream <string, Epoch> ReadTextFromAzureBlobs(this Computation manager, CloudBlobContainer container, string prefix) { return(manager.ReadFromAzureBlobs <string>(container, prefix, s => s.ReadLines())); }
public void RegisterComputationDependency(Computation computation, Computation dependency, bool isRequired) { }
/// <summary> /// Converts an <see cref="IEnumerable{TRecord}"/> into a constant Naiad <see cref="Stream{TRecord,Epoch}"/>, using the supplied <paramref name="computation"/>. /// </summary> /// <typeparam name="TRecord">record type</typeparam> /// <param name="source">input records</param> /// <param name="computation">graph manager</param> /// <returns>single epoch stream containing source records</returns> public static Stream <TRecord, Epoch> AsNaiadStream <TRecord>(this IEnumerable <TRecord> source, Computation computation) { return(computation.NewInput(new ConstantDataSource <TRecord>(source))); }
public void Test_Caching_With_Write_Delay() { if (Environment.GetEnvironmentVariable("APPVEYOR") == "True") { return; } var clock = new OffsetClock("2017-04-25", "2017-04-25"); var cache = new StringCacheMem(); // Populate cache { var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, cache); MockHttpHelpers.MockRemoteLicense(mgr, HttpStatusCode.OK, LicenseStrings.EliteSubscriptionRemote, null); var conf = new MockConfig(mgr, clock, new [] { "R_Elite", "R4Elite" }, Enumerable.Empty <KeyValuePair <string, string> >()); conf.AddLicense(LicenseStrings.EliteSubscriptionPlaceholder); Assert.Equal(1, mgr.WaitForTasks()); var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true); Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain"))); Assert.Empty(mgr.GetIssues()); Assert.NotNull(conf.GetLicensesPage()); } // Use cache { var mgr = new LicenseManagerSingleton(ImazenPublicKeys.Test, clock, cache); var conf = new MockConfig(mgr, clock, new [] { "R_Elite", "R4Elite" }, new List <KeyValuePair <string, string> >()); conf.AddLicense(LicenseStrings.EliteSubscriptionPlaceholder); conf.FireHeartbeat(); Assert.Equal(0, mgr.WaitForTasks()); var result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true); Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain"))); Assert.NotNull(conf.GetLicensesPage()); Assert.Empty(mgr.GetIssues()); MockHttpHelpers.MockRemoteLicenseException(mgr, WebExceptionStatus.NameResolutionFailure); while (!mgr.AllowFetching()) { conf.FireHeartbeat(); } mgr.WaitForTasks(); result = new Computation(conf, ImazenPublicKeys.Test, mgr, mgr, clock, true); Assert.True(result.LicensedForRequestUrl(new Uri("http://anydomain"))); Assert.Single(mgr.GetIssues()); } }