Honors MP

Posted: September 12th, 2014

Due Date: Friday November 21st 9pm, 2014



Introduction

  This MP consists of three parts. In the first part, you will estimate the volume of a three-dimensional solid using the Monte Carlo method, in the second part you complete a the code for a Matlab program that models molecular collisions and in the third part you will solve an ordinary differential equation.  Study the lecture on the Honors webpage entitled Monte Carlo before you begin part one. Read the instructions for each part before filling out the answer sheet. 



Submit the answer_sheet and the following files via email to Jiahui Jiang:  ta8cs101@cs.illinois.edu

inEllipse.m
update.m

velocities.fig

xvprime.m



No checker will be provided for this Honors project.

Objectives

In this MP, you will:

References



Part 1: Monte Carlo Integration

Section A: Problem Description

In this part, we will approximate the volume of an ellipse centered at the origin. The method of we'll use to approximate the volume is identical to the method discussed in the Monte Carlo lecture. Our ellipse is defined by the formula:

                                                                                   
1 = x2 + y2+ z2/4
 


The graph of the ellipse looks like this:

ellipse


Using calculus, we can compute the volume enclosed by this surface to be  8.377580409572781 You'll use this value to verify your answer later.

 The randomized method that we'll use to approximate the volume comes from observing that the shape is completely contained in the region where x and y range from -1 to 1, and z ranges from -2 to 2. If we randomly generate a ton of points in that region, and see what fraction of the points are inside the ellipse, then we can guess the volume.

Section B: Implementation

The following functions have already been written for you.
  • The function 'vol' is given. This function is the one you will actually be calling, once the program is complete. It approximates the volume of the ellipse by calling the other functions. You can refer to the Monte Carlo lecture for more details on how it works. The file we are using here is slightly different, though. There is an extra part added in to make plots of the ellipse when 'vol' is called.
  • The function 'inbox' is provided. This generates the desired number of random points using the rand function. Refer to the Monte Carlo lecture.
  • The function 'drawEllipse' is provided. It makes a 3D plot of the ellipse using some smooth shading.
  • 'drawEllipseT' is also provided. It's the same as 'drawEllipse', except that it draws the ellipse in a transparent (meshed) fashion, so you can see the points that fall inside the ellipse.
  • The function 'box3' is provided. This draws all the edges of a box given two x, two y and two z values. It's called by 'drawEllipse'.
  • The function 'drawpoints' is provided.  This draws the points generated by 'ptsinbox'.
What you'll need to do:
  • Write a function named inEllipse. This serves the same purpose as the function insphere in the Monte Carlo lecture.
  • Run vol to compute the volume enclosed by our solid 3-D shape.
