sSeptember 13, 2018 (commands,
cd=change directory to
pwd=print working directory
cmsenv=set up CMS environment
ls= lists files in the directory
ls -l=lists one file per line
ls --help=lists information about the files
mkdir=make a directory
hitting the up arrow goes to commands i typed
.txt=text files
.sh or .csh=linux scripts
.x or .exe=executable, compiled code ready to be run
touch=creates new empty files
rm= REMOVES FILE
HOMEWORK for 9/17
1. The touch command creates the new empty files that we named after typing touch
2. The "find . " command. Something after find tells the find which path to take when finding, and the . is the current working directory. So "find . " means we look for something in the current directory
3. The * lets us find all the files in the directory that contain the keyword or letter typed next to it. The * is like a placeholder for the other part of the name of the file. So looking for file1 and file2 we'd type "file*" because the 1 and 2 come after the part of the file. However, looking for test1 and file1, we'd type "*1" becuase the test and file come before the 1.
4. rm removes the files that you name after the command. rm removing files is the default. rmdir removes a directory.
5. The rm makes the data in a file no longer link-able to the filename. So the data doesn't disappear, you just can't get to it anymore, which isn't very useful. You can't undo an rm command.
6. The > made it so that we could get the output of text2 if we input log.txt. "text2" > log.txt made it so that log.txt input was redirected as text2 output. The >> made it so that we could get the output of everything that we'd already put to ""log.txt." So now, when we type log.txt we get test2 and test3 back. If we'd only put the one >, test3 would've been the only thing we got back; the >> keeps it from replaing the other thing we'd assigned log.txt to.
7. The > operator means we get rid of anything that we'd previously assigned to the log.txt
8. I expect to see the files in this directory listed out in descending alphabetical order when i type ls -l > log.txt, and then type cat log.txt.
9. Ten commands:
1. uname -a: prints detailed information about the operating system, machine name, and kernel
- kernel = original distribution
2. # find ~ -empty: finds empty files
-Didn't come up with anything, so I had no empty files
3. sort: I used sort log.txt to sort the files that were assigned to be output when I input "log.txt"
4. ls -ltr: lists stuff based on how recently it was modified (stuff at the bottom was most recently modified)
5. gz: creates a .gz zip file. This helps compress a file for storage reasons.
6. gzip -d log.txt.gz: unzips a zip file so we can see it and work with it again.
7. ps -ef more: lets us see all current running processes so we know what's going on with the system at that moment
8. rm -i: asks for confirmation before you remove a file. If you're very accident-prone (like me) this is extremely helpful in making sure you don't remove something important
9. cp -p: copies one file into/over another
10. whatis: tells you what a command does. Very useful if you don't know much about linux or you want to experiment with making your own code and check what a command does.
HW 3
ARG is like x. We can assign it to values of inputs so that we call it, we actually get something we can work with.
find with a . means we'll be looking for something in our current directory, which is a heck of a lot faster than sorting through extraneous stuff.
find / -name"*$ARG*"
/ is directory path where you're searchign for the file
-name gives option to set the name of the file
"*ARG*"
* at end means any file name that starts with this set value
tcsh./testscript.tcsh<argument>
Replace <argument> with something like "cms" or whatever. This is consider our first input, and since we set ARG=$1 (first input; $2 would be second input, etc), this first input will be echoed back at us. The script is a search script because it looks for all files and directory paths that contain the word we typed.
chmod stands for "change mode"; changes the permissions of files or directories
Home directory is the thing that first appears on screen when I open the terminal, so its the ~
This script redirects what would show up on the terminal screen when searching for testfile into the homesearch.txt text file that we created.
Piping: send output of one program to another program so it can be processed further. A pipe is a form of redirection; this redirection transfers standard output (output from the command line) to another program like a file or printer instead of the display monitor. Pipes create temporary direct connections between multiple programs to perform very specialized tasks that one of those programs could not do alone.
sed -i -e 's/one/two/g' test.txt
searches the word "one" everywhere in the file test.txt and replaces it with the word "two."
.. and ../ means go back one folder
. and ./ means in current folder
rwx, read write execute
touch creates new empty files
HW4
cpp = c++
main.cpp is where we write the code using ASCII symbols
main.cpp code:
#include <iostream>
using namespace std;
int main() {
cout <<"Hello World!" << endl; //Print hello world to screen followed by end line (endl)
return 0; //Exit the program
}
Exit emacs, do g++ main.cpp
do: ./a.out
Use "compiler" to translate this from ASCII codes for letters into assembler language, d translation using g++ command
compiler is g++ (g is for Gnu, the free software foundation)
iostream=in and out stream
Make an executable (the a.out), a list of commands in the computer's native language
int main tells compiler where first line of code is
"cout" uses a command that is in "iostream" group of codes (from first line); it sends text to the terminal
The Linux header files are all of the .h files that contain the functions that the Linux kernel provides that can be called from other programs
The second cpp I write is called: second.cpp
Code:
#include <iostream>
using namespace std;
int main() {
cout << "hello world" << endl;
int i=2;
cout << "i = " <<i<<endl;
double a=3.3;
cout << "a = " <<a<<endl;
int j = a*i;
cout << "a*i = "<<j<<endl;
return 0;
}
a*i = 6
The third cpp I write is called: third.cpp
Code:
#include <iostream>
using namespace std;
int main() {
int n=10;
cout << "n is "<<n<<endl;
n--;
cout<<"n is now "<<n<<endl;
n++;
cout<<"n is now "<<n<<endl;
return 0;
}
n started as the integer 10 (which we told it to with int n=10) then became 9, then became 10 again
So -- subtracted 1 from n, and ++ added 1 to n
non-numeric variables 1
my fourth cpp file is called fourth.cpp
#include <iostream>
using namespace std;
int main() {
bool prop;
prop = (5>1);
cout<<"prop is "<<prop<<endl;
prop = (1>5);
cout<<"prop is "<<prop<<endl;
prop = (1 != 5);
cout << "prop is " <<prop<<endl;
return 0;
}
5 > 1 is a true statement, so the code tells us this property is true by spitting out a 1. 1 also does not equal, so the computer also spits out a 1 to tell us that is a true statement that we typed.
The middle property, 1>5 is obviously not true, and the code tells us this by spitting out a 0, meaning false.
LOOPS
my first loop cpp file is called loop1.cpp
#include <iostream>
using namespace std;
int main() {
int n=10;
while(n>0) {
cout<<"n is "<<n<<endl;
n--;
}
return 0;
}
We use while loops to repeat an action for as long as the certain condition is met. In this case we start with n=10. Then as long as n>0, we subtract 1 from n each loop (n--)
my second loop cpp file is called loop2.cpp
#include <iostream>
using namespace std;
int main() {
int n=10;
// when we declare a for loop, we also initialize the loop \
variable,
// specify the exit condition, and tell the program how to \
modify the
// loop variable at the end of each loop
for (n>0; n--;) {
cout<<"n is "<<n<<endl;
}
// in a for loop, the loop variable (in this case, 'n') onl\
y exists in
// the loop. we are not able to call 'n' from out here
// uncomment the following line and see for yourself
cout<<"n outside the loop: "<<n;
return 0;
}
You need int n=10 to be defined outside of the loop. need a ; before the ) in the for loop.
This loop subtracts 1 from 10 for ns that are greater than 0, and keeps going. Then it tells us the n outside the loop, meaning when n=0, that they subtract 1 and it becomes -1.
my third loop cpp file is called loop3.cpp
#include <iostream>
using namespace std;
int main() {
int n=0, m=0;
for (n<10; n++;); {
cout << "n is " << n <<": ";
m=0;
for (m<=n; m++;) {
cout << m;
}
cout << endl;
}
return 0;
}
N and m start at 0. While n is less than 10, we add one to n. Nested inside of that loop, we have that as long as m is less than or equal to n, we add one to m. So we started with both n and m equal to 0. Before the outer loop can progress, the inner loop has to do its thing (its thing=adding one to m as long as m is less than or equal to n). So because we start with n=m=0, we add one to m, then add one to n. Now n=m=1, so we do this again, getting n=m=2. We keep doing this over and over until we get n=m=10, since we told the loop to stop adding one to n once it hit 10.
HW5
First logic cpp file called logic1.cpp
#include <iostream>
using namespace std;
int main() {
int n = 10;
while (n>=10) {
if(n>5) {
cout<<"n is "<<n<<endl;
}
else {
cout<<"n = "<<n<<endl;
n--;
}
return 0;
}
}
Logic commands work when some condition is satisfied. We set n equal to 10. While n is greater than or equal to 10, as long as n is greater than 5 (which it is), we spit out the statement "n is (whatever value, in this case 10). Otherwise, we'd say what n= and then subtract 1 from n. However, because n already =10, we just say n=10.
If ( )
Then ( )
While.....
(.....)
First pointer cpp file called pointer1.cpp
#include <iostream>
using namespace std;
int main() {
int i = 10;
//picks out an empty "mailbox" to store data in//
cout << "The memory address of i is " << &i << "\n";
//prints out the memory address//
cout << "The data stored at memory address " << &i << " is " << i << "\n";
// tells us what data we had stored at that memory address//
int* p = &i;
//codes the pointer, sets it equal to the address of another variable//
cout << "The value of p is " << p << "\n";
//gives us p's value, which is i
cout << "We say that p 'points at' the memory location referenced by address " << p << "\n";
//gives address//
cout << "The data stored at memory address " << p << " is " << *p << "\n";
//gives the data, which is 10//
return 0;
}
//in this program, p was just another of referring to i, but pointers have other uses//
(Rewriting analogy so it sticks in my head):
mailboxes
int i=10. i is out empty mailbox. It can store integers (int). We give it the integer 10 (data) to put into the mailbox i.
The mailbox has a number that the computer can reference to find it. This number is the memory address.
Here's how we find the memory address and access that data:
cout << “The memory address of i is “ << &i;
//prints the memory address on the screen//
cout << “The data stored at memory address “ << &i << “ is “ << i;
//tells us what data we had stored at that memory address//
Program 1 is called program1.cpp
#include <iostream>
using namespace std;
int main(){
int i = 10;
int j = i;
//set the mailbox and i, stores 10 in it, puts j's contents equal to i's contents//
cout << "i= " << i << " and j= " << j << "\n";
//outputs i=10 and j=10//
i=5;
cout << "i= " << i << " and j= " << j << "\n";
//outputs i=5 and j=10; we changed i's contents, but we didn't change j's, so j still outputs 10//
j=1;
cout << "i= " << i << " and j= " << j << "\n";
//outputs i=5 and j=1; we changed j's contents, but i's contents are still 5 //
return 0;
}
Program 2 is called program2.cpp
#include <iostream>
using namespace std;
int main(){
int i = 10;
int* p = &i;
cout << "i= " << i << " and *p= " << *p << "\n";
//p is a pointer, and whenever we change i, p will change/, because there is only one mailbox/
i=5;
cout << "i= " << i << " and *p= " << *p << "\n";
//p and i are both 5 now//
*p=1;
cout << "i= " << i << " and *p= " << *p << "\n";
//p and i are both 1 now//
return 0;
}
My first new pointer program is called newpointer1.cpp
#include <iostream>
using namespace std;
int main(){
int* p = new int(5);
//makes program find a new empty memory location, stores the value 5 there//
cout << "p points at address " << p << "\n";
cout << "The data stored in address " << p << " is " << *p << "\n";
//gives us address of p and data stored there//
*p = 10;
cout << "Now the data stored in address " << p << " is " << *p << "\n";
//changes the data stored to =10, and gives the new address//
return 0;
}
My new second pointer program is called newpointer2.cpp
#include <iostream>
using namespace std;emacs -nw newpo
int main(){
int* p1 = new int(3.14);
int* p2 = *p1;
cout << "p1 points at address " << p1 << "\n";
cout << "The data stored in address " << p1 << " is " << *p1 << "\n";
cout << "p2 points at address " << p2 << "\n";
cout << "The data stored in address " << p2 << " is " << *p2 << "\n";
*p1 = 2*(*p2);
cout << "Now the data stored in address " << p1 << " is " << *p1 << "\n";
cout << "Now the data stored in address " << p2 << " is " << *p2 << "\n";
return 0;
}
Small program containing if and while loop called:
ifandwhileloop.cpp
#include <iostream>
using namespace std;
int main() {
int n = 0;
while (n<=0) {
if(n<5) {
cout<<"While n is greater than or equal to 0, if it is less than 5, \
then we print n's value"<<endl;
cout<<"n is "<<n<<endl;
}
else {
cout<<"If n is anything but less than 5 (so greater than or equal to\
5, then we add one to n"<<endl;
cout<<"n = "<<n<<endl;
n++;
}
return 0;
}
Files updated in current month program called:
updatedfiles1.tcsh
#!/bin/tcsh
set month = `date | awk '{print $2}'`
//set month to current one//
echo $month
ls -lat | grep "$month"
Prints a list f all files updated this month
HW6
Data arrays
List, vectors
Define a set of things
Arrays/vectors start at 0, n0
[x, y, z]
[n0, n1, n2]
grep= command; get something for me
#include <iostream>
using namespace std;
int main() {
//a loop to demonstrate 1D arrays//
int ii[3] = {1,2,3};
int j=0;
while (j<3) {
cout <<" ii of "<<j<<" is "<<ii[j]<<endl;
//Starts with j=0, print first element of ii (which is 1). Then because we add 1 to j, we print 1st element of ii (which is 2); etc//
j++;
//Add one to j as long as its below 3, so we'll go through j=0,1,2//
}
//a loop to demonstrate 2D arrays//
int LL[2][3] = {1,2,3,4,5,6};
j=0;
int k;
while (j<2) {
k=0;
//don't forget to initialize k//
while (k<3) {
cout<<" LL of "<<j<<" "<<k<<" is "<<LL[j][k]<<endl;
k++;
}
j++;
}
return 0;
}
readdata.cpp
#include <iostream>
//need to read and write standard input/output streams//
#include <fstream>
//has capabilities of ofstream and ifstream, create, write information to,\
and read information from files//
using namespace std;
int main() {
ofstream myfile;
//represents output file stream and is used to create and write info to \
files//
myfile.open("example.txt");
//creates this new file//
myfile<<"write some junk.";
//inserts this sentence into it//
myfile.close();
//closes file so we can use stream for other things//
return 0;
}
hw6main.cpp
/* MAIN.CPP */
#include <iostream>
#include <fstream>
// include the program dotprod1.cpp so that we can find the dot_prod function
#include "dotprod1.cpp"
using namespace std;
int main () {
// declare the vectors
double vector1[3];
double vector2[3];
// open the input file
ifstream infile;
infile.open("vectors.txt");
// store the input in the vectors and print the vectors for the user
infile>>vector1[0]>>vector1[1]>>vector1[2];
cout<<" Vector 1 is ("<<vector1[0]<<","<<vector1[1]<<","<<vector1[2]<<")"<<endl;
infile>>vector2[0]>>vector2[1]>>vector2[2];
cout<<" Vector 2 is ("<<vector2[0]<<","<<vector2[1]<<","<<vector2[2]<<")"<<endl;
// close the input file
infile.close();
// call the dot_prod function from dotprod1.cpp
dot_prod(vector1,vector2);
return 0;
}
dotprod1.cpp
/* DOTPROD.CPP */
#include <iostream>
using namespace std;
double dot_prod(double v1[3],double v2[3]) {
double dotdot;
dotdot = v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2];
//defines dotdot function, definition of a dot product//
cout<<" The dot product is "<<dotdot<<endl;
//tells us the dotproduct is whatever the result of running dotdot is//
return 0;
}
vectors.txt
1 2 3
4 5 6
7
//two vectors and a scalar//
Initial output from this (before scalar):
Vector 1 is (1,2,3)
Vector 2 is (4,5,6)
The dot product is 32
hw6main.cpp with scalar
/* MAIN.CPP */
* MAIN.CPP */
#include <iostream>
#include <fstream>
// include the program dotprod1.cpp so that we can find the dot_prod funct\
ion
#include "dotprod1.cpp"
#include "scalarmult.cpp"
using namespace std;
int main () {
// declare the vectors and scalar \
double vector1[3];
double vector2[3];
double scalar1[1];
// open the input file \
ifstream infile;
infile.open("vectors.txt");
// store the input in the vectors and print the vectors for the user \
infile>>vector1[0]>>vector1[1]>>vector1[2];
cout<<" Vector 1 is ("<<vector1[0]<<","<<vector1[1]<<","<<vector1[2]<<")\
"<<endl;
infile>>vector2[0]>>vector2[1]>>vector2[2];
cout<<" Vector 2 is ("<<vector2[0]<<","<<vector2[1]<<","<<vector2[2]<<")\
"<<endl;
// close the input file \
infile.close();
// call the dot_prod function from dotprod1.cpp \
dot_prod(vector1,vector2);
scalar_mult(scalar1,vector1);
scalar_mult(scalar1,vector2);
return 0;
}
scalarmult.cpp
* SCALARMULT.CPP */
#include <iostream>
using namespace std;
double scalar_mult(double v1[3],double s1) {
//perform scalar mult on a vector and scalar//
double scalarmult[3];
//make scalarmult a three-element vector//
scalarmult[0] = v1[0]*s1;
scalarmult[1] = v1[1]*s1;
scalarmult[2] = v1[2]*s1;
//define each element of scalarmult as the scalar value times each respective element of the input vector//
cout<<" The scalar multiple is ("<<scalarmult[0]<<","<<scalarmult[1]<<","<<scalarmult[2]<<")"<<endl;
return 0;
}
Random number generator
#include <iostream>
#include <math.h>
using namespace std;
// this function is the actual random number generator
// this code is stolen from the book numerical recipes for fortran
// it relies on random generated from overflow of memory locations
// and is a pseudo random number generator
const int a = 7141;
//creates constant integer a//
const int c = 54773;
//creates constant integer c//
const int mmod=256200;
//creates constant integer mmod//
double getFlatRandom(int& inew) {
//the function gets a random integer, and then it can get a new one//
double mranflat = 0.;
//sets mranflat to be 0//
inew = inew%mmod;
//% is modulus, sets the remainder to inew//
double aa = double(inew)/double(mmod);
//aa is inew divided by mmod//
mranflat=aa;
//sets mranflat equal to aa//
inew = a*inew+c;
//sets inew to a times the old inew plus c//
return mranflat;
//gives us mranflat value//
}
// in this code, we will call the pseudo-random number generator and learn some things
// about its properties by filling and then displaying a histogram
int main() {
int num;
cout << "Enter the number of loop iterations: ";
cin >> num;
int inew = 2345; // This is the "seed" for the random number generator
// we will put the results from the call into a histogram that we can look at, to learn some of its
// properties. This histogram has 10 bins.
int histo[10] = {0,0,0,0,0,0,0,0,0,0};
double atmp; //
// call the random number generator 1000 times and fill a histogram
for (int i = 0; i<num; i++){
atmp=getFlatRandom(inew); // call the random number generator
histo[int(atmp*10)]++; // increment the histogram bin the number falls within
if(i<10)
//this statment is for first ten times we select a random number//
cout <<int(atmp*10)<<endl;
//spits out the number that was randomly selected//
}
// print the histogram to the screen
for (int i = 0; i<10; i++){
cout<<i<<": ";
for (int j=0; j<int((double(100*histo[i])/double(num))+0.5); j++) {
cout << "=";
}
cout << endl;
}
return 0;
}
0: ====================
1: ==========
2:
3:
4: ==========
5: ====================
6: ==============================
7: ==========
8:
9:
Remove the and:
Enter the number of loop iterations: 10
0: ====================================================================================================
1:
2:
3:
4:
5:
6:
7:
8:
9:
I get the same value of 0 for each iteration, meaning we definitely need the & symbol
First ten numbers (did this a few times with different number of iterations each time)
Enter the number of loop iterations: 100
0
5
1
5
6
6
7
0
6
4
0: ============
1: ==========
2: =======
3: =============
4: =======
5: ==========
6: ===============
7: =========
8: ======
9: ===========
Enter the number of loop iterations: 1000
0
5
1
5
6
6
7
0
6
4
0: ==========
1: ==========
2: =========
3: ==========
4: ==========
5: ==========
6: ===========
7: ==========
8: ==========
9: ==========
Enter the number of loop iterations: 1000
0
5
1
5
6
6
7
0
6
4
0: ==========
1: ==========
2: =========
3: ==========
4: ==========
5: ==========
6: ===========
7: ==========
8: ==========
9: ==========
Enter the number of loop iterations: 1000
0
5
1
5
6
6
7
0
6
4
0: ==========
1: ==========
2: =========
3: ==========
4: ==========
5: ==========
6: ===========
7: ==========
8: ==========
9: ==========
Enter the number of loop iterations: 10000
0
5
1
5
6
6
7
0
6
4
0: ==========
1: ==========
2: ==========
3: ==========
4: ==========
5: ==========
6: ==========
7: ==========
8: ==========
9: ==========
When we run more iterations, the histogram is more uniform. When we run the same amount of iterations (like I did with the 1000), we get the same histogram each time, meaning its pseudo-random and not actually random.
srand.cpp
#include <stdio.h>
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include <iostream> //not included in hw instructions, but needed to get cout to work//
using namespace std;
int main(){
cout << "Random Number" << rand()%100; /* This will print a random numbe\
r between [0,100). */
return 0;
}
Output: Random Number83
The random number was 83. It says this each time I run the file.
Definition of Object Oriented Program:(via Google)
Object-oriented programming (OOP) is a programming language model organized around objects rather than "actions" and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data.
secretparameters.txt
91. 15. 0.005
resolutions.C (have to make this file ourselves)
#include "Riostream.h"
#include <iostream>
#include <fstream>
/*
some code to help us understand why and how resolutions affect our ability to measure the
mass of a particle
*/
// main routine
void resolutions(){
// set debug mode
bool idebug=0;
// set up the display
gROOT->Reset();
gROOT->SetStyle("Plain");
gStyle->SetOptStat(0);
gStyle->SetOptFit(11);
gStyle->SetErrorX(0);
c1 = new TCanvas("c1","Our data",200,10,700,500);
c1->SetFillColor(0);
c1->SetBorderMode(0);
c1->SetBorderSize(1);
c1->SetFrameBorderMode(0);
// book some histograms
TH1F *histo1 = new TH1F("histo1","mass",1000,0.,200.);
// setup random number generator
gRandom->SetSeed();
// get the secret parameters
ifstream myfile;
myfile.open("secretparameters.txt");
double mass, resE, resA;
myfile>>mass>>resE>>resA;
myfile.close();
// make N bosons at rest
// each boson will decay to 2 back-to-back daughter particles
// they will be back-to-back by conservation of momentum, since the momentum of the mother was zero
// assume that the mass of the daughter particles is small compared to the mother mass so we can
// assume that their energy will be large compared to their mass and we can treat them as massless.
// and thus their energy is equal to the magnitude of their momenta
// by conservations of energy, their energy
// work in 2D. Can always choose my coordinate system so that the 2 daughters are in the same plane
int N=1;
double etrue1,etrue2,phitrue1,phitrue2; // true energy of the 2 daughters
double e1,px1,py1,phi1; // smeared 4-momenta of daughter 1
double e2,px2,py2,phi2; // smeared 4-momenta of daughter 2
double masssmeared;
for(int i=0;i<N;i++) {
// set true energy
etrue1=mass/2.;
etrue2=mass/2.;
if(idebug) cout<<"etrue "<<etrue1<<" "<<etrue2<<endl;
// choose phi for daughter 1 and daughter 2
phitrue1=2*TMath::Pi()*gRandom->Rndm();
phitrue2 = phitrue1+TMath::Pi();
if(idebug) cout<<"phitrue "<<phitrue1<<" "<<phitrue2<<endl;
// smear true energy with resolution of detector
e1=etrue1+resE*gRandom->Gaus(0.,1.);
e2=etrue2+resE*gRandom->Gaus(0.,1.);
if(idebug) cout<<"e "<<e1<<" "<<e2<<endl;
//smear angles with resolution of the detector
phi1=phitrue1+resA*gRandom->Gaus(0.,1.);
phi2=phitrue2+resA*gRandom->Gaus(0.,1.);
if(idebug) cout<<"phi "<<phi1<<" "<<phi2<<endl;
//calculate 4 momenta after smearing
px1=e1*cos(phi1);
py1=e1*sin(phi1);
px2=e2*cos(phi2);
py2=e2*sin(phi2);
if(idebug) cout<<"pxs "<<px1<<" "<<py1<<" "<<px2<<" "<<py2<<endl;
// calculate smeared mass
masssmeared=sqrt((e1+e2)*(e1+e2) - (px1+px2)*(px1+px2) - (py1+py2)*(py1+py2));
if(idebug) cout<<"masssmeared "<<masssmeared<<endl;
histo1->Fill(masssmeared);
histo1->Draw("");
c1->Update();
c1->SaveAs("c1.gif");
}
How to run a root file
root -l file.type
N=1
The mass looks to be about 91
N=10
There's variation in the measurements, but the average looks to be between 90-100
N=100
There's even more variation in the measurements but more frequency of measurements the closer we are to 90. The average would still be about 90-100.
N=1000
There's even even more variation in the measurements, but definitely way greater frequency of measurements the closer we get to 90. Average still looks to be about 90-100. Basically, as N increases, the closer we approach to a normal distribution
When the first number of secretparameter equals 1
N=1000 (as an example)
Mass can't be less than 0. So there's more variation again as N increases. Values around 1 have greater frequency. But, the average will no longer be around 1, especially as N increases, because we have masses up to 160, but no -160.
HW7 (Due 11-12-18)
My file: MG5_aMC_v2.6.3.2.tar.gz
My MCProduction is in my src file
Do find command of *lhe* if I ever lose my file
lhe2root.py and MG5 are under
./MCProduction/MG5_aMC_v2_6_3_2/
Homework to submit:
Brief description of major parts of CMS detector:
Beam tracker: particle collision place
Tracker: Records particles' paths
Calorimeter: Measures particles' energies.
Solenoid: cylindrical coil. Generates uniform magnetic field inside of it
Muon Tracker: tracks, detects muons. Chambers for tracking muons is on outer place of CMS. Muon tracker uses cathode strip chambers, resistive plate chambers, and drift tubes.
Click axes to change xy perspective
Green track is electron
Yellow track is photon
Red track is muon
Purple is missing energy, that can often indicate a neurtrino
Jet is orange/yellow octagonal cones
When a charged particle bends clockwise, that means its positively charged
(PS, jet counts are likely somewhat inaccurate)
(PS, our computers were struggling to run the program, so Matt and I shared some data)
4lepton
Event 1
1. Electrons: 0
2. Muons:4
3. Photons: 0
4. Jets: 28
5. Missing energy: 0
6. Vertices: 5
Event 2
1. Electrons: 4
2. Muons: 1
3. Photons: 4
4. Jets: 32
5. Missing energy: 2
6. Vertices: 0
diphoton
Event 3 (1)
1. Electrons: 0
2. Muons: 1
3. Photons: 0
4. Jets: 16
5. Missing energy: 1
6. Vertices: 0
Event 4 (2)
1. Electrons: 0
2. Muons: 0
3. Photons: 1
4. Jets: 20
5. Missing energy: 1
6. Vertices: 9
Minimum Base
Event 5 (1)
1. Electrons: 0
2. Muons: 0
3. Photons: 0
4. Jets: 5
5. Missing energy: 0
6. Vertices: 2
Event 6 (2)
1. Electrons: 0
2. Muons: 1
3. Photons: 0
4. Jets: 2
5. Missing energy: 0
6. Vertices: 3
Mu category
Event 7 (1)
1. Electrons: 2
2. Muons: 1
3. Photons: 1
4. Jets: 11
5. Missing energy: 1
6. Vertices: 2
Event 8 (2)
1. Electrons: 2
2. Muons: 1
3. Photons: 1
4. Jets: 9
5. Missing energy: 1
6. Vertices: 2
Electron category
Event 9 (1)
1. Electrons: 1
2. Muons: 0
3. Photons: 1
4. Jets: 13
5. Missing energy: 1
6. Vertices: 1
Event 10 (2)
1. Electrons: 1
2. Muons: 0
3. Photons: 1
4. Jets: 7
5. Missing energy: 0
6. Vertices: 2
HW8 Due (11-13-18)
If you are in folder with file you want, when unpacking it, you can just type the file name
tar zxvf LHC-Higgs-Graviton.tgz
mkdir -p src/Higgs-mass
Moving files
mv
filename currently in directory
directory you want it to go to
mv output_Graviton2PMToZZTo4L_M-125_7TeV-JHUgen-PYTHIA6_Tauola.root ./src/Higgs-mass/
Do for all four files
..\ for moving back directories
So go into CMSSW_5_3_32
Then src/Higgs-mass
What the code should do
6. Makes a class called HiggsAnalysis
The HZZ... is the name of the tree
We're calling the tree and then making a class
Leaves/variables under tree
get out of root, emac higgs analysis .h file
.h is a header file
7. So emacs that .C code with the stuff in the
directions
get entry 12, gets 12 events for you
Lorentz vector
Combines relativity and vectors
Higgs produced somehow, went into two z bosons
z bosons decayed into two leptons each, four total
Combine l1 and l2 for four vectors
(x,y,z,t)
(E, Px, Py, Pz)
Mass of z boson is 91, so graph should look like average/median mass is close to 91
Take info of two files input, combine, get a z
Take info for l3 and l4, combine, get a z
Combine the Lorentz vectors
Get a Higgs boson
So combine lepton lorentz vectors for a z
Then combine z lorentz vectors for a higgs
7.
.L HiggsAnalysis.C
NEW CODE:
#define HiggsAnalysis_cxx
#include "HiggsAnalysis.h"
#include <TH2.h>
#include <TStyle.h>
#include <TCanvas.h>
void HiggsAnalysis::Loop()
{
// In a ROOT session, you can do:
// Root > .L HiggsAnalysis.C
// Root > HiggsAnalysis t
// Root > t.GetEntry(12); // Fill t data members with entry number 12
// Root > t.Show(); // Show values of entry 12
// Root > t.Show(16); // Read and show values of entry 16
// Root > t.Loop(); // Loop on all entries
//
// This is the loop skeleton where:
// jentry is the global entry number in the chain
// ientry is the entry number in the current Tree
// Note that the argument to GetEntry must be:
// jentry for TChain::GetEntry
// ientry for TTree::GetEntry and TBranch::GetEntry
//
// To read only selected branches, Insert statements like:
// METHOD1:
// fChain->SetBranchStatus("*",0); // disable all branches
// fChain->SetBranchStatus("branchname",1); // activate branchname
// METHOD2: replace line
// fChain->GetEntry(jentry); //read all branches
//by b_branchname->GetEntry(ientry); //read only this branch
if (fChain == 0) return;
Long64_t nentries = fChain->GetEntriesFast();
Long64_t nbytes = 0, nb = 0;
TFile* output = TFile::Open("Dielectron_MC.root", "RECREATE"); // "RECREATE" would produce a new root file with name Dielectron_MC.root every time you run the code
TH1F* Z_ee = new TH1F("Z_ee", "Di-electron candidate invariant mass", 200, 0, 200);
double el1mt = 0.0;
double el1pt = 0.0;
double el1eta = 0.0;
TH1F* Z_ee2 = new TH1F("Z_ee2", "Di-electron candidate 2 invariant mass", 200, 0, 200);
double el3mt = 0.0;
double el3pt = 0.0;
double el3eta = 0.0;
TH1F* H_zz = new TH1F("H_zz","Higgs candidate invariant mass", 200, 0, 300);
double zCandidatemt = 0.0;
double zCandidatept = 0.0;
double zCandidateeta = 0.0;
for (Long64_t jentry=0; jentry<nentries;jentry++) {
Long64_t ientry = LoadTree(jentry);
if (ientry < 0) break;
nb = fChain->GetEntry(jentry); nbytes += nb;
// if (Cut(ientry) < 0) continue;
TLorentzVector el1, el2;
el1.SetPtEtaPhiM(f_lept1_pt, f_lept1_eta, f_lept1_phi, 0.0);
el2.SetPtEtaPhiM(f_lept2_pt, f_lept2_eta, f_lept2_phi, 0.0);
TLorentzVector zCandidate = el1 + el2;
Z_ee->Fill(zCandidate.M());
el1mt = el1.Mt();
cout << el1mt << endl;
TLorentzVector el3, el4;
el3.SetPtEtaPhiM(f_lept3_pt, f_lept3_eta, f_lept3_phi, 0.0);
el4.SetPtEtaPhiM(f_lept4_pt, f_lept4_eta, f_lept4_phi, 0.0);
TLorentzVector zCandidate2 = el3 + el4;
Z_ee2->Fill(zCandidate2.M());
el3mt = el3.Mt();
cout << el3mt << endl;
TLorentzVector HiggsCandidate = zCandidate + zCandidate2
H_zz->Fill(HiggsCandidate.M());
zCandidatemt = zCandidate.Mt();
cout << zCandidatemt << endl
}
Z_ee->Write();
Z_ee2->Write();
H_zz->Write();
output->Close();
}
HW9
11-13 Class notes
Python
-Artificial intellignece
-Machine learning
-Deep learning
Go thru one exercise of machine, one exercise of deep
AI:
Makes its own decsions that you didn't explicitly tell it to do
Machine learning:
-Learn from experience using math+hardware/software
-Discrimator: whether data matches distribution you're training it to match for
-Probability
Neural Networks:
-Input nodes (node is point where input is coming in from)
-Info manipulated with math functions at hidden nodes
-Input nodes connected to hidden nodes
-Info manipulated thru waves
-Hidden nodes relay info to output nodes
-Iteration
-Back propagation, redoing when you get knowledge/performance at end
-Initially, I was human person setting parameters
-Now machine decides which direction to go into, drop/add inputs
-The above sentence is deep learning
Coding (after going through code, go back and do exercises)
*TABS ARE VERY IMPORTANT*
30 is the total animals in the zoo
pandas=10
#set pandas equal to integer 10
zebras=20
#set zebras equal to integer 20
total_animals_in_zoo=pandas+zebras
#makes variable totals_animals_in_zoo equal to pandas + zebras
print(total_animals_in_zoo)
#prints the sum of pandas and zebras
Area of a circle
pi=3.14159 #Approx.
diameter=10
area=pi*(.5*diameter)**2
print(area)
78.53975
The reason the first method doesn't work is by setting a=b, then b=a, we end up with just having a and b =b, so it prints out b's list both times.
The second method sets temp=a, then sets a=b, then sets b=temp, so the original a is stored as temp and gets to switch with b, and new a is old b.
Method 2 (code that works):
#####Method 2########
a = [1, 2, 3]
b = ['cat', 'dog', 'fish']
temp = a
a = b
b = temp
print('Method 2')
print(a)
print(b)
dog_legs=0
human_legs=4
goldfish_legs=2
temp = dog_legs
dog_legs = human_legs
human_legs = goldfish_legs
goldfish_legs=temp
print(dog_legs)
print(human_legs)
print(goldfish_legs)
4 2 0
def round_to_two_places(num):
#def is used to define functions
return round(num, 2)
#takes the argument number, rounds it to 2 decimal places
print(round_to_two_places(4.325456463))
def round_to_two_places(num):
#def is used to define functions
return round(num, 7)
#takes the argument number, rounds it to 7 decimal places
print(round_to_two_places(8.987654321))
8.9876543
a=[1,5435,324,3,645365,23,4,5665,435,31, -543]
b=-10
c='cat'
print(c)
print(abs(b)) #absolute value
print(min(a)) #min value
print(max(a)) #max value
print(sum(a)) #sum
print(len(c)) #length of a string
print(sorted(a)) #sorts a list
cat 10 -543 645365 656743 3 [-543, 1, 3, 4, 23, 31, 324, 435, 5435, 5665, 645365]
a=[3243,645645,54346] b=[7,3,2] def product_of_maxes(a, b): return max(a)*max(b)
Logic
print(3==10) #False because 3 doesn't equal 10 print(len('abc')==3) #True because length of string abc is 3 print(max([10,40,53]) < 25) #Fale because the max of that list is 53, which is greater than 25 print (5 != 3) #True because 5 doesn't equal 3
print(min([11,41,53]) > 25)
print(sum([11,2]) == 13)
print(max([3,4,5]) < 4)
False True False
a=10
b=20
if(a>b):
print(a, 'is greater than', b)
elif(a<b):
print(b, 'is greater than', a)
else:
print("they're equal")
prints values of a and b, so it says 20 is greater than 10
Variable changes done in colab
def longer_string(string1, string2):
if(len(string1) > len(string2)):
return string1
elif(len(string1) < len(string2)):
return string2
else:
return
print(longer_string('abc', 'jfkdla;s'))
print(longer_string('abcfdsafdasg', 'jfkdla;s'))
print(longer_string('abc', 'def'))
Output:
jfkdla;s abcfdsafdasg None
String 2 was longer,
String 1 was longer
Neither string was longer/they were the same length
def can_make_cake(eggs, flour, milk, almond_milk):
#I can make cake if I have some kind of milk AND flour AND eggs
return (milk or almond_milk) and flour and eggs > 0
print('Can I make cake?')
#What is the following line implying?
print(can_make_cake(10, True, False, True))
#redo the above call to the function with 0 eggs
### your code here ###
In original code, we have 10 eggs, its true we have flour, its false that we have milk, and its true that we have almond milk
If we change eggs to 0, we can't make cake, because eggs needs to be above 0 to make cake
a = [-35423,-5432654,-352435,53252] def abs_of_min_is_odd(a): if ((min(a))%2 == 1): print("odd") else: print("even")
def select_third_element(my_list):
if(len(my_list) < 3):
return None
else:
return my_list[2] #remember index 0, so third element is index 2
foo = ['a', 'b', 'c', 'd']
print(select_third_element(foo))
#prints the third element, c
list1=[1,2,3]
list2=[4,5,6]
list_of_lists=[list1,list2]
print(list_of_lists[0])
#print list 1 cuz that's first item of list of lists
print(list_of_lists[1])
#print list 2, 2nd item of list1
print(list_of_lists[0][1])
#print item 2 of list 1
print(list_of_lists[0][2])
#print item 3 of list 1
print(list_of_lists[1][0])
#print item 1 of list 2
print(list_of_lists[1][2])
#print item 2 of list 2
c [1, 2, 3] [4, 5, 6] 2 3 4 6
real_madrid=['zidane', 'ramos', 'marcelo'] barcelona=['valverde', 'messi', 'pique'] teams = [real_madrid, barcelona] def losing_team_captain(team_list): return barcelona[0] print(losing_team_captain(barcelona[0]))
valverde
def list_contains_seven(my_list): for element in my_list: if element ==7: return True return False print(list_contains_seven([6,14,5,7])) print(list_contains_seven([6,14,5,9]))
True False
def count_to_10(num): while(num<10): num=num+1 print(num) count_to_10(0) count_to_10(5) count_to_10(11)
1 2 3 4 5 6 7 8 9 10 6 7 8 9 10
list=[1,21,7,-14,49,74,700] def seven_counter(my_list): a=0 for element in my_list: if element%7 == 0: a=a+1 return a seven_counter(list)
5
capitals={'United States': 'DC', 'France': 'Paris', 'Mexico': 'DF'} populations={'UMD':40000, 'Towson': 30000, 'UMBC': 20000} print(populations.get('UMD'))
40000
deck={} #represents a deck of cards where the keys are the suits and values are lists of card values hearts=[] clubs=[] diamonds=[] spades=[] values=['ace', 'two', 'three', 'four', 'five', 'six','seven', 'eight', 'nine', 'jack', 'king', 'queen'] def create_cards(suit): for value in values: suit.append(value) create_cards(hearts) create_cards(clubs) create_cards(diamonds) create_cards(spades) ##################################Add your code here according to the comments ########################################## #Use the strings 'h', 's', 'c', 'd' as keys, and add the lists of values to the dictionary. keys = {'h', 's', 'c', 'd'} deck = dict.fromkeys(keys, values) #deck is the dictionary #Python Dictionary fromkeys() creates dictionary from given sequence #Print a view of dictionary (key, value) pairs print(deck.items()) #prints dictionary pairs #Print a view of all of the keys print(deck.values()) #prints keys #Print a view of all of the values print(deck.values()) #Remove all of the spades from the deck deck.pop('s') #Python Dictionary popitem() Returns & Removes Element From Dictionary #Add a new entry to the dictionary with key 'j' and values 'joker1' and 'joker2' deck.setdefault('j',['joker1', 'joker2']) #Clear the dictionary deck.clear() #clear the dictionary print(deck) #print deck
dict_items([('c', ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen']), ('s', ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen']), ('d', ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen']), ('h', ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen'])]) dict_values([['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen'], ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen'], ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen'], ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen']]) dict_values([['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen'], ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen'], ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen'], ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'jack', 'king', 'queen']]) {}
import math as m #I use the as m part so when I refer to the library I can just type m instead of math. Its just an abbreviation. print(m.pi, m.log(32, 2)) # print value for pi (approximate) and log base 2 of 32 print(m.gcd(75348597,979531683)) #print greatest common denominator of given numbers print(m.cos(10)) #print cosine of 10
3.141592653589793 5.0 3 -0.8390715290764524
import matplotlib import matplotlib.pyplot as plt import numpy as np # Data for plotting t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks') ax.grid() plt.show()
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()
# imports some software packages we'll use import pandas as pd import numpy as np %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt inline_rc = dict(mpl.rcParams) # a hashtag tells the program "don't read the rest of the line" # That way we can write "comments" to humans trying to figure out what the code does two_u = pd.read_csv('https://github.com/adamlamee/HEP-data/raw/master/Double_Muon_Run2011A.csv') # two_e = pd.read_csv('https://github.com/adamlamee/HEP-data/raw/master/Double_Electron_Run2011A.csv') # one_u = pd.read_csv('https://github.com/adamlamee/HEP-data/raw/master/Single_Muon_Run2011A.csv') # one_e = pd.read_csv('https://github.com/adamlamee/HEP-data/raw/master/Single_Electron_Run2011A.csv') data = two_u # The .head(n) command displays the first n rows of a file. data.head(3) # The .shape command displays the (number of rows , number of columns) in a file. data.shape # You can specify a column by dataset.columnName (e.g., two_u.E1) # This makes a new column called "totalE" and fills it with (E1 + E2) for each event data['totalE'] = data.E1 + data.E2 # This makes a new column called "Esquared" and fills it with E1^2 for each event data['Esquared'] = data.E1**2 # makes the histogram plt.hist(data.totalE, bins=10, range=[0,120], log=False) plt.title("Dimuon Events") plt.xlabel("x-axis label") plt.ylabel("number of events")
Text(0,0.5,'number of events')