iPython 101 - using numpy, scipy, matplotlib, sqlite3 and Bokeh.

it takes a long time to load - be patient!


In [11]:
a = "hello world"
print(a)


hello world

In [2]:
#%quickref

from bokeh.plotting import figure,  show 

from bokeh.io import output_notebook
output_notebook()
p = figure(plot_width=400, plot_height=400) 
# add a line renderer 
p.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=2) 
show(p)


BokehJS successfully loaded.

In [9]:
#from numpy import pi,linspace,sin
#from matplotlib.pyplot import plot
#x = linspace(0,3*pi,500)
#print(x)
#plot(x,sin(x**2))
#title('A simple chirp');
# OneNote Python 101 - Worked Exampes - bokeh multi line, multi axis 


import numpy as np 
from bokeh.plotting import  show, figure 
from bokeh.io import output_notebook

x = np.linspace(0, 4*np.pi, 100) 
#print(x)
y = np.sin(x) 

output_notebook() 

p = figure() 
p.circle(x, y, legend="sin(x)") 
p.line(x, y, legend="sin(x)") 
p.line(x, 2*y, legend="2*sin(x)", 
       line_dash=[4, 4], line_color="orange", line_width=2) 
p.square(x, 3*y, legend="3*sin(x)", fill_color=None, line_color="green") 
p.line(x, 3*y, legend="3*sin(x)", line_color="green") 

show(p)


[  0.           0.12693304   0.25386607   0.38079911   0.50773215
   0.63466518   0.76159822   0.88853126   1.01546429   1.14239733
   1.26933037   1.3962634    1.52319644   1.65012947   1.77706251
   1.90399555   2.03092858   2.15786162   2.28479466   2.41172769
   2.53866073   2.66559377   2.7925268    2.91945984   3.04639288
   3.17332591   3.30025895   3.42719199   3.55412502   3.68105806
   3.8079911    3.93492413   4.06185717   4.1887902    4.31572324
   4.44265628   4.56958931   4.69652235   4.82345539   4.95038842
   5.07732146   5.2042545    5.33118753   5.45812057   5.58505361
   5.71198664   5.83891968   5.96585272   6.09278575   6.21971879
   6.34665183   6.47358486   6.6005179    6.72745093   6.85438397
   6.98131701   7.10825004   7.23518308   7.36211612   7.48904915
   7.61598219   7.74291523   7.86984826   7.9967813    8.12371434
   8.25064737   8.37758041   8.50451345   8.63144648   8.75837952
   8.88531256   9.01224559   9.13917863   9.26611167   9.3930447
   9.51997774   9.64691077   9.77384381   9.90077685  10.02770988
  10.15464292  10.28157596  10.40850899  10.53544203  10.66237507
  10.7893081   10.91624114  11.04317418  11.17010721  11.29704025
  11.42397329  11.55090632  11.67783936  11.8047724   11.93170543
  12.05863847  12.1855715   12.31250454  12.43943758  12.56637061]
BokehJS successfully loaded.

In [ ]:
from numpy import *
print( cos(array([0, pi/2, pi])) ) 
      
x = array([1,2,3])
y = array([4,5,6])
print( cross(x,y) )  
# vector cross-product

In [ ]:
#%pylab inline
for i in xrange(1000) : 
    print(i)

In [16]:
#from bokeh.plotting import figure, output_file, show

# prepare some data
#x = [1, 2, 3, 4, 5]
#y = [6, 7, 2, 4, 5]

# output to static HTML file
#output_file("lines.html", title="line plot example")

# create a new plot with a title and axis labels
#p = figure(title="simple line example", x_axis_label='x', y_axis_label='y')

# add a line renderer with legend and line thickness
#p.line(x, y, legend="Temp.", line_width=2)

# show the results
#show(p)

In [17]:
from bokeh.sampledata.iris import flowers
#print(dir(flowers))

#from bokeh.plotting import figure, show, output_file
from bokeh.plotting import figure, show
from bokeh.io import output_notebook

colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}
flowers['color'] = flowers['species'].map(lambda x: colormap[x])

#output_file("iris.html", title="iris.py example")
#output_notebook("iris.html", title="iris.py example")
output_notebook()


p = figure(title = "Iris Morphology")
p.xaxis.axis_label = 'Petal Length'
p.yaxis.axis_label = 'Petal Width'

p.circle(flowers["petal_length"], flowers["petal_width"], color=flowers["color"], fill_alpha=0.2, size=10, )

show(p)


BokehJS successfully loaded.

In [ ]:


In [19]:
import pandas
df = pandas.read_csv("C:\Users\pleb1.BRUCE-PC\PycharmProjects\My_Second_Project\medals.csv")
df.head(10)


Out[19]:
Year City Sport Discipline NOC Event Event gender Medal
0 1924 Chamonix Skating Figure skating AUT individual M Silver
1 1924 Chamonix Skating Figure skating AUT individual W Gold
2 1924 Chamonix Skating Figure skating AUT pairs X Gold
3 1924 Chamonix Bobsleigh Bobsleigh BEL four-man M Bronze
4 1924 Chamonix Ice Hockey Ice Hockey CAN ice hockey M Gold
5 1924 Chamonix Biathlon Biathlon FIN military patrol M Silver
6 1924 Chamonix Skating Figure skating FIN pairs X Silver
7 1924 Chamonix Skating Speed skating FIN 10000m M Gold
8 1924 Chamonix Skating Speed skating FIN 10000m M Silver
9 1924 Chamonix Skating Speed skating FIN 1500m M Gold

In [20]:
__author__ = 'Bruce.Woodley'
# version 3
#http://sqlite.org/
#https://addons.mozilla.org/en-us/firefox/addon/sqlite-manager/
#For Ankur Pandey's  "sql learnings"
def main():
    import sqlite3

    conn = sqlite3.connect('music.sqlite3')
    cur = conn.cursor()
    cur.execute('DROP TABLE IF EXISTS Tracks')
    cur.execute('CREATE TABLE Tracks (title TEXT , plays INTEGER)')
    conn.close()

    conn = sqlite3.connect('music.sqlite3')
    cur = conn.cursor()
    cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ?)', ('Thunderstruck',20) )
    cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ?)',('My Way', 15) )
    cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ?)',('Lean On (by Major Lazer & DJ Snake)', 100) )
    conn.commit()

    print("Tracks:")
    cur.execute('SELECT title, plays FROM Tracks')
    for row in cur :
       print(row)
    cur.execute('DELETE FROM Tracks WHERE plays < 100')
    conn.commit()
    cur.close()

    return

main()


Tracks:
(u'Thunderstruck', 20)
(u'My Way', 15)
(u'Lean On (by Major Lazer & DJ Snake)', 100)

In [8]:
import pandas as pd 
from bokeh.plotting import figure 

AAPL = pd.read_csv( 
    "http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000&d=0&e=1&f=2015", 
    parse_dates=['Date']) 
#print(AAPL)

MSFT = pd.read_csv( 
    "http://ichart.yahoo.com/table.csv?s=MSFT&a=0&b=1&c=2000&d=0&e=1&f=2015", 
    parse_dates=['Date']) 

IBM = pd.read_csv( 
    "http://ichart.yahoo.com/table.csv?s=IBM&a=0&b=1&c=2000&d=0&e=1&f=2015", 
    parse_dates=['Date']) 

def make_figure(): 
    p = figure(x_axis_type="datetime", width=700, height=300) 
    p.line(AAPL['Date'], AAPL['Adj Close'], color='#A6CEE3', legend='AAPL') 
    p.line(IBM['Date'], IBM['Adj Close'], color='#33A02C', legend='IBM') 
    p.line(MSFT['Date'], MSFT['Adj Close'], color='#FB9A99', legend='MSFT') 
    p.title = "Stock Closing Prices" 
    p.grid.grid_line_alpha=0.3 
    p.xaxis.axis_label = 'Date' 
    p.yaxis.axis_label = 'Price' 
    p.legend.orientation = "top_left" 
    return p 

