Note: When requesting assistance with this module during the supervision sessions, please ask to speak to Adam by putting his name next to yours on waglys.
(*Stochastic Simulation - Random walk on the integers*) noSim = 1000; tSteps = 100; xlim = 10; p = 1; klippor = 0; strand = 0; start = 0; (* Starting point *) fmat = ConstantArray[0, {noSim, tSteps}]; (*This Matrix fmat has elements fmat[[a,b]]: position of particle a at time b*) Occupancy = ConstantArray[0, {2*xlim + 1, tSteps}]; (*This Matrix has elements Occupancy[[a,b]]: number of particles at position a at time b*) (* Simulation of the random walk *) For[j = 1, j <= noSim, j++, fmat[[j, 1]] = start; For[t = 2, t <= tSteps, t++, If[RandomReal[] < p, r = RandomInteger[]; If[r == 0, fmat[[j, t]] = fmat[[j, t - 1]] - 1]; If[r == 1, fmat[[j, t]] = fmat[[j, t - 1]] + 1];, fmat[[j, t]] = fmat[[j, t - 1]] ]; If[fmat[[j,t]] == xlim, klippor = klippor+1; Break[]]; If[fmat[[j,t]] == -xlim, strand = strand+1; Break[]]; ] ] For[t = 1, t <= tSteps, t++, For[i = 1, i <= (2*xlim + 1), i++, Occupancy[[i, t]] = Count[fmat[[All, t]], i - xlim]] ] Occupancy = Occupancy*(1/noSim); (*Visualize the results*) SinglePathPlot = ListLinePlot[ fmat[[1, All]]] (*Trajectory of an individual particle*) Manipulate[ ListLinePlot[Occupancy[[All, t]], PlotRange -> {-0.5, 1}], {t, 1, tSteps, 1}] (*Print the numbre of times the particle reached the two edges of the domain*) klippor strand
tend = 2000; (*End time*) xlim = 3; (*Spatial domain defined by [-xlim, xlim]*) D1 = 1.45*10^(-3); (*Diffusion coefficient 1*) xpts = Range[-xlim, xlim, 0.1]; (*Define x-domain*) eqn1 = D[S[x, t], t] == D1*D[S[x, t], {x, 2}]; (*Equation 1*) sol = NDSolve[{eqn1, S[x, 0] == 20, S[-xlim, t] == 100, S[xlim, t] == 100}, S, {x, -xlim, xlim}, {t, 0, tend}]; Manipulate[ ListLinePlot[S[xpts, t] /. sol, PlotRange -> {-5, 105}], {t, 0, tend, 0.1}]