Anda di halaman 1dari 30

Scientific Computing Using

Atriya Sen
Broad Outline
Part I, in which I discuss several aspects of the
Python programming language
Part II, in which I talk about some Python
modules for scientific computing
Part III, in which I show you how Python can be
integrated with other languages
Broad Outline
Part I, in which I discuss several aspects of
the Python programming language
Part II, in which I talk about some Python
modules for scientific computing
Part III, in which I show you how Python can be
integrated with other languages
#1: Readable & Compact Code
Shorter and more readable programs
Higher programmer productivity

1.1 9 5.2
1.762543E-02
0 0.01 0.001

F = open(filename, r);
F.read().split()
#2: Dynamic typing
Types are decided at run-time, as opposed to static typing, where
types are decided at compile-time
Procedure to dump a data structure with a debugging message:

def debug(leading_text, variable):


if os.environ.get(MYDEBUG, 0) == 1:
print leading_text, variable

Dynamic typing extends elegantly to nested heterogeneous data


structures!
The Same Code In C++...
template <class T>
void debug(std::ostream& o, const std::string& leading_text, const
T& variable) {
char* c = getenv("MYDEBUG");
bool defined = false;
if (c != NULL) // if MYDEBUG is defined ...
if (std::string(c) == "1") // if MYDEBUG is true ...
defined = true;
if (defined)
o << leading_text << " " << variable << std::endl;
}
#3: Interactive Computing
#4: Easy GUI Programming
A graphical Hello World program:

#!/usr/bin/env python
from Tkinter import *
root = Tk()
Label(root, text=Hello, World!,
foreground="white", background="black").pack()
root.mainloop()

C + X11: 176 lines of ugly code


Things get even worse for C when it comes to web development!
#5: Create Code At Runtime!
Code can be constructed and executed at run-time:

a = 1.2
no of iterations = 100
solution strategy = implicit
c1 = 0
c2 = 0.1
A = 4
c3 = StringFunction(A*sin(x))

Can we read this file and define a, no_of_iterations, solution_strategy,


c1, c2, c3, A with the specified values? Yes!
#5: Create Code At Runtime (2)

file = open(inputfile.dat, r)
for line in file:
variable, value = line.split(=).strip()
variable = re.sub( , _, variable)
exec(variable + = + value)
# magic :D

This cannot be done in C, C++, FORTRAN, or Java!


Python Compared To MATLAB
Python modules provide functionality comparable to MATLAB
Python can be as fast as MATLAB (and faster than Octave)
The Python language is more flexible and powerful
Object oriented programming is more convenient in Python
Transferring functions as arguments to functions is simpler
Nested, variable-type data structures are simpler to construct
and use
Interfacing with other languages and tools is simpler in Python
MATLAB is more self-contained
Python respects your freedom; Python runs on more platforms
Broad Outline
Part I, in which I discuss several aspects of the
Python programming language
Part II, in which I talk about some Python
modules for scientific computing
Part III, in which I show you how Python can be
integrated with other languages
numpy.scipy.or
g

numpy = Numeric + numarray


Efficient array computations using a fixed-size, fixed-type
multi-dimensional array type; also offers a matrix type
Trigonometric and other functions don't use these on
scalars!
Basic random number generation and linear algebra
capabilities
More functionality in the numpyutils module
NumPy Example: Just How Fast Are
We Talking?
from numpy import *
import time
a = linspace(0, 1, 1E+07)
t0 = time.clock()
b = 3*a -1
t1 = time.clock()
for i in xrange(a.size): b[i] = 3*a[i] - 1
t2 = time.clock()
print '3*a-1: %g sec, loop: %g sec' % (t1-t0, t2-
t1)
SciPy (www.scipy.org)
Builds on NumPy to provide a rapidly developing environment
for scientific computing
Special mathematical functions
Integration
ODE solvers
Random variables and statistics
Linear algebra calls up LAPACK
Optimization and root-finding
Interpolation
An alternative is ScientificPython (dirac.cnrs-
orleans.fr/plone/software/scientificpython)
A short digression: matplotlib and gnuplot
SciPy Examples
Finding the first four Simple integration:
zeroes of the Bessel
function J3: from scipy import
integrate
def myfunc(x):
return sin(x)
from scipy.special result, error =
integrate.quad(myfunc, 0,
import jn_zeros pi)
jn_zeros(3, 4) print result, error
Biopython (biopython.org)
Parse bioinformatics files
Use NCBI Blast, Entrez, PubMed and ExPASy data
Interfaces to common bioinformatics programs
A standard sequence class
Tools for performing common operations on sequences
Code to perform classification of data
Code for dealing with alignments
Split up parallelizable tasks into separate processes
GUI-based programs
Extensive documentation
Integration with BioSQL
SymPy (sympy.org)
Aims to become a full- Limits
featured computer Symbolic matrices
algebra system
Written in pure Python
Quantum physics
Differential equations
An alternative is Pattern matching
Swiginac (SWIG- Geometric algebra
based interface to
GiNaC, which is
Complex numbers
written in C++) Expansions
SymPy Example

