private void Test(string input, Type expectedException) { Exception actualException = null; try { try { FunctionParser parser = new FunctionParser(); FunctionTree function = parser.Parse(input); throw new ArgumentException(); } catch (SyntaxException ex) { actualException = ex; Assert.AreEqual(expectedException.FullName, actualException.GetType().FullName); } } catch (Exception ex) { if (actualException == null) { actualException = ex; } Assert.Fail(MessageHandler.GetMessage(ex, input, expectedException, actualException)); } }
public static Logic parsePureFunctionCall(Logic[] logicOrder, int lineNumber, Scope currentScope) { if (logicOrder.Length != 1) { return(new UnknownLogic(lineNumber)); } if (logicOrder [0].currentType == WordTypes.functionCall) { FunctionCall tempCall = (logicOrder [0] as FunctionCall); FunctionParser.linkFunctionCall(tempCall, lineNumber, currentScope); if (tempCall.targetFunc.pauseWalker) { CodeWalker.pauseWalker(); } tempCall.runFunction(currentScope); if (tempCall.targetFunc.isUserFunction) { throw new FunctionCallException(); } return(tempCall); } else { return(new UnknownLogic(lineNumber)); } }
private void ParseExpression(object sender, EventArgs e) { if ((sender as TextBox).Text != string.Empty) { parser = new FunctionParser((sender as TextBox).Text); } }
private ParserStatus ParseBracket(char c) { switch (_state) { case ParserState.INT: case ParserState.FLOAT: CompleteValue(); goto case ParserState.VALUE; case ParserState.VALUE: case ParserState.VARIABLE: if (c == '(' || c == '<') { _tree.AddNode(new MultiplicationOperNode()); } goto case ParserState.UOPER; case ParserState.UOPER: case ParserState.NOPER: case ParserState.BEGIN: case ParserState.OPEN_PARENTHESIS: { if (c == '(') { _tree.AddNode(new ParenthesisOperNode()); _parenthesisDepth++; _state = ParserState.OPEN_PARENTHESIS; } else if (c == ')') { if (_parenthesisDepth == 0) { return(EnterErrorState(ErrorType.UNPAIRED_PARENTHESIS)); } else if (_state == ParserState.OPEN_PARENTHESIS) { return(EnterErrorState(ErrorType.CANNOT_PROCEED)); } _parenthesisDepth--; _tree.CloseParenthesis(); _state = ParserState.VALUE; } else if (c == '<') { _activeFunctionParser = FunctionParser.MakeFunctionParser(c); _activeFunctionParser.ParseFirstChar(c); _state = ParserState.FUNCTION; } else { return(EnterErrorState(ErrorType.UNPAIRED_PARENTHESIS)); } return(GetSuccessState()); } default: return(EnterErrorState(ErrorType.UNKNOWN)); } }
private bool ComputeAnswer() { immediate.Focus(); Buffer = Buffer.Trim(); if (Buffer.Length == 0) { Buffer = AnswerKey; } // Print what we're about to evaluate ScreenBuffer += "> " + Buffer.Trim() + "\n"; ShowScreenText(); try { var exp = FunctionParser.Parse(Buffer); _lastAnswer = exp.Simplify(); if (_lastAnswer is ConstantExpression) { VariableExpression.Define(AnswerKey, ((ConstantExpression)_lastAnswer).Value); } return(true); } catch (FunctionParserException) { ScreenBuffer += "Error!\n"; _lastAnswer = new ConstantExpression(0); VariableExpression.Define(AnswerKey, 0.0); Buffer = string.Empty; return(false); } }
public void TryParse_ValidFunctionTest_ReturnsFunction() { var parser = new FunctionParser(); parser.TryParse <string>("test", out var function).Should().BeFalse(); function.Should().NotBeNull(); }
public decimal EvalFunctionalCcyAmt(BankStmt bsi, FinActivity activityMap, List <GenLedgerFinActivityJoin> genLedgerFinActivityJoin) { // get maps that have been computed for each bank statement item var fp = new FunctionParser(); ParserDelegate TokenFAmountHandler = delegate(FunctionParseDelegateArgs e) { // e.FunctionArgs[0] will have value like, for example, 'A' var result = from j in genLedgerFinActivityJoin where j.FinActivity.Token == e.FunctionArgs[0] select j.GenLedgerKey.FunctionalCcyAmt; return(result.Sum()); }; fp.Add("FA", TokenFAmountHandler); var parsed = fp.ParseToCriteria(activityMap.FunctionalCcyAmtExpr.Replace("{FA}", "FunctionalCcyAmt")); try { object exprResult = bsi.Evaluate(CriteriaOperator.Parse(parsed.Criteria, parsed.Parameters)); decimal famt = 0.00M; if (exprResult != null && Decimal.TryParse(exprResult.ToString(), out famt)) { return(famt); } return(0.00M); } catch (Exception ex) { throw new InvalidOperationException(string.Format( "Error parsing map expression = '{1}', at FinActivity.Oid = '{0}', BankStmt.Oid = '{2}'\r\n{3}", activityMap.Oid, activityMap.FunctionalCcyAmtExpr, bsi.Oid, ex.Message), ex); } }
public void DeclareFunction(string name, FunctionParser parser) { if (Functions.ContainsKey(name)) { throw new ArgumentException("This function was already declared"); } Functions[name] = parser; }
public void ParseFormalTest() { FunctionParser functionParser = new FunctionParser(Init("param1")); Formal parsedFormal = functionParser.ParseFormal(); //Test identifier Assert.AreEqual("param1", parsedFormal.ToString()); }
public void FunctionWithoutArguments() { // Create the token stream. TokenStream stream = new TokenStream(new Token[] { // Program starting point token. new Token { Type = TokenType.Unknown }, new Token { Type = TokenType.TypeInt, Value = "int" }, new Token { Type = TokenType.Identifier, Value = "test" }, new Token { Type = TokenType.SymbolParenthesesL, Value = "(" }, new Token { Type = TokenType.SymbolParenthesesR, Value = ")" }, new Token { Type = TokenType.SymbolBlockL, Value = "{" }, new Token { Type = TokenType.SymbolBlockR, Value = "}" } }); // Read the expected output IR code. string expected = TestUtil.ReadOutputDataFile("FunctionWithoutArguments"); // Invoke the function parser. Function function = new FunctionParser().Parse(stream); // Emit the function. function.Emit(this.module.Source); // Emit the module. string output = this.module.ToString(); System.Console.WriteLine(output); // Compare stored IR code with the actual, emitted output. Assert.AreEqual(expected, output); }
public async Task TryParse_SingleValueFunction_ReturnsCorrectValue() { var parser = new FunctionParser(); parser.TryParse <int>("2 + 2", out var function).Should().BeFalse(); var val = await function.Execute(); val.Should().Be(4); }
private static void BuildDocumentation(string content, List <string> matches, string schemaName) { PGSchema schema = SchemaProcessor.GetSchema(schemaName); content = content.Replace("[DBName]", Program.Database.ToUpperInvariant()); content = content.Replace("[SchemaName]", schemaName); content = SequenceParser.Parse(content, matches, SequenceProcessor.GetSequences(schemaName)); content = TableParser.Parse(content, matches, schema.Tables); content = ViewParser.Parse(content, matches, schema.Views); content = SequenceParser.Parse(content, matches, schema.Sequences); content = MaterializedViewParser.Parse(content, matches, schema.MaterializedViews); content = FunctionParser.Parse(content, matches, schema.Functions); content = FunctionParser.ParseTriggers(content, matches, schema.TriggerFunctions); content = TypeParser.Parse(content, matches, schema.Types); foreach (PgTable table in schema.Tables) { Console.WriteLine("Generating documentation for table \"{0}\".", table.Name); TableRunner.Run(table); } foreach (PgFunction function in schema.Functions) { Console.WriteLine("Generating documentation for function \"{0}\".", function.Name); FunctionRunner.Run(function); } foreach (PgFunction function in schema.TriggerFunctions) { Console.WriteLine("Generating documentation for trigger function \"{0}\".", function.Name); FunctionRunner.Run(function); } foreach (PgMaterializedView materializedView in schema.MaterializedViews) { Console.WriteLine("Generating documentation for materialized view \"{0}\".", materializedView.Name); MaterializedViewRunner.Run(materializedView); } foreach (PgView view in schema.Views) { Console.WriteLine("Generating documentation for view \"{0}\".", view.Name); ViewRunner.Run(view); } foreach (PgType type in schema.Types) { Console.WriteLine("Generating documentation for type \"{0}\".", type.Name); TypeRunner.Run(type); } string targetPath = System.IO.Path.Combine(OutputPath, schemaName + ".html"); FileHelper.WriteFile(content, targetPath); }
/// <summary> /// Добавление парсера сторонней реализации IFunction /// </summary> /// <param name="parser"></param> /// <returns></returns> public MathParser AddFunctionParser <Function>(FunctionParser <Function> parser) where Function : IFunction, new() { if (_mathparserEntities.Exists(e => e.Name.ToLower() == parser.Name.ToLower())) { throw new Exception($"Wrong name for entity {parser.Name}. There is already entity with the same name"); } _expressionParsers.Add(parser); _mathparserEntities.Add(parser); return(this); }
public void FunctionParserTests_NoArgs() { string function = "beginMonitoringEvents:"; FunctionParser parser = new FunctionParser(); Assert.IsTrue(parser.parseFunction(function)); Assert.AreEqual(parser.Function, "beginMonitoringEvents"); Assert.AreEqual(parser.Arguments.Count, 0); }
public void FunctionParserTests_NoFunctionName() { string function = "foo;bar"; FunctionParser parser = new FunctionParser(); Assert.IsFalse(parser.parseFunction(function)); Assert.AreEqual(parser.Function, null); Assert.AreEqual(parser.Arguments.Count, 0); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultParser"/> class. /// </summary> public DefaultParser() { _state = ParserState.BEGIN; _input = string.Empty; _tree = new ExpTree(); _activeFunctionParser = null; _cache = string.Empty; _parenthesisDepth = 0; _position = 0; }
public void FunctionParserTests_InvalidCharactersInArgument() { string function = "MyFunc:an/arg"; FunctionParser parser = new FunctionParser(); Assert.IsFalse(parser.parseFunction(function)); Assert.AreEqual(parser.Function, "MyFunc"); Assert.AreEqual(parser.Arguments.Count, 0); }
public virtual void Init(NPCStruct npc) { npcStruct = npc; transform.name = npc.nameKor; skills = FunctionParser.ParsingSkillTable(npc.skillValue, dataManager); foreach (Skill skill in Skills) { skill.SetOwner(this); } OnNPCInit(this); }
private void GraphScene3D(Canvas screenCanvas, String eqX, String eqY, String eqZ) { // We do this so we can get good error information. // The values return by these calls are ignored. FunctionParser.Parse(eqX); FunctionParser.Parse(eqY); FunctionParser.Parse(eqZ); PerspectiveCamera camera = new PerspectiveCamera(); camera.Position = new Point3D(0, 0, 5); camera.LookDirection = new Vector3D(0, 0, -2); camera.UpDirection = new Vector3D(0, 1, 0); camera.NearPlaneDistance = 1; camera.FarPlaneDistance = 100; camera.FieldOfView = 45; Model3DGroup group = null; group = new Model3DGroup(); FunctionMesh mesh = new FunctionMesh(eqX, eqY, eqZ, UMin, UMax, VMin, VMax); group.Children.Add(new GeometryModel3D(mesh.CreateMesh(UGrid + 1, VGrid + 1), new DiffuseMaterial(Brushes.Blue))); group.Children.Add(new DirectionalLight(Colors.White, new Vector3D(-1, -1, -1))); Viewport3D viewport = new Viewport3D(); //<newcode> ModelVisual3D sceneVisual = new ModelVisual3D(); sceneVisual.Content = group; viewport.Children.Clear(); viewport.Children.Add(sceneVisual); //</newcode> //viewport.Models = group; viewport.Camera = camera; viewport.Width = CanvasWidth; viewport.Height = CanvasHeight; viewport.ClipToBounds = true; screenCanvas.Children.Clear(); screenCanvas.Children.Add(viewport); _tb = new Trackball(); _tb.Attach(screenCanvas); _tb.Enabled = true; _tb.Servants.Add(viewport); screenCanvas.IsVisibleChanged += new DependencyPropertyChangedEventHandler(screenCanvas_IsVisibleChanged); }
public Tuple <Matrix, double> NewtonsMethod(Matrix x0, double eps, double a = 1, int steps = 100) { int n = function.Variables.Count; FunctionParser[] gradFunctional = new FunctionParser[n]; for (int i = 0; i < n; ++i) { gradFunctional[i] = function.DifferentiateBy(function.Variables[i]);//.Optimize(); } FunctionParser[,] HessianFunctional = new FunctionParser[n, n]; for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { FunctionParser tmp = function.DifferentiateBy(function.Variables[i]); tmp = tmp.DifferentiateBy(function.Variables[j]); tmp = tmp.Optimize(); HessianFunctional[i, j] = HessianFunctional[j, i] = tmp; //function.DifferentiateBy(function.Variables[i]).DifferentiateBy(function.Variables[j]).Optimize(); } } Matrix x = (Matrix)x0.Clone(), grad = CountGrad(x, gradFunctional), HessianMatrix; int step = steps; while (Norm(grad) >= eps && step-- > 0) { HessianMatrix = CountHessian(x, HessianFunctional); Matrix invertedH; if (!HessianMatrix.TryInvert(out invertedH)) { throw new ArgumentException("Ошибка в поиске обратной матрицы!"); } Matrix a_grad = a * grad, mult = a_grad * invertedH; x = x - mult; grad = CountGrad(x, gradFunctional); } if (step < 0) { throw new MethodDivergencyException($"Методу не удалось найти решение за {steps} шагов."); } return(new Tuple <Matrix, double>(x, f(x.ToVector()))); }
public Tuple <Matrix, double> SpeedestDescentMethod(Matrix x0, double epsilon, double a = 1, int steps = 100) { int n = function.Variables.Count, accuracy = 10;// Regex.Match(epsilon.ToString(), @"(?<=[,])\d+").Value.Count(); //заполняем градиент FunctionParser[] gradFunctional = new FunctionParser[n]; for (int i = 0; i < n; ++i) { gradFunctional[i] = function.DifferentiateBy(function.Variables[i]).Optimize(); } //вычисляем градиент в точке x_0 Matrix x = (Matrix)x0.Clone(), grad = CountGrad(x, gradFunctional); int step = steps; //пока ||grad f(x_0)|| >= e while (Norm(grad) >= epsilon && step-- > 0) { string func = function.ToString(); //заменяем цифры в скобках просто цифрами func = Regex.Replace(func, @"[(](\d+)[)]", "$1"); //заменяем переменные x_i на x_i - x * grad_i, чтобы получить функцию одной переменной x for (int i = 0; i < function.Variables.Count; ++i) { string replacedVariable = function.Variables[i], //replacement = grad[i] > 0 ? $"{Math.Round(x[i], accuracy)}-{Math.Round(grad[i], accuracy)}a" : $"{Math.Round(x[i], accuracy)}+{Math.Abs(Math.Round(grad[i], accuracy))}a"; replacement = grad[i] > 0 ? $"{x[i]:f10}-{grad[i]:f10}a" : $"{x[i]:f10}+{Math.Abs(grad[i]):f10}a"; func = Regex.Replace(func, $@"(?<=[(]){replacedVariable}(?=[)])", replacement); func = Regex.Replace(func, replacedVariable, $"({replacement})"); } FunctionParser Ф = new FunctionParser(func); Matrix A = new Matrix(1); A[0] = a; Optimizer support = new Optimizer(Ф); var min = support.NewtonsMethod(A, epsilon); x = x - min.Item1[0] * grad; grad = CountGrad(x, gradFunctional); } if (step < 0) { throw new MethodDivergencyException($"Методу не удалось найти решение за {steps} шагов."); } return(new Tuple <Matrix, double>(x, f(x.ToVector()))); }
private void buttonPenaltyMethod_Click(object sender, EventArgs e) { int error; double[] variables; if (!TryGetMultidimentionalPoint(out variables, out error)) { MessageBox.Show($"Неверное значение переменной в строке {error}!"); return; } MatrixNamespace.Matrix x_0 = new MatrixNamespace.Matrix(variables.Count(), variables); double epsilon; if (!double.TryParse(textBoxEpsilonMultidimentional.Text, out epsilon)) { MessageBox.Show("Неверное значение ε!"); return; } double c; if (!double.TryParse(textBoxC.Text, out c)) { MessageBox.Show("Неверное значение c!"); return; } FunctionParser penaltyFunc; try { penaltyFunc = new FunctionParser(textBoxPenaltyFunc.Text); } catch (Exception) { MessageBox.Show("Не удалось преобразовать строку в функцию, проверьте ввод."); return; } Optimizer opt = new Optimizer(parser); Tuple <MatrixNamespace.Matrix, double> result; try { result = opt.PenaltyMethod(x_0, penaltyFunc, epsilon, c); } catch (MethodDivergencyException ex) { MessageBox.Show(ex.Message); return; } textBoxMultidimentionalX.Text = $"{ result.Item1:F5}"; textBoxMultidimentionalFx.Text = $"{ result.Item2:F5}"; }
private IExpression Parse(string equation, string labelName, string registryName) { try { var exp = FunctionParser.Parse(equation); Registry.SetValue(_regSaveBase, registryName, equation, RegistryValueKind.String); return(exp); } catch (FunctionParserException ex) { throw new InvalidExpressionException("Error in equation: \"" + labelName + "\"", ex); } }
public void FunctionParserTests_TrailingDelim() { string function = "readOffset:ABCD;Int16;myVar;"; FunctionParser parser = new FunctionParser(); Assert.IsTrue(parser.parseFunction(function)); Assert.AreEqual(parser.Function, "readOffset"); Assert.AreEqual(parser.Arguments.Count, 3); Assert.AreEqual(parser.Arguments[0], 0xABCD); Assert.AreEqual(parser.Arguments[1], typeof(short)); Assert.AreEqual(parser.Arguments[2], "myVar"); }
public async Task TryParse_SingleArgument_ReturnsCorrectValue() { var input = new ClosuredObject { HasBeenMutated = false }; var parser = new FunctionParser(); parser.TryParse <ClosuredObject, bool>("HasBeenMutated = true", out var function).Should().BeFalse(); _ = await function.Execute(input); input.HasBeenMutated.Should().BeTrue(); }
public void ParseFormalsTest() { FunctionParser functionParser = new FunctionParser(Init("(param1, param2)")); FunctionDefinition functionDefinition = new FunctionDefinition(); functionParser.ParseFormals(functionDefinition); //Test formals Assert.AreEqual(2, functionDefinition.GetFormals().Count); Formal[] formalArray = (Formal[])functionDefinition.GetFormals().ToArray(); Assert.AreEqual("param1", formalArray[0].ToString()); Assert.AreEqual("param2", formalArray[1].ToString()); }
public void ParseEmptyFunctionDefinitionTest() { FunctionParser functionParser = new FunctionParser(Init("home(param1, param2) \n end")); FunctionDefinition parsedFunctionDefinition = functionParser.ParseFunctionDefinition(); //Test FunctionDefinition Assert.AreEqual("home", parsedFunctionDefinition.GetIdentifier()); Assert.AreEqual(2, parsedFunctionDefinition.GetFormals().Count); //Check formals Formal[] formalArray = (Formal[])parsedFunctionDefinition.GetFormals().ToArray(); Assert.AreEqual("param1", formalArray[0].ToString()); Assert.AreEqual("param2", formalArray[1].ToString()); }
void InitInventory(NPC npc) { this.Log(npc.NPCStruct.nameKor + " : Initialize Inventory"); drops = FunctionParser.ParsingDropTable(npc.NPCStruct.dropTable); foreach (DropStruct drop in drops) { Tube tube = gameManager.FindTubeByCid(drop.cid); if (tube == null) { npc.Warning(npc.NPCStruct.nameKor + " : " + drop.cid + "이 드롭 테이블에 있는데 실제 튜브 데이터에서 찾을 수 없어요."); continue; } GetTube(tube); this.Log(npc.NPCStruct.nameKor + " : Add to Inventory " + tube.NameKor); } }
private void ValidateOption(string value, string registryName) { try { var exp = FunctionParser.Parse(value).Simplify(); if (!(exp is ConstantExpression)) { throw new InvalidExpressionException("The input expression must be constant"); } Registry.SetValue(_regSaveBase, registryName, value, RegistryValueKind.String); } catch (FunctionParserException ex) { throw new InvalidExpressionException("Cannot save value for \"" + registryName + "\"", ex); } }
public Tuple <Matrix, double> MillingStepMethod(Matrix x0, double epsilon, double a = 1, int steps = 100) { int n = function.Variables.Count; //заполняем градиент FunctionParser[] gradFunctional = new FunctionParser[n]; for (int i = 0; i < n; ++i) { gradFunctional[i] = function.DifferentiateBy(function.Variables[i]).Optimize(); } //вычисляем градиент в точке x_0 Matrix x = (Matrix)x0.Clone(), grad = CountGrad(x, gradFunctional); double f_x = f(x0.ToVector()); int step = steps; //пока ||grad f(x_0)|| >= e while (Norm(grad) >= epsilon && step-- > 0) { Matrix tmp = x - (a * grad); double f_tmp = f(tmp.ToVector()); while (f_tmp >= f_x) { if (a == 0) { throw new MethodDivergencyException("Метод расходится!"); } a = a / 2; tmp = x - (a * grad); f_tmp = f(tmp.ToVector()); } x = tmp; f_x = f_tmp; grad = CountGrad(x, gradFunctional); } if (step < 0) { throw new MethodDivergencyException($"Методу не удалось найти решение за {steps} шагов."); } return(new Tuple <Matrix, double>(x, f(x.ToVector()))); }
public void Setup() { _parser = new FunctionParser(); }