Freefem Fisher's equation - pde

I'm new with Freefem++, the problem I'm trying to solve is Fisher's equation:
du/dt = d^2u/dx^2 + d^2u/dy^2 + k * u * (1-u)
du/dn = 0 - border condition
I've tried to reformulate the problem in weak form, however Freefem shows a mistake with formula:
problem Fisher(uh, vh) = int2d(Th)(uh * vh/dt + Grad(uh)' * Grad(vh) ) - int2d(Th)(k * uh * vh) + int2d(Th)(uh0 * vh/dt) - int2d(Th)(k * uh * vh * uh);
Could you please tell what I do wrong? Something is wrong with last terms.

This is a 2D transient diffusion/conduction equation with a temperature-dependent, non-linear generation term.
If you leave off the non-linear generation term, the equations should look exactly like the weak form for the 2D transient diffusion/conduction equation.
How does freefem++ linearize that non-linear term? How did you plan to handle it?
You realize, of course, that the last term makes the solution a very different animal. You have to use iteration within time steps to solve it (e.g. a Newton-Raphson solver).
The algorithm becomes an iterative, non-linear one. You won't solve for u anymore; you'll solve for an increment du and iterate until convergence.
You linearize the last term like this:
d(k*u(1-u)) = k*du(1-u) - k*u*du = k*(1-2*u)*du ~ k*du
You still have a product u*du that's non-linear. What to do? Throw it away.
Now you're solving a non-linear transient equation for du.

The easiest way to model Fisher's equations is to linearize the nonlinear part so that the computational method stays stable. In our case it means that in discrete formulations we replace the term u_i(1 - u_i) with u_{i-1}(1 - u_i) (where i is time counter) and choose attentively the space and time steps. Here I provide an example of resulting code:
verbosity=0.;
real Dx=.1,Dy=.1;
mesh Th=square(floor(10./Dx),floor(10./Dy), [-5 + 10*x, -5 + 10*y]);
fespace Vh(Th,P1);
Vh uh, vh, uh0 = ((x)^2+(y)^2)<=1;
real mu = 0.1, dt=0.01, Tf=10., k = 3.0;
macro Grad(u)[dx(u),dy(u)]//
problem KFisher(uh,vh) = int2d(Th)(uh*vh/dt + Grad(uh)'*Grad(vh)*mu) - int2d(Th)(uh0*vh/dt) + int2d(Th)(k*uh0*uh*vh) - int2d(Th)(k*vh*uh0);
for (real t=0.;t<Tf;t+=dt)
{
KFisher;
uh0 = uh;
plot(uh0, cmm="t="+t+"[sec]", dim=2, fill=true, value=true, wait=0);
}

Related

How to implement 3rd order Polynomial Formula calculations in C on a 16bit MCU

it is my first time posting but I'll start by apologizing in advance if this question has been asked before.
I have been struggling on how to implement a 3rd order polynomial formula in C because of either extremely small values or larger than 32bit results (on a 16bit MCU).
I use diffrent values but as an example I would like to compute for "Y" in formula:
Y = ax^3 + bx^2 + cx + d = 0.00000012*(1024^3) + 0.000034*(1024^2) + 0.056*(1024) + 789.10
I need to use a base32 to get a meaningful value for "a" = 515
If I multiply 1024^3 (10bit ADC) then I get a very large amount of 1,073,741,824
I tried splitting them up into "terms A, B, C, and D" but I am not sure how to merge them together because of different resolution of each term and limitation of my 16bit MCU:
u16_TermA = fnBase32(0.00000012) * AdcMax * AdcMax * AdcMax;
u16_TermB = fnBase24(0.000034) * AdcMax * AdcMax;
u16_TermC = fnBase16(0.056) * AdcMax;
u16_TermD = fnBase04(789.10);
u16_Y = u16_TermA + u16_TermB + u16_TermC + u16_TermD;
/* AdcMax is a variable 0-1024; u16_Y needs to be 16bit */
I'd appreciate any help on the matter and on how best to implement this style of computations in C.
Cheers and thanks in advance!
One step toward improvement:
ax^3 + bx^2 + cx + d --> ((a*x + b)*x + c)*x + d
It is numerically more stable and tends to provide more accurate answers near the zeros of the function and less likely to overflow intermediate calculations.
2nd idea; consider scaling the co-efficents if they maintain their approximate relative values as given on the question.
N = 1024; // Some power of 2
aa = a*N*N*N
bb = b*N*N
cc = c*N
y = ((aa*x/N + bb)*x/N + cc)*x/N + d
where /N is done quickly with a shift.
With a judicious selection of N (maybe 2**14 for high precision avoid 32-bit overflow), then entire code might be satisfactorily done using only integer math.
As aa*x/N is just a*x*N*N, I think a scale of 2**16 works well.
Third idea:
In addition to scaling, often such cubic equations can be re-written as
// alpha is a power of 2
y = (x-root1)*(x-root2)*(x-root3)*scale/alpha
Rather than a,b,c, use the roots of the equation. This is very satisfactory if the genesis of the equation was some sort of curve fitting.
Unfortunately, OP's equation roots has a complex root pair.
x1 = -1885.50539
x2 = 801.08603 + i * 1686.95936
x3 = 801.08603 - i * 1686.95936
... in which case code could use
B = -(x1 + x2);
C = x1 * x2;
y = (x-x1)*(x*x + B*x + C)*scale/alpha

How do you iterate through multiple arrays and substitute values into an equation?

Don't know if I phrased the question correctly because it's sort of hard to explain. But I have three arrays which represent temperature, salinity, and depth. They're massive so I've put the simplified versions of them below just to get the gist:
t = (np.arange(26)[25:21:-1]).reshape(2,2)
s = (np.arange(34,35,0.25).reshape(2,2))
z = (np.arange(0,100,25).reshape(2,2))
I have this equation here (also stripped down for simplicity):
velocity = 1402.5 + 5*(t) - (5.44 * 10**(-2) * t**(-2)) + (2.1 * 10**(-4) * t**(3)) + 1.33*(s) - (1.56*10**(-2)*z)
What I want to do is to iterate through the values from the t,s,z arrays and have them substituted into the equation to calculate velocity for each case. I want the resultant value to then append into a new array with the same configuration - (2,2) in this case. I can't seem to figure out the best way to approach this, so any sort of feedback would be appreciated.
Cheers!
Just use the same equation as-is with one change:
velocity = 1402.5 + 5*(t) - (5.44 * 10**(-2.0) * t**(-2.0)) + (2.1 * 10**(-4) * t**(3)) + 1.33*(s) - (1.56*10**(-2)*z)
Change: t**(-2) has been changed to t**(-2.0). To better understand why we need to change the type of the exponent see the answer here: https://stackoverflow.com/a/43287598/13389591.
The above gives the output:
[[1576.00116296 1570.56544556]
[1565.15996716 1559.7834676 ]]

How should I write these coupled PDE's in FiPy?

I'm trying to implement a phase field solidification model of a ternary alloy using FiPy. I have looked at most of the phase field examples provided on FiPy's website and my model is similar to examples.phase.quaternary.
The evolution equation for the concentrations looks like this:
Which should be solved for C_1 and C_2 (C_3 is solvent). The concentration equations are coupled with the phase evolution equation and we have D_i = D_i(phi), h = h(phi).
There are nonlinear dependencies of the variable solved for (C_i) in all three terms which makes me unsure on how to define them in FiPy. The first term (red) is a diffusion term with a nonlinear coefficient and that should be fine, but how should I define the counterdiffusion and the phasetransformation terms?
I tried defining them as diffusion and convection terms with nonlinear coefficients but without success. Therefore I am hoping for some advice on how I can define so that FiPy likes it.
Any help is highly appreciated, thanks!
/Anders
This set of equations can be solved in a coupled manner. The counter diffusion term can be defined as a coupled diffusion term and the phase transformation term can be defined as a convection term. The equations will be,
eqn1 = fipy.TransientTerm(var=C_1) == \
fipy.DiffusionTerm(D_1 - coeff_1 * (D_1 - D_3), var=C_1) \ # coupled
- fipy.DiffusionTerm(coeff_1 * (D_2 - D_3), var=C_2) \ # coupled
+ fipy.ConvectionTerm(conv_coeff_1, var=C_1)
where
coeff_1 = D_1 * C_1 / ((D_1 - D_3) * C_1 + (D_2 - D_3) * C_2 + D_3)
conv_coeff_1 = Vm / R * D_1 * h.faceGrad * inner_sum_1.faceValue
and inner_sum_1 is the complicated inner sum in the phase transformation term. The $\nabla h$ part has been taken out of the inner sum. You can either use (h.grad * inner_sum_1).faceValue or h.faceGrad * inner_sum_1.faceValue or use face values for the variables that constitute inner_sum_1. I don't know how much difference it makes. After both the C_1 and C_2 equations are defined in a similar manner, then combine them into one equation with
eqn = eqn1 & eqn2

How to efficiently evaluate or approximate a road Clothoid?

I'm facing the problem of computing values of a clothoid in C in real-time.
First I tried using the Matlab coder to obtain auto-generated C code for the quadgk-integrator for the Fresnel formulas. This essentially works great in my test scnearios. The only issue is that it runs incredibly slow (in Matlab as well as the auto-generated code).
Another option was interpolating a data-table of the unit clothoid connecting the sample points via straight lines (linear interpolation). I gave up after I found out that for only small changes in curvature (tiny steps along the clothoid) the results were obviously degrading to lines. What a surprise...
I know that circles may be plotted using a different formula but low changes in curvature are often encountered in real-world-scenarios and 30k sampling points in between the headings 0° and 360° didn't provide enough angular resolution for my problems.
Then I tried a Taylor approximation around the R = inf point hoping that there would be significant curvatures everywhere I wanted them to be. I soon realized I couldn't use more than 4 terms (power of 15) as the polynom otherwise quickly becomes unstable (probably due to numerical inaccuracies in double precision fp-computation). Thus obviously accuracy quickly degrades for large t values. And by "large t values" I'm talking about every point on the clothoid that represents a curve of more than 90° w.r.t. the zero curvature point.
For instance when evaluating a road that goes from R=150m to R=125m while making a 90° turn I'm way outside the region of valid approximation. Instead I'm in the range of 204.5° - 294.5° whereas my Taylor limit would be at around 90° of the unit clothoid.
I'm kinda done randomly trying out things now. I mean I could just try to spend time on the dozens of papers one finds on that topic. Or I could try to improve or combine some of the methods described above. Maybe there even exists an integrate function in Matlab that is compatible with the Coder and fast enough.
This problem is so fundamental it feels to me I shouldn't have that much trouble solving it. any suggetions?
about the 4 terms in Taylor series - you should be able to use much more. total theta of 2pi is certainly doable, with doubles.
you're probably calculating each term in isolation, according to the full formula, calculating full factorial and power values. that is the reason for losing precision extremely fast.
instead, calculate the terms progressively, the next one from the previous one. Find the formula for the ratio of the next term over the previous one in the series, and use it.
For increased precision, do not calculate in theta by rather in the distance, s (to not lose the precision on scaling).
your example is an extremely flat clothoid. if I made no mistake, it goes from (25/22) pi =~ 204.545° to (36/22) pi =~ 294.545° (why not include these details in your question?). Nevertheless it should be OK. Even 2 pi = 360°, the full circle (and twice that), should pose no problem.
given: r = 150 -> 125, 90 degrees turn :
r s = A^2 = 150 s = 125 (s+x)
=> 1+(x/s) = 150/125 = 1 + 25/125 x/s = 1/5
theta = s^2/2A^2 = s^2 / (300 s) = s / 300 ; = (pi/2) * (25/11) = 204.545°
theta2 = (s+x)^2/(300 s) = (6/5)^2 s / 300 ; = (pi/2) * (36/11) = 294.545°
theta2 - theta = ( 36/25 - 1 ) s / 300 == pi/2
=> s = 300 * (pi/2) * (25/11) = 1070.99749554 x = s/5 = 214.1994991
A^2 = 150 s = 150 * 300 * (pi/2) * (25/11)
a = sqrt (2 A^2) = 300 sqrt ( (pi/2) * (25/11) ) = 566.83264608
The reference point is at r = Infinity, where theta = 0.
we have x = a INT[u=0..(s/a)] cos(u^2) d(u) where a = sqrt(2 r s) and theta = (s/a)^2. write out the Taylor series for cos, and integrate it, term-by-term, to get your Taylor approximation for x as function of distance, s, along the curve, from the 0-point. that's all.
next you have to decide with what density to calculate your points along the clothoid. you can find it from a desired tolerance value above the chord, for your minimal radius of 125. these points will thus define the approximation of the curve by line segments, drawn between the consecutive points.
I am doing my thesis in the same area right now.
My approach is the following.
at each point on your clothoid, calculate the following (change in heading / distance traveled along your clothoid), by this formula you can calculate the curvature at each point by this simple equation.
you are going to plot each curvature value, your x-axis will be the distance along the clothoid, the y axis will be the curvature. By plotting this and applying very easy linear regression algorithm (search for Peuker algorithm implementation in your language of choice)
you can easily identify where are the curve sections with value of zero (Line has no curvature), or linearly increasing or decreasing (Euler spiral CCW/CW), or constant value != 0 (arc has constant curvature across all points on it).
I hope this will help you a little bit.
You can find my code on github. I implemented some algorithms for such problems like Peuker Algorithm.

Calculate initial velocity to move a set distance with inertia

I want to move something a set distance. However in my system there is inertia/drag/negative accelaration. I'm using a simple calculation like this for it:
v = oldV + ((targetV - oldV) * inertia)
Applying that over a number of frames makes the movement 'ramp up' or decay, eg:
v = 10 + ((0 - 10) * 0.25) = 7.5 // velocity changes from 10 to 7.5 this frame
So I know the distance I want to travel and the acceleration, but not the initial velocity that will get me there. Maybe a better explanation is I want to know how hard to hit a billiard ball so that it stops on a certain point.
I've been looking at Equations of motion (http://en.wikipedia.org/wiki/Equations_of_motion) but can't work out what the correct one for my problem is...
Any ideas? Thanks - I am from a design not science background.
Update: Fiirhok has a solution with a fixed acceleration value; HTML+jQuery demo:
http://pastebin.com/ekDwCYvj
Is there any way to do this with a fractional value or an easing function? The benefit of that in my experience is that fixed acceleration and frame based animation sometimes overshoots the final point and needs to be forced, creating a slight snapping glitch.
This is a simple kinematics problem.
At some time t, the velocity (v) of an object under constant acceleration is described by:
v = v0 + at
Where v0 is the initial velocity and a is the acceleration. In your case, the final velocity is zero (the object is stopped) so we can solve for t:
t = -v0/a
To find the total difference traveled, we take the integral of the velocity (the first equation) over time. I haven't done an integral in years, but I'm pretty sure this one works out to:
d = v0t + 1/2 * at^2
We can substitute in the equation for t we developed ealier:
d = v0^2/a + 1/2 * v0^2 / a
And the solve for v0:
v0 = sqrt(-2ad)
Or, in a more programming-language format:
initialVelocity = sqrt( -2 * acceleration * distance );
The acceleration in this case is negative (the object is slowing down), and I'm assuming that it's constant, otherwise this gets more complicated.
If you want to use this inside a loop with a finite number of steps, you'll need to be a little careful. Each iteration of the loop represents a period of time. The object will move an amount equal to the average velocity times the length of time. A sample loop with the length of time of an iteration equal to 1 would look something like this:
position = 0;
currentVelocity = initialVelocity;
while( currentVelocity > 0 )
{
averageVelocity = currentVelocity + (acceleration / 2);
position = position + averageVelocity;
currentVelocity += acceleration;
}
If you want to move a set distance, use the following:
Distance travelled is just the integral of velocity with respect to time. You need to integrate your expression with respect to time with limits [v, 0] and this will give you an expression for distance in terms of v (initial velocity).

Resources