Converting string to illegal/unsupported expression in Mathematica. - string

I need to input a variable, say var, into Mathematica function Series[ ] like this: Series[A^2+B^2+C^2, var]. Series[ ] has the following syntax:
Series[f, {x, x_0, n}] generates a power series expansion for f about the point x=x_0 to order n.
Series[f, {x, x_0, n}, {y, y_0, m}, ...] successively finds series expansions with respect to x, then y, etc.
Because I am not always computing Series[ ] in one dimension (i.e., B and C are not always variables at each iteration), var must be properly formatted to fit the dimension demands. The caveat is that Mathematica likes lists, so any table degenerated will have a set of outer {}.
Suppose my previous code generates the following two sets of sets:
table[1]= {{A, 0, n}};
table[2]= {{A, 0, n}, {B, 0, m}}; .
My best idea is to use string manipulation (for i= 2):
string = ToString[table[i]]; .
str = StringReplacePart[string, {" ", " "}, {{1}, {StringLength[string], StringLength[string]}}]
The next step is to convert str to an expression like var and do Series[A^2 + B^2 + C^2, var] by doing var= ToExpression[str], but this returns the following error:
ToExpression::sntx: Invalid syntax in or before "{A, 0, n}, {B, 0, m}".
$Failed
Help convert str to expression propertly or suggest another way to handle this problem.

