Size: 11891
Comment:
|
Size: 1335
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
= Warum Python? = | #acl AdminGroup:read,write EditorGroup:read All:read #format wiki #language en #pragma section-numbers off |
Line 3: | Line 6: |
* Frei (Open Source) und auf allen Plattformen verfügbar * Dynamische Very High Level Language (VHLL) * Mächtig mit vielen Anwendungsbereichen * Leicht erlernbar und kurze Entwicklungszeiten * Leicht erweiterbar durch Routinen in C/C++ oder Fortran * Module für wissenschaftliche Anwendungen (wie IDL und MATLAB) * Gut dokumentiert und dokumentierbar |
SatelliteImageAnalysis |
Line 11: | Line 8: |
= Die Programmierumgebung = | = Programming Python = |
Line 13: | Line 10: |
Der normale Pythoninterpreter wird mit dem Befehl '''python''' aufgerufen. {{{#!python python #Python 2.4.4 (#2, Apr 5 2007, 20:11:18) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> }}} |
== Lesson 1 - Introduction == |
Line 22: | Line 12: |
Ein Python Programm startet man entweder durch Aufruf des Interpreters und des Programmnamens {{{#!python python hello.py Hallo Welt }}} Oder als ausführbares Programm {{{#!python ./hello.py Hallo Welt }}} Dazu muss das Programm zuvor mit einer Magic-Line '''#!/usr/bin/python''' versehen werden und die Rechte mit '''chmod +x hello.py''' ensprechend gesetzt werden. |
SiaProgrammingPythonIntroduction |
Line 34: | Line 14: |
Der Quelltext des Programms mit dem Dateinamen '''hello.py''' sieht wie folgt aus. Die Endung '''.py''' ist Konvention für Python Programme. {{{#!python #!/usr/bin/python print "Hallo Welt" }}} |
SiaProgrammingPythonBasicPython |
Line 40: | Line 16: |
Das Programm kann mit einem Editor (z.B. '''nedit''' oder '''xemacs''') erzeugt und verändert werden. | SiaExercisesLesson1 |
Line 42: | Line 18: |
== IPython == http://ipython.scipy.org/ |
== Lesson 2 - Data types, structures and functions == |
Line 45: | Line 20: |
IPython (Aufruf '''ipython''') bietet eine stark erweiterte Interaktive Funktionalität des Interpreters (in Anlehnung an IDL und MATLAB). | SiaProgrammingPythonDatatypes |
Line 47: | Line 22: |
Nützlich sind die Magic-Kommandos, Betriebssystem-Aliase und die einfache Hilfe-Funktion. | SiaProgrammingPythonFunctions |
Line 49: | Line 24: |
{{{#!python ipython ... In [1]: run hello.py Hallo Welt }}} |
SiaExercisesLesson2 |
Line 56: | Line 26: |
=== Standardeditor === | == Lesson 3 - System, IO == |
Line 58: | Line 28: |
In der Konfigurationsdatei kann der Editor geändert werden: | SiaProgrammingPythonSystem |
Line 60: | Line 30: |
{{{#!python nedit .ipython/ipythonrc }}} |
== Documentation == |
Line 64: | Line 32: |
{{{#!python # Which editor to use with the %edit command. If you leave this at 0, IPython # will honor your EDITOR environment variable. Since this editor is invoked on # the fly by ipython and is meant for editing small code snippets, you may # want to use a small, lightweight editor here. # For Emacs users, setting up your Emacs server properly as described in the # manual is a good idea. An alternative is to use jed, a very light editor # with much of the feel of Emacs (though not as powerful for heavy-duty work). editor nedit }}} = Was ist ein Programm? = == Interpreter versus Compiler == Quellcode -> Interpreter -> Ergebnis Quellcode -> Compiler -> Objectcode -> Ausführung -> Ergebnis == Programmablauf == Eingabe, Ausgabe, Algorithmus == Debugging/Fehlersuche == Syntaxfehler: Formale Struktur des Programms Laufzeitfehler: Fehler und Ausnahmen, die während des Ablaufs auftreten Semantische Fehler: Formal korrektes Programm, welches zu falschem Ergebnis führt Debugging ist Detektivarbeit und eine eigene Wissenschaft für sich. Durch Experimente können Fehler gefunden werden. Es muss eine Idee (Hypothese) über die Fehlerquelle vorhanden sein, die durch den Programmablauf getestet wird. Verschiende Werkzeuge können das Debugging erleichern. Eine vielbenutzte einfache Methode ist die Print Anweisung um Variablen zu überwachen. = Variablen, Ausdrücke, Anweisungen, Operatoren, Kommentare = == Werte und Typen == Werte (z.B. 1) sind verschiedenen Typen zugeordnet {{{#!python In [32]: type(1) Out[32]: <type 'int'> In [33]: type(1.0) Out[33]: <type 'float'> In [34]: type('Hallo') Out[34]: <type 'str'> }}} == Variablen == Variablen sind Namen, zu denen ein Wert gehört {{{#!python In [51]: a=1 In [52]: s='Zeichenkette' In [53]: a Out[53]: 1 In [54]: s Out[54]: 'Zeichenkette' In [55]: type(a) Out[55]: <type 'int'> In [56]: type(s) Out[56]: <type 'str'> }}} Über den Zustand der Variablen kann man sich mit dem IPython Kommando %who bzw. %whos informieren. {{{#!python In [57]: %whos Variable Type Data/Info ---------------------------- a int 1 s str Zeichenkette }}} == Erlaubte Namen == Variablennamen sollten sinnvoll vergeben werden. Die Länge ist unbegrenzt und es können Buchstaben und Zahlen verwendet werden. Am Anfang darf jedoch keine Zahl stehen. Als Sonderzeichen ist der Unterstrich erlaubt. Illegale Namen führen zu Syntaxfehlern: {{{#!python In [59]: 5a=1 ------------------------------------------------------------ File "<ipython console>", line 1 5a=1 ^ SyntaxError: invalid syntax }}} Python Keywords dürfen nicht als Variablennamen verwendet werden. Reservierte Keywords sind: {{{#!python and else import raise assert except in return break exec is try class finally lambda while continue for not yield def from or del global pass elif if print }}} |
* http://www.python.org/doc/ *[[http://37mm.no/mpy/idl-numpy.html|NumPy for IDL users]] *[[http://www.scipy.org/NumPy_for_Matlab_Users|NumPy for Matlab users]] |
Line 167: | Line 37: |
== Anweisung (Statements) == Eine Anweisung ist ein Befehl, den der Python Interpreter ausführen kann, z.B. eine Print-Anweisung oder Variablen-Zuweisung |
== Modules == |
Line 170: | Line 39: |
{{{#!python In [60]: s='Welt' In [61]: print 'Hallo '+s Hallo Welt }}} == Operaturen == Operatoren sind spezielle Symbole für Rechenanweisungen * + Plus * - Minus * * Multiplikation * / Division * ** Exp. Das Plus Zeichen kann im Zusammenhang mit Strings als Operator verwendet werden, um diese zu verbinden. {{{#!python In [63]: a='Aller Anfang ' In [64]: b='ist schwer' In [65]: a+b Out[65]: 'Aller Anfang ist schwer' }}} == Ausdrücke (Expressions) == Ein Ausdruck ist eine Kombination von Variablen, Werten und Operatoren. Der Interpreter evaluiert den Ausruck. {{{#!python In [62]: 1+1 Out[62]: 2 }}} == Kommentare == Kommentare helfen ein Programm zu verstehen. Sie werden durch ein Doppelkreuz (#) eingeleitet = Funktionen = Eine Funktion ist eine Reihe von Anweisungen um eine Rechenoperation durchzuführen. Eine Funktion wird durch einen Namen spezifiziert (erlaubte Namen wie bei Variablen). Nach der Definition kann die Funktion durch den Namen aufgerufen werden. {{{#!python In [9]: type(1) Out[9]: <type 'int'> }}} Dies ist ein Beispiel für eine eingebaute Funktion (Übersicht http://docs.python.org/lib/built-in-funcs.html). Der Name der Funktion ist '''type'''. In Klammern wird der Funktion ein Argument (1) übergeben. Die Funktion liefert einen Rückgabewert (int) zurück. == Typumwandlungsfunktionen == {{{#!python In [12]: int(2.3) Out[12]: 2 In [13]: float(2) Out[13]: 2.0 In [14]: 1/2 Out[14]: 0 In [15]: 1/float(2) Out[15]: 0.5 In [16]: str(1) Out[16]: '1' }}} == Hinzufügen neuer Funktionen == Das Hinzufügen neuer Funktionen geschieht durch eine Deklaration (Definition). Dabei ist die Python Symtax der Einrückungen wichtig. Die Einrückungen definieren den Gültigkeitsbereich der Funktion. Quellcode '''einfache_funktion.py''' {{{#!python def summe(a,b): c=a+b return c a=1 b=2 print summe(a,b) }}} {{{#!python In [17]: %edit einfache_funktion.py Editing... done. Executing edited code... 3 In [18]: run einfache_funktion.py 3 In [19]: summe(4,5) Out[19]: 9 }}} Das Beispiel enthält nicht nur eine Funktion sondern auch ein Hauptprogramm, welches die Funktion aufruft. Nach dem Editieren wird dieser Teil sofort ausgeführt. == Dokumentation == Gute Dokumentation ist wichtig! Funktionen können durch '''docstrings''' ergänzt werden {{{#!python def summe(a,b): """Berechne die Summe aus a und b""" c=a+b return c a=1 b=2 print summe(a,b) }}} Ruft man nun die Hilfefunktion auf, dann bekommt man eine Auskunft über das Interface: {{{#!python In [27]: help(summe) Help on function summe in module __main__: summe(a, b) Berechne die Summe aus a und b }}} = Module = Module sind Sammlungen von Funktionen und erweitern den sehr minimalen Sprachumfang von Python um neue Funktionen. Eine Liste der verfügbaren Module erhält man durch die Hilfe-Funktion: {{{#!python In [3]: help() help> modules ArgImagePlugin WalImageFile ftplib pygtk ArrayPrinter WmfImagePlugin gc pylab .. UserString fpformat pyexpat zonetab2pot }}} Um ein Modul zu nutzen muss es zunächst '''importiert''' werden: {{{#!python import scipy }}} Jetzt können die Funktionen des Moduls '''scipy''' genutzt werden. Mit '''scipy''' erhält Python mathematische Fähigkeiten ähnlich wie IDL und MATLAB. {{{#!python In [9]: a=scipy.array([1,2,3,4,5]) In [10]: b=scipy.array([1,2,3,4,5]) In [11]: a+b Out[11]: array([ 2, 4, 6, 8, 10]) }}} Es gibt verschiedene Möglichkeiten Module zu importieren. Davon hängt ab, in welchem '''Namensraum''' das Modul erreichbar ist {{{#!python import scipy as sp }}} {{{#!python In [9]: a=sp.array([1,2,3,4,5]) In [10]: b=sp.array([1,2,3,4,5]) In [11]: a+b Out[11]: array([ 2, 4, 6, 8, 10]) }}} Durch die Möglichkeit das Modul in den Wurzelnamensraum zu importieren {{{#!python from scipy import * }}} spart man sich einige Schreibarbeit {{{#!python In [9]: a=array([1,2,3,4,5]) In [10]: b=array([1,2,3,4,5]) In [11]: a+b Out[11]: array([ 2, 4, 6, 8, 10]) }}} jedoch besteht die Möglichkeit von Konflikten falls noch weitere Module mit Funktionen gleichen Namens importiert werden. === scipy === http://www.scipy.org/ Das Modul '''scipy''' beinhaltet eine Reihe von Submodulen für eine Vielzahl von wissenschaftlichen Anwendungen {{{#!python import scipy help(scipy) ndimage --- n-dimensional image package [*] stats --- Statistical Functions [*] io --- Data input and output [*] lib --- Python wrappers to external libraries [*] linalg --- Linear algebra routines [*] linsolve.umfpack --- Interface to the UMFPACK library. [*] signal --- Signal Processing Tools [*] misc --- Various utilities that don't have another home. interpolate --- Interpolation Tools [*] lib.lapack --- Wrappers to LAPACK library [*] cluster --- Vector Quantization / Kmeans [*] linsolve --- Linear Solvers [*] fftpack --- Discrete Fourier Transform algorithms [*] sparse --- Sparse matrix [*] maxentropy --- Routines for fitting maximum entropy models [*] integrate --- Integration routines [*] optimize --- Optimization Tools [*] special --- Special Functions [*] lib.blas --- Wrappers to BLAS library [*] [*] - using a package requires explicit import (see pkgload) }}} Scipy baut auf dem Modul Numpy auf, welches optimierte Matrixoperationen bereitstellt. Der Umstieg von IDL und MATLAB auf scipy/numpy fällt mit diesen Kurzanleitungen besonders leicht: [http://37mm.no/mpy/idl-numpy.html NumPy for IDL users] [http://www.scipy.org/NumPy_for_Matlab_Users NumPy for Matlab users] |
=== SciPy/NumPy === * http://www.scipy.org/ |
Line 391: | Line 43: |
http://matplotlib.sourceforge.net/ | * [[http://matplotlib.sourceforge.net/|Matplotlib/pylab]] Plotting functions with a high degree of Matlab compatibility === GDAL === * [[http://www.gdal.org/|GDAL - Geospatial Data Abstraction Library]] for various satellite data formats |
Line 393: | Line 47: |
Pylab (matplotlib) reichert Python um die Fähigkeiten zur graphischen Ausgabe an, die im grossen Umfang mit Matlab kompatibel ist. | === PyNGL === * [[http://www.pyngl.ucar.edu/|PyNGL/PyNIO]] Python interface to [[http://www.ncl.ucar.edu/ | NCAR Command Language]] * Scientific visualization and data formats (netCDF, HDF, GRIB etc.) |
Line 395: | Line 51: |
Um ein gutes interaktives Arbeiten mit diesem Modul zu ermöglichen, muss der Interpreter mit besonderer Option gestartet werden: '''ipython -pylab''' === GDAL === [http://www.gdal.org/ GDAL - Geospatial Data Abstraction Library] = Weiterführende Information = http://www.greenteapress.com/thinkpython/ |
To enable PyNGL (on ZMAW Linux ia32/x64 and solaris10) you have to type {{{ module load PyNGL/1.2.0 }}} |
Programming Python
Lesson 1 - Introduction
SiaProgrammingPythonIntroduction
SiaProgrammingPythonBasicPython
Lesson 2 - Data types, structures and functions
Lesson 3 - System, IO
Documentation
Modules
SciPy/NumPy
pylab
Matplotlib/pylab Plotting functions with a high degree of Matlab compatibility
GDAL
GDAL - Geospatial Data Abstraction Library for various satellite data formats
PyNGL
PyNGL/PyNIO Python interface to NCAR Command Language
- Scientific visualization and data formats (netCDF, HDF, GRIB etc.)
To enable PyNGL (on ZMAW Linux ia32/x64 and solaris10) you have to type
module load PyNGL/1.2.0