public void SolveNewmark() { List <double> aConstants = CalculateIntegrationConstantsNewmark(); double[,] hatStiffnessMatrixNewmark = CalculateHatKMatrixNewmark(aConstants); explicitSolution.Add(0, InitialValues.InitialDisplacementVector); explicitVelocity.Add(0, InitialValues.InitialVelocityVector); explicitAcceleration.Add(0, CalculateInitialAccelerationsNewmark()); TimeAtEachStep.Add(0, 0.0); double[] nextSolution; for (int i = 1; i < timeStepsNumber; i++) { double time = i * timeStep + InitialValues.InitialTime; if (ActivateNonLinearSolution == false) { double[] hatRVectorNewmark = CalculateHatRVectorNewmark(i, aConstants); nextSolution = LinearSolver.Solve(hatStiffnessMatrixNewmark, hatRVectorNewmark); Console.WriteLine("Solution for Load Step {0} is:", i); VectorOperations.PrintVector(nextSolution); } else { nextSolution = NewtonIterationsNewmark(ExternalForcesVector, i, aConstants); Console.WriteLine("Solution for Load Step {0} is:", i); VectorOperations.PrintVector(nextSolution); } explicitSolution.Add(i, nextSolution); explicitAcceleration.Add(i, CalculateAccelerationNewmark(i, aConstants)); explicitVelocity.Add(i, CalculateVelocityNewmark(i, aConstants)); TimeAtEachStep.Add(i, time); } ExportToFile.ExportExplicitResults(explicitSolution, TimeAtEachStep, 1, 1); //ShowToGUI.ShowResults(explicitSolution, TimeAtEachStep, 1, 1); }
/// <summary> /// Intersection test. /// </summary> /// <remarks>Test does not handle parallel lines.</remarks> /// <param name="one">The first line segment.</param> /// <param name="other">The second line segment.</param> /// <param name="t1">The interpolation for first line segment, only if intersects is true.</param> /// <param name="t2">The interpolation for second line segment, only if intersects is true.</param> /// <returns>Do lines intersect.</returns> public static bool Intersect(LineSegment2d one, LineSegment2d other, out double t1, out double t2) { t1 = t2 = 0.0; // We solve 2x2 system and then check if it is ok for the third argument. Vector2d r = LinearSolver.SolveSystem( new Matrix2x2d(one.Direction.X, -other.Direction.X, one.Direction.Y, -other.Direction.Y), new Vector2d(other.A.X - one.A.X, other.A.Y - one.A.Y)); // If system has the solution, it must be in range [0,1]. if (r.X < 0.0 || r.X > 0.0) { return(false); } if (r.Y < 0.0 || r.Y > 0.0) { return(false); } // We check if the last line satisfies. if (!Vector2d.NearEqual(one.Sample(r.X), other.Sample(r.Y))) { return(false); } // We copy interpolation. t1 = r.X; t2 = r.Y; return(true); }
public void SolveExplicit() { double[,] hatMassMatrix = CalculateHatMMatrix(); explicitSolution.Add(-1, CalculatePreviousDisplacementVector()); explicitSolution.Add(0, InitialValues.InitialDisplacementVector); explicitAcceleration.Add(0, CalculateInitialAccelerations()); TimeAtEachStep.Add(-1, -1 * timeStep + InitialValues.InitialTime); TimeAtEachStep.Add(0, 0.0); double[] nextSolution; for (int i = 1; i < timeStepsNumber; i++) { double time = i * timeStep + InitialValues.InitialTime; if (ActivateNonLinearSolution == false) { double[] hatRVector = CalculateHatRVector(i); nextSolution = LinearSolver.Solve(hatMassMatrix, hatRVector); Console.WriteLine("Solution for Load Step {0} is:", i); VectorOperations.PrintVector(nextSolution); } else { double[] hatRVector = CalculateHatRVectorNL(i); nextSolution = LinearSolver.Solve(hatMassMatrix, hatRVector); //nextSolution = NewtonIterations(hatRVector); Console.WriteLine("Solution for Load Step {0} is:", i); VectorOperations.PrintVector(nextSolution); } explicitSolution.Add(i, nextSolution); explicitAcceleration.Add(i, CalculateAccelerations()); TimeAtEachStep.Add(i, time); } ExportToFile.ExportExplicitResults(explicitSolution, TimeAtEachStep, 1, 1); }
/// <summary> /// Obtains barycentric coordinate relative to this triangle. /// </summary> /// <param name="input">The vector that lies in triangle plane.</param> /// <returns></returns> public Vector2f GetBarycentric(Vector2f input) { // Automatic Z-projection for 2D. return(LinearSolver.SolveSystem(B.X - A.X, C.X - A.X, B.Y - A.Y, C.Y - A.Y, input.X - A.X, input.Y - A.Y)); }
public void SetSolver(LinearSolver a_Solver) { if (a_Solver != null) { m_Solver = a_Solver; } }
static void Main(string[] args) { // Дано квадратное уравнение вида // 5x-3=0 var vars = new Variables() { A = 5, B = 3 }; //Инструмент для решения линейного уравнения var solver = new LinearSolver(); //Результат решения линейного уравнения var root = solver.Solve(vars); //Вывод результата программы if (root.HasRoots) { Console.WriteLine($"x = {root.Root}"); } else { Console.WriteLine("a=0, вычислеие невозможно"); } Console.ReadKey(); }
private double[] LoadControlledNR(double[] forceVector) { lambda = 1.0 / numberOfLoadSteps; double[] incrementDf = VectorOperations.VectorScalarProductNew(forceVector, lambda); double[] solutionVector = new double[forceVector.Length]; double[] incrementalExternalForcesVector = new double[forceVector.Length]; double[] tempSolutionVector = new double[solutionVector.Length]; double[] deltaU = new double[solutionVector.Length]; double[] internalForcesTotalVector; double[] dU; double[] residual; double residualNorm; //Assembler.UpdateAccelerations(CalculateAccelerations(InitialValues.InitialAccelerationVector)); for (int i = 0; i < numberOfLoadSteps; i++) { incrementalExternalForcesVector = VectorOperations.VectorVectorAddition(incrementalExternalForcesVector, incrementDf); Assembler.UpdateDisplacements(solutionVector); Assembler.UpdateAccelerations(explicitAcceleration.Values.Last()); internalForcesTotalVector = Assembler.CreateTotalInternalForcesVector(); double[,] tangentMatrix = CalculateHatMMatrix(); dU = LinearSolver.Solve(tangentMatrix, incrementDf); solutionVector = VectorOperations.VectorVectorAddition(solutionVector, dU); Assembler.UpdateDisplacements(solutionVector); tangentMatrix = CalculateHatMMatrix(); internalForcesTotalVector = Assembler.CreateTotalInternalForcesVector(); residual = VectorOperations.VectorVectorSubtraction(internalForcesTotalVector, incrementalExternalForcesVector); residualNorm = VectorOperations.VectorNorm2(residual); int iteration = 0; Array.Clear(deltaU, 0, deltaU.Length); while (residualNorm > tolerance && iteration < maxIterations) { tangentMatrix = CalculateHatMMatrix(); deltaU = VectorOperations.VectorVectorSubtraction(deltaU, LinearSolver.Solve(tangentMatrix, residual)); tempSolutionVector = VectorOperations.VectorVectorAddition(solutionVector, deltaU); Assembler.UpdateDisplacements(tempSolutionVector); //Assembler.UpdateAccelerations(CalculateAccelerations(solutionVector)); internalForcesTotalVector = Assembler.CreateTotalInternalForcesVector(); residual = VectorOperations.VectorVectorSubtraction(internalForcesTotalVector, incrementalExternalForcesVector); residualNorm = VectorOperations.VectorNorm2(residual); iteration = iteration + 1; } solutionVector = VectorOperations.VectorVectorAddition(solutionVector, deltaU); if (iteration >= maxIterations) { Console.WriteLine("Newton-Raphson: Solution not converged at current iterations"); } } return(solutionVector); }
public long GetSolution1(String path) { var input = System.IO.File.ReadLines(path); var solver = new LinearSolver(); return(input.Sum(x => (long)solver.Solve(x))); }
private double[] NewtonIterationsNewmark(double[] forceVector, int stepNumber, List <double> aConstants) { lambda = 1.0 / numberOfLoadSteps; //double[] incrementDf = VectorOperations.VectorScalarProductNew(forceVector, lambda); double[] solutionVector = new double[forceVector.Length]; double[] deltaU = new double[solutionVector.Length]; double[] internalForcesTotalVector; double[] residual; double residualNorm; double[] hatR; solutionVector = explicitSolution.Values.Last(); Assembler.UpdateDisplacements(solutionVector); //Assembler.UpdateAccelerations(explicitAcceleration.Values.Last()); hatR = CalculateHatRVectorNewmarkNL(stepNumber, aConstants, solutionVector); internalForcesTotalVector = Assembler.CreateTotalInternalForcesVector(); residual = VectorOperations.VectorVectorSubtraction(hatR, internalForcesTotalVector); residual = VectorOperations.VectorVectorSubtraction(forceVector, Assembler.CreateTotalInternalForcesVector()); int iteration = 0; Array.Clear(deltaU, 0, deltaU.Length); for (int i = 0; i < maxIterations; i++) { double[,] tangentMatrix = CalculateHatKMatrixNewmark(aConstants); deltaU = LinearSolver.Solve(tangentMatrix, residual); solutionVector = VectorOperations.VectorVectorAddition(solutionVector, deltaU); Assembler.UpdateDisplacements(solutionVector); //Assembler.UpdateAccelerations(CalculateAccelerations()); hatR = CalculateHatRVectorNewmarkNL(stepNumber, aConstants, solutionVector); internalForcesTotalVector = Assembler.CreateTotalInternalForcesVector(); residual = VectorOperations.VectorVectorSubtraction(hatR, internalForcesTotalVector); residualNorm = VectorOperations.VectorNorm2(residual); if (residualNorm < tolerance) { break; } iteration = iteration + 1; } //Console.WriteLine(iteration); if (iteration >= maxIterations) { Console.WriteLine("Newton-Raphson: Solution not converged at current iterations"); } return(solutionVector); }
public ParticleSystem(LinearSolver a_Solver, float a_ConstraintSpringConstant, float a_ConstraintDampingConstant) { m_Solver = a_Solver; if (m_Solver == null) { throw new Exception("Please provide a valid solver."); } m_Particles = new List <Particle>(); m_Forces = new List <Force>(); m_Constraints = new List <Constraint>(); m_J = new BlockSparseMatrix(); m_JDot = new BlockSparseMatrix(); m_ConstraintSpringConstant = a_ConstraintSpringConstant; m_ConstraintDampingConstant = a_ConstraintDampingConstant; }
/// <summary> /// Obtains barycentric coordinate relative to this triangle. /// </summary> /// <param name="input">The vector that lies in triangle plane.</param> /// <returns></returns> public Vector2f GetBarycentric(Vector3f input) { //#ifdef 3D // We need positive components of normal, only magnitude relavant. Vector3f normal = this.Normal; normal = Vector3f.ComponentMultiply(normal, normal); if (normal.X > normal.Y) { if (normal.X > normal.Y) { // We project to x axis, all xs are the same. return(LinearSolver.SolveSystem(B.Y - A.Y, C.Y - A.Y, B.Z - A.Z, C.Z - A.Z, input.Y - A.Y, input.Z - A.Z)); } else { // We project to z axis, all zs are the same. return(LinearSolver.SolveSystem(B.X - A.X, C.X - A.X, B.Y - A.Y, C.Y - A.Y, input.X - A.X, input.Y - A.Y)); } } else { if (normal.Y > normal.Z) { // We project to y axis, all ys are the same. return(LinearSolver.SolveSystem(B.X - A.X, C.X - A.X, B.Z - A.Z, C.Z - A.Z, input.X - A.X, input.Z - A.Z)); } else { // We project to z axis, all zs are the same. return(LinearSolver.SolveSystem(B.X - A.X, C.X - A.X, B.Y - A.Y, C.Y - A.X, input.X - A.X, input.Y - A.Y)); } } //#endif }
private double[] CalculateInitialAccelerationsNewmark() //Bathe page 771 { if (CustomStiffnessMatrix != null) { return(InitialValues.InitialAccelerationVector); } int step = explicitSolution.Count - 1; Assembler.UpdateDisplacements(explicitSolution[step]); double[,] stiffness = Assembler.CreateTotalStiffnessMatrix(); double[,] mass = Assembler.CreateTotalMassMatrix(); double[] Ku = VectorOperations.MatrixVectorProduct(stiffness, explicitSolution[step]); double[] RHS = VectorOperations.VectorVectorSubtraction(ExternalForcesVector, Ku); double[] acceleration = LinearSolver.Solve(mass, RHS); return(acceleration); }
private static IEquationSolutions Solve(string variable, IExpression expression, ClassificationResult classification) { if (classification.EquationType == EquationTypes.Undefined) { return(new EquationSolutions()); } if (classification.SearchResult.ElementAt(0).Key != variable) { //var expression = equation.Left; //var classification = equation.Classification; //var clone = expression.Clone(); //substitute = new Tuple<string, string>(variable, GetNewVariableForSub(equation)); //var sub = new VariableExpression(substitute.Item2, 1); //clone.Substitute(ref clone, sub, classification.SearchResult.ElementAt(0).Key); var sols = Solve(classification.SearchResult.ElementAt(0).Key, expression, classification); return(sols); } else { if (classification.EquationType == EquationTypes.Linear) { var solver = new LinearSolver(); return(solver.Solve(expression, variable, classification)); } else if (classification.EquationType == EquationTypes.Quadratic) { var solver = new QuadraticSolver(); return(solver.Solve(expression, variable, classification)); } else if (classification.EquationType == EquationTypes.Trigonometric) { var solver = new TrigonometricSolver(); return(solver.Solve(expression, variable, classification)); } else { return(null); } } }
public static void Main(string[] args) { var arg = ParseArgs(args); Console.WriteLine($"Jetzige Konfiguration: {arg}\n"); Stopwatch sw = new Stopwatch(); Tuple <bool, int, List <int[]> > input = ReadInput(); // Falls der eingegebene Datei-Name gueltig ist if (input.Item1) { // CancellationToken fuers Beenden der Threads var cToken = new CancellationTokenSource(); var sToken = new CancellationTokenSource(); // Eigene Simplex Methode Tuple <bool, Dictionary <string, rat> > res = new Tuple <bool, Dictionary <string, rat> >(false, null); var simplexThread = new Thread(() => res = Solve(input.Item3, sToken.Token)); CompleteSearch c = new CompleteSearch(input.Item3); var searchThread = new Thread(() => c.Process(cToken.Token)); // Falls OrTools nicht explizit erlaubt ist, i.e. verboten ist // Kombination von CompleteSearch und Simplex if (!arg.UseGoogle) { simplexThread.Start(); // Falls durch Kommando-Zeile-Argumente // CompleteSearch nicht explizit verboten ist if (!arg.ForceSimplex) { searchThread.Start(); } // Messen von Zeit sw.Start(); while ((arg.ForceSimplex || searchThread.IsAlive) && simplexThread.IsAlive) { Thread.Sleep(100); if (sw.ElapsedMilliseconds > arg.TimeLimit) { cToken.Cancel(); sToken.Cancel(); sw.Stop(); // Warten auf die Threads aufzuhoeren while ((!arg.ForceSimplex && searchThread.IsAlive) || simplexThread.IsAlive) { Thread.Sleep(500); } // Falls die Zeitbeschraenkung ueberschritten wird Console.WriteLine($"\nTIME LIMIT EXCEEDED: {sw.ElapsedMilliseconds}ms"); Console.WriteLine("Das koennte dazu fuehren, dass das ausgedurckte Ergebnis nicht optimal ist. "); // Falls Simplex ein besseres Ergebnis hat, durckt diese aus if (res.Item2["P"] >= c.HighestProfit) { PrintResult(res.Item2, "Simplex"); } // und vice versa else { PrintResult(c.GetResult(), "CompleteSearch"); } } } // Falls Complete Search hat das Problem zuerst geloest if (!arg.ForceSimplex && c.IsCompleted) { PrintResult(c.GetResult(), "CompleteSearch"); // Die andere kann dann aufhoeren sToken.Cancel(); } // Falls Simplex hat das Problem zuerst geloest else if (res.Item1) { cToken.Cancel(); // Die andere kann dann aufhoeren PrintResult(res.Item2, "Simplex"); } } // Falls Google Solver durch KommandoZeile-Argumente // explizit erlaubt wurde else { Dictionary <string, rat> result = LinearSolver.GoogleSolve(input.Item3); PrintResult(result, "OR-Tool (SCIP)"); } Console.WriteLine($"Gesamt verwendete Zeit: {sw.ElapsedMilliseconds}"); } else { Console.WriteLine("Die gegebene Datei-Namen ist nicht gueltig. Das Programm und die Datei muessen in demselben Ordner stehen. "); } Console.WriteLine("\r\nDrueck eine beliebige Taste zu schliessen..."); Console.ReadKey(); }
public void Solve() { IFiniteElementSolver solver = new LinearSolver(this.Model); this.Results = solver.Solve(); }
static void Main(string[] args) { int choose; double a = 0; double b = 0; double c = 0; string pathFile = ConfigurationManager.AppSettings["log"]; StreamWriter writer = new StreamWriter(pathFile, true); while (true) { Console.WriteLine(" Выберите действие"); Console.WriteLine("0. Линейное уравнение"); Console.WriteLine("1. Квадратное уравнение"); Console.WriteLine("2. Перемножить матрицу (данные из файла)"); Console.WriteLine("3. Выход"); while (true) { if (Int32.TryParse(Console.ReadLine(), out choose)) { break; } else { Console.WriteLine("Введите пожалуйста цифру из предложенных"); } } switch (choose) { case 0: Console.WriteLine("Ax + B = 0"); Console.WriteLine("Введите коэффиценты А и В"); while (true) { Console.WriteLine("Введите A"); if (Double.TryParse(Console.ReadLine(), out a)) { break; } else { Console.WriteLine("Введите пожалуйста цифру"); writer.WriteLine($"Линейное уравнение (ВВОД НЕКОРРЕКТНЫХ ДАННЫХ : А={a} "); } } while (true) { Console.WriteLine("Введите B"); if (Double.TryParse(Console.ReadLine(), out b)) { break; } else { Console.WriteLine("Введите пожалуйста цифру"); writer.WriteLine($"Линейное уравнение (ВВОД НЕКОРРЕКТНЫХ ДАННЫХ : B={b} "); } } LinearSolver linearEquation = new LinearSolver(a, b); Console.WriteLine("Корень уравнения: " + linearEquation.solve()); writer.WriteLine($"Линейное уравнение : {a}x+{b} = 0" + "\tКорень уравнения : " + linearEquation.solve()); Console.ReadLine(); break; case 1: Console.WriteLine("Ax^2 + Bx + C = 0"); Console.WriteLine("Введите коэффиценты А,B и С"); while (true) { Console.WriteLine("Введите A"); if (Double.TryParse(Console.ReadLine(), out a)) { break; } else { Console.WriteLine("Введите пожалуйста цифру"); writer.WriteLine($"Квадратное уравнение (ВВОД НЕКОРРЕКТНЫХ ДАННЫХ : А={a} "); } } while (true) { Console.WriteLine("Введите B"); if (Double.TryParse(Console.ReadLine(), out b)) { break; } else { Console.WriteLine("Введите пожалуйста цифру"); writer.WriteLine($"Квадратное уравнение (ВВОД НЕКОРРЕКТНЫХ ДАННЫХ : B={b} "); } } while (true) { Console.WriteLine("Введите C"); if (Double.TryParse(Console.ReadLine(), out c)) { break; } else { Console.WriteLine("Введите пожалуйста цифру"); writer.WriteLine($"Квадратное уравнение (ВВОД НЕКОРРЕКТНЫХ ДАННЫХ : C={c} "); } } QuadraticSolver quadriticEquation = new QuadraticSolver(a, b, c); double[] result = quadriticEquation.solve(); Console.WriteLine($" Корни уравнения : x1= {result[1]} x2= {result[2]}"); writer.WriteLine($"Квадратное уравнение : {a}x^2 + {b}x + c = 0 " + $" Корни уравнения : x1= {result[1]} x2= {result[2]}"); Console.ReadLine(); break; case 2: string matrix1 = ConfigurationManager.AppSettings["matrix1"]; string matrix2 = ConfigurationManager.AppSettings["matrix2"]; double[,] A = MatrixSolver.readMatrix(matrix1); double[,] B = MatrixSolver.readMatrix(matrix1); Console.WriteLine(); Console.WriteLine("Матрицв А"); MatrixSolver.printMatrix(A); Console.WriteLine(); Console.WriteLine("Матрицв B"); MatrixSolver.printMatrix(B); Console.WriteLine(); double[,] answer = MatrixSolver.Multuply(A, B); if (answer == null) { Console.WriteLine("Перемножение невозможно"); } else { Console.WriteLine("Результат"); MatrixSolver.printMatrix(answer); } Console.ReadKey(); break; case 3: writer.Close(); Environment.Exit(0); break; } } }
private double[] NewtonIterationsExplicit(int timeStep, double[] forceVector, double[,] tangentMatrix) { //lambda = 1.0 / numberOfLoadSteps; //double[] incrementDf = VectorOperations.VectorScalarProductNew(forceVector, lambda); double[] solutionVector = new double[forceVector.Length]; double[] deltaU = new double[solutionVector.Length]; //double[] internalForcesTotalVector; double[] residual; double residualNorm; double[] hatRPrevious; double[] hatRNext; solutionVector = explicitSolution.Values.Last(); Assembler.UpdateDisplacements(solutionVector); Assembler.UpdateAccelerations(explicitAcceleration.Values.Last()); hatRPrevious = CalculateHatRVectorNL(timeStep); hatRNext = hatRPrevious; //internalForcesTotalVector = Assembler.CreateTotalInternalForcesVector(); //residual = VectorOperations.VectorVectorSubtraction(hatR, internalForcesTotalVector); residual = hatRPrevious; int iteration = 0; Array.Clear(deltaU, 0, deltaU.Length); for (int i = 0; i < maxIterations; i++) { if (i == 0) { //deltaU = LinearSolver.Solve(tangentMatrix, residual); //solutionVector = VectorOperations.VectorVectorAddition(solutionVector, deltaU); solutionVector = LinearSolver.Solve(tangentMatrix, residual); Assembler.UpdateDisplacements(solutionVector); //Assembler.UpdateAccelerations(CalculateAccelerations()); hatRNext = CalculateHatRVectorNL(timeStep); //internalForcesTotalVector = Assembler.CreateTotalInternalForcesVector(); residual = VectorOperations.VectorVectorSubtraction(hatRNext, hatRPrevious); residualNorm = VectorOperations.VectorNorm2(residual); if (residualNorm < tolerance) { break; } iteration = iteration + 1; hatRPrevious = hatRNext; } else { deltaU = LinearSolver.Solve(tangentMatrix, residual); solutionVector = VectorOperations.VectorVectorAddition(solutionVector, deltaU); //solutionVector = LinearSolver.Solve(tangentMatrix, residual); Assembler.UpdateDisplacements(solutionVector); //Assembler.UpdateAccelerations(CalculateAccelerations()); hatRNext = CalculateHatRVectorNL(timeStep); //internalForcesTotalVector = Assembler.CreateTotalInternalForcesVector(); residual = VectorOperations.VectorVectorSubtraction(hatRNext, hatRPrevious); residualNorm = VectorOperations.VectorNorm2(residual); if (residualNorm < tolerance) { break; } iteration = iteration + 1; hatRPrevious = hatRNext; } } //Console.WriteLine(iteration); if (iteration >= maxIterations) { Console.WriteLine("Newton-Raphson: Solution not converged at current iterations"); } return(solutionVector); }
public void Solve() { IFiniteElementSolver solver = new LinearSolver(this.Model); this.Results = solver.Solve(); }