how to convert string into math expression in R? - string

I have a vectors of strings, say c("E^A","S^P","lambda","T","E^Q","E^Q","AT"), and I want to plot them as the x axis label using math expression. (I believe I have written them in math expression format, but with quote)
When I put
text(x,par("usr")[3]-0.2,labels=substitute(A,list(A=label)),srt=20,pos=1,adj = c(1.1,1.1), xpd = TRUE,cex=0.7)
The x axis only shows "E^A","S^P","lambda","T","E^Q","E^Q","AT", not the mathematical interpretation of the strings, and I guess it's because they are not regarded as math symbols.
How can I get mathematical labeling then? Thanks so much!

In general, use expression (see ?plotMath):
plot(1,main=expression(E^A))
Note that the 'E^A' is not in quote marks.
To generate expressions from a character vector, use parse(text=...):
lbls <- c("E^A","S^P","lambda","T","E^Q","E^Q","AT")
x <- 1:length(lbls)
y <- runif(length(lbls))
# I'm just going to draw labels on the (x,y) points.
plot(x,y,'n')
text(x,y, labels=parse(text=lbls)) # see the parse(text=lbls) ?

Related

Changing printing format for fractions using sympy and PythonTex

Below is a minimal working problem, of what I am working on.
The file is a standard LaTeX file using sympy within pythontex, where I want to change
how sympy displays fractions.
Concretely I would like to make the following changes, but have been struggling:
How can I make sympy display the full, and not inline version of it's fractions for some of its fractions? In particular I would like the last fraction 1/5 to instead be displayed in full.
eg. \fraction{1}{5}
In the expression for the derivative, I have simplified the results, but I struggle to substitute the variable x with the fraction a/b. Whenever I substitute this expression into the fraction it fully simplifies the expression, which is not what I want. I just want to replace x with the fraction a/b (in this case 2/3 or 1/3 depending on the seed).
Below I have attached two images displaying what my code produces, and what I would like it to display. Do note that this is also stated in the two bullets above
Current output
Desired output
Code
\documentclass{article}
\usepackage{pythontex}
\usepackage{mathtools,amssymb}
\usepackage{amsmath}
\usepackage{enumitem}
\begin{document}
\begin{pycode}
import math
from sympy import *
from random import randint, seed
seed(2021)
\end{pycode}
\paragraph{Oppgave 3}
\begin{pycode}
a, b = randint(1,2), 3
ab = Rational(a,b)
pressure_num = lambda x: 1-x
pressure_denom = lambda x: 1+x
def pressure(x):
return (1-x)/(1+x)
pressure_ab = Rational(pressure_num(ab),pressure_denom(ab))
x, y, z = symbols('x y z')
pressure_derivative = simplify(diff(pressure(x), x))
pressure_derivative_ab = pressure_derivative.xreplace({ x : Rational(a,b)})
\end{pycode}
The partial pressure of some reaction is given as
%
\begin{pycode}
print(r"\begin{align*}")
print(r"\rho(\zeta)")
print(r"=")
print(latex(pressure(Symbol('\zeta'))))
print(r"\qquad \text{for} \ 0 \leq \zeta \leq 1.")
print(r"\end{align*}")
\end{pycode}
%
\begin{enumerate}[label=\alph*)]
\item Evaluate $\rho(\py{a}/\py{b})$. Give a physical interpretation of your
answer.
\begin{equation*}
\rho(\py{a}/\py{b})
= \frac{1-(\py{ab})}{1+\py{ab}}
= \frac{\py{pressure_num(ab)}}{\py{pressure_denom(ab)}}
\cdot \frac{\py{b}}{\py{b}}
= \py{pressure_ab}
\end{equation*}
\end{enumerate}
The derivative is given as
%
\begin{pycode}
print(r"\begin{align*}")
print(r"\rho'({})".format(ab))
print(r"=")
print(latex(pressure_derivative))
print(r"=")
print(latex(simplify(pressure_derivative_ab)))
print(r"\end{align*}")
\end{pycode}
\end{document}
Whenever I substitute this expression into the fraction it fully simplifies the expression, which is not what I want. I just want to replace x with the fraction a/b (in this case 2/3 or 1/3 depending on the seed).
It's possible to do this, if we use a with expression to temporarily disable evaluation for that code block, and then we use two dummy variables in order to represent the fraction, and finally we do the substitution with numerical values.
So the following line in your code:
pressure_derivative_ab = pressure_derivative.xreplace({ x : Rational(a,b)})
can be changed to:
with evaluate(False):
a1,b1=Dummy('a'),Dummy('b')
pressure_derivative_ab = pressure_derivative.subs(x,a1/b1).subs({a1: a,b1: b})
The expressions pressure_derivative and pressure_derivative_ab after this are:
How can I make sympy display the full, and not inline version of it's fractions for some of its fractions? In particular I would like the last fraction 1/5 to instead be displayed in full. eg. \fraction{1}{5}
For this, you only need to change this line:
= \py{pressure_ab}
into this line:
= \py{latex(pressure_ab)}
Because we want pythontex to use the sympy latex printer, instead of the ascii printer.
To summarize, the changes between the original code and the modified code can be viewed here.
All the code in this post is also available in this repo.