To accomplish those three tasks, follow these steps:
  1. Download the files vol.m, box3.m, inbox.m, drawEllipse.m , drawEllipseT.m and  drawpoints.m into your home directory by right clicking on the links and selecting "Save Link As...".
  2. Start up Matlab if you have not already done so. Then use the command what. You should see the files you just downloaded.
  3. Run either of the scripts drawEllipse or  drawEllipseT. You should see a 3-D plot similar to the graph above. Rotate the graph manually by using the Rotate icon on the far right of the tool bar to get a better feeling of the shape. You won't have to code these scripts, they are already complete. You can use the editor to see that they use the ellipsoid function to draw the ellipse.
  4. Write a Matlab function inEllipse. Your function should take as input the vectors xr, yr, zr, which represents the coordinates of a set of points in 3-D. For example, [xr(1),yr(1),zr(1)] and [xr(10),yr(10),zr(10)] are the first and tenth points, respectively. You can assume that the three vectors will all be the same length.

  5. inEllipse should return a vector called inout_vec which consists of 0s and 1s and has the same length as the input vectors. The element inout_vec(i) will be 0 if the corresponding point [xr(i), yr(i),zr(i)] is outside the ellipse, and 1 if it's inside.

    The function as given below is almost complete. Only the last line needs to be finished. You should make use of r in the last line. Use an inequality like in the Monte Carlo lecture. Test your inequality on some points like (0,0,0) to make sure you assign the 1s and 0s to the right points.

      function inout_vec = inEllipse(xr,yr,zr)
    %
    function inout_vec = inEllipse(xr,yr,zr) 
    % inEllipse: Determines if points are inside the ellipse.
      % xr, yr, zr are all row vectors of same length.  Returns a
      % row-vector inout_vec of the same as the inputs.

     

      inout_vec = ______________________________________;
    Note that the formula that will be used here will be the formula given above, not the one in the slide (that's a unit sphere, which is certainly not what the ellipse looks like). Remember to save your file as inEllipse.m. Also remember to suppress all output by adding a semicolon at the end of the line.
     
  6. Compute the volume by running the function named 'vol'.

    (Note: In previous semesters , inorder to perform the graphics for this honors project you must type the following at the Matlab prompt before you run the vol function,
        >> opengl software

     )

    When using 'vol', we must specify a box that contains the object we're measuring. We'll get the best results if we use the smallest box which contains the object. In our case, the range of the smallest box which contains our ellipse is:

    x from -1 to 1
    y from -1 to 1
    z from -2 to 2

    Make sure to enclose 'inEllipse' in single quotes when using it in the call to 'vol'.

  • Answer Part 1: Questions 1 through 3 on your answer sheet.
    How does your answer compare to the analytical answer given at the beginning of this part?
  • Answer Part 1: Question 4 on your answer sheet.


Part 2: Modeling collisions

Instructions: You will need to read the following instructions in sections 1) thru 3). You will begin coding in section 4) Implementation


You will need to read the following instructions in sections 1) thru 3). You will begin coding in section 4) Implementation


1) Introduction

1.1) Dynamics of Hard Spheres - Your Honor’s Project

The motion of molecules in a gas, the dynamics of chemical reactions, atomic diffusion, sphere packing, the stability of the rings around Saturn, the phase transitions of cerium and cesium, one-dimensional self-gravitating systems, a game of billiards or snooker, front propagation are all examples of dynamics. Also, they have the additional similarity of having spherical or nearly spherical colliding objects in each of the above presented examples. We can take some time here to observe three facts: 1) Their inter-disciplinary nature, 2) The role of Computer Programming and 3) The fact that a common program written to simulate the motion of colliding particles can describe all these phenomena. We could also observe the fact that all these are at least related to the Brownian Motion which was introduced earlier.

The purpose of this programming assignment is to develop a computer program which could represent to an acceptable level of accuracy, the above mentioned condition; that is, to simulate the motion of “N” colliding particles based on the laws governing elastic collisions and basic dynamics.

[P.S.: We are really grateful to the Computer Sciences Department of the Princeton University for providing us with useful material in this respect. More information regarding this can be found here.]


2) Modeling

2.1) In General

Modeling refers to the process of the reproduction of the given problem, usually to a smaller scale. Modeling often involves certain simplifying assumptions which make the process of creating a model simpler.

The modeling involved in dynamical analysis is in turn sub divided into 2 major steps:-

a) Creating an Analytical Model

b) Obtaining a Mathematical Model from the Analytical Model.

The process of obtaining the Analytical Model consists of the following main steps:

a) A list of simplifying assumptions which permit to reduce the real life problem into a simpler analytical model.

b) Drawings that depict the Analytical Model.

c) A list of design parameters.

To create a useful Analytical Model, you must clearly have in mind the intended use of the analytical model, that is, the types of behavior of the real system that the model is supposed to represent faithfully.

Once the analytical model of the structure has been created, we can apply the concerned physical laws to convert the dynamical equations of the system under question into Mathematical equations. These Mathematical equations so obtained are termed the “Mathematical Model”.

In practice, you will find that the entire process of creating first an analytical model and then a mathematical model may be referred to simply as mathematical modeling.

2.2) Analytical Modeling of the “Molecular Dynamics” Problem

Any real life problem is a complex one. However, it is observed that certain simplifying assumptions can be made which reduce the complexity of the problem without a great deal of reduction in the accuracy of the desired variables. In other words, these assumptions make life much simpler than what it would be otherwise.