from bokeh.io import output_notebook, show 

output_notebook() 

p = make_figure() 

show(p)


BokehJS successfully loaded.

In [25]:
import numpy as np 
from bokeh.plotting import  show, figure 
from bokeh.io import output_notebook

x = np.linspace(-1.0*np.pi, 2*np.pi, 400) 
#print(x)
#y1 = np.sin(x) 
y1 =np.exp(x)

output_notebook() 

p = figure() 
p.circle(x, y1, legend="sin(x)",line_color="orange") 
#p.circle(x, y2, legend="exp(x)",line_color="orange") 




show(p)


BokehJS successfully loaded.

In [ ]:


In [ ]:


In [25]:
from bokeh.sampledata.autompg import autompg as df 
#from bokeh.charts import Scatter, output_file, show 
from bokeh.charts import Scatter  
from bokeh.io import output_notebook, show 



scatter = Scatter(df, x='mpg', y='hp', color='cyl', marker='origin', 
                  title="mpg", xlabel="Miles Per Gallon", ylabel="Horsepower") 

#output_file('scatter.html') 
output_notebook() 


show(scatter)


C:\Anaconda2\lib\site-packages\bokeh\charts\_attributes.py:78: FutureWarning: sort(columns=....) is deprecated, use sort_values(by=.....)
  df = df.sort(columns=columns)
BokehJS successfully loaded.

In [26]:
#from bokeh.sampledata.autompg import autompg as df
from bokeh.sampledata.autompg import autompg
from bokeh.sampledata.iris import flowers
#from bokeh.sampledata.stocks  import AAPL

#print(type(df))
print(str(flowers))
#print(df.index)
#print(df.info)


     sepal_length  sepal_width  petal_length  petal_width    species color
0             5.1          3.5           1.4          0.2     setosa   red
1             4.9          3.0           1.4          0.2     setosa   red
2             4.7          3.2           1.3          0.2     setosa   red
3             4.6          3.1           1.5          0.2     setosa   red
4             5.0          3.6           1.4          0.2     setosa   red
5             5.4          3.9           1.7          0.4     setosa   red
6             4.6          3.4           1.4          0.3     setosa   red
7             5.0          3.4           1.5          0.2     setosa   red
8             4.4          2.9           1.4          0.2     setosa   red
9             4.9          3.1           1.5          0.1     setosa   red
10            5.4          3.7           1.5          0.2     setosa   red
11            4.8          3.4           1.6          0.2     setosa   red
12            4.8          3.0           1.4          0.1     setosa   red
13            4.3          3.0           1.1          0.1     setosa   red
14            5.8          4.0           1.2          0.2     setosa   red
15            5.7          4.4           1.5          0.4     setosa   red
16            5.4          3.9           1.3          0.4     setosa   red
17            5.1          3.5           1.4          0.3     setosa   red
18            5.7          3.8           1.7          0.3     setosa   red
19            5.1          3.8           1.5          0.3     setosa   red
20            5.4          3.4           1.7          0.2     setosa   red
21            5.1          3.7           1.5          0.4     setosa   red
22            4.6          3.6           1.0          0.2     setosa   red
23            5.1          3.3           1.7          0.5     setosa   red
24            4.8          3.4           1.9          0.2     setosa   red
25            5.0          3.0           1.6          0.2     setosa   red
26            5.0          3.4           1.6          0.4     setosa   red
27            5.2          3.5           1.5          0.2     setosa   red
28            5.2          3.4           1.4          0.2     setosa   red
29            4.7          3.2           1.6          0.2     setosa   red
..            ...          ...           ...          ...        ...   ...
120           6.9          3.2           5.7          2.3  virginica  blue
121           5.6          2.8           4.9          2.0  virginica  blue
122           7.7          2.8           6.7          2.0  virginica  blue
123           6.3          2.7           4.9          1.8  virginica  blue
124           6.7          3.3           5.7          2.1  virginica  blue
125           7.2          3.2           6.0          1.8  virginica  blue
126           6.2          2.8           4.8          1.8  virginica  blue
127           6.1          3.0           4.9          1.8  virginica  blue
128           6.4          2.8           5.6          2.1  virginica  blue
129           7.2          3.0           5.8          1.6  virginica  blue
130           7.4          2.8           6.1          1.9  virginica  blue
131           7.9          3.8           6.4          2.0  virginica  blue
132           6.4          2.8           5.6          2.2  virginica  blue
133           6.3          2.8           5.1          1.5  virginica  blue
134           6.1          2.6           5.6          1.4  virginica  blue
135           7.7          3.0           6.1          2.3  virginica  blue
136           6.3          3.4           5.6          2.4  virginica  blue
137           6.4          3.1           5.5          1.8  virginica  blue
138           6.0          3.0           4.8          1.8  virginica  blue
139           6.9          3.1           5.4          2.1  virginica  blue
140           6.7          3.1           5.6          2.4  virginica  blue
141           6.9          3.1           5.1          2.3  virginica  blue
142           5.8          2.7           5.1          1.9  virginica  blue
143           6.8          3.2           5.9          2.3  virginica  blue
144           6.7          3.3           5.7          2.5  virginica  blue
145           6.7          3.0           5.2          2.3  virginica  blue
146           6.3          2.5           5.0          1.9  virginica  blue
147           6.5          3.0           5.2          2.0  virginica  blue
148           6.2          3.4           5.4          2.3  virginica  blue
149           5.9          3.0           5.1          1.8  virginica  blue