If I understood correctly, you have
table[2] = {{A, 0, n}, {B, 0, m}};
and are trying to obtain from that
Series[f[A,B],{A,0,n},{B,0,m}]
This may be done using Sequence, like so (I will use series instead of Series to keep it unevaluated so you can see what is happening):
series[f[A, B], Sequence ## table[2]]
(*
-> series[f[A,B],{A,0,n},{B,0,m}]
*)
So for instance
table[3] = {{A, 0, 2}, {B, 0, 2}};
Series[f[A, B], Sequence ## table[3]]
gives the right series expansion.

You can use First or Last or more generally, Part to get the List you want. For e.g.,
var = {{x, 0, 3}, {x, 0, 5}};
Series[1/(1 + x), var[[1]]]
Out[1]= 1 - x + x^2 - x^3 + O[x]^4
Series[1/(1 + x), var[[2]]]
Out[2]= 1 - x + x^2 - x^3 + x^4 - x^5 + O[x]^6
EDIT:
For multiple variables, you can use a SlotSequence (##) along with Apply (##) like so:
Series[Sin[u + w], ##] & ## {{u, 0, 3}, {w, 0, 3}}

Related

How to interpret autoarima SARIMAX(1, 0, [1], 7)

I've run this and was expecting to see something like: SARIMAX (#, #, #) x(#, #, #, #)
auto_arima(df['total'],seasonal=True,m=7).summary()
But I got this:
SARIMAX(1, 0, [1], 7)
How do I interpret this, so when I come to build my model I can use the correct parameters?
Thanks a lot
It means that the values of P, D, Q are 1, 0, [1]. And the values of p,d,q are 0,0,0 if switch trace=True in the auto_arima() method.

how to change the type of constraint's arguments in ortools

I don't know my question is possible or not. I am using ortools to solve an optimization problem and I know in the part of conditions the argument should be defined in double type, like this:
constraints[i] = solver.Constraint(0.0 , 10,0)
But my problem is that, I don't want to use this type of argument in creating conditions. For example I want to have a list.
So I wrote this in my code:
constraints[i] = solver.Constraint([1,2,3,...])
And I got this error:
return _pywraplp.Solver_Constraint(self, *args)
NotImplementedError: Wrong number or type of arguments for overloaded
function 'Solver_Constraint'.
Possible C/C++ prototypes are:
operations_research::MPSolver::MakeRowConstraint(double,double)
operations_research::MPSolver::MakeRowConstraint()
operations_research::MPSolver::MakeRowConstraint(double,double,std::string
const &)
operations_research::MPSolver::MakeRowConstraint(std::string const &)
Is there any way to change the type of condition's argument?
My Assumptions
your constraint expression is "a sum of some lists", meaning something along the lines of what the NumPy library does: e.g., if you have two lists of values, [1, 2, 3] and [4, 5, 6], their sum would be element-wise, s.t. [1, 2, 3] + [4, 5, 6] = [1+4, 2+5, 3+6] = [5, 7, 9].
your "list constraint" is also element-wise; e.g., [x1, x2, x3] <= [1, 2, 3] means x1 <= 1, x2 <= 2 and x3 <= 3.
you're using the GLOP Linear Solver. (Everything I say below applies to the ILP/CP/CP-SAT solvers, but some of the particular method names/other details are different.)
My Answer
The thing is, ortools only lets you set scalar values (like numbers) as variables; you can't make a "list variable", so to speak.
Therefore, you'll have to make a list of scalar variables that effectively represents the same thing.
For example, let's say you wanted your "list variable" to be a list of values, each one subjected to a particular constraint which you have stored in a list. Let's say you have a list of upper bounds:
upper_bounds = [1, 2, 3, ..., n]
And you have several lists of solver variables like so:
vars1 = [
# variable bounds here are chosen arbitrarily; set them to your purposes
solver.NumVar(0, solver.infinity, 'x{0}'.format(i))
for i in range(n)
]
vars2 = [...] # you define any other variable lists in the same way
Then, you would make a list of constraint objects, one constraint for each upper bound in your list:
constraints = [
solver.Constraint(0, ubound)
for ubound in upper_bounds
]
And you insert the variables into your constraints however is dictated for your problem:
# Example expression: X1 - X2 + 0.5*X3 < UBOUND
for i in range(n):
constraints[i].SetCoefficient(vars1[i], 1)
constraints[i].SetCoefficient(vars2[i], -1)
constraints[i].SetCoefficient(vars3[i], 0.5)
Hope this helps! I recommend taking (another, if you already have) look at the examples for your particular solver. The one for GLOP can be found here.

How do you substitute into symbolic gradient in sympy module?

I use the code
from sympy.physics.vector import *
RF = ReferenceFrame('e')
from sympy.physics.vector import gradient
scalar_field = 1/(sqrt(RF[0]**2+RF[1]**2+RF[2]**2))
gradient(scalar_field, RF)
The output is
Now I want to make substitutions, e_x = 1, etc., or maybe e_x= t.
Does it possible? How?
Substitutions are performed with subs method, for example:
gr = gradient(scalar_field, RF)
gr.subs({RF[0]: 1, RF[1]: 2, RF[2]: 3})
outputs
- sqrt(14)/196*e.x - sqrt(14)/98*e.y - 3*sqrt(14)/196*e.z
You can also substitute formulas, say
var('t')
gr.subs({RF[0]: 1, RF[1]: t, RF[2]: 3*t+2})

multipanel plot with labels extracted from htest R objects

ks.test returns a list with class "htests", but I do not find the way to store those lists with the proper class into a vector. The code I am using is:
random.sim <- read.delim("ABC_searStatsForModelFit_model0_RandomValidation.txt")
labels <- names(random.sim)
par(mfrow=c(4,3), oma=c(0.5, 0.75, 2, 0.25), mar=c(4, 4, 4, 4))
pdf("posterior_bias_random.pdf",width=9,height=13)
ks = vector("list",12)
i=1
for (n in c(6,11,16,21,26,31,36,41,46,51,56,61)) {
ks[i]<-ks.test(random.sim[,n], "qunif")
i=i+1
hist(random.sim[,n], main="", xlab=labels[n], ylab="Frequency")
add_label(0.4, 0.07, paste("K-S test = ", ks[i], sep=""))
}
title("2CAB+CJAfg", outer=T)
dev.off()
I know I'm doing something wrong because each ks[i] has not class htest
Please note that "add_label" is a small function that I borrowed from somewhere else (sorry I do not recall where, but possibly from Stackoverflow) to align the labels within the plots
add_label <- function(xfrac, yfrac, label, pos = 4, ...) {
u <- par("usr")
x <- u[1] + xfrac * (u[2] - u[1])
y <- u[4] - yfrac * (u[4] - u[3])
text(x, y, label, pos = pos, ...)
}
Thanks for any help.
Pablo
I could solve the plot part by labeling on the fly
pdf("posterior_bias_random.pdf",width=9,height=13)
par(mfrow=c(4,3), oma=c(0.5, 0.75, 2, 0.25), mar=c(4, 4, 4, 4))
for (n in c(6,11,16,21,26,31,36,41,46,51,56,61)) {
ks<-ks.test(random.sim[,n], "qunif")
hist(random.sim[,n], main="", xlab=labels[n], ylab="Frequency")
add_label(0.4, 0.07, paste("K-S test = ", signif(ks$statistic, digits=3), sep=""))
}
title("2CAB+CJAfg", outer=T)
dev.off()
However, I still wonder how to store such list. I have read Q:"How to store htest list into a matrix", but can not use the solutions. Josh's only keeps the last test list, whereas Bruno's own answer do not clarify how to store the non-numeric info.
Tanks anyway for maintaining this great forum. Probably my preferred source for solving R code questions.
Pablo

Mathematica: difficulty using Multinormal Distribution and InverseCDF functions

I'm struggling to use the functions MultinormalDistribution and InverseCDF in MultivariateStatistics package. Essentially
<< MultivariateStatistics`
sig = .5; u = .5;
dist = MultinormalDistribution[{0, 0}, sig*IdentityMatrix[2]];
delta=InverseCDF[dist, 1 - u]
The output is
InverseCDF[
MultinormalDistribution[{0, 0}, {{0.5, 0}, {0, 0.5}}], {0.5}]
can someone correct the above code? If I've understood this correctly, delta should be a single number.
1) MultinormalDistribution is now built in, so don't load MultivariateStatistics it unless you are running version 7 or older. If you do you'll see MultinormalDistribution colored red indicating a conflict.
2) this works:
sig = .5; u = .5;
dist = MultinormalDistribution[{0, 0}, sig IdentityMatrix[2]];
delta = CDF[dist, {xx, yy}]
(*1/4 Erfc[-1. xx] Erfc[-1. yy]*)
note it is a 2d distribution so that CDF needs two variables in its second argument. The "inverse" of this is a curve in {xx,yy} space. I don't think InverseCDF works for such multivariate distributions however.
You can visualize your inverse like this:
ContourPlot[delta == 1/2 , {xx, -2, 4}, {yy, -2, 4}]

Resources