For this problem, one major simplification has been made. The molecule (or the sphere) under study is an elastic body, which should undergo elastic deformations upon collisions. However, it has been observed that neglecting these small deformations does not affect the end result very much, although it reduces the complexity of the problem a good deal. So, in the analytical model of this problem, we assume that atoms or molecules or the spheres (these three terms are equivalent; the use of any of these three words in future would represent the same.) in the container behave as “hard spheres”, also called the “billiard ball model”. When we focus on the two-dimensional version of this, they behave as the “hard disc model”.

We will do our calculations in 2D. (3D would not be much more difficult but we will leave that for you to do for fun.)

In addition to this major assumption, we also make other simplifications which result in the following salient features of this model:

a) “N” particles in motion.

b) All particles are confined in the ‘unit box’.

A box of unit height and width, 0 <= x <=1, 0 <= y <= 1.

c) Particle ‘i has the position (rxi, ryi), velocity (vxi, vyi), mass mi, and radius σi.

d) All particles interact via elastic collisions with each other and with the reflecting boundary.

e) No other forces are exerted. (e.g. no gravitaional effect on particles or between particles.) Thus, particles travel in straight lines at constant speed between collisions.

There are two natural approaches to simulating the system of particles.

A) Time-driven simulation:

Discretize time into quanta of size dt. Update the position of each particle after every dt units of time and check for overlaps. If there is an overlap, roll back the clock to the time of the collision, update the velocities of the colliding particles, and continue the simulation. This approach is simple, but it suffers from two significant drawbacks.

First, we must perform on the order of N2 collision checks per time quantum ,

(actually N choose 2 particle-to-particle collisions, N choose 2= N*(N-1)/2 plus 2*N checks for the particle-wall collisions).

Second, we may miss collisions if dt is too large and colliding particles fail to overlap when we are looking. To ensure a reasonably accurate simulation, we must choose dt to be very small, and this slows down the simulation.
We will NOT do time-driven simulation in this MP.

B) Event-driven simulation:

With event-driven simulation we focus on those times at which interesting events occur. In the hard disc model, all particles travel in straight line trajectories at constant speeds between collisions. Thus, our main challenge is to determine the ordered sequence of particle collisions. We address this challenge by maintaining a event matrix of future events for each particle. At any given time, the event matrix contains the next future collision that would occur for each particle, assuming each particle moves in a straight line trajectory forever. As particles collide and change direction, some of the events scheduled on the priority queue become "stale" or "invalidated", and no longer correspond to physical collisions. Thus we will have to update this event matrix. For example, we have the following events in the queue:

particle# |  time-to-next-collision | particle/wall

1   .02     5  ( particle #1 will collide in .02 seconds with particle #5)

2   .2       1   ( particle #2 will collide in .2 seconds with particle #1, we haven't yet taken into account here that particle #1 will first collide with paricle #5 )

3   .05    -1 ( partice #3 will collide with  the horizontal wall  in .05 seconds,  -1 means horizontal wall collision)

4   .4      -2 ( particle #4 will collide with the vertical wall in .4 seconds, -2 means vertical wall collision)

5   .02     1  ( particle #5 will collide in .02 seconds with particle #1)

N   Inf     -3   ( particle #N will not make any collisions since a value of -3 means zero velocity so no collison with any wall,  and there is also no particle collisions. Inf is the Matlab constant for +infinity.)

From the values shown above the next collision for any of the particles is between Particle 1 and 5 since the time for this collision is the smallest value ( .02 seconds).
Particle 2’s next collision is with Particle 1 but that won’t happen since Particle 1 will collide with Particle 5 first ( in .02 seconds).

The event matrix will have N rows but just two columns (since the first column above is always 1 thru N we don’t need to store this in the event matrix.).

So the format of the event matrix will be such that the i-th row of the event matrix has the form:

[ time-to-next-collision   j   ]

where j is an integer from 1 to N  representing a particle number or -1,-2 representing a horizontal or vertical wall collision respectively or -3 meaning NO COLLISION with wall or partice.

In the case where j = -3 instead of using the Matlab Inf as in a row value of

[ Inf   -3]
instead we could record this row as

[ arbitrary_real_number    -3]

if we wanted to avoid using the Matlab constant Inf.

 

3) The Math

In this section we present the formulas that specify if and when a particle will collide(hit) with the boundary (wall) or with another particle, assuming all particles travel in straight-line trajectories.
For simplicity we will avoid considering simultaneous collisions with 3 or more particles or simultaneous collisions of separate pairs of particles or a particle that hits the corner of the box ( hits both walls simultaneously).

 

3.1) Collision Prediction

I) Collision between particle and a wall:

  Assume you had only a single particle of radius σ in the unit box (0 <= x <= 1 and 0 <= y <= 1) where the center of the partice is located at (rx, ry) and thus σ <= rx <= 1-σ and σ <= ry <= 1-σ , with velocity (vx, vy).
The questions we need answered are:

1) Which wall will the particle hit, if any? 
2) What is the new position vector (rx', ry') and new velocity vector (vx', vy') after the collision.
3) How much time does it take to hit the wall Δt?

