Presentation is loading. Please wait.

Presentation is loading. Please wait.

ECE 1180 Professor Steven Levitan TA: Rakshit Joydeep

Similar presentations


Presentation on theme: "ECE 1180 Professor Steven Levitan TA: Rakshit Joydeep"— Presentation transcript:

1 ECE 1180 Professor Steven Levitan levitan@pitt.edu TA: Rakshit Joydeep jor73@pitt.edu http://kona.ee.pitt.edu/1180wiki

2 Goals Provide students with the skills to: Apply knowledge of mathematics, engineering, and computer science to the modeling of physical systems Use programming techniques to develop computer simulations of physical systems. Understand the significance and limitations of computational models to predict the behavior of systems and the ethical and social implications of using models to make design choices and policy decisions.

3 Learning Objectives Students will be able to: Develop mathematical models of physical systems and processes. Develop simulation software that captures the interactions of models and generates the representative behaviors. Create visualizations of the behavior of system simulations. Perform an engineering “code review” on a software project created by another team. Critique the use of simulation tools in terms of the methodologies used and the conclusions made.

4 Requirements Use a laboratory notebook –Bring it with you every day –Take good notes Lots of very important details given in class, will be lost if you do not write them down Stop the lecture and ask for clarification Do not assume it will “be on the web” later unless you put it there (wiki) Bring a memory stick (bring a laptop) Code in C/C++ –Only use python/Vpython for graphics Give attribution to all sources! –Lab partners, web sites, papers, books Collaboration is encouraged, but cheating will not be tolerated

5 Course Organization Focused on programming projects –Lots of them –Staged in order of complexity –Each project: New system to be modeled New modeling / simulation technique New programming concepts Grades based on projects (both code and write-ups), quizzes and homework

6 Four Themes Simulation methodology Programming (C, C++, Visual Python) Physics of what we are modeling Mathematical models of systems and interactions

7 Simulation Methodology Model Objects - are we modeling fields, molecules, masses, or devices? World Representations – are we using grid-based, grid- less, or network models? Object Interactions – how do the objects interact - with forces, energy conservation, exchanges of matter, or passing information? Time – do we use fixed time steps, variable time steps, or discrete events? State Transformation and Convergence – do we keep our model states consistent by testing and iterating, performing explicit integration, or assume consistency based on fine granularity in space and time?

8 Lecture/Project Format Introduce new system to be modeled Research physics/system we are modeling - find resources on line Define goals of simulation – what are we trying to accomplish with the simulation? Chose simulation methodology Discuss modeling concepts “math/physics” Identify numerical methods required Review programming concepts

9 Falling Apples

10 Gravity F = m * A F = G*m 1 * m 2 /r 2 G = Gravitational Constant m 1 = mass of earth r = radius of earth m 2 * A = m 2 * Gm 1 /r 2 A = Gm 1 /r 2 acceleration at earth surface

11 Closed Form Solution Velocity is the integral of acceleration Distance is the integral of velocity Time to fall 100 meters is: 4.517539515 s

12 Why not always use closed form? What if forces are more complex, or forces (or mass) changes? Rocket with fuel burning, wind resistance, distance from earth changing… –Sometimes we can find a closed form –Sometimes we can not…

13 Spread Sheet Exercise

14 Compute using discrete sums “area under the curve”

15 Compute using discrete sums Area under the curve?

16 Delta t Dt = 1.0 sec 98m in 4 sec Dt = 0.1sec 101 m in 4.5 sec

17 “area under the curve” What is correct ? Area = V1 * Dt ? (backward Euler) Area = V2 * Dt ? (Forward Euler) Area = (V1+V2)/2 * Dt ? (Trapezoid) v1 v2 Dt

18 Exam 1 On a sheet with your name AND photo: 1.Write a list of your goals for the course 2.Watch the first Feynman Messenger Lecture (Explorer/silverlight) http://research.microsoft.com/apps/tools/tuva/# http://research.microsoft.com/apps/tools/tuva/# 3.Answer: –Why are there two tides a day? And who figured it out? –What is the explanation of the ratio of the strength of gravity to that of electricity? 4.Define and compare: –Energy, Momentum, Force, Work and Acceleration 5.Define and explain “SI units” and list the base units