Generating clustered spatstat marks for a ppp object

This question is very close to what has been asked here. The answer is great if we want to generate random marks to an already existing point pattern - we draw from a multivariate normal distribution and associate with each point.
However, I need to generate marks that follows the marks given in the lansing dataset that comes with spatstat for my own point pattern. In other words, I have a point pattern without marks and I want to simulate marks with a definite pattern (for example, to illustrate the concept of segregation for my own data). How do I make such marks? I understand the number of points could be different between lansing and my data set but I am allowed to reduce the window or create more points. Thanks!
Here is another version of segregation in four different rectangular
regions.
library(spatstat)
p <- c(.6,.2,.1,.1)
prob <- rbind(p,
p[c(4,1:3)],
p[c(3:4,1:2)],
p[c(2:4,1)])
X <- unmark(spruces)
labels <- factor(LETTERS[1:4])
subwins <- quadrats(X, 2, 2)
Xsplit <- split(X, subwins)
rslt <- NULL
for(i in seq_along(Xsplit)){
Y <- Xsplit[[i]]
marks(Y) <- sample(labels, size = npoints(Y),
replace = TRUE, prob = prob[i,])
rslt <- superimpose(rslt, Y)
}
plot(rslt, main = "", cols = 1:4)
plot(subwins, add = TRUE)
Segregation refers to the fact that one species predominates in a
specific part of the observation window. An extreme example would be to
segregate completely based on e.g. the x-coordinate. This would generate strips
of points of different types:
library(spatstat)
X <- lansing
Y <- cut(X, X$x, breaks = 6, labels = LETTERS[1:6])
plot(Y, cols = 1:6)
Without knowing more details about the desired type of segregation it is
hard to suggest something more useful.

Convert Cartesian expression to polar expression using SymPy