Here is our strategy for answering the above questions.
We will answer 3) first then use our results to determine 1) and then 2) will follow.

To answer question 3) ,

If the inital velocity is zero i.e.  (vx, vy) = (0,0) then the particle would not move and thus not make contact with a new wall( of course it could be touching a wall and not moving too but that doesn't change the fact that the particle will not hit a new wall). This answers question 1)  and to answer question 2) since vx = vy = 0 then its new position at any future time would be (rx', ry') = (rx, ry) and new velocity (vx', vy') = (0,0).
Else if the particle were moving, ie. vx and vy are not both 0 then then there must be a future contact with the walls of the unit box. Lets solve this problem in a lazy way. We first assume that the box has no vertical walls, only horizontal walls (extended infinitly in both directions) and then try compute Δt_y the time the hit the horizontal wall. Next assume that the box has no horizontal walls jut vertical walls and then try to compute Δt_x the time to hit the vertical wall. Now that we have computed Δt_y and Δt_x find the smallest of the two Δt = min(Δt_x, Δt_y) and that will tell us which wall is actually hit. This answers question 1). Question 2) is answered by using the formula (rx', ry') = (rx, ry) +Δt * (vx,vy) and (vx', vy') = (vx, -vy) if a horizontal wall is hit and (vx', vy') = (-vx , vy) if a vertical wall is hit.  There is a very rare case where Δt_x = Δt_y when the particle hits the corner of the box. You don't have to write code for this case. If you write code then the new positon is also given by the same formula (rx', ry') = (rx, ry) +Δt * (vx,vy) but the new velocity is given by  (vx', vy') = (-vx, -vy).

Yes, it may occur that vx > 0 and vy = 0 so that computing  Δt_y = Inf in Matlab  but since  Δt_x is finite then  Δt = min( Δt_xΔt_y) =  Δt_x and this is correct so your code should work correctly without any changes.
Also, it may occur that vx = vy = 0 but this would give Δt = min( Δt_x, Δt_y) = min(Inf, Inf) = Inf and that is correct so again you don't need to modify your code for this special case. If you don’t like working with Inf then in these cases set Δt = 1.0e100.

All that is left to do is to find the formulas for Δt_x and Δt_y.

a) Δt_y  ---Horizontal Wall Collision

Given the position vector (rx, ry), velocity vector (vx, vy), and radius σ of a single particle at time t, we wish to determine if and when it will collide with a vertical or horizontal wall. the new velocity (vx', vy') =  (vx, -vy) for either upper or lower wall collision. To determine the new position  (rx', ry') consider the figure below.

collision-elastic2.png

                                                                                                                                                        The figure above shows a future collision of a particle with the lower horizontal side of the boundary(wall).


A particle comes into contact with a horizontal wall at time t + Δt if the quantity ry + Δt * vy equals either σ (lower horizontal wall collision) or (1 - σ) (upper horizontal wall collison).
Solving for Δt yields:

delta_t_y



b) Δt_x ---Vertical Wall Collision

