markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
All those types are symbolic, meaning they don't have values at all. Theano variables can be defined with simple relations, such as
a = T.scalar('a') c = a**2 print a.type print c.type
TheanoLearning/TheanoLearning/theano_demo.ipynb
shengshuyang/PCLCombinedObjectDetection
gpl-2.0
note that c is also a symbolic scalar here. We can also define a function:
f = theano.function([a],a**2) print f
TheanoLearning/TheanoLearning/theano_demo.ipynb
shengshuyang/PCLCombinedObjectDetection
gpl-2.0
Again, Theano functions are symbolic as well. We must evaluate the function with some input to check its output. For example:
print f(2)
TheanoLearning/TheanoLearning/theano_demo.ipynb
shengshuyang/PCLCombinedObjectDetection
gpl-2.0
Shared variable is also a Theano type
shared_var = theano.shared(np.array([[1, 2], [3, 4]], dtype=theano.config.floatX)) print 'variable type:' print shared_var.type print '\nvariable value:' print shared_var.get_value() shared_var.set_value(np.array([[4, 5], [6, 7]], dtype=theano.config.floatX)) print '\nvalues changed:' print shared_var.get_value()
TheanoLearning/TheanoLearning/theano_demo.ipynb
shengshuyang/PCLCombinedObjectDetection
gpl-2.0
They have a fixed value, but are still treated as symbolic (can be input to functions etc.). Shared variables are perfect to use as state variables or parameters. Fore example, in CNN each layer has a parameter matrix 'W', we need to store its value so we can perform testing against thousands of images, yet we also need to update their values during training. As a side note, since they have fixed value, they don't need to be explicitly specified as input to a function:
bias = T.matrix('bias') shared_squared = shared_var**2 + bias bias_value = np.array([[1,1],[1,1]], dtype=theano.config.floatX) f1 = theano.function([bias],shared_squared) print f1(bias_value) print '\n' print shared_squared.eval({bias:bias_value})
TheanoLearning/TheanoLearning/theano_demo.ipynb
shengshuyang/PCLCombinedObjectDetection
gpl-2.0
The example above defines a function that takes square of a shared_var and add by a bias. When evaluating the function we only provide value for bias because we know that the shared variable is fixed value. Gradients To calculate gradient we can use a T.grad() function to return a tensor variable. We first define some variable:
def square(a): return a**2 a = T.scalar('a') b = square(a) c = square(b)
TheanoLearning/TheanoLearning/theano_demo.ipynb
shengshuyang/PCLCombinedObjectDetection
gpl-2.0
Then we define two ways to evaluate gradient:
grad = T.grad(c,a) f_grad = theano.function([a],grad)
TheanoLearning/TheanoLearning/theano_demo.ipynb
shengshuyang/PCLCombinedObjectDetection
gpl-2.0
The TensorVariable grad calculates gradient of b w.r.t. a. The function f_grad takes a as input and grad as output, so it should be equivalent. However, evaluating them have different formats:
print grad.eval({a:10}) print f_grad(10)
TheanoLearning/TheanoLearning/theano_demo.ipynb
shengshuyang/PCLCombinedObjectDetection
gpl-2.0
MLP Demo with Theano
class layer(object): def __init__(self, W_init, b_init, activation): [n_output, n_input] = W_init.shape assert b_init.shape == (n_output,1) or b_init.shape == (n_output,) self.W = theano.shared(value = W_init.astype(theano.config.floatX), name = 'W', borrow = True) self.b = theano.shared(value = b_init.reshape(n_output,1).astype(theano.config.floatX), name = 'b', borrow = True, broadcastable=(False, True)) self.activation = activation self.params = [self.W, self.b] #return super(layer, self).__init__(*args, **kwargs) def output(self, x): lin_output = T.dot(self.W, x) + self.b if self.activation is not None: non_lin_output = self.activation(lin_output) return ( lin_output if self.activation is None else non_lin_output ) t1 = time.time() W_init = np.ones([3,3]) b_init = np.array([1,3,2.5]).transpose() activation = None #T.nnet.sigmoid L = layer(W_init,b_init,activation) x = T.vector('x') out = L.output(x) print out.eval({x:np.array([1.0,2,3.5]).astype(theano.config.floatX)}) t2 = time.time() print 'time:', t2-t1
TheanoLearning/TheanoLearning/theano_demo.ipynb
shengshuyang/PCLCombinedObjectDetection
gpl-2.0
Plotting Flowchart (or Theano Graph) The code snippet below can plot a flowchart that shows what happens inside our mlp layer. Note that the input out is the output of layer, as defined above.
from IPython.display import SVG SVG(theano.printing.pydotprint(out, return_image=True, compact = True, var_with_name_simple = True, format='svg'))
TheanoLearning/TheanoLearning/theano_demo.ipynb
shengshuyang/PCLCombinedObjectDetection
gpl-2.0
Authenticate to Earth Engine In order to access Earth Engine, signup at signup.earthengine.google.com. Once you have signed up and the Earth Engine package is installed, use the earthengine authenticate shell command to create and store authentication credentials on the Colab VM. These credentials are used by the Earth Engine Python API and command line tools to access Earth Engine servers. You will need to follow the link to the permissions page and give this notebook access to your Earth Engine account. Once you have authorized access, paste the authorization code into the input box displayed in the cell output.
import ee # Check if the server is authenticated. If not, display instructions that # explain how to complete the process. try: ee.Initialize() except ee.EEException: !earthengine authenticate
python/examples/ipynb/EarthEngineColabInstall.ipynb
tylere/earthengine-api
apache-2.0
Test the installation Import the Earth Engine library and initialize it with the authorization token stored on the notebook VM. Also import a display widget and display a thumbnail image of an Earth Engine dataset.
import ee from IPython.display import Image # Initialize the Earth Engine module. ee.Initialize() # Display a thumbnail of a sample image asset. Image(url=ee.Image('CGIAR/SRTM90_V4').getThumbUrl({'min': 0, 'max': 3000}))
python/examples/ipynb/EarthEngineColabInstall.ipynb
tylere/earthengine-api
apache-2.0
Or, run code in parallel mode (command may need to be customized, depending your on MPI installation.)
!mpirun -n 4 swirl
applications/clawpack/advection/2d/disk/swirl.ipynb
ForestClaw/forestclaw
bsd-2-clause
Create PNG files for web-browser viewing, or animation.
%run make_plots.py
applications/clawpack/advection/2d/disk/swirl.ipynb
ForestClaw/forestclaw
bsd-2-clause
View PNG files in browser, using URL above, or create an animation of all PNG files, using code below.
%pylab inline import glob from matplotlib import image from clawpack.visclaw.JSAnimation import IPython_display from matplotlib import animation figno = 0 fname = '_plots/*fig' + str(figno) + '.png' filenames=sorted(glob.glob(fname)) fig = plt.figure() im = plt.imshow(image.imread(filenames[0])) def init(): im.set_data(image.imread(filenames[0])) return im, def animate(i): image_i=image.imread(filenames[i]) im.set_data(image_i) return im, animation.FuncAnimation(fig, animate, init_func=init, frames=len(filenames), interval=500, blit=True)
applications/clawpack/advection/2d/disk/swirl.ipynb
ForestClaw/forestclaw
bsd-2-clause
Imprima todos los numeros primos positivos menores que n, solicite el n.
n = int(input("Ingrese el n: ")) #ojo... podriamos saltar de a 2, desde el 3. for i in range(2,n): cantdiv = 0 for j in range(2,int(i**0.5)+1): if i%j == 0: cantdiv += 1 if cantdiv == 0: print(i, "es primo")
labs/ejercicios_for.ipynb
leoferres/prograUDD
mit
Solicite n y k y calcule $\binom{n}{k}$
n = int(input("Ingrese el n: ")) k = int(input("Ingrese el k: ")) if n < 0 or k < 0: print("No se puede calcular, hay un elemento negativo") elif n < k: print("No se puede calcular, n debe ser mayor o igual a k") else: menor = k if (n-k) < menor: menor = (n-k) resultado = 1 for i in range(menor): resultado *= (n-i)/(i+1) print("El resultado es =", resultado)
labs/ejercicios_for.ipynb
leoferres/prograUDD
mit
Se define como numero perfecto, aquél natural positivo en que la suma de sus divisores, no incluido si mismo, es el mismo número.
# obviaremos chequeo que sea positivo n = int(input("Ingrese su n: ")) for i in range(1, n+1): suma = 0 for j in range(1,i): if i%j == 0: suma += j if suma == i: print(i, "es perfecto") for i in range(1, 496): if 496%i == 0: print(i)
labs/ejercicios_for.ipynb
leoferres/prograUDD
mit
Si queremos añadir ramas adicionales al condicional, podemos emplear la instrucción elif (abreviatura de else if). Para la parte final, que debe ejecutarse si ninguna de las condiciones anteriores se ha cumplido, usamos la instrucción else.
x, y = 2, 0 if x > y: print("x es mayor que y") else: print("x es menor que y") # Uso de ELIF (contracción de else if) x, y = 2 , 0 if x < y: print("x es menor que y") elif x == y: print("x es igual a y") else: print("x es mayor que y")
python/howto/005_Estructuras de control.ipynb
xMyrst/BigData
gpl-3.0
<br /> EXPRESIONES TERNARIAS Las expresiones ternarias en Python tienen la siguiente forma: e = valorSiTrue if &lt;condicion&gt; else valorSiFalse Permite definir la instrucción if-else en una sola línea. La expresión anterior es equivalente a: if &lt;condicion&gt;: e = valorSiTrue else: e = valorSiFalse
# Una expresión ternaria es una contracción de un bucle FOR # Se define la variable para poder comparar x = 8 # Se puede escrbir la expresión de esta manera o almacenando el resultado dentro de una variable # para trabajar posteriormente con ella "Hola CICE" if x == 8 else "Adios CICE" a = 'x es igual a 8' if x == 8 else 'x es distinto de 8' a
python/howto/005_Estructuras de control.ipynb
xMyrst/BigData
gpl-3.0
<br /> BUCLES FOR Y WHILE El bucle FOR Permite realizar una tarea un número fijo de veces. Se utiliza para recorrer una colección completa de elementos (una tupla, una lista, un diccionario, etc ): for &lt;element&gt; in &lt;iterable_object&gt;: &lt;hacer algo...&gt; Aquí el objeto &lt;iterable_object&gt; puede ser una lista, tupla, array, diccionario, etc. El bucle se repite un número fijo de veces, que es la longitud de la colección de elementos.
# itera soble los elementos de la tupla for elemento in (1, 2, 3, 4, 5): print(elemento) # Suma todos los elementos de la tupla suma = 0 for elemento in (1, 2, 3, 4, 5): suma = suma + elemento print(suma) # Muestra todos los elemntos de una lista dias = ["Lunes", "Martes", "Miércoles", "Jueves", 'Viernes', 'Sábado', 'Domingo'] for nombre in dias: print(nombre) # La instrucción CONTINUE permite saltar de una iteración a otra # Crea la lista de enteros en el intervalo [0,10) # No se ejecuta si j es un número par, gracias a la sentencia continue for j in range(10): if j % 2 == 0: continue print(j) # También es posible recorrer un diccionario mediante el bucle FOR # dic.items # dic.keys # dic.values dic = {1:'Lunes', 2:'Martes', 3:'Miércoles' } # Python 3.5 for i in dic.items(): print(i) dic = {1:'Lunes', 2:'Martes', 3:'Miércoles' } # Python 3.5 for (clave, valor) in dic.items(): print("La clave es: " + str(clave) + " y el valor es: " + valor) dic.items(), dic.keys(), dic.values()
python/howto/005_Estructuras de control.ipynb
xMyrst/BigData
gpl-3.0
<br /> El bucle WHILE Los bucles while repetirán las instrucciones anidadas en él mientras se cumpla una condición: while &lt;condition&gt;: &lt;things to do&gt; El número de iteraciones es variable, depende de la condición. +Como en el caso de los condicionales, los bloques se separan por sangrado sin necesidad de instrucciones del tipo end.
i = -2 while i < 5: print(i) i = i + 1 print("Estoy fuera del while") # Para interrumpir un bucle WHILE se utiliza la instrucción BREAK # Se pueden usar expresiones de tipo condicional (AND, OR, NOT) i = 0 j = 1 while i < 5 and j == 1: print(i) i = i + 1 if i == 3: break
python/howto/005_Estructuras de control.ipynb
xMyrst/BigData
gpl-3.0
<BR /> LA FUNCIÓN ENUMERATE Cuando trabajamos con secuencias de elementos puede resultar útil conocer el índice de cada elemento. La función enumerate devuelve una secuencia de tuplas de la forma (i, valor). Mediante un bucle es posible recorrerse dicha secuencia:
# Creamos una lista llamada ciudades # Recorremos dicha lista mediante la instrucción FOR asignando una secuencia de números (i) a cada valor de la lista ciudades = ["Madrid", "Sevilla", "Segovia", "Valencia" ] for (i, valor) in enumerate(ciudades): print('%d: %s' % (i, valor)) # Uso de la función reversed # la función reversed devuelve un iterador inverso de una lista for (i, valor) in enumerate(reversed(ciudades)): print('%d: %s' % (i, valor))
python/howto/005_Estructuras de control.ipynb
xMyrst/BigData
gpl-3.0
1) Boxplot of General Density
# syn_unmasked_T = syn_unmasked.values.T.tolist() # columns = [syn_unmasked[i] for i in [4]] plt.boxplot(syn_unmasked[:,3], 0, 'gD') plt.xticks([1], ['Set']) plt.ylabel('Density Distribution') plt.title('Density Distrubution Boxplot') plt.show()
code/Assignment11_Group.ipynb
Upward-Spiral-Science/team1
apache-2.0
2) Is the spike noise? More evidence. We saw from Emily's analysis that there is strong evidence against the spike being noise. If we see that the spike is noticeable in the histogram of synapses as well as the histogram of synapse density, we will gain even more evidence that the spike is noise.
figure = plt.figure() plt.hist(data_thresholded[:,4],5000) plt.title('Histogram of Synapses in Brain Sample') plt.xlabel('Synapses') plt.ylabel('frequency')
code/Assignment11_Group.ipynb
Upward-Spiral-Science/team1
apache-2.0
Since we don't see the spike in the histogram of synapses, the spike may be some artifact of the unmasked value. Let's take a look! 3) What is the spike? We still don't know.
plt.hist(data_thresholded[:,3],5000) plt.title('Histogram of Unmasked Values') plt.xlabel('unmasked') plt.ylabel('frequency')
code/Assignment11_Group.ipynb
Upward-Spiral-Science/team1
apache-2.0
4) Synapses and unmasked: Spike vs Whole Data Set
# Spike a = np.apply_along_axis(lambda x:x[4]/x[3], 1, data_thresholded) spike = a[np.logical_and(a <= 0.0015, a >= 0.0012)] print "Average Density: ", np.mean(spike) print "Std Deviation: ", np.std(spike) # Histogram n, bins, _ = plt.hist(spike, 2000) plt.title('Histogram of Synaptic Density') plt.xlabel('Synaptic Density (syn/voxel)') plt.ylabel('frequency') bin_max = np.where(n == n.max()) print 'maxbin', bins[bin_max][0] bin_width = bins[1]-bins[0] syn_normalized[:,3] = syn_normalized[:,3]/(64**3) spike = syn_normalized[np.logical_and(syn_normalized[:,3] <= 0.00131489435301+bin_width, syn_normalized[:,3] >= 0.00131489435301-bin_width)] print "There are ", len(spike), " points in the 'spike'" spike_thres = data_thresholded[np.logical_and(syn_normalized[:,3] <= 0.00131489435301+bin_width, syn_normalized[:,3] >= 0.00131489435301-bin_width)] print spike_thres import math fig, ax = plt.subplots(1,2,sharey = True, figsize=(20,5)) weights = np.ones_like(spike_thres[:,3])/len(spike_thres[:,3]) weights2 = np.ones_like(data_thresholded[:,3])/len(data_thresholded[:,3]) ax[0].hist(data_thresholded[:,3], bins = 100, alpha = 0.5, weights = weights2, label = 'all data') ax[0].hist(spike_thres[:,3], bins = 100, alpha = 0.5, weights = weights, label = 'spike') ax[0].legend(loc='upper right') ax[0].set_title('Histogram of Unmasked values in the Spike vs All Data') weights = np.ones_like(spike_thres[:,4])/len(spike_thres[:,4]) weights2 = np.ones_like(data_thresholded[:,4])/len(data_thresholded[:,4]) ax[1].hist(data_thresholded[:,4], bins = 100, alpha = 0.5, weights = weights2, label = 'all data') ax[1].hist(spike_thres[:,4], bins = 100, alpha = 0.5, weights = weights, label = 'spike') ax[1].legend(loc='upper right') ax[1].set_title('Histogram of Synapses in the Spike vs All Data') plt.show()
code/Assignment11_Group.ipynb
Upward-Spiral-Science/team1
apache-2.0
5) Boxplot of different clusters by coordinates and densities Cluster 4 has relatively high density
import sklearn.mixture as mixture n_clusters = 4 gmm = mixture.GMM(n_components=n_clusters, n_iter=1000, covariance_type='diag') labels = gmm.fit_predict(syn_unmasked) clusters = [] for l in range(n_clusters): a = np.where(labels == l) clusters.append(syn_unmasked[a,:]) print len(clusters) print clusters[0].shape counter = 0 indx = 0 indy = 0 for cluster in clusters: s = cluster.shape cluster = cluster.reshape((s[1], s[2])) counter += 1 print print'Working on cluster: ' + str(counter) plt.boxplot(cluster[:,-1], 0, 'gD', showmeans=True) plt.xticks([1]) plt.ylabel('Density') plt.title('Boxplot of density \n at cluster = ' + str(int(counter))) plt.show() print "Done with cluster" plt.show()
code/Assignment11_Group.ipynb
Upward-Spiral-Science/team1
apache-2.0
5 OLD ) Boxplot distrubutions of each Z layer
data_uniques, UIndex, UCounts = np.unique(syn_unmasked[:,2], return_index = True, return_counts = True) ''' print 'uniques' print 'index: ' + str(UIndex) print 'counts: ' + str(UCounts) print 'values: ' + str(data_uniques) ''' fig, ax = plt.subplots(3,4,figsize=(10,20)) counter = 0 for i in np.unique(syn_unmasked[:,2]): # print 'calcuating for z: ' + str(int(i)) def check_z(row): if row[2] == i: return True return False counter += 1 xind = (counter%3) - 1 yind = (counter%4) - 1 index_true = np.where(np.apply_along_axis(check_z, 1, syn_unmasked)) syn_uniqueZ = syn_unmasked[index_true] ax[xind,yind].boxplot(syn_uniqueZ[:,3], 0, 'gD') ax[xind,yind].set_xticks([1], i) ax[xind,yind].set_ylabel('Density') ax[xind,yind].set_title('Boxplot at \n z = ' + str(int(i))) #print 'yind = %d, xind = %d' %(yind,xind) #print i ax[xind+1,yind+1].boxplot(syn_uniqueZ[:,3], 0, 'gD',showmeans=True) ax[xind+1,yind+1].set_xticks([1], 'set') ax[xind+1,yind+1].set_ylabel('Density') ax[xind+1,yind+1].set_title('Boxplot for \n All Densities') print "Density Distrubtion Boxplots:" plt.tight_layout() plt.show()
code/Assignment11_Group.ipynb
Upward-Spiral-Science/team1
apache-2.0
One of the first things you do with a class is to define the _init_() method. The __init__() method sets the values for any parameters that need to be defined when an object is first created. The self part will be explained later; basically, it's a syntax that allows you to access a variable from anywhere else in the class. The Rocket class stores two pieces of information so far, but it can't do anything. The first behavior to define is a core behavior of a rocket: moving up. Here is what that might look like in code:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0 def move_up(self): # Increment the y-position of the rocket. self.y += 1
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
The Rocket class can now store some information, and it can do something. But this code has not actually created a rocket yet. Here is how you actually make a rocket:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0 def move_up(self): # Increment the y-position of the rocket. self.y += 1 # Create a Rocket object. my_rocket = Rocket() print(my_rocket)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
To actually use a class, you create a variable such as my_rocket. Then you set that equal to the name of the class, with an empty set of parentheses. Python creates an object from the class. An object is a single instance of the Rocket class; it has a copy of each of the class's variables, and it can do any action that is defined for the class. In this case, you can see that the variable my_rocket is a Rocket object from the __main__ program file, which is stored at a particular location in memory. Once you have a class, you can define an object and use its methods. Here is how you might define a rocket and have it start to move up:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0 def move_up(self): # Increment the y-position of the rocket. self.y += 1 # Create a Rocket object, and have it start to move up. my_rocket = Rocket() print("Rocket altitude:", my_rocket.y) my_rocket.move_up() print("Rocket altitude:", my_rocket.y) my_rocket.move_up() print("Rocket altitude:", my_rocket.y)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
To access an object's variables or methods, you give the name of the object and then use dot notation to access the variables and methods. So to get the y-value of my_rocket, you use my_rocket.y. To use the move_up() method on my_rocket, you write my_rocket.move_up(). Once you have a class defined, you can create as many objects from that class as you want. Each object is its own instance of that class, with its own separate variables. All of the objects are capable of the same behavior, but each object's particular actions do not affect any of the other objects. Once you have a class, you can define an object and use its methods. Here is how you might define a rocket and have it start to move up:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0 def move_up(self): # Increment the y-position of the rocket. self.y += 1 # Create a fleet of 5 rockets, and store them in a list. my_rockets = [] for x in range(0,5): new_rocket = Rocket() my_rockets.append(new_rocket) # Show that each rocket is a separate object. for rocket in my_rockets: print(rocket)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
You can see that each rocket is at a separate place in memory. By the way, if you understand list comprehensions, you can make the fleet of rockets in one line:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0 def move_up(self): # Increment the y-position of the rocket. self.y += 1 # Create a fleet of 5 rockets, and store them in a list. my_rockets = [Rocket() for x in range(0,5)] # Show that each rocket is a separate object. for rocket in my_rockets: print(rocket)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
You can prove that each rocket has its own x and y values by moving just one of the rockets:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0 def move_up(self): # Increment the y-position of the rocket. self.y += 1 # Create a fleet of 5 rockets, and store them in a list. my_rockets = [Rocket() for x in range(0,5)] # Move the first rocket up. my_rockets[0].move_up() # Show that only the first rocket has moved. for rocket in my_rockets: print("Rocket altitude:", rocket.y)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
The syntax for classes may not be very clear at this point, but consider for a moment how you might create a rocket without using classes. You might store the x and y values in a dictionary, but you would have to write a lot of ugly, hard-to-maintain code to manage even a small set of rockets. As more features become incorporated into the Rocket class, you will see how much more efficiently real-world objects can be modeled with classes than they could be using just lists and dictionaries. top <a name='exercises_what'></a>Exercises Rocket With No Class Using just what you already know, try to write a program that simulates the above example about rockets. Store an x and y value for a rocket. Store an x and y value for each rocket in a set of 5 rockets. Store these 5 rockets in a list. Don't take this exercise too far; it's really just a quick exercise to help you understand how useful the class structure is, especially as you start to see more capability added to the Rocket class.
# Ex 9.0 : Rocket with no Class # put your code here
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
top <a name='oop_terminology'></a>Object-Oriented terminology Classes are part of a programming paradigm called object-oriented programming. Object-oriented programming, or OOP for short, focuses on building reusable blocks of code called classes. When you want to use a class in one of your programs, you make an object from that class, which is where the phrase "object-oriented" comes from. Python itself is not tied to object-oriented programming, but you will be using objects in most or all of your Python projects. In order to understand classes, you have to understand some of the language that is used in OOP. <a name='general_terminology'></a>General terminology A class is a body of code that defines the attributes and behaviors required to accurately model something you need for your program. You can model something from the real world, such as a rocket ship or a guitar string, or you can model something from a virtual world such as a rocket in a game, or a set of physical laws for a game engine. An attribute is a piece of information. In code, an attribute is just a variable that is part of a class. A behavior is an action that is defined within a class. These are made up of methods, which are just functions that are defined for the class. An object is a particular instance of a class. An object has a certain set of values for all of the attributes (variables) in the class. You can have as many objects as you want for any one class. There is much more to know, but these words will help you get started. They will make more sense as you see more examples, and start to use classes on your own. top <a name='closer_look'></a>A closer look at the Rocket class Now that you have seen a simple example of a class, and have learned some basic OOP terminology, it will be helpful to take a closer look at the Rocket class. <a name="init_method"></a>The __init()__ method Here is the initial code block that defined the Rocket class:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
The first line shows how a class is created in Python. The keyword class tells Python that you are about to define a class. The rules for naming a class are the same rules you learned about naming variables, but there is a strong convention among Python programmers that classes should be named using CamelCase. If you are unfamiliar with CamelCase, it is a convention where each letter that starts a word is capitalized, with no underscores in the name. The name of the class is followed by a set of parentheses. These parentheses will be empty for now, but later they may contain a class upon which the new class is based. It is good practice to write a comment at the beginning of your class, describing the class. There is a more formal syntax for documenting your classes, but you can wait a little bit to get that formal. For now, just write a comment at the beginning of your class summarizing what you intend the class to do. Writing more formal documentation for your classes will be easy later if you start by writing simple comments now. Function names that start and end with two underscores are special built-in functions that Python uses in certain ways. The __init()__ method is one of these special functions. It is called automatically when you create an object from your class. The __init()__ method lets you make sure that all relevant attributes are set to their proper values when an object is created from the class, before the object is used. In this case, The __init__() method initializes the x and y values of the Rocket to 0. The self keyword often takes people a little while to understand. The word "self" refers to the current object that you are working with. When you are writing a class, it lets you refer to certain attributes from any other part of the class. Basically, all methods in a class need the self object as their first argument, so they can access any attribute that is part of the class. Now let's take a closer look at a method. <a name='simple_method'></a>A simple method Here is the method that was defined for the Rocket class:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0 def move_up(self): # Increment the y-position of the rocket. self.y += 1
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
A method is just a function that is part of a class. Since it is just a function, you can do anything with a method that you learned about with functions. You can accept positional arguments, keyword arguments, an arbitrary list of argument values, an arbitrary dictionary of arguments, or any combination of these. Your arguments can return a value or a set of values if you want, or they can just do some work without returning any values. Each method has to accept one argument by default, the value self. This is a reference to the particular object that is calling the method. This self argument gives you access to the calling object's attributes. In this example, the self argument is used to access a Rocket object's y-value. That value is increased by 1, every time the method move_up() is called by a particular Rocket object. This is probably still somewhat confusing, but it should start to make sense as you work through your own examples. If you take a second look at what happens when a method is called, things might make a little more sense:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0 def move_up(self): # Increment the y-position of the rocket. self.y += 1 # Create a Rocket object, and have it start to move up. my_rocket = Rocket() print("Rocket altitude:", my_rocket.y) my_rocket.move_up() print("Rocket altitude:", my_rocket.y) my_rocket.move_up() print("Rocket altitude:", my_rocket.y)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
In this example, a Rocket object is created and stored in the variable my_rocket. After this object is created, its y value is printed. The value of the attribute y is accessed using dot notation. The phrase my_rocket.y asks Python to return "the value of the variable y attached to the object my_rocket". After the object my_rocket is created and its initial y-value is printed, the method move_up() is called. This tells Python to apply the method move_up() to the object my_rocket. Python finds the y-value associated with my_rocket and adds 1 to that value. This process is repeated several times, and you can see from the output that the y-value is in fact increasing. top <a name='multiple_objects'></a>Making multiple objects from a class One of the goals of object-oriented programming is to create reusable code. Once you have written the code for a class, you can create as many objects from that class as you need. It is worth mentioning at this point that classes are usually saved in a separate file, and then imported into the program you are working on. So you can build a library of classes, and use those classes over and over again in different programs. Once you know a class works well, you can leave it alone and know that the objects you create in a new program are going to work as they always have. You can see this "code reusability" already when the Rocket class is used to make more than one Rocket object. Here is the code that made a fleet of Rocket objects:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0 def move_up(self): # Increment the y-position of the rocket. self.y += 1 # Create a fleet of 5 rockets, and store them in a list. my_rockets = [] for x in range(0,5): new_rocket = Rocket() my_rockets.append(new_rocket) # Show that each rocket is a separate object. for rocket in my_rockets: print(rocket)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
If you are comfortable using list comprehensions, go ahead and use those as much as you can. I'd rather not assume at this point that everyone is comfortable with comprehensions, so I will use the slightly longer approach of declaring an empty list, and then using a for loop to fill that list. That can be done slightly more efficiently than the previous example, by eliminating the temporary variable new_rocket:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0 def move_up(self): # Increment the y-position of the rocket. self.y += 1 # Create a fleet of 5 rockets, and store them in a list. my_rockets = [] for x in range(0,5): my_rockets.append(Rocket()) # Show that each rocket is a separate object. for rocket in my_rockets: print(rocket)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
What exactly happens in this for loop? The line my_rockets.append(Rocket()) is executed 5 times. Each time, a new Rocket object is created and then added to the list my_rockets. The __init__() method is executed once for each of these objects, so each object gets its own x and y value. When a method is called on one of these objects, the self variable allows access to just that object's attributes, and ensures that modifying one object does not affect any of the other objecs that have been created from the class. Each of these objects can be worked with individually. At this point we are ready to move on and see how to add more functionality to the Rocket class. We will work slowly, and give you the chance to start writing your own simple classes. <a name='check_in'></a>A quick check-in If all of this makes sense, then the rest of your work with classes will involve learning a lot of details about how classes can be used in more flexible and powerful ways. If this does not make any sense, you could try a few different things: Reread the previous sections, and see if things start to make any more sense. Type out these examples in your own editor, and run them. Try making some changes, and see what happens. Try the next exercise, and see if it helps solidify some of the concepts you have been reading about. Read on. The next sections are going to add more functionality to the Rocket class. These steps will involve rehashing some of what has already been covered, in a slightly different way. Classes are a huge topic, and once you understand them you will probably use them for the rest of your life as a programmer. If you are brand new to this, be patient and trust that things will start to sink in. top <a name='exercises_closer_look'></a>Exercises Your Own Rocket Without looking back at the previous examples, try to recreate the Rocket class as it has been shown so far. Define the Rocket() class. Define the __init__() method, which sets an x and a y value for each Rocket object. Define the move_up() method. Create a Rocket object. Print the object. Print the object's y-value. Move the rocket up, and print its y-value again. Create a fleet of rockets, and prove that they are indeed separate Rocket objects.
# Ex 9.1 : Your Own Rocket # put your code here
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
top <a name='refining_rocket'></a>Refining the Rocket class The Rocket class so far is very simple. It can be made a little more interesting with some refinements to the __init__() method, and by the addition of some methods. <a name='init_parameters'></a>Accepting paremeters for the __init__() method The __init__() method is run automatically one time when you create a new object from a class. The __init__() method for the Rocket class so far is pretty simple:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self): # Each rocket has an (x,y) position. self.x = 0 self.y = 0 def move_up(self): # Increment the y-position of the rocket. self.y += 1
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
All the __init__() method does so far is set the x and y values for the rocket to 0. We can easily add a couple keyword arguments so that new rockets can be initialized at any position:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self, x=0, y=0): # Each rocket has an (x,y) position. self.x = x self.y = y def move_up(self): # Increment the y-position of the rocket. self.y += 1
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
Now when you create a new Rocket object you have the choice of passing in arbitrary initial values for x and y:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self, x=0, y=0): # Each rocket has an (x,y) position. self.x = x self.y = y def move_up(self): # Increment the y-position of the rocket. self.y += 1 # Make a series of rockets at different starting places. rockets = [] rockets.append(Rocket()) rockets.append(Rocket(0,10)) rockets.append(Rocket(100,0)) # Show where each rocket is. for index, rocket in enumerate(rockets): print("Rocket %d is at (%d, %d)." % (index, rocket.x, rocket.y))
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
top <a name='method_parameters'></a>Accepting paremeters in a method The __init__ method is just a special method that serves a particular purpose, which is to help create new objects from a class. Any method in a class can accept parameters of any kind. With this in mind, the move_up() method can be made much more flexible. By accepting keyword arguments, the move_up() method can be rewritten as a more general move_rocket() method. This new method will allow the rocket to be moved any amount, in any direction:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self, x=0, y=0): # Each rocket has an (x,y) position. self.x = x self.y = y def move_rocket(self, x_increment=0, y_increment=1): # Move the rocket according to the paremeters given. # Default behavior is to move the rocket up one unit. self.x += x_increment self.y += y_increment
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
The paremeters for the move() method are named x_increment and y_increment rather than x and y. It's good to emphasize that these are changes in the x and y position, not new values for the actual position of the rocket. By carefully choosing the right default values, we can define a meaningful default behavior. If someone calls the method move_rocket() with no parameters, the rocket will simply move up one unit in the y-direciton. Note that this method can be given negative values to move the rocket left or right:
class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self, x=0, y=0): # Each rocket has an (x,y) position. self.x = x self.y = y def move_rocket(self, x_increment=0, y_increment=1): # Move the rocket according to the paremeters given. # Default behavior is to move the rocket up one unit. self.x += x_increment self.y += y_increment # Create three rockets. rockets = [Rocket() for x in range(0,3)] # Move each rocket a different amount. rockets[0].move_rocket() rockets[1].move_rocket(10,10) rockets[2].move_rocket(-10,0) # Show where each rocket is. for index, rocket in enumerate(rockets): print("Rocket %d is at (%d, %d)." % (index, rocket.x, rocket.y))
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
top <a name='adding_method'></a>Adding a new method One of the strengths of object-oriented programming is the ability to closely model real-world phenomena by adding appropriate attributes and behaviors to classes. One of the jobs of a team piloting a rocket is to make sure the rocket does not get too close to any other rockets. Let's add a method that will report the distance from one rocket to any other rocket. If you are not familiar with distance calculations, there is a fairly simple formula to tell the distance between two points if you know the x and y values of each point. This new method performs that calculation, and then returns the resulting distance.
from math import sqrt class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self, x=0, y=0): # Each rocket has an (x,y) position. self.x = x self.y = y def move_rocket(self, x_increment=0, y_increment=1): # Move the rocket according to the paremeters given. # Default behavior is to move the rocket up one unit. self.x += x_increment self.y += y_increment def get_distance(self, other_rocket): # Calculates the distance from this rocket to another rocket, # and returns that value. distance = sqrt((self.x-other_rocket.x)**2+(self.y-other_rocket.y)**2) return distance # Make two rockets, at different places. rocket_0 = Rocket() rocket_1 = Rocket(10,5) # Show the distance between them. distance = rocket_0.get_distance(rocket_1) print("The rockets are %f units apart." % distance)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
Hopefully these short refinements show that you can extend a class' attributes and behavior to model the phenomena you are interested in as closely as you want. The rocket could have a name, a crew capacity, a payload, a certain amount of fuel, and any number of other attributes. You could define any behavior you want for the rocket, including interactions with other rockets and launch facilities, gravitational fields, and whatever you need it to! There are techniques for managing these more complex interactions, but what you have just seen is the core of object-oriented programming. At this point you should try your hand at writing some classes of your own. After trying some exercises, we will look at object inheritance, and then you will be ready to move on for now. top <a name='exercises_refining_rocket'></a>Exercises Your Own Rocket 2 There are enough new concepts here that you might want to try re-creating the Rocket class as it has been developed so far, looking at the examples as little as possible. Once you have your own version, regardless of how much you needed to look at the example, you can modify the class and explore the possibilities of what you have already learned. Re-create the Rocket class as it has been developed so far: Define the Rocket() class. Define the __init__() method. Let your __init__() method accept x and y values for the initial position of the rocket. Make sure the default behavior is to position the rocket at (0,0). Define the move_rocket() method. The method should accept an amount to move left or right, and an amount to move up or down. Create a Rocket object. Move the rocket around, printing its position after each move. Create a small fleet of rockets. Move several of them around, and print their final positions to prove that each rocket can move independently of the other rockets. Define the get_distance() method. The method should accept a Rocket object, and calculate the distance between the current rocket and the rocket that is passed into the method. Use the get_distance() method to print the distances between several of the rockets in your fleet. Rocket Attributes Start with a copy of the Rocket class, either one you made from a previous exercise or the latest version from the last section. Add several of your own attributes to the __init__() function. The values of your attributes can be set automatically by the __init__ function, or they can be set by paremeters passed into __init__(). Create a rocket and print the values for the attributes you have created, to show they have been set correctly. Create a small fleet of rockets, and set different values for one of the attributes you have created. Print the values of these attributes for each rocket in your fleet, to show that they have been set properly for each rocket. If you are not sure what kind of attributes to add, you could consider storing the height of the rocket, the crew size, the name of the rocket, the speed of the rocket, or many other possible characteristics of a rocket. Rocket Methods Start with a copy of the Rocket class, either one you made from a previous exercise or the latest version from the last section. Add a new method to the class. This is probably a little more challenging than adding attributes, but give it a try. Think of what rockets do, and make a very simple version of that behavior using print statements. For example, rockets lift off when they are launched. You could make a method called launch(), and all it would do is print a statement such as "The rocket has lifted off!" If your rocket has a name, this sentence could be more descriptive. You could make a very simple land_rocket() method that simply sets the x and y values of the rocket back to 0. Print the position before and after calling the land_rocket() method to make sure your method is doing what it's supposed to. If you enjoy working with math, you could implement a safety_check() method. This method would take in another rocket object, and call the get_distance() method on that rocket. Then it would check if that rocket is too close, and print a warning message if the rocket is too close. If there is zero distance between the two rockets, your method could print a message such as, "The rockets have crashed!" (Be careful; getting a zero distance could mean that you accidentally found the distance between a rocket and itself, rather than a second rocket.) <a name='exercise_person_class'></a>Person Class Modeling a person is a classic exercise for people who are trying to learn how to write classes. We are all familiar with characteristics and behaviors of people, so it is a good exercise to try. Define a Person() class. In the __init()__ function, define several attributes of a person. Good attributes to consider are name, age, place of birth, and anything else you like to know about the people in your life. Write one method. This could be as simple as introduce_yourself(). This method would print out a statement such as, "Hello, my name is Eric." You could also make a method such as age_person(). A simple version of this method would just add 1 to the person's age. A more complicated version of this method would involve storing the person's birthdate rather than their age, and then calculating the age whenever the age is requested. But dealing with dates and times is not particularly easy if you've never done it in any other programming language before. Create a person, set the attribute values appropriately, and print out information about the person. Call your method on the person you created. Make sure your method executed properly; if the method does not print anything out directly, print something before and after calling the method to make sure it did what it was supposed to. <a name='exercise_car_class'></a>Car Class Modeling a car is another classic exercise. Define a Car() class. In the __init__() function, define several attributes of a car. Some good attributes to consider are make (Subaru, Audi, Volvo...), model (Outback, allroad, C30), year, num_doors, owner, or any other aspect of a car you care to include in your class. Write one method. This could be something such as describe_car(). This method could print a series of statements that describe the car, using the information that is stored in the attributes. You could also write a method that adjusts the mileage of the car or tracks its position. Create a car object, and use your method. Create several car objects with different values for the attributes. Use your method on several of your cars.
# Ex 9.2 : Your Own Rocket 2 # put your code here # Ex 9.3 : Rocket Attributes # put your code here # Ex 9.4 : Rocket Methods # put your code here # Ex 9.5 : Person Class # put your code here # Ex 9.6 : Car Class # put your code here
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
top <a name='inheritance'></a>Inheritance One of the most important goals of the object-oriented approach to programming is the creation of stable, reliable, reusable code. If you had to create a new class for every kind of object you wanted to model, you would hardly have any reusable code. In Python and any other language that supports OOP, one class can inherit from another class. This means you can base a new class on an existing class; the new class inherits all of the attributes and behavior of the class it is based on. A new class can override any undesirable attributes or behavior of the class it inherits from, and it can add any new attributes or behavior that are appropriate. The original class is called the parent class, and the new class is a child of the parent class. The parent class is also called a superclass, and the child class is also called a subclass. The child class inherits all attributes and behavior from the parent class, but any attributes that are defined in the child class are not available to the parent class. This may be obvious to many people, but it is worth stating. This also means a child class can override behavior of the parent class. If a child class defines a method that also appears in the parent class, objects of the child class will use the new method rather than the parent class method. To better understand inheritance, let's look at an example of a class that can be based on the Rocket class. <a name='shuttle'></a>The SpaceShuttle class If you wanted to model a space shuttle, you could write an entirely new class. But a space shuttle is just a special kind of rocket. Instead of writing an entirely new class, you can inherit all of the attributes and behavior of a Rocket, and then add a few appropriate attributes and behavior for a Shuttle. One of the most significant characteristics of a space shuttle is that it can be reused. So the only difference we will add at this point is to record the number of flights the shutttle has completed. Everything else you need to know about a shuttle has already been coded into the Rocket class. Here is what the Shuttle class looks like:
from math import sqrt class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self, x=0, y=0): # Each rocket has an (x,y) position. self.x = x self.y = y def move_rocket(self, x_increment=0, y_increment=1): # Move the rocket according to the paremeters given. # Default behavior is to move the rocket up one unit. self.x += x_increment self.y += y_increment def get_distance(self, other_rocket): # Calculates the distance from this rocket to another rocket, # and returns that value. distance = sqrt((self.x-other_rocket.x)**2+(self.y-other_rocket.y)**2) return distance class Shuttle(Rocket): # Shuttle simulates a space shuttle, which is really # just a reusable rocket. def __init__(self, x=0, y=0, flights_completed=0): super().__init__(x, y) self.flights_completed = flights_completed shuttle = Shuttle(10,0,3) print(shuttle)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
When a new class is based on an existing class, you write the name of the parent class in parentheses when you define the new class:
class NewClass(ParentClass):
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
The __init__() function of the new class needs to call the __init__() function of the parent class. The __init__() function of the new class needs to accept all of the parameters required to build an object from the parent class, and these parameters need to be passed to the __init__() function of the parent class. The super().__init__() function takes care of this:
class NewClass(ParentClass): def __init__(self, arguments_new_class, arguments_parent_class): super().__init__(arguments_parent_class) # Code for initializing an object of the new class.
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
The super() function passes the self argument to the parent class automatically. You could also do this by explicitly naming the parent class when you call the __init__() function, but you then have to include the self argument manually:
class Shuttle(Rocket): # Shuttle simulates a space shuttle, which is really # just a reusable rocket. def __init__(self, x=0, y=0, flights_completed=0): Rocket.__init__(self, x, y) self.flights_completed = flights_completed
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
This might seem a little easier to read, but it is preferable to use the super() syntax. When you use super(), you don't need to explicitly name the parent class, so your code is more resilient to later changes. As you learn more about classes, you will be able to write child classes that inherit from multiple parent classes, and the super() function will call the parent classes' __init__() functions for you, in one line. This explicit approach to calling the parent class' __init__() function is included so that you will be less confused if you see it in someone else's code. The output above shows that a new Shuttle object was created. This new Shuttle object can store the number of flights completed, but it also has all of the functionality of the Rocket class: it has a position that can be changed, and it can calculate the distance between itself and other rockets or shuttles. This can be demonstrated by creating several rockets and shuttles, and then finding the distance between one shuttle and all the other shuttles and rockets. This example uses a simple function called randint, which generates a random integer between a lower and upper bound, to determine the position of each rocket and shuttle:
from math import sqrt from random import randint class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self, x=0, y=0): # Each rocket has an (x,y) position. self.x = x self.y = y def move_rocket(self, x_increment=0, y_increment=1): # Move the rocket according to the paremeters given. # Default behavior is to move the rocket up one unit. self.x += x_increment self.y += y_increment def get_distance(self, other_rocket): # Calculates the distance from this rocket to another rocket, # and returns that value. distance = sqrt((self.x-other_rocket.x)**2+(self.y-other_rocket.y)**2) return distance class Shuttle(Rocket): # Shuttle simulates a space shuttle, which is really # just a reusable rocket. def __init__(self, x=0, y=0, flights_completed=0): super().__init__(x, y) self.flights_completed = flights_completed # Create several shuttles and rockets, with random positions. # Shuttles have a random number of flights completed. shuttles = [] for x in range(0,3): x = randint(0,100) y = randint(1,100) flights_completed = randint(0,10) shuttles.append(Shuttle(x, y, flights_completed)) rockets = [] for x in range(0,3): x = randint(0,100) y = randint(1,100) rockets.append(Rocket(x, y)) # Show the number of flights completed for each shuttle. for index, shuttle in enumerate(shuttles): print("Shuttle %d has completed %d flights." % (index, shuttle.flights_completed)) print("\n") # Show the distance from the first shuttle to all other shuttles. first_shuttle = shuttles[0] for index, shuttle in enumerate(shuttles): distance = first_shuttle.get_distance(shuttle) print("The first shuttle is %f units away from shuttle %d." % (distance, index)) print("\n") # Show the distance from the first shuttle to all other rockets. for index, rocket in enumerate(rockets): distance = first_shuttle.get_distance(rocket) print("The first shuttle is %f units away from rocket %d." % (distance, index))
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
Inheritance is a powerful feature of object-oriented programming. Using just what you have seen so far about classes, you can model an incredible variety of real-world and virtual phenomena with a high degree of accuracy. The code you write has the potential to be stable and reusable in a variety of applications. top <a name='exercises_inheritance'></a>Exercises <a name='exercise_student_class'></a>Student Class Start with your program from Person Class. Make a new class called Student that inherits from Person. Define some attributes that a student has, which other people don't have. A student has a school they are associated with, a graduation year, a gpa, and other particular attributes. Create a Student object, and prove that you have used inheritance correctly. Set some attribute values for the student, that are only coded in the Person class. Set some attribute values for the student, that are only coded in the Student class. Print the values for all of these attributes. Refining Shuttle Take the latest version of the Shuttle class. Extend it. Add more attributes that are particular to shuttles such as maximum number of flights, capability of supporting spacewalks, and capability of docking with the ISS. Add one more method to the class, that relates to shuttle behavior. This method could simply print a statement, such as "Docking with the ISS," for a dock_ISS() method. Prove that your refinements work by creating a Shuttle object with these attributes, and then call your new method.
# Ex 9.7 : Student Class # put your code here # Ex 9.8 : Refining Shuttle # put your code here
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
top <a name='modules_classes'></a>Modules and classes Now that you are starting to work with classes, your files are going to grow longer. This is good, because it means your programs are probably doing more interesting things. But it is bad, because longer files can be more difficult to work with. Python allows you to save your classes in another file and then import them into the program you are working on. This has the added advantage of isolating your classes into files that can be used in any number of different programs. As you use your classes repeatedly, the classes become more reliable and complete overall. <a name='single_class_module'></a>Storing a single class in a module When you save a class into a separate file, that file is called a module. You can have any number of classes in a single module. There are a number of ways you can then import the class you are interested in. Start out by saving just the Rocket class into a file called rocket.py. Notice the naming convention being used here: the module is saved with a lowercase name, and the class starts with an uppercase letter. This convention is pretty important for a number of reasons, and it is a really good idea to follow the convention.
# Save as rocket.py from math import sqrt class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self, x=0, y=0): # Each rocket has an (x,y) position. self.x = x self.y = y def move_rocket(self, x_increment=0, y_increment=1): # Move the rocket according to the paremeters given. # Default behavior is to move the rocket up one unit. self.x += x_increment self.y += y_increment def get_distance(self, other_rocket): # Calculates the distance from this rocket to another rocket, # and returns that value. distance = sqrt((self.x-other_rocket.x)**2+(self.y-other_rocket.y)**2) return distance
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
Make a separate file called rocket_game.py. If you are more interested in science than games, feel free to call this file something like rocket_simulation.py. Again, to use standard naming conventions, make sure you are using a lowercase_underscore name for this file.
# Save as rocket_game.py from rocket import Rocket rocket = Rocket() print("The rocket is at (%d, %d)." % (rocket.x, rocket.y))
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
This is a really clean and uncluttered file. A rocket is now something you can define in your programs, without the details of the rocket's implementation cluttering up your file. You don't have to include all the class code for a rocket in each of your files that deals with rockets; the code defining rocket attributes and behavior lives in one file, and can be used anywhere. The first line tells Python to look for a file called rocket.py. It looks for that file in the same directory as your current program. You can put your classes in other directories, but we will get to that convention a bit later. Notice that you do not. When Python finds the file rocket.py, it looks for a class called Rocket. When it finds that class, it imports that code into the current file, without you ever seeing that code. You are then free to use the class Rocket as you have seen it used in previous examples. top <a name='multiple_classes_module'></a>Storing multiple classes in a module A module is simply a file that contains one or more classes or functions, so the Shuttle class actually belongs in the rocket module as well:
# Save as rocket.py from math import sqrt class Rocket(): # Rocket simulates a rocket ship for a game, # or a physics simulation. def __init__(self, x=0, y=0): # Each rocket has an (x,y) position. self.x = x self.y = y def move_rocket(self, x_increment=0, y_increment=1): # Move the rocket according to the paremeters given. # Default behavior is to move the rocket up one unit. self.x += x_increment self.y += y_increment def get_distance(self, other_rocket): # Calculates the distance from this rocket to another rocket, # and returns that value. distance = sqrt((self.x-other_rocket.x)**2+(self.y-other_rocket.y)**2) return distance class Shuttle(Rocket): # Shuttle simulates a space shuttle, which is really # just a reusable rocket. def __init__(self, x=0, y=0, flights_completed=0): super().__init__(x, y) self.flights_completed = flights_completed
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
Now you can import the Rocket and the Shuttle class, and use them both in a clean uncluttered program file:
# Save as rocket_game.py from rocket import Rocket, Shuttle rocket = Rocket() print("The rocket is at (%d, %d)." % (rocket.x, rocket.y)) shuttle = Shuttle() print("\nThe shuttle is at (%d, %d)." % (shuttle.x, shuttle.y)) print("The shuttle has completed %d flights." % shuttle.flights_completed)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
The first line tells Python to import both the Rocket and the Shuttle classes from the rocket module. You don't have to import every class in a module; you can pick and choose the classes you care to use, and Python will only spend time processing those particular classes. <a name='multiple_ways_import'></a>A number of ways to import modules and classes There are several ways to import modules and classes, and each has its own merits. import module_name The syntax for importing classes that was just shown:
from module_name import ClassName
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
is straightforward, and is used quite commonly. It allows you to use the class names directly in your program, so you have very clean and readable code. This can be a problem, however, if the names of the classes you are importing conflict with names that have already been used in the program you are working on. This is unlikely to happen in the short programs you have been seeing here, but if you were working on a larger program it is quite possible that the class you want to import from someone else's work would happen to have a name you have already used in your program. In this case, you can use simply import the module itself:
# Save as rocket_game.py import rocket rocket_0 = rocket.Rocket() print("The rocket is at (%d, %d)." % (rocket_0.x, rocket_0.y)) shuttle_0 = rocket.Shuttle() print("\nThe shuttle is at (%d, %d)." % (shuttle_0.x, shuttle_0.y)) print("The shuttle has completed %d flights." % shuttle_0.flights_completed)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
The general syntax for this kind of import is:
import module_name
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
After this, classes are accessed using dot notation:
module_name.ClassName
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
This prevents some name conflicts. If you were reading carefully however, you might have noticed that the variable name rocket in the previous example had to be changed because it has the same name as the module itself. This is not good, because in a longer program that could mean a lot of renaming. import module_name as local_module_name There is another syntax for imports that is quite useful:
import module_name as local_module_name
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
When you are importing a module into one of your projects, you are free to choose any name you want for the module in your project. So the last example could be rewritten in a way that the variable name rocket would not need to be changed:
# Save as rocket_game.py import rocket as rocket_module rocket = rocket_module.Rocket() print("The rocket is at (%d, %d)." % (rocket.x, rocket.y)) shuttle = rocket_module.Shuttle() print("\nThe shuttle is at (%d, %d)." % (shuttle.x, shuttle.y)) print("The shuttle has completed %d flights." % shuttle.flights_completed)
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
This approach is often used to shorten the name of the module, so you don't have to type a long module name before each class name that you want to use. But it is easy to shorten a name so much that you force people reading your code to scroll to the top of your file and see what the shortened name stands for. In this example,
import rocket as rocket_module
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
leads to much more readable code than something like:
import rocket as r
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
from module_name import * There is one more import syntax that you should be aware of, but you should probably avoid using. This syntax imports all of the available classes and functions in a module:
from module_name import *
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
This is not recommended, for a couple reasons. First of all, you may have no idea what all the names of the classes and functions in a module are. If you accidentally give one of your variables the same name as a name from the module, you will have naming conflicts. Also, you may be importing way more code into your program than you need. If you really need all the functions and classes from a module, just import the module and use the module_name.ClassName syntax in your program. You will get a sense of how to write your imports as you read more Python code, and as you write and share some of your own code. top <a name='module_functions'></a>A module of functions You can use modules to store a set of functions you want available in different programs as well, even if those functions are not attached to any one class. To do this, you save the functions into a file, and then import that file just as you saw in the last section. Here is a really simple example; save this is multiplying.py:
# Save as multiplying.py def double(x): return 2*x def triple(x): return 3*x def quadruple(x): return 4*x
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
Now you can import the file multiplying.py, and use these functions. Using the from module_name import function_name syntax:
from multiplying import double, triple, quadruple print(double(5)) print(triple(5)) print(quadruple(5))
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
Using the import module_name syntax:
import multiplying print(multiplying.double(5)) print(multiplying.triple(5)) print(multiplying.quadruple(5))
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
Using the import module_name as local_module_name syntax:
import multiplying as m print(m.double(5)) print(m.triple(5)) print(m.quadruple(5))
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
Using the from module_name import * syntax:
from multiplying import * print(double(5)) print(triple(5)) print(quadruple(5))
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
top <a name='exercises_importing'></a>Exercises Importing Student Take your program from Student Class Save your Person and Student classes in a separate file called person.py. Save the code that uses these classes in four separate files. In the first file, use the from module_name import ClassName syntax to make your program run. In the second file, use the import module_name syntax. In the third file, use the import module_name as different_local_module_name syntax. In the fourth file, use the import * syntax. Importing Car Take your program from Car Class Save your Car class in a separate file called car.py. Save the code that uses the car class into four separate files. In the first file, use the from module_name import ClassName syntax to make your program run. In the second file, use the import module_name syntax. In the third file, use the import module_name as different_local_module_name syntax. In the fourth file, use the import * syntax.
# Ex 9.9 : Importing Student # put your code here # Ex 9.10 : Importing Car # put your code here
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
top <a name="mro"></a>Method Resolution Order (mro)
class A: def __init__(self, a): self.a = a class GreatB: def greetings(self): print('Greetings from Type: ', self.__class__) class B(GreatB): def __init__(self, b): self.b = b class C(A,B): def __init__(self, a, b): A.__init__(self, a) B.__init__(self, b) print('MRO: ', C.mro()) c = C('A', 'B') print('c.a: ', c.a) print('c.b: ', c.b) c.greetings() super(C, c).greetings() super(B, c).greetings()
08 Classes and OOP.ipynb
leriomaggio/python-in-a-notebook
mit
Load directories
root_directory = 'D:/github/w_vattenstatus/ekostat_calculator'#"../" #os.getcwd() workspace_directory = root_directory + '/workspaces' resource_directory = root_directory + '/resources' #alias = 'lena' user_id = 'test_user' #kanske ska vara off_line user? # workspace_alias = 'lena_indicator' # kustzonsmodellen_3daydata workspace_alias = 'kustzonsmodellen_3daydata' # ## Initiate EventHandler print(root_directory) paths = {'user_id': user_id, 'workspace_directory': root_directory + '/workspaces', 'resource_directory': root_directory + '/resources', 'log_directory': 'D:/github' + '/log', 'test_data_directory': 'D:/github' + '/test_data', 'cache_directory': 'D:/github/w_vattenstatus/cache'} t0 = time.time() ekos = EventHandler(**paths) #request = ekos.test_requests['request_workspace_list'] #response = ekos.request_workspace_list(request) #ekos.write_test_response('request_workspace_list', response) print('-'*50) print('Time for request: {}'.format(time.time()-t0)) ############################################################################################################################### # ### Make a new workspace # ekos.copy_workspace(source_uuid='default_workspace', target_alias='kustzonsmodellen_3daydata') # ### See existing workspaces and choose workspace name to load ekos.print_workspaces() workspace_uuid = ekos.get_unique_id_for_alias(workspace_alias = workspace_alias) #'kuszonsmodellen' lena_indicator print(workspace_uuid) workspace_alias = ekos.get_alias_for_unique_id(workspace_uuid = workspace_uuid) ############################################################################################################################### # ### Load existing workspace ekos.load_workspace(unique_id = workspace_uuid) ############################################################################################################################### # ### import data # ekos.import_default_data(workspace_alias = workspace_alias) ############################################################################################################################### # ### Load all data in workspace # #### if there is old data that you want to remove ekos.get_workspace(workspace_uuid = workspace_uuid).delete_alldata_export() ekos.get_workspace(workspace_uuid = workspace_uuid).delete_all_export_data() ############################################################################################################################### # #### to just load existing data in workspace ekos.load_data(workspace_uuid = workspace_uuid) ############################################################################################################################### # ### check workspace data length w = ekos.get_workspace(workspace_uuid = workspace_uuid) len(w.data_handler.get_all_column_data_df()) ############################################################################################################################### # ### see subsets in data for subset_uuid in w.get_subset_list(): print('uuid {} alias {}'.format(subset_uuid, w.uuid_mapping.get_alias(unique_id=subset_uuid))) ############################################################################################################################### # # Step 0 print(w.data_handler.all_data.columns) ############################################################################################################################### # ### Apply first data filter w.apply_data_filter(step = 0) # This sets the first level of data filter in the IndexHandler ############################################################################################################################### # # Step 1 # ### make new subset # w.copy_subset(source_uuid='default_subset', target_alias='test_kustzon') ############################################################################################################################### # ### Choose subset name to load subset_alias = 'test_kustzon' # subset_alias = 'period_2007-2012_refvalues_2013' # subset_alias = 'test_subset' subset_uuid = ekos.get_unique_id_for_alias(workspace_alias = workspace_alias, subset_alias = subset_alias) print('subset_alias', subset_alias, 'subset_uuid', subset_uuid)
notebooks/lv_notebook_kustzon.ipynb
ekostat/ekostat_calculator
mit
Set subset filters
# #### year filter w.set_data_filter(subset = subset_uuid, step=1, filter_type='include_list', filter_name='MYEAR', data=[2007,2008,2009,2010,2011,2012])#['2011', '2012', '2013']) #, 2014, 2015, 2016 ############################################################################################################################### # #### waterbody filter w.set_data_filter(subset = subset_uuid, step=1, filter_type='include_list', filter_name='viss_eu_cd', data = []) #'SE584340-174401', 'SE581700-113000', 'SE654470-222700', 'SE633000-195000', 'SE625180-181655' # data=['SE584340-174401', 'SE581700-113000', 'SE654470-222700', 'SE633000-195000', 'SE625180-181655']) # wb with no data for din 'SE591400-182320' f1 = w.get_data_filter_object(subset = subset_uuid, step=1) print(f1.include_list_filter) print('subset_alias:', subset_alias, '\nsubset uuid:', subset_uuid) f1 = w.get_data_filter_object(subset = subset_uuid, step=1) print(f1.include_list_filter) ############################################################################################################################### # ## Apply step 1 datafilter to subset w.apply_data_filter(subset = subset_uuid, step = 1) filtered_data = w.get_filtered_data(step = 1, subset = subset_uuid) print(filtered_data['VISS_EU_CD'].unique()) filtered_data[['AMON','NTRA','DIN','CPHL_INTEG_CALC','DEPH']].head()
notebooks/lv_notebook_kustzon.ipynb
ekostat/ekostat_calculator
mit
######################################################################################################################### Step 2
### Load indicator settings filter w.get_step_object(step = 2, subset = subset_uuid).load_indicator_settings_filters() ############################################################################################################################### ### set available indicators w.get_available_indicators(subset= subset_uuid, step=2) ############################################################################################################################### # ### choose indicators #list(zip(typeA_list, df_step1.WATER_TYPE_AREA.unique())) # indicator_list = ['oxygen','din_winter','ntot_summer', 'ntot_winter', 'dip_winter', 'ptot_summer', 'ptot_winter','bqi', 'biov', 'chl', 'secchi'] # indicator_list = ['din_winter','ntot_summer', 'ntot_winter', 'dip_winter', 'ptot_summer', 'ptot_winter'] #indicator_list = ['biov', 'chl'] # indicator_list = ['bqi', 'biov', 'chl', 'secchi'] #indicator_list = ['bqi', 'secchi'] + ['biov', 'chl'] + ['din_winter'] # indicator_list = ['din_winter','ntot_summer'] # indicator_list = ['indicator_' + indicator for indicator in indicator_list] indicator_list = w.available_indicators ############################################################################################################################### # ### Apply indicator data filter print('apply indicator data filter to {}'.format(indicator_list)) for indicator in indicator_list: w.apply_indicator_data_filter(step = 2, subset = subset_uuid, indicator = indicator)#, # water_body_list = test_wb) #print(w.mapping_objects['water_body'][wb]) #print('*************************************') #df = w.get_filtered_data(subset = subset_uuid, step = 'step_2', water_body = 'SE625180-181655', indicator = 'indicator_din_winter').dropna(subset = ['DIN'])
notebooks/lv_notebook_kustzon.ipynb
ekostat/ekostat_calculator
mit
######################################################################################################################### Step 3
# ### Set up indicator objects print('indicator set up to {}'.format(indicator_list)) w.get_step_object(step = 3, subset = subset_uuid).indicator_setup(indicator_list = indicator_list) ############################################################################################################################### # ### CALCULATE STATUS print('CALCULATE STATUS to {}'.format(indicator_list)) w.get_step_object(step = 3, subset = subset_uuid).calculate_status(indicator_list = indicator_list) ############################################################################################################################### # ### CALCULATE QUALITY ELEMENTS w.get_step_object(step = 3, subset = subset_uuid).calculate_quality_element(quality_element = 'nutrients') # w.get_step_object(step = 3, subset = subset_uuid).calculate_quality_element(quality_element = 'phytoplankton') # w.get_step_object(step = 3, subset = subset_uuid).calculate_quality_element(quality_element = 'bottomfauna') # w.get_step_object(step = 3, subset = subset_uuid).calculate_quality_element(quality_element = 'oxygen') # w.get_step_object(step = 3, subset = subset_uuid).calculate_quality_element(quality_element = 'secchi') # w.get_step_object(step = 3, subset = subset_uuid).calculate_quality_element(subset_unique_id = subset_uuid, quality_element = 'Phytoplankton')
notebooks/lv_notebook_kustzon.ipynb
ekostat/ekostat_calculator
mit
Figure 1 csv data generation Figure data consolidation for Figure 1, which maps samples and shows distribution across EMPO categories Figure 1a and 1b for these figure, we just need the samples, EMPO level categories, and lat/lon coordinates
# Load up metadata map metadata_fp = '../../../data/mapping-files/emp_qiime_mapping_qc_filtered.tsv' metadata = pd.read_csv(metadata_fp, header=0, sep='\t') metadata.head() metadata.columns # take just the columns we need for this figure panel fig1ab = metadata.loc[:,['#SampleID','empo_0','empo_1','empo_2','empo_3','latitude_deg','longitude_deg']] fig1ab.head()
methods/figure-data/fig-1/Fig1_data_files.ipynb
cuttlefishh/emp
bsd-3-clause
Write to Excel notebook
fig1 = pd.ExcelWriter('Figure1_data.xlsx') fig1ab.to_excel(fig1,'Fig-1ab') fig1.save()
methods/figure-data/fig-1/Fig1_data_files.ipynb
cuttlefishh/emp
bsd-3-clause
Optionally, enable debug level logging
# Uncomment this if you want debug logging enabled #setup_logger(log_file="pytx.log")
ipynb/ThreatExchange Data Dashboard.ipynb
tiegz/ThreatExchange
bsd-3-clause
Search for data in ThreatExchange Start by running a query against the ThreatExchange APIs to pull down any/all data relevant to you over a specified period of days.
# Our basic search parameters, we default to querying over the past 14 days days_back = 14 search_terms = ['abuse', 'phishing', 'malware', 'exploit', 'apt', 'ddos', 'brute', 'scan', 'cve']
ipynb/ThreatExchange Data Dashboard.ipynb
tiegz/ThreatExchange
bsd-3-clause
Next, we execute the query using our search parameters and put the results in a Pandas DataFrame
from datetime import datetime, timedelta from time import strftime import pandas as pd import re from pytx import ThreatDescriptor from pytx.vocabulary import ThreatExchange as te # Define your search string and other params, see # https://pytx.readthedocs.org/en/latest/pytx.common.html#pytx.common.Common.objects # for the full list of options search_params = { te.FIELDS: ThreatDescriptor._default_fields, te.LIMIT: 1000, te.SINCE: strftime('%Y-%m-%d %H:%m:%S +0000', (datetime.utcnow() + timedelta(days=(-1*days_back))).timetuple()), te.TEXT: search_terms, te.UNTIL: strftime('%Y-%m-%d %H:%m:%S +0000', datetime.utcnow().timetuple()), te.STRICT_TEXT: False } data_frame = None for search_term in search_terms: print "Searching for '%s' over -%d days" % (search_term, days_back) results = ThreatDescriptor.objects( fields=search_params[te.FIELDS], limit=search_params[te.LIMIT], text=search_term, since=search_params[te.SINCE], until=search_params[te.UNTIL], strict_text=search_params[te.STRICT_TEXT] ) tmp = pd.DataFrame([result.to_dict() for result in results]) tmp['search_term'] = search_term print "\t... found %d descriptors" % tmp.size if data_frame is None: data_frame = tmp else: data_frame = data_frame.append(tmp) print "\nFound %d descriptors in total." % data_frame.size
ipynb/ThreatExchange Data Dashboard.ipynb
tiegz/ThreatExchange
bsd-3-clause
Do some data munging for easier analysis and then preview as a sanity check
from time import mktime # Extract a datetime and timestamp, for easier analysis data_frame['ds'] = pd.to_datetime(data_frame.added_on.str[0:10], format='%Y-%m-%d') data_frame['ts'] = pd.to_datetime(data_frame.added_on) # Extract the owner data owner = data_frame.pop('owner') owner = owner.apply(pd.Series) data_frame = pd.concat([data_frame, owner.email, owner.name], axis=1) # Extract freeform 'tags' in the description def extract_tags(text): return re.findall(r'\[([a-zA-Z0-9\:\-\_]+)\]', text) data_frame['tags'] = data_frame.description.map(lambda x: [] if x is None else extract_tags(x)) data_frame.head(n=5)
ipynb/ThreatExchange Data Dashboard.ipynb
tiegz/ThreatExchange
bsd-3-clause
Create a Dashboard to Get a High-level View The raw data is great, but it would be much better if we could take a higher level view of the data. This dashboard will provide more insight into: what data is available who's sharing it how is labeled how much of it is likely to be directly applicable for alerting
import math import matplotlib.pyplot as plt import seaborn as sns from pytx.vocabulary import ThreatDescriptor as td %matplotlib inline # Setup subplots for our dashboard fig, axes = plt.subplots(nrows=4, ncols=2, figsize=(16,32)) axes[0,0].set_color_cycle(sns.color_palette("coolwarm_r", 15)) # Plot by Type over time type_over_time = data_frame.groupby( [pd.Grouper(freq='d', key='ds'), te.TYPE] ).count().unstack(te.TYPE) type_over_time.added_on.plot( kind='line', stacked=True, title="Indicator Types Per Day (-" + str(days_back) + "d)", ax=axes[0,0] ) # Plot by threat_type over time tt_over_time = data_frame.groupby( [pd.Grouper(freq='w', key='ds'), 'threat_type'] ).count().unstack('threat_type') tt_over_time.added_on.plot( kind='bar', stacked=True, title="Threat Types Per Week (-" + str(days_back) + "d)", ax=axes[0,1] ) # Plot the top 10 tags tags = pd.DataFrame([item for sublist in data_frame.tags for item in sublist]) tags[0].value_counts().head(10).plot( kind='bar', stacked=True, title="Top 10 Tags (-" + str(days_back) + "d)", ax=axes[1,0] ) # Plot by who is sharing owner_over_time = data_frame.groupby( [pd.Grouper(freq='w', key='ds'), 'name'] ).count().unstack('name') owner_over_time.added_on.plot( kind='bar', stacked=True, title="Who's Sharing Each Week? (-" + str(days_back) + "d)", ax=axes[1,1] ) # Plot the data as a timeseries of when it was published data_over_time = data_frame.groupby(pd.Grouper(freq='6H', key='ts')).count() data_over_time.added_on.plot( kind='line', title="Data shared over time (-" + str(days_back) + "d)", ax=axes[2,0] ) # Plot by status label data_frame.status.value_counts().plot( kind='pie', title="Threat Statuses (-" + str(days_back) + "d)", ax=axes[2,1] ) # Heatmap by type / source owner_and_type = pd.DataFrame(data_frame[['name', 'type']]) owner_and_type['n'] = 1 grouped = owner_and_type.groupby(['name', 'type']).count().unstack('type').fillna(0) ax = sns.heatmap( data=grouped['n'], robust=True, cmap="YlGnBu", ax=axes[3,0] ) # These require a little data munging # translate a severity enum to a value # TODO Add this translation to Pytx def severity_value(severity): if severity == 'UNKNOWN': return 0 elif severity == 'INFO': return 1 elif severity == 'WARNING': return 3 elif severity == 'SUSPICIOUS': return 5 elif severity == 'SEVERE': return 7 elif severity == 'APOCALYPSE': return 10 return 0 # translate a severity def value_severity(severity): if severity >= 9: return 'APOCALYPSE' elif severity >= 6: return 'SEVERE' elif severity >= 4: return 'SUSPICIOUS' elif severity >= 2: return 'WARNING' elif severity >= 1: return 'INFO' elif severity >= 0: return 'UNKNOWN' # Plot by how actionable the data is # Build a special dataframe and chart it data_frame['severity_value'] = data_frame.severity.apply(severity_value) df2 = pd.DataFrame({'count' : data_frame.groupby(['name', 'confidence', 'severity_value']).size()}).reset_index() ax = df2.plot( kind='scatter', x='severity_value', y='confidence', xlim=(-1,11), ylim=(-10,110), title='Data by Conf / Sev With Threshold Line', ax=axes[3,1], s=df2['count'].apply(lambda x: 1000 * math.log10(x)), use_index=td.SEVERITY ) # Draw a threshhold for data we consider likely using for alerts (aka 'high value') ax.plot([2,10], [100,0], c='red')
ipynb/ThreatExchange Data Dashboard.ipynb
tiegz/ThreatExchange
bsd-3-clause
Dive A Little Deeper Take a subset of the data and understand it a little more. In this example, we presume that we'd like to take phishing related data and study it, to see if we can use it to better defend a corporate network or abuse in a product. As a simple example, we'll filter down to data labeled MALICIOUS and the word phish in the description, to see if we can make a more detailed conclusion on how to apply the data to our existing internal workflows.
from pytx.vocabulary import Status as s phish_data = data_frame[(data_frame.status == s.MALICIOUS) & data_frame.description.apply(lambda x: x.find('phish') if x != None else False)] # TODO: also filter for attack_type == PHISHING, when Pytx supports it %matplotlib inline # Setup subplots for our deeper dive plots fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(16,8)) # Heatmap of type / source owner_and_type = pd.DataFrame(phish_data[['name', 'type']]) owner_and_type['n'] = 1 grouped = owner_and_type.groupby(['name', 'type']).count().unstack('type').fillna(0) ax = sns.heatmap( data=grouped['n'], robust=True, cmap="YlGnBu", ax=axes[0] ) # Tag breakdown of the top 10 tags tags = pd.DataFrame([item for sublist in phish_data.tags for item in sublist]) tags[0].value_counts().head(10).plot( kind='pie', title="Top 10 Tags (-" + str(days_back) + "d)", ax=axes[1] )
ipynb/ThreatExchange Data Dashboard.ipynb
tiegz/ThreatExchange
bsd-3-clause
Extract The High Confidence / Severity Data For Use With a better understanding of the data, let's filter the MALICIOUS, REVIEWED_MANUALLY labeled data down to a pre-determined threshold for confidence + severity. You can add more filters, or change the threshold, as you see fit.
from pytx.vocabulary import ReviewStatus as rs # define our threshold line, which is the same as the red, threshold line in the chart above sev_min = 2 sev_max = 10 conf_min= 0 conf_max = 100 # build a new series, to indicate if a row passes our confidence + severity threshold def is_high_value(conf, sev): return (((sev_max - sev_min) * (conf - conf_max)) - ((conf_min - conf_max) * (sev - sev_min))) > 0 data_frame['is_high_value']= data_frame.apply(lambda x: is_high_value(x.confidence, x.severity_value), axis=1) # filter down to just the data passing our criteria, you can add more here to filter by type, source, etc. high_value_data = data_frame[data_frame.is_high_value & (data_frame.status == s.MALICIOUS) & (data_frame.review_status == rs.REVIEWED_MANUALLY)].reset_index(drop=True) # get a count of how much we kept print "Kept %d of %d data as high value" % (high_value_data.size, data_frame.size) # ... and preview it high_value_data.head()
ipynb/ThreatExchange Data Dashboard.ipynb
tiegz/ThreatExchange
bsd-3-clause
Now, output all of the high value data to a file as CSV or JSON, for consumption in our other systems and workflows.
use_csv = False if use_csv: file_name = 'threat_exchange_high_value.csv' high_value_data.to_csv(path_or_buf=file_name) print "CSV data written to %s" % file_name else: file_name = 'threat_exchange_high_value.json' high_value_data.to_json(path_or_buf=file_name, orient='index') print "JSON data written to %s" % file_name
ipynb/ThreatExchange Data Dashboard.ipynb
tiegz/ThreatExchange
bsd-3-clause
Creamos una matriz cuadrada relativamente grande (4 millones de elementos).
np.random.seed(0) data = np.random.randn(2000, 2000)
C elemental, querido Cython..ipynb
Ykharo/notebooks
bsd-2-clause
Ya tenemos los datos listos para empezar a trabajar. Vamos a crear una función en Python que busque los mínimos tal como los hemos definido.
def busca_min(malla): minimosx = [] minimosy = [] for i in range(1, malla.shape[1]-1): for j in range(1, malla.shape[0]-1): if (malla[j, i] < malla[j-1, i-1] and malla[j, i] < malla[j-1, i] and malla[j, i] < malla[j-1, i+1] and malla[j, i] < malla[j, i-1] and malla[j, i] < malla[j, i+1] and malla[j, i] < malla[j+1, i-1] and malla[j, i] < malla[j+1, i] and malla[j, i] < malla[j+1, i+1]): minimosx.append(i) minimosy.append(j) return np.array(minimosx), np.array(minimosy)
C elemental, querido Cython..ipynb
Ykharo/notebooks
bsd-2-clause
Veamos cuanto tarda esta función en mi máquina:
%timeit busca_min(data)
C elemental, querido Cython..ipynb
Ykharo/notebooks
bsd-2-clause
Buff, tres segundos y pico en un i7... Si tengo que buscar los mínimos en 500 de estos casos me va a tardar casi media hora. Por casualidad, vamos a probar numba a ver si es capaz de resolver el problema sin mucho esfuerzo, es código Python muy sencillo en el cual no usamos cosas muy 'extrañas' del lenguaje.
from numba import jit @jit def busca_min_numba(malla): minimosx = [] minimosy = [] for i in range(1, malla.shape[1]-1): for j in range(1, malla.shape[0]-1): if (malla[j, i] < malla[j-1, i-1] and malla[j, i] < malla[j-1, i] and malla[j, i] < malla[j-1, i+1] and malla[j, i] < malla[j, i-1] and malla[j, i] < malla[j, i+1] and malla[j, i] < malla[j+1, i-1] and malla[j, i] < malla[j+1, i] and malla[j, i] < malla[j+1, i+1]): minimosx.append(i) minimosy.append(j) return np.array(minimosx), np.array(minimosy) %timeit busca_min_numba(data)
C elemental, querido Cython..ipynb
Ykharo/notebooks
bsd-2-clause
Ooooops! Parece que la magia de numba no funciona aquí. Vamos a especificar los tipos de entrada y de salida (y a modificar el output) a ver si mejora algo:
from numba import jit from numba import int32, float64 @jit(int32[:,:](float64[:,:])) def busca_min_numba(malla): minimosx = [] minimosy = [] for i in range(1, malla.shape[1]-1): for j in range(1, malla.shape[0]-1): if (malla[j, i] < malla[j-1, i-1] and malla[j, i] < malla[j-1, i] and malla[j, i] < malla[j-1, i+1] and malla[j, i] < malla[j, i-1] and malla[j, i] < malla[j, i+1] and malla[j, i] < malla[j+1, i-1] and malla[j, i] < malla[j+1, i] and malla[j, i] < malla[j+1, i+1]): minimosx.append(i) minimosy.append(j) return np.array([minimosx, minimosy], dtype = np.int32) %timeit busca_min_numba(data)
C elemental, querido Cython..ipynb
Ykharo/notebooks
bsd-2-clause
Pues parece que no, el resultado es del mismo pelo. Usando la opción nopython me casca un error un poco feo,... Habrá que seguir esperando a que numba esté un poco más maduro. En mis pocas experiencias no he conseguido aun el efecto que buscaba y en la mayoría de los casos obtengo errores muy crípticos. No es que no tenga confianza en la gente que está detrás, solo estoy diciendo que aun no está listo para 'producción'. Esto no pretende ser una guerra Cython/numba, solo he usado numba para ver si a pelo era capaz de mejorar algo el tema. Como no ha sido así, nos olvidamos de numba de momento. Cythonizando, que es gerundio (toma 1). Lo más sencillo y evidente es usar directamente el compilador cython y ver si usando el código python tal cual es un poco más rápido. Para ello, vamos a usar las funciones mágicas que Cython pone a nuestra disposición en el notebook. Solo vamos a hablar de la función mágica %%cython, de momento, aunque hay otras.
# antes cythonmagic %load_ext Cython
C elemental, querido Cython..ipynb
Ykharo/notebooks
bsd-2-clause
EL comando %%cython nos permite escribir código Cython en una celda. Una vez que ejecutamos la celda, IPython se encarga de coger el código, crear un fichero de código Cython con extensión .pyx, compilarlo a C y, si todo está correcto, importar ese fichero para que todo esté disponible dentro del notebook. [INCISO] a la función mágica %%cython le podemos pasar una serie de argumentos. Veremos alguno en este análisis pero ahora vamos a definir uno que sirve para que podamos nombrar a la funcíon que se crea y compila al vuelo, -n o --name.
%%cython --name probandocython1 import numpy as np def busca_min_cython1(malla): minimosx = [] minimosy = [] for i in range(1, malla.shape[1]-1): for j in range(1, malla.shape[0]-1): if (malla[j, i] < malla[j-1, i-1] and malla[j, i] < malla[j-1, i] and malla[j, i] < malla[j-1, i+1] and malla[j, i] < malla[j, i-1] and malla[j, i] < malla[j, i+1] and malla[j, i] < malla[j+1, i-1] and malla[j, i] < malla[j+1, i] and malla[j, i] < malla[j+1, i+1]): minimosx.append(i) minimosy.append(j) return np.array(minimosx), np.array(minimosy)
C elemental, querido Cython..ipynb
Ykharo/notebooks
bsd-2-clause
El fichero se creará dentro de la carpeta cython disponible dentro del directorio resultado de la función get_ipython_cache_dir. Veamos la localización del fichero en mi equipo:
from IPython.utils.path import get_ipython_cache_dir print(get_ipython_cache_dir() + '/cython/probandocython1.c')
C elemental, querido Cython..ipynb
Ykharo/notebooks
bsd-2-clause
No lo muestro por aquí porque el resultado son más de ¡¡2400!! líneas de código C. Veamos ahora lo que tarda.
%timeit busca_min_cython1(data)
C elemental, querido Cython..ipynb
Ykharo/notebooks
bsd-2-clause
Bueno, parece que sin hacer mucho esfuerzo hemos conseguido ganar en torno a un 5% - 25% de rendimiento (dependerá del caso). No es gran cosa pero Cython es capaz de mucho más... Cythonizando, que es gerundio (toma 2). En esta parte vamos a introducir una de las palabras clave que Cython introduce para extender Python, cdef. La palabra clave cdef sirve para 'tipar' estáticamente variables en Cython (luego veremos que se usa también para definir funciones). Por ejemplo: Python cdef int var1, var2 cdef float var3 En el bloque de código de más arriba he creado dos variables de tipo entero, var1 y var2, y una variable de tipo float, var3. Los tipos anteriores son la nomenclatura C. Vamos a intentar usar cdef con algunos tipos de datos que tenemos dentro de nuestra función. Para empezar, veo evidente que tengo varias listas (minimosx y minimosy), tenemos los índices de los bucles (i y j) y voy a convertir los parámetros de los range en tipos estáticos (ii y jj):
%%cython --name probandocython2 import numpy as np def busca_min_cython2(malla): cdef list minimosx, minimosy cdef unsigned int i, j cdef unsigned int ii = malla.shape[1]-1 cdef unsigned int jj = malla.shape[0]-1 minimosx = [] minimosy = [] for i in range(1, ii): for j in range(1, jj): if (malla[j, i] < malla[j-1, i-1] and malla[j, i] < malla[j-1, i] and malla[j, i] < malla[j-1, i+1] and malla[j, i] < malla[j, i-1] and malla[j, i] < malla[j, i+1] and malla[j, i] < malla[j+1, i-1] and malla[j, i] < malla[j+1, i] and malla[j, i] < malla[j+1, i+1]): minimosx.append(i) minimosy.append(j) return np.array(minimosx), np.array(minimosy) %timeit busca_min_cython2(data)
C elemental, querido Cython..ipynb
Ykharo/notebooks
bsd-2-clause
Vaya decepción... No hemos conseguido gran cosa, tenemos un código un poco más largo y estamos peor que en la toma 1. En realidad, estamos usando objetos Python como listas (no es un tipo C/C++ puro pero Cython lo declara como puntero a algún tipo struct de Python) o numpy arrays y no hemos definido las variables de entrada y de salida. [INCISO] Cuando existe un tipo Python y C que tienen el mismo nombre (por ejemplo, int) predomina el de C (porque es lo deseable, ¿no?). Cythonizando, que es gerundio (toma 3). En Cython existen tres tipos de funciones, las definidas en el espacio Python con def, las definidas en el espacio C con cdef (sí, lo mismo que usamos para declarar los tipos) y las definidas en ambos espacios con cpdef. def: ya lo hemos visto y funciona como se espera. Accesible desde Python cdef: No es accesible desde Python y la tendremos que envolver con una función Python para poder acceder a la misma. cpdef: Es accesible tanto desde Python como desde C y Cython se encargará de hacer el 'envoltorio' para nosotros. Esto meterá un poco más de código y empeorará levemente el rendimiento. Si definimos una función con cdef debería ser una función que se usa internamente dentro del módulo Cython que vayamos a crear y que no sea necesario llamar desde Python. Veamos un ejemplo de lo dicho anteriormente definiendo la salida de la función como tupla:
%%cython --name probandocython3 import numpy as np cdef tuple cbusca_min_cython3(malla): cdef list minimosx, minimosy cdef unsigned int i, j cdef unsigned int ii = malla.shape[1]-1 cdef unsigned int jj = malla.shape[0]-1 cdef unsigned int start = 1 minimosx = [] minimosy = [] for i in range(start, ii): for j in range(start, jj): if (malla[j, i] < malla[j-1, i-1] and malla[j, i] < malla[j-1, i] and malla[j, i] < malla[j-1, i+1] and malla[j, i] < malla[j, i-1] and malla[j, i] < malla[j, i+1] and malla[j, i] < malla[j+1, i-1] and malla[j, i] < malla[j+1, i] and malla[j, i] < malla[j+1, i+1]): minimosx.append(i) minimosy.append(j) return np.array(minimosx), np.array(minimosy) def busca_min_cython3(malla): return cbusca_min_cython3(malla) %timeit busca_min_cython3(data)
C elemental, querido Cython..ipynb
Ykharo/notebooks
bsd-2-clause