Second Year C and R Assignment

Similar documents
2nd Year Computational Physics Week 1 (experienced): Series, sequences & matrices

Lesson 8 - Practice Problems

pointers + memory double x; string a; int x; main overhead int y; main overhead

Lab 1: Silver Dollar Game 1 CSCI 2101B Fall 2018

Getting Started With Linux and Fortran Part 2

Quadratics Functions: Review

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

Question 1. [5 points] Consider the following partially-complete program, which begins on the left and continues on the right: HERE

Pointers, Arrays and Parameters

Biostatistics 615/815 - Lecture 2 Introduction to C++ Programming

Lab 2: Threads and Processes

CSC D84 Assignment 2 Game Trees and Mini-Max

Practical 2: Using Minitab (not assessed, for practice only!)

2. EXERCISE SHEET, RETURN DATE MAY 7/8TH 2015, INDIVIDUALLY. to the compiler options. I also suggest you to use the options

INTRODUCTION TO LABVIEW

COMPUTER SCIENCE LARGE PRACTICAL.

Linux Tutorial #1. Introduction. Login to a remote Linux machine. Using vim to create and edit C++ programs

Oregon State University School of Electrical Engineering and Computer Science. CS 261 Recitation 1. Spring 2011

CS 430 Computer Architecture. C/Assembler Arithmetic and Memory Access William J. Taffe. David Patterson

Molecular Statistics Exercise 1. As was shown to you this morning, the interactive python shell can add, subtract, multiply and divide numbers.

CprE Computer Architecture and Assembly Level Programming Spring Lab-8

Setting up my Dev Environment ECS 030

CS488 2D Graphics. Luc RENAMBOT

Introduction to Computer Science Midterm 3 Fall, Points

Assignment 4. Overview. Prof. Stewart Weiss. CSci 335 Software Design and Analysis III Assignment 4

CSC 112 Lab 1: Introduction to Unix and C++ Fall 2009

Chapter 8: Implementation- Clipping and Rasterization

Assignment 3: Distance COP3330 Fall 2017

School of Informatics, University of Edinburgh

Programming. Dr Ben Dudson University of York

Part 6b: The effect of scale on raster calculations mean local relief and slope

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

= 3 + (5*4) + (1/2)*(4/2)^2.

MATH SPEAK - TO BE UNDERSTOOD AND MEMORIZED DETERMINING THE INTERSECTIONS USING THE GRAPHING CALCULATOR

Computer Graphics: 7-Polygon Rasterization, Clipping

ECE454, Fall 2014 Homework3: Dynamic Memory Allocation Assigned: Oct 9th, Due: Nov 6th, 11:59PM

(Refer Slide Time: 1:27)

Computational Modelling 102 (Scientific Programming) Tutorials

Parallel Programming Pre-Assignment. Setting up the Software Environment

Statistics & Curve Fitting Tool

Lesson 8 Introduction to Quadratic Functions

CS 101, Spring 2014 April 1st Exam 2 Question 1. [3 points] What output is printed by the following code?