An analogous equation predicts the time of collision with a vertical wall. The


delta_t_x

Since we are going to be dealing not with just one particle in the unit box it may occur that before a particle hits a wall of the box the particle hits (or is hit ... depending on your perspective, that is, from which particle you view the collision) another particle. We need to answer the following questions.

We are given information on particle  i   at time t , its position (rxi , ryi) and velocity (vxi , vyi )

1) Will particle i hit particle j   (whose position at time t is (rxj , ryj) and velocity is (vxj , vyj ))  ? 
2) What is the new position vector (rx', ry') and new veloctiy vector (vx', vy') at the time of collision for both particles i and j ?
3) How much time Δt does it take for particle i to hit particle j  ?


II) Collision between two particles.

Again, we will answer 3) first and if Δt  = Inf we know there is no collision but if Δt  is finite there will be a collision and then we will answer 2).

 

Given the positions and velocities of two particles i and j at time t, we wish to determine if and when they will collide with each other.

collision-elastic.png

Let (rxi' , ryi' ) and (rxj' , ryj' ) denote the positions of particles i and j at the moment of contact, say t + Δt. When the particles collide, their centers are separated by a distance of σ = σi + σj. In other words:

σ2 = (rxi' - rxj' )2 + (ryi' - ryj' )2

During the time prior to the collision, the particles move in straight-line trajectories. Thus,

rxi' = rxi + Δt vxi,   ryi' = ryi + Δt vyi      EQUATION  1
rxj' = rxj
+ Δt vxj,    ryj' = ryj + Δt vyj       EQUATION  2

Substituting these four equations into the previous one, solving the resulting quadratic equation for Δt, selecting the physically relevant root, and simplifying, we obtain an expression for Δt in terms of the known positions, velocities, and radii.

collision-particle.png
      and
delta_rEQUATION 3

delta_vEQUATION 4

     and
other
            equations

 

If either (Δv Δr) ≥ 0 or d < 0, then the quadratic equation has no solution for Δt > 0; otherwise we are guaranteed that Δt0.

 

In the event the particles i and j will collide at the future time we then need to determine the new positions and velocities. There are three equations governing the elastic collision between a pair of hard discs: (i) conservation of linear momentum, (ii) conservation of kinetic energy, and (iii) upon collision, the normal force acts perpendicular to the surface at the collision point. Students inclined towards Physics are encouraged to derive the equations from first principles; the rest of you may keep reading.

I) Collision between particle and a wall:

When two hard discs collide, the normal force acts along the line connecting their centers (assuming no friction or spin). The impulse (Jx, Jy) due to the normal force in the x and y directions of a perfectly elastic collision at the moment of contact are:

J

JxEQUATION 5

JyEQUATION 6

 

and where mi and mj are the masses of particles i and j, and σ, Δx, Δy and Δ v Δr are defined as above. Once we know the impulse, we can apply Newton's second law (in momentum form) to compute the velocities immediately after the collision.

vxi' = vxi + Jx / mi, vxj' = vxj - Jx / mj     EQUATION 7
vyi' = vyi
+ Jy / mi, vyj' = vyj - Jy / mj    EQUATION 8


4) Implementation

Download ALL of the following files:

main.m

start_position1.m

start_position2.m

create_event.m

update.m

box.m

plotbox.m

plotp.m

demo.p

 

Your programming in this MP will involve completing the update function.


We have given you the code for the main function but it’s a good idea to look at the code before you begin coding for the update function. There is NO checker for this MP. So you must first complete your code for the update function and then type the following at the Matlab prompt:

>> position = main(500, 1.0e-11, 'start_position1');

or

>> position = main(500, 2.0e-10, 'start_position2');

Your results should look similar to,

>> position = demo(500,2.0e-10, 'start_position2');

You can type Control-C to terminate execution.

4.1) The main function a Step - by - Step Algorithm

1. The function ‘main.m’ which has three inputs, the number of molecules N, the total time total_timeand a function that computes the initial position matrix.

