Giter Club home page Giter Club logo

ryacas's Introduction

Ryacas

Build Status Build status JOSS status DOI

Ryacas is an R interface to the free yacas Computer Algebra System. Ryacas allows one to send unprocessed yacas strings and certain other R objects to yacas process from R and get back the result. It also has facilities for manipulating yacas strings and R expressions destined for yacas processing.

It can be used for arbitrary-precision arithmetic, symbolic math, ASCII pretty printing and translating R to TeX.

Install from GitHub

To build and install from Github using R 3.3.0 (or later) and the R devtools package 1.11.0 (or later) run this command from within R:

devtools::install_github("r-cas/ryacas", 
                         build_opts = c("--no-resave-data", "--no-manual"))

You can also install the package without vignettes if needed as follows:

devtools::install_github("r-cas/ryacas")

Online info

For vignettes, overview, pointers to additional information, installation instructions and a sample session see http://r-cas.github.io/ryacas/.

Yacas documentation can be found at http://yacas.readthedocs.org/.

Contribute, issues, and support

Please use the issue tracker at https://github.com/r-cas/ryacas/issues if you want to notify us of an issue or need support. If you want to contribute, please either create an issue or make a pull request.

Brief examples

Below we show a few examples. We highly recommend reading the “Getting started” vignette (and the other vignettes) for a more thorough introduction to the package.

There are two interfaces: a high-level interface that makes yacas objects work similar to R objects, and a low-level interface where the user can write yacas code and get results as strings or as R expressions. Below, we demonstrate both.

High-level interface

A brief example with a polynomial is:

x <- ysym("x")
p <- x^2+x-6
p
#> y: x^2+x-6
y_fn(p, "Factor")
#> y: (x-2)*(x+3)
p %>% y_fn("Factor")
#> y: (x-2)*(x+3)
p %>% as_r()
#> expression(x^2 + x - 6)

A small matrix example follows:

A <- outer(0:3, 1:4, "-") + diag(2:5)
a <- 1:4
B <- ysym(A)
B
#> {{ 1, -2, -3, -4},
#>  { 0,  2, -2, -3},
#>  { 1,  0,  3, -2},
#>  { 2,  1,  0,  4}}
solve(B)
#> {{   37/202,     3/101,    41/202,    31/101},
#>  {(-17)/101,    30/101,     3/101,     7/101},
#>  {(-19)/202,  (-7)/101,    39/202,  (-5)/101},
#>  { (-5)/101,  (-9)/101, (-11)/101,     8/101}}
B[2, 3] <- "x"
B
#> {{ 1, -2, -3, -4},
#>  { 0,  2,  x, -3},
#>  { 1,  0,  3, -2},
#>  { 2,  1,  0,  4}}
b <- ysym(a)
b[1] <- "x"
b
#> {x, 2, 3, 4}
B %*% b
#> {x-29, 3*x+4-12, x+9-8, 2*x+18}
t(B)
#> {{ 1,  0,  1,  2},
#>  {-2,  2,  0,  1},
#>  {-3,  x,  3,  0},
#>  {-4, -3, -2,  4}}
B[, 2:3]
#> {{-2, -3},
#>  { 2,  x},
#>  { 0,  3},
#>  { 1,  0}}

Low-level interface

Returning strings with yac_str():

yac_str("x+x+x+x")
#> [1] "4*x"
yac_str("Factor(x^2+x-6)")
#> [1] "(x-2)*(x+3)"
yac_str("D(x) x^2+x-6")
#> [1] "2*x+1"

Returning R expressions with yac_expr():

yac_expr("x+x+x+x")
#> expression(4 * x)
eval(yac_expr("x+x+x+x"), list(x = 4))
#> [1] 16
yac_expr("Factor(x^2+x-6)")
#> expression((x - 2) * (x + 3))
yac_expr("D(x) x^2+x-6")
#> expression(2 * x + 1)

Using functions easier (using magrittr’s pipe, %>%):

"x^2+x-6" %>% y_fn("Factor") %>% yac_str()
#> [1] "(x-2)*(x+3)"
"x^2+x-6" %>% y_fn("D(x)") %>% yac_expr()
#> expression(2 * x + 1)

Solving equations (removes the x== from yacas with the y_rmvars() function):

