# Introduction

## Learning outcomes

This Jupyter notebook will introduce the idea of pressure in the context of fluid mechanics.
You will learn about the history of our understanding of pressure through the important measurements performed in the $17^{th}$ Century by an Anglo-Irish scientist. We will then delve deeper and look at some examples of the role of pressure in engineering flows.

The key areas are:
* Boyle's Law
* The Ideal Gas law
* Hydrostatics
* Pressure in moving fluids

## Description of Pressure

Fundamental to fluid flow is the concept of pressure which is defined as the force per unit area ($N/m^2$) which is exerted by or on a fluid. We can think of many everyday examples that involve pressure; atmospheric pressure, tyre pressure, water pressure, exam pressure. But what causes pressure?

At the molecular scale we can describe pressure (and by extension temperature) according to kinetic theory. In the video below a cube containing particles is shown. These represent gas molecules and their kinetic energy as they randomly jostle about can be averaged into a quantity called temperature.

As the particles collide with the walls of the cube a force acting outward is observed. If we add more energy to the cube the particles motion will become more energetic and the pressure and temperature will increase. We observe this behaviour on the macro scale for example as a hot-air balloon is inflated or as a bicycle tyre gets warm as it is inflated.

On a larger scale again we experience the result of a *pressure gradient* as wind. Air will move from regions of the atmosphere at a higher pressure than their surroundings, perhaps due to solar heating, to regions of lower pressure. This relationship between pressure and flow velocity is extremely important in fluid mechanics and we will explore it in detail in this module.

<video controls src="media/1.2/pressure_particles.mp4" width="700" loop=1/>

# Boyle's Law

Robert Boyle was born in Waterford in 1627 the fourteenth son of an English aristocrat, the first Earl of Cork. At age eight Boyle was sent to Eaton College in England and subsequently travelled around Europe developing an interest in the physical sciences. He settled in Dorset and begun to carry out a great many experiments. After a brief time in Ireland he moved to Oxford and, with his student Robert Hooke, begun to investigate the properties of air, in particular the 'spring of air'. Boyle and Hooke empirically observed (that is via experiment) that the volume of a gas varies inversely with the pressure of the gas. This observation became known as **Boyle's Law**.

Here is an image of his apparatus from the paper he published on this work [1]:

The J-tube apparatus , shown on the left, used by Boyle to measure volume and pressure. Shown also are other apparatus to measure other quantities such as the atmospheric pressure.

The apparatus consists of a glass tube in the shape of the letter 'J". The tube is closed at the short end and Boyle added mercury, a dense metal that is liquid at room temperature, to the open long end which resulted in the compression of the air trapped in the short end.
Here are his actual data (yes, data is plural):

The experimental observations of Boyle relating the pressure and volume of air.

This can be a little hard to read, the letter 's' is written as 'f' for example, but the main point of the table is that as the volume of the air is reduced (columns A) the height of the mercury in the long leg increases. In column C Boyle notes the additional effect of atmospheric pressure, something we will cover a little later, and in Column D records the "preffure fuftained by the included air", i.e. the air trapped in the short end. Finally in column E he tests his hypothesis to show "what the preffure should be according to the Hypothefis, that fufposes the preffures and expanfions to be in reciprocal proportion". The result is in very good agreement!

Boyle use inches of mercury to measure the pressure and arbitrary marking on the glass to measure the air volume. Today we prefer to use SI units but lets work with the original data for now.

| Volume | Pressure |
|--------|----------|
|48	     |	29.125  |
|46	     |	30.5625 |
|44	     |	31.9375 |
|42	     |	33.5    |
|40	     |	35.3125 |
|38	     |	37      |
|36	     |	39.3125 |
|34	     |	41.625  |
|32	     |	44.1875 |
|30	     |	47.0625 |
|28	     |	50.3125 |
|26	     |	54.3125 |
|24	     |	58.8125 |
|23	     |	61.3125 |
|22	     |	64.0625 |
|21	     |	67.0625 |
|20	     |	70.6875 |
|19	     |	74.125  |
|18	     |	77.875  |
|17	     |	82.75   |
|16	     |	87.875  |
|15	     |	93.0625 |
|14	     |	100.4375|
|13	     |	107.8125|
|12	     |	117.5625|

We can use python to plot the data and test the hypothesis.

\begin{equation}
p \propto \frac{1}{V}
\end{equation}

or more concretely the product of pressure and volume is some constant $k$ that tells us something about the air's properties.

\begin{equation}
{p}{V} = k
\end{equation}
where k is a constant

```python
# This is a Python cell. Juypter lets us run bits of code and see the results inline.
# Pressing SHIFT-ENTER in a Jupyter cell runs the contents of the cell.

# With Python we can import various libraries that offer additinal functionality as needed.
# Here we need to import some libraries that give Python Matlab like functinality.
# This means we can perform various calculations and tasks with matrices and vectors.
# The first is numpy which offers a lot of powerful numerical functions.
# These functions are prefixed with an 'np.' in the code becasue we tell Python
# to import the library numpy and thereafter refer to it as np for short.

import numpy as np

# Next we import the pyplot part of matplotlib and refer to it as 'plt'.
# This library lets us make varous types of plots just like in Matlab.
# As with numpy, matplotlib functions will pre prefixed by 'plt.'.

import matplotlib.pyplot as plt

# If you want to try and run this code elsewehere like in an interactive shell then ignore this next line.
# if you are using a Jupyter notebook as we are here then you need this line of code to make the plot show up below.
%matplotlib inline

# This line increases the resolution for Apple retina displays but also works well for 4K diplays.
%config InlineBackend.figure_format = 'retina'

# Define numpy arrays for our data
Volume = np.array([48, 46, 44, 42, 40, 38, 36, 34, 32, 30, 28, 26, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12])
Pressure = np.array([29.12500,  30.56250,  31.93750,  33.50000,  35.31250,  37.00000,  39.31250,  41.62500,  44.18750,  47.06250,  50.31250,  54.31250,  58.81250,  61.31250,  64.06250,  67.06250,  70.68750,  74.12500,  77.87500,  82.75000,  87.87500,  93.06250, 100.43750, 107.81250, 117.56250])

# Find the constant of proportionality between pressure and volume
k = Pressure * Volume
k = np.mean(k)

plt.plot(Volume, Pressure,'bo')
plt.plot(Volume, k/Volume,'r-')

plt.xlabel('Volume')
plt.ylabel('Pressure')

print('k = '+str(k))
```

```python
plt.plot(Volume, 1/Pressure ,'bo')
plt.plot(Volume, Volume/k ,'r-')

plt.xlabel('Volume')
plt.ylabel('Pressure$^{-1}$')

print('Pressure is inversely proportional to volume')
```

For the arbitrary units we see that $k = 1408.09$. Plotting the inverse of the pressure against the volume we obtain a straight line which means that the hypothesis is indeed valid, pressure is inversely proportional to volume. If we evaluate $k$ at any point along the data we should get the same answer. Therefore we can compute the change in pressure and volume from one condition to another for a constant $k$.

Now that Boyle's hypothesis has been tested we can write Boyle's Law as:

\begin{equation}
{p_1}{V_1} = {p_2}{V_2}
\end{equation}

### An Example

Lets do an example. We have a $1~m^3$ tank of compressed air at $300~kPa$. If we expand the gas into a $3~m^3$ container and ignore any temperature changes, what is the pressure of the air?

Invoking Boyle's law and entering our known data we have:
\begin{align}
{p_1}{V_1} = {p_2}{V_2} = {300,000}\times{1} = {p_2}\times{3}
\end{align}

and solving for $p_2$:
\begin{align}
{p_2} =  {300,000} / 3 = 100~kPa
\end{align}

So we see that as we expand the gas to a larger volume the force (per unit area) the gas exerts on the walls of the container reduces. This also works in reverse, if we compress a volume of gas into a smaller container then the pressure will increase.

## The Ideal Gas Law

