python for scientists
DESCRIPTION
This is a presentation about using the programming language Python in science and research.TRANSCRIPT
Python for Scientists
A. DewesQuantronics Group Seminar
Python: Qu'est-ce que c'est?
A high-level programming
language …… with a simple &
easy to learn syntax… … a huge
standard library … … and packages for
mathematics, data processing, UI
design …
print “Easy as…“for i in [1,2,3]: print i
Matplotlib,SciPy,NumPy,PyQT,…
ctypes,sockets,files,regex,…
Multi-paradigm (object oriented, functional…)
Why to use it: A Scientific Workflow
Experiment(Re-)Design
DataAcquisition
DataAnalysis
Presentation & Visualization
Software makes life easier…
Experiment(Re-)Design
Data Acquisition
Labview, TestPoint, C++
Data Analysis
Mathlab, Mathematica
Presentation & Visualization
Origin, …
Experiment(Re-)Design
Data Acquisition
PyVisa, ctypes, …
Data Analysis
NumPy, SciPy, …
Presentation & Visualization
Mathplotlib, PyQt, …
Using Python…
Data Acquisition
PyVisa•Wrapper library for NI-Visa
interface•Allows to easily control
instruments via GPIB, VXI, TCP/IP...
ctypes•Library for calling C DLL
functions•Allows to control all kinds of
external libraries (e.g. Acqiris card)
http://pyvisa.sourceforge.net http://docs.python.org/library/ctypes.html
PyVisa Example: MWG & VNA
Keypoints•Clear, object-oriented interface•Directly process & analyze measured data•Fast, flexible programming•Not too much worrying about technical details…•VNA example uses PyQt for the user interface
from visa import *#Open a connection to an Anritsu MWGanritsu = instrument(“GPIB0::12“)#Ask for the output frequencyprint anritsu.ask(“OF1“)#Set the output poweranritsu.write(“L15DM“)#Turn on the microwaveanritsu.write(“RF0“)
VNA Frontpanel
vna = instrument(„GPIB0::15“)x = vna.ask_for_values(“fma;ofv;“)y = vna.ask_for_values(“fma;ofd;“)
ctypes Example: Taming an Acqiris card
from pylab import *;from ctypes import *
vi_session = c_uint32()temperature = c_int32() time_us = c_int32() timestamp = c_int32() nsegments_returned = c_int32()npoints_returned = c_int32()
acqiris = windll.LoadLibrary(r‘C:\projects\python\pylab\instruments\dllAcqiris.dll‘)acqiris.FindDevicesV1(byref(vi_session),byref(temperature))
#Configuration...
acqiris.AcquireV1(vi_session,1,byref(time_us))
waveforms = zeros((4,250 *100))
acqiris.DMATransferV1(vi_session,15,100,250,0,1,4e-9, byref(timestamp),waveforms[0,:].ctypes.data,waveforms[1,:].ctypes.data,waveforms[2,:].ctypes.data,waveforms[3,:].ctypes.data,byref(time_us),byref(nsegments_returned),byref(npoints_returned))
#Waveform data now is stored in „waveforms“ array and can be processed, e.g. apply FFT & plot:plot(range(len(waveforms[0,:])),fft(waveforms[0,:]))
Objective: Load the external DLL, transfer some measurement data and process it on the fly.
Data Analysis
SciPy•Free collection of algorithms
and tools•Tools for optimization, (fast)
linear algebra, signal processing, …
NumPy•High-level interface for
handling large arrays & matrices
•Based on highly optimized & fast C code
http://www.scipy.org http://numpy.scipy.org
SciPy & NumPy Exampleimport scipy.optimize
#Define the model to be fittedfitfunc = lambda p, x: p[0]+p[1]*
exp(-x*abs(p[2]))*cos(p[3]+p[4]*x)
#Define the error functionerrfunc = lambda p, x, y: fitfunc(p, x) – y
#Make a fit by minimizing the error functionp1 = scipy.optimize.fmin(lambda p,x,y: norm(errfunc(p,x,y)), p0, args=(data [:,0], data[:,1]))
#Print the returned parametersprint p1
#Plot the data and the fit…plot(data[:,0], data[:,1], "ro", data[:,0],
fitfunc(p1, data[:,0]), "b-")
#Add a legendlegend(("data","fit"))
#Add a titletitle("Ramsey - $V_{fluxline}= %d mV$,
$T_2 = %d$ ns, $A = %f$ " % (int(voltage) , abs(int(1.0/p1[2])),p1[1]))
Presentation & VisualizationMathplotlib•Easy to use, powerful
plotting library•Generates publication quality
output•Mathlab-like interface
PyQT•Free-to-use, cross-platform
user interface development kit
•Easy to learn, flexible and versatile
http://matplotlib.sourceforge.net/ http://qt.nokia.com/
Matplotlib Examplesgrid() #Add grid lines to the plot#Plot 4 datasetsplot(x1,y1,x2,y2,x3,y3,x4,y4)#Add a legend
legend((“Amplification …“,“…“))
#Set the axis labelsxlabel(“frequency [GHz]“)ylabel(“attenuation [dB]“)
#Save the figure as a PDFsavefig(“attenuation.pdf“)
jet() #Select a color sheme
#Plot the matriximshow(dataMatrix ,aspect = 'auto',origin = 'lower',extent = (xmin,xmax,ymin,ymax))
xlabel("$A$ [V]")ylabel("$f$ [GHz]")
#Use Latex for text…title("Qubit 1 – Modulated by $V_{flux2} = A \cdot \sin{(20 MHz \cdot 2\pi t)}$")
Some more examples…
PyQT Example: Instrument frontpanelstitle = QLabel(„Qubit 1") splitter = QSplitter(Qt.Horizontal)
SetButton = QPushButton("Set") splitter.addWidget(SetButton)
#... grid = QGridLayout(self)grid.addWidget(title,0,0)grid.addWidget(QLabel("Voltage"),1,0)#...self.connect(SetButton,SIGNAL("clicked()"),self.changeVoltage) self.setLayout(grid)
Or useQt Designer:
How To Get Started1. Download it…
http://www.python.org http://docs.python.org/tutorial/ http://wiki-quantro.extra.cea.fr
2. Check out the documentation & tutorial (online)3. Go &contribute to the Wiki
4. Ask your colleagues…
That‘s it.
Object Hirarchy Example
Instrument
RemoteInstrument VisaInstrument
VNA AgilentMWG YokogawaAcqiris
Dispatcher SubjectReloadable
ThreadedDispatcher