From 7b63aa09a03b3b680b188ebdd68b5af3c3900392 Mon Sep 17 00:00:00 2001 From: MilesCranmer Date: Mon, 29 Apr 2024 13:57:22 +0100 Subject: [PATCH] docs: improve `@parse_expression` docs --- docs/src/utils.md | 6 ++++++ src/Parse.jl | 29 +++++++++++++++++++++++++---- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/docs/src/utils.md b/docs/src/utils.md index d3b0acc4..e862c344 100644 --- a/docs/src/utils.md +++ b/docs/src/utils.md @@ -1,5 +1,11 @@ # Node utilities +## Creating trees + +```@docs +@parse_expression +``` + ## `Base` Various functions in `Base` are overloaded to treat an `AbstractNode` as a diff --git a/src/Parse.jl b/src/Parse.jl index f3998322..0719d21e 100644 --- a/src/Parse.jl +++ b/src/Parse.jl @@ -12,18 +12,21 @@ using ..ExpressionModule: AbstractExpression, Expression Parse a symbolic expression `expr` into a computational graph where nodes represent operations or variables. ## Arguments + - `expr`: An expression to parse into an `AbstractExpression`. + +## Keyword Arguments + - `operators`: An instance of `OperatorEnum` specifying the available unary and binary operators. - `variable_names`: A list of variable names as strings or symbols that are allowed in the expression. - `evaluate_on`: A list of external functions to evaluate explicitly when encountered. - -## Keyword Arguments - `node_type`: The type of the nodes in the resulting expression tree. Defaults to `Node`. ## Usage + The macro is used to convert a high-level symbolic expression into a structured expression tree that can be manipulated or evaluated. Here are some examples of how to use `parse_expression`: -- Parsing a simple mathematical expression involving custom operations: +### Parsing from a custom operator ```julia julia> my_custom_op(x, y) = x + y^3; @@ -44,7 +47,7 @@ julia> ex(ones(2, 1)) 2.487286478935302 ``` -- Handling expressions with symbolic variable names, and custom node types: +### Handling expressions with symbolic variable names ```julia julia> ex = @parse_expression( @@ -58,6 +61,24 @@ cos(exp(α)) julia> typeof(ex.tree) GraphNode{Float32} ``` + +### Using external functions and variables + +``` +julia> c = 5.0 +5.0 + +julia> show_type(x) = (@show typeof(x); x); + +julia> ex = @parse_expression( + c * 2.5 - show_type(cos(x)), + operators = OperatorEnum(; binary_operators=[*, -], unary_operators=[cos]), + variable_names = [:x], + evaluate_on = [show_type], + ) +typeof(x) = Node{Float32} +(5.0 * 2.5) - cos(x) +``` """ macro parse_expression(ex, kws...) # Initialize default values for operators and variable_names