19 Programming Assignment 1 1.Write a program to generate 100 random numbers between 0 and 100 –Histogram the numbers into bins of multiples of 10 –Then sort them –Turn in program, histogram (numeric or graphic), and output 2.Write a program that displays maximum ( and minimum) int, long, float, double for your computer –Also show the difference between the max and the next smaller number 3.Get the visual studio / visual python environment up on your machine (use CodeBlocks as the IDE) –Write program that opens a Vpython window with “hello world” as text –Turn in image and code (with comments)

20 Falling, Bouncing, and Cannon Balls

21 Simulation Methodology Model Objects - are we modeling fields, molecules, masses, or devices? World Representations – are we using grid-based, grid- less, or network models? Object Interactions – how do the objects interact - with forces, energy conservation, exchanges of matter, or passing information? Time – do we use fixed time steps, variable time steps, or discrete events? State Transformation and Convergence – do we keep our model states consistent by testing and iterating, performing explicit integration, or assume consistency based on fine granularity in space and time?

22 P2 What are the objects? What is the world model? What are the object interactions? What is the model of time? What are the state transformations?

23 Visual Studio Use it or CodeBlocks See the wiki http://kona.ee.pitt.edu/1180wiki http://kona.ee.pitt.edu/1180wiki and the page: how_to_mix_c_and_python

24 VPython Only use the “V” part See the wiki on linking with visual studio For your own machine: –Download install from http://vpython.org/ (it tells you how to install python too)

25 Escape Velocity

26 Derivation using Conservation of Energy Watch the Feynman Lectures! http://research.microsoft.com/apps/tools/tu va/#http://research.microsoft.com/apps/tools/tu va/# Yes, all of them Yes really I am serious Also the NASA youtube http://www.youtube.com/watch?v=iCqm5u xc2dE

27 Back from our commercial

28 Top Down Design /* perhaps for all programs? */ Initialize the world While(not_done) –Do something Cleanup Exit

29 Top Down Design 2 /* perhaps for all simulators? */ Initialize the world –Initialize state of objects –Initialize graphics While(not_done) –Update object state –Update graphics Cleanup Exit

30 Top Down Design 3a Initialize the world –Initialize global (world states) –Initialize state of objects Create objects Initialize state variables –Initialize graphics Start graphics engine (Vpython) Place global (static objects, e.g. coordinate axis) Initial drawing of all objects

31 Top Down Design 3b While(not_done) –Update object states For each object –Update state variables –(based on interactions with world and each other) Update global state variables –Update graphics Draw/re-draw objects, draw-print global information –Test for done

32 Top Down Design 3c Cleanup –Free space, resources, etc. –Close graphics Exit –Return status result /* a modular design would enable “main” to be a sub- routine */

33 Top Down Design 3b1 –Update object states For each object –Update state variables /*** key step: DO THIS FIRST ***/ not top-down, not bottom-up Inside out Do the general case first Assume you have all the information you need Optimize this case Update global state variables

34 Top Down Design 3b1a Update state variables Generally each object has a state Sometimes there is only global shared state –Assume we can index through objects… (array of objects?) –Assume we can calculate what we need…(e.g., F(x,i,j) = ma) –Assume we can access state variables… ( e.g., x(i) v(j) ) Collect information about interactions between this object and world, other objects and itself –Compute instantaneous values (e.g., forces, energy, voltages) –Compute time depended changes (e.g., integrate) –Update state variables –Outputs should be same as needed for next iteration

35 3b1a example Start (inside out) HERE: Interaction between objects, each other, and world as a function of time: Between every two planets (me and thee) F(t)=m*a(t) = G*m*m /r^2 Need G, masses, and distance between objects Need position of objects, Have Acceleration: a = F/m; Need to integrate to get position from acceleration Therefore: For physical motion simulations of objects the assumed State Variables include: Per object: position, velocity, acceleration, forces, mass, (color, size) Global: time, delta-time, G Instantaneous update (instantaneous summation over all pairwise objects): Total Force on me += force between me and everyone else Total acceleration for me = Total_Force/my_mass Time dependent updates (integration: continuous summation over time): My_velocity += My_acceleration * delta_time My_position += My_velocity * delta_time DO NOT MIX THESE UP

