Fall 2019 Old Logbook:
Homework 3:
$ARG creates a variable within the script. "$ARG" displays that variable as a string.
"$ARG*" displays ARG and an asterisk as a string.
Backticks (') run the echo as a command instead of displaying it in the terminal.
chmod changes the mode.
Piping allows you to take the output from one command and the input from another or string multiple commands.
Homework 4:
Main.cpp:
#include <iostream>
//Calls the in and out library of commands to be able to be\
used within the script
using namespace std;
//Allows the user to write commands within the std domain \
without printing "std." before each command (in this case, cout)
int main() {
//Initializes the program
cout <<"Hello World!" << endl;
//Print hello world to screen followed by end line (endl)
return 0;
//Exit the program
}
find /usr/include/c++ -name "4*" //Finds all files within the directory that start with 4
g++ -dumpspecs //Displays info about g++
ls /usr/include/c++/4.4.4/ //Displays info about file 4.4.4
ls /usr/include/math.h //Displays info about math.h
ls /usr/include/bits/*math*.h //Displays any file with math in the name
Variable:
#include <iostream> //Calls the in and out library of commands to be able \
to be used within the script
using namespace std; //Allows the user to write commands within the std dom\
ain without printing "std." before each command (in this case, cout)
int main() { //Initializes the program
cout << "hello world" <<endl; //Prints "hello world" in the terminal then\
ends the line
int i=2; //Initializes variable i to equal 2
cout << "i = " <<i<<endl; //Prints "i = " then prints i and ends the line
double a=3.3; //Initializes a decimal point variable as opposed to a whol\
e number variable
cout << "a = " <<a<<endl; //Displays "a = " then prints a and ends the li\
ne
int j = a*i; //Initializes variable j to be equal to the value of a times\
the value of i
cout << "a*i = " <<j<<endl; //Prints "a*i = " then displays the value of j
return 0; //Exits the program
}
Operations:
#include <iostream> //Calls the in and out library of commands to be able t\
o be used within the script
using namespace std; //Allows the user to write commands within the std dom\
ain without printing "std." before each command (in this case, cout)
int main() { //Initializes the program
int n=10; //Initializes variable n
cout << "n is "<<n<<endl; //Displays "n is " then prints n and ends the l\
ine
n--; //Decreases the value of n by 1
cout<<"n is now "<<n<<endl; //Displays "n is now " then prints the new va\
lue of n and ends the line
n++; //Increases the value of n by 1
cout<<"n is now "<<n<<endl; //Displays "n is now " then prints the new va\
lue of n and ends the line
return 0; //Ends the program
}
Nonnumeric:
#include <iostream> //Calls the in and out library of commands to be able t\
o be used within the script
using namespace std; //Allows the user to write commands within the std dom\
ain without printing "std." before each command (in this case, cout)
int main() { //Initializes the program
bool prop; //Initializes a boolean variable named "prop" which will have \
a value of 1 if the input is true and a value of 0 if the input is false.
prop = (5>1); //Sets prop equal to the value that corresponds with the st\
atement's validity.
cout<<"prop is "<<prop<<endl; //Displays "prop is " then prints prop
prop = (1>5); //Sets prop equal to the value that corresponds with the st\
atement's validity.
cout<<"prop is "<<prop<<endl; //Displays "prop is " then prints prop
return 0; //Ends the program.
}
Loops1:
#include <iostream>
using namespace std;
int main() {
int n=10; //Initializes variable n to equal 10
while(n>0) { //Creates a loop that runs continuously as long as n is grea\
ter than 0
cout<<"n is "<<n<<endl; //Displays "n is " then prints n and ends the l\
ine
n--; //Subtracts 1 from n
}
return 0;
}
Loops2
#include <iostream>
using namespace std;
int main() {
// 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 (int n=10; n>0; n--) { //Creates a for loop that starts when n is equ\
al to 10, limits n to be greater than 0, and subtracts 1 from n at the end of e\
ach loop
cout<<"n is "<<n<<endl; //Displays "n is " and prints n and ends the li\
ne
}
// in a for loop, the loop variable (in this case, 'n') only 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;
// If uncommented, this line would attempt to call n outside the loop. As a r\
esult the program would fail because n exists locally within the loop.
return 0;
}
Loops3:
#include <iostream>
using namespace std;
int main() {
int n=0, m=0;
for (int n=0; n<=10; n++) { //Creates a loop that begins at n=0, stops wh\
en n is greater than 10, and adds 1 to the value of n each loop
//while(n<10) {
// this is the slow (or outer) loop
cout<<"n is "<<n<<": "; //Displays the current value of n, but does n\
ot end the line
m=0;
for (int m=0; m<=n; m++) { //Creates an inner loop within the first t\
hat starts at m=0 and goes until m is larger than n and adds 1 to the value of \
m.
//while(m<=n) {
// this is the fast (or inner) loop
// in this loop, the slow loop variable (n) is a constant
// this loop must run to completion before the slow loop
// can progress (during every iteration of the slow loop!)
cout<<m; //Displays the value of m for each loop onto the line
}
// now the fast loop has finished and the slow loop can
// continue with the current iteration
cout<<endl;
}
return 0;
}
Homework 5:
echo $0 Finds what type of shell your machine is
Using bash
echo $SHELL Finds where bash is located
Basic command structure: command -option1 -option2 -option3... target1 target2
command_name --help Displays help for command
man command_name Manual for the command
pwd: Displays what directory you are in
ls: Lists what
Homework 5:
Date: 10/16/2018
Logic Statements:
#include <iostream>
using namespace std;
int main() {
int n = 10;
while (n>=10) { //n>=10 means n is greater than or equal to
if(n>5) { //> is greater than but not equal to
cout<<"n is "<<n<<endl;
}
else {
cout<<"n = "<<n<<endl;
n--; //Subtract 1 from n
}
return 0;
}
}
Pointers:
Pointers are used to store the memory location of a variable that updates automatically with the variable without having to create a separate storage address.
#include <iostream> //Calls the in and out library of commands to be able to be used within the script
using namespace std;
int main() {
int i = 10; //Initializes a variable i with value equal to 10
cout << "The memory address of i is " << &i << "\n"; //&i displays the memory address of i
cout << "The data stored at memory address " << &i << " is " << i << "\n"; //&i displays the memory address of i while simply typing i displays the value of i
int* p = &i; //Initializes a pointer to equal the memory address of i
cout << "The value of p is " << p << "\n"; //Displays the memory address stored at p
cout << "We say that p 'points at' the memory location referenced by address " << p << "\n"; //Displays the memory address stored at p
cout << "The data stored at memory address " << p << " is " << *p << "\n"; //*p will display the value at memory address p
return 0;
}
Pointer Programs:
/*PROGRAM 1*/
#include <iostream>
using namespace std;
int main(){
//Initialize a variable named i and set it equal to 10.
int i = 10;
//Initialize a variable named j and set it equal to the current value of i.
int j = i;
//Display the values of i and j
cout << "i= " << i << " and j= " << j << "\n";
//Set the value of i to 5, which does not impact the value of j
i=5;
//Display the new values of i and j
cout << "i= " << i << " and j= " << j << "\n";
//Set the value of j to 1, which does not impact the value of i
j=1;
//Display the new values of i and j
cout << "i= " << i << " and j= " << j << "\n";
return 0;
}
/*PROGRAM 2*/
#include <iostream>
using namespace std;
int main(){
//Initialize a variable named i and set it equal to 10.
int i = 10;
//Initialize a pointer named p that points to the value of i.
int* p = &i;
//Display the values of i and the variable that p points to (i).
cout << "i= " << i << " and *p= " << *p << "\n";
//Set the value of variable i equal to 5, which also affects the value that pointer p points to.
i=5;
//Display the new value of i and the new value that p points to (5)
cout << "i= " << i << " and *p= " << *p << "\n";
//Set the value that p points to equal to 1, which changes what is stored at i.
*p=1;
//Display the new value of i and the new value p points to (1)
cout << "i= " << i << " and *p= " << *p << "\n";
return 0;
}
Program 1 uses a variable j to store the memory address. This works if both variables are static. However, if one of the variable values is changed, the other variable will not update automatically. By contrast, Program 2 changes the data stored at memory address p, which changes the value of i, leading to less error in the program and allowing the data to stay consistent.
#include <iostream>
using namespace std;
int main(){
int* p = new int(5); //Creates a new variable at p with value 5
cout << "p points at address " << p << "\n";
cout << "The data stored in address " << p << " is " << *p << "\n"; //Dot operator can be used to display data at p
*p = 10; //Dot operator can also be used to change value at p
cout << "Now the data stored in address " << p << " is " << *p << "\n";
return 0;
}
In this program, the new int(5) command creates a new variable that is stored at memory address p without creating a separate variable. The only downside to this is that the value of the variable can only be accessed by using the * operator on p instead of calling the variable name as one would normally do.
Homework 6:
Date: 10/29/18
Arrays:
#include <iostream>
using namespace std;
int main() {
/************************************************\ * * * Arrays * * This program demonstrates arrays * * * \************************************************/
//Create an array named ii that has length 5.
int ii[3] = {1,2,3};
//Create a variable to count the amount of times the while loop runs.
int j = 0;
while (j<3) {
//Display each index value of the array and the corresponding value at said index.
cout<<"ii of "<<j<<" is "<<ii[j]<<endl;
//Add one to j.
j++;
}
//Create a matrix named LL that has 2 rows and 3 columns.
int LL[2][3] = {1,2,3,4,5,6};
//Reset j to 0 so that it can be used for the matrix.
j=0;
//Initialize a second variable to track the columns.
int k;
//Cycle through each j value.
while (j<2) {
//Reset k equal to 0.
k=0;
//Cycle through each k value for the current j value.
while (k<3) {
//Display each row then column index of the current location in the matrix and the value at said location.
cout<<"LL of "<<j<<" "<<k<<" is "<<LL[j][k]<<endl;
//Add 1 to k
k++;
}
//Add 1 to j
j++;
}
//End program.
return 0;
}
Data files:
#include <iostream> #include <fstream> using namespace std; int main() {
//Loads the file into the file stream
ofstream myfile;
//Opens the file that is being modified to allow it to be modified.
myfile.open("example.txt");
//Stores text into the file. myfile<<"write some junk.";
//Closes the file myfile.close(); return 0; }
This program opens a text file and stores lines of text or data in it. ofstream.open and ofstream.close open and close the file, while the << store values in the myfile file.
Input other files:
/* MAIN.CPP */ #include <iostream> #include <fstream> // include the program dotprod.cpp so that we can find the dot_prod function #include "dotprod.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 dotprod.cpp dot_prod(vector1,vector2); return 0; }
Acts as the primary program which compiles other programs to compute the dot product.
/* 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]; cout<<" The dot product is "<<dotdot<<endl; return 0; }
Computes the dot product.
1 2 3 4 5 6 7
Acts as input.
RNG:
#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; const int c = 54773; const int mmod=256200; double getFlatRandom(int& inew) { double mranflat = 0.; inew = inew%mmod; double aa = double(inew)/double(mmod); mranflat=aa; inew = a*inew+c; return mranflat; } // 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 } // 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; }
ROOT:
#include "Riostream.h"
#include <iostream>
#include <fstream>
void resolutions(){
//Reset all start values
bool idebug=0;
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);
//Initialize the histogram
TH1F *histo1 = new TH1F("histo1","mass",1000,0.,200.);
//Open secretparameters.txt to use as input
ifstream myfile;
myfile.open("secretparameters.txt");
//Create variables
double mass, resE, resA;
//Set the variables to the input in secretparameters.txt
myfile>>mass>>resE>>resA;
myfile.close();
//Create necessary variables
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;
//Set values to variables using for loop
for(int i=0;i<N;i++) {
etrue1=mass/2.;
etrue2=mass/2.;
if(idebug) cout<<"etrue "<<etrue1<<" "<<etrue2<<endl;
phitrue1=2*TMath::Pi()*gRandom->Rndm();
phitrue2 = phitrue1+TMath::Pi();
if(idebug) cout<<"phitrue "<<phitrue1<<" "<<phitrue2<<endl;
e1=etrue1+resE*gRandom->Gaus(0.,1.);
e2=etrue2+resE*gRandom->Gaus(0.,1.);
if(idebug) cout<<"e "<<e1<<" "<<e2<<endl;
phi1=phitrue1+resA*gRandom->Gaus(0.,1.);
phi2=phitrue2+resA*gRandom->Gaus(0.,1.);
if(idebug) cout<<"phi "<<phi1<<" "<<phi2<<endl;
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;
masssmeared=sqrt((e1+e2)*(e1+e2) - (px1+px2)*(px1+px2) - (py1+py2)*(py1+py2));
if(idebug) cout<<"masssmeared "<<masssmeared<<endl;
//Draw the histogram
histo1->Fill(masssmeared);
histo1->Draw("");
c1->Update();
c1->SaveAs("c1.gif");
}
}
Homework 7:
//Open Firefox
[cms-opendata@localhost ~]$ firefox &
//Make a new directory called MCProduction, then download a tar file and untar it.
cd CMSSW_5_3_32/src
cmsenv
mkdir MCProduction
mv ~/Downloads/MG5_aMC_v2.6.0.tar.gz MCProduction/
cd MCProduction/
tar -xvzf MG5_aMC_v2.6.0.tar.gz
//Open the mg5_aMC program
./bin/mg5_aMC
//Generate event
MG5_aMC>generate p p > t t~
//Display the processes
MG5_aMC>display processes
//Display particles
MG5_aMC>display particles
//Display the multiparticles
MG5_aMC>display multiparticles
//Add a process
MG5_aMC>add process p p > W+ j, W+ > l+ vl
//Output and launch the processes initialized
MG5_aMC>output MY_FIRST_MG5_RUN
MG5_aMC> launch MY_FIRST_MG5_RUN
//Run the processes
MY_FIRST_MG5_RUN/Events/run_01/ unweighted_events.lhe.gz
//Convert the file to root
python lhe2root.py MY_FIRST_MG5_RUN/Events/run_01/unweighted_events.lhe MY_FIRST_MG5_RUN.root
//Run the file in root
root -l MY_FIRST_MG5_RUN.root
Write a brief description of major parts of the CMS detector. Beam pipe, tracker, calorimeter, solenoid, muon tracker. What are the physical dimensions of each part?
Beam Pipe: part of the machine where particles collide.
Tracker: records the path of particles. Dimensions: radius: 1, width: 13 meters
Calorimeter: records the energies of particles. Dimensions: outer radius: 2 meters. Inner radius: 1 meter. Length: 13 meters
Solenoid: Generates a magnetic field to guide particles
Muon Tracker: records muon direction. Uses drift tubes, cathode strip chambers, and resistive plate chambers. Dimensions: radius: 3 meters, length: 13 meters
Find how to change the display to show you a view along the beam pipe?
Click the button to change the perspective to the XY plane.
Which color tracks are electrons
Green
Which color tracks are muon?
Red
Which color track missing energy is represented with?
Pink/purple
How are jets depicted in this visualization?
Octagonal cones extending from the point of collision.
Can you figure out if a track has clockwise curvature, it is +vely charged or negatively charged? (when looking at the x-y view, with x along the horizontal axis)
The charge is positive if the track has clockwise curvature.
Study at least 2 events from each category in the files available with the display and specify how many objects of each kind are seen in every event?
Electrons
Event 718940510: 1 electron, 1 unknown
Event 718984830: 1 electron
Muons
Event 90634848: 1 muon, 2 electrons, 1 unknown
Event 90649368: 1 muon, 1 electron, 1 unknown
Photons
Jets
missing energy
Vertices
Note: iSpy takes up over 90% of my RAM, and therefore runs so slow that it is almost unusable. Counts may be inaccurate as a result, especially jets
Note: The program crashed on my computer after 7 events. Last 3 events were taken from Sam Engler’s data as a result. Sam’s computer happened to also crash shortly after mine did, but thankfully we did the results in reverse order so I was able to give her the ones she wasn’t able to get.
Electron category:
Event 718940510:
Electrons: 1
Muons: 0
Photons: 1
Jets: 13
Missing energy: 1
Vertices: 1
Event 718984830:
Electrons: 1
Muons: 0
Photons: 1
Jets: 10
Missing energy: 0
Vertices: 2
Mu category:
Event 90634848:
Electrons: 2
Muons: 1
Photons: 1
Jets: 9
Missing energy: 1
Vertices: 2
Event 90649368:
Electrons: 1
Muons: 1
Photons: 1
Jets: 7(?)
Missing energy: 1
Vertices: 3
MinimumBias category:
Event 441596299:
Electrons: 0
Muons: 0
Photons: 0
Jets: 5
Missing energy: 0
Vertices: 2
Event 441610515:
Electrons: 0
Muons: 1
Photons: 0
Jets: 2
Missing energy: 0
Vertices: 3
Diphoton category:
Event 688901524:
Electrons: 0
Muons: 0
Photons: 1
Jets: around 20 (too condensed to accurately count with an extremely slow computer)
Missing energy: 1
Vertices: 9
Event 1
Electrons: 0
Muons: 1
Photons: 0
Jets: 16
Missing energy: 1
Vertices: 0
4lepton category:
Event 1
Electrons: 0
Muons: 4
Photons: 0
Jets: 28
Missing energy: 0
Vertices: 5
Event 2
Electrons: 4
Muons: 1
Photons: 4
Jets: 32
Missing energy: 2
Vertices: 0
Homework 8:
HZZ4LeptonsAnalysisReduced->MakeClass("HiggsAnalysis") creates a class of commands named “HiggsAnalysis” and saves it under the file “HiggsAnalysis.h” that can be called by using “#include “HiggsAnalysis.h”” in the root code. It also creates a separate .C file that has executable code in it.
#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
//Initialize histograms and variables
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, 200);
double zCandidatemt = 0.0;
double zCandidatept = 0.0;
double zCandidateeta = 0.0;
//Initialize the loop
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;
//Trace back the paths of the first two leptons to find the first z boson candidate
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;
//Trace back the paths of the second two leptons to find the second z boson candidate
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;
//Trace back the paths of the z boson candidates to find the higgs candidate
TLorentzVector higgsCandidate = zCandidate + zCandidate2;
H_zz->Fill(higgsCandidate.M());
zCandidatemt = zCandidate.Mt();
cout<<zCandidatemt<<endl;
}
//Write the histograms
Z_ee->Write();
Z_ee2->Write();
H_zz->Write();
output->Close();
}
Homework 9
Exercise: What is the difference between CPU and GPU?
CPU stands for Central Processing Unit and acts as the main processing center of the computer. The Graphics Processing Unit, or GPU, acts as a secondary processor that is specialized to run repetitive instuctions at a fast rate. It initially developed as a way to process computer gaming graphics, but has since been used for a variety of computational tasks.
Programming:
# Create a variable called pandas and set it equal to 10
pandas=10
# Create a variable called zebras and set it equal to 20
zebras=20
# Create a variable called total_animals_in_zoo and set it equal to the number of pandas plus the number of zebras.
total_animals_in_zoo=pandas+zebras
# Display the value of total_animals_in_zoo
print(total_animals_in_zoo)
What is the output you get?
30
# Exercise: Using the pre-declared variables, calculate the area of a circle,
# and assign it to a new variable named 'area'. Print 'area' to the console.
pi = 3.14159 #Approx.
diameter = 10
#######YOUR CODE HERE#######
#Define a variable named area and set it equal to pi times half of the diameter squared.
area = pi*(diameter/2)**2
#Print the value of area.
print(area)
#####Method 1#####
# Create a list named a composed of numbers
a = [1, 2, 2]
# Creat a list named b composed of animal names
b = ['cat', 'dog', 'fish']
# Set a equal to b
a=b
# Set b equal to a, which already equals b, so this line does nothing.
b=a
# Print "Method 1", then display the new values of a and b
print('Method 1')
print(a)
print(b)
#####Method 2#####
# Create a list named a composed of numbers
a = [1, 2, 3]
# Create a list named b composed of animal names
b = ['cat', 'dog', 'fish']
# Create a temporary variable called temp to store the value of a while the two lists are being switched and store the value of a in it.
temp = a
# Set a equal to b.
a = b
# Set b equal to the original value of a.
b = temp
# Print "Method 2", then display the new values of a and b
print('Method 2')
print(a)
print(b)
Why does one method work and the other does not?
Method 1 does not work because by the time 'b' is set equal to 'a', the value that was initially stored in 'a' has been lost because it was overwritten by the value at 'b'. Method 2 works because the original value of 'a' is preserved by the variable 'temp'.
# Exercise: Using temporary variables, switch the following data so that
# it makes sense. Print the new variables to the console.
dog_legs = 0
human_legs = 4
goldfish_legs = 2
#####NEW CODE AFTER THIS LINE###
# Use a temporary variable to store the value of dog_legs.
temp = dog_legs
# Rotate the variable values, then set the value of dog_legs to its correct variable.
dog_legs = human_legs
human_legs = goldfish_legs
goldfish_legs = temp
# Print the correct number of legs for each animal.
print("Number of legs:")
print('Dog:', dog_legs)
print('Human:', human_legs)
print('Goldfish:', goldfish_legs)
def roundToTwoPlaces(num): # Define a function named "roundToTwoPlaces" that takes in a value and defines it as variable "num".
return round(num, 2) # round is a built in function that rounds a number to x number of decimal places.
print(roundToTwoPlaces(4.325456463)) # Run the function
# Exercise: Write a function that will round a number to 'n' digits.
# Test your function using a print statement. Make sure the print
# statement is outside of your function.
def roundToNPlaces(number, n):
return round(number, n)
print(roundToNPlaces(2.435636723445, 4))
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
What do you see when you execute this code?
cat
10
-543
645365
656743
3
[-543, 1, 3, 4, 23, 31, 324, 435, 5435, 5665, 645365]
# Exercise: Write a function that takes in two lists as arguments.
# Your function must first find the max of both lists.
# It must return the product ('*') of the maxes.
# Test your function by printing to the console.
a = [3243, 645645, 54346]
b = [7, 3, 2]
def productOfMaxes(a,b):
maxA = max(a)
maxB = max(b)
return maxA*maxB
print(productOfMaxes(a,b))
# If 3 is equal to 10, print true. Otherwise, print false.
print(3==10)
# If the length of the text string 'abc' is 3 characters, print true. Otherwise, print false.
print(len('abc')==3)
# If the max of the list is less than 25, print true. Otherwise, print false.
print(max([10,40,53]) < 25)
# If 5 is not equal to 3, print true. Otherwise, print false.
print (5 != 3)
What is the output of the above code?
False
True
False
True
# Exercise: Using print statements, and built-in functions min(), max(),
# sum(), write some code that either evaluates to True or False.
a = [5, 2, 7, 1, 4]
b = True
c = [50, 31]
def trueOrFalse(a, b, c):
# If the max of a is positive and b is false, or the min of c is greater than 25 and the sum of a is positive, return true. Otherwise, return false.
if (((max(a)>0) and (b==False)) or ((min(c)>25) and (sum(a)>0))):
return True
else:
return False
print(trueOrFalse(a,b,c))
a=10
b=20
# If statement.
if(a>b):
print(a, 'is greater than', b)
# Else/If statement.
elif(a<b):
print(b, 'is greater than', a)
# Else statement.
else:
print("they're equal")
For the assigned values of variables a and b, what is the output?
20 is greater than 10
# Exercise: Change the values of a and b such that the other two conditions
# are met.
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")
a=25
b=5
if(a>b):
print(a, 'is greater than', b)
elif(a<b):
print(b, 'is greater than', a)
else:
print("they're equal")
a=15
b=15
if(a>b):
print(a, 'is greater than', b)
elif(a<b):
print(b, 'is greater than', a)
else:
print("they're equal")
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'))
What is the output of the above code?
jfkdla;s
abcfdsafdasg
None
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?')
print(can_make_cake(10, True, False, True))
What is the following line implying?
print(can_make_cake(10, True, False, True))
You can make cake with 10 eggs, flour, no milk, and almond milk.
# Exercise: Redo the above call to the function with 0 eggs
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?')
print(can_make_cake(0, True, False, True))
# Exercise: Write a function to determine if the absolute value of the
# minimum in a list is odd. If it is odd, print 'odd' to the console. Else,
# print 'even' to the console
a = [-35423,-5432654,-352435,53252]
def abs_of_min_is_odd(a):
###Your logic here###
if(min(a)%2==1):
return 'odd'
elif(min(a)%2==0):
return 'even'
print(abs_of_min_is_odd(a))
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))
list1=[1,2,3]
list2=[4,5,6]
list_of_lists=[list1,list2]
print(list_of_lists[1][2])
# Add the following lines of code one by one to the above code and add comments
# to explain what they mean.
# Prints the first list within the array that contains multiple lists.
print(list_of_lists[0])
# Prints the second list within the array that contains multiple lists.
print(list_of_lists[1])
# Prints the second element of the first list within the array that contains
# multiple lists.
print(list_of_lists[0][1])
# Prints the third element of the first list within the array that
# contains multiple lists.
print(list_of_lists[0][2])
# Prints the first element of the second list within the array that
# contains multiple lists.
print(list_of_lists[1][0])
# Exercise: You are analyzing sports teams. Members of each team are stored in
# a list. The Coach is the first name in the list, the captain is the second
# name in the list, and other players are listed after that. These lists are
# stored in another list, which starts with the best team and proceeds through
# the list to the worst team last.
# Final is between the two teams. Complete the function below to select the
# captain of the losing team and print to console.
real_madrid=['zidane', 'ramos', 'marcelo']
barcelona=['valverde', 'messi', 'pique']
teams = [real_madrid, barcelona]
def losing_team_captain(team_list):
#######Your code here###########
return teams[1][1]
print (losing_team_captain(teams))
# Exercise: The next iteration of Mario Kart will feature an extra-infuriating
# new item, the Purple Shell. When used, it warps the last place racer into
# first place and the first place racer into the last place.
# Complete the function below to implement the Purple Shell's effect. Pass the
# list 'standings' into your function and print the updated standings to the
# console. (Hint: Keep in mind the concept of temporary variables from a
# previous lesson)
standings=['mario', 'bowser', 'luigi','peach']
def purple_shell(racers):
#######YOUR CODE HERE##########
temp = standings[0]
standings[0] = standings[3]
standings[3] = temp
purple_shell(standings)
print(standings)
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]))
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)
# Exercise: Your lucky number is 7. You really like 7. You even like numbers
# divisible by 7 (do I smell a modulus operator?). Write a function that counts
# the frequency of numbers divisible by 7 in a list, and print that frequency
# to the console.
list=[1,21,7,-14,49,74,700]
def seven_counter(my_list):
###Your code here###
counter = 0
for element in my_list:
if element%7 == 0:
counter += 1
return counter
print(seven_counter(list))
# Tag, colon, value
capitals={'United States': 'DC', 'France': 'Paris', 'Mexico': 'DF'}
populations={'UMD':40000, 'Towson': 30000, 'UMBC': 20000}
print(populations.get('UMD'))
############################DO NOT TOUCH THIS CODE#########################
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.
deck = {'h': hearts, 's': spades, 'c': clubs, 'd': diamonds}
#Print a view of dictionary (key, value) pairs
print(deck)
#Print a view of all of the keys
print(deck.keys())
#Print a view of all of the values
print(deck.values())
#Remove all of the spades from the deck
deck.pop('s')
#Add a new entry to the dictionary with key 'j' and values 'joker1' and 'joker2'
deck.update({'j':['joker1', 'joker2']})
#Clear the dictionary
deck.clear()
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(m.gcd(75348597,979531683))
print(m.cos(10))
# Here's a more advanced example.
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()
What is the output?
Randomized scatter plots
# Exercise. Google the functions used by the matplotlib and numpy libraries to
# get an understanding of the flow of the code. In the blank code space below,
# import the matplotlib and numpy libraries and make any plot of your own. Use
# the above examples and the documentation pages to help you.
import matplotlib, numpy as np
import matplotlib.pyplot as plt
School = ['UMD','Towson','UMBC']
Population = [40000,30000,20000]
plt.bar(School, Population)
plt.xlabel('School')
plt.ylabel('Population')
# 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
Part One
Let's get acquainted with this dimuon data set. Look at the cells above to find the answers to the following questions:
In the table above, what do you think each of the column headings represent?
The columns are different aspects of each run, in the order:
Run,Event,Type1,E1,px1,py1,pz1,pt1,eta1,phi1,Q1,Type2,E2,px2,py2,pz2,pt2,eta2,phi2,Q2
How many events does this data set contain?
475465
# 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")
Paste the output of the above code to your HW.
Text(0,0.5,'number of events')
Homework 10:
'''Deep Dreaming in Keras. Run the script with: ``` python deep_dream.py path_to_your_base_image.jpg prefix_for_results ``` e.g.: ``` python deep_dream.py img/mypic.jpg results/dream ``` ''' from __future__ import print_function from keras.preprocessing.image import load_img, save_img, img_to_array import numpy as np import scipy import argparse from keras.applications import inception_v3 from keras import backend as K parser = argparse.ArgumentParser(description='Deep Dreams with Keras.') parser.add_argument('base_image_path', metavar='base', type=str, help='Path to the image to transform.') parser.add_argument('result_prefix', metavar='res_prefix', type=str, help='Prefix for the saved results.') args = parser.parse_args() base_image_path = args.base_image_path result_prefix = args.result_prefix # These are the names of the layers # for which we try to maximize activation, # as well as their weight in the final loss # we try to maximize. # You can tweak these setting to obtain new visual effects. settings = { 'features': { 'mixed2': 0.2, 'mixed3': 0.5, 'mixed4': 2., 'mixed5': 1.5, }, } def preprocess_image(image_path): # Util function to open, resize and format pictures # into appropriate tensors. img = load_img(image_path) img = img_to_array(img) img = np.expand_dims(img, axis=0) img = inception_v3.preprocess_input(img) return img def deprocess_image(x): # Util function to convert a tensor into a valid image. if K.image_data_format() == 'channels_first': x = x.reshape((3, x.shape[2], x.shape[3])) x = x.transpose((1, 2, 0)) else: x = x.reshape((x.shape[1], x.shape[2], 3)) x /= 2. x += 0.5 x *= 255. x = np.clip(x, 0, 255).astype('uint8') return x K.set_learning_phase(0) # Build the InceptionV3 network with our placeholder. # The model will be loaded with pre-trained ImageNet weights. model = inception_v3.InceptionV3(weights='imagenet', include_top=False) dream = model.input print('Model loaded.') # Get the symbolic outputs of each "key" layer (we gave them unique names). layer_dict = dict([(layer.name, layer) for layer in model.layers]) # Define the loss. loss = K.variable(0.) for layer_name in settings['features']: # Add the L2 norm of the features of a layer to the loss. if layer_name not in layer_dict: raise ValueError('Layer ' + layer_name + ' not found in model.') coeff = settings['features'][layer_name] x = layer_dict[layer_name].output # We avoid border artifacts by only involving non-border pixels in the loss. scaling = K.prod(K.cast(K.shape(x), 'float32')) if K.image_data_format() == 'channels_first': loss += coeff * K.sum(K.square(x[:, :, 2: -2, 2: -2])) / scaling else: loss += coeff * K.sum(K.square(x[:, 2: -2, 2: -2, :])) / scaling # Compute the gradients of the dream wrt the loss. grads = K.gradients(loss, dream)[0] # Normalize gradients. grads /= K.maximum(K.mean(K.abs(grads)), K.epsilon()) # Set up function to retrieve the value # of the loss and gradients given an input image. outputs = [loss, grads] fetch_loss_and_grads = K.function([dream], outputs) def eval_loss_and_grads(x): outs = fetch_loss_and_grads([x]) loss_value = outs[0] grad_values = outs[1] return loss_value, grad_values def resize_img(img, size): img = np.copy(img) if K.image_data_format() == 'channels_first': factors = (1, 1, float(size[0]) / img.shape[2], float(size[1]) / img.shape[3]) else: factors = (1, float(size[0]) / img.shape[1], float(size[1]) / img.shape[2], 1) return scipy.ndimage.zoom(img, factors, order=1) def gradient_ascent(x, iterations, step, max_loss=None): for i in range(iterations): loss_value, grad_values = eval_loss_and_grads(x) if max_loss is not None and loss_value > max_loss: break print('..Loss value at', i, ':', loss_value) x += step * grad_values return x """Process: - Load the original image. - Define a number of processing scales (i.e. image shapes), from smallest to largest. - Resize the original image to the smallest scale. - For every scale, starting with the smallest (i.e. current one): - Run gradient ascent - Upscale image to the next scale - Reinject the detail that was lost at upscaling time - Stop when we are back to the original size. To obtain the detail lost during upscaling, we simply take the original image, shrink it down, upscale it, and compare the result to the (resized) original image. """ # Playing with these hyperparameters will also allow you to achieve new effects step = 0.01 # Gradient ascent step size num_octave = 3 # Number of scales at which to run gradient ascent octave_scale = 1.4 # Size ratio between scales iterations = 20 # Number of ascent steps per scale max_loss = 10. img = preprocess_image(base_image_path) if K.image_data_format() == 'channels_first': original_shape = img.shape[2:] else: original_shape = img.shape[1:3] successive_shapes = [original_shape] for i in range(1, num_octave): shape = tuple([int(dim / (octave_scale ** i)) for dim in original_shape]) successive_shapes.append(shape) successive_shapes = successive_shapes[::-1] original_img = np.copy(img) shrunk_original_img = resize_img(img, successive_shapes[0]) for shape in successive_shapes: print('Processing image shape', shape) img = resize_img(img, shape) img = gradient_ascent(img, iterations=iterations, step=step, max_loss=max_loss) upscaled_shrunk_original_img = resize_img(shrunk_original_img, shape) same_size_original = resize_img(original_img, shape) lost_detail = same_size_original - upscaled_shrunk_original_img img += lost_detail shrunk_original_img = resize_img(original_img, shape) save_img(result_prefix + '.png', deprocess_image(np.copy(img))) © 2018 GitHub, Inc. Terms Privacy Security Status Help Contact GitHub Pricing API Training Blog About
Finds and enhances patterns in images to create complicated distortions. Can be looped to enhance effects.