sol <- yac_str("Solve(x^2+x-6 == 0, x)")
sol
#> [1] "{x==2,x==(-3)}"
sol %>% y_rmvars() %>% yac_str()
#> [1] "{2,-3}"
sol %>% y_rmvars() %>% yac_expr()
#> expression(c(2, -3))
sol %>% y_rmvars() %>% yac_expr() %>% eval()
#> [1]  2 -3

And output in TeX:

"3/4 + Pi/8" %>% y_fn("Simplify") %>% y_fn("TeXForm") %>% yac_str()
#> [1] "\\frac{\\pi  + 6}{8} "

And arbitrary precision (see also the “Arbitrary-precision arithmetic” vignette):

yac_str("N(Pi, 50)")
#> [1] "3.1415926535897932384626433832795028841971693993751058209"

Yacas

The package contains the yacas distribution. The development of the yacas source code is available at https://github.com/grzegorzmazur/yacas/ . For more information on yacas see http://www.yacas.org/ or the documention directly at https://yacas.readthedocs.io/.


Mikkel Meyer Andersen, mikl at math dot aau dot dk
Rob Goedman, goedman at mac dot com
Gabor Grothendieck, ggrothendieck at gmail dot com
Søren Højsgaard, sorenh at math dot aau dot dk
Ayal Pinkus, apinkus at xs4all dot nl
Grzegorz Mazur, teoretyk at gmail dot com

ryacas's People

Contributors

ggrothendieck avatar grzegorzmazur avatar hojsgaard avatar jeksterslab avatar mikldk avatar pbosetti avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ryacas's Issues

How to connect yacas with rstudio

Hi,
I already downloaded Yacas on my windows. I first installed package Ryacas directly from Rstudio but no yacas functions can be run.
I later ran this command and got the following errors:

> devtools::install_github("r-cas/ryacas", build_opts = c("--no-resave-data", "--no-manual"))
Downloading GitHub repo r-cas/ryacas@HEAD
√  checking for file 'C:\Users\Esther\AppData\Local\Temp\RtmpEpL65w\remotes58d46bf01207\r-cas-ryacas-ea52235/DESCRIPTION' (684ms)
-  preparing 'Ryacas': (1.4s)
√  checking DESCRIPTION meta-information ... 
-  cleaning src
-  checking for LF line-endings in source and make files and shell scripts (1s)
-  checking for empty or unneeded directories (501ms)
-  building 'Ryacas_1.1.3.9002.tar.gz'
   
Installing package into ‘C:/Users/Esther/Documents/R/win-library/4.1’ as ‘lib’ is unspecified)
* installing *source* package 'Ryacas' ...
ERROR: cannot remove earlier installation, is it in use?
* removing 'C:/Users/Esther/Documents/R/win-library/4.1/Ryacas'
* restoring previous 'C:/Users/Esther/Documents/R/win-library/4.1/Ryacas'
Warning in file.copy(lp, dirname(pkgdir), recursive = TRUE, copy.date = TRUE) :
  problem copying C:\Users\Esther\Documents\R\win-library\4.1\00LOCK-Ryacas\Ryacas\libs\x64\Ryacas.dll to C:\Users\Esther\Documents\R\win-library\4.1\Ryacas\libs\x64\Ryacas.dll: Permission denied
Warning message:
In i.p(...) :
  installation of package ‘C:/Users/ESTHER~1/AppData/Local/Temp/RtmpEpL65w/file58d4192555cc/Ryacas_1.1.3.9002.tar.gz’ had non-zero exit status

How to run/install ryacas?

Thanks

Sum and product

With 1.1.1, sum(expression, variable, lower, upper) can make summation as in yacas (summing an expression by letting a variable taking values from lower to upper).

But a simple

x <- ysym("x")
vec <- c(2*x, x)
sum(vec)
prod(vec)

is not possible.

Solving systems of equations with unknowns as functions

Hi,
I tried to evaluate a system of equations while keeping all the variables as functions. Symbolic solution might be the answer but still I have some coding issues that need help.

Settings:

pi's are functions of t, unknown, and what I want to find. Their expressions are very ugly. They are needed to take higher order derivatives

pi = (pi0, pi1, pi2) 
pi0 + pi1 + pi2 = 1

Q = rbind((q1, q2, q3) , (q4, q5, q6) , (q7, q8, q9))

All the q are functions of t; and

q1 = q2+q3
q5 = q4+q6
q9 = q7+q8

All q have the same format but different parameters (delta, beta, Z vary by q but values will be given)