36 3b1a example /* remember to reset acceleration states before re-computing */ /* Between every two planets (me (i) and thee(j)) F=ma = G*mi*mj /r^2 */ /* For acceleration i's mass cancels out. Use r^3 to get direction and +/- sign right for forces */ Ag = (G * planets[j].mass) /(pow(dist3D(planets[i],planets[j]),3)); /* Using direction cosines http://en.wikipedia.org/wiki/Direction_cosines */http://en.wikipedia.org/wiki/Direction_cosines planets[i].ax += -Ag * (planets[i].x - planets[j].x); planets[i].ay += -Ag * (planets[i].y - planets[j].y); planets[i].az += -Ag * (planets[i].z - planets[j].z); /* after we have summed all the forces we can update the time dependent state variables */ planets[i].vx += planets[i].ax*DT; /* continuosly integrate a for v */ planets[i].vy += planets[i].ay*DT; planets[i].vz += planets[i].az*DT; planets[i].x += planets[i].vx*DT; /* continuosly integrate v for x */ planets[i].y += planets[i].vy*DT; planets[i].z += planets[i].vz*DT;

37 Arrays From: http://publications.gbdirect.co.uk/c_book/chapter5/arrays.htmlhttp://publications.gbdirect.co.uk/c_book/chapter5/arrays.html double ar[100]; The name of the array is ar and its members are accessed as ar[0] through to ar[99] inclusive Each of the hundred members is a separate variable whose type is double All arrays in C are numbered from 0 up to one less than the bound given in the declaration This is a prime cause of surprise to beginners—watch out for it Arrays don't permit the use of varying or unknown sizes. Size must be constant expressions which can be evaluated at compile time, not run time* * This is NOT true for newer C compilers (C99 and later) see in later slides

38 Multi-dimension Arrays int three_dee[5][4][2]; int t_d[2][3]; In terms of actual machine storage layout the rightmost subscript ‘varies fastest’. This has an impact when arrays are accessed via pointers We can think of this as Row Major indexing Elements can be used just as would be expected; expressions like these are quite in order: three_dee[1][3][1] = 0; three_dee[4][3][1] += 2; /* increment last element of array by two */

39 Pointers Pointer declarations look much like other declarations: but don't be misled. When pointers are declared, the keyword declares the type of variable that the pointer will point to. The pointer itself is not of that type, it is of type pointer to that type. A given pointer only points to one particular type, not to all possible types. int ar[5], *ip; ar[0] = 1; ar[1] = -4; ar[2] =0; ar[3] =4; ar[4] =4; ip = &ar[3]; AddressNameValue 0H0010ar[0]1 0H0014ar[1]-4 0H0018ar[2]0 0H001Car[3]4 0H0020ar[4]4 0H0024ip0H001C

40 Pointer Example main() { int x, *p; p = &x; /* initialize pointer */ *p = 0; /* set x to zero */ printf("x is %d p is %x *p is %d\n", x, p, *p); *p += 1; /* increment what p points to */ printf("x is %d p is %x *p is %d\n", x, p, *p); (*p)++; /* increment what p points to */ printf("x is %d p is %x *p is %d\n", x, p, *p); *p++; printf("x is %d p is %x *p is %d\n", x, p, *p); } x is 0 p is 12ff60 *p is 0 x is 1 p is 12ff60 *p is 1 x is 2 p is 12ff60 *p is 2 x is 2 p is 12ff64 *p is -858993460 Press any key to continue...

41 Pointers and Arrays Array elements are just like other variables, they have addresses. int ar[20], *ip; ip = &ar[5]; *ip = 0; /* equivalent to ar[5] = 0; */ The address of ar[5] is put into ip, then the place pointed to has zero assigned to it. Pointer arithmetic is one of the cornerstones of C. Adding an integral value to a pointer results in another pointer of the same type. Adding n gives a pointer which points n elements further along an array than the original pointer did. int i, ar[20], *ip; for(i = 0; i < 20; i++) ar[i] = 0; for(ip = &ar[0]; ip < &ar[20]; ip++) *ip = 0; Notes: It is permissible to use the address of ar[20] even though no such element exists. The advantage (in this case) is that the pointer access requires no arithmetic. ar[i] requires a multiplication of i by the size of an integer.

