HONR269L Logbook
***************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
COMMAND
tar cf file.tar files
DESCRIPTION
Creates file.tar containing files
sed -i 's/original/new/g' file.txt
Uses Stream EDitor to replace original with new in file.txt
head -n file
Outputs just the first n lines of a file for previewing
clear
Clears the current terminal window
history
Shows a history of all the commands you have typed in order for the current terminal.
wget "url"
Downloads a file at the given url to the current directory.
mv source dest
Moves a source file to the dest directory
tar xf file.tar
Un-packages file.tar inside its current directory
nautilus .
Opens the pwd in the System file viewer
cat files >> file
Concatenates the files into the file
C++ Programming
main.cpp
//Imports input/output libraries used by the cout command
#include <iostream>
//Declares the program namespace once so that it doesn't need
//to be attached to each individual command
using namespace std;
//Method header (main method - driver for any program)
//Returns an integer value
int main() {
//Prints Hello World! followed by an end line.
cout << "Hello World!" << endl;
//Exits the program by exiting main method.
return 0;
}
g++ file.cpp
Compiles the C++ file into assembler language so that it can be executed.
Creates a new file > a.out
variables.cpp
#include <iostream>
using namespace std;
int main() {
cout << "hello world" << endl;
//Initializes an int variable and sets it to the value 2
int i=2;
//Outputs "i = 2"
cout << "i = " <<i<<endl;
//Outputs "a = 3.3"
double a=3.3;
cout << "a = " <<a<<endl;
//Sets j to be the product of a and i
int j = a*i;
//Outputs "a*i = 6.6" because j is an int and will truncate the decimal
cout << "a*i = "<<j<<endl;
return 0;
}
increment.cpp
#include <iostream>
using namespace std;
int main() {
int n=10;
cout << "n is "<<n<<endl;
//Decrements n and sets it to 9.
n--;
cout<<"n is now "<<n<<endl;
//Increments n and set it back to 10
n++;
cout<<"n is now "<<n<<endl;
return 0;
}
C++ probably got its name from being a higher level (incremented) cousin to the programming language C
boolean.cpp
#include <iostream>
using namespace std;
int main() {
bool prop;
//Sets prop to true (1) because 5 is greater than 1
prop = (5>1);
cout<<"prop is "<<prop<<endl;
//Sets prop to false (0) because 1 is not greater than 5
prop = (1>5);
cout<<"prop is "<<prop<<endl;
//Sets prop to true (1) because 1 does not equal 5
prop = (1 != 5);
cout << "prop is " <<prop<<endl;
return 0;
}
loops.cpp
#include <iostream>
using namespace std;
int main() {
int n=10;
//Prints out n until it <= 0. Prints 10 then 9 then 8 then ...
while(n>0) {
cout<<"n is "<<n<<endl;
n--;
}
return 0;
}
for.cpp
#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--) {
cout<<"n is "<<n<<endl;
}
// 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;
//Uncommenting returns the following error:
//for.cpp: In function 'int main()':
//for.cpp:16: error: name lookup of 'n' changed for ISO 'for' scoping
//for.cpp:16: note: (if you use '-fpermissive' G++ will accept your code)
return 0;
}
rewrite.cpp
#include <iostream>
using namespace std;
int main() {
int m=0;
for(int n=0; n<10; n++) {
// this is the slow (or outer) loop
cout << "n is " << n << ": ";
for(int m=0; m<=n; m++) {
// 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;
}
// now the fast loop has finished and the slow loop can
// continue with the current iteration
cout << endl;
}
return 0 ;
}
logic.cpp
#include <iostream>
using namespace std;
int main() {
int n = 10;
//Continuously running code block that runs until n is less than 10. In this implementation, the while block will
//run once because the program will exit at the end of the first run.
while (n>=10) {
//If n is greater than 5 the first part of the following block will run otherwise the second part will run.
if(n>5) {
cout<<"n is "<<n<<endl;
}
else {
cout<<"n = "<<n<<endl;
//Decrements n
n--;
}
//Ends program execution
return 0;
}
}
pointers.cpp
#include <iostream>
using namespace std;
int main() {
int i = 10;
//Prints out the memory address of the local variable i
cout << "The memory address of i is " << &i << "\n";
//Prints out the memory address of the local variable i followed by its data
cout << "The data stored at memory address " << &i << " is " << i << "\n";
//Creates a new pointer variable p that stores the memory address of i
int* p = &i;
//Prints out the memory address p is pointing to
cout << "The value of p is " << p << "\n";
cout << "We say that p 'points at' the memory location referenced by address " << p << "\n";
//*p will retrieve the data of the pointer by retrieving the data from the memory address
cout << "The data stored at memory address " << p << " is " << *p << "\n";
return 0;
}
program1.cpp
/*PROGRAM 1*/
#include <iostream>
using namespace std;
int main(){
int i = 10;
//Sets j to the value 10 and stores it at a new memory location
int j = i;
cout << "i= " << i << " and j= " << j << "\n";
//Sets i to 5 and j remains unchanged as 10
i=5;
cout << "i= " << i << " and j= " << j << "\n";
//Sets j to 1 and i remains unchanged as 5
j=1;
cout << "i= " << i << " and j= " << j << "\n";
return 0;
}
program2.cpp
/*PROGRAM 2*/
#include <iostream>
using namespace std;
int main(){
//Sets i to 10
int i = 10;
//Sets p as the memory address of i
int* p = &i;
//Prints out the value of i and the value of the data stored at the memory addressed referenced by p (p -> i -> 10)
cout << "i= " << i << " and *p= " << *p << "\n";
//Sets i to 5 and p remains unchanged, still the same memory address
i=5;
//Prints out the value of i and the value of the data stored at the memory addressed referenced by p (p -> i -> 5)
cout << "i= " << i << " and *p= " << *p << "\n";
//Changes the data at the memory location referenced by p to 1
*p=1;
//Prints out i as 1 now that the data has been changed via pointer p
cout << "i= " << i << " and *p= " << *p << "\n";
return 0;
}
objectsandpointers.cpp
#include <iostream>
using namespace std;
int main(){
//Sets new pointer variable p to the memory address of a new integer object with value 5
int* p = new int(5);
//Prints out address of the newly created object
cout << "p points at address " << p << "\n";
cout << "The data stored in address " << p << " is " << *p << "\n";
//Changes the data at memory address referenced by p to 10
*p = 10;
cout << "Now the data stored in address " << p << " is " << *p << "\n";
return 0;
}
Awk/ Date/ Grep Commands (Shell Scripting)
#!/bin/tcsh
#Sets month variable to the second element of the return value of the date command
#Date returns the current system date and time
#awk is used to filter using a regular expression
set month = `date | awk '{print $2}'`
echo $month
#Sets tmpday variable to the third element of the return value of the date command
set tmpday = `date | awk '{print $3}'`
echo $tmpday
#Adds a space before the day to make sure the final command still works for single digit days if applicable
if ($tmpday < 10) then
set today = " $tmpday"
else
set today = $tmpday
endif
echo $today
#grep used to filter files so they contain the month and day
ls -lat | grep "$month $today"
Arrays C++
#include <iostream>
using namespace std;
int main() {
//Initializes an array with elements: 1, 2, 3
int ii[3] = {1,2,3};
int j=0;
//Prints out element in the array using index j, incrementing
//j at the end of the loop cycle
while (j<3) {
cout <<" ii of "<<j<<" is "<<ii[j]<<endl;
j++;
}
//Initializes a two dimensional array with 2 rows and 3 columns
//[1 2 3] <-- matrix representation
//[4 5 6]
int LL[2][3] = {1,2,3,4,5,6};
j=0;
int k;
//Prints out each element in the array at row j, col k using
//an inner loop
while (j<2) {
k=0;
while (k<3) {
cout<<" LL of "<<j<<" "<<k<<" is "<<LL[j][k]<<endl;
k++;
}
j++;
}
return 0;
}
Comments
#include <iostream>
using namespace std;
// Multiline comment example
/************************************************\
* *
* Arrays *
* This program demonstrates arrays *
* *
\************************************************/
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;
j++;
}
// a loop ot demonstrate 2D arrays
int LL[2][3] = {1,2,3,4,5,6};
j=0;
int k;
while (j<2) {
k=0; // do not forget to initialize k here
while (k<3) {
cout<<" LL of "<<j<<" "<<k<<" is "<<LL[j][k]<<endl;
k++;
}
j++;
}
return 0;
}
Reading Data
#include <iostream>
//File reading library for C++
#include <fstream>
using namespace std;
int main() {
//Initializes an ofstream, that can be used to work with files
ofstream myfile;
//Opens a file using ofstream object
myfile.open("example.txt");
//Appends the file with the string "write some junk."
myfile<<"write some junk.";
//Closes the stream which saves the file
myfile.close();
return 0;
}
Multiple Source Files
/* MAIN.CPP */
#include <iostream>
#include <fstream>
// include the program dotprod.cpp so that we can find the dot_prod function
#include "dotprod.cpp"
#include "scalarmult.cpp"
using namespace std;
int main () {
// declare the vectors as arrays of type double
double vector1[3];
double vector2[3];
// Declare scalar variable as type double.
double scalar;
// 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;
//Read the scalar value
infile>>scalar;
// close the input file
infile.close();
cout<<"The scalar multiple is "<<scalar<<endl;
// call the dot_prod function from dotprod.cpp
dot_prod(vector1,vector2);
scalar_mult(scalar,vector1);
scalar_mult(scalar,vector2);
return 0;
}
/* DOTPROD.CPP */
#include <iostream>
using namespace std;
double scalar_mult(double v1[3],double v2[3]) {
double dotdot;
//Formula for calculating dot product for 3 dimensional vectors
dotdot = v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2];
//Outputs the dot product
cout<<" The dot product is "<<dotdot<<endl;
return 0;
}
/* SCALARMULT.CPP */
#include <iostream>
using namespace std;
double dot_prod(double scalar,double v1[3]) {
double dotdot;
//Formula for calculating dot product for 3 dimensional vectors
v1[0] = v1[0]*scalar;
v1[1] = v1[1]*scalar;
v1[2] = v1[2]*scalar;
//Outputs the dot product
cout<<"The scalar multiple is "<<v1[0]<<","<<v1[1]<<","<<v1[2]<<")"<<endl;
return 0;
}
Random Numbers srand and rand
#include <stdio.h>
#include <stdlib.h> /* srand, rand */
#include <time.h>
using namespace std;
int main(){
cout << "Random Number" << rand()%100; /* This will print a random number between [0,100). */
return 0;
}
HW7
Running MadGraph with the command ./bin/mg5_aMC
Note: You must be in the correct directory containing the script
Bypass configuration options by pressing enter. Will use default values
Generating a process
MG5_aMC> launch MY_FIRST_MG5_RUN
Unzip .lhe file from the run
lhe2root.py python code that will be used to generate the root file.
Run the python code using the following command structure "python <python file> <arguments>"
1. Read the final file.
2. Looks for the Monte Carlo ID for the top quark .
3. Fill a histogram with all the events with a top quark in them .
4. Print the histogram as topevents.C and topevents .root.
File > Save As > Choose .C type
5. Open the topevents.root and change the color of the histogram.
View > Editor and then click on specific region for options
HW8
HZZ4LeptonsAnalysisReduced->MakeClass("HiggsAnalysis") generates HiggsAnalysis.C (C++ class) and HiggsAnalysis.h (C++ header) files which are used inside root. You can run the loop inside the root terminal.
Modified HiggsAnalysis.C code
//Lets the compiler know about the definition of the HiggsAnalysis class
#define HiggsAnalysis_cxx
//Includes the header information from the generated HiggsAnalysis header file
#include "HiggsAnalysis.h"
//Includes three libraries that allow us to work with the root browser (canvas, style, etc..)
#include <TH2.h>
#include <TStyle.h>
#include <TCanvas.h>
//Defines a method called loop under the HiggsAnalysis namespace with no return type
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
//Makes sure the fChain is not empty
if (fChain == 0) return;
//Gets the total number of data entries from the fChain as a Long_64_t
Long64_t nentries = fChain->GetEntriesFast();
//Initializes two new Long64_t type variables and sets their values to 0.
Long64_t nbytes = 0, nb = 0;
//Creates a new root file that will hold the histograms
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
//Defines three new histograms. Two for the first four leptons mother particle and one for the Higgs
TH1F* Z_ee = new TH1F("Z_ee", "Di-electron candidate invariant mass", 200, 0, 200);
TH1F* Z_ee2 = new TH1F("Z_ee2", "Di-electron candidate invariant mass 2", 200, 0, 200);
TH1F* Z_ee3 = new TH1F("Higgs", "Higgs Boson", 200, 0, 200);
//Initializes variables to hold information about mass, momentum and angle
double el1mt = 0.0;
double el1pt = 0.0;
double el1eta = 0.0;
double el2mt = 0.0;
double el2pt = 0.0;
double el2eta = 0.0;
double el3mt = 0.0;
double el3pt = 0.0;
double el3eta = 0.0;
//For loop used to traverse through every entry of raw data
for (Long64_t jentry=0; jentry<nentries;jentry++) {
//Temp variable used to reference the current entry
Long64_t ientry = LoadTree(jentry);
//Jumps to next entry if the entry is empty
if (ientry < 0) break;
//Updates nbytes and nb to show the accurate number of bytes
nb = fChain->GetEntry(jentry); nbytes += nb;
// if (Cut(ientry) < 0) continue;
//Initializes TLorentzVector objects to hold information about the first two leptons
TLorentzVector el1, el2;
//Sets the momentum, theta angle, phi angle, and mass for the TLorentzVector from the Tree that was loaded
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);
//Gets the “zCandidate” by combining the information from the two leptons produced
TLorentzVector zCandidate = el1 + el2;
//Adds the zCandidate mass to the first histogram
Z_ee->Fill(zCandidate.M());
//Prints out the mass for first lepton
el1mt = el1.Mt();
cout << el1mt << endl;
//Does same thing as above
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());
el2mt = el2.Mt();
cout << el2mt << endl;
//Combines the two derived zCandidates from this entry to get the Higgs
TLorentzVector zCandidate3 = zCandidate + zCandidate2;
//Adds Higgs mass from this entry to the Histogram
Z_ee3->Fill(zCandidate3.M());
el3mt = el3.Mt();
cout << el3mt << endl;
}
//Writes the three histograms to the root file that was opened
Z_ee->Write();
Z_ee2->Write();
Z_ee3->Write();
//Finishes output explicitly which saves the file
output->Close();
}
Give the object type HiggsAnalysis a variable name and run its methods using the dot notation and the specific method name.
The loop will traverse the raw data of events and fill the histograms and then write the histograms. The histograms are viewable in the the TBrowser.
HW9
Python Syntax Notes
# Initialize pandas and zebras variables to 10 and 20 respectively. Then
# adds them together and stores their sum in a variable called
# total_animals_in_zoo and then uses the Python native function print() to
# print the sum as standard output.
pandas=10
zebras=20
total_animals_in_zoo=pandas+zebras
print(total_animals_in_zoo)
Temp Variables
#####Method 1########
# Creates two lists and fills them with values: 1,2,3 and cat,dog,fish
a = [1, 2, 3]
b = ['cat', 'dog', 'fish']
# Reassigns variable a to the value of b
a=b
# Reassigns variable b to the value of a which was recently changed to the
# value of b. This line effectively changes nothing.
b=a
# Prints the contents of both lists
print('Method 1')
print(a)
print(b)
#####Method 2########
a = [1, 2, 3]
b = ['cat', 'dog', 'fish']
# With the introduction of a temp variable the original value of a when the
# variable a is reassigned to the value of b
temp = a
a = b
b = temp
print('Method 2')
print(a)
print(b)
Functions
# Function definition that takes in a number parameter and returns that
# number rounded to two decimal places
def round_to_two_places(num):
return round(num, 2)
print(round_to_two_places(4.325456463))
Built In Functions
Booleans and Conditionals
# Prints false because 3 does not equal 10
print(3==10)
# Prints true because ‘abc’ is 3 characters long
print(len('abc')==3)
# Prints false because the max of the list is 53 which is greater than 25
print(max([10,40,53]) < 25)
# Prints true because 5 does not equal 3
print (5 != 3)
Modulus Operator
a = [-35423,-5432654,-352435,53252]
def abs_of_min_is_odd(list):
if(abs(min(list))%2 == 0) :
print(‘even’)
else :
print(‘odd’)
abs_of_min_is_odd(a)
# Output: even
Lists
def select_third_element(my_list):
# len() determines the length of the list. Returns None if there is no third
# element
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])
# Output: [1,2,3] - list 2
print(list_of_lists[0])
# Output: [4,5,6] - list 1
print(list_of_lists[1])
# Output: 2 - list 1, second element
print(list_of_lists[0][1])
# Output: 3 - list 1, third element
print(list_of_lists[0][2])
# Output: 4 - list 2, first element
print(list_of_lists[1][0])
Loops
# Iterates through every element in the list returning true if 7 is passed
# otherwise returns False when the loop finishes one traversal
def list_contains_seven(my_list):
# iterates through every item in the list referencing the current item as
# ‘element’
for element in my_list:
if element ==7:
return True
return False
print(list_contains_seven([6,14,5,7]))
# Output: True
print(list_contains_seven([6,14,5,9]))
# Output: False
# Prints the next 10 numbers from the original number while the numbers are
# under 10
def count_to_10(num):
while(num<10):
num=num+1
print(num)
count_to_10(0)
# Output: 1 \ 2 \ 3 \ 4 \ 5 \ 6 \ 7 \ 8 \ 9 \ 10
count_to_10(5)
# Output: 6 \ 7 \ 8 \ 9 \ 10
count_to_10(11)
# Output:
Dictionaries
# dictionary storing country capitals
capitals={'United States': 'DC', 'France': 'Paris', 'Mexico': 'DF'}
populations={'UMD':40000, 'Towson': 30000, 'UMBC': 20000}
# returns 40000, the value for the corresponding key ‘UMD’
print(populations.get('UMD'))
External Libraries
# Python library import statement
import math as m
# Prints out math lib’s value for pi and log base 2 of 32
print(m.pi, m.log(32, 2))
# Prints the greatest common denominator of the two numbers
print(m.gcd(75348597,979531683))
# Prints cos(10)
print(m.cos(10))
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
# Sets parametric range from 0 to 2 with step 0.01
t = np.arange(0.0, 2.0, 0.01)
# Creates a parametric function to graph
s = 1 + np.sin(2 * np.pi * t)
# Plots the data of the parametric function with parametric ranges
fig, ax = plt.subplots()
ax.plot(t, s)
# Sets info about the graph
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
plt.show()
HW10
Colab notebook the is able to connect to Google Drive to run python scripts and access assets stored in My Drive.
Info about DeepDream - https://en.wikipedia.org/wiki/DeepDream
Developed Images