[150 rows x 6 columns]

In [27]:
a=0xfe
print(hex(a), int(a), oct(a), bin(a))

print(int('010', 2)  ) 
print(int('010', 8)  ) 
print(int('010', 10)  ) 
print(int('010', 16)  ) 

print(int('ff', 16)  )


('0xfe', 254, '0376', '0b11111110')
2
8
10
16
255

In [ ]:
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [1, 2, 6]
fig = plt.figure()
ax = plt.axes()

plt.plot(x, y)
plt.show()

In [ ]:
'''
  Example of selecting a transformation from two equally probable
  transformations
  '''
  import matplotlib.pyplot as plt
  import random

  def transformation_1(p):
      x = p[0]
      y = p[1]
      return x + 1, y - 1

  def transformation_2(p):
      x = p[0]
      y = p[1]
      return x + 1, y + 1

  def transform(p):
      # List of transformation functions
      transformations = [transformation_1, transformation_2]
      # Pick a random transformation function and call it
      t = random.choice(transformations)
      x, y = t(p)
      return x, y

  def build_trajectory(p, n):
      x = [p[0]]
      y = [p[1]]
      for i in range(n):
          p = transform(p)
          x.append(p[0])
          y.append(p[1])
      return x, y
  if __name__ == '__main__':
      # Initial point
      p = (1, 1)
      n = int(input('Enter the number of iterations: '))
      x, y = build_trajectory(p, n)
      # Plot
      plt.plot(x, y)
      plt.xlabel('X')
      plt.ylabel('Y')
      plt.show()

In [ ]:
'''
Draw a Barnsley Fern
'''
import random
import matplotlib.pyplot as plt

def transformation_1(p):
    x = p[0]
    y = p[1]
    x1 = 0.85*x + 0.04*y
    y1 = -0.04*x + 0.85*y + 1.6
    return x1, y1

def transformation_2(p):
    x = p[0]
    y = p[1]
    x1 = 0.2*x - 0.26*y
    y1 = 0.23*x + 0.22*y + 1.6
    return x1, y1

def transformation_3(p):
    x = p[0]
    y = p[1]
    x1 = -0.15*x + 0.28*y
    y1 = 0.26*x + 0.24*y + 0.44
    return x1, y1

