Python:Various
Revision as of 16:07, 15 October 2014 by KevinYager (talk | contribs)
This page collects some notes/hints about the use of Python.
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 ) |
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 |