Skip to content

Commit

Permalink
enhanced parser substitution
Browse files Browse the repository at this point in the history
  • Loading branch information
chakravala committed Sep 27, 2017
1 parent acebb0f commit 0eefa92
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 40 deletions.
34 changes: 17 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

# Reduce.jl

*Symbolic parser generator for Julia language expressions using REDUCE computer algebra term rewrite system*
*Symbolic parser generator for Julia language expressions using REDUCE algebra term rewrite system*

[![Build Status](https://travis-ci.org/chakravala/Reduce.jl.svg?branch=master)](https://travis-ci.org/chakravala/Reduce.jl) [![Build status](https://ci.appveyor.com/api/projects/status/kaqu2yri4vxyr63n?svg=true)](https://ci.appveyor.com/project/chakravala/reduce-jl) [![Coverage Status](https://coveralls.io/repos/github/chakravala/Reduce.jl/badge.svg?branch=master)](https://coveralls.io/github/chakravala/Reduce.jl?branch=master) [![codecov.io](http://codecov.io/github/chakravala/Reduce.jl/coverage.svg?branch=master)](http://codecov.io/github/chakravala/Reduce.jl?branch=master)
[![](https://img.shields.io/badge/docs-stable-blue.svg)](https://chakravala.github.io/Reduce.jl/stable)
Expand All @@ -26,12 +26,12 @@ Interface for applying symbolic manipulation on [Julia expressions](https://docs

* reduce expressions are `RExpr` objects that can `parse` into julia `Expr` objects and vice versa;
* interface link communicates and interprets via various reduce output modes using `rcall` method;
* high-level reduce-julia syntax parser-generator can walk arbitrary expression to rewrite mathematical code;
* high-level reduce-julia syntax parser-generator walks arbitrary expression to rewrite mathematical code;
* import operators from REDUCE using code generation to apply to arbitrary computational expressions.

## Setup

The `Reduce` package currently provides the base functionality to work with Julia and Reduce expressions, provided that you have `redpsl` in your path. On GNU/Linux/OSX/Windows, `Pkg.build("Reduce")` will automatically download a precompiled binary of `redpsl` for you. If you are running a different Unix operating system, the build script will download the source and attempt to compile `redpsl` for you, success depends on the build tools installed. Automatic download on Windows is now supported.
The `Reduce` package currently provides the base functionality to work with Julia and Reduce expressions, provided that you have `redpsl` in your path. On GNU/Linux/OSX/Windows, `Pkg.build("Reduce")` will automatically download a precompiled binary for you. If you are running a different Unix operating system, the build script will download the source and attempt to compile `redpsl` for you, success depends on the build tools installed. Automatic download on Windows is supported.

```Julia
julia> Pkg.add("Reduce"); Pkg.build("Reduce")
Expand All @@ -41,19 +41,6 @@ Reduce (Free PSL version, revision 4015), 5-May-2017 ...

View the documentation [stable](https://chakravala.github.io/Reduce.jl/stable) / [latest](https://chakravala.github.io/Reduce.jl/latest) for more features and examples.

## Background

The `Reduce` package currently provides a robust interface to directly use the PSL version of REDUCE within the Julia language and the REPL. This is achieved by interfacing the abstract syntax tree of `Expr` objects with the parser generator for `RExpr` objects and then using an `IOBuffer` to communicate with `redpsl`.

> REDUCE is a system for doing scalar, vector and matrix algebra by computer, which also supports arbitrary precision numerical approximation and interfaces to gnuplot to provide graphics. It can be used interactively for simple calculations but also provides a full programming language, with a syntax similar to other modern programming languages.
> REDUCE has a long and distinguished place in the history of computer algebra systems. Other systems that address some of the same issues but sometimes with rather different emphasis are Axiom, Macsyma (Maxima), Maple and Mathematica.
> REDUCE is implemented in Lisp (as are Axiom and Macsyma), but this is completely hidden from the casual user. REDUCE primarily runs on either Portable Standard Lisp (PSL) or Codemist Standard Lisp (CSL), both of which are included in the SourceForge distribution. PSL is long-established and compiles to machine code, whereas CSL is newer and compiles to byte code. Hence, PSL may be faster but CSL may be available on a wider range of platforms.
Releases of `Reduce.jl` enable the general application of various REDUCE functionality and packages to manipulate the Julia language to simplify and compute new program expressions at run-time. Intended for uses where a symbolic pre-computation is required for numerical algorithm code generation.

> Julia is a high-level, high-performance dynamic programming language for numerical computing. It provides a sophisticated compiler, distributed parallel execution, numerical accuracy, and an extensive mathematical function library. Julia’s Base library, largely written in Julia itself, also integrates mature, best-of-breed open source C and Fortran libraries for linear algebra, random number generation, signal processing, and string processing.
> The strongest legacy of Lisp in the Julia language is its metaprogramming support. Like Lisp, Julia represents its own code as a data structure of the language itself. Since code is represented by objects that can be created and manipulated from within the language, it is possible for a program to transform and generate its own code. This allows sophisticated code generation without extra build steps, and also allows true Lisp-style macros operating at the level of abstract syntax trees.
## Usage

Reduce expressions encapsulated into `RExpr` objects can be manipulated within julia using the standard syntax. Create an expression object either using the `RExpr("expression")` string constructor or `R"expression"`. Additionally, arbitrary julia expressions can also be parsed directly using the `RExpr(expr)` constructor. Internally `RExpr` objects are represented as an array that can be accessed by calling `*.str[n]` on the object.
Expand All @@ -69,7 +56,7 @@ quote
-(((log((x ^ 2 - x) + 1) - 2 * log(x + 1)) - 2 * sqrt(3) * atan((2x - 1) // sqrt(3)))) // 6
end
```
Call `split(::RExpr)` to create a new `RExpr` object with all `Reduce` expressions split into separate array elements.
Call `split(::RExpr)` to create a new `RExpr` object with all expressions split into separate array elements.

The `rcall` method is used to evaluate any type of expression.
```Julia
Expand Down Expand Up @@ -135,6 +122,19 @@ reduce> df(atan(golden_ratio*x),x);
2*(x + 3*x + 1)
```

## Background

The `Reduce` package currently provides a robust interface to directly use the PSL version of REDUCE within the Julia language and the REPL. This is achieved by interfacing the abstract syntax tree of `Expr` objects with the parser generator for `RExpr` objects and then using an `IOBuffer` to communicate with `redpsl`.

> REDUCE is a system for doing scalar, vector and matrix algebra by computer, which also supports arbitrary precision numerical approximation and interfaces to gnuplot to provide graphics. It can be used interactively for simple calculations but also provides a full programming language, with a syntax similar to other modern programming languages.
> REDUCE has a long and distinguished place in the history of computer algebra systems. Other systems that address some of the same issues but sometimes with rather different emphasis are Axiom, Macsyma (Maxima), Maple and Mathematica.
> REDUCE is implemented in Lisp (as are Axiom and Macsyma), but this is completely hidden from the casual user. REDUCE primarily runs on either Portable Standard Lisp (PSL) or Codemist Standard Lisp (CSL), both of which are included in the SourceForge distribution. PSL is long-established and compiles to machine code, whereas CSL is newer and compiles to byte code. Hence, PSL may be faster but CSL may be available on a wider range of platforms.
Releases of `Reduce.jl` enable the general application of various REDUCE functionality and packages to manipulate the Julia language to simplify and compute new program expressions at run-time. Intended for uses where a symbolic pre-computation is required for numerical algorithm code generation.

> Julia is a high-level, high-performance dynamic programming language for numerical computing. It provides a sophisticated compiler, distributed parallel execution, numerical accuracy, and an extensive mathematical function library. Julia’s Base library, largely written in Julia itself, also integrates mature, best-of-breed open source C and Fortran libraries for linear algebra, random number generation, signal processing, and string processing.
> The strongest legacy of Lisp in the Julia language is its metaprogramming support. Like Lisp, Julia represents its own code as a data structure of the language itself. Since code is represented by objects that can be created and manipulated from within the language, it is possible for a program to transform and generate its own code. This allows sophisticated code generation without extra build steps, and also allows true Lisp-style macros operating at the level of abstract syntax trees.
## Troubleshooting

If the `reduce>` REPL is not appearing when `}` is pressed or the `Reduce.PSL` pipe is broken, the session can be restored by simply calling `Reduce.Reset()`, without requiring a restart of `julia` or reloading the package. This kills the currently running `redpsl` session and then re-initializes it for new use.
Expand Down
33 changes: 21 additions & 12 deletions docs/src/index.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Reduce.jl

*Symbolic parser generator for Julia language expressions using REDUCE computer algebra term rewrite system*
*Symbolic parser generator for Julia language expressions using REDUCE algebra term rewrite system*


```@contents
Expand All @@ -10,21 +10,30 @@

REDUCE is a system for general algebraic computations of interest to mathematicians, scientists and engineers:

* exact arithmetic using integers and fractions; arbitrary precision numerical approximation;
* polynomial and rational function algebra; factorization and expansion of polynomials and rational functions;
* differentiation and integration of multi-variable functions; exponential, logarithmic, trigonometric and hyperbolic;
* output of results in a variety of formats; automatic and user controlled simplification of expressions;
* substitutions and pattern matching of expressions; quantifier elimination and decision for interpreted first-order logic;
* solution of ordinary differential equations; calculations with a wide variety of special (higher transcendental) functions;
* calculations involving matrices with numerical and symbolic elements; general matrix and non-commutative algebra;
* powerful intuitive user-level programming language; generating optimized numerical programs from symbolic input;
* Dirac matrix calculations of interest to high energy physicists; solution of single and simultaneous equations.
* exact arithmetic using integers and fractions;
* arbitrary precision numerical approximation;
* polynomial and rational function algebra;
* factorization and expansion of polynomials and rational functions;
* differentiation and integration of multi-variable functions;
* exponential, logarithmic, trigonometric and hyperbolic;
* output of results in a variety of formats;
* automatic and user controlled simplification of expressions;
* substitutions and pattern matching of expressions;
* quantifier elimination and decision for interpreted first-order logic;
* solution of ordinary differential equations;
* calculations with a wide variety of special (higher transcendental) functions;
* calculations involving matrices with numerical and symbolic elements;
* general matrix and non-commutative algebra;
* powerful intuitive user-level programming language;
* generating optimized numerical programs from symbolic input;
* Dirac matrix calculations of interest to high energy physicists;
* solution of single and simultaneous equations.

Interface for applying symbolic manipulation on [Julia expressions](https://docs.julialang.org/en/latest/manual/metaprogramming) using [REDUCE](http://www.reduce-algebra.com)'s term rewrite system:

* reduce expressions are `RExpr` objects that can `parse` into julia `Expr` objects and vice versa;
* interface link communicates and interprets via various reduce output modes using `rcall` method;
* high-level reduce-julia syntax parser-generator can walk arbitrary expression to rewrite mathematical code;
* high-level reduce-julia syntax parser-generator walks arbitrary expression to rewrite mathematical code;
* import operators from REDUCE using code generation to apply to arbitrary computational expressions.

## Setup
Expand Down Expand Up @@ -67,7 +76,7 @@ quote
-(((log((x ^ 2 - x) + 1) - 2 * log(x + 1)) - 2 * sqrt(3) * atan((2x - 1) // sqrt(3)))) // 6
end
```
Call `split(::RExpr)` to create a new `RExpr` object with all `Reduce` expressions split into separate array elements.
Call `split(::RExpr)` to create a new `RExpr` object with all expressions split into separate array elements.

The `rcall` method is used to evaluate any type of expression.
```Julia
Expand Down
27 changes: 16 additions & 11 deletions src/rexpr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ function split(r::RExpr)
end

const r_to_jl = Dict(
"i" => "im",
"euler_gamma" => "eulergamma",
"infinity" => "Inf"
)
Expand All @@ -145,12 +146,12 @@ const r_to_jl_utf = Dict(
"pi" => "π",
"golden_ratio" => "φ",
"**" => "^",
#":=" => "=",
"/" => "//"
)

const jl_to_r = Dict(
#"eu" => "euler_gamma",
"im" => "i",
"eu" => "euler_gamma",
"eulergamma" => "euler_gamma",
"golden" => "golden_ratio",
"Inf" => "infinity"
Expand All @@ -161,24 +162,23 @@ const jl_to_r_utf = Dict(
"γ" => "euler_gamma",
"φ" => "golden_ratio",
"^" => "**",
#"=" => ":=",
"//" => "/"
)

# convert substitution dictionary into SUB parameter string
function _syme(syme::Dict{String,String})
str = ""
for key in keys(syme)
str = str*"($key)=($(syme[key])),"
str = str*"($key => $(syme[key])),"
end
return str[1:end-1]
end

const symrjl = _syme(r_to_jl)
reprjl = Dict(r_to_jl...,r_to_jl_utf...)
reprjl = r_to_jl_utf
const symjlr = _syme(jl_to_r)
const repjlr = Dict(jl_to_r...,jl_to_r_utf...)
# _subst(syme::String,expr) = "sub({$syme},$expr)" |> RExpr |> rcall
const repjlr = jl_to_r_utf
_subst{T}(syme::String,expr::T) = convert(T, "!*hold($expr)\$ ws where $syme" |> rcall)

Rational = ( () -> begin
gs = true
Expand All @@ -194,7 +194,7 @@ function JSymReplace(str::Compat.String)
for key keys(repjlr)
str = replace(str,key,repjlr[key])
end
ImParse() && !isinfix(str) && (str = str*"\$ ws where im => i" |> rcall)
ImParse() && !isinfix(str) && (str = _subst(symjlr,str))
return str
end

Expand All @@ -213,7 +213,7 @@ cos(---------------) + sinh(x)*i
RExpr(expr::Expr) = expr |> unparse |> RExpr |> split

function RSymReplace(str::String)
ImParse() && (str = str*"\$ ws where i => im" |> rcall)
ImParse() && (str = _subst(symrjl,str))
for key in keys(reprjl)
str = replace(str,key,reprjl[key])
end
Expand Down Expand Up @@ -343,8 +343,13 @@ function rcall(r::RExpr;
trim = false
expo = false
for o in ona
o == :expand ? (ons = ons*"on exp\$ ") : (ons = ons*"on $o\$ ")
o == :expand ? (onr = onr*"; off exp ") : (onr = onr*"; off $o ")
if o == :expand
ons = ons*"on exp\$ "
onr = onr*"; off exp "
else
ons = ons*"on $o\$ "
onr = onr*"; off $o "
end
o == :factor && (expo = true)
o in offa && throw(ReduceError("Invalid: switch on and off at once"))
o in [:latex,:nat] && (mode = false)
Expand Down

0 comments on commit 0eefa92

Please sign in to comment.