16
Computer Science Class Master SMA/STEU/GC/AMASONE Lab and Homework 5 2015

Lab5

Embed Size (px)

Citation preview

Computer Science Class

Master SMA/STEU/GC/AMASONE

Lab and Homework 5

2015

General instruction for all lab

See resource Assignment in https://hippocampus.ec-nantes.fr ”Labs” section of M SMA PROLAcourse for due date and delivery.

Your work is sources answering to exercises given below. They must be provided as individualtext files following naming convention of your subject. For each exercise a table, called ’requestedinformation table’ hereafter, sets precisely what is expected in terms of naming convention, precisesorder of input data for the programs you create and output format of these programs results (seechapter 4.4 for complete explanations). You are expected to upload an archive containing all yourwork in resource Assignments of course ”Labs” section of Pedagogic server (no individual file willbe allowed)

An auto evaluation tool called auto eval.bash (see chapter 4.1, 4.2, and 4.3 for details) givenwith this document, has to be used to generate this archive. It can also be used to auto evaluateyour archive before submission and check partially correctness of your work.

The same auto evaluation tool will be used by the teachers to evaluate your work.

Failure to return the sources archive on time on the server will result in a gradeof zero for this homework.

Uploading an archive with a wrong structure or name (i.e. archive not readableor not named correctly) will result in a grade of zero for this homework.

Note : Some useful tricks are given in chapter 4.5.

1

1 Template function

In lab 1, the computation of π with a trapezoidal rule may be implemented using a rather generalfunction like it is proposed in the correction. It has been isolated in the given trapezoidal.cc andtrapezoidal.h files. In this implementation we see that trapez rule depends explicitly on unitCircle(see the given trapezoidal.cc file). We want to expand trapez rule to make it compute the trapezoidalrule of any user given function. For that you will use template programing.

1.1 Function object

A first simple solution is to add a 4th argument to the initial function to pass a function object(see course C6 slide 28). Follow the track :

1. Copy the given trapez rule in a trapTemplate.h (declaration), and trapTemplate imp.h (im-plementation).

2. Change the name of the function to trapTemplate

3. Add a 4th argument, that we can call func, to trapTemplate that will be a constant referenceto an object. This object func will be of generic type. You must transform trapTemplate intoa function template to have func generic.

4. This 4th argument object will be considerer to have at least a”double operator ()(const double &x)const”method that take a ”double” as argument and return the result of the computation of f(x).f is the function that this object represent. This is is the only requirement on generic typeof func. This kind of object are called ”function object”.

5. Use this func instance in the implementation in place of unitCircle calls. You will keep allthe algorithmic part from the original function unchanged.

6. To test the new trapTemplate template function you will first have to create in objFunc.ccand declare in objFunc.h a set of object functions representing f corresponding to :

Name of the class/struct f(x) mathematical definition

unitCircleOF 4√

1− x2lineOF xtrigoOF sin(15× x) + cos(3× x)

bilineOF