2. You will be able to download two functions that compute the initial position matrix one is named start_position1.m and the other start_position2.m. The main function calls the start_position1.m or start_position2.m function that you pass to main as a function argument. Note that the start position matrix has the form:

[ x , y , vx , vy , radius , mass ] and has ‘N’ rows.

3. We first plot the position matrix.

4. Assign time = 0

5. Call the create_event function to create initial event matrix.

6. Loop while time < total_time

a. Call the update function to find the time to the next collision dt, and update both the position and event matrices.

b. Increase time by dt.

c. plot the position matrix

4.2) Event Driven Simulation … update function

When we update the event matrix we will,

1)   1) find the minimum time-to-collision value in the event matrix

2)   2) if the above event corresponds to a particle-to-particle collision then add these to the update list. The update list contains the particle number (integer) for those particles we need to update the event matrix, that is, for these particles we need to find their next collision and put that collision in the event matrix. If the next collision is particle-wall then just add this particle to the list.

3)   3) check whether there are other particles in the event list that were to collide with the particle(s) in the list above. These particles should also be added to the list.

4)   4) update the position matrix using the math below above

5)   5) reduce the time (every row in the event matrix) by the minimum time-to-collision found in 1)

6)   6) call the create_event function and update all rows in the event matrix that are in the list from steps 2) and 3)

 

 

You are required to complete the following two tasks.

First Task: Completing the code for the function update.m. Replace all the blanks with your code.

Second Task:  Using the start_position1  call main as shown below. The start_position1  function assigns all particles to have the same magnitude for velocity in the position matrix. Remember if the velocity of a particle is V = [Vx, Vy] then the magnitude of the velocity would be,

magnitude

After you run the Matlab command,

>> position = main(500, 8.0e-11, 'start_position1');  % this may take 20-30 minutes and if you run it on a lab computer while and not remotely it will take less time

create a vector named velocities that contains only the magnitudes of the velocities of the particles and then display the velocities in a histogram, (see Maxwell/Boltzmann  to get an approximate view what your plot should look like. Your plot would look closer to the one shown if you increased the value 8.0e-11)

>> hist(velocities,14)

In the figure window click File/Save As and save this image as velocities.fig.

Submit the following files:
:

I) update.m

II) velocities.fig



Part 3: Solving the harmonic oscillator problem.

Instructions: In this portion of the MP, we will be writing MATLAB code to plot the position on the horizontal axis of a weight attached to  a spring assuming the existence of air friction.


oscillator


(Think of a spring loaded screen door on your house.)
 1. Problem Definition
      We will use the Matlab function ode45. The goal is to plot the horizontal position of the mass m with respect to time.
 2. Refine, Generalize, Decompose the problem definition (i.e. identify sub-problems, I/O, etc.)
       When you code your solution in the function xvprime.m you should run  your program with the following three cases.
        a.    m = 1, k = 100, b = 2
        b.    m = 1, k = 100, b = 20
        c.    m = 1, k = 100, b = 5

      When you  submit your solution  you can  leave  either one of the three choices  listed above.
       Assume that at  t = 0  , x = 1 and v = 0.   Use the time interval  [0, 10].
   3. Develop Algorithm (processing steps to solve problem)
       The ODE is described by the harmonic oscillator:

       equation

       Answer Part 3: Question 1 on your answer sheet.

     4. Write the Function (Code)
         The first line should be

          function xvp = xvprime(t , xv)

          % use m = 1 k = 100 b = 2 as values for now then after you have done a plot then change b = 20 and later b = 5

     5. Test and Debug the Code
          Answer Part 3: Question 2 on your answer sheet.

     6. Run the Code
         After you have run the code, plot the solution. Do this for each of the three cases for b = 2,20,5.
         Answer Part 3: Question 3 on your answer sheet.

       You will not handin the plots.   Answer Part 3: Question 4 on your answer sheet.





Your solution to this MP should include the answering the questions on the Answer webpage ( answer_sheet )and emailing the answers and all of the following files to ( Jiahui Jiang:  ta8cs101@cs.illinois.edu ).

inEllipse.m

update.m
velocities.fig

xvprime.m