HONR269L Research - Amphibious Quad-copter with Smooth Powered Air-Water Transition
5/10/19
I created a control panel and wired electrical components that will allow the actuators to be controlled by a potentiometer. I additionally installed a button which will be used for calibration. To calibrate before testing, the rotor will be lowered to the surface of the water and the button will be pressed to provide an important reference point: the air-water boundary.
5/1/19
Today, we were finally able to attach the linear actuators to the tank system as shown below. Ilya and I had to climb onto the tank to make the connections. The project is coming together well.
4/26/19
This Friday consisted of attaching metal brackets onto the linear actuators to secure them to 80/20 pieces. This consisted of sliding washers between the metal brackets and the linear actuators. This became rather tedious because of how small the gap was. I needed to use tape and tweezers to slide the washers in.
4/24/19
Today, we had to head to Home Depot to buy a hose, chlorine, chlorine dispenser, and door stoppers for the water tank. The door stoppers will help keep the tank in place, and the other items will be needed once we are ready to pour the water into the tank. Although I was not present, last Friday, a special moving crew had to come move this heavy tank from the Manufacturing Building to the Cypress Building. The operation involved a forklift and truck. The wheels were attached to the bottom of the tank after the forklift moved it off the ground. Although it may be difficult to see, the second picture shows some partially assembled 80/20 on top of the tank. Once assembled, the system will include the two linear actuators shown in third picture. This will allow the rotor to be lowered into the tank at different depths and speeds.
4/19/19
Good Friday, so we did not meet today.
4/17/19
Today, we continued drilling holes for the entirety of my 2 hour session. There is really nothing else that can be added in this log for today.
4/16/19
To move the tank pictured below on the left, we must first attach cast iron wheels to move it. The tank is very heavy; using all of our strength, Ilya and I were barely able to lift up one side of the tank to slide a piece of wood underneath the base. Attaching the wheels requires 16 hole to be drilled on the base of the tank for appropriate attachments to be made. I learned today that drilling into steel is a very tedious task.
4/12/19
I created another version of the bottom motor mount which is parametrized by an angle which will allow the motor to be tested at various angles with respect to the surface boundary between water and air.
4/10/19
Today, Ilya and I used bifilar pendulums to find the moments of inertia of the current amphibious quad-copter about its yaw, pitch and roll axes.
By giving the system an initial amplitude and measuring the period of oscillation, the following equation was used to find moment of inertia:
Where M = mass of the quad-copter, g = gravitational acceleration, T = period, b = distance between the two strings (from the above picture, b=r), and L = length of the strings.
Knowing the moments of inertia about the yaw, pitch, and roll axes will allow for accurate simulations of the quad-copter in flight.
4/9/19
The 80/20 frames were finally delivered allowing us to start building. We were additionally able to successfully 3D print the parts I designed on AutoDesk Inventor. Our current progress is shown below:
4/5/19
The 80/20 aluminum frames needed to start building the new setup did not come it yet so there was not much for us to do. So Ilya spent some time teaching me about helicopter dynamics. I learned that there is an asymmetry in forward helicopter flight since one blade moves in the direction of horizontal air flow while the other moves in the opposite.
A swash plate is used to create cyclic pitch between the blades creating a net thrust that allows the helicopter to move forwards, backwards, left and right. One may reason that tilting the swash plate backwards as shown below will cause the helicopter to move forward. However, due to gyroscopic effects, this will actually cause the helicopter to move left (out of the page with respect to the screen).
4/3/19
Using Autodesk Inventor, I created CAD drawings of 2 pieces that will be used to attach the force gauge to the motor. 2 separate pieces had to be made to allow screws to project from the bottom mount into the motor. I additionally learned that the electrical power graph from 3/27 displayed power as a negative number until about 1250 RPM due to an offset in the system that read in data. In reality, the initial power started at zero and increased with RPM.
3/29/19
Ilya was pretty busy with exams this week so I spent some time on my own familiarizing myself with analytical concepts related to rotor and propeller testing. Both coefficients are important indications of the performance of a motor. More specifically, the thrust coefficient shows how much energy extraction affects fluid flow (http://www.energy.kth.se/compedu/webcompedu/WebHelp/S9_Renewable_Energy/B2_Wind_Energy/C2_Introduction_to_Basic_Aerodynamics_of_wind_turbines/ID76_files/Definition_of_thrust_coefficient_CT.htm). The power coefficient shows the ratio of the power absorbed to the density of the ambient fluid surrounding the propeller (https://bondline.org/wiki/Basic_Engine_and_Propeller_Performance). The figure of merit quantifies the efficiency of the propeller.
Let C_T = thrust coefficient, C_P = power coefficient, FM = figure of merit, T = thrust, rho = fluid density, A = area swept out by propeller, V_tip = linear velocity of the tip of the rotor, omega = rotational velocity, and R = radius of the propeller. Then
3/27/19
I took the data collected yesterday and plotted several variables vs the RPM of the motor. Most of these results were expected; however, although subtle, I did not expect to see a decrease in the voltage. I am not currently aware what may have caused this.
3/26/18
Performed my first rotor test with Ilya with the rotor spinning in air using the old set up shown in one of the first logs for this semester. Additionally, I made a CAD file of a mount that will allow the torque cell to be mounted on the newer setup. This mount will connect to the bottom of the top beam shown on the setup drawn in the March 8th log. The new plan is to put the force gauge below the torque cell instead of putting it above as originally sketched.
3/13/19
Today, I began by attaching 3D printed parts to the torque cell. These were that parts that I previously made using Autodesk Inventor. Unfortunately, some of the dimensions were printed a tad small so I spent a lot of time sanding the center of each piece so that each nut could be attached to the center. Once each side of the torque cell is attached to the 3D printed pieces, the torque cell will be able to be attached to the setup that will be used to test the motors used to propel the quadcopter.
3/8/19
I began today by carrying four very heavy wheels from Glenn. L. Martin Hall to the Manufacturing Building. These wheels can support a weight of 3 tons and will be need to be attached to the tank which will contain the water for rotor testing to take place. Last week I mistaken and thought that the stepper motors were going to be used on the quadcopter. Today, I found out that the stepper motors will remain attached to the linear actuators which will lower the propellers into the water by precisely known distance and speed. Ilya and I had to go to the machine shop next to the wind tunnel to cut out a few more brackets. When we got back to the manufacturing building, I drilled holes into metal brackets which will be used to attach the linear actuators to the rest of the system shown in the sketch Ilya made below.
3/6/19
With the help of an Arduino, af988 driver, linear actuator, voltage supply, and oscilloscope, I varied the maximum speed and acceleration of the brush-less stepper motor attached to the actuator until the motor hit its stall torque. I varied these in such a fashion that allowed the motor to almost hit it maximum RPM before stalling. The motor had four stator coils which rotate the drive shaft 1.8 degrees per step. 200 steps are needed to rotate the drive shaft through one full rotation. This calibration will allow us to perform tests on the stepper motor we will use. In the mean time, Ilya used a drill press to drill holes in the metal brackets that were cut on Friday. The metal brackets allowed the linear actuator pictures below to be attached to various setups.
3/1/19
Today, in the engineering laboratory building, I helped cut metal pieces in the shapes shown below. These metal brackets will be used to help secure the apparatus used to take torque measurements. This took a long time and the band saw cut slowly, so unfortunately this procedure took up my whole 2 hour time block today.
2/27/19
Today, I used AutoDesk Inventor to CAD two mounting adapters which, once 3D printed, will allow the torque cell to be mounted between the force gauge and ESC shown below. Calibration of the torque cell was completed which will allow us to measure torque along the axis of the rotors. We will begin testing later this week. This will allow us to generate our own characteristic curves for the brushless motors, since little information about their specifications can be found online. Observing this torque as the rotor transitions in and out of water will provide very useful information pertaining to the effectiveness of smooth powered air-water transition. The current overarching goal is to create an automated system that independently adjusts the speed of each rotor, depending on the resistance experienced. That is, if one rotor contacts air while the other three are in water, its rotational speed will independently increase to compensate for the decrease in viscosity. This will allow the quad-copter to effectively move between the two mediums, even if there is a wave that causes the transition plane to be non-horizontal. Shown below is the current setup which will be modified in the future.
2/22/19
Along with Ilya, I set up everything needed to calibrate the toque cell so that calibration can be complete the next time we meet. Calibration will allow us to determine the mechanical power of the rotors. Test results will allow us to confirm predictions of the behavior of the rotor in air and water. Having an accurate model will allow us to more properly control the rotor through the two mediums. We will also be able to generate brushless motor characteristic curves which will be useful in future design. Research recently has been somewhat slow, which is why this logbook has been so brief; however, I hope for things to pick up soon, once calibration is completed.
2/20/19
I was supposed to finish setting up everything for the torque cell calibration; however, the snow day prevented me from coming in.
2/15/19
I started attaching lever arms to the torque cell so that it can be calibrated. This will allow us to measure the mechanical power of the rotors and determine brushless motor characteristic curves.
2/13/19
I met with Ilya Semenov, the grad student I will be working with. He had me solder a HX711 board from sparkfun.com and program an arduino so that a strain sensor could measure torque.
2/11/19
I went to presentation where Dr. Chopra's graduate students presented their research. I will be helping with a quadcopter that works in air and in water.
2/5/19
I got to meet Dr. Moody and Mr. Norton today at the Gravitational Research Lab in the Toll Physics Building. I was exposed to many of the lab's detectors and gravitational gradiometers. Mr. Norton had me learn more about the machine that they use to make fine and precise coils of wire. Although I find gravity interesting, I do not think this type of research is right for me. Right after leaving the lab, I went to Dr. Chopra's office to ask for a research opportunity in aerospace. I know Dr. Chopra from my involvement in the Gamera Solar club, and I had already previously asked him for future research opportunities so I was fairly confident he would say yes. For the remainder of the semester, I will be doing research related to aerospace engineering, most likely something to do with smart structures and/or rotor craft, since those are Dr. Chopra's primary research interests.
_____________________________________________________________________________________________________________________________________________________
HW9
MOVING to PYTHON and Machine Learning.
Introduction:
EXERCISE: What is the difference between CPU and GPU?
CPU à central processing unit à “brain” of computer
GPU à graphicsprocessing unit à displays graphics
This tutorial will serve as an overview of Python syntax and fundamentals to help you get started with Python for machine learning and deep learning.
In each section, you will first see the example code, then exercises based on the sample code for you to complete.
For those of you with coding experience, the syntax element should be helpful.
Get the Colaboratory App for GOOGLE.
In your google drive, add the app called "colaboratory."
Start a new notebook in that app "NONR268N-Python-Tutorial."
Syntax, Variables, and Numbers
The following is a basic example of variable declaration and computation. Take a look at it, then try the exercise below in your colab notebook.
Copy paste this code in the code box in the notebook.
NOTE: in Python, indentation is part of the language. So pay attention when copying and pasting.
pandas=10
zebras=20
total_animals_in_zoo=pandas+zebras
print(total_animals_in_zoo)
To execute the code, move your curser to [ ] in the left corner of the code block and click.
What is the output you get?
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
The following data structure is a list. A list can store any type of data structure, even other lists. In this example, I want to switch the values of lists 'a' and 'b'. Take a look at both methods, try to figure out why one works and the other doesn't.
#####Method 1########
a = [1, 2, 3]
b = ['cat', 'dog', 'fish']
a=b
b=a
print('Method 1')
print(a)
print(b)
#####Method 2########
a = [1, 2, 3]
b = ['cat', 'dog', 'fish']
temp = a
a = b
b = temp
print('Method 2')
print(a)
print(b)
Method 1 will not work because a will be assigned the values of b and then b had its values assigned to itself. In this case, both a and b are ['cat', 'dog', 'fish']. A third variable is needed to temporarily store the values of a so that b can receive them after a is assigned the values of b.
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
Functions
Functions allow us to execute the same lines of code, and therefore logic, multiple times in a program.
def round_to_two_places(num):
return round(num, 2)
print(round_to_two_places(4.325456463))
You'll notice a few things here
1. The keyword 'def' is used to define functions
2. The item takes in an argument 'num'
3. The function has a return statement
When I call the function 'round_to_two_places' in the print statement, the argument '4.325456463' is passed into my function and I return the truncated value.
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 round_to_n_places('''Hint: the arugment can take in two values seperated by a comma'''):
Built-in functions min(), max(), sort(), sum(), len()
As you have already noticed, the round function is a function built into the Python library.
Here are some other useful built-in functions with examples.
You've already seen the print() function used. I am wrapping the other built-in functions with a print statement, so they print to the console.
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?
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 product_of_maxes('''arguments here'''):
Booleans and Conditionals
Logic, logic, logic.
In Python, a logical statement can only ever evaluate to two values, True or False.
(Note: For equivalencies use the '==' operator, and not '!=')
print(3==10)
print(len('abc')==3)
print(max([10,40,53]) < 25)
print (5 != 3)
What is the output of the above code?
Exercise: Using print statements, and built-in functions min(), max(), sum(), write some code that either evaluates to True or False.
We use conditional statements to evaluate logic in a program and to dictate the program flow.
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")
For the assigned values of variables a and b, what is the output?
Exercise: Change values of a and b such that other two conditions are met.
Logic by itself is great, but most times we want it in a function. Let's combine the two concepts. You'll also see examples of the 'and' and 'or' keywords. They are equivalent to their meaning in the english language.
You'll also notice sometimes functions don't return anything.
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?
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
modulus operator ('%')
The modulus operator (mod) gives the remainder when you divide two numbers.
For example 10%3 is 1, 20%7 is 6, and 10%2 is 0.
Because of this, mod is a great tool to determine whether or not a number is even or odd. If you take any odd number, n, and % 2, you'll get 1. If you take an even number, and % 2, you'll get 0.
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('''arguments here'''):
Lists
An important thing to remember is that lists are indexed starting a 0. In contrast to, for example, MATLAB, which is indexed starting at 1.
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 one by one to the above code and add comments to explain what they mean?
print(list_of_lists[0])
print(list_of_lists[1])
print(list_of_lists[0][1])
print(list_of_lists[0][2])
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):
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):
Loops
loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,loop,
for loops
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]))
While loop
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):
Dictionaries
A dictionary is a data type in python that contains both a key and a value, similar to a real dictionary.
In real life, the key would be the literal word, and the value would be the definition.
In computing, we have more flexibility for our keys and values. For example, a key could be a certain jet from CMS, and the value could be a cross section.
capitals={'United States': 'DC', 'France': 'Paris', 'Mexico': 'DF'}
populations={'UMD':40000, 'Towson': 30000, 'UMBC': 20000}
print(populations.get('UMD'))
Using the methods described at https://www.programiz.com/python-programming/methods/dictionary (Links to an external site.) (Links to an external site.)
complete the following practice problems with dictionaries.
#########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.
#Print a view of dictionary (key, value) pairs
#Print a view of all of the keys
#Print a view of all of the values
#Remove all of the spades from the deck
#Add a new entry to the dictionary with key 'j' and values 'joker1' and 'joker2'
#Clear the dictionary
External Libraries
Sometimes, the built-in functionality of Python and its data structures aren't enough for what we want to accomplish. In that case, we must import external libraries.
In this example, I'll import the math library. An important part of using external libraries is reading the documentation.
https://docs.python.org/2/library/math.html (Links to an external site.)
is the documentation for the library.
Refer to it if you are unsure what the below code is doing.
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()
What is the output?
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()
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.
PYTHON FOR CMS ANALYSIS
# 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? How many events does this data set contain?
# 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.
HW8
Using relativistic kinematics - TLORENTZ vector class to get Z-boson and Higgs boson invariant mass
On your CERN VM
1. download http://hepcms-hn.umd.edu/~jabeen/Analysis/LHC-Higgs-Graviton.tgz
1. either through a web browser like Firefox or directly using the command
2. wget http://hepcms-hn.umd.edu/~jabeen/Analysis/LHC-Higgs-Graviton.tgz
2. google how to unpack this format ".tgz."
3. Make a new directory in the CMSSW area "CMSSW .../src/Higgs-mass"
4. Move the file to this directory and unpack it. You should see new root files in your directory.
5. Open one of the root files root file for example root -l output-xyz....-pythia6.root
6. Inside root, execute command HZZ4LeptonsAnalysisReduced->MakeClass("HiggsAnalysis")
1. What does this command do?
This commad makes a class called HiggsAnalysis which will be needed to analyze the data to successfully find the Higgs Boson.
2. You should see a "HiggsAnalysis.C" and a "HiggsAnalysis.h" file created. This is automatic C++ code created for you.
7. replace the code in HiggsAnalysis.C by the following code. and run it using the instructions in the code (red color comments below)
(more code outside of photo)
#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;
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;
}
Z_ee->Write();
output->Close();
}
Excercise:
1. in the above code add new TLorentzVector el3, el4 for the 3rd and 4th lepton and set their pt, eta phi, mass.
2. Add these two vectors to get a new vector TLorentzVector zCandidate2.
3. Add the two vectors zCandidate and zCandidate2 to get a new TLorentzVector Higgs.
4. DEfine a new histogram H_zz
1. TH1F* H_zz = new TH1F("H_zz", "ZZ candidate invariant mass", 200, 0, 300);
5. Fill the H_zz histogram with HIggs mass. (using Higgs.M() )
6. Write the H_zz histogram.
7. open the output file and paste the Z_ee and H_zz histograms in your HW file.
The graph for the Higgs Boson is the first graph displayed below:
HW7
Download and Install MadGraph
On the VM prompt open the web browser
[cms-opendata@localhost ~]$ firefox &
download MadGraph go to the website: http://madgraph.physics.illinois.edu/ (Links to an external site.)
xf "MG5_aMC_v2.2.3.tar.gz", will be saved in virtual machine.
move it to a new directory in the CMSSW area and expand the zipped file.
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
· To start madgraph
./bin/mg5_aMC
Note the dot at the beginning of the command.
· Let's start with the first point, how to generate a process:
MG5_aMC>generate p p > t t~
Note that space is mandatory between the particle names.
· To list all defined processes, type
MG5_aMC>display processes
· If you want to know more about particles and multiparticles present,
MG5_aMC>display particles
MG5_aMC>display multiparticles
· If you want to add a second process, use the add process command:
MG5_aMC>add process p p > W+ j, W+ > l+ vl
This adds a decay chain process, with the W+ decaying
leptonically.
· Now let us create the output of these processes that we will use to generate and calculate cross-sections:
MG5_aMC>output MY_FIRST_MG5_RUN
· To generate your events:
MG5_aMC> launch MY_FIRST_MG5_RUN
The newly generated events for the process pp→ ttbar are Here:
MY_FIRST_MG5_RUN/Events/run_01/ unweighted_events.lhe.gz
You can unzip the file:
gunzip unweighted_events.lhe.gz
A .lhe file includes all the information for the 1000 generated events. This is the file that we use to correctly simulate other physical effects that can change the properties (for example momentum distribution) when the newly generated particles interact with the detector material.
You can learn more about the use of this tool here: http://madgraph.physics.illinois.edu/ (Links to an external site.)
Now let us try to convert this file into our favourite format. (root.)
download this file to your working area in the VM.
I downloaded the file and saved it
python lhe2root.py MY_FIRST_MG5_RUN/Events/run_01/unweighted_events.lhe MY_FIRST_MG5_RUN.root
Note: I saved the file as myroot.root instead of MY_FIRST_MG5_RUN.root
root -l MY_FIRST_MG5_RUN.root
Opened myroot.root in root:
Opened TBrowser:
Here is a graph from root:
There are a total of 13 graphs in this folder
HW6
We will use a version of root associated with a CMSSW release.
cd to your CMSSW-.... /src directory on the VM
cmsenv
mkdir testRoot
exit root by typing
.quit (note the dot . before word quit )
Arrays in C++
Matrices and arrays are important in all kinds of physics, from quantum mechanics to error analysis with correlated uncertainties to geometrical optics.
In C++, the values in an array or a matrix are stored in adjacent memory spaces, and so you’ll often see pointers used.
For a matrix, you iterate through the first later indices before the earlier ones.
Try the following code to see how they are handled in C++.
NOTE: that the array index begins with 0.
#include <iostream>
using namespace std;
int main() {
int ii[3] = {1,2,3}; //initializes an array
int j=0;
while (j<3) {
cout <<" ii of "<<j<<" is "<<ii[j]<<endl;
j++;
} //prints out all three values of ii
int LL[2][3] = {1,2,3,4,5,6}; //initializes a 2D array
j=0;
int k;
while (j<2) {
k=0;
while (k<3) {
cout<<" LL of "<<j<<" "<<k<<" is "<<LL[j][k]<<endl;
k++;
}
j++;
} //prints the values of LL. The loop prints down the column first
return 0;
}
When you are working in a large collaboration, your code will be shared and edited by others. It is very important that your code have comment lines, to help in its intelligibility. When in doubt, add more comments. See below for the syntax.
#include <iostream>
using namespace std;
/************************************************\
* *
* 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;
}
You can tell the author of this tutorial is an old FORTRAN programmer due to the short variable names. However, your code will be much more readable if you use more descriptive names.
Try the following code. Discuss with your neighbor what each line does.
#include <iostream>
#include <fstream> //allows for information to be written and read from files
using namespace std;
int main() {
ofstream myfile; //needed to input information
myfile.open("example.txt");
myfile<<"write some junk.";
myfile.close(); //closes the file
return 0;
}
Declarations and combining code from different files
If many people are working on some code, or if you want to make your code organized so you can find pieces of it better, you may want to put some code in one file, some code in another file. When you do the compilation, you need to bring all the resulting binary together. However, when you use a function from one file in code in another file, you need to “declare” the function in that file so the compiler will know what to do when it reaches the line with the call. The declaration shows the compiler how much memory to reserve (and so needs the variables types for the inputs and outputs).
So, make two files, one main.cpp, like (note the inclusion of dotprod.cpp at the top of this file)
/* 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;
}
the other dotprod.cpp, like:
/* 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]; //dotdot is set equal to the equation of a dot product
cout<<" The dot product is "<<dotdot<<endl;
return 0;
}
Provide an input file: vectors.txt:
1 2 3
4 5 6
7
Then do:
g++ main.cpp
./a.out
Now try modifying main.cpp so that the third line of vectors.txt is read in as a double called 'scalar'. Print the value of this scalar after the lines printing the two vectors. Now, write and include a new program called 'scalarmult.cpp' which contains a function called scalar_mult. The scalar_mult function should take one vector and one scalar as inputs and print the vector multiplied by the scalar (recall that we just multiply each vector component by the scalar to do this). Finally, call the scalar_mult function on both vector1 and scalar, and vector2 and scalar after the call to dot_prod. The output should be:
scalarmult.cpp
#include <iostream>
#include <fstream>
#include "dotprod.cpp"
using namespace std
double scalar_mult(double vec[3], double scal){
int j = 0;
double output[3]
while(j<3){output[j] = vec[j] * scal;}
cout<<"The scalar multiple is "<<output<<endl;
_________________________________________
dotprod(vector1, vector2)
scalarmult(vector1, 7)
scalarmult(vector2, 7)
Vector 1 is (1,2,3)
Vector 2 is (4,5,6)
The scalar is 7
The dot product is 32
The scalar multiple is (7,14,21)
The scalar multiple is (28,35,42)
#include <iostream> //needed to printing outputs to the command line
using namespace std; //specifies that the C++ standard library will be used
int main() { //initializes main function which holds the code
int n = 10; //assigns n to integer value 10
while (n>=10) { //only runs when n>=10
if(n>5) { //only runs when n>5
cout<<"n is "<<n<<endl; //outputs “n is “ followed by the output of n
}
else {
cout<<"n = "<<n<<endl; //outputs “n = “ followed by the output of n
n--; //subtracts 1 from n
}
return 0; //returns 0
}
}
logic syntax at:http://www.cplusplus.com/doc/tutorial/control/
Pointers
#include <iostream>
using namespace std;
int main() {
int i = 10; //assigns i to integer value 10
cout << "The memory address of i is " << &i << "\n"; //outputs “The memory address of i is “ followed by the memory address of i
cout << "The data stored at memory address " << &i << " is " << i << "\n";
int* p = &i; //stores variable p to be memory address of i
cout << "The value of p is " << p << "\n";
cout << "We say that p 'points at' the memory location referenced by address " << p << "\n";
cout << "The data stored at memory address " << p << " is " << *p << "\n";
return 0;}
Recall that we earlier defined a variable as: “a way of reserving a memory location for the storage of information.” A useful comparison that is used often when introducing pointers in that of the mailbox. In this analogy, the mailbox itself is the memory location where data is stored and the data are the contents of the mailbox. When we code:
int i = 10;
we have picked out an empty mailbox, given it a handy nickname (in this case, “i”), told it what kind of data it will be used to store (an integer), and put some data (the integer 10) into the mailbox.
However, you know that computers can’t process names like a human can, so while calling our new integer “i” makes a programmer’s life easier, we also know that the computer must have a different, more numerical, way of referencing out variable. Specifically, each memory location (or mailbox) has a unique number that can be used to reference it. We can think of this like the mailbox number. In computer language, this number is called the ‘address’ of the memory location or the ‘memory address’. We can use c++ to check the address where our integer is located by using the ‘&’operator:
cout << “The memory address of i is “ << &i;
cout << “The data stored at memory address “ << &i << “ is “ << i;
An often-used feature of both C and C++ that seems odd at first is the pointer. A pointer is a type of variable which stores a memory address.
When we declare a pointer, we will set it equal to the address of some other variable. We must also specify the type of the variable that is stored in that address. If we want to declare a pointer to i, we code:
int* p = &i;
cout << “The value of p is “ << p;
cout << “We say that p ‘points at’ the memory location referenced by address “ << &i;
Notice that we declare a pointer to an integer with ‘int*’. How do you think we will declare a pointer to a double?
Pointers are unique because we are able to use another operator on them: *. The * operator tells the program to open the memory location ‘pointed at’ by p and retrieve the data inside. The program knows how to interpret this data because we specified the variable type when we declared the pointer.
cout << “The data stored at memory address “ << p << “ is “ << *p;
So, it seems like *p is just another way of referring to our integer i. However, as you continue to explore c++, you will begin to see the many uses of pointers. Consider the following programs:
/*PROGRAM 1*/
#include <iostream>
using namespace std;
int main(){
int i = 10;
int j = i;
cout << "i= " << i << " and j= " << j << "\n"; //outputs values of i and j
i=5;
cout << "i= " << i << " and j= " << j << "\n";
j=1;
cout << "i= " << i << " and j= " << j << "\n";
return 0;
}
/*PROGRAM 2*/
#include <iostream>
using namespace std;
int main(){
int i = 10;
int* p = &i;
cout << "i= " << i << " and *p= " << *p << "\n";
i=5;
cout << "i= " << i << " and *p= " << *p << "\n";
*p=1;
cout << "i= " << i << " and *p= " << *p << "\n";
return 0;
}
Why is the behaviour of Program1 different than that of Program2?
Recall that we said that the statement ‘int i = 10;’ will pick out a new mailbox and fill it with data.
In Program1, we’ve done this twice, creating two separate mailboxes, each of which stores an integer. When we declared the second mailbox, j, we set its data equal to “whatever data happens to be in mailbox i” by saying ‘int j = i’. However, we are still dealing with two different mailboxes; the contents of one is not affected by the contents of the other unless we explicitly code ‘i=j;’ or ‘j=i;’.
In Program2, however, we have only declared a single mailbox. i and *p were not simply initialized to the same value, they actually both reference the exact same data! Thus changing one will affect the other. This is one of the ways in which pointers can be more useful than simpler variables: they allow a programmer multiple ways to reference and modify data which is stored in a single memory location.
Finally, you may wonder if you can declare a pointer without having to point to an already used memory address. In c++, this can be accomplished using the ‘new’ construct. See the following example code:
#include <iostream>
using namespace std;
int main(){
int* p = new int(5);
cout << "p points at address " << p << "\n";
cout << "The data stored in address " << p << " is " << *p << "\n";
*p = 10;
cout << "Now the data stored in address " << p << " is " << *p << "\n";
return 0;}
Based on what we’ve already seen, we expect ‘int* p =’ to be followed by a memory address. Well, that’s exactly what ‘new int(5)’ is. Specifically, ‘new int(5)’ tells the program to find an empty memory location, stores the value ‘5’ in that location, and then returns the address of that location. So, ‘int* p = new int(5);’ is very similar to saying ‘int i = 5; int *p = &i’ with the big difference that when we use the ‘new’ construct there is no variable that references our data directly. The only way to view or modify the data stored by ‘int* p = new int(5);’ is by using the * operator on pointer p.
To test your understanding, try writing a similar code. In your code, use the ‘new’ construct to create a new pointer, ‘p1’, and point it at a new double with value ‘3.14’. Then, declare another pointer, ‘p2’, and point it at the same double as p1. Print the address pointed to by each pointer, and the value when the * operator is used on each pointer. Finally, multiply the value of the original double by 2 (you’ll have to use the * operator for this) and print the values of *p1 and *p2 again.
Computing
Write a small C++ code that shows examples of if and while logic statements. (START in class). Explain what the code does by using cout statements.
Alter the script given below so that it outputs the list of files that were updated within the current month. Note that the marks which surround date | awk '{print $2}' are not apostrophes, but rather a backticks. The backtick can be found on the same key as '~' (to the left of the '1/!' key). (Hint: the resulting script will be shorter and simpler :-))
HW 4 (completed October 9th)
HW4
Konrad Shire
To get started:
· log onto your VM and cd to CMSSW.../src/ directory.
· create a file main.cpp with emacs
· put the following into it
#include <iostream> //imports files needed for code to run
using namespace std;
int main() {
cout <<"Hello World!" << endl; //Print hello world to screen .
//followed by end line (endl)
return 0; //Returns 0
}
· exit emacs
· do: g++ main.cpp //compiles code
· do: ./a.out //prints code, a.out is an executable
Let’s look at what versions of c++ are contained in your CERN virtual machine. You can find it by doing
· find /usr/include/c++ -name "4*" //Finds files starting with 4* in the
. //directory usr/include/c++
Try
· g++ -dumpspecs //compiles dumpspecs
and look through the spew and see if you can see which one you are using.
Using:
You can find other header files, with other commands that come precoded by doing
· ls /usr/include/c++/4.4.4/ //lists files in each of the directories
· ls /usr/include/math.h
· ls /usr/include/bits/*math*.h
Variables
Write the following code, compile it, and run it.
#include <iostream>
using namespace std; //the std namespace is C++ library where things such as string or vector are declared. This code says we are going to use std
int main() { //Initializes integer method called main
cout << "hello world" << end; //Displays hello world
int i=2; //Stores value 2 to newly defined integer i
cout << "i = " <<i<<endl; //Displays i = 2
double a=3.3; //Stores value 3.3 to newly defined double a
cout << "a = " <<a<<endl;
int j = a*i; //Stores a*j as integer j (which is 6)
cout << "a*i = "<<j<<endl;
return 0; //returns 0
}
a*i equals 6 instead of 6.6 because it is initialized as an integer, meaning that it can not store decimal places. Thus, it truncates the decimal and is equal only to 6.
Some operations with numbers
#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;
}
What do the ++ and -- operations do? (and does this give you an idea why C++ has its name?)
The ++ operation adds 1 to n, and the – operation subtracts 1 from n. C++ has its name to signify the nature of the changes from C since ++ us the increment operator.
non-numeric variables 1
#include <iostream>
using namespace std;
int main() {
bool prop; //Initializes Boolean variable prop
prop = (5>1); //essentially, prop is true so we assign it //value 1
cout<<"prop is "<<prop<<endl; //displays “prop is “ and value of prop
prop = (1>5); //essentially, prop is false so we assign //it value 0
cout<<"prop is "<<prop<<endl;
prop = (1 != 5);
cout << "prop is " <<prop<<endl;
return 0;
}
Try this
#include <iostream>
using namespace std;
int main() {
int n=10;
while(n>0) {
cout<<"n is "<<n<<endl;
n--;
}
return 0;
}
#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--) {
//for loop will run 10 times (once for 10, 9,…,1). n //decreases by 1 every time for loop starts
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;
return 0;
}
You should find that a for loop is really just an equivalent and slightly more compact way of writing a while loop.
This is in fact a slightly more compact version of the while loop which produces the same output. It is a little more compact because the initial condition, final condition, and the increment are all specified on one line.
Try it yourself: rewrite the following code using for loops in place of the while loops.
#include <iostream>
using namespace std;
int main() {
int n=0, m=0;
while(n<10) { //stuff inside {} executes as long as n //is less than 10
// this is the slow (or outer) loop
cout << "n is " << n << ": ";
m=0;
while(m<=n) { //stuff inside {} executes as long as n //is less than or equal to n 10
// 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;
m++;
}
// now the fast loop has finished and the slow loop can
// continue with the current iteration
cout << endl;
n++;
}
return 0 ;
}
Debugging
The most primitive way to debug is to put many cout statements in your code. At the next level, you could even put a variable at the top of your code, perhaps
int idebug=0;
and then change this to
int idebug =1;
when you want to debug. Your cout statements could then look like:
if(idebug) cout<<"the current value of my variable is "<<my_variable_name<<endl;
October 4th
Had to set up the virtual machine on my new laptop. I am more comfortable with the Linux commands involved.
I only had some trouble with the last part involving downloading and the code involving root.
To download, type in "wget link"
HW2
What did it seem like the 'touch' command does?
It updates the time stamp of the previous file to current time stamp (current time)
Why do you think we include that '.' after the 'find' commands?
This specifies that we only want to find and search in the current directory
Based on the outputs from the four 'find' commands, what purpose do you think the '*' character serves? (Hint: it's called the "wildcard" character in linux jargon)
The "*" put after a word allows a search for that word in the name of the current directory
What did the 'rm' command do, and how do you think 'rm' differs from the 'rmdir' command we saw earlier? Warning: There is no way to undo the 'rm' command!
The rm command removes files and directories. The rmdir command removes directories, but only if they are empty
Finally, to test your understanding, why do you think that you should never run the command 'rm *'? True story: a thoughtless 'rm *' almost deleted all of Toy Story 2! (https://www.youtube.com/watch?v=8dhp_20j0Ys)
The rm removes everything in the current directory and cannot be undone. Therefore, it is best to stay away from this command to avoid accidentally permanently deleting everything
Try the following commands and answer the questions below.
echo "test"
echo "test1" > log.txt
ls
cat log.txt
echo "test2" > log.txt
cat log.txt
echo "test3" >> log.txt
cat log.txt
What do the '>' and '>>' operators do? How are they similar? How are they different?
The > operator will replace the things in a file with output of the previous command. The >> operator adds output to the current file. Both of these operators allow access to files
What is one potential danger of using the '>' operator?
The > operator will delete everything in the current operator permanently. This can be potentially dangerous when dealing with important files which require use of the >> operator. A typo may lead to a > appearing instead.
What do you expect to see if you run:
ls -l > log.txt
This takes everything in the current directory and replaces it with the information in log.txt
cat log.txt
This will display a calendar
Use google and collect 10 Linux commands that you think could be useful for you. For example, one such command would be to find and replace a word or phrase in a large text file.
Show that your commands actually work.
ls - shows everything in directory
cd - changes directory
pwd - writes full pathway of current directory
clear - clears directory
mkdir - makes a directory
history - shows history of commands
mv - moves file to another directory
whoami - prints user information
g++ compiles code
./a.out displays output of code
October 2nd
My new laptop will arrive today so I will finally be able to keep up with the class and do my work efficiently. My old computer is quite slow. I actually managed to get a lot of HW 4 done but then my computer froze for the last 5 - 10 minutes.
September 27th
We had another guest speaker who talked about image processing and photoshop. It was an interesting and controversial topic.
September 20th
We had a guest speaker from Google (online) who talked about software and deep learning.
September 18th
The first part of class we learned about relativity and natural units. All units can be in terms of electron volts. An electron volt it the amount of energy gained or lost by moving an electron across 1 volt of potential difference.
My computer runs very slow so I spent the computing part of class learning more about emacs and GNU. I will hopefully upgrade my laptop this weekend so I can learn and do linux operations mroe efficiently.
September 13th
Learned basic commands:
cd --> change directory
pwd --> writes full pathway of current directory
Went to the ispy website to view particle collision data from LHC. The first one I saw was a 4 lepton collision.