q <- function(t, delta, beta, Z) {t^delta / (1+t^delta) * exp(beta'Z)}

I use simplify() from yacas to simplify each q, given delta, beta, Z,

  q1 <- simplify(q(t, deltas[1,1], beta, Z))
  q2 <- simplify(q(t, deltas[1,2], beta, Z))
  q3 <- simplify(q1+q2)

... same for the rest of q's

> q2
{(0.1351286808*(x==1)^0.4)/(0.0965204863*(x==1)^1.4+1), (0.1351286808*(y==1)^0.4)/(0.0965204863*(y==1)^1.4+1)} 
> q3
{(0.0629721536*(x==1)^1.1)/(0.0299867398*(x==1)^2.1+1), (0.0629721536*(y==1)^1.1)/(0.0299867398*(y==1)^2.1+1)} 
> q1
{((-0.0040520686)*(x==1)^2.5-0.1351286808*(x==1)^0.4-0.0060781028*(x==1)^2.5-0.0629721536*(x==1)^1.1)/(0.0028943347*(x==1)^3.5+0.0965204863*(x==1)^1.4+0.0299867398*(x==1)^2.1+1), ((-0.0040520686)*(y==1)^2.5-0.1351286808*(y==1)^0.4-0.0060781028*(y==1)^2.5-0.0629721536*(y==1)^1.1)/(0.0028943347*(y==1)^3.5+0.0965204863*(y==1)^1.4+0.0299867398*(y==1)^2.1+1)} 

I need to get pi(t) by solving pi(t) * Q(t) = 0, while pi(t) are 3x1.

I cannot substituting t in pi(t) first because I later need to take the derivatives of pi(t) .

My plan is to manually add and multiple all the functions and put them into a system, and then use oldSolve() in yacas

pi0 * q1 + pi1 * q4 + pi2 * q7 = 0
pi0 * q2 + pi1 * q5 + pi2 * q8 = 0
pi0 * q3 + pi1 * q6 + pi2 * q9 = 0

However, how should I code pi0, pi1 ? pi0 <- pi1 <- function(t) {...} ?

How to use oldSolve (or other better options) for my case? oldSolve seems to handle something like ax+by+cz=0; ..., where a,b,c are scalars.

Thanks

conflicts with base r functions

When I load Ryacas package, it conflicts with base R's functions

library(Ryacas)

Attaching package: 'Ryacas'

The following object is masked from 'package:stats':

    integrate

The following objects are masked from 'package:base':

    %*%, diag, diag<-, lower.tri, upper.tri

> conflicts()
[1] "integrate" "%*%"       "body<-"    "diag"      "diag<-"    "kronecker" "lower.tri" "plot"      "upper.tri"

I don't think it's also good idea like dplyr

Solving an equality doesn't work with powers of ten by the degree of 11 or so

My code:

MASS_PROTON = 1.6726219e-27 ELEMENTARYCHARGE = 1.6E-19 library(Ryacas) equality = paste(MASS_PROTON * 35e6 ^ 2, "/ radius ==", ELEMENTARYCHARGE * 35e6 * .5 * sin(pi / 2), sep = " ") equality radiusOfProton = eval(parse(text = yac_str(y_rmvars(paste("Solve(", equation, ", radius)", sep = "")))))
The result:

Error in eval(parse(text = yac_str(y_rmvars(paste("Solve(", equation, :
object 'Undefined' not found
Calls: ... withCallingHandlers -> withVisible -> eval -> eval -> eval -> eval
Execution halted

The solver should recognize that it's possible to cancel out some degrees of ten before trying to do a calculation with a large or very zero-close number. If I perfom the calculation manually:

2.0489618275e-12 / 2.8e-12

then I see the correct result:

[1] 0.7317721

installation problem due to libcurl

Googling relevant issues with curl/libcurl didn't help much. Installation from CRAN went through just fine. Any hints how to fix this are appreciated.

> devtools::install_github("ggrothendieck/ryacas")
Installation failed: unable to load shared object '/Library/Frameworks/R.framework/Versions/3.3/Resources/library/curl/libs/curl.so':
  dlopen(/Library/Frameworks/R.framework/Versions/3.3/Resources/library/curl/libs/curl.so, 6): Library not loaded: /opt/local/lib/libcurl.4.dylib
  Referenced from: /Library/Frameworks/R.framework/Versions/3.3/Resources/library/curl/libs/curl.so
  Reason: Incompatible library version: curl.so requires version 9.0.0 or later, but libcurl.4.dylib provides version 7.0.0
> sessionInfo()
R version 3.3.3 (2017-03-06)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: macOS Sierra 10.12.3

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] tools_3.3.3
> packageVersion("devtools")
[1] ‘1.12.0.9000’

combine vignettes

Ryacas originally had a single vignette which made it very easy to search through it for something but now it has been split up making it much harder to locate anything since you have to search them one by one which is really tedious.

Also Ryacas0 has been split up too.

In both these packages all vignettes should be combined into one vignette to make it easier to find stuff. This is really a big impediment to using these packages in my opinion.

Remove dontrun in examples

Martin Maechler mentioned that now that yacas is part of the Ryacas package the \dontrun in the help file examples could be removed.

JOSS Review Issues

Thank you for your work on this software package and corresponding paper. CAS is somewhat out of my field of expertise (other than fairly basic use) but should the need arise I think this would make a useful addition to my workflow.

From a usability perspective, everything worked as described in the repository and the few tests I ran also went successfully. There are a couple of minor issues that I have identified:

  • The repository is missing an OSI compatible license.
  • The vignettes do not appear to be accessible from within R (and weren't listed by using vigentte(pkg="ryacas"). It's unclear to be whether they are supposed to be, but I think it would be a nice addition and in line with R package standards.
  • There are currently no guidelines for contribution, reporting issues or seeking support.

Otherwise, I believe the package/paper is ready for publication.

PrettyForm output too narrow

If I get a large equation in the environment:
...
then it is folding it to several parts which is inconvenient
even the Rstudio default wideness is larger than this.
Could you not fold it?

/
|
|
|
|
|
|
\

                         2 * pi * AR                    

/             2                                         
| /  2 * AR  \                                          
| | -------- |    /       2                         2 \ 

sqrt\ \ pi * ClA / * \ 1 - Ma + tan( sweep _ quarter ) /

      \
      |

--------- |
\ |
| |
| |

  • 4 / + 2 |
    /

But this folding is invisible from r

a=PrettyForm.Func(ClA_correction_trapsimp)
a

/
|
|
|
|
|
|
\

                         2 * pi * AR                    

/             2                                         
| /  2 * AR  \                                          
| | -------- |    /       2                         2 \ 

sqrt\ \ pi * ClA / * \ 1 - Ma + tan( sweep _ quarter ) /

      \
      |

--------- |
\ |
| |
| |

  • 4 / + 2 |
    /

str(a)
Classes 'Sym', 'character' chr "( PrettyForm( {\n 2 * pi * AR/(2 + sqrt(4 + (AR/(ClA/2 * pi))^2 * ((1 - Ma^2) + tan(sweep_quarter)^2)))\n} ) )"

Thank you

Having trouble installing with devtools

Hi there.

I'm trying to run my friend's code from here.

I'm on a Debian desktop:

jj5@orac:~$ uname -a
Linux orac 3.16.0-4-amd64 #1 SMP Debian 3.16.39-1+deb8u1 (2017-02-22) x86_64 GNU/Linux

I had GNU R and R Commander installed from before.

So over here I found this command to run within R:

devtools::install_github("ggrothendieck/ryacas")

But I didn't have the devtools package. So over here I found this command to run within R to install the devtools package:

install.packages("devtools")

But it didn't work so I tried installing dependencies:

sudo apt-get install r-cran-curl r-cran-httr

Then I was able to install devtools in R:

install.packages("devtools")

I had trouble with the AU mirrors, I used USA (CA 1) and that worked.

Then I tried installing Ryacas via devtools in R again:

devtools::install_github("ggrothendieck/ryacas")

But when I do I get:

[3] ERROR: argument is of length zero

Not sure what my next move is. Help?

abs not recognized in quadratic formula

Trying to reproduce the solutions to the quadratic formula reveals what appears to be a bug in yac_expr.

"Solve(a^2 + b^2 == c^2, b)" %>%
  yac_str() %>%
  yac_expr()

For me this returns:

expression(c(b == sqrt(fabs(a^2 - c^2)) * complex(1, cos(Arg(c^2 -
a^2)/2), sin(Arg(c^2 - a^2)/2)), b == sqrt(fabs(a^2 - c^2)) *
complex(1, cos((Arg(c^2 - a^2) + 2 * pi)/2), sin((Arg(c^2 -
a^2) + 2 * pi)/2))))

fabs is not an R function in any of the packages I have installed. In other words, ??fabs produces 'No results found' for me. Surely this should be recognized as abs?

New tutorial proposal - Ryacas

ZIP unavialiable temporarily as I am changing the list of contents. Sorry for this inconvenience. Please read the following info. Suggestions are welcomed. Thank you.
@grzegorzmazur @hojsgaard @mikldk
#21
I will update this once every 3 days typically in this Month to get the main things settled.

As is known to one who may concerns, Ryacas has no down-to-earth English tutorials to follow on R courses or YouTube or major blocks, which made it real difficult to have more users and contributors to better the project itself and explore wider applications with R itself.

The linkage of a CAS system and R can be cruicial to a lot of mathamatic modeling and statitistical pre-modeling and can possibly speed up the workflow of certain project or research. Ryacas provide so far the best (at least I think in terms of compatibility, reliability and power).

A new tutorial would address the problem mentioned above and would be beneficial for both R and Yacas. Taking the advantage of the symbolic object convertion and expression derivations and evaluations more complexed modelling can be (OR HAVE BEEN) demonstrated.

The tutorial MUST cover:

  • Installation and quick explorations with base R and Ryacas.(done)
  • Yacas syntax and comparisions on different levels(I am horrible at this)
  • Different levels of Ryacas: yacmode(), yacas() and Sym() (most encouraged), usage, pros& cons, tips of avoiding nuissances(lol)
  • Examples: Ryacas in action - solve pure / applied math problems with code provided and discussed.(I have done some) (plenty of my previous codes to be organized)
  • Further development and deeper discussions of the parsing system. And tips to require() the package to do further tasks(well, this may offend some people though)

IMPORTANT Main Structure to be discussed

Operating level to be discussed separately or together with CAS?
Main directions to develop, Exploratory calculation or part of modelling workflow?

Discuss cases when a CAS is needed within a language environment

symbolic derivation for;

  • eq solving
  • simplification
  • judging the state of a system

mixed computation when;

  • technical judgement in numerical computation is needed
  • computation modules needed as extension of n computing

Questions:

Who is also engaged and want to be one of the authors?

How should we licence the work? Creative Common? GNU FDL? R docu with(C)?

How should we share the work? Via Blogs? Gitbooks?

Should we make videos or prioritize on the tutorial?

12/19Update: I only found one existing Ryacas Tutorial on Youtube and Yacas tutorials have been absent from major platforms.

I would like to thank all of you for making it better.

Integration problem

Hello,

I tried to use the Ryacas library to calculate a pair of integrals, and to test the function, I tried to integrate different functions, finding that by setting functions of the form

  • x^a * exp(-x)

with a > 1, the result obtained is incorrect.

For example, I used the following code

library(Ryacas)
yac_expr("Integrate(x) x^2* Exp(-(x))")

the result obtained is

expression(-2 * exp(-x) - x^2 * exp(-x))

when the real result is

  • -2 * exp(-x) - 2 * x * exp(-x) - x^2 * exp(-x)

where it is observed that the value - 2 * x * exp(-x) is omitted.

Due to this I tried using the caracas library to replicate the exercise and I got the following result

library(caracas)
sympy <- get_sympy()
x <- sympy$symbols('x')
fun <- "x**2 * exp(-x)"
sympy$integrate(fun, x)

(-x**2 - 2*x - 2)*exp(-x)

Which matches with the correct result.

I hope you can give a look to the error that mentioned above since I would like to use the Ryacas library to teach my students to solve integrals and derivatives not evaluated in R.

Thank you very much and I look forward to your comments.

PrettyForm generates some garbage at end

This works except that it also generates some garbage (unprocessed XML) at the end.

> library(Ryacas)
> d <- Sym("d")
> S <- (281*d^6)/128+((-65)*d^5)/32+(29*d^4)/16+((-3)*d^3)/2+d^2
> PrettyForm(S)

       6         5         4        3     
281 * d    65 * d    29 * d    3 * d     2
-------- - ------- + ------- - ------ + d 
  128        32        16        2        

<OMOBJ>
  <OMS cd="logic1" name="true"/>
</OMOBJ>

R 3.4.1 warnings

I am trying to use Ryacas 0.3-1 with R 3.4.1, and I get these warnings:

Warning messages:
1: In structure(x$children, class = "XMLNodeList") :
    Calling 'structure(NULL, *)' is deprecated, as NULL cannot have
attributes.
    Consider 'structure(list(), *)' instead. 

The warnings arise in the orphaned XML package that is called from OpenMath2R. A patch suggestion using the xml2 package instead is below:

diff --git a/R/OpenMath2R.R b/R/OpenMath2R.R
index 8738349..957ce60 100644
--- a/R/OpenMath2R.R
+++ b/R/OpenMath2R.R
@@ -1,35 +1,35 @@
-
 OpenMath2R <- function(x) {
  out <- c()
  recurse <- function( x ) {
-	if ("name" %in% names(xmlAttrs(x))) {
-		out <<- c(out, trans(xmlAttrs(x)[["name"]], from="OM", to="R"), " ")
+	if ("name" %in% names(xml2::xml_attrs(x))) {
+		out <<- c(out, trans(xml2::xml_attr(x, "name"), from="OM", to="R"), " ")
 	}
-	if (xmlName(x) == "text") out <<- c(out, xmlValue(x), " ")
-	if (xmlName(x) == "OMF") out <<- c(out, xmlAttrs(x)[["dec"]], " ")
-	if (xmlName(x) == "OMS") {
-	if (xmlAttrs(x)[["cd"]] == "logic1" && "name" %in% names(xmlAttrs(x))
-		&& xmlAttrs(x)[["name"]] %in% c("true", "false")) {}
-	   else if ((xmlAttrs(x)[["cd"]] != "nums1") ||
-				(xmlAttrs(x)[["name"]] == "rational")) 
-			out <<- c(out, xmlValue(x), "(")
+	if (xml2::xml_name(x) == "text") out <<- c(out, xml2::xml_text(x), " ")
+	if (xml2::xml_name(x) == "OMF") out <<- c(out, xml2::xml_attr(x, "dec"), " ")
+	if (xml2::xml_name(x) == "OMI") out <<- c(out, xml2::xml_text(x), " ")
+	if (xml2::xml_name(x) == "OMS") {
+	if (xml2::xml_attr(x, "cd") == "logic1" && "name" %in% names(xml2::xml_attrs(x))
+		&& xml2::xml_attr(x, "name") %in% c("true", "false")) {}
+	   else if ((xml2::xml_attr(x, "cd") != "nums1") ||
+				(xml2::xml_attr(x, "name") == "rational")) 
+			out <<- c(out, xml2::xml_text(x), "(")
 	}
-	# if (xmlName(x) == "OMS") out <<- c(out, "(")
-	if (xmlName(x) == "OMSTR") {
-	# out <<- c(out, sQuote(gsub("'", "\\\\'", xmlValue(x))))
-	out <<- c(out, paste("'", gsub("'", "\\\\'", xmlValue(x)), "'", sep=""))
-	} else if ( length( xmlChildren(x) ) > 0 )
-		for( i in seq( along = xmlChildren(x) ) ) {
-			Recall( x[[i]] )
-			if (i > 1 && i < length(xmlChildren(x))) 
+	# if (xml2::xml_name(x) == "OMS") out <<- c(out, "(")
+	if (xml2::xml_name(x) == "OMSTR") {
+	# out <<- c(out, sQuote(gsub("'", "\\\\'", xml2::xml_text(x))))
+	out <<- c(out, paste("'", gsub("'", "\\\\'", xml2::xml_text(x)), "'", sep=""))
+	} else if ( length( xml2::xml_children(x) ) > 0 )
+		for( i in seq( along = xml2::xml_children(x) ) ) {
+			Recall( xml2::xml_children(x)[[i]] )
+			if (i > 1 && i < length(xml2::xml_children(x)))
 				out <<- c(out, ",")
 		}
-	# if (xmlName(x) == "OMA" || xmlName(x) == "OMBIND") out <<- c(out, xmlValue(x), ")")
-	if (xmlName(x) == "OMA" || xmlName(x) == "OMBIND") out <<- c(out, ")")
+	# if (xml2::xml_name(x) == "OMA" || xml2::xml_name(x) == "OMBIND") out <<- c(out, xml2::xml_text(x), ")")
+	if (xml2::xml_name(x) == "OMA" || xml2::xml_name(x) == "OMBIND") out <<- c(out, ")")
  }
  x <- paste(x, "\n", collapse = "")
- x <- xmlTreeParse(x, asText = TRUE)
- x <- xmlRoot(x)
+ x <- xml2::read_xml(x)
+ x <- xml2::xml_root(x)
  recurse(x)
  paste(out, collapse = "")
 }

Request for a more compatible way of defining "expressions"

When we get a list of expressions in R,
e.g.
#ASSUMPTIONS
w<-expression(200+5t)
p<-expression(0.65-0.01
t)
C<-expression(0.45t)
R<-expression(p
w)
P<-expression(R-C)
#--------------------------------------------------------------
#Then ,we load symbolic calculation packages
library(Ryacas)
library(Deriv)
#Then subtitute and expand P(R,c) to get P(t)
yacas(P)##DO NOT RUN expression((0.65 - 0.01 * t) * (5 * t + 200) - 0.45 * t)
##There were 15 warnings (use warnings() to see them)
y<-yacas(P)
#The problem occurs here,
#because y is not an expression,
#Then we use
class(y)
#It shows [1] "yacas" and by clicking y in r studio we have`
111

#To get ready for the next step of calculations
y<-y[["text"]]
y<-parse(text=y)
#But an easier way of doing this, is
casOut<-function(y) return(parse(text=y[["text"]]))
y<-casOut(y)
The output expression need to be in the type of "expression" because it is the way R and also other R packages recognizes it. Also it prevents possible errors that might happen while copying the result manually.
However, simply naming it casOut() might not be a proper idea, as there are other types of output of yacas() that does not come in this format
for example when we get an expression solved,e.g.
dydt<-Deriv(y,"t")
Expand(dydt)
yacas("Solve((%)==0,t)")# shows the results properly
if i go,
t<-yacas("Solve((%)==0,t)")
It , not surprisingly, leads to an error, so if, for a function there is limited number of roots, is it possible that we assign t as a 'yacas' type that consist of a list with the text of expressions that can be later 'parse'd to expressions?

I am aware that usually, in CAS, the roots of a function is a set or multiple sets of number. but if the output of the function solving the roots shows texts, it can be (maybe separarely) converted to an expression or a list of expressions. Because an expression can also be seen as a 'data'.

So what I am suggesting, if I go
t.opti<-yacas("Solve(a^2==2s),a")
t.opti#shows that
t.opti

#[[1]]text
#[1]sqrt(2 * s)
#[2]-sqrt(2 * s)
#[[2]]Variable
"a"#(Is it a better idea?)
#Then we can do something like
for(i in 1:length(t.opti[[1]])){
assign(paste(t.opti[[2]][1],i),parse(t.opti[[1]][i]))
}
#It would be very convenient for the next step of the modelling (plotting, evaluating etc.) if these can be #written as functions to take place of the copy and paste process and the visible for loop, though I am
#not sure how this can be made concrete.
And , if in 'yacas' type, can we use a kind of 'transformation' funcitons to assign each 'text' line to expressions (&| functions so that they can be more easily used in R with other functions in math modelling? Huge thanks to developers.

Request for switches

Hi I am just thinking of when defining/processing expressions it would be great of we can have a more intuitive way of viewing equations.
Is it possible to make something in the .GlobalEnv or in the yacas environment as a boolean value like
.PrettyForm<-TRUE #when it is turned on
so that when I type

yacas(expression(x^2+y^2))
it automatically follows
PrettyForm(yacas(expression(x^2+y^2)))#or arguably this function, PrettyForm()... not to be displayed

2 2
x + y

.PrettyForm<-FALSE#then it is turned off


or if we can define something like

switch_PrettyForm<-function(state = FALSE) ifelse(state = '',mget(.PrettyForm,pos = .Global.Env),.PrettyForm<<-state)#

Similarly when I run Ryacas there lots of warnings which arfe not needed nor relevant to the mathematical models I am applying,
but if I type

warnings('off')#

that doesn't work.
I know someone does

suppressPackageStartupMessages(library(Ryacas))#when starting

at the start
Is there any switches that can be safely applied there?
Thanks. Looking for the 1.6.1 to be for R.

ysym without quotes (for the lazy)

Typing the quotes in eg ysym is extra work. How about allowing something like

library(Ryacas)

ysym2 <- function(s){
s_ <- substitute(s)
s2 <- as.character(s_)
ysym(s2)
}

ysym3 <- function(s){
s_ <- substitute(s)
s2 <- as.character(s_)
assign(s2, ysym(s2), envir = .GlobalEnv)
}

Giving

a <- ysym2(a)
a
y: a
ysym3(b)
b
y: b

Coercing Yacas Pi to R pi

The call yac_expr("Pi") currently return expression(Pi) and not expression(pi) as I believe it should.

Convert yacas output to R

Is there an easier way to convert res to R?

library(Ryacas)
eq <- "((2300+1900*1)+(x+2300+1900*1)*0.002)/(600-400)==1"

res <- solve(ysym(eq), "x")
eval(yac_expr(res)[[1:3]])  # convert to R
## [1] -2004200

Printing of objects that are not vectors nor matrices

x <- ysym("x")
y <- ysym("y")
eq <- x^2 + 3*x + 4*y + y^4
eq

gives

## [1] x^2+3*x+4*y+y^4

It would be better if it was more clear that eq is a yac_symbol. For vectors and matrices this is more clear due to the {'s.

A suggestion:

## y: x^2+3*x+4*y+y^4

drop = FALSE

...for [ does not work. This needs to be implemented.

ysym_make / ysym_ls

Function to create vector of yac_symbols() suggested by @hojsgaard :

make_ysym <- function(sym_vec){
    sapply(sym_vec,
           function(v) assign(v, ysym(v), envir = .GlobalEnv))
    invisible(NULL)
}
v <- c("a","b","y", "w")
make_ysym(v)

I propose the name ysym_make() to have common ysym prefix for related functions.

Shorter name for yac_symbol()

Shorter name for yac_symbol() as initially discussed in #33. Moving discussion to here.

I will not use Sym(), and since sym() is already used by rlang I see these options:

  • ys() (for yacas symbol) -- I prefer this
  • ysym() (same as above)
  • sy() (for symbol in yacas)

Any inputs on these names or suggestions for others?

vec and vech

I am thinking of adding vec and vech in linalg as these come up from time to time in my work. From my reading of the reference manual however, I am not sure if yacas supports vectorization and half-vectorization out of the box. If there's a way to do vec and vech in yacas I'll work on this next. If there's no way to do vec and vech in yacas out of the box, I think it's a good feature request.

What do you think @mikldk @grzegorzmazur ?

https://en.wikipedia.org/wiki/Vectorization_(mathematics)

Multinomiel likelihood

Multinomiel log-likelihood with constraint:
[
l(\theta) = y_1 \log(\theta_1) + y_2 \log(\theta_2) + y_3 \log(\theta_3)
g(\theta) = \theta_1 + \theta_2 + \theta_3 - 1
]

Maximise $l(\theta)$ for $g(\theta) = 0$.

Lagrange multiplicators to get unconstrainted optimisation to minimise
[
L = -l(\theta) + \lambda g(\theta)
]

> p <- ysym(c("p1", "p2", "p3"))
> y <- ysym(c("y1", "y2", "y3"))
> lambda <- ysym("lambda")
> l <- sum(y*log(p))
> L <- -l + lambda*(sum(p) - 1)
> L
y: lambda*(p1+p2+p3-1)-(y1*Ln(p1)+y2*Ln(p2)+y3*Ln(p3))
> gL <- deriv(L, c("p1", "p2", "p3", "lambda"))
> gL
{lambda-y1/p1, lambda-y2/p2, lambda-y3/p3, p1+p2+p3-1} 
> solve(gL, c("p1", "p2", "p3", "lambda"))
{{p1==y1/lambda, p2==y2/lambda, p3==y3/lambda, lambda==lambda}} 

evaluating expressions with sum

I guess both expressions should give the same answer, but right now, the first works:

eval(yac_expr("Sum(i,1,4,x[10 - 2*i])"), list(x = 1:10))

and this doesn't work:
``
eval(yac_expr("Sum(i,1,n,x[N - 2*i])"), list(x = 1:10, n = 4, N = 10))

sum of a vector in ryacas

Hi, I've just discovered this package! very cool!

Say that I have a vector of x

N <- 20
x <- paste0("x_", 1:N) %>% ysym()

I want to sum n even numbers starting from N:

If I set $n=5$ then I can do it:

n <- 5
i <- seq(1,n)
sum(x[N - 2 * (i-1)])

But what if I want leave it with an arbitrary $n$?
Is there some way to do this?
Can ryacas use the large sigma to denote summation? I'd like to generate something like the latex code before. Is it possible?

TeXForm fails

I get:

y_fn(ysym("2*x"), "TeXForm")
Error in yac_core(x) :
Yacas returned this error: CommandLine(1) : Error parsing expression near token x

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.