Is there a way to convert a Cartesian expression in SymPy to a polar one?
I have the following expression:
1/sqrt(x^2+y^2)
However, I can't seem to get SymPy to acknowledge that this is 1/r in polar coordinates. I tried using the 'subs' command, both of the following options (I imported sympy as asp, and defined all of the symbols earlier):
expr = 1/sp.sqrt(x**2+y**2)
expr.subs((x,y),(r*cos(theta),r*sin(theta))
expr.subs((sp.sqrt(x**2+y**2),sp.atan(y/x)),(r,theta))
but in both cases, I simply receive the original expr again.
Is there a way to convert a Cartesian expression to a polar one in SymPy?
subs((x,y),(r*cos(theta),r*sin(theta))
is not a correct syntax for subs. When multiple symbols are to be replaced, one has to provide either a dictionary
subs({x: r*sp.cos(theta), y: r*sp.sin(theta)})
or an iterable with pairs (old, new) in it:
subs(((x, r*sp.cos(theta)), (y, r*sp.sin(theta))))
The former is more readable; the latter is needed when substitutions must be carried out in a particular order (not the case here).
Either way, to achieve 1/r you also need to declare r as nonnegative
r = sp.symbols('r', nonnegative=True)
and simplify the result of substitution:
expr.subs({x: r*sp.cos(theta), y: r*sp.sin(theta)}).simplify()

Stuck with Apostolico-Crochemore algorithm

I am trying to understand the Apostolico-Crochemore algorithm.
The only English description I have found is http://www-igm.univ-mlv.fr/~lecroq/string/node12.html#SECTION00120, but I am stuck with the second line of the description where it says
x is a power of a single character
What does that mean?
m in this case is the length of the pattern, c is a character from the alphabet in use. I can't understand how x == c^m.
This is then followed by (x=(a^l)bu for a, b in Sigma, u in Sigma and a neq b that also uses ^ operation which I cannot understand.
Algorithms on strings are sometimes described in the jargon of formal languages, where concatenation (joining) of strings is written as multiplication: x * y, usually written just xy, means "the string x followed by the string y". So x^n (i.e. "raising the string x to the nth power") naturally means "n copies of the string x, joined together".
This is mostly just a notational device, though multiplication (of ordinary real numbers) and string concatenation do share some abstract mathematical properties. E.g. they are both associative: (xy)z = x(yz), whether we're talking about multiplying numbers or joining strings. (OTOH, xy = yx for real numbers but not for strings, in general. But then matrix multiplication is not commutative either.)

Generate random points inside a rectangle (uniformly)?

I am trying to generate a certain amount of random uniform points inside a rectangle (I know the pair of coordinates for each corner).
Let our rectangle be
ABCD
My idea is:
Divide the rectangle into two triangles by the AC diagonal. Find the slope and the intercept of the diagonal.
Then, generate two random numbers from [0,1] interval, let them be a,b.
Evaluate x = aAB and y = bAD (AB, AD, distances). If A is not (0,0), then we can add to x and y A's coordinates.
Now we have a point (x,y). If it is not in the lower triangle (ABC), skip to the next step.
Else, add the point to our plot and also add the symmetric of (x,y) vs. the AC diagonal so that we can fill the upper triangle (ADC) too.
I have implemented this, but I highly doubt that the points are uniformly generated (judging from the plot). How should I modify my algorithm? I guess that the issue is related to how I pick the triangle and the symmetric thing.
Why not just generate x=random([A.x, B.x]) and y=random([B.y, C.y]) and put them together as (x,y)? A n-dimensional uniform distribution is simply the product of the n uniform distributions of the components.
This is referred to as point picking and other similar terms. You seem to be on the right track in that the points should come from the uniform distribution. Your plot looks reasonably random to me.
What are you doing with upper and lower triangles? They seem unnecessary and would certainly make things less random. Is this some form variance reduction along the lines of antithetic variates? If #Paddy3118 is right an you really just need random-ish points to fill the space, then you should look into low-discrepancy sequences. The Halton sequence generalizes the van der Corput sequence to multiple dimensions. If you have Matlab's Statistics Toolbox check out the sobolset and haltonset functions or qrandstream and qrand.
This approach (from #Xipan Xiao & #bonanova.) should be reproducible in many languages. MATLAB code below.
a = 0; b = 1;
n = 2000;
X = a + (b-a)*rand(n,1);
Y = a + (b-a)*rand(n,1);
Newer versions of MATLAB can make use of the makedist and random commands.
pdX = makedist('Uniform',a,b);
pdY = makedist('Uniform',a,b);
X = random(pdX,n,1);
Y = random(pdY,n,1);
The points (X,Y) will be uniformly in the rectangle with corner points (a,a), (a,b), (b,a), (b,b).
For verification, we can observe the marginal distributions for X and Y and see that those are uniform as well.
scatterhist(X,Y,'Marker','.','Direction','out')
Update: Using haltonset (suggested by #horchler)
p = haltonset(2);
XY = net(p,2000);
scatterhist(XY(:,1),XY(:,2),'Marker','.','Direction','out')
If you are after a more uniform density then you might consider a Van der Corput sequence. The sequence finds use in Monte-Carlo simulations and Wolfram Mathworld calls them a quasi-random sequence.
Generate two random numbers in the interval [0,1] translate and scale them to your rectangle as x and y.
There is just my thought, i haven't test with code yet.
1.Divide the rectangle to grid with N x M cells, depends on variable density.
2.loop through the cell and pick a random point in the cell until it reached your target point quantity.

Resources