Differential Eq using deSolve in R - r

My apologies, for being unclear earlier. I now understand the function a bit more, but could use some assistance on a few aspects.
I would like to get back a relationship of conversion ( X ) versus volume ( V ), or the other way around would be fine as well. It would seem to me that the traditional "times" term is what I want to replace with an X sequence from 0 - 1, X is conversion remember so bounded by 0 and 1.0
Below, rw is the reaction rate, and is a function of the partial pressures at any given moment, which are described as P.w, P.x, P.y, and P.z which themselves are functions of the initial conditions (P.w0, v.0) and the conversion, again X.
Thank you in advance
rm(list = ls())
weight <- function( Vols, State, Pars ) {
with(as.list(c(State, Pars)), {
y = 1
delta = 2
ya.0 = 0.4
eps = ya.0 * delta
temp = 800
R = 8.314
k.2 = exp( (35000 / ( R*temp )) - 7.912 )
K.3 = exp( 4.084 / temp - 4.33 )
P.w <- P.w0 * ( 1 - X ) * y / ( 1 + eps * X )
P.x <- P.w0 * ( 1 - 2*X ) * y / ( 1 + eps * X )
P.y <- P.w0 * ( 1 + X ) * y / ( 1 + eps * X )
P.z <- P.w0 * ( 1 + 4*X ) * y / ( 1 + eps * X )
r.w <- k.2 * ( K.3 * P.w * P.x ^ 2 - P.y * P.z^4 )
F.w0 <- P.w0 * v.0 / ( R * temp )
dX.dq <- r.w / F.w0
res <- dX.dq
return(list(res))
})
}
pars <- c( y = 1,
P.w0 = 23,
v.0 = 120 )
yini <- c( X = 0 )
vols <- seq( 0 , 100 , by = 1 )
out <- ode( yini , vols , weight , pars )

Just running
vol.func(0,0,params)
i.e., evaluating the gradient at the initial conditions, gives NaN. The proper way to diagnose this is to divide your complex gradient expressions up into separate terms and see which one is causing trouble. I'm not going to go through this in detail, but as #Sixiang.Hu points out in comments above, you're dividing by V in your gradient function, which will cause infinite values if the numerator is finite or NaN values if the numerator is zero ...
More generally, it's not clear whether you understand that the first argument to the gradient function (your vol.func) is supposed to be the current time, not a value of the state variable. Perhaps V is supposed to be your state variable, and X should be a parameter ...?

Related

Calculating double integral with gamma incomplete function in R

I need to calculate a double integral on two variables (B0 and B1) in R.
Till now, nothing complicated with the int2 function.
But, my function to integrate includes gamma incomplete function (gammainc in R ) !
The following error message appears :
Error in gammainc(1/eta, lambda * exp(B0 + B1 * z_arm) * tmax^eta) :
Arguments must be of length 1; function is not vectorized.
Any advice to help me ?
tmax = 5
Sig = matrix ( c(0.2, 0, 0, 0.4) , ncol = 2 )
Mu = matrix ( c(1, 0) , ncol = 1 )
eta = 0.5
lambda = 0.8
z_arm = c(rep(0.5,10), rep(1,15))
to.integrate = function(B0, B1)
{
first.int = 1/eta *(lambda * exp(B0 + B1 * z_arm))^(-1/eta)* gammainc(1/eta, lambda * exp(B0 + B1 * z_arm)*tmax^eta)['lowinc']
B = matrix(c(B0, B1), ncol=1)
multi.norm = 1 / (2 * pi * det(Sig)^(1/2)) * exp (- 0.5 * t( B - Mu ) * solve(Sig) * ( B - Mu ) )
return (first.int * multi.norm)
}
int2(to.integrate , a=c(-Inf,-Inf), b=c(Inf,Inf), eps=1.0e-6, max=16, d=5)
Thanks for any help!

How to find solution with optim using r