def transformation_4(p):
    x = p[0]
    y = p[1]
    x1 = 0
    y1 = 0.16*y
    return x1, y1

def get_index(probability):
      r = random.random()
      c_probability = 0
      sum_probability = []
      for p in probability:
          c_probability += p
          sum_probability.append(c_probability)
      for item, sp in enumerate(sum_probability):
          if r <= sp:
              return item
      return len(probability)-1

def transform(p):
      # List of transformation functions
      transformations = [transformation_1, transformation_2,
                             transformation_3, transformation_4]
      probability = [0.85, 0.07, 0.07, 0.01]
      # Pick a random transformation function and call it
      tindex = get_index(probability)
      t = transformations[tindex]
      x, y = t(p)
      return x, y

def draw_fern(n):
      # We start with (0, 0)
      x = [0]
      y = [0]

      x1, y1 = 0, 0
      for i in range(n):
         x1, y1 = transform((x1, y1))
         x.append(x1)
         y.append(y1)
      return x, y

if __name__ == '__main__':
      n = int(input('Enter the number of points in the Fern: '))
      x, y = draw_fern(n)
      # Plot the points
      plt.plot(x, y, 'o')
      plt.title('Fern with {0} points'.format(n))
      plt.show()

In [ ]:
import math
math.sin(math.pi/2)

In [ ]:
import inspect 
import sympy
print(sympy.sin(math.pi/2))



#print(dir(sympy))
#print(inspect.getclasstree(sympy))
#print(inspect.getmembers(sympy.tan,isclass))


from sympy import sin, sine_transform, solve
print(sin(math.pi/2))


print("\n")
print ("inspect.ismodule(sympy.sin):", inspect.ismodule(sympy.sin))
print ("inspect.ismethod(sympy.sin):", inspect.ismethod(sympy.sin))
print ("inspect.isclass(sympy.sin):", inspect.isclass(sympy.sin))
print ("inspect.isfunction(sympy.sin)", inspect.isfunction(sympy.sin))
#print(dir(solve))

from sympy import Symbol
theta = Symbol('theta')
print( sympy.sin(theta) + sympy.sin(theta) ) 

from sympy import sin, solve, Symbol
u = Symbol('u')
t = Symbol('t')
g = Symbol('g')
theta1 = Symbol('theta1')
solve(u*sin(theta1)-g*t, t)



x = Symbol('x', positive=True)
if (x+5) > 0:
    print('Do Something where positive=True')
else:
    print('Do Something else where not(positive=True)')


from sympy import Limit, Symbol, S
x = Symbol('x')
y = Limit(1/x, x, S.Infinity)
print(type(y), y)

In [ ]:
import inspect 
import re




print(dir(re))
print("\n")
print ("inspect.ismodule(re.findall):", inspect.ismodule(re.findall))
print ("inspect.ismethod(re.findall):", inspect.ismethod(re.findall))
print ("inspect.isclass(re.findall):", inspect.isclass(re.findall))
print ("inspect.isfunction(re.findall)", inspect.isfunction(re.findall))


#print(inspect.getclasstree(re))
print(inspect.getmembers(re))




#print ("inspect.ismethod(findall):", inspect.ismethod(finall))
#print(dir(solve))

In [4]:
#from numpy import pi,linspace,sin
#from matplotlib.pyplot import plot
#x = linspace(0,3*pi,500)
#print(x)
#plot(x,sin(x**2))
#title('A simple chirp');
# OneNote Python 101 - Worked Exampes - bokeh multi line, multi axis 


import numpy as np 
from bokeh.plotting import  show, figure 
from bokeh.io import output_notebook

x = np.linspace(0, 2*np.pi, 100) 
#print(x)
y = np.sin(1/x) 

output_notebook() 

p = figure() 
 
p.line(x, y, legend="sin(1/x)") 



show(p)


BokehJS successfully loaded.