public Equation generate(Equation.Operator op) { IEquationGenerator generator = generators[op]; Equation generated = generator.generate(); return generated; }
public void setupQuestion() { Array operators = Enum.GetValues(typeof(Equation.Operator)); currentEquation = EquationFactory.Instance.generate((Equation.Operator)operators.GetValue(UnityEngine.Random.Range(0, operators.Length))); updateEquationText(currentEquation); setupButtons(currentEquation); }
/// <summary> /// Initializes a new instance of the AbstractFunction class. /// </summary> /// <param name="str">Name of the function</param> /// <param name="type">Type of function</param> /// <param name="arit">Some integer</param> /// <param name="eqs">List of Eqs</param> /// <param name="weight">Weight of function</param> public AbstractFunction(string str, Type type, int arit, Equation[] eqs, double weight) { this.Name = str; this.Type = type; this.Arit = arit; this.Eqs = eqs; this.Weight = weight; }
// given the point P , return a new line parallel to L public static Equation GetParallelLine(Equation E, Point P) { double Slope = E.m; Equation Parallell = new Equation(); Parallell.m = Slope; Parallell.b = -Slope * P.X + P.Y; return Parallell; }
private EquationBalancer(Equation eq) { equation = eq; left = eq.left; leftCoeff = eq.leftCoeff; right = eq.right; rightCoeff = eq.rightCoeff; }
/// <summary> Only method a program needs to use. /// Returns true iff the balance is successful. </summary> public static bool BalanceEquation(Equation eq) { //creates a new instance to be thread safe EquationBalancer balancer = new EquationBalancer(eq); if(!balancer.equation.Balanced) { balancer.BruteForceBalance(20, 0); } return balancer.equation.Balanced; }
// given a point P , return the perpendicular projection point with the line L public static Point GetPIntersection(Line L, Point P) { Equation E = GetEquation(L); double Slope = -1 / E.m; Equation Perpendicular = new Equation(); Perpendicular.m = Slope; Perpendicular.b = -Slope * P.X + P.Y; Point r = GetIntersection(E, Perpendicular); return r; }
// return the intersection point bewteen two lines public static Point GetIntersection(Equation E1, Equation E2 ) { double delta = E2.m - E1.m; if (delta == 0) throw new ArgumentException("Lines are parallel"); double x = Double.Parse(((E1.b-E2.b)/delta).ToString("0.00")); double y = Double.Parse(((- E1.m * E2.b + E2.m * E1.b) / delta).ToString("0.00")); return new Point(x,y); }
/****** BUTTONS ******/ private void setupButtons(Equation equation) { enableButtons(); int[] guesses = equation.getGuesses(inputButtons.Length); for (int i = 0; i < inputButtons.Length; i++) { updateButtonText(inputButtons[i], guesses[i].ToString()); } }
public void ShoudCheckIfEquationIsNotRight() { //x=2x; x=1 not true var varX = new Variable("x"); varX.Value = new List<Expression>() { new Expression(1, Variable.NULL) }; var left = new Expression(1, varX); var right = new Expression(2, varX); var target = new Equation(left, right); var result = target.IsCorrect; Assert.IsFalse(result); }
public void ShouldCompare2Equations() { var left11 = new Expression(1, new Variable("x")); var left21 = new Expression(2, new Variable("y")); var rightPart1 = new Expression(1, Variable.NULL); var leftPart1 = new List<Expression> {left11, left21}; var left12 = new Expression(10, new Variable("x")); var left22 = new Expression(20, new Variable("y")); var rightPart2 = new Expression(10, Variable.NULL); var leftPart2 = new List<Expression> { left12, left22 }; var target1 = new Equation(leftPart1, rightPart1); var target2 = new Equation(leftPart2, rightPart2); bool result = target1.IsEquivalent(target2); Assert.IsTrue(result); }
public void ShouldSolveSystemWith1EquationAnd1Variable() { // x = 2 var variableX = new Variable("x"); var left = new Expression(1, variableX); var right = new Expression(2, Variable.NULL); var equation = new Equation(left, right); var equationList = new List<Equation>(); equationList.Add(equation); var target = new SystemOfEquations(equationList); target.Solve(); var result = variableX.Value; Assert.AreEqual(1, result.Count); Assert.AreEqual(2, result.First().Coefficient); Assert.AreEqual(Variable.NULL, result.First().Variable); }
private Equation MergeEquations(Equation eq1, Equation eq2) { if (eq1.Divisor == eq2.Divisor) { return(new Equation { Dividend = eq2.Divisor, Divisor = eq1.Divisor, Result = eq2.Result / eq1.Result }); } if (eq1.Dividend == eq2.Dividend) { return(new Equation { Dividend = eq1.Divisor, Divisor = eq2.Divisor, Result = eq2.Result / eq1.Result }); } if (eq1.Dividend == eq2.Divisor) { return(new Equation { Dividend = eq2.Dividend, Divisor = eq1.Divisor, Result = eq1.Result * eq2.Result }); } if (eq1.Divisor == eq2.Dividend) { return(new Equation { Dividend = eq1.Dividend, Divisor = eq2.Divisor, Result = eq1.Result * eq2.Result }); } throw new ArgumentException("Unable to merge"); }
/// <summary> /// Convert this <c>LinearCurve</c> to a <c>Graphmatic.Interaction.Equation</c> object representing the same line. /// </summary> public override Equation ToEquation() { Expression expression = new Expression(null); expression.Add(new VariableToken(DependentVariable)); expression.Add(new SymbolicToken(SymbolicToken.SymbolicType.Equals)); expression.AddRange(ValueToTokenSequence(Intercept)); if (Slope >= 0) // avoid adding consecutive +- tokens { expression.Add(new OperationToken(OperationToken.OperationType.Add)); } expression.AddRange(ValueToTokenSequence(Slope)); expression.Add(new VariableToken(IndependentVariable)); Equation equation = new Equation(expression) { Name = this.ToString() }; equation.Parse(); return(equation); }
private static bool SatisfyLineGeneralForm(Equation equation, out Line line) { line = null; var lhsTerm = equation.Lhs as Term; if (lhsTerm == null) { return(false); } var rhsZero = equation.Rhs.Equals(0); if (!rhsZero) { return(false); } lhsTerm = lhsTerm.FlatTerm(); line = lhsTerm.UnifyLineTerm(); return(line != null); }
public void Invoke() { var totalLinesProcessed = 0; var inputLines = File.ReadAllLines(InputFile); var outputLines = inputLines.Select((input, i) => { if (Equation.TryParse(input, out Equation equation)) { totalLinesProcessed++; return(equation.ToCanonicalForm().ToString()); } string message = $"Failed to parse line {i}: {input}"; throw new Exception(message); }); File.WriteAllLines(OutputFile, outputLines); Console.WriteLine($"Processed {totalLinesProcessed} lines."); }
public void Test_Reify_1() { //a = 1, a*b = -1; //true positive var graph = new RelationGraph(); var a = new Var("a"); var b = new Var("b"); var eqGoal = new EqGoal(a, 1); var lhsTerm = new Term(Expression.Multiply, new List <object>() { a, b }); var equation = new Equation(lhsTerm, -1); graph.AddNode(eqGoal); var en = graph.AddNode(equation) as EquationNode; Assert.NotNull(en); Assert.True(en.Equation.CachedEntities.Count == 1); Assert.True(graph.Nodes.Count == 3); }
public void Invoke() { Console.WriteLine("(To exit press Ctrl+C)"); while (true) { Console.WriteLine(); Console.Write("Enter equation: "); string line = Console.ReadLine(); Equation equation; if (Equation.TryParse(line, out equation)) { Console.WriteLine("Canonical form: " + equation.ToCanonicalForm()); } else { Console.WriteLine("Cannot parse equation. Please make sure it has valid format."); } } }
public void ShouldCreateEquationWithComplexLeftAndRightParts() { var rigth1 = new Expression(2, Variable.NULL); var rigth2 = new Expression(2, new Variable("y")); var rigthPart = new List<Expression>() { rigth1, rigth2 }; var expression1 = new Expression(2.4, new Variable("x")); var expression2 = new Expression(2.4, new Variable("y")); var leftPart = new List<Expression>() { expression1, expression2 }; var target = new Equation(leftPart, rigthPart); Assert.AreEqual(expression1.Coefficient, target.LeftPart.First().Coefficient); Assert.AreEqual(expression1.Variable.Name, target.LeftPart.First().Variable.Name); Assert.AreEqual(expression2.Coefficient, target.LeftPart.Last().Coefficient); Assert.AreEqual(expression2.Variable.Name, target.LeftPart.Last().Variable.Name); Assert.AreEqual(rigth1.Coefficient, target.RightPart.First().Coefficient); Assert.AreEqual(rigth1.Variable.Name, target.RightPart.First().Variable.Name); Assert.AreEqual(rigth2.Coefficient, target.RightPart.Last().Coefficient); Assert.AreEqual(rigth2.Variable.Name, target.RightPart.Last().Variable.Name); }
public void Resolve() { var e1 = new Equation(Variable.Slack(2), new[] { new VariableFactor(Variable.Problem(1), -40), new VariableFactor(Variable.Problem(2), -120) }, 2400); var e2 = new Equation(Variable.Problem(1), new[] { new VariableFactor(Variable.Slack(1), -1), new VariableFactor(Variable.Problem(2), -1) }, 40); var r = new Equation(Variable.Slack(2), new[] { new VariableFactor(Variable.Slack(1), 40), new VariableFactor(Variable.Problem(2), -80) }, 800); Assert.AreEqual(r, e1.Resolve(e2)); }
public void NextEquation() { if (currentEquation.status == Equation.Status.Null) { currentEquation.status = Equation.Status.Skipped; } clusters[currentEquationIndex] = null; currentEquationIndex++; currentEquation = EquationCache.SharedCache.GetEquation(currentEquationIndex); if (currentEquation == null) { displayEquation = false; CalculateResults(); return; } //CreateCluster(); }
private static bool SatisfySpecialForm(Equation equation, out Line line) { line = null; bool isRhsNum = LogicSharp.IsNumeric(equation.Rhs); if (!isRhsNum) { return(false); } double dNum; LogicSharp.IsDouble(equation.Rhs, out dNum); double rhs = -1 * dNum; object xCoeff; bool result = IsXTerm(equation.Lhs, out xCoeff); if (result) { line = new Line(null, xCoeff, null, rhs); return(true); } object yCoeff; result = IsYTerm(equation.Lhs, out yCoeff); if (result) { line = new Line(null, null, yCoeff, rhs); return(true); } result = IsXYTerm(equation.Lhs, out xCoeff, out yCoeff); if (result) { line = new Line(null, xCoeff, yCoeff, rhs); return(true); } return(false); }
public void Render(ref Equation equation, ref float dT, ref int maxNumSolutions, ref float epsilon, ref float stepSolverDT, ref float solutionScaler, ref Vector3 initialState) { if (equation != null) { GUI.Label(new Rect(Screen.width - 200, 10, 150, 30), equation.GetName()); for (int i = 0; i < equation.Parameters.List.Count; i++) { equation.Parameters.List[i].value = GUI.HorizontalSlider(new Rect(Screen.width - 190, 45 + i * 40, 150, 30), equation.Parameters.List[i].value, -50f, 50f); GUI.Label(new Rect(Screen.width - 245, 45 + i * 40, 100, 30), equation.Parameters.List[i].name); GUI.Label(new Rect(Screen.width - 100, 55 + i * 40, 100, 30), equation.Parameters.List[i].value.ToString()); } } dT = GUI.HorizontalSlider(new Rect(100, 45, 100, 30), dT, 0.0001F, 0.01F); GUI.Label(new Rect(5, 40, 100, 30), "dt"); maxNumSolutions = (int)GUI.HorizontalSlider(new Rect(100, 85, 100, 30), maxNumSolutions, 1000, 100000); GUI.Label(new Rect(5, 80, 100, 30), "length"); epsilon = GUI.HorizontalSlider(new Rect(100, 125, 100, 30), epsilon, 0.01F, 0.0000001F); GUI.Label(new Rect(5, 120, 100, 30), "accuracy"); stepSolverDT = GUI.HorizontalSlider(new Rect(100, 165, 100, 30), stepSolverDT, 0.001f, 0.00001f); GUI.Label(new Rect(5, 160, 100, 30), "anim speed"); solutionScaler = GUI.HorizontalSlider(new Rect(100, 200, 100, 30), solutionScaler, .1f, 10f); GUI.Label(new Rect(5, 200, 100, 30), "scaler"); x = GUI.HorizontalSlider(new Rect(20, Screen.height - 50, 50, 30), x, -10f, 10f); GUI.Label(new Rect(25, Screen.height - 40, 50, 30), "x=" + x.ToString("#.##")); y = GUI.HorizontalSlider(new Rect(80, Screen.height - 50, 50, 30), y, -10f, 10f); GUI.Label(new Rect(85, Screen.height - 40, 50, 30), "y=" + y.ToString("#.##")); z = GUI.HorizontalSlider(new Rect(140, Screen.height - 50, 50, 30), z, -10f, 10f); GUI.Label(new Rect(145, Screen.height - 40, 50, 30), "z=" + z.ToString("#.##")); initialState = new Vector3(x, y, z); }
/// <summary> /// Fits a circle at a point providing G2 connection: coincidence of Continuity+Tangency+Curvature. /// <para/>The specified tolerance actually refers to clothoid parametric equation parameter value, rather than a true result spatial accuracy. /// </summary> public static bool FitCircle(Clothoid clothoid, Point point, double tol, out Circle circle, out double clothoidLength) { circle = new Circle(Point.NaP, double.NaN); clothoidLength = double.NaN; if (double.IsNaN(clothoid.CurvatureRate)) { return(false); } var newXAxis = new Line(clothoid.Origin, clothoid.OriginDirection); var vx = newXAxis.GetProjection(point) - clothoid.Origin; var pt = new Point(vx.Length * Math.Sign(vx * newXAxis.Direction), newXAxis.DistanceTo(point)); if (pt.X * pt.Y * clothoid.CurvatureRate <= 0.0) { return(false); } Equation.Func func = length => Math.Abs(GetRadius(clothoid.CurvatureRate, length)) - (GetCurvatureCenter(clothoid.CurvatureRate, length) - pt).Length; var sign = Math.Sign(clothoid.CurvatureRate * pt.Y); var boundL = sqrtPi / Math.Abs(clothoid.CurvatureRate) * sign; clothoidLength = Equation.SolveBisection(func, 0 + tol * sign, boundL - tol * sign, tol); // Brent method does not work since the func changes it's 2nd derivative sign if (double.IsNaN(clothoidLength)) { return(false); } var r = GetRadius(clothoid.CurvatureRate, clothoidLength); var c = clothoid.GetPoint(clothoidLength) + clothoid.GetNormal(clothoidLength) * r; circle = new Circle(c, r); return(true); }
public void Test_Unify_1() { //a = 1, a*b = -1; //true positive var a = new Var("a"); var b = new Var("b"); var eqGoal = new EqGoal(a, 1); var lhsTerm = new Term(Expression.Multiply, new List <object>() { a, b }); var equation = new Equation(lhsTerm, -1); var eqNode = new EquationNode(equation); object obj; bool result = RelationLogic.ConstraintCheck(eqNode, eqGoal, null, out obj); Assert.True(result); Assert.NotNull(obj); }
// DELETE api/Equation/5 public HttpResponseMessage DeleteEquation(int id) { Equation equation = db.Equations.Find(id); if (equation == null) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } db.Equations.Remove(equation); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex)); } return(Request.CreateResponse(HttpStatusCode.OK, equation)); }
private void resetEquation_Click(object sender, EventArgs e) { //Reset equation button quadFormula = new Equation(); //Reset solve button solveEquation.Font = new Font(solveEquation.Font, FontStyle.Regular); //Disable buttons solveEquation.Enabled = false; resetEquation.Enabled = false; //Clear term boxes ClearTerm(tbTermA); ClearTerm(tbTermB); ClearTerm(tbTermC); //Clear labels EquationLabel.Text = ""; x1Solution.Text = ""; x2Solution.Text = ""; }
public void CalculerRelation(GrandeurPhysique depart) { int indiceEquation = 0; foreach (var Arrivee in Produit.GrandeurPhysiques) { indiceEquation = Relation.MatriceRelations[depart.iM][Arrivee.Value.iM]; if (indiceEquation != 0) { Equation.Calculer(indiceEquation); } } indiceEquation = 0; foreach (var Arrivee in Produit.GrandeurPhysiques) { indiceEquation = Relation.MatriceRelations[Arrivee.Value.iM][depart.iM]; if (indiceEquation != 0) { Equation.Calculer(indiceEquation); } } }
public void MultipleMatrixTest() { string[] equations = new[] { "4x+y-z+t=7", "y+x-5t-z=-1", "z-3t+x-y=6", "t+x-z+3y=1" }; Equation equation = new Equation(equations); Assert.AreEqual(new Vector <double>(4) { 4, 1, -1, 1 }, equation.Coefficients[0]); Assert.AreEqual(new Vector <double>(4) { 1, 1, -1, -5 }, equation.Coefficients[1]); Assert.AreEqual(new Vector <double>(4) { 1, -1, 1, -3 }, equation.Coefficients[2]); Assert.AreEqual(new Vector <double>(4) { 1, 3, -1, 1 }, equation.Coefficients[3]); }
private static void Test_Equation_Parsing() { string s = "1.0 / (1.0 + exp(-1 * {0}))"; //string s = "maxL(0, 10, 1, $0$)"; List <EquationParsingException> exc; Equation e = Equation.Parse(s, out exc); foreach (EquationParsingException ec in exc) { Debug.WriteLine("ParsingException: " + ec.Message); } List <EquationEvaluationException> evExc = null; Debug.WriteLine(e.Evaluate(out evExc, 2)); foreach (EquationEvaluationException ec in evExc) { Debug.WriteLine("EvaluationException: " + ec.Message); } }
public void TestExtractionInsertion_Multiplication() { string eEquation1 = "2*x=8"; string expected = "x = 4"; Equation exp = MathParser.ParseEquation(eEquation1); Print(exp.ToString()); OperatorExpressionPair pair = exp.LeftHandSide.Extract((IOperator)exp.LeftHandSide.TokenAt(1), (ITerm)exp.LeftHandSide.TokenAt(0)); Print(exp.ToString()); Print("Extracted: " + pair.ToString()); exp.RightHandSide.Insert(pair); Print(exp.ToString()); exp.RightHandSide.Simplify(); Print(exp.ToString()); Assert.AreEqual(expected, exp.ToString()); }
public static Equation ReplaceVarWithExpression(this Equation equation, Variable varToReplace, IEnumerable <Term> aliasExpr) { var foundOnLeft = equation.LeftSide.SingleOrDefault(term => term.Variable?.Equals(varToReplace) ?? false); var foundOnRight = equation.RightSide.SingleOrDefault(term => term.Variable?.Equals(varToReplace) ?? false); if (foundOnLeft != null) { equation.AddToLeft(new Term[] { new Term { SignedCoefficient = foundOnLeft.SignedCoefficient * -1, Variable = varToReplace } }); equation.AddToLeft(aliasExpr.Copy().Multiply(foundOnLeft.SignedCoefficient)); } if (foundOnRight != null) { equation.AddToRight(new Term[] { new Term { SignedCoefficient = foundOnRight.SignedCoefficient * -1, Variable = varToReplace } }); equation.AddToRight(aliasExpr.Copy().Multiply(foundOnRight.SignedCoefficient)); } return(equation); }
/// <summary> /// Parse an equation string e.g. x^2 + 3.5xy + y = y^2 - xy + y /// </summary> public static Equation Parse(string input) { if (String.IsNullOrEmpty(input)) { throw new ArgumentException(nameof(input)); } var polinomials = input.Split('='); if (polinomials.Length != 2 || String.IsNullOrEmpty(polinomials[0]) || String.IsNullOrEmpty(polinomials[1])) { throw new ArgumentException(nameof(input)); } var leftSummands = ParsePolinomialIntoSummands(polinomials[0]).ToList(); var rightSummands = ParsePolinomialIntoSummands(polinomials[1]).ToList(); rightSummands.ForEach(i => i.Coefficient *= -1); leftSummands.AddRange(rightSummands); var equation = new Equation(); foreach (var summand in leftSummands) { var found = equation.Summands.Find(x => x.SummandID.Equals(summand.SummandID)); if (found != null) { found.Coefficient += summand.Coefficient; } else { equation.Summands.Add(summand); } } equation.Summands = equation.Summands.OrderByDescending(s => s.MaxExponent).ThenBy(i => i.SummandID).ToList(); return(equation); }
private void HandleMergeVertex(MyPoint vertex) { var e = vertex.ledge; if (this.helper[e].Tip == 4) { this.D.AddLast(new Edge() { p1 = this.helper[e].Point, p2 = vertex.Point }); } this.T.Remove(e); var query = from val in this.T where (val.p1.Y <= vertex.Point.Y && val.p2.Y >= vertex.Point.Y) select val; var dist = double.MaxValue; var e1 = new Edge(); foreach (var edge in query) { var eq = new Equation(edge); var d = eq.distance(vertex.Point); if (d > 0 && d < dist) { e1 = edge; dist = d; } } if (this.helper[e1].Tip == 4) { this.D.AddLast(new Edge() { p1 = this.helper[e1].Point, p2 = vertex.Point }); } this.helper[e1] = vertex; }
protected async Task CopyTo(IVariable copy) { if (copy == null) { throw new ArgumentNullException(nameof(copy)); } copy.GraphicalFunction = GraphicalFunction; copy.Range = Range; copy.Scale = Scale; copy.Units = Units; if (Equation != null) { copy.Equation = await Equation.Clone(Model); } copy.Value = Value; copy.NonNegative = NonNegative; copy.Access = Access; copy.StoreResult = StoreResult; copy.Children = new List <string>(); copy.Children.AddRange(Children); }
public void CorrectTranslationOfAdresses() { CellType myAnswer = default(CellType); Equation myEquation = default(Equation); Coords[] correctCoords = new Coords[4]; Coords[] myCoords = new Coords[4]; correctCoords[0] = new Coords(9, 0); correctCoords[1] = new Coords(3, 22); correctCoords[2] = new Coords(1769874982, 730); correctCoords[3] = new Coords(1256376568, 12356614); Equation.TryParse(ShortAddress, out myEquation, out myAnswer); myCoords[0] = myEquation.FirstOperand; myCoords[1] = myEquation.SecondOperand; Equation.TryParse(LongAddress, out myEquation, out myAnswer); myCoords[2] = myEquation.FirstOperand; myCoords[3] = myEquation.SecondOperand; Assert.IsTrue(Utilities.AreEqual(correctCoords, myCoords)); }
public static void Resolve() { var c1 = new Constant(3); var c2 = new Constant(6); var c3 = new Constant(11); var a = new Variable(1, 1); var b = new Variable(2, 1); var lhs1 = new Expression(c1); var rhs1 = new Expression(new [] { (Number)c2, a * -1, b * -1 }); var eq1 = new Equation(lhs1, rhs1); var lhs2 = new Expression(c1); var rhs2 = new Expression(new[] { (Number)c3, a * -4, b * -2 }); var eq2 = new Equation(lhs2, rhs2); var ex1 = eq1.Get(a); var ex2 = eq2.Get(a); var eq3 = new Equation(ex1, ex2); var x = Resolve(eq3); }
public static void EnterCoefficients(Equation eq) { double[] coefs = new double[eq.GetNumberOfCoefficients()]; bool isNumber; string input; NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat; for (int i = 0; i < eq.GetNumberOfCoefficients(); i++) { do { Console.WriteLine($"Enter cofficient {eq.GetNamesOfCoefficients()[i]}:"); input = Console.ReadLine(); isNumber = Double.TryParse(input.Replace(',', '.').Replace('.', nfi.NumberDecimalSeparator[0]), out coefs[i]); if (!isNumber) { Console.WriteLine("You must enter a number!"); logger.LogIncorrectInput(input); } } while (!isNumber); } eq.SetCoefficients(coefs); }
protected override void Execute(CodeActivityContext executionContext) { var error = false; var errorMessage = String.Empty; var formula = Formula.Get <string>(executionContext); try { var parameters = new Dictionary <string, string>(); AddParameters(executionContext, parameters); var equation = parameters.Aggregate(formula, (c, p) => c.Replace(p.Key, String.Format(" {0} ", p.Value))); SetOutputValues(executionContext, Equation.Solve(equation)); } catch (Exception ex) { errorMessage = ex.Message; error = true; } Error.Set(executionContext, error); ErrorMessage.Set(executionContext, errorMessage); }
private EquationNode AddEquationNode(Equation equation) { //1. build relation using geometry constraint-solving (synthesize new node) (Top-Down) //2. Reify itself (Bottom-up) object relations; ConstraintSatisfy(equation, out relations); EquationNode eqNode = CreateEqNode(equation, relations); /* GraphNode sinkNode = FindSinkNode(eqNode); * Reify(sinkNode);*/ Reify(eqNode); /* foreach (object obj in goalRels) * { * var goalNode = obj as GoalNode; * if (goalNode == null) continue; * Reify(goalNode); * //Reify(eqNode); * }*/ return(eqNode); }
public void EquationsAreSame(Equation Original, Equation Copy) { Assert.AreEqual(Original.NumberOfAllOperators, Copy.NumberOfAllOperators, "AllOperators Count is not the same"); Assert.AreEqual(Original.Holders.Count, Copy.Holders.Count, "SortedOperators Count is not the same"); for (int i = 0; i < Original.AllOperators.Length; i++) { RecursiveCompareOperators(Original.AllOperators[i], Copy.AllOperators[i]); } for (int i = 0; i < Original.Holders.Count; i++) { for (int y = 0; y < Original.Holders[0].Operators.Length; y++) { if (!(Original.Holders[i].Operators[y] == null && Copy.Holders[i].Operators[y] == null || Original.Holders[i].Operators[y] != null && Copy.Holders[i].Operators[y] != null)) { Assert.Fail("SortedOperators is not the same"); } } } }
public void Fit(Point[] points) { if (points == null) { throw new ArgumentException("No points to fit"); } SystemOfEquations = new Equation[points.Length]; var r = Definition.R; for (int i = 0; i < points.Length; i++) { SystemOfEquations[i] = new Equation(r); for (int j = 0; j < r; j++) { SystemOfEquations[i].Left[j].VariableValue = points[i].X; } SystemOfEquations[i].Y = points[i].Y; } N = points.Length; }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Параметров не передано!"); } else { string str = Utils.Base64Decode(args[0]); var utf8Reader = new Utf8JsonReader(Encoding.ASCII.GetBytes(str)); JSONEquations json = JsonSerializer.Deserialize <JSONEquations>(ref utf8Reader); Equation func = new Equation(json.FuncX1, json.FuncX2, null, 0); Equation[] limits = new Equation[2]; limits[0] = new Equation(json.Limit1X1, json.Limit1X2, "<=", json.Limit1C); limits[1] = new Equation(json.Limit2X1, json.Limit2X2, "<=", json.Limit2C); MethodLandAndDoig method = new MethodLandAndDoig(func, limits); method.BranchMethod += HandlerBranch; method.EndMethod += endHandler; method.StartMethod += startHandler; method.solve(); Console.ReadKey(); } }
public void ReadConfiguration(XElement Configuration) { Name = Configuration.SafeParseString("Name"); foreach (var eq in Configuration.Elements("Equation")) { var eqs =new Equation(); eqs.StartMonth = eq.SafeParseInt("StartMonth")??1; eqs.EndMonth = eq.SafeParseInt("EndMonth") ?? 12; eqs.Par1 = eq.SafeParseDouble("Par1") ?? 3.882; eqs.Par2 = eq.SafeParseDouble("Par2") ?? 0.7753; if (eqs.StartMonth < eqs.EndMonth) for (int i = eqs.StartMonth; i <= eqs.EndMonth; i++) equations.Add(i, eqs); else { for (int i = eqs.StartMonth; i <= 12; i++) equations.Add(i, eqs); for (int i = 1; i <= eqs.EndMonth; i++) equations.Add(i, eqs); } } }
public void Init() { equation = new Equation(); }
private void Parse(string file) { var ini = new IniFile(file); SetValues(this, ini["Version Section"].Values); SetValues(this, ini["Signature Section"].Values); SetValues(this, ini["Schedule"].Values); var steps = new List<Step>(); foreach (var section in ini.Where(x => x.Name.IsMatch(@"^Schedule_Step\d+$"))) { var step = new Step(); step.Number = int.Parse(section.Name.Match(@"^Schedule_Step(\d+)$")); SetValues(step, section.Values); steps.Add(step); } Steps = steps.OrderBy(x => x.Number).ToList(); foreach (var section in ini.Where(x => x.Name.IsMatch(@"^Schedule_Step\d+_Limit\d+$"))) { var limit = new Limit(); limit.Number = int.Parse(section.Name.Match(@"^Schedule_Step\d+_Limit(\d+)$")); SetValues(limit, section.Values); var equationNumber = @"^Equation(\d+).*$"; foreach (var equationValues in section.Values .Where(x => x.Key.IsMatch(@"^Equation\d+.*$")) .GroupBy(x => x.Key.Match(equationNumber))) { var equation = new Equation(); equation.Number = int.Parse(equationValues.First().Key.Match(equationNumber)); SetValues(equation, equationValues.ToDictionary(x => x.Key.Match(@"^Equation\d+(.*)$"), x => x.Value)); limit.Equations = limit.Equations.Concat(equation).OrderBy(x => x.Number).ToList(); } var step = Steps[int.Parse(section.Name.Match(@"^Schedule_Step(\d+)_Limit\d+$"))]; step.Limits = step.Limits.Concat(limit).OrderBy(x => x.Number).ToList(); } }
public static Point Intersect(Equation eq1, Equation eq2) { var y = (eq1.a * eq2.c - eq2.a * eq1.c) / (eq2.b * eq1.a - eq1.b * eq2.a); var x = (eq1.c - eq1.b * y) / eq1.a; return new Point(x, y); }
public void ShouldMoveVarsFromRigthPartToLeft() { //x+2y+2y = 5+2y 2y = 5 - x y = 2.5-0.5x var left1 = new Expression(1, new Variable("x")); var left2 = new Expression(2, new Variable("y")); var right1 = new Expression(2, new Variable("y")); var rigth2 = new Expression(5, Variable.NULL); var target = new Equation( new List<Expression>() { left2, left1, right1 }, new List<Expression>() { right1, rigth2 } ); target.Solve(left2.Variable); Assert.AreEqual(1, target.LeftPart.Count); Assert.AreEqual(left2.Variable.Name, target.LeftPart.First().Variable.Name); Assert.AreEqual(2,target.RightPart.Count); Assert.AreEqual(-0.5,target.RightPart.First(x => x.Variable == left1.Variable).Coefficient); Assert.AreEqual(2.5,target.RightPart.First(x => x.Variable.Name == null).Coefficient); }
public void ShouldCreateSimpleStatement() { var leftPart = new Expression(2.4, new Variable("x")); var rigthPart = new Expression(2.4, Variable.NULL); var target = new Equation(leftPart, rigthPart); Expression leftPartResult = target.LeftPart.First(); Expression rightPartResult = target.RightPart.First(); Assert.AreEqual(leftPart.Coefficient, leftPartResult.Coefficient); Assert.AreEqual(leftPart.Variable, leftPartResult.Variable); Assert.AreEqual(rigthPart.Coefficient, rightPartResult.Coefficient); Assert.AreEqual(rigthPart.Variable, rightPartResult.Variable); }
public void ShouldInsertValuesInsteadOfVariablesAndGetResult() { //2x+2y=8 y=2; => x=2 var variableY = new Variable("y"); variableY.Value = new List<Expression>() { new Expression(2, null) }; var variableX = new Variable("x"); var expression1 = new Expression(2, variableX); var expression2 = new Expression(2, variableY); var rigthPart = new Expression(8, Variable.NULL); var leftPart = new List<Expression>() {expression1, expression2}; var target = new Equation(leftPart, rigthPart); target.Solve(variableX); var leftResult = target.LeftPart.First(); var rightResult = target.RightPart.First(); Assert.AreEqual(1, target.LeftPart.Count); Assert.AreEqual(variableX, leftResult.Variable); Assert.AreEqual(2.0, rightResult.Coefficient); Assert.AreEqual(null, rightResult.Variable.Name); Assert.AreEqual(2,variableY.Value.First().Coefficient); }
void Add(string label, Equation eq) { VariableEditor ve = eq.WriteEditor(null); ve.sail = VarGroup.Sail; ve.AutoFillData = VarGroup.Sail.Watermark(VarGroup).ToList<object>(); m_flow.Controls.Add(ve); ve.ReturnPress += ve_ReturnPress; }
internal void HighlightEquation(Equation equation) { for (int i = 0; i < m_flow.Controls.Count; i++) if ((m_flow.Controls[i] as VariableEditor).Label == equation.Label) (m_flow.Controls[i] as VariableEditor).FocusEditBox(); }
public void Should_Pass_In_Left_Part_Only_1_Var_From_Right_Part_When_Right_Part_Is_Complex() { var expression1 = new Expression(2.4, new Variable("x")); var expression2 = new Expression(2.4, new Variable("y")); var rightPart = new List<Expression>() { expression1, expression2 }; var leftPart = new Expression(2.4, Variable.NULL); var target = new Equation(leftPart, rightPart); target.Solve(expression1.Variable); Assert.AreEqual(1, target.LeftPart.Count); Assert.AreEqual("x", target.LeftPart.First().Variable.Name); Assert.AreEqual(1.0, target.LeftPart.First().Coefficient); Assert.AreEqual(2, target.RightPart.Count); Assert.AreEqual(1.0, target.RightPart.First(x => x.Variable.Name == leftPart.Variable.Name).Coefficient); Assert.AreEqual(-1.0, target.RightPart.First(x => x.Variable.Name == expression2.Variable.Name).Coefficient); }
public void ShouldSummTwoEquations() { //x = 2y |+ //10x + 20z = 10 | //= //11x + 20z = 2y + 10 var left11 = new Expression(1, new Variable("x")); var rightPart1 = new Expression(2, new Variable("y")); var leftPart1 = new List<Expression> { left11 }; var left12 = new Expression(10, new Variable("x")); var left22 = new Expression(20, new Variable("z")); var rightPart2 = new Expression(10, Variable.NULL); var leftPart2 = new List<Expression> { left12, left22 }; var target1 = new Equation(leftPart1, rightPart1); var target2 = new Equation(leftPart2, rightPart2); Equation result = target1+target2; var xCoeff = result.LeftPart.First(x => x.Variable.Name == "x").Coefficient; var yCoeff = result.RightPart.First(x => x.Variable.Name == "y").Coefficient; var zCoeff = result.LeftPart.First(x => x.Variable.Name == "z").Coefficient; var nullCoef = result.RightPart.Find(x => x.Variable.Name == null).Coefficient; Assert.AreEqual(2, result.LeftPart.Count); Assert.AreEqual(2, result.RightPart.Count); Assert.AreEqual(11, xCoeff); Assert.AreEqual(2, yCoeff); Assert.AreEqual(20, zCoeff); Assert.AreEqual(10, nullCoef); }
public void ShouldPassInLeftPartOnly1Variable() { //2.4x + 2.4y = 2.4 => x = 1 - 1.0y var expression1 = new Expression(2.4, new Variable("x")); var expression2 = new Expression(2.4, new Variable("y")); var leftPart = new List<Expression>() { expression1, expression2 }; var rightPart = new Expression(2.4, Variable.NULL); var target = new Equation(leftPart, rightPart); target.Solve(expression1.Variable); Assert.AreEqual(1, target.LeftPart.Count); Assert.AreEqual("x", target.LeftPart.First().Variable.Name); Assert.AreEqual(1.0, target.LeftPart.First().Coefficient); Assert.AreEqual(2, target.RightPart.Count); Assert.AreEqual(1.0, target.RightPart.First(x => x.Variable.Name == rightPart.Variable.Name).Coefficient); Assert.AreEqual(-1.0, target.RightPart.First(x => x.Variable.Name == expression2.Variable.Name).Coefficient); }
public void ShouldSolveUnSortedSystemWith3ComplexEquations() { //x=1; y=2; z=3; //x+2y-z = 2 // z = 3 //x-y = -1 var variableX = new Variable("x"); var variableY = new Variable("y"); var variableZ = new Variable("z"); var left1FirstEq = new Expression(1, variableX); var left2FirstEq = new Expression(2, variableY); var left3FirstEq = new Expression(-1, variableZ); var rightFirstEq = new Expression(2, Variable.NULL); var left1SecondEq = new Expression(1, variableZ); var rightSecondEq = new Expression(3, Variable.NULL); var left1ThirdEq = new Expression(1, variableX); var left2ThirdEq = new Expression(-1, variableY); var rightThirdEq = new Expression(-1, Variable.NULL); var firstEquation = new Equation(new List<Expression>() { left1FirstEq, left2FirstEq,left3FirstEq }, rightFirstEq); var secondEquation = new Equation(new List<Expression>() { left1SecondEq }, rightSecondEq); var thirdEquation = new Equation(new List<Expression>() {left1ThirdEq, left2ThirdEq}, rightThirdEq); var target = new SystemOfEquations(new List<Equation>() {firstEquation, secondEquation, thirdEquation}); target.Solve(); var resultX = variableX.Value; var resultY = variableY.Value; var resultZ = variableZ.Value; Assert.AreEqual(1, resultX.Count); Assert.AreEqual(1, resultY.Count); Assert.AreEqual(1, resultZ.Count); Assert.AreEqual(Variable.NULL, resultX.First().Variable); Assert.AreEqual(1, resultX.First().Coefficient); Assert.AreEqual(Variable.NULL, resultY.First().Variable); Assert.AreEqual(2, resultY.First().Coefficient); Assert.AreEqual(Variable.NULL, resultZ.First().Variable); Assert.AreEqual(3, resultZ.First().Coefficient); }
public void ShouldIncreaseEquationOnConst() { var left1 = new Expression(1, new Variable("x")); var left2 = new Expression(2, new Variable("y")); var rightPart = new Expression(1, Variable.NULL); var leftPart = new List<Expression> { left1, left2 }; var target = new Equation(leftPart, rightPart); target = target * 3.0; var xCoeff = target.LeftPart.First(x => x.Variable.Name == "x").Coefficient; var yCoeff = target.LeftPart.First(x => x.Variable.Name == "y").Coefficient; var nullCoeff = target.RightPart.First(x => x.Variable.Name == null).Coefficient; Assert.AreEqual(3, xCoeff); Assert.AreEqual(6, yCoeff); Assert.AreEqual(3, nullCoeff); Assert.AreEqual(1,left1.Coefficient); Assert.AreEqual(2, left2.Coefficient); Assert.AreEqual(1,rightPart.Coefficient); }
/// <summary> /// Hesaplama fonksiyonu /// </summary> /// <param name="equation"></param> /// <returns></returns> public static double Execute(Equation equation) { ANS = equation.Exe(); return ANS; }
public void ShouldMoveAllVarsToLeftAndAllConstsToRight() { //x+2y+2y= 2y+5 should return x+2y=5 var left1 = new Expression(1, new Variable("x")); var left2 = new Expression(2, new Variable("y")); var right1 = new Expression(2, new Variable("y")); var rigth2 = new Expression(5, Variable.NULL); var target = new Equation( new List<Expression>() { left2, left1, right1 }, new List<Expression>() { right1, rigth2 } ); target.MoveAllVarsToLeft(); Assert.AreEqual(2, target.LeftPart.Count); Assert.AreEqual(1.0, target.LeftPart.First(x => x.Variable.Name == "x").Coefficient); Assert.AreEqual(2.0, target.LeftPart.First(x => x.Variable.Name == "y").Coefficient); Assert.AreEqual(1, target.RightPart.Count); Assert.AreEqual(5, target.RightPart.First().Coefficient); }
public void ShouldSolveSystemWith1EquationAnd2Variables() { //x+y=10 x=6; y=4 //x-y=2 var variableX = new Variable("x"); var variableY = new Variable("y"); var left1FirstEq = new Expression(1, variableX); var left2FirstEq = new Expression(1, variableY); var rightFirstEq = new Expression(10, Variable.NULL); var left1SecondEq = new Expression(1, variableX); var left2SecondEq = new Expression(-1, variableY); var rightSecondEq = new Expression(2, Variable.NULL); var firstEquation = new Equation(new List<Expression>() { left1FirstEq, left2FirstEq }, rightFirstEq); var secondEquation = new Equation(new List<Expression>() {left1SecondEq, left2SecondEq}, rightSecondEq); var target = new SystemOfEquations(new List<Equation>() {firstEquation, secondEquation}); target.Solve(); var resultX = variableX.Value; var resultY = variableY.Value; Assert.AreEqual(1, resultX.Count); Assert.AreEqual(1, resultY.Count); Assert.AreEqual(Variable.NULL, resultX.First().Variable); Assert.AreEqual(6, resultX.First().Coefficient); Assert.AreEqual(Variable.NULL, resultY.First().Variable); Assert.AreEqual(4, resultY.First().Coefficient); }