PR quadtree. public class prquadtree< T extends Compare2D<? super T> > {

Part 1 (70% of grade for homework 2): MIPS Programming: Simulating a simple computer

EECS 560 Lab 6: Min 3-Heap and Performance Analysis of Operations

Function Grapher Demystified Step 2

SYSC 2006 C Winter 2012

University of Wisconsin-Madison Spring 2018 BMI/CS 776: Advanced Bioinformatics Homework #2

Project #1: Tracing, System Calls, and Processes

AP Computer Science Unit 1. Programs

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

THE DEGREE OF POLYNOMIAL CURVES WITH A FRACTAL GEOMETRIC VIEW

Programming Assignment #4 Arrays and Pointers

Image Sharpening. Practical Introduction to HPC Exercise. Instructions for Cirrus Tier-2 System

Fractals exercise. Investigating task farms and load imbalance

Ingredients of Change: Nonlinear Models

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

HPC Introductory Course - Exercises

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

A Hands-On Tutorial: RNA Sequencing Using High-Performance Computing

CSE2003: System Programming (Spring 2010) Programming Assignment #1: Adding floating-point numbers. Due: April 11, 11:59PM

Exercises: Instructions and Advice

Dr Richard Greenaway

CSCI 204 Introduction to Computer Science II

Creating a Histogram Creating a Histogram

sftp - secure file transfer program - how to transfer files to and from nrs-labs

Revising CS-M41. Oliver Kullmann Computer Science Department Swansea University. Linux Lab Swansea, December 13, 2011.

Graphing with a Graphing Calculator

CS 241 Data Organization. August 21, 2018

CS 2400 Laboratory Assignment #1: Exercises in Compilation and the UNIX Programming Environment (100 pts.)

CMSC 150 LECTURE 1 INTRODUCTION TO COURSE COMPUTER SCIENCE HELLO WORLD

CS61C : Machine Structures

G-Databar Introduction. September 2017

CS451 - Assignment 3 Perceptron Learning Algorithm

CP Lab 5: Functions, pointers, some arrays

CP Lab 5: Functions, pointers, some arrays

EECS 560 Lab 9: Leftist Heap vs Skew Heap

Functions in C C Programming and Software Tools

Project 1: Convex hulls and line segment intersection

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

cd h: mkdir -p CS101 cd CS101 curl -O unzip zipfile cd CS101_Exam4

This is a combination of a programming assignment and ungraded exercises

Working Outside the Lab

RAY-TRACING WITH UNIFORM SPATIAL DIVISION:PRACTICE

Intermediate Programming, Spring 2017*

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 3

Product Engineering Optimizer

QUIZ. What is wrong with this code that uses default arguments?

CS 361 Computer Systems Fall 2017 Homework Assignment 4 - Inter-Process Communications & I/O

Tutorial 1: Unix Basics

Computer Graphics Prof. Sukhendu Das Dept. of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 14

Systems Programming and Computer Architecture ( ) Exercise Session 01 Data Lab

Question 2. [2 points] True False By default, structures are passed-by-reference.

Session 1: Accessing MUGrid and Command Line Basics

Bitnami Apache Solr for Huawei Enterprise Cloud

CS1600 Lab Assignment 1 Spring 2016 Due: Feb. 2, 2016 POINTS: 10

Tips to Save Typing, etc.

Introduction to Algorithms and Programming I Lab. Exercises #1 Solution

Dr Richard Greenaway

To become familiar with array manipulation, searching, and sorting.

Transcription:

Prof. R. Willingale January 16, 2017 University Road Leicester LE1 7RH Telephone +44-116-252-3556 Internet http://www.star.le.ac.uk/zrw Email zrw@le.ac.uk Contents 1 Introduction 2 2 The Investigation 2 3 Instructions 5 4 Submission 9 1

Page: 2 1 Introduction The C+R programming assignment is 3 credits of the 30 credit module PA2900. All the programming skills required to carry out this assignment were covered in the 2nd year CandRprogrammingworkshop youdid during the1st term andtherprogramming workshop you did in the 1st year. Make sure that the programs you write do ALL that is specified below but don t make things unecessarily complicated. In order to do this assignment you need a machine/operating system which provides a C compliler and has R installed. Unless you have these on your personal laptop or desktop computer you will have to use the UoL IT SPECTRE system. You should log on and use SPECTRE or HPC in exactly the same way as you did in the C and R Programming workshop. This script is a pdf file and can be found at http://www.star.le.ac.uk/zrw/compshop/2nd_year_c_r_assignment.pdf or on Blackboard under PA2900: Laboratory Physics 2 We suggest you download the file to your Desktop for ease of use. 2 The Investigation The assignment comprises an investigation into the behaviour of a simple dynamical system. This task has been chosen for the following reasons. The investigation can only be done using a computer. It requires a very large number of calculations to be executed and this would be impossible to do any other way. C is an ideal language to program the behaviour of the system. Using a function written in C but calling it as a function within the R environment provides a good way of analysing the system behaviour and producing plots of the results. The system involves iteration of a simple formula which can be programmed easily and efficiently using C but is more tricky to implement efficiently using R.

Page: 3 The investigation has the potential to produce huge amounts of data which can be managed easily using C but, again, is more difficult to handle easily using just R. The computer programming required for this investigation is very similar to the methods employed in many studies involving modelling or simulation using computers. The dynamical system is defined by a non-linear 2-D mapping. x n+1 = c 0 x n (1 x n )+c 1 y n y n+1 = c 2 x n +c 3 y n (1 y n ) (1) The detailed behaviour (dynamics) of the system is controlled by the constant coefficients c 0,c 1,c 2,c 3. Westartwithapairofvalues(x 0,y 0 )andrepeatedapplicationofthemapping equations will produce vectors x 0,x 1,x 2,... and y 0,y 1,y 2,... After a few interations the values start to fall into a pattern which depends on the values of c 0,c 1,c 2,c 3. Such patterns are referred to as an orbit. We are only interested in orbits which are bounded such that 0 < x i < 1 and 0 < y i < 1. For many combinations of the coefficient values c 0,c 1,c 2,c 3 the orbit is very simple comprising a single point x 1,y 1 or a few fixed points x 1,x 2,...,y 1,y 2,... and these few points are repeated over and over. However for some coefficients the orbit is much more complicated and although bounded never seems to repeat. Because there are 4 coefficients the number of potentially interesting combinations of these coefficients is rather large. For this investigation we will restrict our range of interest to c 1 = c 2 = 0.04 and c 0 = c 3 = µ where 2.8 < µ < 3.8. There are many non-linear 2-D mappings which exhibit similar dynamical behaviour. An alternative system is defined by the following equations. x n+1 = cos(c 0 x n )+sin(c 1 y n ) y n+1 = sin(c 2 x n ) cos(c 3 y n ) (2) In this case bounded orbits are confined to 2 < x i < 2 and 2 < y i < 2 and for this mapping we will confine our interest to c 1 = c 2 = 1 and c 0 = c 3 = µ where 1 < µ < 3. If you start with some arbitary point within the required range, as specified above, it is very unlikely that this point will lie on the orbit specified by the coefficients. However after a few iterations the points will settle on to the orbit. This is why the orbits are often referred to as attractors. It is important that if we start with some arbitary point, for example (0.2,0.4) was used when testing the software for this assignment, then we

Page: 4 execute a number of iterations (100 say) to allow the transient behaviour to settle down so that x 0,y 0 lies on the attractor. This should be done automatically every time we set new values for the coefficients and start to gather data for a particular orbit. The investigation is simple. We want to find values for µ which are within the ranges quoted above but which result in complicated orbits for 2-D mapping(1) and 2-D mapping (2). There are many ways of visualising the orbits. The simplest is to plot points at positions x i,y i as iteration proceeds. This is fine providing the number of iterations is small but becomes impractical for a large number of points. A better approach is to bin the points into a 2-D histogram and then plot the histogram as an image. A very large number of points can be accumulated in the histogram without the need to keep a record of all the points in vectors x i,y i and as well as plotting the histogram we can analyse the histogram further to study the properties of the orbits. To generate a 2-D histogram we must set up an array of dimensions nx,ny which spans ranges x min < x < x max and y min < y < y max. The size of the cells will be px = (x max x min )/nx and py = (y max y min )/ny. At the start we must initialize all the array values to zero. As iteration proceeds we bin the x i,y i positions into the array. The indicies will be given by ix = (x i x min )/px and iy = (y i y min )/py. If you perform these as assignments in C where ix and iy are declared as int and the other variables are declared as double then the double precision value will be correctly rounded down to the required integer. If the histogram array is simply declared as a 1-D array with nx ny elements then the insertion index will be ii = ix + iy nx and we must increment the array value for that index, hist[ii]++. We want to find complicated orbits. An initial approach is to look at the images but this is tedious and subjective. What is required is a statistic which is a measure of the complexity. A good choice is the configurational entropy of the 2-D histogram E = log b (N) 1 N ni log b n i (3) where N is the total number of iterations (points binned into the histogram), n i are the values in the bins of the histogram and b is the base for the logarithm. When n i = 0, which is likely to be the case for a large number of bins, then we define n i log b n i = 0 rather than NaN (Not a Number) which is returned by the computer. If all the points end up in 1 bin of the histogram then E = 0 (minimum) and if all the points are distributed so that the maximum value of n i = 1 then E = log b (N) (maximum). So the most complicated orbit corresponds to the maximum entropy. Physical examples of dynamical systems usually evolve in time. For such systems their

Page: 5 behaviour can be described using equations which are similar to (1) or (2) above or by using differential equations. In such cases successive iterations correspond to increments in time, t. When we use a computer to solve differential equations we set up difference equations which approximate the differentials. In each iteration we predict the state of the sytem at time t+ t using the state at time t and the difference equations. We set the initial state of the system at t = 0 and iterate to follow the behaviour of the system as time proceeds. We can then analyse the behaviour by calculating properties and statistics from the iterates generated. This investigation gives you some experience in the computer programming required for such studies. 3 Instructions 1. Go to your home directory on Spectre and create a working directory which has a file name which includes your username. Move into the new directory to start work on the assignment. My username is zrw so for me the commands look like: $ cd $ mkdir zrw_assign $ cd zrw_assign Just replace zrw with your username! 2. Create a C source file called map funs.c and write a C function which performs both the 2-D mappings defined above. The arithmetic and results should be done in double precision. Use a prototype like the following. void mapfun(int imap, double *c, double xi, double yi, double *xo, double *yo); The arguments are intended to be: imap used to select mapping 1 or mapping 2 (use if else construct) *c a pointer to an array of 4 coefficients xi,yi the input point *xo,*yo pointers to the resulting output point Include your name and some comments in your source file so it is clear who wrote the code and what it does. 3. In the same C source file write a function which calls mapfun() above to perform the initial iterations to produce the start position x 0,y 0. Don t save the intermediate points but just return the final position. A suggested prototype is: void mapspin(int imap, double *c, int nspin, double *xo, double *yo);

Page: 6 Here nspin is the number of iterations used to allow the orbit to settle. Start with the point (0.2,0.4) or something similar. Don t forget to add comments describing what the function does. Compile and debug the two functions you have written. 4. CreateanewCsource filemap main.candwriteamain()cprogramfunctionwhich sets up the coefficents for one or other of the mappings and calls the mapspin() function to generate a start position and then has a loop which calls mapfun() to generate 1000 iterates (points). Within the loop write out the points to a tabulation file called orbit.dat. Include your name and a few comments in your source code. 5. Compile the program and functions together to produce an executable program and run it to create the orbit.dat tabulation file with 1000 samples. 6. Write a short R script in the file plot orbit.r which reads the orbit.dat tabulation file and plots out the points produced. You can use this to test the C program and functions. Make sure you put your name and comments in the R script so it is clear what the code is doing. Run the program map main for different mappings (1 or 2) and different coefficients within the ranges specifed above and use plot orbit.r to see what the orbits look like. Don t proceed to the next stage until you are satisfied that everything is working correctly. 7. You need one more C function to complete the investigation. This function generates and orbit and creates a 2-D histogram of the orbit as the iteration proceeds. The source code below is an example of such a function. /* Generate a 2-D histogram from iterates of a 2-D mapping Author R. Willingale Sept. 2013 int *imp mapping 1 or 2 double *c coefficient for mapping int *n number of iterations int *nx x dimension of histogram int *ny y dimension of histogram double *xmin minimum x for histogram double *xmax maximum x for histogram double *ymin minimum y for histogram double *ymax maximum y for histogram double *hist histogram array */ void maphist(int *imp, double *c, int *n, int *nx, int *ny, double *xmin, double *xmax, double *ymin, double *ymax, double *hist) { double xin, yin, xout, yout, px, py; int i,ix,iy; /* calculate sample sizes */ px = (*xmax- *xmin)/ *nx; py = (*ymax- *ymin)/ *ny;

Page: 7 /* initialize histogram array */ for(i=0; i< (*nx)*(*ny); i++) { hist[i]=0; } /* spin to get the start position */ mapspin(*imp, c, 100, &xin, &yin); /* loop to generates iterates */ for(i=0; i< (*n); i++) { mapfun(*imp, c,xin,yin,&xout,&yout); /* calculate indicies in 2-D histogram array */ ix = (xout- *xmin)/ px; iy = (yout- *ymin)/ py; /* check indices in range and increment histogram */ if((ix>=0)&&(ix< *nx)&&(iy>=0)&&(iy< *ny)) { hist[ix+iy*(*nx)]++; } /* set input for next iteration */ xin = xout; yin = yout; } } Copy this source code into your map funs.c file and make any modifications required so that your versions of functions mapspin() and mapfun() are compatible with this function. Study the code carefully to make sure you understand what it is doing. The variables have the same names as used in the description of the 2-D histogram given above. Notethat all the arguments are declared as pointers so that we can call the C function from within the R environment. Compile and debug this function along with the other functions in map fun.c. 8. You are now in a position to create a shareable image containing the functions which can be used by R. You do this using the following command line as described in the 2nd year C and R workshop Exercise 14. $ R CMD SHLIB map_fun.c This will create the shareable object file map fun.so which can be dynamically loaded into R. 9. Write a R script which uses the map hist() function and searches for the values of the coefficient µ which give the highest entropy orbits for mappings (1) and (2). At the start of the script you need to define the interface to the C function and load the shareable object. Here is a version of what is required. maphist<- function(imap,cof,n,nx,ny,xmin,xmax,ymin,ymax) {

Page: 8 nh<- nx*ny a<-.c("maphist", as.integer(imap), as.double(cof), as.integer(n), as.integer(nx), as.integer(ny), as.double(xmin), as.double(xmax), as.double(ymin), as.double(ymax), h = double(length=nh)) dim(a$h) <- c(nx,ny) return(a$h) } dyn.load("map_funs.so") Within the script you need to write code to do the following select mapping 1 or 2 calculate the entropy for orbits over a range of µ values find the µ value which gives the highest entropy generate a high resolution histogram using this µ value plot entropy vs. coefficient µ plot the high resolution histogram as an image In the search for the µ value which gives the highest entropy calculate orbits for 100 µ values across the the range of µ specified for each of the mappings above. For each orbit calculate 1000000 (1e6) iterations and bin into a histogram dimensions 300 by 300. When calculating the entropy use log base 2 and trap for NaN in the summation. sum(his*log2(his),na.rm=true) When generating the high resolution histogram of the maximum entropy orbit use 1000000000 (1e9) iterations and bin into a histogram 1000 by 1000. This will give you excellent resolution and sufficient statistics although it will take a few seconds to perform the calculation because you are calling the mapping function a billion times! When you plot the high resolution histogram you can use the image() R function as described in section 2.9 of the 1st year programming workshop script. It s worth spending a little time playing with the way the image is plotted so that all the detail is visible. You can change the z-mapping and the colour scheme to achieve the best results. The dynamic range of the histogram can be large so you

Page: 9 may get a better result using a logarithmic z-scaling or, for example, plotting the sqrt(hist) rather than using the linear hist values. You must include your name and suitable comments in the R script to indicate what the code is doing. 10. Use the final R script to produce pdf plot files which give: Plots of entropy vs. µ for mapping 1 and mapping 2. Make sure you include your name and the mapping number (1 or 2) in the title of each graph. Plots of the high resolution histogram of the highest entropy orbit for mapping 1 and mapping 2. Include your name, the mapping number and the µ value in the title of the plots. 4 Submission Before you submit your work make sure you have included your name in the source code files and the pdf plots. When you are happy with all the files in your user name assign working directory move to the SPECTRE parent directory (which should be your home directory on SPECTRE) and use the Linux tar command to produce a tar archive file. My user name is zrw so the commands look like: $ cd (this will move you to your home directory) $ tar -cvzf zrw_assign.tar.gz zrw_assign This will produce the file username assign.tar.gz in your home directory. The archive (a so called tar-ball) contains all the files in your assignment directory. Of course you must substitute your user name for mine! Now transfer the tar-ball file to your home directory on the UoL IT Windows system and email it to zrw@le.ac.uk as an attachment. To transfer the file on to your UoL IT Windows home directory you can use Windows Explorer. Enter the following in the address bar \\spectre2.le.ac.uk\username substituting your username. You can drag the file from the Windows Explorer window onto your Desktop.

Page: 10 If you are working away from the campus on a Windows machine you will have to use a client like WinSCP and login to the UoL IT system. If you are using a Linux machine then you can use sftp (secure file transfer protocol) or scp (secure copy) to do the copy. Alternatively you could use a client like FileZilla which uses secure copy protocol. Use can find out more details on the University help for the SPECTRE system.