{x ifx < 0.5

1− x ifx > 0.5

7. You must then test your work with the main program given in the file test trapTemplate.cc.Whatever implementation you choose for these function and object functions, this programshould give the appropriate results without modification of test trapTemplate.cc source file.

Requested informationFiles

trapTemplate.h, trapTemplate imp.h, objFunc.h, objFunc.ccInput

Output

Scaling : 1/4

Here is the expected output :

2

Give number of interval

5

PI : 3.03705

ERRORPI : 0.0332773

LINE : 0.5

ERRORLINE : 0

TRIGO : 0.0580991

ERRORTRIGO : 0.646497

BILINE : 0.24

ERRORBILINE : 0.04

1.2 Generalisation to every arithmetic types

Imagine that we want to use another arithmetic or precision to compute the trapezoidal rule. Saysinstead of ”double” real we want to use for example the Real type (from Lab 3). Generalizationof the initial trapez rule function is now not only related to the use of any f function but also tothe use of any arithmetic. Follow the track :

1. Copy the given trapez rule in a trapTemplateGeneral.h (declaration), and trapTemplateGen-eral imp.h (implementation).

2. Change the name of the function to trapTemplateGeneral

3. Add a 4th argument, that we can call func, to trapTemplateGeneral that will be a reference toa function that takes one ”const double” reference as unique argument and returns a ”double”(see course C3 slide 14 where you can replace pointers by references). The exact syntax isthe following :”double (&func)(const double &)”Use this func variable name (representing a function) in the implementation in place ofunitCircle calls. You will keep all the algorithmic part from the original function unchanged.Note that this gives another solution than function objects and template functions to theproblem of treating any f user given function. You can do some partial tests. Normally ifyou call this new function with unitCircle (and 0.,1.,n for first 3 arguments) you should get aresult approaching π.

4. Now continue the generalization by making trapTemplateGeneral a template function on thearithmetic type used for the computation. Says your trapTemplateGeneral might be ableto integrate a function f dealing with int,float,double or . . . Modify all the implementationaccording to this new template parameter representing generic arithmetic type.

5. To test the new trapTemplateGenaral function template you will first have to create in func.ccand declare in func.h a set of function representing f corresponding to :

Name of the function f(x) mathematical definition Arithmetic

unitCircle (you can copy the version in trapezoidal.cc) 4√

1− x2 doubleline x integertrigo sin(15× x) + cos(3× x) double

biline

{x ifx < 0.5

1− x ifx > 0.5float

6. You must then test your work with the main program given in file test GtrapTemplate.cc.Proceed step by step. First comment out all the tests and includes related to other arithmeticsthan int, float and double. Test. If you are successful pass to the next step.

7. Starting from the given Starting Real1.h and Starting Real1.cc try now to compute the in-tegral of a rline function in Real arithmetic. For that use now the full original version oftest GtrapTemplate.cc. Add a function rline to func.cc and func.h that does the same asline but in Real arithmetic. Copy Starting Real1.h and Starting Real1.cc files in Real1.h andReal1.cc respectively and try to compile. If it does not compile modify class Real so that

3

it fulfills trapTemplateGeneral,rline and ’test GtrapTemplate’ requirements. Whatever imple-mentation you choose for trapTemplateGeneral function and testing functions, this programshould give the appropriate results without modification of test GtrapTemplate.cc source file.

Requested informationFiles

trapTemplateGeneral.h, trapTemplateGeneral imp.h, func.h, func.cc,Real1.cc, Real1.h

Input

Output

Scaling : 1/4

Here is the expected output :

Give number of interval

5

LINE : 0

BILINE : 0.24

ERRORBILINE : 0.04

PI : 3.03705

ERRORPI : 0.0332773

TRIGO : 0.0580991

ERRORTRIGO : 0.646497

RLINE : 0.5E40

ERRORRLINE : -0.41633363423443E-15

2 Template Class

For this exercise, you will come back to Matrix class created during the previous lab. A newimplementation design, based on the use of three member variables is now mandatory for this ex-ercise (this is somehow a kind of mixing of Vector class into Matrix class). Those three membersdefine your matrix dimension(n), structure(index ) and entries(rows). To avoid losing time on thisspecific reshaping task a header file (Matrix.h) and an implementation file (Matrix.cc) give youthe corresponding implementation. In this version the use of Vector class has been completelyremoved. The data members described above are now pointers to a standard array. Multiplicationmatrix by a vector method is now rather artificial as it takes a pointer to ”double” for right handside argument. This doesn’t give a way to check the dimension consistency between matrix andvector but simplifies the exercise (it is assumed that they are consistent). Compare to the previouslab the friend ”<<” operator is also replaced by a display function to simplify the exercise. All theother methods keep the same interface as the previous lab.

You must expand this class to make it a template class on the arithmetic your matrix workson. Up to now you could only compute matrices with entries represented as ”double”. Change theMatrix class so that it becomes a template class, in order to compute matrices with entries of anynumber type. The objective is to test the new version of Matrix class with a class Complex thatyou will have to reimplement (using files Starting Complex.cc and Starting Complex.h),and with the class Real already defined in previous work.

Follow the track :

1. Implement your template version of Matrix class. You must start from the Matrix class de-fined in Matrix.h, keeping all the interface functionalities unchanged and the number of mem-bers unchanged. Store your declaration in MatrixTemplate.h. Then starting from Matrix.cc

4

do the appropriate modifications and put your implementation in MatrixTemplate imp.h.Again you must not change the algorithms of Matrix.cc but only the necessary source partto make Matrix class template.

2. Before any attempt to use special types as template parameter, test ”double” type templateparameter and verify that the results (computed values, output format) are the same as thosegiven by non template class. For that use test MatrixTemplate D.cc and test Matrix D.ccto create programs to test the template and non template version respectively. Try yourprograms with the same input. Using the following given data, you should get :

Double arithmetic

Input dimension of Matrix A :

3

Input total number of terms of row skyline storage for upper triangle part

of A (diagonal included) :

6

Input row of A

Input number of term of 0 row :

3

Input 0 term of 0 row :

1.

Input 1 term of 0 row :

2.

Input 2 term of 0 row :

3.

Input number of term of 1 row :

2

Input 0 term of 1 row :

4.

Input 1 term of 1 row :

5.

Input number of term of 2 row :

1

Input 0 term of 2 row :

6.

i j 0 1

DAij : 2

DAji : 2

Test copy constructor.

DCopyConstructor : [ [1, 2, 3], [4, 5], [6] ]

i j 0 1

DCij : 2

DCji : 2

Input total number of terms of row skyline storage for upper triangle part

of B (diagonal included) :

4

Input row of B

Input number of term of 0 row :

1

Input 0 term of 0 row :

4.

Input number of term of 1 row :

2

Input 0 term of 1 row :

7.

Input 1 term of 1 row :

5

-5.

Input number of term of 2 row :

1

Input 0 term of 2 row :

9.

Test addition.

DAddition : [ [5, 2, 3], [11], [15] ]

Input terms of V

Input term of 0 row :

1.

Input term of 1 row :

2.

Input term of 2 row :

3.

Test matrix vector.

DMultiplication : [14, 25, 31]

3. Then try Real class type with test MatrixTemplate R.cc. Start from the version you wantbut put your work in the files Real2.cc and Real2.h. Normally, independently on how youtransform Matrix class, you should not be able to compile the program. Figure out what arethe problems, and avoid them by modifing Real class so that function member of templateclass Matrix “works” without algorithmic modifications. If you don’t modify Real class andyou pass the compilation stage successfully, it means that you changed too much the initialMatrix class. It certainly won’t do things the way the initial template free class Matrix did.Please revert to the initial class and start again from this point.

Using test MatrixTemplate R.cc with the given data, you should get the following output :

Real arithmetic

Input dimension of Matrix A :

3

Input total number of terms of row skyline storage for upper triangle part

of A (diagonal included) :

6

Input row of A

Input number of term of 0 row :

3

Input 0 term of 0 row :

1.e+300

Input 1 term of 0 row :

2.e+300

Input 2 term of 0 row :

3.e+300

Input number of term of 1 row :

2

Input 0 term of 1 row :

4.e+300

Input 1 term of 1 row :

5.e+300

Input number of term of 2 row :

1

Input 0 term of 2 row :

6.e+300

i j 0 1

RAij : 0.2E301

RAji : 0.2E301

Test copy constructor.

6

RCopyConstructor : [ [0.1E301, 0.2E301, 0.3E301], [0.4E301, 0.5E301], [0.6E301] ]

i j 0 1

RCij : 0.2E301

RCji : 0.2E301

Input total number of terms of row skyline storage for upper triangle part

of B (diagonal included) :

4

Input row of B

Input number of term of 0 row :

1

Input 0 term of 0 row :

4.e+300

Input number of term of 1 row :

2

Input 0 term of 1 row :

7.e+300

Input 1 term of 1 row :

-5.e+300

Input number of term of 2 row :

1

Input 0 term of 2 row :

9.e+300

Test addition.

RAddition : [ [0.5E301, 0.2E301, 0.3E301], [0.11E302], [0.15E302] ]

Input terms of V

Input term of 0 row :

1.e+300

Input term of 1 row :

2.e+300

Input term of 2 row :

3.e+300

Test matrix vector.

RMultiplication : [0.14E602, 0.25E602, 0.31E602]

4. Finally, try Complex class type with test MatrixTemplate C.cc. Start by renaming Start-ing Complex.cc and Starting Complex.h in Complex.cc and Complex.h respectively. You willthen have to analyze, and modify this proposed Complex class to make it work with yourtemplate Matrix class.

Note that ”>>” input operator is not implemented in given files. You will have to implementit by saying that an input of a Complex instance corresponds to two inputs of two real ”double”.

Using test MatixTemplate C.cc with the given data, you should get the following output :

Complex arithmetic

Input dimension of Matrix A :

3

Input total number of terms of row skyline storage for upper triangle part

of A (diagonal included) :

6

Input row of A

Input number of term of 0 row :

3

Input 0 term of 0 row :

1. 0.

Input 1 term of 0 row :

7

2. 1.

Input 2 term of 0 row :

3. 2.

Input number of term of 1 row :

2

Input 0 term of 1 row :

4. 3.

Input 1 term of 1 row :

5. 4.

Input number of term of 2 row :

1

Input 0 term of 2 row :

6. 5.

i j 0 1

CAij : (2,1i)

CAji : (2,1i)

Test copy constructor.

CCopyConstructor : [ [(1,0i), (2,1i), (3,2i)], [(4,3i), (5,4i)], [(6,5i)] ]

i j 0 1

CCij : (2,1i)

CCji : (2,1i)

Input total number of terms of row skyline storage for upper triangle part

of B (diagonal included) :

4

Input row of B

Input number of term of 0 row :

1

Input 0 term of 0 row :

4. 1.

Input number of term of 1 row :

2

Input 0 term of 1 row :

7. 2.

Input 1 term of 1 row :

-5. -4.

Input number of term of 2 row :

1

Input 0 term of 2 row :

9. 8.

Test addition.

CAddition : [ [(5,1i), (2,1i), (3,2i)], [(11,5i)], [(15,13i)] ]

Input terms of V

Input term of 0 row :

1. -1.

Input term of 1 row :

2. -2.

Input term of 2 row :

3. -3.

Test matrix vector.

CMultiplication : [(22,-6i), (44,-6i), (56,-6i)]

At the end, with MatrixTemplate.h, and MatrixTemplate imp.h files (where respectively youdeclare and implement template version of the class Matrix), whatever implementation you chose,’test MatrixTemplate D ’, ’test MatrixTemplate R’ and ’test MatrixTemplate C ’ programs shouldgive the appropriate results without modification of test MatrixTemplate D.cc, test MatrixTemplate R.ccand test MatrixTemplate C.cc source files.

8

Requested informationFiles

MatrixTemplate.h, MatrixTemplate imp.h, Complex.h, Complex.cc,Real2.h, Real2.cc

Input

Output

Scaling : 2/5

3 STL

Based on the previous exercise, and the implementation of class Matrix given in MatrixSTL.ccand MatrixSTL.h, create a new template version of class Matrix, with appropriate combinationof STL containers as your unique member data for matrix entries (of any kind) in skyline storage.

Starting from MatrixSTL.h, only generate the interface (i.e. the declaration in MatrixTem-plateSTL.h header) that looks the more logical to you. To simplify the correction use T for thetemplate parameter name and stick to MatrixSTL.h declaration for unchanged instruction.

Requested informationFiles

MatrixTemplateSTL.hInput

Output

Scaling : 1/10

Optional :

For those who wish to verify their choice, do the implementation part in MatrixTemplat-eSTL imp.h. Then by just including MatrixTemplateSTL.h in place of MatrixTemplate.h intest MatrixTemplate D.cc, test MatrixTemplate R.cc or test MatrixTemplate C.cc you can verifythat you get the same results as exercise 2 This illustrates the fact that only the public interfacecounts for a user. The implementation is hidden and your main ”doesn’t care” that Matrix classuses STL or anything else.

4 Annexe

4.1 Auto eval.bash limits

This tool is just a help to verify mainly that:

• Your program is located in correct source files having correct names

• No file is missing. If so you will be able to pass through all steps but your points for themissing file will be lost.

• Exercises program at least compiles and runs correctly (to obtain the 2 points see 4.2 ).

• With the student parameter setting it gives correct results(to obtain the 6 points see 4.2 ).

• The archive given to teacher has the correct structure and name.

9

What this tool doesn’t verify is that:

• Your programs are correct in absolute. Be careful auto eval.bash is tuned to have exercisesrunning with a set of parameter but different setting will be used by the teacher to correct yourwork. This means that your code may work with auto eval.bash and the student parametersetting but not with the teacher parameter setting. It’s your responsibility to ensure thatyour program is correct and work with any setting.

• Your programs are correct if you just generate an archive and didn’t pass through evaluationstep.

• You give your correct group identification number. If you generated archive following a wronggroup ID and upload it as is you will have grade of zero for this homework.

4.2 Evaluation rule

The auto evaluation tool auto eval.bash will be used by teachers (in a slightly modified version)to evaluate your work with the following rule:

• For an exercise the mandatory program doesn’t compile => 0 Points for the exercise.

• For an exercise the mandatory program compiles but doesn’t execute correctly (i.e. crash,stopin the middle ...) => 1 Points

• For an exercise the mandatory program compiles and executes without bug but doesn’t givecorrect results => 2 Points

• For an exercise the mandatory program compiles, executes without bug and gives correctresults/behavior => 6 Points

Naturally when you are in position of having only 1 or 2 points, program will be inspected to seeif it is relevant (answering the question). If not (something that as nothing to do with the exercisebut compiles and runs correctly) => 0 points.

For every exercise an extra scaling is done. After each requested information table (see 4.4)you will have the coefficient used for this scaling.

By using auto eval.bash you will be able to estimate how many source evaluation points youwill have for this lab without scaling.

4.3 Getting and using auto eval.bash

auto eval.bash like this pdf files come from self extracting file labX.bash that you download fromresource ”Lx subject” in https://hippocampus.ec-nantes.fr ”Labs” section of M SMA PROLAcourse, where X correspond to current lab number.

Place auto eval.bash in the folder where you have all exercises source that have to be given toteachers. Then in this folder just type:

· · ·> ./auto eval.bash

The first step is to input your group ID (letter A or B and a number):

Input your group letter and number

10

If you launch the script for the first time, you have to create an archive of your work. Select”Prepare an archive of your work”.

Create archive

A .gz archive file is created, and ready to be uploaded on the pedagogic server. If you want, atthis point you can stop the program (Type ”q”). Note that theses two steps at least are mandatoryto create the archive of your work that you will upload on the server. You can create this archiveby yourself (for instance using the tar command), but if there is any kind of problem when wetry to uncompress it, your grade may be affected with no protestation possible (the most stupidproblem would be that your archive doesn’t have the correct name which leads to ... zero for thewall lab evaluation) .

Otherwise, you can use this tool to get an auto-evaluation of your work. Now that your archiveis created, you can notice that a new command appeared, ”evaluate archive already generated”.Type ”b”.

Auto-evaluate your work

Some information are displayed on the screen, saying that the auto-evaluation worked throughwell (or not). The most interesting information for you are the ones on the next screen-shot.

11

Results of your auto-evaluation

Here you can see:

• Which ones of your source codes compile correctly

• Which ones of your programs run correctly

• Which ones of your programs give the expected results

This way you can have an estimation of your grade according to the rules detailed in section4.2. However keep in mind that the grade estimated using this tool may not be your definitivegrade (see section 4.1).Note that you can use this command only if you have generated an archivefirst.

You could see that in the previous example, one of the results given by program ”ex1” isincorrect. To display the difference between your results and the expected one, select the newcommand ”display difference from solution of last generated archive” by typing ”c”.

12

Compare obtained results and expected results

Now you can:

• Generate a new archive of your work, if you modified some of your source files

• Auto-evaluate the current archive

• Compare the results obtained with your program and the solution

• Stop using the program

In the last case, if you decide to quit the program, you will be asked whether you want to cleanor save a certain temporary folder. This temporary folder was generated during the auto-evaluationstep, and can eventually be used for debugging even if the script is not launched. The ones of youwho are the most at ease with programming may want to use it, otherwise you can just delete it.

Stop the auto-evaluation program

13

4.4 Requested information

Table given at the end of each exercise untitled ’Requested information’ contains the followingitems:

• Files: This is the list of files which must be present in your archive uploaded in the server.auto eval.bash harvest this files to generate the mandatory archive.

• Input: This describes for each program the precise order in which informations must beentered.

• Output: This describes for each program the output format of results. Results (thatteacher want to check easily) must be presented by your program in a ratherrigid format described by followings:

– A result is present on one single line. No other things may be written on that line.

– A result is first identified by a token which starts the line.

– After the token a ’:’ must separate token from result value.

– After ’:’ result value must be written (it could be anything).

– token, ’:’ and result value must be separated at least by one blank character.

In this section you have the list of mandatory results given by token names and in parenthesesby result name coming from subject.

Here is an example of a ’Lame’ program made of one file lame.cc. It is generating 2 outputresults called λ and µ in the subject. From subject this program should ask for 2 input values callE and ν to compute results. The requested informations table would look like

Requested informationFiles

lam.ccInput

ν then EOutput

MU(µ), LAMBDA(λ)

Scaling : 1/8

’Lame’ program execution would look like with E = 2500., ν = 0.28 and computed µ = 976.5625and λ = 1242.8977 :

blablabla

please enter nu :

0.28

blabla

please enter E :

2500.

LAMBDA : 1242.8977

blabla

MU : 976.5625

blabla

Notice in this example that ν is asked before E as mandatory by ”Input” directive. And λ andµ appears in undefined order but with mandatory format (i.e token LAMBDA and MU).

Very important. You should avoid at any cost the use of token for anything else than theresult it corresponds. Consequences may result in a zero grade just because you messed up thetools with false information.

In example above if in any ’blabla’ you write MU or LAMBDA you will get a zero for associatedresults.

Last but not least when you enter information and output first a question message

14

you must always add a new line to your question if it precedes a result. Let’s takethe example of ’Lame’ above which output token ’LAMBDA’ right after asking to input E. Ifyou don’t follow this last recommendation you may ask for E without inserting new line after thequestion as you can see in the example below:

Your executable is Lame and on terminal you type:· · ·> ./Lame

And obtain the following bunch of output:

blabla

please enter E : 2500.

LAMBDA : 1242.8977

blabla

This works well on the terminal by typing on the keyboard 2500. and ’enter’. But auto eval.bashworks differently. It uses what is called redirection mechanisms. And in fact this leadsauto eval.bash to miss recognize your results.

In this example you must add a ’end of line’ after the question to obtain:· · ·> ./Lame

blabla

please enter E :

2500.

LAMBDA : 1242.8977

blabla

and auto eval.bash will work correctly in this case.

4.5 Useful

During Labs you will have questions where testing program ask for many inputs. During debuggingstage you may then be obliged to re enter those inputs manually many times. That may be errorprone and time consuming. To simplify your work use redirection.

For example lets take a ’prg ’ program which run the following :· · ·> prg

Enter number :

23

Enter number :

13

Enter number :

-1

Mean value :

18

Here for illustration we just limit inputs to three entries. Put all those inputs in a file, with oneinput per line. Lets call this file ”ip.txt”. Its contain for this example will be :

23

13

-1

Now if you type the following command you get the same execution of ’prg ’ without typinganything :

· · ·> prg < ip.txt

Enter number :

Enter number :

Enter number :

Mean value :

18

Note that inputs just vanish from terminal display.

15