Python:Various
This page collects some notes/hints about the use of the Python programming language.
Contents
[hide]Super
In object-oriented programming, one must sometimes call upon the parent class or super class.
In python, a given object (self) can refer to its parent as:
1 2 3 4 5 6 7 | #!/usr/bin/python # -*- coding: utf-8 -*- class Cube(Platonic): def __init__( self , args = {}): super (Cube, self ).__init__( args = args ) |
Also note that you can exploit * and ** to pass arguments along:
1 2 3 4 5 6 7 8 9 10 11 | #!/usr/bin/python class Foo( object ): def __init__( self , value1, value2): # do something with the values print value1, value2 class MyFoo(Foo): def __init__( self , * args, * * kwargs): # do something else, don't care about the args print 'myfoo' super (MyFoo, self ).__init__( * args, * * kwargs) |
In Python 3+, you can simply use 'super()' instead of 'super(MyFoo)'.
Matrix
Multiply matrix/array/grid by vector
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #!/usr/bin/python import numpy as np # 2D example size = 11 extent = 1.0 #axis_x = np.linspace( -extent, +extent, size ) #axis_y = np.linspace( -extent, +extent, size ) X, Y = np.meshgrid( axis_x, axis_y ) # Example 2D arrays v = np.asarray( [ np.linspace( 0 , 1 , size ) ] ) print X * v # Multiplies across row (x-direction) print X * v.transpose() # Multiplies down columns (y-direction) # 3D example size = 3 extent = 1.0 X, Y, Z = np.mgrid[ - extent: + extent:size * 1j , - extent: + extent:size * 1j , - extent: + extent:size * 1j ] # Example 3D arrays # Example vectors we want to multiply with u = np.linspace( 1 , 2 , size ).reshape(size, 1 , 1 ) # Multiplies down layers (z-direction) v = np.linspace( 1 , 2 , size ).reshape( 1 ,size, 1 ) # Multiplies down column (y-direction) w = np.linspace( 1 , 2 , size ).reshape( 1 , 1 ,size) # Multiplies across row (x-direction) print X print '--' print u print X * u print '--' print v print X * v print '--' print w print X * w |
Linear Regression
1 2 3 4 5 6 7 | #!/usr/bin/python3 data = [ [ 0 , 1 ], [ 10 , 11.1 ], [ 20 , 17.5 ] ] import numpy as np from scipy import stats slope, intercept, r_value, p_value, std_err = stats.linregress(np.asarray(data)[:, 0 ], np.asarray(data)[:, 1 ]) print ( "m = {:.3f} ; b = {:.3f} [R^2 = {:.2f}]" . format (slope, intercept, r_value)) |