42 More than you want to know… As far as the compiler is concerned, an expression like x[n] is translated into *(x+n) and use made of the fact that an array name is converted into a pointer to the array's first element whenever the name occurs in an expression. if x is an array name, then in an expression, x is equivalent to &x[0], i.e. a pointer to the first element of the array. So, since *(&x[0]) uses the pointer to get to x[0], *(&x[0] + 5) is the same as *(x + 5) which is the same as x[5]. \ A curiosity springs out of all this. If x[5] is translated into *(x + 5), and the expression x + 5 gives the same result as 5 + x (it does), then 5[x] should give the identical result to x[5]!

43 What does this do? #define ARSZ 20 main(){ int ar[ARSZ], i; for(i = 0; i < ARSZ; i++){ ar[i] = i; i[ar]++; printf("ar[%d] now = %d\n", i, ar[i]); } printf("15[ar] = %d\n", 15[ar]); }

44 Summary Arrays always index from zero—end of story. There are no multidimensional arrays; you use arrays of arrays instead. Pointers point to things; pointers to different types are themselves different types. They have nothing in common with each other or any other types in C; there are no automatic conversions between pointers and other types. Pointers can be used to simulate ‘call by reference’ to functions, but it takes a little work to do it. Incrementing or adding something to a pointer can be used to step along arrays. To facilitate array access by incrementing pointers, the Standard guarantees that in an nelement array, although element n does not exist, use of its address is not an error—the valid range of addresses for an array declared as int ar[N] is &ar[0] through to &ar[N]. You must not try to access this last pseudo-element.

45 So what? Use pointers –For efficient multidimensional array indexing –For dynamically allocated arrays and structures –To enable functions to alter values of their arguments –&x “the address of x”, *y “what y points to”

46 2/3D Arrays with helpers Use arrays of pointers to point to 1D arrays Read Numerical Recipes in C intro Faster than multiplication Easy to pass around (pointers)

47 3 d Arrays Ideal Structure: 4 x 4 x 4 A[i][j][k] = *(A+i*height*width+j*width+k) Lots of multiplies and adds Every one needs to know height and width of array Real Memory 64x1

48 3 d Arrays Memory Slice Pointers Row Pointers Pointer Arithmetic a[i][j][k] = *(*(*(a+k)+j)+i) Need helper array (s) Don’t need to know size at compile time Can malloc array(s) to needed sizes at run time a k j i k j i

49 Gaussian Elimination N equations in N unknowns (x, y, z) A,B,C,D are known constants: A1x + B1y + C1z = D1 A2x + B2y + C2z = D2 A3x + B3y + C3z = D3 Put the constants into a matrix: A1 B1 C1 D1 A2 B2 C2 D2 A3 B3 C3 D3 Use linear operators to transform the matrix to: 1 0 0 Dx 0 1 0 Dy 0 0 1 Dz Dx, Dy Dz are the values for x y and z that make the first equations true – thus solving the equations.

50 Gaussian Elimination Two basic linear operations used on matrix: */ by constant add/sub rows from each other: A1 B1 C1 D1 A2 B2 C2 D2 A3 B3 C3 D3 Divide first row by A1, becomes: 1 B1/A1 C1/A1 D1/A1 Subtract A2 times first row from second row, becomes: 0 B2-B1A2 C2-C1A2 D2-D1A2 Subtract A3 times first row from third row, becomes: 0 B3-B1A3 C3-C1A3 D3-D1A3 Now we have the first column in the right form, continue with second row, second column, etc.