I have quite simple question yet I cannot seem to solve it.
I'm trying to find a parameter with optim() r function.
Here is the case:
library(rootSolve)
d <- read.table(text="indx rate n d
1 0.12 158 14
2 0.095 135 9
3 0.057 123 4
4 0.033 115 5
5 0.019 90 4", header=T)
d$real <- with(d, d/n)
opt <- d[ ,c("rate","real", "n")]
# this is close to the correct solution!
scaler <- apply(opt, 1, function(z) uniroot.all(
function(alpha) z[2] - (1 / (1 + alpha * ( (1 - z[1]) / z[1] )) ), interval = c(0,10)))
# check for solution (not fully correct!)
round(crossprod(scaler * opt$real, opt$n)/sum(opt$n), 3) == round(crossprod(round(opt$rate, 3), opt$n)/sum(opt$n), 3)
# using optim() - completely wrong results
infun <- function(data, alpha){ l <- with(data,
( rate - (1 / ( 1 + alpha[1] * ( (1 - real)/real ))) )); return( -sum( l ) ) }
opt_out <- optim(c(0,0), infun, data=opt, method = "BFGS", hessian = TRUE)
with(opt, (1 / ( 1 + opt_out$par[1] * ( (1 - real)/real ))))
You are trying, with your code, to get an unique alpha for all, but you want to have five values ..
So, you are leaded to make a sum .. but if you have negative and positive values, your sum could go near zero even with individual terms far from 0 ..
Moreover, your infun function is not in accordance with your previous function ..
What you can do is something like that :
infun <- function(alpha){ l <- with(cbind(d, alpha), ( real - (1 / ( 1 +
alpha * ( (1 - rate)/rate ))) )); return( sum(abs(l)) ) }
param <- c(5,5,5,5,5)
opt_out <- optim(par = scaler, infun, method = "BFGS", hessian = TRUE)
And in order to check the result you should have written :
with( cbind(opt,opt_out$par), real -1 / ( 1 + opt_out$par * ( (1 - rate)/rate )))
To get the true solution, you can do (after a very litle mathematics on a paper) :
sol <- -((opt[,2]-1)/(opt[,2]))*(opt[,1]/(1-opt[,1]))
and test it :
with( cbind(opt,sol), real -1 / ( 1 + opt_out$par * ( (1 - rate)/rate )))

How to calculate the entropy of a coin flip

I would like to know ...
In the repeated coin flip, ¿how do I calculate the entropy of the random variable X that represents the number of flips to do until get "head" for first time?
The variable X can take any number from 1 through infinity. The probabilities are:
p(X = i) = (1/2)^i
The entropy is:
H = - Sum {i from 1 to infinity} ( p(X = i) * log2(p(X = i)) )
= - Sum {i from 1 to infinity} ( 1/2^i * log2(1/2^i) )
= - Sum {i from 1 to infinity} ( 1/2^i * i * log2(1/2) )
= Sum {i from 1 to infinity} ( 1/2^i * i )
Solving this yields:
H = 2 bit

Solving a cubic to find nearest point on a curve to a point

Ok,
I have a projectile that has its position defined such that:
a.x = initialX + initialDX * time;
a.y = initialY + initialDY * time + 0.5 * gravtiy * time^2;
I want to be able to predict which obstacles in my environment this projectile will collide with. I plan on checking the distance from A the closest point on the curve to the point P.
I figure that at the point A the tangent to the curve will be perpendicular to the vector AP, and that the tangent to the curve at A will simply be the velocity V of the projectile at that point.
AP dot V = 0
ap.x = initialX + initialDX * time - p.x;
ap.y = initialY + initialDY * time + gravity * time^2 - p.y;
v.x = initialDX;
v.y = initialDY + gravity * time;
=>
AP dot V =
( 0.5 * gravity^2 ) * t^3 +
( 1.5 * gravity * initialDY ) * t^2 +
( initialDX^2 + initialDY^2 + gravity * ( initialY - p.y ) ) * t +
( initialDX * ( initialX - p.x ) + initialDY * ( initialY - p.y ) )
From here I can see that this is a cubic function. I have spent some time researching online and found that there is a general equation that seems to work for certain values for finding the roots.
This is the process I have attempted to implement.
http://www.sosmath.com/algebra/factor/fac11/fac11.html
a = 0.5 * gravity^2;
b = 1.5 * gravity * initialDY;
c = initialDX^2 + initialDY^2 + gravity * ( initialY - p.y );
d = initialDX * ( initialX - p.x ) + initialDY * ( initialY - p.y );
A = ( c - ( b * b ) / ( 3 * a ) ) / a;
B = -( d + ( 2 * b * b * b ) / ( 27 * a * a ) - ( b * c ) / ( 3 * a ) ) / a;
workingC = -Math.pow( A, 3 ) / 27;
u = ( -B + Math.sqrt( B * B - 4 * workingC ) ) / 2; // Quadratic formula
s = Math.pow( u + B, 1 / 3 );
t = Math.pow( u, 1 / 3 );
y = s - t;
x = y - b / ( 3 * a );
When I plug x back into my original equations for the curve as the time, this should give me A. This seems to work well for certain values, however when p.y is above a certain value, I don't have a positive to take a square root of in the quadratic equation.
I don't have a full enough understanding of the math to understand why this is happening, or what I can do to resolve the issue.
Any help on this would be much appreciated.
UPDATE:
I have adjusted my algorithm to deal with complex roots, however I am still having trouble.
This is what I do now if the discriminant is negative:
a = 0.5 * gravity^2;
b = 1.5 * gravity * initialDY;
c = initialDX^2 + initialDY^2 + gravity * ( initialY - p.y );
d = initialDX * ( initialX - p.x ) + initialDY * ( initialY - p.y );
A = ( c - ( b * b ) / ( 3 * a ) ) / a;
B = -( d + ( 2 * b * b * b ) / ( 27 * a * a ) - ( b * c ) / ( 3 * a ) ) / a;
workingC = -Math.pow( A, 3 ) / 27;
discriminant = B * B - 4 * workingC;
then if discriminant < 0;
uc = new ComplexNumber( -B / 2, Math.sqrt( -discriminant ) / 2 );
tc = uc.cubeRoot( );
uc.a += B;
sc = uc.cubeRoot( );
yc = sc - tc;
yc.a -= b / ( 3 * a );
x = -d / ( yc.a * yc.a + yc.b * yc.b );
For some reason, this is still not giving me the results I expect. Is there anything that stands out as being wrong here?
Real polynomials can have complex number roots and if the roots are not real, they occur in conjugate pairs.
This implies cubics always have at least one real root.
Now if you get a complex root using your method, you can try to get the conjugate, mutiply and divide the constant of the cubic, take reciprocal to get the real root.
So if you had to take the square root of a -ve number, then it is same as multiplying the square root of its modulus by the imaginary number 'i'.
So if you represent your root as (m,n) denoting the complex number m + in. Then the other root is m - in = (m, -n) and m and n are real numbers.
The cubic can then be written as P(x) = (x^2 - 2m + (m^2 + n^2))(x-r).
So if P(x) = x^3 - a_1 *x^2 + a_2*x - a_3, then we have that r = a_3/(m^2 + n^2) (a_3 is the product of the roots, which is r(m^2+n^2))
A simpler way to get r would be to use the formula r = a_1 - 2m (a_1 is the sum of the roots, which is r+2m).
Check out: http://en.wikipedia.org/wiki/Complex_number

Why are there 3 conflicting OpenCV camera calibration formulas?

I'm having a problem with OpenCV's various parameterization of coordinates used for camera calibration purposes. The problem is that three different sources of information on image distortion formulae apparently give three non-equivalent description of the parameters and equations involved:
(1) In their book "Learning OpenCV…" Bradski and Kaehler write regarding lens distortion (page 376):
xcorrected = x * ( 1 + k1 * r^2 + k2 * r^4 + k3 * r^6 ) + [ 2 * p1 * x * y + p2 * ( r^2 + 2 * x^2 ) ],
ycorrected = y * ( 1 + k1 * r^2 + k2 * r^4 + k3 * r^6 ) + [ p1 * ( r^2 + 2 * y^2 ) + 2 * p2 * x * y ],
where r = sqrt( x^2 + y^2 ).
Assumably, (x, y) are the coordinates of pixels in the uncorrected captured image corresponding to world-point objects with coordinates (X, Y, Z), camera-frame referenced, for which
xcorrected = fx * ( X / Z ) + cx and ycorrected = fy * ( Y / Z ) + cy,
where fx, fy, cx, and cy, are the camera's intrinsic parameters. So, having (x, y) from a captured image, we can obtain the desired coordinates ( xcorrected, ycorrected ) to produced an undistorted image of the captured world scene by applying the above first two correction expressions.
However...
(2) The complication arises as we look at OpenCV 2.0 C Reference entry under the Camera Calibration and 3D Reconstruction section. For ease of comparison we start with all world-point (X, Y, Z) coordinates being expressed with respect to the camera's reference frame, just as in #1. Consequently, the transformation matrix [ R | t ] is of no concern.
In the C reference, it is expressed that:
x' = X / Z,
y' = Y / Z,
x'' = x' * ( 1 + k1 * r'^2 + k2 * r'^4 + k3 * r'^6 ) + [ 2 * p1 * x' * y' + p2 * ( r'^2 + 2 * x'^2 ) ],
y'' = y' * ( 1 + k1 * r'^2 + k2 * r'^4 + k3 * r'^6 ) + [ p1 * ( r'^2 + 2 * y'^2 ) + 2 * p2 * x' * y' ],
where r' = sqrt( x'^2 + y'^2 ), and finally that
u = fx * x'' + cx,
v = fy * y'' + cy.
As one can see these expressions are not equivalent to those presented in #1, with the result that the two sets of corrected coordinates ( xcorrected, ycorrected ) and ( u, v ) are not the same. Why the contradiction? It seems to me the first set makes more sense as I can attach physical meaning to each and every x and y in there, while I find no physical meaning in x' = X / Z and y' = Y / Z when the camera focal length is not exactly 1. Furthermore, one cannot compute x' and y' for we don't know (X, Y, Z).
(3) Unfortunately, things get even murkier when we refer to the writings in Intel's Open Source Computer Vision Library Reference Manual's section Lens Distortion (page 6-4), which states in part:
"Let ( u, v ) be true pixel image coordinates, that is, coordinates with ideal projection, and ( u ̃, v ̃ ) be corresponding real observed (distorted) image coordinates. Similarly, ( x, y ) are ideal (distortion-free) and ( x ̃, y ̃ ) are real (distorted) image physical coordinates. Taking into account two expansion terms gives the following:
x ̃ = x * ( 1 + k1 * r^2 + k2 * r^4 ) + [ 2 p1 * x * y + p2 * ( r^2 + 2 * x^2 ) ]
y ̃ = y * ( 1 + k1 * r^2 + k2 * r^4 ] + [ 2 p2 * x * y + p2 * ( r^2 + 2 * y^2 ) ],
where r = sqrt( x^2 + y^2 ). ...
"Because u ̃ = cx + fx * u and v ̃ = cy + fy * v , … the resultant system can be rewritten as follows:
u ̃ = u + ( u – cx ) * [ k1 * r^2 + k2 * r^4 + 2 * p1 * y + p2 * ( r^2 / x + 2 * x ) ]
v ̃ = v + ( v – cy ) * [ k1 * r^2 + k2 * r^4 + 2 * p2 * x + p1 * ( r^2 / y + 2 * y ) ]
The latter relations are used to undistort images from the camera."
Well, it would appear that the expressions involving x ̃ and y ̃ coincided with the two expressions given at the top of this writing involving xcorrected and ycorrected. However, x ̃ and y ̃ do not refer to corrected coordinates, according to the given description. I don't understand the distinction between the meaning of the coordinates ( x ̃, y ̃ ) and ( u ̃, v ̃ ), or for that matter, between the pairs ( x, y ) and ( u, v ). From their descriptions it appears their only distinction is that ( x ̃, y ̃ ) and ( x, y ) refer to 'physical' coordinates while ( u ̃, v ̃ ) and ( u, v ) do not. What is this distinction all about? Aren't they all physical coordinates? I'm lost!
Thanks for any input!
There is no one and only formula for camera calibration, they are all valid. Notice the first one contains constants K1, K2 & K3 for r^2, r^4 & r^6, and the other two only have constants for r^2 and r^4? That is because they are all approximate models. The first one is likely to be more accurate since it has more parameters.
Anytime you see:
r = sqrt( x^2 + y^2 )
it is probably safe to assume x = (the x coordinate pixel) - (the camera center in pixels) since r usually means radius from the center.
What are you trying to do by the way? Estimate the camera parameters, correct for lens distortion, or both?

Resources