def make_symbols(*args):
return [Symbol(s) for s in args]
x, a, A, omega, sigma, m, t = \
make_symbols('x', 'a', 'A', 'omega', 'sigma', 'm',
't')
f = A*exp(-((x-m)/(2*sigma))**2)*exp(-
a*t)*sin(2*pi*omega*x)
Prms = {'A': 1, 'a': 0.1, 'm': 1, 'sigma': 1,
'omega': 1, 't': 0.2}
print diff(f, x, 2)
More Python Modules!

PyPI

The Python Package Index

(pypi.python.org/pypi)
Broad Outline
Part I, in which I discuss several aspects of the
Python programming language
Part II, in which I talk about some Python
modules for scientific computing
Part III, in which I show you how Python can
be integrated with other languages
Python and C
Migration of performance- extern double hw1(double
critical code to C r1, double r2);
Access existing C code from hw import hw1
r1 = 1.2; r2 = -1.2
s = hw1(r1, r2)
Python is written in C and
designed to be extended
with C functions Python C API
C has strong typing rules; Extending and Embedding the Python
Interpreter
variables in Python are
(official documentation)
typeless
Needed to manipulate Python data
So, we need a wrapper structures in C
function written in C
The Wrapper Function
static PyObject Compile the wrapper
*_wrap_hw1(PyObject *self,
PyObject *args) {
function
double arg1, arg2, Compile the hw1 function
result; Link their object codes to
if (! form a shared library
PyArg_ParseTuple(args,
"dd:hw1", &arg1, &arg2)) { module
return NULL; This is called an extension
} module and can be
result = hw1(arg1, imported into Python code
arg2); There is no way to tell
return between a C module and a
Py_BuildValue("d", result);
Python module
}
Generation of Wrapper Code
SWIG (Simplified Wrapper Interface Generator) for
C and C++
F2PY for FORTRAN
Instant has support for inline C code. Uses SWIG
Pysco is a JIT for Python
Pyrex and Cython convert pseudo-Python code to C
Many other tools available CXX, SCXX,
Boost.Python, Weave, Pyrex, Pysco
Python, Java, .NET

Seamless Implementation on
implementation of Python on the JVM
Python on .NET Seamless - any Java
Python tools for MS class can be used in a
Visual Studio Jython script
Python, MATLAB, Mathematica
The pymat module import pymat
sends NumPy arrays to x = linspace(0, 4*math.pi,
MATLAB. It only has the 401)
functions open, close, m = pymat.open()
eval, put, get pymat.put(m, x, x);
The mlabwrap module pymat.eval(m, y =
sin(x))
makes MATLAB
command available pymat.eval(m, plot(x,y))
directly in Python y = pymat.get(m, y)
PYML is a Python- import time; time.sleep(4)
Mathematica interface pymat.close(m)
Where To Go For More
http://diveintopython.org/, or even
http://diveintopython3.org/. Both by Mark
Pilgrim
Python Scripting For Computational Science
by H. P. Langtangen
http://home.simula.no/~hpl/scripting/ebook/.
The password for the 3rd edition is 'Clicking'
http://www.scipy.org/NumPy_for_Matlab_Users
(for MATLAB users)

Anda mungkin juga menyukai