51 Gaussian Elimination int gauss(double **M, int maxrow, int maxcol) { int diag, row, col; double pivot, pivot2; for (diag = 0; diag < maxrow; diag++) { /* for each row = variable = diagonal element */ pivot = M[diag][diag]; if (pivot == 0) { printf("Gauss: Singular Matrix!\n"); return(1); } for (col = diag; col < maxcol; col++) { /* from diagonal to right, divide out by the pivot diagonal element */ M[diag][col] /= pivot; } for(row = 0; row < maxrow; row++) /* for all other rows subtract scalled diag row, zeroing pivot column */ if (row != diag) {{ /* scale all elements of diag row by value which will zero diag element of this row, and subtract from this row */ pivot2 = M[row][diag]; for (col = diag; col < maxcol; col++) M[row][col] -= M[diag][col]*pivot2; } return(0); }

52 Nodal Analysis: NA For a linear circuit, solve Kirchhoff's current law (KCL) and voltage law (KVL) using a matrix formulation, just Ohm’s law in a matrix: |G| x |V| = |I| G is conduction matrix (1/R) V is vector of unknown node voltages I is vector of known node currents Solve by inverting G and then multiplying I to get V or concatenating |G||I| and performing Gaussian elimination (or equivalent) to get V Assumes G and I are constant

53 Modified Nodal Analysis: MNA Adds voltage sources to circuits Matrices are a little more complex, solution is the same General form of linear equations: used for a lot of systems beyond circuits A matrix is conduction and voltage sources G is conduction, B is voltages C = B T, D = 0 X is unknown voltages and currents Z is known voltages, currents Solve by matrix inversion and multiplication:

54 Conduction Matrix G is matrix of conductions (1/R) = g For each impedance: if R is on node k, add value of 1/R on diagonal (k,k). –If other end of R is on ground, stop –Else, if R is on node j add 1/R to other diagonal (j,j) and add (-1/R) on elements (k,j) and (j,k)

55 Voltage Source Matrices B has a column for each voltage source, V If V has a positive terminal on node j, put 1 in row j. –If other end of V is on ground, stop –Else, if V has a negative terminal on node k put -1 on row k C is B transpose (row for each source…) D (corner) is zero if no dependent sources

56 Vector of Unknowns X is composed of the unknown node voltages and voltage source currents. V k for each unknown voltage at node k J i for the current through each voltage source i (in the direction of positive terminal through the device to the negative terminal).

57 Vector of Knowns Z is composed of the known node currents and voltage source voltages. I k for each known current at node k. This is zero unless there is a current source at node k. if so, the value is +current positive node. If other end is not on ground, then value is –current at other node. V j for the value of voltage source j.

58 Example Circuit

59

60 X=        j v        e i        DC BG 1 5V12V 32V -30V 70mA

61 Energy Storage Capacitors and Inductors store energy and thus have voltage (current) dependent conductance: Capacitor: Inductor:

62 Need to do Numerical Integration Two rectangular rules for integration x n+1 = x n + h*x ’ n ( forward Euler) x n+1 = x n + h*x ’ n+1 ( backward Euler) Many others: Trapezoid, Gear, Simpson Use for integration for charge storage: v n+1 = v n + h * v ’ n+1 v n+1 = v n + h/c * i n+1 Rearrange: I n+1 = (c/h)* v n+1 – (c/h) * v n Define: Geq = c/h Gives a Norton Equivalent circuit: xnxn x n+1 x’nx’n x ’ n+1 h

63 Capacitor Companion Model in MNA Adds companion model (Norton equivalent circuit) to G, X and Z matrices. Note signs of Ieq nodes Ieq must be re-calculated after each time step: Ieq n+1 = (V + n+1 -V - n+1 ) * C/h If h changes, then Geq = C/h must be re-calculated too!

64 Low Pass Filter A = 0.0002 -0.0002 1.0000 -0.0002 0.0012 0 1.0000 0 0 R = 5Kohm C =.001 uF h = 1 uSec C/h = 1e-3 I c = V 2 * C/h X = 0 5.0000 5.0000 5.0000 5.000 5.000 5.000 5.000 5.000 0 0.8333 1.5278 2.1065 2.5887 2.9906 3.255 3.6046 3.8372 0 -0.0008 -0.0007 -0.0006 -0.0005 -0.0004 -0.0003 -0.0003 -0.0002 A X Z T = 0 1uSec 2uSec 3uSec 4uSec 5uSec 6uSec 7uSec 8uSec

65 Low Pass Filter

66 Non Linear Devices MNA provides solution for linear system of components, using a linear solution technique (matrix inversion) For non-linear devices we need to generate a “good” linear approximation model –Only good for a particular region of operation (operating point) –Only as good as our linearization technique Any linear circuit can be modeled as a Norton (or Thevenin) equivalent circuit –Find a linear “companion model” using Norton equivalent circuit

67 Diode Linear Companion Model Need values to approximate the function: Nonlinear diode equation: Slope of line: Y intercept: IdId VdVd V do I do I eq Short Circuit Current: I eq

68 Need to Find Operating Point I eq is function of both I do and V do Use Newton’s (tangent) Method: –Guess and Iterate using linear companion model (Norton equivalent) This is true for some value of V d such that:

69 Functions Functions return a value (int is assumed) Void means they do not int sam() { return (1); } double jane(); void fred();

70 Call by Reference int fred(int a, int b) { a = b; return(a); } void swap (int a, int b) { }

71 Structs and Typedefs Structs define a collection variables that share a name. Struct atom { double mass; int color; }; atom a;/* a single atom */ atom gas[100]; /* array of 100 atoms */ a.mass = 2.4e-22 gas[3].color = 3; Structs can have other structs inside. Arrays of structs and structs with arrays inside are fine In C you can not assign all of a struct at once (in C++ you can) a = atom[3]; /* not allowed */ You can not print structs as one object either: printf(“struct is %?”, a); /* not allowed */

72 Typedefs Typedefs define a “type” like int, float –It allows you to introduce synonyms for types which could have been declared some other way. The new name becomes equivalent to the type that you wanted. typdef int fred[100]; fred sam; /* sam is an array of 100 ints */ Unlike C++ you can not overload operators –You have to write explicit functions Programmers often use stucts and typedefs and pointers together typedef struct foo { int a,b; float c; } bar *p_bar ; bar b; /* sam is of type struct foo */ p_bar p; /* p is of type pointer to struct foo */

73 Dynamic Storage Often you don’t know in advance how big to make an array or other structure. 1.Make it as big as you think (worst case) –Don’t forget to test it (! C will not !) Number 1 method of hacking systems 2.Ask the operating system for storage as you need it: malloc(); /* memory allocation request */ free(); /* return the memory to the nice operating system */

74 malloc() malloc, like exit(); and printf(); are calls to the operating system to do something outside the program itself (void *) malloc(int); /* malloc takes the number of chars = bytes */ /* and returns a pointer to that memory, or 0 */ Note the memory itself is in a shared pool, so make sure you use it correctly Not guaranteed to be zero, if someone else used it first (calloc) How big – use sizeof(), gives size of objects in chars=bytes typedef char *string; string s; s = (string) malloc(81* sizeof(char)); /* an 80 character string */ s[0] – s[79] is for characters, S[80] is reserved for the null termination, if you use all 80 characters. s[81] is someone else’s memory!

75 Example: Linked Lists typedef struct le { double time, value; char name[20]; struct le *next; } list_element, *list; Note self reference to a pointer – like this is allowed! (recursive storage is not) next list_element time value name[20] list

76 List Operations list new_list(list l, string s, double t, double v) { list n; int i=0; n = (list)malloc(sizeof(list_element)); n->time = t; n->value = v; while(s && i name[i++] = *(s++); n->name[i] = 0; n->next = l; return(n); } void print_list(list l) { while(l) { printf(“%s - Time:%e, Value:%e \n”, l->name, l->time, l->value); l = l->next; } list_element n next time value name[20] l

77 List Insertion (on head) new->next = head; head = new; head new head

78 List Insertion (on end) for (p = head; p->next; p = p->next) {} p->next = new; new->next = NULL; What happens if head == NULL or if head->next == null? head new pppp

79 List Insertion (sorted) for (pl = head; pl; pf = pl, pl = pl->next) { if (pl->value > new->value) { new->next = pl; pf->next = new; } What happens if head == NULL or if head->next == null or if new->value is < all of them? head new pl pf

80 DE data structures module_head event_head inlist_head net_head

81 DE linkages and simulation nets modules events Due to the nature of the netlist, we know which/how many nets go with each module, as we parse the netlist. But we do not know how many modules go with each net, or which module is the driver, until we get to it. nand functions nor


Download ppt "ECE 1180 Professor Steven Levitan TA: Rakshit Joydeep"

Similar presentations


Ads by Google