Boyle's Law gives us a relationship between the pressure and volume of a gas. However what does the product ${p}{V} =k$ physically mean? While Boyle varied pressure and volume at a fixed temperature other scientists began to look at other combinations. What happens to pressure if you vary temperature but keep volume constant? (Gay-Lussac's law) What if you attempt to keep pressure constant but vary volume and temperature? (Charles's law) From these empirical observations a number of similar Laws were observed that relate the above relationships. The result is the ideal gas law:

\begin{equation}
{p}{V} = n \mathrm{R} T
\end{equation}

Where $p$ and $V$ are our familiar pressure and volume, $T$ is the temperature, $\mathrm{R}$ is a universal gas constant and $n$ is the number of moles in the gas. Assuming that $\mathrm{R}$ and $n$ are constants this means that we now have a equation that describes the interrelationship between pressure, volume and temperature. We know from experience that if we heat a fixed volume of gas its pressure increases. Alternatively we can increase the volume of the container to maintain the pressure constant. You may even recognise the role of this equation in describing the operation of an internal combustion engine.

But what are $\mathrm{R}$ and $n$?

The latter is easy, $n$ is just the amount of stuff. The amount of gas molecules in our container. Chemists like to use moles as a measure of the amount of stuff because it allows them to make like for like comparisons in their reaction calculations. Like many other SI units the definition of the mole has changed recently. The current definition of a mole is exactly  $6.022~140~76×10^{23}$ particles. Particles in this case are elementary entities such as atoms, ions, molecules, electrons etc. If I want to make pure water ${H_2}{O}$ I need to ensure I have twice as many Hydrogen atoms as Oxygen atoms. Hydrogen and Oxygen are stable in their $H_2$ and $O_2$ states so the chemical reaction is $2H_2 + O_2 \rightarrow 2{H_2}{O}$. I cannot completely react twice the mass of Hydrogen with Oxygen since it has a much smaller atomic mass than Oxygen, $1.008~g/mol$ vs $15.999~g/mol$.
So the ratio is $(2\times1.008) : 15.999$ or about eight time as much oxygen to hydrogen by mass needed to satisfy our reaction equation.

Next is the universal gas constant $\mathrm{R}$. With units $J.K^{-1}.mol^{-1}$ the purpose of $\mathrm{R}$ is to relate the energy to the temperature scales that we have chosen. While convenient, many of our units are often arbitrary; the number of particles in a mole, the division of the temperature scale etc. The universal gas constant is found to be $\mathrm{R} = 8.31451~J.K^{-1}.mol^{-1}$

But as engineers we are less concerned about atoms and molecules. Instead we can write the ideal gas law in the form of a **state equation** using the specific gas constant $R_{\text{specific}} = \frac{\mathrm{R}}{M}$ where M is the molar mass ($g/mol$) of the species. We can replace $n$ with the ratio of the mass of the gas, $m$, in grams, to the molar mass in $g/mol$.

\begin{equation}
n = \frac{m}{M}
\end{equation}

therefore

\begin{equation}
pV = \frac{m}{M}{\mathrm{R}}{T}
\end{equation}

\begin{equation}
pV = {m}\frac{\mathrm{R}}{M}{T} = {m}R_{\text{specific}} T
\end{equation}

which gives:
\begin{equation}
p = \frac{m}{V} R_{\text{specific}} T = \rho R_{\text{specific}} T
\end{equation}

since the mass per unit volume is the density $\rho$. The specific gas constant for air is $287.05~J/Kg.K$.

Now we have a very useful equation that relates pressure, density (or mass and volume) and the temperature. We don't need to worry about the number of moles of our gas we just need to know its bulk properties. In Engineering we often refer to the specific gas constant as just $R$. Just be careful not to confuse it with the universal gas constant $\mathrm{R}$.

\begin{equation}
p = \rho R T
\end{equation}

## An Example

Lets do another example using the ideal gas law we've just derived with the help of Boyle's and other's data.

Air at sea level has a density of $1.225~Kg/m^3$ and a pressure of $101.32~kPa$ (1 atmosphere). The specific gas constant of air is $287.05~J/Kg.K$. What is the temperature at sea level?

```python
p = 101.32e3  # Pa
rho = 1.225   # Kg/m^3
R = 287.05    # J/Kg.K

# Temperature
T = p/(rho * R)

# Print the result using an f-string
print(f"The temperature is {T:.2f} Kelvin, or {(T-273.15):.2f} degrees Celsius")
```

    The temperature is 288.14 Kelvin, or 14.99 degrees Celsius

What happens to pressure as we increase altitude? What happens as we dive deep into the ocean?

The answer to these questions depends on the fluid. Gases, as we have seen already can be readily compressed. We can take a lot of natural gas and compress it into a small container. The air-fuel mixture in a car engine exploits this compression as part of its operation. Liquids on the other hand do not compress very much at all and for most cases we can assume that they are **incompressible**. This means that the density $\rho$ of the liquid doesn't change, no matter how much pressure we apply to it (note that it can change due to temperature too). For gases we can assume that they too are incompressible, within limits. This allows us to ignore changes in density for applications such as low-speed aerodynamics — such as for Formula One cars and light aircraft which makes engineering calculations much easier. However for high speed aircraft such as commercial airliners and military jets the effects of compressibility are significant and can result in very interesting flow physics.

An image of the compressible flow shockwave pattern around a T-38 test aircraft using the Background Orientated Schlieren technique, NASA.

As we increase altitude into the atmosphere the pressure and density both reduce. This is captured in the U.S. Standard atmosphere model available from http://www.pdas.com/atmos.html.
This model is derived from equations we will study in this course including the Ideal Gas Law. Lets just plot the data for now.

```python
Altitude = [-2.0,  0.0,  2.0,  4.0,  6.0,  8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 38.0, 40.0, 42.0, 44.0, 46.0, 48.0, 50.0, 52.0, 54.0, 56.0, 58.0, 60.0, 62.0, 64.0, 66.0, 68.0, 70.0, 72.0, 74.0, 76.0, 78.0, 80.0, 82.0, 84.0, 86.0]
Temperature = [301.2, 288.1, 275.2, 262.2, 249.2, 236.2, 223.3, 216.6, 216.6, 216.6, 216.6, 216.6, 218.6, 220.6, 222.5, 224.5, 226.5, 228.5, 233.7, 239.3, 244.8, 250.4, 255.9, 261.4, 266.9, 270.6, 270.6, 269.0, 263.5, 258.0, 252.5, 247.0, 241.5, 236.0, 230.5, 225.1, 219.6, 214.3, 210.3, 206.4, 202.5, 198.6, 194.7, 190.8, 186.9]
Pressure = [1.278e+02, 1.013e+02, 7.950e+01, 6.166e+01, 4.722e+01, 3.565e+01, 2.650e+01, 1.940e+01, 1.417e+01, 1.035e+01, 7.565e+00, 5.529e+00, 4.047e+00, 2.972e+00, 2.188e+00, 1.616e+00, 1.197e+00, 8.890e-01, 6.634e-01, 4.985e-01, 3.771e-01, 2.871e-01, 2.200e-01, 1.695e-01, 1.313e-01, 1.023e-01, 7.977e-02, 6.221e-02, 4.833e-02, 3.736e-02, 2.872e-02, 2.196e-02, 1.669e-02, 1.260e-02, 9.459e-03, 7.051e-03, 5.220e-03, 3.835e-03, 2.800e-03, 2.033e-03, 1.467e-03, 1.052e-03, 7.498e-04, 5.308e-04, 3.732e-04]
Density = [1.478, 1.225, 1.007, 0.819, 0.660, 0.526, 0.413, 0.312, 0.228, 0.167, 0.122, 0.089, 0.065, 0.047, 0.034, 0.025, 0.018, 0.014, 0.010, 0.007, 0.005, 0.004, 0.003, 0.002, 0.002, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000]

plt.subplots(1,3,figsize=(10,10))

plt.subplot(131)
plt.plot(Temperature,Altitude,'k-')
plt.grid(True)
plt.ylabel('Altitude (km)')
plt.xlabel('Temperature (K)')

plt.text(250, 10, "Troposphere")
plt.text(250, 20, "Tropopause")
plt.text(250, 35, "Stratosphere")
plt.text(200, 50, "Mesosphere")

plt.subplot(132)
plt.plot(Pressure,Altitude,'k-')
plt.grid(True)
plt.xlabel('Pressure (kPa)')

plt.subplot(133)
plt.plot(Density,Altitude,'k-')
plt.grid(True)
plt.xlabel('Density ($kg/m^3$)')

print('International Standard Atmosphere model')
```

The model shows that both pressure and density reduce with some exponent as altitude increases. Temperature however initially drops linearly up to $10~km$ (referred to as the troposphere) before becoming stable from $10 – 20~km$ (in the tropopause) before slowly creeping up again (in the stratosphere) before falling linearly once more beyond $50~km$ (in the mesoshpere). In the troposphere the air is heated by the heat of the earth cooling with altitude. The temperature rise in the stratosphere is due to Ozone gas absorbing the sun's energy falling thereafter as the Ozone concentration reduces.

To reiterate, this foundational course in Fluid Mechanics is concerned with incompressible flow. We will assume the density doesn't change which is a reasonable assumption once we stay at a fixed altitude and don't exert significant force on our working fluids. All this discussion about the atmosphere is to provide an interesting introduction to the fluid that surrounds us!

## Hydraulics

The use of liquids, particularly water, in many engineering applications is often referred to as hydraulics (air based systems are referred to as pneumatic). Here the incompressible nature of water or hydraulic oil is used to operate complex machinery. A common example is a hydraulic ram as shown in the video below. Hydraulic fluid pressurised (coloured red in the video) by a pump is used to push a piston attached to the ram arm along with the unpressurised fluid which is forced out of the chamber back to the supply reservoir. Such devices are used extensively in automotive applications such as brakes, and power steering. In aviation they are used to articulate control surfaces and in heavy machinery such as excavators and can deliver significant amounts of mechanical power.

<video controls src="media/1.2/ram.mp4" width="700" loop=1/>

## Pneumatics
Pneumatic systems are similar to hydraulic systems but can incorporate a compressor pump to compress the ambient air and so are not reliant on a specialist fluid. Pneumatic systems are considered simpler and more reliable than hydraulic systems and are used extensively in systems where size and weight are more important than power. Examples of pneumatically powered systems include handheld power tools such as impact wrenches, high-speed CNC spindles, musical instruments and clean room equipment such as spin coaters.

## Pressure and Depth — Hydrostatics

Another important aspect of Hydraulics is Hydrostatics and is concerned with the pressure exerted by a fluid (usually a liquid) with increasing depth. If the density of an incompressible fluid is constant, what happens when we compress it? We've actually already seen this in Boyle's experiment. He used mercury, which is a very dense liquid metal, to compress the air. The weight and height of the mercury column increased the pressure in the trapped gas. Another example is a deep sea diver experiencing increasing compression from the surrounding water the deeper they dive. To understand the effect of depth and pressure we need to consider Pascal's Law which states that the change in pressure $\Delta P$ is given by

\begin{equation*}
\Delta P = \rho g \Delta h
\end{equation*}

where $g$ is acceleration due to gravity and $\Delta h$ is the height. As Boyle added more mercury of density $\rho$ to the open side of the J tube he increased $\Delta h$ the pressure experienced at the closed end of the tube increased under the weight of the dense fluid pushing down on it. The next three notebooks will discuss hydrostatics in some detail.

## Measuring Pressure

As stated, pressure is the force exerted on or by a fluid per unit area. How do we go about quantifying it so we can use it precisely in engineering applications such as hydraulic rams or measure it accurately so we can perform tasks such as weather forecasting? There are many ways to measure pressure and they are often suited to particular fluids and applications. For example some fluids are corrosive and could damage fragile instruments. Sensors one would use for air may not be appropriate for water because of the electrical conductivity of the liquid. Some flows are very sensitive or precious such as biological flows so non-invasive methods are preferred. We will discuss several of these measurement methods throughout this course. These include manometers, Bourdon gauges, strain gauges and piezoelectric transducers. Some of these are used in conjunction with devices such as **orifice plates** and **Venturi meters** to measure flow velocity, which as we will see through a derivation of **Bernoulli's Equation** is as a result of pressure differences in fluids.

### The Bourdon Pressure Gauge

The image below shows the fundamental operation of a Bourdon pressure gauge which is a common type of gauge in many engineering systems. You may be familiar with such a device from a tyre pump or an air compressor. The pressure in the vessel fills a tube with a closed end. The tube has a non-circular cross section and as a result undergoes an outward deflection when pressurised. This deflection is then amplified by a mechanical system to turn a needle pointer against a calibrated scale.

Illustration of the basic function of the Bourdon pressure gauge. (left) the gauge installed in a pressure vessel such as the tank of an air compressor, (middle) detailed view of the gauge. A tube open at one end is connected to the pressure tap and the closed end is attached via a linkage to a gear system which it itself connected to the pointer. (right) the Bourdon tube has a non-circular cross section. When the pressure in the tube is increased the tube shape expands as show in Section A-A and the tube's curvature along its length is reduced resulting in an outward defection. The mechanical linkage and gear system deflects the pointer and the pressure can be read from the scale.

## Static Pressure

Somewhat confusingly there are various other quantities that are also referred to as pressure, such as *dynamic pressure* and *total pressure*. These concern fluid in motion and incorporate the kinetic energy of the flow. The pressure described thus far we will refer to as the **static pressure** as it refers to the pressure of the fluid under static conditions.

A typical static pressure measurement is performed by attaching a suitable instrument to a *static-pressure port* or *pressure tap* on the vessel of interest. This is a small hole located normal to the surface where the fluid pressure at the point can me measured.

## Absolute and Gauge Pressure

An important concept to understand right now is the idea of gauge pressure as this often confuses students and can lead to simple errors.

- The **Absolute Pressure** is the pressure measured relative to a **Vacuum**.
- The **Gauge Pressure** is the pressure measured relative to **Atmospheric Pressure**.

We live on a planet with an atmosphere and not in the vacuum of space. This means that we are subject to the static pressure due the height of the atmosphere above us and acceleration due to gravity. We calculated the sea level temperature earlier using the standard atmospheric pressure of $101.32 kPa = 1~atm$. If we have a pressure vessel, say a bicycle tube as (shown below) that we want to inflate, we would need to consider the pressure of the atmosphere on the outside and the pressure of the air within as these competing forces will determine how inflated the tube will be.

If there was a vacuum inside the tube the atmosphere would squish it flat as there is nothing inside to push outwards. We would struggle to move the tube walls relative to each other as the atmosphere pushes them together.

Opening the valve and allowing the atmosphere to rush in and *equalise* the tube would be more easily manipulated in our hands. We could roll the tube walls between our fingers but it would not be much use on our bike. The atmosphere now has no effect on the tube shape as it acts equally on the outside and the inside.

Using a pump to inflate the tube to a value of $600 kPa$ on the Bourdon gauge would result in an almost rigid torus. It is now very difficult to squish the tube and the rubber is now stretched tight. The pressure inside the tube is much higher than the atmosphere and the compressed air inside can push the tube wall out against the atmosphere.

- The **Absolute Pressure** inside the inflated tube is $600 + 101.32 = 701.32~kPa$. This is the pressure relative to a vacuum.
- The **Absolute Pressure** outside the tube is $101.32~kPa$. Again, this is the pressure relative to a vacuum.
- The **Gauge Pressure** inside the inflated tube is simply $600~kPa$ and is the pressure relative to our atmosphere.
- The **Gauge Pressure** outside the tube is simply $0~kPa$ and is the pressure relative to our atmosphere.

Illustration of the difference between absolute (top row) and gauge (bottom row) pressures for a cross section of a bicycle tyre tube (left) *flat* tube with vacuum inside, (middle) tube open to atmosphere, (right) inflated tube. Pressure act normal to the tube surface as indicated by the arrows. Shown also on the bottom left are vectors indicating the magnitude of the absolute, gauge and inflated pressure.

Pressure gauges which report gauge pressure are vented to the atmosphere. This means that they report the pressure relative to the ambient pressure which can change from day to day depending on metrological conditions or on altitude. Absolute pressure gauges are sealed so they can report pressure against a vacuum. Both types have their advantages and an engineer must select an appropriate instrument.

Take a look at an online vendor such as https://ie.rs-online.com/ and compare commerical gauges.

## Vapour Pressure

Another quantity of interest is the vapour pressure. This is a measure of the evaporation of a substance in a closed container. At the molecular level, as we've seen in the video at the top of this notebook molecules are jostling about quite energetically. At this length scale the interface between a liquid and a gas (or a solid and a gas) is not so distinct. High energy molecules in the gas phase may impact the liquid phase and return to a lower energy state. Conversely molecules may be thrown off and join the high energy molecules in the gas phase. This process is continuously occurring.

A liquid placed in a sealed container with any empty space (a vacuum) and with no influences from outside (adiabatic) will eventually reach an equilibrium where the number of molecules entering the liquid phase is equal to those entering the gas phase. The gas molecules will fill any empty space. The pressure of the resulting gas phase in this equilibrium state is the vapour pressure.

Some liquids are more volatile than others and this is why you can smell pungent liquids like alcohol and ammonia which readily evaporate at room temperature. A open container of a volatile liquid like ethanol will evaporate to the environment in a few minutes.
Other liquids like mercury and various silicon oils have much lower vapour pressures and evaporate at much slower rates.

For mixtures of gases there is the concept of partial pressures but this is beyond the scope of this course.

## Measuring Pressure

There are various instruments, including the Bourdon Gauge, that are commonly employed to measure pressure. This include:

* Mercury barometer
* Aneroid Barometer
* MEMS — Smartphones
* Manometer
* Piezoelectric diaphragm

As we will see later Bernoulli's equation allows us to relate pressure and flow velocity. There are additional instruments that also measure pressure to provide a velocity measurement.

* Pitot static tube
* Venturi meter
* Orifice plate

We will explore several of these instruments during this course.

# References

1. Boyle, R., 1662, *"A defence of the doctrine touching the spring and weight of the air"*, The works of Robert Boyle
2. Munson, B.R., Young, D.F., Okiishi, T.H. and Huebsch, W.W., 2010. *"Fundamentals of Fluid Mechanics"*. Singapore: Wiley.


# Oil Data Quality Index

### December 2016
Author: Bill Lehr
Edited By: James L. Makela

## Background

The Adios3 Oil Library will accept data on crude oils and refined products provided they contain a minimum required set of data.  Additional missing data will be generated by approximation formulas according to the Oil Properties Estimation document.

It is reasonable to propose that the more measured data that an oil record has, the better job we will do when estimating missing oil properties. (Ideally, we would not need to estimate anything, but simply use measured values)

So in addition to requiring a minimum set of measured data, we will try to assess an oil record's quality index.  The quality index is a numeric score that we will use to represent an oils "fitness", or to put it another way, how well we expect to be able to calculate reasonable estimates of the missing oil properties.

## Minimum Data Required

| Type | Density (or API) | Viscosity | Distillation Cuts |
| ---- |:----------------:|:---------:|:-----------------:|
| Crude | Yes | Yes | No |
| Refined Product | Yes | Yes | Yes (at least 3) |

## Calculating the Quality Index

More, and more recent, information about an oil will result in a higher quality index.
A quality index $Q_i$ is defined with a range:

$$
\begin{align}
0 &\leq Q_i \leq 10
\end{align}
$$

| Quality Criteria                | Points | Cumulative |
| ----------------                |:------:|:----------:|
| Crude Oil                       | 1      | 1          |
| 3-4 distillation cuts           | 1      | 2          |
| 5+ distillation cuts            | 2      | 3          |
| SARA Fractions                  | 1.5    | 4.5        |
| SARA Distillation               | 2      | 5.0        |
| Data Less Than 5 Years Old      | 1      | 6          |
| Extra Viscosity Data            | 0.5    | 6.5        |
| Pour Point                      | 0.5    | 7          |
| Oil-Water Interfacial Tension   | 1      | 8          |
| Maximum Water Fraction/Per Cent | 1      | 9          |
| Emulsion Stability              | 1      | 10         |

- Extra data, not used by Adios, will be recorded by a plus after the score, e.g. 2.5+.  This will include such information as adhesion, flash point, metal content, Conradsen number or multiple oil densities at different temperatures.
- SARA distillation means that we have distillation data individually for each SARA fraction.
- Extra viscosity data refers to initial viscosity at different temperatures.
- Emulsion stability is Environment Canada's designation as:
    - entrained/unstable
    - meso-stable
    - stable
- Maximum water fraction is the maximum possible mass water fraction of the emulsified oil.
- Crude oil gets an extra point over refined products because the oil name better corresponds to the actual data (e.g., 'Louisiana Sweet Crude' is more descriptive than 'Fuel Oil #2')
- Do not double-credit oils in computing their score.  An oil with 5 or more distillation cuts gets 2 points total.  Similarly, an oil with SARA fractions with individual distillation data gets only 2 points, not $(2 + 1.5)$.

```python

```


# Lista de Exercício 7
### Introdução à Visão Computacional (SEL0339/SEL5886)

**Instruções:**

 1. Esta lista consiste de 3 exercícios.
 1. Deve-se colocar comentários nos códigos desenvolvidos.
 1. As perguntas devem ser respondidas também como comentários no arquivo.
 1. Colocar seu nome e número USP abaixo.
 1. Quaisquer problemas na execução das listas, entrar em contato com os monitores.
 1. Depois de terminado os exercícios, deve ser gerado um arquivo **extensão .ipynb** para ser enviado ao professor pelo E-DISCIPLINAS da disciplina até a data máxima de entrega.
 1. Caso não seja enviado, o aluno ficará sem nota.

---

    Executar no Google Colab

    Ver codigo fonte no GitHub

`Nome: Murilo Henrique Pasini Trevisan `

`Número USP: 9796078 `

### Introdução:

Vamos importar as bibliotecas que iremos utilizar:

```
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv

from skimage.transform import hough_circle, hough_circle_peaks
```

#### **Atenção**: os códigos abaixo são para fazer o download das imagens (EXECUTE-OS). Os mesmos não fazem parte dessa prática.

```
import urllib.request

try:
  urllib.request.urlretrieve("https://github.com/LAVI-USP/SEL0339-SEL5886_2021/raw/main/imagens/pratica_07/test_01.png", "test_01.png")
except:
  print("[ERRO] Não foi possível fazer o download das imagens dessa prática. Entre em contato com o monitor")

try:
  urllib.request.urlretrieve("https://github.com/LAVI-USP/SEL0339-SEL5886_2021/raw/main/imagens/pratica_07/house.tif", "house.tif")
except:
  print("[ERRO] Não foi possível fazer o download das imagens dessa prática. Entre em contato com o monitor")

try:
  urllib.request.urlretrieve("https://github.com/LAVI-USP/SEL0339-SEL5886_2021/raw/main/imagens/pratica_07/wirebond_mask.tif", "wirebond_mask.tif")
except:
  print("[ERRO] Não foi possível fazer o download das imagens dessa prática. Entre em contato com o monitor")

try:
  urllib.request.urlretrieve("https://github.com/LAVI-USP/SEL0339-SEL5886_2021/raw/main/imagens/pratica_07/notas_functions.py", "notas_functions.py")
except:
  print("[ERRO] Não foi possível fazer o download das imagens dessa prática. Entre em contato com o monitor")
```

### 1) Filtros derivativos de $1^a$ e $2^a$ ordem

A equação para o cálculo da $1^a$ derivada em relação a $y$ é dada por:

\begin{equation}
\frac{\partial f(x,y)}{\partial y} = f(x,y+1) - f(x,y)
\end{equation}

Já a equação para o cálculo da $2^a$ derivada em relação a $y$ é dada por:

\begin{equation}
\frac{\partial^2 f(x,y)}{\partial y^2} = f(x,y+1) - 2f(x,y) + f(x,y-1)
\end{equation}

**Exercício:**

1. Crie um *kernel* para o filtro derivativo de $1^a$ ordem e um *kernel* para o de $2^a$ ordem.

2. Aplique os *kernels* para detectar as bordas na vertical, ou seja, no eixo $y$. A imagem já está criada no código.

3. Mostre a imagem original e ambos os resultados utilizando `subplot`.

4. Utilize a função `plt.plot` para mostrar o perfil das bordas detectadas em ambos os casos. Isso pode ser feito através de qualquer linha da imagem resultante. Utilize um `subplot` com 3 linhas e 1 coluna, sendo a primeira linha para o perfil da imagem original, a segunda para o filtro de $1^a$ ordem e a terceira para o filtro de $2^a$ ordem.

    Dicas:

*  Você pode utilizar a função [cv.filter2D](https://docs.opencv.org/3.4/d4/d86/group__imgproc__filter.html#ga27c049795ce870216ddfb366086b5a04) para fazer a filtragem.

*  Você pode utilizar a função [plt.plot](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.plot.html) para mostrar os gráficos na tela. Você pode fazer a leitura de qualquer linha da imagem para mostrar o gráfico.

*Ex:*
``` python
plt.plot(x,y)
plt.plot(y) # Dessa maneira a função cria um range para o x
cv.filter2D(myImg, -1, myKernel)
```

```
img = np.zeros((100,100),np.float32)
img[:,25:75] = 255
img = cv.blur(img,(3,3))

## -- Seu código começa AQUI -- ##

Kernel_1 = np.array(((-1, 0, 1),
                     (-1, 0, 1),
                     (-1, 0, 1)))

Kernel_2 = np.array(((-1, -1, -1),
                     (-1,  8, -1),
                     (-1, -1, -1)))

img_filter_1 = cv.filter2D(img, -1, Kernel_1)
img_filter_2 = cv.filter2D(img, -1, Kernel_2)

plt.figure(figsize = (7,7))
plt.subplot(1,3,1)
plt.imshow(img)
plt.title("Original")

plt.subplot(1,3,2)
plt.imshow(img_filter_1)
plt.title("1 ordem")

plt.subplot(1,3,3)
plt.imshow(img_filter_2)
plt.title("2 ordem")

## -- Seu código termina AQUI -- ##

```

### 2) Detector de bordas (Prewitt e Sobel)

**Exercício:**

1. Aplicar o detector de bordas de Prewitt e Sobel na imagem ```wirebond_mask.tif``` para detectar as bordas horizontais e depois as verticais. Note que vários *kernels* foram fornecidos abaixo. Alguns serão utilizados no próximo exercício também.

2. Mostre as 4 imagens resultantes e comente os resultados encontrados.

    Dicas:

*  Nós criamos uma lista contendo os *kernels* de cada método. Você pode criar um laço de repetição para pegar cada kernel da lista. Segue abaixo um exemplo de um `for loop` em uma lista.

*Ex:*
``` python
kernel_lista = [kernel1,kernel2,kernel3]
for kernel in kernel_lista:
  print(kernel)
# Resultado do print:
# kernel1
# kernel2
# kernel3
```

```
# Prewitt
p1 = np.array(((-1,-1,-1),
               ( 0, 0, 0),
               ( 1, 1, 1)))

p2 = np.array(((-1, 0, 1),
               (-1, 0, 1),
               (-1, 0, 1)))

# Lista com todos os kernels (Prewitt)
prewitt = [p1,p2]

# Sobel
s1 = np.array(((-1,-2,-1),
               ( 0, 0, 0),
               ( 1, 2, 1)))

s2 = np.array(((-1, 0, 1),
               (-2, 0, 2),
               (-1, 0, 1)))

s3 = np.array(((-2,-1, 0),
               (-1, 0, 1),
               ( 0, 1, 2)))

s4 = np.array((( 0, 1, 2),
               (-1, 0, 1),
               (-2,-1, 0)))

s5 = np.array((( 2, 1, 0),
               ( 1, 0,-1),
               ( 0,-1,-2)))

s6 = np.array((( 0,-1,-2),
               ( 1, 0,-1),
               ( 2, 1, 0)))

# Lista com todos os kernels (Sobel)
sobel = [s1,s2,s3,s4,s5,s6]

# Laplaciano
laplaciano = np.array(((-1,-1,-1),
                       (-1, 8,-1),
                       (-1,-1,-1)))

## -- Seu código termina AQUI -- ##

wire = cv.imread("wirebond_mask.tif")

wire_filter_yp = cv.filter2D(wire, -1, p1)
wire_filter_xp = cv.filter2D(wire, -1, p2)

wire_filter_ys = cv.filter2D(wire, -1, s1)
wire_filter_xs = cv.filter2D(wire, -1, s2)

plt.figure(figsize = (10,10))
plt.subplot(1,5,1)
plt.imshow(wire)
plt.title("original")

plt.subplot(1,5,2)
plt.imshow(wire_filter_yp)
plt.title("prewitt x")

plt.subplot(1,5,3)
plt.imshow(wire_filter_xp)
plt.title("prewitt y")

plt.subplot(1,5,4)
plt.imshow(wire_filter_ys)
plt.title("Sobel x")

plt.subplot(1,5,5)
plt.imshow(wire_filter_xs)
plt.title("Sobel y")

#Nota-se que para os kernels em y somente as linhas que possuem variação em y
#foram mantidas, assim como em x somente as que variam em x, além disso notou-se
#que para estes exemplos a diferença entre prewitt e sobel não é tão expressiva
#visto que as imagens já possuem bordas bem destacadas, porém nota-se que para os
#kernels em sobel, houve maior destaque na borda, comparado a prewitt, como 7
#esperado pela teoria dos kernels de prewitt e sobel

## -- Seu código termina AQUI -- ##
```

### 3) Detector de bordas (Sobel e Laplaciano)

**Exercício:**

1. Aplicar o detector de bordas de Sobel na imagem ```house.tif``` para detectar todas as bordas. Os *kernels* foram definidos no exercício anterior.

  *   Para cada *kernel*, aplique um *threshold* no resultado do filtro a fim de tentar manter somente as bordas que aquele filtro foi desenvolvido para detectar. Nas dicas deixamos um valor sugerido;
  *   Some o resultado obtido por cada *kernel* em uma variável chamada `sobel_sum`.

2. Mostre os 6 resultados anteriores e um `subplot`;

3. Aplique o detector de bordas Laplaciano na imagem ```house.tif```. Criei um `sobplot` para mostrar a imagem original, a soma de todos os resultados de Sobel (`sobel_sum`) e por fim o resultado do Laplaciano. O que se pode concluir?

    Dicas:

*  O valor de *threshold* sugerido é 220. Esse não é um valor ótimo para cada *kernel*, mas sim um valor médio para todos os *kernels* no geral.

*  Faça um `for loop` para aplicar os filtros de Sobel. Isso simplifica o código

*Ex:*
``` python
kernel_lista = [kernel1,kernel2,kernel3]
for kernel in kernel_lista:
  print(kernel)
# Resultado do print:
# kernel1
# kernel2
# kernel3
```

```
## -- Seu código começa AQUI -- ##

house = cv.imread("house.tif", cv.IMREAD_GRAYSCALE)

house_filter = cv.filter2D(house, -1, s1)
(thresh, house_1) = cv.threshold(house_filter, 220, 255, cv.THRESH_BINARY)

house_filter = cv.filter2D(house, -1, s2)
(thresh, house_2) = cv.threshold(house_filter, 220, 255, cv.THRESH_BINARY)

house_filter = cv.filter2D(house, -1, s3)
(thresh, house_3) = cv.threshold(house_filter, 220, 255, cv.THRESH_BINARY)

house_filter = cv.filter2D(house, -1, s4)
(thresh, house_4) = cv.threshold(house_filter, 220, 255, cv.THRESH_BINARY)

house_filter = cv.filter2D(house, -1, s5)
(thresh, house_5) = cv.threshold(house_filter, 220, 255, cv.THRESH_BINARY)

house_filter = cv.filter2D(house, -1, s6)
(thresh, house_6) = cv.threshold(house_filter, 220, 255, cv.THRESH_BINARY)

Sobel_sum = house_1 + house_2 + house_3 + house_4 + house_5 + house_6

house_filter = cv.filter2D(house, -1, laplaciano)
(thresh, house_lap) = cv.threshold(house_filter, 40, 255, cv.THRESH_BINARY)

plt.figure(figsize = (20,20))
plt.subplot(1,7,1)
plt.imshow(house, cmap="gray")
plt.title("original")

plt.subplot(1,7,2)
plt.imshow(house_1, cmap="gray")
plt.title("Sobel 1")

plt.subplot(1,7,3)
plt.imshow(house_2, cmap= "gray")
plt.title("Sobel 2")

plt.subplot(1,7,4)
plt.imshow(house_3, cmap= "gray")
plt.title("Sobel 3")

plt.subplot(1,7,5)
plt.imshow(house_4, cmap= "gray")
plt.title("Sobel 4")

plt.subplot(1,7,6)
plt.imshow(house_5, cmap= "gray")
plt.title("Sobel 5")

plt.subplot(1,7,7)
plt.imshow(house_6, cmap= "gray")
plt.title("Sobel 6")

plt.figure(figsize = (15,15))
plt.subplot(1,3,1)
plt.imshow(house, cmap="gray")
plt.title("original")

plt.subplot(1,3,2)
plt.imshow(Sobel_sum, cmap="gray")
plt.title("Sobel soma")

plt.subplot(1,3,3)
plt.imshow(house_lap, cmap= "gray")
plt.title("Laplaciano")

#Conclui-se que cada sobel obteve em cada direção o filtro, a partir da direção
#do kernel, como esperado, e assim como previsto pela teoria, caso realize a
#filtragem da primeira derivada em todas as direções, o resultado é um filtro
#semelhante a um de segunda ordem, como pode ser visto pela comparação entre a
#soma dos filtros de sobel e do laplaciano, porém, nota-se que o threshold do
#filtro laplaciano teve que ser menor que o da soma dos filtros de sobel, devido
#a forma como é feita a filtragem em segunda ordem e primeira ordem, porém
#ajustando-se os thresholds, obteve-se imagens semelhantes

## -- Seu código termina AQUI -- ##
```


Towards preventing overfitting: Regularization

In machine learning, you must have come across the term Overfitting. Overfitting is a phenomenon where a machine learning model models the training data too well but fails to perform well on the testing data. Performing sufficiently good on testing data is considered as a kind of ultimatum in machine learning.

There are quite a number of techniques which help to prevent overfitting. Regularization is one such technique. And this post is all dedicated to that. In this post, I will try to explain Regularization with less maths but with more intuition. Unlike my other tutorials it will not cover any sort of case study. Before delving into any case study, I would like you to understand the importance and little delicacies of Regularization. Because Regularization is tricky but a very import technique to know as a Data Scientist.

This post is outlined as the following:

What is overfitting in machine learning?

What is Regularization and how does it help prevent the phenomenon of Overfitting?

Conclusion

What is overfitting in machine learning?

Before explaining overfitting, let’s talk a bit about generalization in machine learning.

Generalization refers to how well the concepts learned by a machine learning model apply to specific examples not seen by the model when it was learning (testing set in short).

The goal of a good machine learning model is to generalize well from the training data to any data from the problem domain. This allows you to make predictions in the future on data the model has never seen.

I will just quote from the introduction section:
“Overfitting is a phenomenon where a machine learning model models the training data too well but fails to perform well on the testing data."

Overfitting happens when a model learns the details and noise in the training data to the extent that it negatively impacts the performance of the model on unseen data. This means that the noise or random fluctuations in the training data is picked up and learned as concepts by the model. The problem is that these concepts do not apply to new data and negatively impact the models ability to generalize.

Overfitting is more likely with nonparametric and nonlinear models that have more flexibility when learning a target function. As such, many nonparametric machine learning algorithms also include parameters or techniques to limit and constrain how much detail the model learns.

For example, decision trees are a nonparametric machine learning algorithm that is very flexible and is subject to overfitting training data. This problem can be addressed by pruning a tree after it has learned in order to remove some of the detail it has picked up.
On the other hand, Underfitting refers to a model that can neither model the training data nor generalize to new data.

What is Regularization?

When you hear the word Regularization without anything else related to Machine Learning, you all understand that Regularization is the process of regularizing something, or the process in which something is regularized. The problem is: what is exactly something. In terms of Machine Learning, you talk about learning algorithms or models, and what is actually inside the algorithms or models? That’s the set of parameters. In short, Regularization in machine learning is the process of regularizing the parameters that constrains / regularizes or shrinks the coefficient estimates towards zero. In other words, this technique discourages learning a more complex or flexible model, so as to avoid the risk of Overfitting.

Now, you are slowly moving towards understaning how Regularization actually helps in preventing Overfitting? Let's get straight to that.

After knowing that Regularization is actually to regularize our parameters, then you may wonder: Why regularizing the parameters helps to prevent Overfitting? Let’s consider the graph below graph:

As you can see in the graph, it has got two functions represented by a green curve and a blue curve respectively. Both the curves fit those red points so well that you can consider they both incur zero loss. From the intuition of Overfitting you may have guessed that green curve is the on that overfits. Yeah, you are totally right! But have you ever wondered why the green curve (or any curve which is similar to it) is overfitting the data?

To understand that in a bit more mathematical way, let’s assume the two functions that are used to draw the graph above:

The green curve:

\begin{align}
h_1(x)=-x^4+7x^3-5x^2-31x+30
\end{align}

The red curve:

\begin{align}
h_2(x)=\frac{x^4}{5}-\frac{7x^3}{5}+x^2+\frac{31x}{5}-6
\end{align}

If you look at each function’s equation, you will find that the green curve has larger coefficients, and that’s the main cause of Overfitting. As mentioned before, Overfitting can be interpreted that your model fits the dataset so well, which it seems to memorize the data we showed rather than actually learn from it. Intuitively, having large coefficients can be seen as an evidence of memorizing the data. For example, you got some noises in our training dataset, where the data’s magnitude is far different than the others, those noises will cause our model to put more weight into the coefficient of higher degree, and what you received is a model that overfits our training data!

Often in Data Science problems, with increasing number of features a machine learning model can fit your data really well. But everything has its drawback, if you add so many features, we will be punished with Overfitting.  Some of you may think, if adding so many features causes Overfitting, than why don’t we just stop adding features when we got an acceptable model? But think about that this way. If your customer or your boss wants a learned model with 95% accuracy, but you can’t achieve that result without adding some more features, which results in overfitting the data. What will you do in the next step?

Or think about it in one other way. You are facing a problem where you are provided with a large dataset, which each of them contains a great deal of features. You don’t know which features to drop, and even worse if it turns out that every feature is fairly informative, which means that dropping some features will likely ruin the algorithm’s performance. What do you plan to do next?

The answer is regularization.

The Regularization term:

Therefore, it’s not always a good idea to drop some features just to prevent Overfitting. And as you saw in the example above, it requires further analysis to know whether you can remove some less informative features. So, it’s a good practice that you use all features to build your first model in the beginning. And Regularization comes out as a solution. To make it clearer, let’s first take a look at the MSE cost function (MSE: Mean Squared Error):

\begin{align}
J = \frac{1}{2m}\sum_{i=1}^m(h_\theta(X^{(i)})-y^{(i)})^2
\end{align}

where,
-  hθ(X(i)) is the learned predicition given on the i-th input parameter Xi
- y(i) is the origianl predicition
- m is the total number of input sample

In models like Logistic Regression, the objective of learning is to minimize this MSE function. It means that your parameters can be updated in anyway, just to lower the MSE value. And as mentioned you above, the larger your parameters become, the higher chance your model overfits the data. So the question is: can you not only minimize the cost function, but also restrict the parameters not to become too large? The answer is: YOU CAN, by adding the regularization term like below:

\begin{align}
J = \frac{1}{2m}\sum_{i=1}^m(h_\theta(X^{(i)})-y^{(i)})^2+\frac{\lambda}{2m}\sum_{j=1}^n\theta_j^2
\end{align}

where,
 - λ is a constant to control the value of regularization term
 - n is the number of the features.

Take a look at your new cost function after adding the regularization term. The regularization term penalizes large parameters. Obviously, minimize the cost function consists of minimizing both terms in the right: the MSE term and the regularization term. So each time some parameter is updated to become significantly large, it will increase the value of the cost function by the regularization term, and as a result, it will be penalized and updated to a small value.

I will conclude this post right here. I believe the post is not that long but there's enough for you to revise and rework for yourselves. When you feel confident with the intuition you built with this post, the next steps would be to

- Study about the different types of Regularization viz. L1 and L2 variants of Regularization.
- Implement Regularization in any Machine Learning model that is parameterized.

DataCamp Regularization Blog/Towards preventing overfitting - Regularization.ipynb


# Regresión Lineal

### Tabla de Contenido

[Introducción](#Introducción) \\

[Historia de la Regresión Lineal](#Historia) \\

[Algoritmo](#Algortimo) \\

[Ejemplo: Cambio Climático](#Ejemplo) \\

[Conclusiones](#Conclusiones) \\

[Referencias](#Bibliografia)

# Introducción

> La regresion es el estudio de la dependencia,  se ha utilizado para responder preguntas como, ¿cambiar el tamaño de las clases afecta el rendimiento de los estudiantes? ¿ Podemos predecir el tiempo en el que ocurrirar la siguiente erupcion del géiser Old Faithful a partir de la duración de la erupcion mas reciente? ¿Cambios en la dieta resultan en cambios en el nivel de colesterol, y si asi fuera, estos resultados dependen de caracterisiticas como la edad, sexo, y cantidad de ejercicio? ¿Tienen los paises con mas alto PIB menores tasas de nacimientos versus paises con menor PIB?. Como en muchos análisis estadísticos, el objetivo de la regresión es recoger informacion de la manera más simple, útil, y elegante posible. En algunos problemas, puede estar disponible una teoría que especifique cómo varía la respuesta a medida que cambian los valores de los predictores. En otros problemas puede faltar una teoría y necesitamos usar los datos para ayudarnos a decidir como proceder. En cualquier caso, un primer paso esencial en el análisis de regresión es dibujar gráficos apropiados. \\

> Los análisis de regresión, incluido el análisis de regresión simple, responde preguntas acerca de la dependencia de una variable respuesta sobre uno o mas predictores, incluyendo predecir valores futuros de respuesta, descubriendo que predictores son importantes, y estimando el impacto de cambiar un predictor en el valor de la respuesta. [1]

Figura 1. Representación Regresión Lineal simple. Tomado de [Imagen](https://economipedia.com/definiciones/modelo-de-regresion.html). \\

#Historia de la regresión lineal

La primera noción de regresión estadística es usualmente atribuidaa Francis Galton, aunque las primeras nociones de una curva lineal que ajustara un conjunto de datos se remonta a inicios del siglo XIX, con los ajustes hechos por Gauss y Legendre. Trabajos recientes han traido a la luz información sobre un pionero en el tema, R. J Adcock. A pesar de errores de ejecución, merece ser recordado en la historia de nuestra ciencia. Estuvo cerca de inventar la regresión lineal; también observó la necesidad de especificar criterios para tener una estimación de parámetros óptima. [2] \\

Un examen de las publicaciones de Sir Francis Galton y Karl Pearson mostraron que el trabajo de Galton sobre caracteristicas heredadas de los guisantes de olor llevarón a la conceptualización inicial de la regresión lineal. Seguido a esto, esfuerzos tanto de Pearson y Galton resultaron en el desarrollo de técnicas mas generales sobre regresión multiple y el coeficiente de correlación producto-momento ( conocido actualmente como el coeficiente de Pearson). Aunque Pearson desarrollo el coeficiente que lleva su nombre de una manera rigurosamente matemática, fue la imaginación de Sir Francis Galton, que originalmente concibió las ideas modernas de regresión y correlación. \\

Las ideas que resultaron en el desarrollo del coeficiente de Pearson comenzaron con un problema de herencia, el cual consistia en entender cuan fuertemente las caracteristicas de una generacion de seres vivos se manifestaba en la siguiente generación. Galton inicialmente aproximó el problema examinando caracteristicas de los guisantes. Los primeros planteamientos sobre regresión se obtuvieron en una dispersion bidimensional de el tamaño de los guisantes hijos versus el tamaño de los guisantes padres. Galton uso esta representación de los datos para ilustrar lo que luego los estadisticos conocerian como regresión. La generalización de estos esfuerzos resultaron en el coeficiente de Pearson y mas completos y complejos desarrollos sobre regresión multiple.[3]

>

# Planteamiento del Algoritmo : Regresión Lineal Simple

El modelo de regresión lineal simple consiste en las funciones de la varianza y la esperanza , como sigue \\

\begin{equation}
E(Y|X=x)= \beta_0 + \beta_1 x
\end{equation}

\begin{equation}
Var(Y|X=x)= \sigma^2
\end{equation}

Los parámetros en la función de la media son el intercepto $\beta_0$, el cual es el valor de $E(Y|X=x)$ cuando $x$ es igual cero, y la pendiente $\beta_1$, la cual da cuenta de la rata de cambio de $E(Y|X=x)$ por unidad de $X$.

Figura 2. Ecuación de una linea recta $E(Y|X=x)=\beta_0 + \beta_1 x$.  \\

Cuando se varian los parámetros, podemos obtener todas las posibles lineas rectas. En la mayoria de aplicaciones, los parametros son desconocidos y deben ser estimados usando los datos. La función de varianza se asume una constante, con un valor positivo de magnitud $\sigma^2$.

## Estimación Por Mínimos Cuadrados

Como los parametros son cantidades desconocidas, estimar los parametros de punto de corte y pendiente se vuelve nuestra principal tarea. El valor que debe representar el modelo para cada valor $i$ viene dado por

\begin{equation}
\hat{y}_i = \hat{E} (Y|X=x_i)= \hat{\beta_0} + \hat{\beta_1} x_i
\end{equation}

Como los anteriores son valores a estimar, se denotan con el sombrero y letras griegas. \\

Los errores de la estimación se pueden calcular, como :

\begin{equation}
e_i =y_i -(\beta_0 + \beta_1)x_i , \ \ i=1,...,n
\end{equation}

Todos los mínimos cuadrados para un regresión simple dependen solo de promedios, sumas de cuadrados y sumas de productos cruzados. En la siguiente tabla se consigna la notación usada por Weisberg. \\

Los mínimos cuadrados pueden ser derivados de muchas maneras, y el proposito de este documento no es incluir una deducción detallada de ese proceso, en cambio, se quiere presentar el algoritmo correspondiente para calcular el ajuste lineal. Los valores de los estimadores $\hat{\beta_0}$ , $\hat{\beta_1}$, vienen dados por \\

\begin{equation}
\hat{\beta_1}=\frac{SXY}{SXX} =r_{xy}\frac{SD_y}{SD_x} =r_{xy} (\frac{SYY}{SXX})^2
\end{equation}

\begin{equation}
\hat{\beta_0}= \bar{y} - \hat{\beta_1} \bar{x}
\end{equation}

Los valores anteriores permiten calcular la recta de mejor ajuste a un conjunto de parejas de datos $(x_i,y_i)$, de tal manera que la siguiente función tenga el valor mínimo posible

\begin{equation}
RSS(\beta_0, \beta_1) = \sum_{i=1}^{n} [y_i -(\beta_{0} + \beta_{1} x_i)]^2
\end{equation}

# Ejemplo: Cambio Climático

Han existido mucho estudios documentando que la temperatura global promedio se ha ido incrementando a lo largo del último siglo. Las consecuencias de un aumento continuo de la temperatura a nivel global sería terrible. Aumentando la altura del nivel del mar y aumentando la frecuencia de eventos climaticos extremos que afectarian billones de personas. Este problema se abordo en un curso del MIT a modo de Tarea , y se pude ver la información correspondiente en el siguiente enlace [LinearRegression](https://ocw.mit.edu/courses/sloan-school-of-management/15-071-the-analytics-edge-spring-2017/linear-regression/assignment-2/).  \\

En este problema se intenta estudiar la relación entre la temperatura promedio global y otros factores que se describen a continuación: \\

*   *Year*: El año de observación
*   *Month*: El mes de observación
*   *Temp*: La diferencia en grados Celsius entre la temperatura promedio global en un periodo y un valor de referencia arbitrario. Esta información viene de [Climatic Research Unit](https://sites.uea.ac.uk/cru/) . \\

*   *CO2,N2O,CH4,CFC.11,CFC.12*: Concentraciones atmosfericas de dioxido de carbono (CO2), oxido nitroso (NO2), metano (CH4), triclorofluorometano (CFC-11), diclorodifluorometano (CFC-12), respectivamente. Los datos fueron tomados de [ESRL/NOAA Global Monitoring Division](https://www.esrl.noaa.gov/gmd/ccgg/data-products.html).  \\

*   CO2, N2O, y CH4 son expresados en ppmv ( partes por millon de volumen, ...i.e, 397 ppmv de CO2 significa que CO2 constituye 397 millones de particulas de todo el volumen total de la atmosfera). \\

*  *Aerosols*: La profundidad óptica media del aerosol estratosférico a 550 nm.

*   *TSI*: Irradiancia solar total en $\frac{W}{m^2}$ . Esta tasa indica la cantidad de energia por segundo y por unidad de area que impacta a la tierra.

##Codigo en python
El siguiente codigo se tomo y modifico  del a fuente :[Codigo](https://www.aprendemachinelearning.com/regresion-lineal-en-espanol-con-python/). Se utiliza para analisar el set de datos anterior, ajeno a su proposito orginal.\\

```
import numpy as np
#Importando Numpy
import pandas as pd
#Importando Pandas
import seaborn as sb
#Importando la libreria de visualizacion de python
import matplotlib.pyplot as plt
#Importando la libreria de visualizacion de python
%matplotlib inline
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
plt.rcParams['figure.figsize'] = (16, 9)
plt.style.use('ggplot')
from sklearn import linear_model
#Importando de la biblioteca de aprendizaje automatico sklearn el modelo de regresion lineal.
from sklearn.metrics import mean_squared_error, r2_score
```

```
#cargamos los datos de entrada de cambio climatico
data = pd.read_csv("climate_change.csv")
#veamos cuantas dimensiones y registros contiene (Numero de filas y columnas)
data.shape
```

    (308, 11)

```
#Vista de los primeros y ultimos 5 registros
data.head()
```

      Year
      Month
      MEI
      CO2
      CH4
      N2O
      CFC-11
      CFC-12
      TSI
      Aerosols
      Temp

      0
      1983
      5
      2.556
      345.96
      1638.59
      303.677
      191.324
      350.113
      1366.1024
      0.0863
      0.109

      1
      1983
      6
      2.167
      345.52
      1633.71
      303.746
      192.057
      351.848
      1366.1208
      0.0794
      0.118

      2
      1983
      7
      1.741
      344.15
      1633.22
      303.795
      192.818
      353.725
      1366.2850
      0.0731
      0.137

      3
      1983
      8
      1.130
      342.25
      1631.35
      303.839
      193.602
      355.633
      1366.4202
      0.0673
      0.176

      4
      1983
      9
      0.428
      340.17
      1648.40
      303.901
      194.392
      357.465
      1366.2335
      0.0619
      0.149

```
#Filtrando los datos a dos culumnas
filtered_data = data[(data['Year']<= 3500) & (data['Temp']<= 3500)]
# Asignamos nuestra variable de entrada X para entrenamiento y las etiquetas Y.
dataX =filtered_data[["Year"]]
X_train = np.array(dataX)
y_train = filtered_data['Temp'].values

# Creamos el objeto de Regresión Linear
regr = linear_model.LinearRegression()

# Entrenamos nuestro modelo
regr.fit(X_train, y_train)

# Hacemos las predicciones que en definitiva una línea (en este caso, al ser 2D)
y_pred = regr.predict(X_train)

# Veamos los coeficienetes obtenidos, En nuestro caso, serán la pendiente
print('Coefficients: \n', regr.coef_)
# Este es el valor donde corta el eje Y (en X=0)
print('Independent term: \n', regr.intercept_)
# Error Cuadrado Medio
print("Mean squared error: %.2f" % mean_squared_error(y_train, y_pred))
# Puntaje de Varianza. El mejor puntaje es un 1.0
print('Variance score: %.2f' % r2_score(y_train, y_pred))
```

    Coefficients:
     [0.01823254]
    Independent term:
     -36.129211902349155
    Mean squared error: 0.01
    Variance score: 0.57

```
#Graficando con matplotlib  y usando ggplot
plt.scatter(X_train, y_train, c='r', edgecolors=(0, 0, 0), alpha=0.5)
b , a = regr.coef_ , regr.intercept_
plt.plot(X_train, [a + b * x for x in X_train], c="b")
plt.xlabel('Año (12 datos por año, uno para cada mes) ')
plt.ylabel('Delta de Temperatura')
plt.show()

```

La grafica anterior representa por año, la variación del intervalo en el aumento de la temperatura y a su vez el aumento lineal a lo largo del tiempo en 25 años desde 1983 hasta 2008. Es una grafica interesante, pues se observa que aunque no se tenga una función como tal, pues para cada abscisa se tiene varias ordenadas, aún asi, es aplicable la regresión lineal. \\

# Conclusiones

*   La regresión lineal es una muy buena aproximación para predecir el comportamiento de dos variables que se relacionan de manera proporcional. Para nuestro caso se observa que la temperatura a nivel global ha aumentado de manera lineal a lo largo de los ultimos 25 años, lo cual es una clara de evidencia de que el calentamiento global es un problema serio.

* El procedimiento anterior resulta de suma importancia, pues al tener una función que me permita relacionar la variable dependiente con la independiente, se podrá calcular a futuro el valor de la variable dependiente o almenos su comportamiento aparente. Todo lo anterior dependiendo de que tan bueno sea el ajuste.

# Bibliografía

1.   *Weisberg, S. (2005). Applied linear regression (Vol. 528). John Wiley & Sons.*
2.   *Finney*, D. J. (1996). A note on the history of regression.

3.   Stanton, J. M. (2001). Galton, Pearson, and the peas: A brief history of linear regression for statistics instructors. Journal of Statistics Education, 9(3).

```

```


```
#A=['1','2','3']
A = [123]
for a in A:
  print(3*a)
```

    369

```
n =20
X = n**2
print(X)
```

    400

```
!pip install qiskit

```

    Collecting qiskit
      Downloading https://files.pythonhosted.org/packages/38/4e/f275e4b0bc1b8d1c61d8088d693e480fa396c8f3d32e516655f25c510792/qiskit-0.19.6.tar.gz
    Collecting qiskit-terra==0.14.2
      Downloading https://files.pythonhosted.org/packages/64/84/47c2b87551fe81a435eb4224991c1713d538b0605bda4e3c737f4a9f2cc2/qiskit_terra-0.14.2-cp36-cp36m-manylinux2010_x86_64.whl (6.7MB)
         |████████████████████████████████| 6.7MB 4.4MB/s
    Collecting qiskit-aer==0.5.2
      Downloading https://files.pythonhosted.org/packages/45/6f/2d269684891b634cce6ddb5684fd004c7b6bf986cec8544f4b6f495c8b99/qiskit_aer-0.5.2-cp36-cp36m-manylinux2010_x86_64.whl (23.3MB)
         |████████████████████████████████| 23.3MB 1.3MB/s
    Collecting qiskit-ibmq-provider==0.7.2
      Downloading https://files.pythonhosted.org/packages/92/1f/0c6b290064a471a8a9c1e3366367b46d320efdad6b730eadefbd1f3c4eb0/qiskit_ibmq_provider-0.7.2-py3-none-any.whl (155kB)
         |████████████████████████████████| 163kB 43.7MB/s
    Collecting qiskit-ignis==0.3.3
      Downloading https://files.pythonhosted.org/packages/06/5e/273c6f99b4b64dcbab37990627778ed38d8f52e8060db7fc67f38f09fbb2/qiskit_ignis-0.3.3-py3-none-any.whl (179kB)
         |████████████████████████████████| 184kB 49.5MB/s
    Collecting qiskit-aqua==0.7.3
      Downloading https://files.pythonhosted.org/packages/89/18/00c426f06abfa0461a4d794d833c036f8ac5f88062f368d01f739ee1c032/qiskit_aqua-0.7.3-py3-none-any.whl (1.9MB)
         |████████████████████████████████| 1.9MB 46.4MB/s
    Collecting marshmallow-polyfield<6,>=5.7
      Downloading https://files.pythonhosted.org/packages/0c/7e/ceb805d05cd03709b8de122b4ac1e736c4eb91d05281ad2a2bcb484accef/marshmallow-polyfield-5.9.tar.gz
    Requirement already satisfied: dill>=0.3 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (0.3.2)
    Collecting marshmallow<4,>=3
      Downloading https://files.pythonhosted.org/packages/8e/4d/1c64381398d25bc46250373dbeec89713f06e23eba8531c9eccd4e671a8a/marshmallow-3.6.1-py2.py3-none-any.whl (45kB)
         |████████████████████████████████| 51kB 6.2MB/s
    Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (2.6.0)
    Collecting ply>=3.10
      Downloading https://files.pythonhosted.org/packages/a3/58/35da89ee790598a0700ea49b2a66594140f44dec458c07e8e3d4979137fc/ply-3.11-py2.py3-none-any.whl (49kB)
         |████████████████████████████████| 51kB 6.4MB/s
    Collecting retworkx>=0.3.2
      Downloading https://files.pythonhosted.org/packages/28/44/e28d30808fc093bb82393737f36f1fd370afe5ed82a08c382c4672340916/retworkx-0.3.4-cp36-cp36m-manylinux2010_x86_64.whl (763kB)
         |████████████████████████████████| 768kB 43.9MB/s
    Requirement already satisfied: networkx>=2.2; python_version > "3.5" in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (2.4)
    Collecting python-constraint>=1.4
      Downloading https://files.pythonhosted.org/packages/37/8b/5f1bc2734ca611943e1d6733ee244238679f6410a10cd45ede55a61a8402/python-constraint-1.4.0.tar.bz2
    Collecting fastjsonschema>=2.10
      Downloading https://files.pythonhosted.org/packages/3a/2b/5e93ebbdc92fe742bfc006f79336c2ddcb436747ef579bc05057c43ad876/fastjsonschema-2.14.4-py3-none-any.whl
    Requirement already satisfied: python-dateutil>=2.8.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (2.8.1)
    Collecting sympy>=1.3
      Downloading https://files.pythonhosted.org/packages/1e/ed/4b0576282597e87e7cf3be33fa4f738d5974471f9b59a55b3730c3877530/sympy-1.6.1-py3-none-any.whl (5.8MB)
         |████████████████████████████████| 5.8MB 33.4MB/s
    Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (1.18.5)
    Requirement already satisfied: scipy>=1.4 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (1.4.1)
    Requirement already satisfied: psutil>=5 in /usr/local/lib/python3.6/dist-packages (from qiskit-terra==0.14.2->qiskit) (5.4.8)
    Requirement already satisfied: cython>=0.27.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-aer==0.5.2->qiskit) (0.29.20)
    Collecting pybind11>=2.4
      Downloading https://files.pythonhosted.org/packages/89/e3/d576f6f02bc75bacbc3d42494e8f1d063c95617d86648dba243c2cb3963e/pybind11-2.5.0-py2.py3-none-any.whl (296kB)
         |████████████████████████████████| 296kB 37.4MB/s
    Requirement already satisfied: requests>=2.19 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (2.23.0)
    Collecting nest-asyncio!=1.1.0,>=1.0.0
      Downloading https://files.pythonhosted.org/packages/74/b4/b24e0a271fb78990c2c62238321686454824b1357ce7abcf20f431fd903d/nest_asyncio-1.3.3-py3-none-any.whl
    Collecting requests-ntlm>=1.1.0
      Downloading https://files.pythonhosted.org/packages/03/4b/8b9a1afde8072c4d5710d9fa91433d504325821b038e00237dc8d6d833dc/requests_ntlm-1.1.0-py2.py3-none-any.whl
    Collecting websockets<8,>=7
      Downloading https://files.pythonhosted.org/packages/43/71/8bfa882b9c502c36e5c9ef6732969533670d2b039cbf95a82ced8f762b80/websockets-7.0-cp36-cp36m-manylinux1_x86_64.whl (63kB)
         |████████████████████████████████| 71kB 8.9MB/s
    Requirement already satisfied: urllib3>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from qiskit-ibmq-provider==0.7.2->qiskit) (1.24.3)
    Requirement already satisfied: scikit-learn>=0.17 in /usr/local/lib/python3.6/dist-packages (from qiskit-ignis==0.3.3->qiskit) (0.22.2.post1)
    Requirement already satisfied: setuptools>=40.1.0 in /usr/local/lib/python3.6/dist-packages (from qiskit-ignis==0.3.3->qiskit) (47.3.1)
    Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (2.10.0)
    Collecting docplex
      Downloading https://files.pythonhosted.org/packages/00/06/ad4441a00b8a9ff415882ff31273fe6519034879b6c2b65c47758a0278d5/docplex-2.14.186.tar.gz (572kB)
         |████████████████████████████████| 573kB 37.8MB/s
    Collecting dlx
      Downloading https://files.pythonhosted.org/packages/54/c0/b8fb5bb727e983b6f5251433ef941b48f38c65bb0bd6ec509e9185bcd406/dlx-1.0.4.tar.gz
    Requirement already satisfied: fastdtw in /usr/local/lib/python3.6/dist-packages (from qiskit-aqua==0.7.3->qiskit) (0.3.4)
    Collecting quandl
      Downloading https://files.pythonhosted.org/packages/07/ab/8cd479fba8a9b197a43a0d55dd534b066fb8e5a0a04b5c0384cbc5d663aa/Quandl-3.5.0-py2.py3-none-any.whl
    Collecting pyscf; sys_platform != "win32"
      Downloading https://files.pythonhosted.org/packages/0c/69/c6dad63aec5519c287036e82beb36ca46e4a409604676b8787425fa7499c/pyscf-1.7.3-cp36-cp36m-manylinux1_x86_64.whl (26.0MB)
         |████████████████████████████████| 26.0MB 1.3MB/s
    Requirement already satisfied: decorator>=4.3.0 in /usr/local/lib/python3.6/dist-packages (from networkx>=2.2; python_version > "3.5"->qiskit-terra==0.14.2->qiskit) (4.4.2)
    Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.8.0->qiskit-terra==0.14.2->qiskit) (1.12.0)
    Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.6/dist-packages (from sympy>=1.3->qiskit-terra==0.14.2->qiskit) (1.1.0)
    Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit) (2.9)
    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit) (2020.6.20)
    Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19->qiskit-ibmq-provider==0.7.2->qiskit) (3.0.4)
    Collecting cryptography>=1.3
      Downloading https://files.pythonhosted.org/packages/3c/04/686efee2dcdd25aecf357992e7d9362f443eb182ecd623f882bc9f7a6bba/cryptography-2.9.2-cp35-abi3-manylinux2010_x86_64.whl (2.7MB)
         |████████████████████████████████| 2.7MB 42.0MB/s
    Collecting ntlm-auth>=1.0.2
      Downloading https://files.pythonhosted.org/packages/ff/84/97c550164b54942b0e908c31ef09d9469f3ba4cd7332a671e2125732f63b/ntlm_auth-1.5.0-py2.py3-none-any.whl
    Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.17->qiskit-ignis==0.3.3->qiskit) (0.15.1)
    Requirement already satisfied: more-itertools in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit) (8.4.0)
    Collecting inflection>=0.3.1
      Downloading https://files.pythonhosted.org/packages/d2/cd/f04c661d1b5ba6b7d77008e8fedd28a27a683eeeffcd93c6b2dbe54ea983/inflection-0.5.0-py2.py3-none-any.whl
    Requirement already satisfied: pandas>=0.14 in /usr/local/lib/python3.6/dist-packages (from quandl->qiskit-aqua==0.7.3->qiskit) (1.0.5)
    Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python3.6/dist-packages (from cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit) (1.14.0)
    Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.14->quandl->qiskit-aqua==0.7.3->qiskit) (2018.9)
    Requirement already satisfied: pycparser in /usr/local/lib/python3.6/dist-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.3->requests-ntlm>=1.1.0->qiskit-ibmq-provider==0.7.2->qiskit) (2.20)
    Building wheels for collected packages: qiskit, marshmallow-polyfield, python-constraint, docplex, dlx
      Building wheel for qiskit (setup.py) ... done
      Created wheel for qiskit: filename=qiskit-0.19.6-cp36-none-any.whl size=3019 sha256=8b1ed62dfb51f147aadd9aebcf5183a04ae775c23d86a84354dd97b4d8c70723
      Stored in directory: /root/.cache/pip/wheels/35/45/55/8b82d355edf738ebd6d7f261f17ef1e7ca9ffc7d139c878e10
      Building wheel for marshmallow-polyfield (setup.py) ... done
      Created wheel for marshmallow-polyfield: filename=marshmallow_polyfield-5.9-cp36-none-any.whl size=8537 sha256=cad8dff8589a6e1838ec5fe1d4244516fdae2aa69207663dbdd100c4dba7c614
      Stored in directory: /root/.cache/pip/wheels/69/27/3e/7472f75eab2db111aa387715fe009af15899459517fc1a1906
      Building wheel for python-constraint (setup.py) ... done
      Created wheel for python-constraint: filename=python_constraint-1.4.0-py2.py3-none-any.whl size=24080 sha256=c0bbecc28bd5c0e1a554259dc44306f4bcb304dab352102b0c664f9bf42d0442
      Stored in directory: /root/.cache/pip/wheels/34/31/15/7b070b25d0a549d20ce2e9fe6d727471c2c61ef904720fd40c
      Building wheel for docplex (setup.py) ... done
      Created wheel for docplex: filename=docplex-2.14.186-cp36-none-any.whl size=634442 sha256=961b6aacb49d47a18e3a6b9451323180bba2aca63a08d6703148a3985357822a
      Stored in directory: /root/.cache/pip/wheels/aa/28/cd/ba75f92d49b25dacec6b80f99efcc393dc84abf33f96632ac4
      Building wheel for dlx (setup.py) ... done
      Created wheel for dlx: filename=dlx-1.0.4-cp36-none-any.whl size=5712 sha256=2dd838c4ad0c50328b2242cd1f94021275d4df6b3e148d7a37c51a696884ec54
      Stored in directory: /root/.cache/pip/wheels/bb/ba/15/fdd0deb104df3254912998150ba9245668db06b00af5912d1a
    Successfully built qiskit marshmallow-polyfield python-constraint docplex dlx
    Installing collected packages: marshmallow, marshmallow-polyfield, ply, retworkx, python-constraint, fastjsonschema, sympy, qiskit-terra, pybind11, qiskit-aer, nest-asyncio, cryptography, ntlm-auth, requests-ntlm, websockets, qiskit-ibmq-provider, qiskit-ignis, docplex, dlx, inflection, quandl, pyscf, qiskit-aqua, qiskit
      Found existing installation: sympy 1.1.1
        Uninstalling sympy-1.1.1:
          Successfully uninstalled sympy-1.1.1
    Successfully installed cryptography-2.9.2 dlx-1.0.4 docplex-2.14.186 fastjsonschema-2.14.4 inflection-0.5.0 marshmallow-3.6.1 marshmallow-polyfield-5.9 nest-asyncio-1.3.3 ntlm-auth-1.5.0 ply-3.11 pybind11-2.5.0 pyscf-1.7.3 python-constraint-1.4.0 qiskit-0.19.6 qiskit-aer-0.5.2 qiskit-aqua-0.7.3 qiskit-ibmq-provider-0.7.2 qiskit-ignis-0.3.3 qiskit-terra-0.14.2 quandl-3.5.0 requests-ntlm-1.1.0 retworkx-0.3.4 sympy-1.6.1 websockets-7.0

```

```

```
#Creating Bell State
from qiskit import QuantumCircuit,execute,Aer
import numpy as np
%matplotlib inline
from qiskit.visualization import plot_histogram, plot_bloch_multivector

#create a Quantum circuit with 2 Qubits & 2 classical bits
circuit = QuantumCircuit(2,2)
#Add a H gate on qubit 0
circuit.h(0)

#adding a CX(CNOT) gate on q0 & target will be q1
circuit.cx(0,1)

# Measurement
circuit.measure([0,1],[0,1])

#AER'S AQUA  Simulator
simulator = Aer.get_backend('qasm_simulator')

#execute the circuit
job = execute(circuit,simulator, shots = 1024)

# result
result = job.result()

#resturn Counts
counts = result.get_counts(circuit)
print("/ total count for 00 & 11 are: ", counts)
circuit.draw(output='mpl')
```

```

```