code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
import pygame, sys, threading
from pygame import font as pf
from pygame.locals import *
from vec2d import *
from math import sqrt, e, log
from random import uniform, normalvariate
from threading import Thread
#import psyco
#single node
class node:
def __init__(self, x, text="tag"):
self.x = x #position
self.oldx = x #old position
self.a = 0 #force accumulators
# Tag information
self.text = text
self.weight = int(round(uniform(0,100)))
self.marked= False #for bfs
self.color = (int(uniform(0,150)), int(uniform(0,150)), int(uniform(0,150)))
self.numNodes=0 #num of nodes this is connected to. filled in countNodes()
#single spring
class spring:
def __init__(self, n1, n2, k = -40, restDist = 200):
self.n1 = n1
self.n2 = n2
self.k = k
self.rest = restDist
#main class
class graphMain(Thread):
def __init__(self):
Thread.__init__(self)
self.running = True
self.nodeGetter = None
self.nodeLock = threading._allocate_lock()
self.updateLock = threading._allocate_lock()
self.topN = []
self.w = 1200
self.h = 700
pygame.init()
self.screen = pygame.display.set_mode((self.w, self.h))
self.screen.fill((0,0,0))
#PHYSICS
self.dt = 0.01 #time step
self.friction = 0.05
#lists of nodes and springs
self.nodes = {}
self.springs = []
self.dragging = None #is user dragging a node?
self.selected = None #selected node
self.physics = True #is physics enabled?
self.c = 0 #program counter used in main loop
self.tinyFont = pf.Font(None,20)
self.smallFont = pf.Font(None,30)
self.mediumFont = pf.Font(None,40)
self.largeFont = pf.Font(None,60)
#returns the top N tags
def getTopN(self, number):
topN = []
with self.nodeLock:
l = self.nodes.values()
l.sort(lambda a, b: cmp(a.weight, b.weight), reverse=True)
for i in range(0, min(number, len(l))):
topN.append(l[i])
return topN
#integrate one single time step to get new positions
#from old positions based on acceleration of each node.
def verlet(self):
for n in self.topN:
temp = vec2d(n.x.x, n.x.y) #store old position
# cap movement speed
n.a.length = min(n.a.length, 2500)
n.x += (1.0 - self.friction)*n.x - (1.0 - self.friction)*n.oldx + n.a*self.dt*self.dt
n.oldx = temp
for n in self.topN: #reset accelerations for next iteration
n.a = vec2d(0,0)
#accumulate all the forces between all the nodes
def accumulate_force(self):
#REPELL NODES CLOSE TO OTHER NODES
#proportional to their separation in graph
#Nodes are close => big repulsion
#Nodes are far => no repulsion
for n1 in self.topN:
for n2 in self.topN:
dst =n1.x.get_distance(n2.x) #distance on actual layout
if dst > 0.0005:
dp = n2.x - n1.x #get vector from n1->n2
x0 = 0
x1 = 300
x = dst
f1 = 100000/(0.001*x*x*x)
f0 = 100000/(0.00001*x)*min(3000, n2.weight*n1.weight)
dp.length = f0 + (f1 - f0)/(x1 - x0)*(x-x0) #set its length to strength of interaction
n2.a += dp #add that vector to both acceleration of n1 and n2
n1.a += -dp
# slightly drag to center of the screen. nodes with higher weight are dragged more
center = vec2d(self.w/2,self.h/2)
dst = center.get_distance(n1.x)
if dst > 0.0005:
dc = center - n1.x #get vector from n1->center
dc.length = 0.01*dst*dst*n1.weight*n1.weight*n1.weight*n1.weight
#set its length to strength of interaction
n1.a += dc #add that vector to both acceleration of n1 and n2
#SPRING STUFF
for s in self.springs:
dp = s.n2.x - s.n1.x #get vector pointing from n1->n2
if dp.length != 0:
dx = dp.length - s.rest #get the displacement from rest length
dp.length = s.k*dx #multiply by spring contant
s.n2.a += dp #add the vector to each n1 and n2 accelerations
s.n1.a += -dp
#return the net movement of all nodes.
#if there is very little movement then the simulation
#can be stopped and result returned
def netMovement(self):
a=0.0
for n in self.topN:
a+= (n.x - n.oldx).length
return a
# removes nodes which have lost too much weight
def removeDead(self):
toRem = []
deleted = False
with self.nodeLock:
for n in self.nodes.values():
if n.weight < 0:
for s in self.springs:
if s.n1 == n or s.n2 == n:
toRem.append(s)
self.nodes.pop(n.text)
deleted = True
if deleted:
for t in toRem:
self.springs.remove(t)
self.doBFS()
self.doCount()
#handle all user input and interactivity
def handle_input(self):
for event in pygame.event.get():
if event.type == QUIT:
self.quit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.quit()
elif event.key == K_r:
self.initNodes()
self.doBFS()
self.doCount()
elif event.key == K_d:
#delete closest node
d = self.findclosest(pygame.mouse.get_pos())
toRem = []
for s in self.springs:
if s.n1 == d or s.n2 == d:
toRem.append(s)
for t in toRem:
self.springs.remove(t)
self.nodes.pop(d.text)
self.doBFS()
self.doCount()
elif event.key == K_p:
self.physics = not self.physics
elif event.key == K_n:
with self.nodeLock:
for z in self.nodes.values():
z.x = vec2d(uniform(self.w/2-10,self.w/2+10), uniform(self.h/2-10,self.h/2+10))
z.oldx = z.x
elif event.type == MOUSEBUTTONUP:
if event.button == 1:
self.dragging = None
else:
now = vec2d(event.pos)
then = vec2d(self.selected)
if now.get_distance(then) < 10:
#just make a new node here (at now)
#self.nodes["tag%s%s",now] = node(now)
#self.doBFS()
#self.doCount()
pass
else:
#make new line btw last node and this node
#nowNode=self.findclosest(now)
#thenNode=self.findclosest(then)
#self.springs.append(spring(nowNode, thenNode))
#self.doBFS()
#self.doCount()
pass
self.selected = None
elif event.type == MOUSEBUTTONDOWN:
if event.button == 1:
self.dragging = self.findclosest(event.pos)
else:
self.selected = event.pos
#find the closest node to position p. p is a vec2d
def findclosest(self, p):
ld = self.w + self.h
li = None
v = vec2d(p)
for n in self.topN:
d = v.get_distance(n.x)
if d < ld:
ld = d
li = n
return li
#draw all springs and nodes
def draw(self):
self.screen.fill((255,255,255))
# edges
for s in self.springs:
pygame.draw.aaline(self.screen, (200,200,200), s.n1.x.inttup(), s.n2.x.inttup(), 1)
#with self.nodeLock:
# topN = self.topN
for n in self.topN:
# determine font size by node weight
if (n.weight < 25):
font = self.tinyFont
elif(n.weight <50):
font = self.smallFont
elif(n.weight <75):
font = self.mediumFont
else:
font = self.largeFont
#pygame.draw.circle(self.screen, n.color, n.x.inttup(), 10)
# text="(%s|%s)" % (x,y)
text = "%s" % n.text
fontFace = font.render(text, False, (0,0,0))
tW, tH = font.size(text)
rW = tW+10
rH = tH+5
rA = n.x.inttup()[0]-rW/2
rB = n.x.inttup()[1]-rH/2
tA = n.x.inttup()[0]-tW/2
tB = n.x.inttup()[1]-tH/2
pygame.draw.rect(self.screen, (255,255,255), (rA,rB,rW,rH))
pygame.draw.rect(self.screen, (0,0,0), (rA,rB,rW,rH), 1)
self.screen.blit(fontFace,(tA,tB))
pygame.display.flip()
#true if there is no spring yet between the k'th and l'th node
def dnc(self, k, l):
i=self.nodes.values()[k]
j=self.nodes.values()[l]
for s in self.springs:
if (s.n1==i and s.n2==j) or (s.n1==j and s.n2==i):
return False
return True
#initialize all the nodes and springs
def initNodes(self):
self.nodes={}
self.springs=[]
self.c = 0
#do a BFS search to create the dictionary containing the length of the
#shortest path between any two nodes in the graph, along springs
def doBFS(self):
#construct the initial dict
self.paths={}
for n in self.nodes.values():
for n2 in self.nodes.values():
if n == n2:
self.paths[(n,n2)] = 0
else:
self.paths[(n,n2)] = 10 #10 if they arent connected
#now run BFS on each node to find the right values and fill them in
for n in self.nodes.values():
lst=[n]
d=1
for n2 in self.nodes.values(): #reset nodes
n2.marked = False
while len(lst) > 0:
nn = lst[0]
del lst[0]
nn.marked = True
for s in self.springs:
n2 = None
if s.n1 == nn:
n2 = s.n2
elif s.n2 == nn:
n2 = s.n1
if n2 != None and n2.marked == False:
#nn is part of this spring
#we found n2 in depth d from n
self.paths[(n,n2)] = min(d, self.paths[(n,n2)])
self.paths[(n2,n)]= min(d, self.paths[(n2,n)])
n2.color = nn.color
#append n2 to the lst
lst.append(n2)
d+=1 #increment depth
#count number of connections for each node
#return the highest number of connections of any node
def doCount(self):
maxN = 0
for n in self.topN:
k=0
for s in self.springs:
if s.n1 == n or s.n2 == n:
k+=1
n.numNodes=k/2 #k/2 because graph is undirected. nodes are doublecounted
if k/2 > maxN:
maxN = k/2
#now set the spring constants appropriately
for s in self.springs:
n=max(s.n1.numNodes, s.n2.numNodes)
#s.rest=50+n*10
return maxN
def updateNodes(self, newNodes=[]):
with self.updateLock:
for new in newNodes:
try:
with self.nodeLock:
self.nodes[new[0]].weight += new[1]
except:
# print "!!! creating new node for tag: %s, %s" % (new[0], new[1])
# create new node
z=node(vec2d(uniform(self.w/2-100,self.w/2+100), uniform(self.h/2-100,self.h/2+100)))
z.text = new[0]
z.weight = new[1]
with self.nodeLock:
self.nodes[z.text] = z
#main method. do the simulation
def run(self):
#initialize the particle system
with self.nodeLock:
self.initNodes()
self.doBFS()
self.doCount()
try:
self.nodeGetter.start()
except:
print "No nodeGetter could be started."
while self.running:
self.c +=1
# update topN every 100 frames
if self.c % 100 == 0:
# recalculate topN
topN = self.getTopN(20)
with self.nodeLock:
self.topN = topN
#if physics is enabled then do simulation
if self.physics:
with self.nodeLock:
self.accumulate_force()
self.verlet()
self.handle_input() #handle all user input
#handle node dragging
if not self.dragging == None:
pos = pygame.mouse.get_pos()
self.dragging.x = vec2d(pos)
self.dragging.oldx = vec2d(pos)
#draw everything
self.draw()
def quit(self):
self.running = False
self.nodeGetter.stop()
sys.exit() | Python |
"""
This code is currently broken
small changes are required to adapt it to the new pulsed measurements (without hardware API).
See rabi.py as example.
"""
class T1( PulsedTau ):
"""Defines a T1 measurement."""
laser = Range(low=1., high=100000., value=3000., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True)
def generate_sequence(self):
tau = self.tau
laser = self.laser
sequence = [ (['aom'],laser) ]
for t in tau:
sequence += [ ([],t), (['detect','aom'],laser) ]
sequence += [ ([],1000) ]
sequence += [ (['sequence'],100) ]
return sequence
get_set_items = PulsedTau.get_set_items + ['laser']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time'),
),
Tabbed(VGroup(HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='parameter'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'),
),
),
title='T1 Measurement',
)
class SingletDecay( Pulsed ):
"""Singlet Decay."""
laser = Range(low=1., high=100000., value=3000., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True)
tau_begin = Range(low=0., high=1e8, value=0., desc='tau begin [ns]', label='tau begin [ns]', mode='text', auto_set=False, enter_set=True)
tau_end = Range(low=1., high=1e8, value=300., desc='tau end [ns]', label='tau end [ns]', mode='text', auto_set=False, enter_set=True)
tau_delta = Range(low=1., high=1e6, value=3., desc='delta tau [ns]', label='delta tau [ns]', mode='text', auto_set=False, enter_set=True)
tau = Array( value=np.array((0.,1.)) )
def apply_parameters(self):
"""Overwrites apply_parameters() from pulsed. Prior to generating sequence, etc., generate the tau mesh."""
self.tau = np.arange(self.tau_begin, self.tau_end, self.tau_delta)
Pulsed.apply_parameters(self)
def start_up(self):
PulseGenerator().Night()
def shut_down(self):
PulseGenerator().Light()
def generate_sequence(self):
tau = self.tau
laser = self.laser
sequence = [ (['sequence'],100) ]
for t in tau:
sequence += [ ([],t), (['detect','aom'],laser) ]
return sequence
get_set_items = Pulsed.get_set_items + ['tau_begin','tau_end','tau_delta','laser','tau']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
),
Tabbed(VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
Item('stop_time'),),
label='manipulation'),
VGroup(HGroup(Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='detection'
),
),
),
title='Singlet decay',
)
class SingletDecayDouble( PulsedTau ):
"""Singlet Decay."""
laser = Range(low=1., high=100000., value=3000., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True)
def start_up(self):
PulseGenerator().Night()
def shut_down(self):
PulseGenerator().Light()
def generate_sequence(self):
tau = self.tau
laser = self.laser
sequence = [ (['sequence'],100) ]
for t in tau:
sequence += [ ([],t), (['detect','aom'],laser) ]
for t in tau[::-1]:
sequence += [ ([],t), (['detect','aom'],laser) ]
return sequence
get_set_items = Pulsed.get_set_items + ['tau_begin','tau_end','tau_delta','laser','tau']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time'),
),
Tabbed(VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='manipulation'),
VGroup(HGroup(Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='detection'
),
),
),
title='Singlet decay double',
)
class T1pi( Rabi ):
"""Defines a T1 measurement with pi pulse."""
t_pi = Range(low=1., high=100000., value=1000., desc='pi pulse length', label='pi [ns]', mode='text', auto_set=False, enter_set=True)
def generate_sequence(self):
tau = self.tau
laser = self.laser
wait = self.wait
t_pi = self.t_pi
sequence = []
for t in tau:
sequence.append( ([ ], t ) )
sequence.append( (['detect','aom'], laser ) )
sequence.append( ([ ], wait ) )
for t in tau:
sequence.append( (['mw' ], t_pi ) )
sequence.append( ([ ], t ) )
sequence.append( (['detect','aom'], laser ) )
sequence.append( ([ ], wait ) )
sequence.append( (['sequence'], 100 ) )
return sequence
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time'),
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),
Item('t_pi', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='parameter'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'),
),
),
title='T1pi',
)
get_set_items = Rabi.get_set_items + ['t_pi']
class T1Meta( Rabi ):
"""T1 measurement of metastable state."""
t_pi = Range(low=0., high=100000., value=1000., desc='pi pulse length', label='pi [ns]', mode='text', auto_set=False, enter_set=True)
delay = Range(low=0., high=1000., value=450., desc='delay of AOM relative to trigger', label='AOM delay [ns]', mode='text', auto_set=False, enter_set=True)
def generate_sequence(self):
tau = self.tau
laser = self.laser
wait = self.wait
t_pi = self.t_pi
delay = self.delay
s1 = []
s2 = []
s2.append( ([], delay+wait ) )
for t in tau:
s1.append( ([ ], wait + t_pi + t ) )
s1.append( (['detect','aom'], laser ) )
s2.append( (['mw' ], t_pi ) )
s2.append( ([ ], t+laser+wait ) )
s1.append( ([ ], 1000 ) )
s1.append( (['sequence'], 100 ) )
s2.pop()
"""
s1.append( (['aom'], laser ) )
s2.append( ([], delay+laser+wait ) )
for t in tau:
s1.append( ([ ], wait + t_pi + t ) )
s1.append( (['detect','aom'], laser ) )
s2.append( (['mw' ], t_pi ) )
s2.append( ([ ], t+laser+wait ) )
s1.append( ([ ], 1000 ) )
s1.append( (['sequence'], 100 ) )
s2.pop()
"""
return sequence_union(s1,s2)
get_set_items = Rabi.get_set_items + ['t_pi','delay']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time'),
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),
Item('t_pi', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='parameter'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('delay', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'),
),
),
title='T1Meta',
)
| Python |
import numpy
import threading
import time
import logging
from traits.api import HasTraits, Trait, Instance, Property, Float, Range,\
Bool, Array, String, Str, Enum, Button, on_trait_change, cached_property, DelegatesTo
from traitsui.api import View, Item, Group, HGroup, VGroup, Tabbed, EnumEditor, TextEditor, Action, Menu, MenuBar
from enable.api import ComponentEditor, Component
from chaco.api import CMapImagePlot, ArrayPlotData, DataRange1D,\
Spectral, ColorBar, LinearMapper, DataLabel, PlotLabel
import chaco.api
from chaco.tools.cursor_tool import CursorTool2D
from tools.emod import ManagedJob
#customized zoom tool to keep aspect ratio #
from tools.chaco_addons import SavePlot as Plot, SaveHPlotContainer as HPlotContainer, SaveTool, AspectZoomTool
from tools.utility import GetSetItemsMixin, GetSettableHistory as History
class Confocal( ManagedJob, GetSetItemsMixin ):
resolution = Range(low=1, high=1000, value=100, desc='Number of point in long direction', label='resolution', auto_set=False, enter_set=True)
seconds_per_point = Range(low=1e-3, high=10, value=0.005, desc='Seconds per point [s]', label='Seconds per point [s]', mode='text', auto_set=False, enter_set=True)
bidirectional = Bool( True )
return_speed = Range(low=1.0, high=100., value=10., desc='Multiplier for return speed of Scanner if mode is monodirectional', label='return speed', mode='text', auto_set=False, enter_set=True)
constant_axis = Enum('z', 'x', 'y',
label='constant axis',
desc='axis that is not scanned when acquiring an image',
editor=EnumEditor(values={'x':'1:x','y':'2:y','z':'3:z',},cols=3),)
# buttons
history_back = Button(label='Back')
history_forward = Button(label='Forward')
reset_range = Button(label='reset range')
reset_cursor = Button(label='reset position')
# plot parameters
thresh_high = Trait( 'auto', Str('auto'), Float(10000.), desc='High Limit of image plot', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float))
thresh_low = Trait( 'auto', Str('auto'), Float(0.), desc='Low Limit of image plot', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float))
colormap = Enum('Spectral','gray')
show_labels = Bool(False)
# scan data
X = Array()
Y = Array()
image = Array()
# plots
plot_data = Instance( ArrayPlotData )
scan_plot = Instance( CMapImagePlot )
cursor = Instance( CursorTool2D )
zoom = Instance( AspectZoomTool )
figure = Instance( Plot )
figure_container = Instance( HPlotContainer, editor=ComponentEditor() )
z_label_text = Str('z:0.0')
cursor_position = Property(depends_on=['x','y','z','constant_axis'])
get_set_items=['constant_axis', 'X', 'Y', 'thresh_high', 'thresh_low', 'seconds_per_point',
'return_speed', 'bidirectional', 'history', 'image', 'z_label_text',
'resolution', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'z', 'z1', 'z2']
def __init__(self, scanner, **kwargs):
super(Confocal, self).__init__(**kwargs)
self.scanner = scanner
# scanner position
self.add_trait('x', Range(low=scanner.getXRange()[0], high=scanner.getXRange()[1], value=0.5*(scanner.getXRange()[0]+scanner.getXRange()[1]), desc='x [micron]', label='x [micron]', mode='slider'))
self.add_trait('y', Range(low=scanner.getYRange()[0], high=scanner.getYRange()[1], value=0.5*(scanner.getYRange()[0]+scanner.getYRange()[1]), desc='y [micron]', label='y [micron]', mode='slider'))
self.add_trait('z', Range(low=scanner.getZRange()[0], high=scanner.getZRange()[1], value=0.5*(scanner.getZRange()[0]+scanner.getZRange()[1]), desc='z [micron]', label='z [micron]', mode='slider'))
# imagging parameters
self.add_trait('x1', Range(low=scanner.getXRange()[0], high=scanner.getXRange()[1], value=scanner.getXRange()[0], desc='x1 [micron]', label='x1', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f')))
self.add_trait('y1', Range(low=scanner.getYRange()[0], high=scanner.getYRange()[1], value=scanner.getYRange()[0], desc='y1 [micron]', label='y1', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f')))
self.add_trait('z1', Range(low=scanner.getZRange()[0], high=scanner.getZRange()[1], value=scanner.getZRange()[0], desc='z1 [micron]', label='z1', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f')))
self.add_trait('x2', Range(low=scanner.getXRange()[0], high=scanner.getXRange()[1], value=scanner.getXRange()[1], desc='x2 [micron]', label='x2', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f')))
self.add_trait('y2', Range(low=scanner.getYRange()[0], high=scanner.getYRange()[1], value=scanner.getYRange()[1], desc='y2 [micron]', label='y2', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f')))
self.add_trait('z2', Range(low=scanner.getZRange()[0], high=scanner.getZRange()[1], value=scanner.getZRange()[1], desc='z2 [micron]', label='z2', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2f')))
self.X = numpy.linspace(scanner.getXRange()[0], scanner.getXRange()[-1], self.resolution+1)
self.Y = numpy.linspace(scanner.getYRange()[0], scanner.getYRange()[-1], self.resolution+1)
self.image = numpy.zeros((len(self.X), len(self.Y)))
self._create_plot()
self.figure.index_range.on_trait_change(self.update_axis_li, '_low_value', dispatch='ui')
self.figure.index_range.on_trait_change(self.update_axis_hi, '_high_value', dispatch='ui')
self.figure.value_range.on_trait_change(self.update_axis_lv, '_low_value', dispatch='ui')
self.figure.value_range.on_trait_change(self.update_axis_hv, '_high_value', dispatch='ui')
self.zoom.on_trait_change(self.check_zoom, 'box', dispatch='ui')
self.on_trait_change(self.set_mesh_and_aspect_ratio, 'X,Y', dispatch='ui')
self.on_trait_change(self.update_image_plot, 'image', dispatch='ui')
self.sync_trait('cursor_position', self.cursor, 'current_position')
self.sync_trait('thresh_high', self.scan_plot.value_range, 'high_setting')
self.sync_trait('thresh_low', self.scan_plot.value_range, 'low_setting')
self.on_trait_change(self.scan_plot.request_redraw, 'thresh_high', dispatch='ui')
self.on_trait_change(self.scan_plot.request_redraw, 'thresh_low', dispatch='ui')
self.history = History(length = 10)
self.history.put( self.copy_items(['constant_axis', 'X', 'Y', 'image', 'z_label_text', 'resolution'] ) )
self.labels = {}
self.label_list = []
# scanner position
@on_trait_change('x,y,z')
def _set_scanner_position(self):
if self.state != 'run':
self.scanner.setPosition(self.x, self.y, self.z)
@cached_property
def _get_cursor_position(self):
if self.constant_axis == 'x':
return self.z, self.y
elif self.constant_axis == 'y':
return self.x, self.z
elif self.constant_axis == 'z':
return self.x, self.y
def _set_cursor_position(self, position):
if self.constant_axis == 'x':
self.z, self.y = position
elif self.constant_axis == 'y':
self.x, self.z = position
elif self.constant_axis == 'z':
self.x, self.y = position
# image acquisition
def _run(self):
"""Acquire a scan"""
try:
self.state='run'
self.update_mesh()
X = self.X
Y = self.Y
XP = X[::-1]
self.image=numpy.zeros((len(Y),len(X)))
"""
if not self.bidirectional:
self.scanner.initImageScan(len(X), len(Y), self.seconds_per_point, return_speed=self.return_speed)
else:
self.scanner.initImageScan(len(X), len(Y), self.seconds_per_point, return_speed=None)
"""
for i,y in enumerate(Y):
if threading.current_thread().stop_request.isSet():
break
if i%2 != 0 and self.bidirectional:
XL = XP
else:
XL = X
YL = y * numpy.ones(X.shape)
if self.constant_axis == 'x':
const = self.x * numpy.ones(X.shape)
Line = numpy.vstack( (const, YL, XL) )
elif self.constant_axis == 'y':
const = self.y * numpy.ones(X.shape)
Line = numpy.vstack( (XL, const, YL) )
elif self.constant_axis == 'z':
const = self.z * numpy.ones(X.shape)
Line = numpy.vstack( (XL, YL, const) )
if self.bidirectional:
c = self.scanner.scanLine(Line, self.seconds_per_point)
else:
c = self.scanner.scanLine(Line, self.seconds_per_point, return_speed=self.return_speed)
if i%2 != 0 and self.bidirectional:
self.image[i,:] = c[-1::-1]
else:
self.image[i,:] = c[:]
"""
self.scanner.doImageLine(Line)
self.image = self.scanner.getImage()
"""
self.trait_property_changed('image', self.image)
if self.constant_axis == 'x':
self.z_label_text='x:%.2f'%self.x
elif self.constant_axis == 'y':
self.z_label_text='y:%.2f'%self.y
elif self.constant_axis == 'z':
self.z_label_text='z:%.2f'%self.z
"""
# block at the end until the image is ready
if not threading.current_thread().stop_request.isSet():
self.image = self.scanner.getImage(1)
self._image_changed()
"""
self.scanner.setPosition(self.x, self.y, self.z)
#save scan data to history
self.history.put( self.copy_items(['constant_axis', 'X', 'Y', 'image', 'z_label_text', 'resolution'] ) )
finally:
self.state = 'idle'
# plotting
def _create_plot(self):
plot_data = ArrayPlotData(image=self.image)
plot = Plot(plot_data, width=500, height=500, resizable='hv', aspect_ratio=1.0, padding=8, padding_left=32, padding_bottom=32)
plot.img_plot('image', colormap=Spectral, xbounds=(self.X[0],self.X[-1]), ybounds=(self.Y[0],self.Y[-1]), name='image')
image = plot.plots['image'][0]
image.x_mapper.domain_limits = (self.scanner.getXRange()[0],self.scanner.getXRange()[1])
image.y_mapper.domain_limits = (self.scanner.getYRange()[0],self.scanner.getYRange()[1])
zoom = AspectZoomTool(image, enable_wheel=False)
cursor = CursorTool2D(image, drag_button='left', color='blue', marker_size=1.0, line_width=1.0 )
image.overlays.append(cursor)
image.overlays.append(zoom)
colormap = image.color_mapper
colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
color_mapper=colormap,
plot=plot,
orientation='v',
resizable='v',
width=16,
height=320,
padding=8,
padding_left=32)
container = HPlotContainer()
container.add(plot)
container.add(colorbar)
z_label = PlotLabel(text='z=0.0', color='red', hjustify='left', vjustify='bottom', position=[10,10])
container.overlays.append(z_label)
container.tools.append(SaveTool(container))
self.plot_data = plot_data
self.scan_plot = image
self.cursor = cursor
self.zoom = zoom
self.figure = plot
self.figure_container = container
self.sync_trait('z_label_text', z_label, 'text')
def set_mesh_and_aspect_ratio(self):
self.scan_plot.index.set_data(self.X,self.Y)
x1=self.X[0]
x2=self.X[-1]
y1=self.Y[0]
y2=self.Y[-1]
self.figure.aspect_ratio = (x2-x1) / float((y2-y1))
self.figure.index_range.low = x1
self.figure.index_range.high = x2
self.figure.value_range.low = y1
self.figure.value_range.high = y2
def check_zoom(self, box):
li,lv,hi,hv=box
if self.constant_axis == 'x':
if not li<self.z<hi:
self.z = 0.5*(li+hi)
if not lv<self.y<hv:
self.y = 0.5*(lv+hv)
elif self.constant_axis == 'y':
if not li<self.x<hi:
self.x = 0.5*(li+hi)
if not lv<self.z<hv:
self.z = 0.5*(lv+hv)
elif self.constant_axis == 'z':
if not li<self.x<hi:
self.x = 0.5*(li+hi)
if not lv<self.y<hv:
self.y = 0.5*(lv+hv)
def center_cursor(self):
i = 0.5 * (self.figure.index_range.low + self.figure.index_range.high)
v = 0.5 * (self.figure.value_range.low + self.figure.value_range.high)
if self.constant_axis == 'x':
self.z = i
self.y = v
elif self.constant_axis == 'y':
self.x = i
self.z = v
elif self.constant_axis == 'z':
self.x = i
self.y = v
def _constant_axis_changed(self):
self.update_mesh()
self.image = numpy.zeros((len(self.X), len(self.Y)))
self.update_axis()
self.set_mesh_and_aspect_ratio()
def update_image_plot(self):
self.plot_data.set_data('image', self.image)
def _colormap_changed(self, new):
data = self.figure.datasources['image']
func = getattr(chaco.api,new)
self.figure.color_mapper=func(DataRange1D(data))
self.figure.request_redraw()
def _show_labels_changed(self, name, old, new):
for item in self.scan_plot.overlays:
if isinstance(item, DataLabel) and item.label_format in self.labels:
item.visible = new
self.scan_plot.request_redraw()
def get_label_index(self, key):
for index, item in enumerate(self.scan_plot.overlays):
if isinstance(item, DataLabel) and item.label_format == key:
return index
return None
def set_label(self, key, coordinates, **kwargs):
plot = self.scan_plot
if self.constant_axis == 'x':
point = (coordinates[2],coordinates[1])
elif self.constant_axis == 'y':
point = (coordinates[0],coordinates[2])
elif self.constant_axis == 'z':
point = (coordinates[0],coordinates[1])
defaults = {'component':plot,
'data_point':point,
'label_format':key,
'label_position':'top right',
'bgcolor':'transparent',
'text_color':'black',
'border_visible':False,
'padding_bottom':8,
'marker':'cross',
'marker_color':'black',
'marker_line_color':'black',
'marker_line_width':1.5,
'marker_size':6,
'arrow_visible':False,
'clip_to_plot':False,
'visible':self.show_labels}
defaults.update(kwargs)
label = DataLabel(**defaults)
index = self.get_label_index(key)
if index is None:
plot.overlays.append(label)
else:
plot.overlays[index] = label
self.labels[key] = coordinates
plot.request_redraw()
def remove_label(self, key):
plot = self.scan_plot
index = self.get_label_index(key)
plot.overlays.pop(index)
plot.request_redraw()
self.labels.pop(key)
def remove_all_labels(self):
plot = self.scan_plot
new_overlays = []
for item in plot.overlays:
if not ( isinstance(item, DataLabel) and item.label_format in self.labels ) :
new_overlays.append(item)
plot.overlays = new_overlays
plot.request_redraw()
self.labels.clear()
@on_trait_change('constant_axis')
def relocate_labels(self):
for item in self.scan_plot.overlays:
if isinstance(item, DataLabel) and item.label_format in self.labels:
coordinates = self.labels[item.label_format]
if self.constant_axis == 'x':
point = (coordinates[2],coordinates[1])
elif self.constant_axis == 'y':
point = (coordinates[0],coordinates[2])
elif self.constant_axis == 'z':
point = (coordinates[0],coordinates[1])
item.data_point = point
def update_axis_li(self):
if self.constant_axis == 'x':
self.z1 = self.figure.index_range.low
elif self.constant_axis == 'y':
self.x1 = self.figure.index_range.low
elif self.constant_axis == 'z':
self.x1 = self.figure.index_range.low
def update_axis_hi(self):
if self.constant_axis == 'x':
self.z2 = self.figure.index_range.high
elif self.constant_axis == 'y':
self.x2 = self.figure.index_range.high
elif self.constant_axis == 'z':
self.x2 = self.figure.index_range.high
def update_axis_lv(self):
if self.constant_axis == 'x':
self.y1 = self.figure.value_range.low
elif self.constant_axis == 'y':
self.z1 = self.figure.value_range.low
elif self.constant_axis == 'z':
self.y1 = self.figure.value_range.low
def update_axis_hv(self):
if self.constant_axis == 'x':
self.y2 = self.figure.value_range.high
elif self.constant_axis == 'y':
self.z2 = self.figure.value_range.high
elif self.constant_axis == 'z':
self.y2 = self.figure.value_range.high
def update_axis(self):
self.update_axis_li()
self.update_axis_hi()
self.update_axis_lv()
self.update_axis_hv()
def update_mesh(self):
if self.constant_axis == 'x':
x1=self.z1
x2=self.z2
y1=self.y1
y2=self.y2
elif self.constant_axis == 'y':
x1=self.x1
x2=self.x2
y1=self.z1
y2=self.z2
elif self.constant_axis == 'z':
x1=self.x1
x2=self.x2
y1=self.y1
y2=self.y2
if (x2-x1) >= (y2-y1):
self.X = numpy.linspace(x1,x2,self.resolution)
self.Y = numpy.linspace(y1,y2,int(self.resolution*(y2-y1)/(x2-x1)))
else:
self.Y = numpy.linspace(y1,y2,self.resolution)
self.X = numpy.linspace(x1,x2,int(self.resolution*(x2-x1)/(y2-y1)))
# GUI buttons
def _history_back_fired(self):
self.stop()
self.set_items( self.history.back() )
def _history_forward_fired(self):
self.stop()
self.set_items( self.history.forward() )
def _reset_range_fired(self):
self.x1 = self.scanner.getXRange()[0]
self.x2 = self.scanner.getXRange()[1]
self.y1 = self.scanner.getYRange()[0]
self.y2 = self.scanner.getYRange()[1]
self.z1 = self.scanner.getZRange()[0]
self.z2 = self.scanner.getZRange()[1]
def _reset_cursor_fired(self):
self.center_cursor()
# saving images
def save_image(self, filename=None):
self.save_figure(self.figure_container, filename)
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('history_back', show_label=False),
Item('history_forward', show_label=False),
),
Item('figure_container', show_label=False, resizable=True,
enabled_when='state != "run"'
),
HGroup(Item('thresh_low', width=-80),
Item('thresh_high', width=-80),
Item('colormap', width=-100),
Item('show_labels'),
),
HGroup(Item('resolution', enabled_when='state != "run"', width=-60),
Item('x1', width=-60),
Item('x2', width=-60),
Item('y1', width=-60),
Item('y2', width=-60),
Item('z1', width=-60),
Item('z2', width=-60),
Item('reset_range', show_label=False),
),
HGroup(Item('constant_axis', style='custom', show_label=False, enabled_when='state != "run"'),
Item('bidirectional', enabled_when='state != "run"'),
Item('seconds_per_point', width=-80),
Item('return_speed', width=-80),
Item('reset_cursor', show_label=False),
),
Item('x', enabled_when='state != "run" or (state == "run" and constant_axis == "x")'),
Item('y', enabled_when='state != "run" or (state == "run" and constant_axis == "y")'),
Item('z', enabled_when='state != "run" or (state == "run" and constant_axis == "z")'),
),
title='Confocal', width=880, height=800, buttons=[], resizable=True, x=0, y=0
)
| Python |
import numpy as np
from traits.api import Range, Array, Instance
from traitsui.api import View, Item, HGroup, VGroup
from enable.api import Component, ComponentEditor
from chaco.api import ArrayPlotData
from tools.chaco_addons import SavePlot as Plot, SaveTool
import logging
from tools.emod import ManagedJob
from tools.utility import GetSetItemsMixin
class Saturation( ManagedJob, GetSetItemsMixin ):
"""
Measures saturation curves.
written by: helmut.fedder@gmail.com
last modified: 2012-08-17
"""
v_begin = Range(low=0., high=5., value=0., desc='begin [V]', label='begin [V]', mode='text', auto_set=False, enter_set=True)
v_end = Range(low=0., high=5., value=5., desc='end [V]', label='end [V]', mode='text', auto_set=False, enter_set=True)
v_delta = Range(low=0., high=5., value=.1, desc='delta [V]', label='delta [V]', mode='text', auto_set=False, enter_set=True)
seconds_per_point = Range(low=1e-3, high=1000., value=1., desc='Seconds per point', label='Seconds per point', mode='text', auto_set=False, enter_set=True)
voltage = Array()
power = Array()
rate = Array()
plot_data = Instance( ArrayPlotData )
plot = Instance( Plot )
get_set_items=['__doc__', 'v_begin', 'v_end', 'v_delta', 'seconds_per_point', 'voltage', 'power', 'rate' ]
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
HGroup(Item('v_begin'),
Item('v_end'),
Item('v_delta'),
),
HGroup(Item('seconds_per_point'),
),
Item('plot', editor=ComponentEditor(), show_label=False, resizable=True),
),
title='Saturation', buttons=[], resizable=True
)
def __init__(self, time_tagger, laser, power_meter, **kwargs):
super(Saturation, self).__init__(**kwargs)
self.time_tagger = time_tagger
self.laser = laser
self.power_meter = power_meter
self._create_plot()
self.on_trait_change(self._update_index, 'power', dispatch='ui')
self.on_trait_change(self._update_value, 'rate', dispatch='ui')
def _run(self):
try:
self.state='run'
voltage = np.arange(self.v_begin, self.v_end, self.v_delta)
power = np.zeros_like(voltage)
rate = np.zeros_like(voltage)
counter_0 = self.time_tagger.Countrate(0)
counter_1 = self.time_tagger.Countrate(1)
for i,v in enumerate(voltage):
self.laser.voltage = v
power[i] = self.power_meter.getPower()
counter_0.clear()
counter_1.clear()
self.thread.stop_request.wait(self.seconds_per_point)
if self.thread.stop_request.isSet():
logging.getLogger().debug('Caught stop signal. Exiting.')
self.state = 'idle'
break
rate[i] = counter_0.getData() + counter_1.getData()
power[i] = self.power_meter.getPower()
else:
self.state = 'done'
del counter_0
del counter_1
self.voltage = voltage
self.power = power
self.rate = rate
finally:
self.state = 'idle'
def _create_plot(self):
plot_data = ArrayPlotData(power=np.array(()), rate=np.array(()),)
plot = Plot(plot_data, padding=8, padding_left=64, padding_bottom=64)
plot.plot(('power','rate'), color='blue')
plot.index_axis.title = 'Power [mW]'
plot.value_axis.title = 'rate [kcounts/s]'
plot.tools.append(SaveTool(plot))
self.plot_data = plot_data
self.plot = plot
def _update_index(self, new):
self.plot_data.set_data('power', new*1e3)
def _update_value(self, new):
self.plot_data.set_data('rate', new*1e-3)
def save_plot(self, filename):
save_figure(self.plot, filename)
if __name__=='__main__':
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.INFO)
logging.getLogger().info('Starting logger.')
import hardware.dummy
time_tagger = hardware.dummy.TimeTagger()
laser = hardware.dummy.Laser()
power_meter = hardware.dummy.PowerMeter()
from tools.emod import JobManager
JobManager().start()
saturation = Saturation(time_tagger, laser, power_meter)
saturation.edit_traits()
| Python |
import numpy as np
from traits.api import Trait, Instance, Property, String, Range, Float, Int, Bool, Array, Enum, Button
from traitsui.api import View, Item, HGroup, VGroup, VSplit, Tabbed, EnumEditor, TextEditor, Group
from enable.api import Component, ComponentEditor
from chaco.api import ArrayPlotData, Plot, Spectral, PlotLabel
from tools.chaco_addons import SavePlot as Plot, SaveTool
import time
import threading
import logging
from tools.emod import ManagedJob
from analysis.odmr_analysis import fit_odmr, n_lorentzians
from tools.utility import GetSetItemsMixin
class ODMR( ManagedJob, GetSetItemsMixin ):
"""Provides ODMR measurements."""
# starting and stopping
keep_data = Bool(False) # helper variable to decide whether to keep existing data
resubmit_button = Button(label='resubmit', desc='Submits the measurement to the job manager. Tries to keep previously acquired data. Behaves like a normal submit if sequence or time bins have changed since previous run.')
# measurement parameters
power = Range(low=-100., high=25., value=-20, desc='Power [dBm]', label='Power [dBm]', mode='text', auto_set=False, enter_set=True)
frequency_begin = Float(default_value=2.85e9, desc='Start Frequency [Hz]', label='Begin [Hz]', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%e'))
frequency_end = Float(default_value=2.88e9, desc='Stop Frequency [Hz]', label='End [Hz]', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%e'))
frequency_delta = Float(default_value=1e6, desc='frequency step [Hz]', label='Delta [Hz]', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%e'))
t_pi = Range(low=1., high=100000., value=1000., desc='length of pi pulse [ns]', label='pi [ns]', mode='text', auto_set=False, enter_set=True)
laser = Range(low=1., high=10000., value=300., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True)
wait = Range(low=1., high=10000., value=1000., desc='wait [ns]', label='wait [ns]', mode='text', auto_set=False, enter_set=True)
pulsed = Bool(False, label='pulsed')
seconds_per_point = Range(low=20e-3, high=1, value=20e-3, desc='Seconds per point', label='Seconds per point', mode='text', auto_set=False, enter_set=True)
stop_time = Range(low=1., value=np.inf, desc='Time after which the experiment stops by itself [s]', label='Stop time [s]', mode='text', auto_set=False, enter_set=True)
n_lines = Range (low=1, high=10000, value=50, desc='Number of lines in Matrix', label='Matrix lines', mode='text', auto_set=False, enter_set=True)
# control data fitting
perform_fit = Bool(False, label='perform fit')
number_of_resonances = Trait( 'auto', String('auto', auto_set=False, enter_set=True), Int(10000., desc='Number of Lorentzians used in fit', label='N', auto_set=False, enter_set=True))
threshold = Range(low=-99, high=99., value=-50., desc='Threshold for detection of resonances [%]. The sign of the threshold specifies whether the resonances are negative or positive.', label='threshold [%]', mode='text', auto_set=False, enter_set=True)
# fit result
fit_parameters = Array(value=np.array((np.nan, np.nan, np.nan, np.nan)))
fit_frequencies = Array(value=np.array((np.nan,)), label='frequency [Hz]')
fit_line_width = Array(value=np.array((np.nan,)), label='line_width [Hz]')
fit_contrast = Array(value=np.array((np.nan,)), label='contrast [%]')
# measurement data
frequency = Array()
counts = Array()
counts_matrix = Array()
run_time = Float(value=0.0, desc='Run time [s]', label='Run time [s]')
# plotting
line_label = Instance( PlotLabel )
line_data = Instance( ArrayPlotData )
matrix_data = Instance( ArrayPlotData )
line_plot = Instance( Plot, editor=ComponentEditor() )
matrix_plot = Instance( Plot, editor=ComponentEditor() )
def __init__(self, microwave, counter, pulse_generator=None, **kwargs):
super(ODMR, self).__init__(**kwargs)
self.microwave = microwave
self.counter = counter
self.pulse_generator = pulse_generator
self._create_line_plot()
self._create_matrix_plot()
self.on_trait_change(self._update_line_data_index, 'frequency', dispatch='ui')
self.on_trait_change(self._update_line_data_value, 'counts', dispatch='ui')
self.on_trait_change(self._update_line_data_fit, 'fit_parameters', dispatch='ui')
self.on_trait_change(self._update_matrix_data_value, 'counts_matrix', dispatch='ui')
self.on_trait_change(self._update_matrix_data_index, 'n_lines,frequency', dispatch='ui')
self.on_trait_change(self._update_fit, 'counts,perform_fit,number_of_resonances,threshold', dispatch='ui')
def _counts_matrix_default(self):
return np.zeros( (self.n_lines, len(self.frequency)) )
def _frequency_default(self):
return np.arange(self.frequency_begin, self.frequency_end+self.frequency_delta, self.frequency_delta)
def _counts_default(self):
return np.zeros(self.frequency.shape)
# data acquisition
def apply_parameters(self):
"""Apply the current parameters and decide whether to keep previous data."""
frequency = np.arange(self.frequency_begin, self.frequency_end+self.frequency_delta, self.frequency_delta)
if not self.keep_data or np.any(frequency != self.frequency):
self.frequency = frequency
self.counts = np.zeros(frequency.shape)
self.run_time = 0.0
self.keep_data = True # when job manager stops and starts the job, data should be kept. Only new submission should clear data.
def _run(self):
try:
self.state='run'
self.apply_parameters()
if self.run_time >= self.stop_time:
self.state='done'
return
# if pulsed, turn on sequence
if self.pulse_generator:
if self.pulsed:
self.pulse_generator.Sequence( 100 * [ (['laser','aom'],self.laser), ([],self.wait), (['microwave'],self.t_pi) ] )
else:
self.pulse_generator.Open()
else:
if self.pulsed:
raise ValueError("pulse_generator not defined while running measurement in pulsed mode.")
n = len(self.frequency)
"""
self.microwave.setOutput( self.power, np.append(self.frequency,self.frequency[0]), self.seconds_per_point)
self._prepareCounter(n)
"""
self.microwave.setPower(self.power)
self.microwave.initSweep( self.frequency, self.power*np.ones(self.frequency.shape))
self.counter.configure(n, self.seconds_per_point, DutyCycle=0.8)
time.sleep(0.5)
while self.run_time < self.stop_time:
start_time = time.time()
if threading.currentThread().stop_request.isSet():
break
self.microwave.resetListPos()
counts = self.counter.run()
self.run_time += time.time() - start_time
self.counts += counts
self.counts_matrix = np.vstack( (counts, self.counts_matrix[:-1,:]) )
self.trait_property_changed('counts', self.counts)
"""
self.microwave.doSweep()
timeout = 3.
start_time = time.time()
while not self._count_between_markers.ready():
time.sleep(0.1)
if time.time() - start_time > timeout:
print "count between markers timeout in ODMR"
break
counts = self._count_between_markers.getData(0)
self._count_between_markers.clean()
"""
self.microwave.setOutput( None, self.frequency_begin)
if self.pulse_generator:
self.pulse_generator.Light()
self.counter.clear()
except:
logging.getLogger().exception('Error in odmr.')
self.microwave.setOutput( None, self.frequency_begin)
self.state = 'error'
else:
if self.run_time < self.stop_time:
self.state = 'idle'
else:
try:
self.save(self.filename)
except:
logging.getLogger().exception('Failed to save the data to file.')
self.state='done'
# fitting
def _update_fit(self):
if self.perform_fit:
N = self.number_of_resonances
if N != 'auto':
N = int(N)
try:
p,dp = fit_odmr(self.frequency,self.counts,threshold=self.threshold*0.01,number_of_lorentzians=N)
except Exception:
logging.getLogger().debug('ODMR fit failed.', exc_info=True)
p = np.nan*np.empty(4)
else:
p = np.nan*np.empty(4)
self.fit_parameters = p
self.fit_frequencies = p[1::3]
self.fit_line_width = p[2::3]
N = len(p)/3
contrast = np.empty(N)
c = p[0]
pp=p[1:].reshape((N,3))
for i,pi in enumerate(pp):
a = pi[2]
g = pi[1]
A = np.abs(a/(np.pi*g))
if a > 0:
contrast[i] = 100*A/(A+c)
else:
contrast[i] = 100*A/c
self.fit_contrast = contrast
# plotting
def _create_line_plot(self):
line_data = ArrayPlotData(frequency=np.array((0.,1.)), counts=np.array((0.,0.)), fit=np.array((0.,0.)))
line_plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=32)
line_plot.plot(('frequency','counts'), style='line', color='blue')
line_plot.index_axis.title = 'Frequency [MHz]'
line_plot.value_axis.title = 'Fluorescence counts'
line_label = PlotLabel(text='', hjustify='left', vjustify='bottom', position=[64,128])
line_plot.overlays.append(line_label)
line_plot.tools.append(SaveTool(line_plot))
self.line_label = line_label
self.line_data = line_data
self.line_plot = line_plot
def _create_matrix_plot(self):
matrix_data = ArrayPlotData(image=np.zeros((2,2)))
matrix_plot = Plot(matrix_data, padding=8, padding_left=64, padding_bottom=32)
matrix_plot.index_axis.title = 'Frequency [MHz]'
matrix_plot.value_axis.title = 'line #'
matrix_plot.img_plot('image',
xbounds=(self.frequency[0],self.frequency[-1]),
ybounds=(0,self.n_lines),
colormap=Spectral)
matrix_plot.tools.append(SaveTool(matrix_plot))
self.matrix_data = matrix_data
self.matrix_plot = matrix_plot
def _perform_fit_changed(self,new):
plot = self.line_plot
if new:
plot.plot(('frequency','fit'), style='line', color='red', name='fit')
self.line_label.visible=True
else:
plot.delplot('fit')
self.line_label.visible=False
plot.request_redraw()
def _update_line_data_index(self):
self.line_data.set_data('frequency', self.frequency*1e-6)
self.counts_matrix = self._counts_matrix_default()
def _update_line_data_value(self):
self.line_data.set_data('counts', self.counts)
def _update_line_data_fit(self):
if not np.isnan(self.fit_parameters[0]):
self.line_data.set_data('fit', n_lorentzians(*self.fit_parameters)(self.frequency))
p = self.fit_parameters
f = p[1::3]
w = p[2::3]
N = len(p)/3
contrast = np.empty(N)
c = p[0]
pp=p[1:].reshape((N,3))
for i,pi in enumerate(pp):
a = pi[2]
g = pi[1]
A = np.abs(a/(np.pi*g))
if a > 0:
contrast[i] = 100*A/(A+c)
else:
contrast[i] = 100*A/c
s = ''
for i, fi in enumerate(f):
s += 'f %i: %.6e Hz, HWHM %.3e Hz, contrast %.1f%%\n'%(i+1, fi, w[i], contrast[i])
self.line_label.text = s
def _update_matrix_data_value(self):
self.matrix_data.set_data('image', self.counts_matrix)
def _update_matrix_data_index(self):
if self.n_lines > self.counts_matrix.shape[0]:
self.counts_matrix = np.vstack( (self.counts_matrix,np.zeros((self.n_lines-self.counts_matrix.shape[0], self.counts_matrix.shape[1]))) )
else:
self.counts_matrix = self.counts_matrix[:self.n_lines]
self.matrix_plot.components[0].index.set_data((self.frequency.min()*1e-6, self.frequency.max()*1e-6),(0.0,float(self.n_lines)))
# saving data
def save_all(self, filename):
self.line_plot.save(filename+'_ODMR_Line_Plot.png')
self.matrix_plot.save(filename+'_ODMR_Matrix_Plot.png')
self.save(filename+'_ODMR.pys')
# react to GUI events
def submit(self):
"""Submit the job to the JobManager."""
self.keep_data = False
ManagedJob.submit(self)
def resubmit(self):
"""Submit the job to the JobManager."""
self.keep_data = True
ManagedJob.submit(self)
def _resubmit_button_fired(self):
"""React to start button. Submit the Job."""
self.resubmit()
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority', enabled_when='state != "run"'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
VGroup(HGroup(Item('power', width=-40, enabled_when='state != "run"'),
Item('frequency_begin', width=-80, enabled_when='state != "run"'),
Item('frequency_end', width=-80, enabled_when='state != "run"'),
Item('frequency_delta', width=-80, enabled_when='state != "run"'),
),
HGroup(Item('seconds_per_point', width=-40, enabled_when='state != "run"'),
Item('pulsed', enabled_when='state != "run"'),
Item('laser', width=-50, enabled_when='state != "run"'),
Item('wait', width=-50, enabled_when='state != "run"'),
Item('t_pi', width=-50, enabled_when='state != "run"'),
),
HGroup(Item('perform_fit'),
Item('number_of_resonances', width=-60),
Item('threshold', width=-60),
Item('n_lines', width=-60),
),
HGroup(Item('fit_contrast', style='readonly'),
Item('fit_line_width', style='readonly'),
Item('fit_frequencies', style='readonly'),
),
),
VSplit(Item('matrix_plot', show_label=False, resizable=True),
Item('line_plot', show_label=False, resizable=True),
),
),
title='ODMR', width=900, height=800, buttons=[], resizable=True
)
get_set_items = ['frequency', 'counts', 'counts_matrix',
'fit_parameters', 'fit_contrast', 'fit_line_width', 'fit_frequencies',
'perform_fit', 'run_time',
'power', 'frequency_begin', 'frequency_end', 'frequency_delta',
'laser', 'wait', 'pulsed', 't_pi',
'seconds_per_point', 'stop_time', 'n_lines',
'number_of_resonances', 'threshold',
'__doc__']
if __name__ == '__main__':
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
from hardware.dummy import Counter, Microwave
microwave = Microwave()
counter = Counter()
#from tools.emod import JobManager
#JobManager().start()
o = ODMR(microwave, counter)
o.edit_traits()
| Python |
import numpy as np
from traits.api import Range, Array, Instance, Enum, on_trait_change, Bool, Button, Float
from traitsui.api import View, Item, HGroup
from enable.api import ComponentEditor
from chaco.api import ArrayPlotData
from tools.chaco_addons import SavePlot as Plot, SaveTool
from threading import currentThread
import logging
import time
from tools.emod import ManagedJob
from tools.utility import GetSetItemsMixin
class Polarization( ManagedJob, GetSetItemsMixin):
"""
Record a polarization curve.
written by: helmut.fedder@gmail.com
last modified: 2012-10-25
"""
seconds_per_point = Range(low=1e-4, high=100., value=1., desc='integration time for one point', label='seconds per point', mode='text', auto_set=False, enter_set=True)
angle_step = Range(low=1e-3, high=100., value=1., desc='angular step', label='angle step', mode='text', auto_set=False, enter_set=True)
angle = Array()
intensity = Array()
power = Array()
plot = Instance( Plot )
plot_data = Instance( ArrayPlotData )
get_set_items=['__doc__', 'seconds_per_point', 'angle_step', 'angle', 'intensity', 'power']
def __init__(self, time_tagger, rotation_stage, power_meter=None, **kwargs):
super(Polarization, self).__init__(**kwargs)
self.time_tagger = time_tagger
self.rotation_stage = rotation_stage
self.power_meter = power_meter
self._create_plot()
self.on_trait_change(self._update_index, 'angle', dispatch='ui')
self.on_trait_change(self._update_value, 'intensity', dispatch='ui')
def _run(self):
"""Acquire data."""
try: # run the acquisition
self.state='run'
self.rotation_stage.go_home()
self.angle = np.array(())
self.intensity = np.array(())
self.power = np.array(())
c1 = self.time_tagger.Countrate(0)
c2 = self.time_tagger.Countrate(1)
for phi in np.arange(0.,360.,self.angle_step):
self.rotation_stage.set_angle(phi)
c1.clear()
c2.clear()
self.thread.stop_request.wait(self.seconds_per_point)
if self.thread.stop_request.isSet():
logging.getLogger().debug('Caught stop signal. Exiting.')
self.state = 'idle'
break
self.angle=np.append(self.angle,phi)
self.intensity=np.append(self.intensity,c1.getData() + c2.getData())
if self.power_meter:
self.power=np.append(self.power,self.power_meter.getPower())
else:
self.power=np.append(self.power,-1)
else:
self.state='done'
except: # if anything fails, recover
logging.getLogger().exception('Error in polarization.')
self.state='error'
finally:
del c1
del c2
def _create_plot(self):
plot_data = ArrayPlotData(angle=np.array(()), intensity=np.array(()),)
plot = Plot(plot_data, padding=8, padding_left=64, padding_bottom=64)
plot.plot(('angle','intensity'), color='blue')
plot.index_axis.title = 'angle [deg]'
plot.value_axis.title = 'intensity [count/s]'
plot.tools.append(SaveTool(plot))
self.plot_data = plot_data
self.plot = plot
def _update_index(self,new):
self.plot_data.set_data('angle',new)
def _update_value(self,new):
self.plot_data.set_data('intensity',new)
def save_plot(self, filename):
save_figure(self.plot, filename)
traits_view = View(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
HGroup(Item('seconds_per_point'),
Item('angle_step'),
),
Item('plot', editor=ComponentEditor(), show_label=False),
title='Polarization', width=640, height=640, buttons=[], resizable=True
)
if __name__ == '__main__':
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
from tools.emod import JobManager
JobManager().start()
p = Polarization()
p.edit_traits()
| Python |
"""
This code is currently broken
small changes are required to adapt it to the new pulsed measurements (without hardware API).
See rabi.py as example.
"""
class Hahn( Rabi ):
"""Defines a Hahn-Echo measurement."""
t_pi2 = Range(low=1., high=100000., value=1000., desc='pi/2 pulse length', label='pi/2 [ns]', mode='text', auto_set=False, enter_set=True)
t_pi = Range(low=1., high=100000., value=1000., desc='pi pulse length', label='pi [ns]', mode='text', auto_set=False, enter_set=True)
def generate_sequence(self):
tau = self.tau
laser = self.laser
wait = self.wait
t_pi2 = self.t_pi2
t_pi = self.t_pi
sequence = []
for t in tau:
sequence += [ (['mw'],t_pi2), ([],0.5*t), (['mw'],t_pi), ([],0.5*t), (['mw'],t_pi2), (['detect','aom'],laser), ([],wait) ]
sequence += [ (['sequence'],100) ]
return sequence
get_set_items = Rabi.get_set_items + ['t_pi2','t_pi']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time'),
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),
Item('t_pi2', width=-80, enabled_when='state != "run"'),
Item('t_pi', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='parameter'
),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'
),
),
),
title='Hahn-Echo Measurement',
)
class Hahn3pi2( Rabi ):
"""Defines a Hahn-Echo measurement with both pi/2 and 3pi/2 readout pulse."""
t_pi2 = Range(low=1., high=100000., value=1000., desc='pi/2 pulse length', label='pi/2 [ns]', mode='text', auto_set=False, enter_set=True)
t_pi = Range(low=1., high=100000., value=1000., desc='pi pulse length', label='pi [ns]', mode='text', auto_set=False, enter_set=True)
t_3pi2 = Range(low=1., high=100000., value=1000., desc='3pi/2 pulse length', label='3pi/2 [ns]', mode='text', auto_set=False, enter_set=True)
def generate_sequence(self):
tau = self.tau
laser = self.laser
wait = self.wait
t_pi2 = self.t_pi2
t_pi = self.t_pi
t_3pi2 = self.t_3pi2
sequence = []
for t in tau:
sequence += [ (['mw'],t_pi2), ([],0.5*t), (['mw'],t_pi), ([],0.5*t), (['mw'],t_pi2), (['detect','aom'],laser), ([],wait) ]
for t in tau:
sequence += [ (['mw'],t_pi2), ([],0.5*t), (['mw'],t_pi), ([],0.5*t), (['mw'],t_3pi2), (['detect','aom'],laser), ([],wait) ]
sequence += [ (['sequence'],100) ]
return sequence
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time'),
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),
Item('t_pi2', width=-80, enabled_when='state != "run"'),
Item('t_pi', width=-80, enabled_when='state != "run"'),
Item('t_3pi2', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='parameter'
),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'
),
),
),
title='Hahn-Echo Measurement with both pi/2 and 3pi/2 readout pulse',
)
get_set_items = Rabi.get_set_items + ['t_pi2','t_pi','t_3pi2']
| Python |
"""
Provides basis for a pulsed measurement based on pulse_generator and time_tagger.
"""
import numpy as np
from traits.api import Range, Int, Float, Bool, Array, Instance, Enum, on_trait_change, Button
from traitsui.api import View, Item, Tabbed, HGroup, VGroup, VSplit, EnumEditor, TextEditor
import logging
import time
from tools.emod import ManagedJob
from tools.utility import GetSetItemsMixin
"""
Several options to decide when to start and when to restart a job, i.e. when to clear data, etc.
1. set a 'new' flag on every submit button
pro: simple, need not to think about anything in subclass
con: continue of measurement only possible by hack (manual submit to JobManager without submit button)
submit button does not do what it says
2. check at start time whether this is a new measurement.
pro:
con: complicated checking needed
checking has to be reimplemented on sub classes
no explicit way to restart the same measurement
3. provide user settable clear / keep flag
pro: explicit
con: user can forget
4. provide two different submit buttons: submit, resubmit
pro: explicit
con: two buttons that user may not understand
user may use wrong button
wrong button can result in errors
"""
from analysis.fitting import find_edge
# utility functions
def find_detection_pulses(sequence):
"""
Find the number of detection triggers in a pulse sequence.
"""
n = 0
prev = []
for channels, t in sequence:
if 'detect' in channels and not 'detect' in prev:
n+=1
prev = channels
if 'sequence' in channels:
break
return n
def sequence_length(sequence):
"""
Return the total length of a pulse sequence.
"""
t = 0
for c,ti in sequence:
t += ti
return t
def sequence_union(s1, s2):
"""
Return the union of two pulse sequences s1 and s2.
"""
# make sure that s1 is the longer sequence and s2 is merged into it
if sequence_length(s1) < sequence_length(s2):
sp = s2
s2 = s1
s1 = sp
s = []
c1, dt1 = s1.pop(0)
c2, dt2 = s2.pop(0)
while True:
if dt1 < dt2:
s.append( ( set(c1) | set(c2), dt1) )
dt2 -= dt1
try:
c1, dt1 = s1.pop(0)
except:
break
elif dt2 < dt1:
s.append( ( set(c1) | set(c2), dt2) )
dt1 -= dt2
try:
c2, dt2 = s2.pop(0)
except:
c2 = []
dt2 = np.inf
else:
s.append( ( set(c1) | set(c2), dt1) )
try:
c1, dt1 = s1.pop(0)
except:
break
try:
c2, dt2 = s2.pop(0)
except:
c2 = []
dt2 = np.inf
return s
def sequence_remove_zeros(sequence):
return filter(lambda x: x[1]!=0.0, sequence)
def spin_state(c, dt, T, t0=0.0, t1=-1.):
"""
Compute the spin state from a 2D array of count data.
Parameters:
c = count data
dt = time step
t0 = beginning of integration window relative to the edge
t1 = None or beginning of integration window for normalization relative to edge
T = width of integration window
Returns:
y = 1D array that contains the spin state
profile = 1D array that contains the pulse profile
edge = position of the edge that was found from the pulse profile
If t1<0, no normalization is performed. If t1>=0, each data point is divided by
the value from the second integration window and multiplied with the mean of
all normalization windows.
"""
profile = c.sum(0)
edge = find_edge(profile)
I = int(round(T/float(dt)))
i0 = edge + int(round(t0/float(dt)))
y = np.empty((c.shape[0],))
for i, slot in enumerate(c):
y[i] = slot[i0:i0+I].sum()
if t1 >= 0:
i1 = edge + int(round(t1/float(dt)))
y1 = np.empty((c.shape[0],))
for i, slot in enumerate(c):
y1[i] = slot[i1:i1+I].sum()
y = y/y1*y1.mean()
return y, profile, edge
class Pulsed( ManagedJob, GetSetItemsMixin ):
"""Defines a pulsed measurement."""
run_time = Float(value=0.0, label='run time [s]',format_str='%.f')
stop_time = Float(default_value=np.inf, desc='Time after which the experiment stops by itself [s]', label='Stop time [s]', mode='text', auto_set=False, enter_set=True)
stop_counts = Float(default_value=np.inf, desc='Stop the measurement when all data points of the extracted spin state have at least this many counts.', label='Stop counts', mode='text', auto_set=False, enter_set=True)
keep_data = Bool(False) # helper variable to decide whether to keep existing data
resubmit_button = Button(label='resubmit', desc='Submits the measurement to the job manager. Tries to keep previously acquired data. Behaves like a normal submit if sequence or time bins have changed since previous run.')
# acquisition parameters
record_length = Float(default_value=3000, desc='length of acquisition record [ns]', label='record length [ns]', mode='text', auto_set=False, enter_set=True)
bin_width = Range(low=0.1, high=1000., value=1.0, desc='bin width [ns]', label='bin width [ns]', mode='text', auto_set=False, enter_set=True)
n_laser = Int(2)
n_bins = Int(2)
time_bins = Array(value=np.array((0,1)))
sequence = Instance( list, factory=list )
# measured data
count_data = Array( value=np.zeros((2,2)) )
# parameters for calculating spin state
integration_width = Float(default_value=200., desc='width of integration window [ns]', label='integr. width [ns]', mode='text', auto_set=False, enter_set=True)
position_signal = Float(default_value=0., desc='position of signal window relative to edge [ns]', label='pos. signal [ns]', mode='text', auto_set=False, enter_set=True)
position_normalize = Float(default_value=-1., desc='position of normalization window relative to edge [ns]. If negative, no normalization is performed', label='pos. norm. [ns]', mode='text', auto_set=False, enter_set=True)
# analyzed data
pulse = Array(value=np.array((0.,0.)))
edge = Float(value=0.0)
spin_state = Array(value=np.array((0.,0.)))
channel_apd_0 = Int(0)
channel_apd_1 = Int(1)
channel_detect = Int(2)
channel_sequence = Int(3)
def __init__(self, pulse_generator, time_tagger, **kwargs):
super(Pulsed, self).__init__(**kwargs)
self.pulse_generator = pulse_generator
self.time_tagger = time_tagger
def submit(self):
"""Submit the job to the JobManager."""
self.keep_data = False
ManagedJob.submit(self)
def resubmit(self):
"""Submit the job to the JobManager."""
self.keep_data = True
ManagedJob.submit(self)
def _resubmit_button_fired(self):
"""React to start button. Submit the Job."""
self.resubmit()
def generate_sequence(self):
return []
def apply_parameters(self):
"""Apply the current parameters and decide whether to keep previous data."""
n_bins = int(self.record_length / self.bin_width)
time_bins = self.bin_width*np.arange(n_bins)
sequence = self.generate_sequence()
n_laser = find_detection_pulses(sequence)
if self.keep_data and sequence == self.sequence and np.all(time_bins == self.time_bins): # if the sequence and time_bins are the same as previous, keep existing data
self.old_count_data = self.count_data.copy()
else:
self.old_count_data = np.zeros((n_laser,n_bins))
self.run_time = 0.0
self.sequence = sequence
self.time_bins = time_bins
self.n_bins = n_bins
self.n_laser = n_laser
self.keep_data = True # when job manager stops and starts the job, data should be kept. Only new submission should clear data.
def start_up(self):
"""Put here additional stuff to be executed at startup."""
pass
def shut_down(self):
"""Put here additional stuff to be executed at shut_down."""
pass
def _run(self):
"""Acquire data."""
try: # try to run the acquisition from start_up to shut_down
self.state='run'
self.apply_parameters()
if self.run_time >= self.stop_time:
logging.getLogger().debug('Runtime larger than stop_time. Returning')
self.state='done'
return
self.start_up()
self.pulse_generator.Night()
if self.channel_apd_0 > -1:
pulsed_0 = self.time_tagger.Pulsed(self.n_bins, int(np.round(self.bin_width*1000)), self.n_laser, self.channel_apd_0, self.channel_detect, self.channel_sequence)
if self.channel_apd_1 > -1:
pulsed_1 = self.time_tagger.Pulsed(self.n_bins, int(np.round(self.bin_width*1000)), self.n_laser, self.channel_apd_1, self.channel_detect, self.channel_sequence)
self.pulse_generator.Sequence(self.sequence)
self.pulse_generator.checkUnderflow()
while self.run_time < self.stop_time and any(self.spin_state<self.stop_counts):
start_time = time.time()
self.thread.stop_request.wait(1.0)
if self.thread.stop_request.isSet():
logging.getLogger().debug('Caught stop signal. Exiting.')
break
if self.pulse_generator.checkUnderflow():
raise RuntimeError('Underflow in pulse generator.')
if self.channel_apd_0 > -1 and self.channel_apd_1 > -1:
self.count_data = self.old_count_data + pulsed_0.getData() + pulsed_1.getData()
elif self.channel_apd_0 > -1:
self.count_data = self.old_count_data + pulsed_0.getData()
elif self.channel_apd_1 > -1:
self.count_data = self.old_count_data + pulsed_1.getData()
self.run_time += time.time() - start_time
if self.run_time < self.stop_time:
self.state = 'idle'
else:
try:
self.save(self.filename)
except:
logging.getLogger().exception('Failed to save the data to file.')
self.state='done'
if self.channel_apd_0 > -1:
del pulsed_0
if self.channel_apd_1 > -1:
del pulsed_1
self.shut_down()
self.pulse_generator.Light()
except: # if anything fails, log the exception and set the state
logging.getLogger().exception('Something went wrong in pulsed loop.')
self.state='error'
@on_trait_change('count_data,integration_width,position_signal,position_normalize')
def _compute_spin_state(self):
y, profile, edge = spin_state(c=self.count_data,
dt=self.bin_width,
T=self.integration_width,
t0=self.position_signal,
t1=self.position_normalize,
)
self.spin_state = y
self.pulse = profile
self.edge = self.time_bins[edge]
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority', width=-40),
Item('state', style='readonly'),
Item('run_time', style='readonly', format_str='%.f'),
Item('stop_time', format_str='%.f'),
Item('stop_counts'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
HGroup(Item('bin_width', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
),
),
title='Pulsed Measurement',
)
get_set_items = ['__doc__','record_length','bin_width','n_bins','time_bins','n_laser','sequence','count_data','run_time',
'integration_width','position_signal','position_normalize',
'pulse','edge','spin_state']
class PulsedTau( Pulsed ):
"""Defines a Pulsed measurement with tau mesh."""
tau_begin = Float(default_value=0., desc='tau begin [ns]', label='tau begin [ns]', mode='text', auto_set=False, enter_set=True)
tau_end = Float(default_value=300., desc='tau end [ns]', label='tau end [ns]', mode='text', auto_set=False, enter_set=True)
tau_delta = Float(default_value=3., desc='delta tau [ns]', label='delta tau [ns]', mode='text', auto_set=False, enter_set=True)
tau = Array( value=np.array((0.,1.)) )
def apply_parameters(self):
"""Overwrites apply_parameters() from pulsed. Prior to generating sequence, etc., generate the tau mesh."""
self.tau = np.arange(self.tau_begin, self.tau_end, self.tau_delta)
Pulsed.apply_parameters(self)
get_set_items = Pulsed.get_set_items + ['tau_begin','tau_end','tau_delta','tau']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
HGroup(Item('bin_width', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
),
),
title='PulsedTau Measurement',
)
if __name__ == '__main__':
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
from tools.emod import JobManager
JobManager().start()
from hardware.dummy import PulseGenerator, TimeTagger
pulse_generator = PulseGenerator()
time_tagger = TimeTagger()
pulsed = PulsedTau(pulse_generator, time_tagger)
pulsed.edit_traits()
| Python |
"""
Auto focus tool.
"""
import numpy as np
from traits.api import SingletonHasTraits, Instance, Range, Bool, Array, Str, Enum, Button, on_trait_change, Trait
from traitsui.api import View, Item, Group, HGroup, VGroup, VSplit, Tabbed, EnumEditor
from enable.api import ComponentEditor
from chaco.api import PlotAxis, CMapImagePlot, ColorBar, LinearMapper, ArrayPlotData, Spectral
from tools.chaco_addons import SaveHPlotContainer as HPlotContainer, SavePlot as Plot, SaveTool
# date and time tick marks
from chaco.scales.api import CalendarScaleSystem
from chaco.scales_tick_generator import ScalesTickGenerator
import threading
import time
import logging
from tools.emod import ManagedJob
from tools.cron import CronDaemon, CronEvent
from tools.utility import GetSetItemsMixin, warning
from measurements.confocal import Confocal
class AutoFocus( ManagedJob, GetSetItemsMixin ):
# overwrite default priority from ManagedJob (default 0)
priority = 10
confocal = Instance( Confocal )
size_xy = Range(low=0.5, high=10., value=1.5, desc='Size of XY Scan', label='Size XY [micron]', mode='slider', auto_set=False, enter_set=True)
size_z = Range(low=0.5, high=10., value=2., desc='Size of Z Scan', label='Size Z [micron]', mode='slider', auto_set=False, enter_set=True)
step_xy = Range(low=0.01, high=10., value=0.1, desc='Step of XY Scan', label='Step XY [micron]', mode='slider', auto_set=False, enter_set=True)
step_z = Range(low=0.01, high=10., value=0.1, desc='Step of Z Scan', label='Step Z [micron]', mode='slider', auto_set=False, enter_set=True)
seconds_per_point_xy = Range(low=1e-3, high=10, value=0.05, desc='Seconds per point for XY Scan', label='seconds per point XY [s]', mode='text', auto_set=False, enter_set=True)
seconds_per_point_z = Range(low=1e-3, high=10, value=0.2, desc='Seconds per point for Z Scan', label='seconds per point Z [s]', mode='text', auto_set=False, enter_set=True)
fit_method_xy = Enum('Maximum', 'Gaussian', desc='Fit Method for XY Scan', label='XY Fit Method')
fit_method_z = Enum('Maximum', 'Gaussian', desc='Fit Method for Z Scan', label='Z Fit Method')
X = Array(value=np.array((0.,1.)) )
Y = Array(value=np.array((0.,1.)) )
Z = Array(value=np.array((-1.,1.)) )
data_xy = Array( )
data_z = Array( value=np.array((0,0)) )
targets = Instance( {}.__class__, factory={}.__class__ ) # Dict traits are no good for pickling, therefore we have to do it with an ordinary dictionary and take care about the notification manually
target_list = Instance( list, factory=list, args=([None],) ) # list of targets that are selectable in current_target editor
current_target = Enum(values='target_list')
drift = Array( value=np.array(((0,0,0,),)) )
drift_time = Array( value=np.array((0,)) )
current_drift = Array( value=np.array((0,0,0)) )
focus_interval = Range(low=1, high=6000, value=10, desc='Time interval between automatic focus events', label='Interval [m]', auto_set=False, enter_set=True)
periodic_focus = Bool(False, label='Periodic focusing')
target_name = Str(label='name', desc='name to use when adding or removing targets')
add_target_button = Button(label='Add Target', desc='add target with given name')
remove_current_target_button = Button(label='Remove Current', desc='remove current target')
remove_all_targets_button = Button(label='Remove All', desc='remove all targets')
forget_drift_button = Button(label='Forget Drift', desc='forget the accumulated drift and reset drift plot')
next_target_button = Button(label='Next Target', desc='switch to next available target')
undo_button = Button(label='undo', desc='undo the movement of the stage')
previous_state = Instance( () )
plot_data_image = Instance( ArrayPlotData )
plot_data_line = Instance( ArrayPlotData )
plot_data_drift = Instance( ArrayPlotData )
figure_image = Instance( HPlotContainer, editor=ComponentEditor() )
figure_line = Instance( Plot, editor=ComponentEditor() )
figure_drift = Instance( Plot, editor=ComponentEditor() )
image_plot = Instance( CMapImagePlot )
def __init__(self, confocal):
super(AutoFocus, self).__init__()
self.confocal = confocal
self.on_trait_change(self.update_plot_image, 'data_xy', dispatch='ui')
self.on_trait_change(self.update_plot_line_value, 'data_z', dispatch='ui')
self.on_trait_change(self.update_plot_line_index, 'Z', dispatch='ui')
self.on_trait_change(self.update_plot_drift_value, 'drift', dispatch='ui')
self.on_trait_change(self.update_plot_drift_index, 'drift_time', dispatch='ui')
@on_trait_change('next_target_button')
def next_target(self):
"""Convenience method to switch to the next available target."""
keys = self.targets.keys()
key = self.current_target
if len(keys) == 0:
logging.getLogger().info('No target available. Add a target and try again!')
elif not key in keys:
self.current_target = keys[0]
else:
self.current_target = keys[(keys.index(self.current_target)+1)%len(keys)]
def _targets_changed(self, name, old, new):
l = new.keys() + [None] # rebuild target_list for Enum trait
l.sort()
self.target_list = l
self._draw_targets() # redraw target labels
def _current_target_changed(self):
self._draw_targets() # redraw target labels
def _draw_targets(self):
c = self.confocal
c.remove_all_labels()
c.show_labels=True
for key, coordinates in self.targets.iteritems():
if key == self.current_target:
c.set_label(key, coordinates, marker_color='red')
else:
c.set_label(key, coordinates)
def _periodic_focus_changed(self, new):
if not new and hasattr(self, 'cron_event'):
CronDaemon().remove(self.cron_event)
if new:
self.cron_event = CronEvent(self.submit, min=range(0,60,self.focus_interval))
CronDaemon().register(self.cron_event)
def fit_xy(self):
if self.fit_method_xy == 'Maximum':
index = self.data_xy.argmax()
xp = self.X[index%len(self.X)]
yp = self.Y[index/len(self.X)]
self.XYFitParameters = [xp, yp]
self.xfit = xp
self.yfit = yp
return xp, yp
else:
print 'Not Implemented! Fix Me!'
def fit_z(self):
if self.fit_method_z == 'Maximum':
zp = self.Z[self.data_z.argmax()]
self.zfit = zp
return zp
else:
print 'Not Implemented! Fix Me!'
def add_target(self, key, coordinates=None):
if coordinates is None:
c = self.confocal
coordinates = np.array((c.x,c.y,c.z))
if self.targets == {}:
self.forget_drift()
if self.targets.has_key(key):
if warning('A target with this name already exists.\nOverwriting will move all targets.\nDo you want to continue?'):
self.current_drift = coordinates - self.targets[key]
self.forget_drift()
else:
return
else:
coordinates = coordinates - self.current_drift
self.targets[key] = coordinates
self.trait_property_changed('targets', self.targets) # trigger event such that Enum is updated and Labels are redrawn
self.confocal.show_labels=True
def remove_target(self, key):
if not key in self.targets:
logging.getLogger().info('Target cannot be removed. Target does not exist.')
return
self.targets.pop(key) # remove target from dictionary
self.trait_property_changed('targets', self.targets) # trigger event such that Enum is updated and Labels are redrawn
def remove_all_targets(self):
self.targets = {}
def forget_drift(self):
targets = self.targets
# reset coordinates of all targets according to current drift
for key in targets:
targets[key] += self.current_drift
# trigger event such that target labels are redrawn
self.trait_property_changed('targets', self.targets)
# set current_drift to 0 and clear plot
self.current_drift = np.array((0., 0., 0.))
self.drift_time = np.array((time.time(),))
self.drift = np.array(((0,0,0),))
def _add_target_button_fired(self):
self.add_target( self.target_name )
def _remove_current_target_button_fired(self):
self.remove_target( self.current_target )
def _remove_all_targets_button_fired(self):
if warning('Remove all targets. Are you sure?'):
self.remove_all_targets()
def _forget_drift_button_fired(self):
if warning('Forget accumulated drift. Are you sure?'):
self.forget_drift()
def _run(self):
logging.getLogger().debug("trying run.")
try:
self.state='run'
if self.current_target is None:
self.focus()
else: # focus target
coordinates = self.targets[self.current_target]
confocal = self.confocal
confocal.x, confocal.y, confocal.z = coordinates + self.current_drift
current_coordinates = self.focus()
self.current_drift = current_coordinates - coordinates
self.drift = np.append(self.drift, (self.current_drift,), axis=0)
self.drift_time = np.append(self.drift_time, time.time())
logging.getLogger().debug('Drift: %.2f, %.2f, %.2f'%tuple(self.current_drift))
finally:
self.state = 'idle'
def focus(self):
"""
Focuses around current position in x, y, and z-direction.
"""
scanner = self.confocal.scanner
xp = self.confocal.x
yp = self.confocal.y
zp = self.confocal.z
self.previous_state = ((xp,yp,zp), self.current_target)
##+scanner.getXRange()[1]
safety = 0 #distance to keep from the ends of scan range
xmin = np.clip(xp-0.5*self.size_xy, scanner.getXRange()[0]+safety, scanner.getXRange()[1]-safety)
xmax = np.clip(xp+0.5*self.size_xy, scanner.getXRange()[0]+safety, scanner.getXRange()[1]-safety)
ymin = np.clip(yp-0.5*self.size_xy, scanner.getYRange()[0]+safety, scanner.getYRange()[1]-safety)
ymax = np.clip(yp+0.5*self.size_xy, scanner.getYRange()[0]+safety, scanner.getYRange()[1]-safety)
X = np.arange(xmin, xmax, self.step_xy)
Y = np.arange(ymin, ymax, self.step_xy)
self.X = X
self.Y = Y
XP = X[::-1]
self.data_xy=np.zeros((len(Y),len(X)))
#self.image_plot.index.set_data(X, Y)
for i,y in enumerate(Y):
if threading.current_thread().stop_request.isSet():
self.confocal.x = xp
self.confocal.y = yp
self.confocal.z = zp
return xp, yp, zp
if i%2 != 0:
XL = XP
else:
XL = X
YL = y * np.ones(X.shape)
ZL = zp * np.ones(X.shape)
Line = np.vstack( (XL, YL, ZL) )
c = scanner.scanLine(Line, self.seconds_per_point_xy)
if i%2 == 0:
self.data_xy[i,:] = c[:]
else:
self.data_xy[i,:] = c[-1::-1]
self.trait_property_changed('data_xy', self.data_xy)
xp, yp = self.fit_xy()
self.confocal.x = xp
self.confocal.y = yp
Z = np.hstack( ( np.arange(zp, zp-0.5*self.size_z, -self.step_z),
np.arange(zp-0.5*self.size_z, zp+0.5*self.size_z, self.step_z),
np.arange(zp+0.5*self.size_z, zp, -self.step_z) ) )
Z = np.clip(Z, scanner.getZRange()[0]+safety, scanner.getZRange()[1]-safety)
X = xp * np.ones(Z.shape)
Y = yp * np.ones(Z.shape)
if not threading.current_thread().stop_request.isSet():
Line = np.vstack( (X, Y, Z) )
data_z = scanner.scanLine(Line, self.seconds_per_point_z)
self.Z = Z
self.data_z = data_z
zp = self.fit_z()
self.confocal.z = zp
logging.getLogger().info('Focus: %.2f, %.2f, %.2f' %(xp, yp, zp))
return xp, yp, zp
def undo(self):
if self.previous_state is not None:
coordinates, target = self.previous_state
self.confocal.x, self.confocal.y, self.confocal.z = coordinates
if target is not None:
self.drift_time = np.delete(self.drift_time, -1)
self.current_drift = self.drift[-2]
self.drift = np.delete(self.drift, -1, axis=0)
self.previous_state = None
else:
logging.getLogger().info('Can undo only once.')
def _undo_button_fired(self):
self.remove()
self.undo()
def _plot_data_image_default(self):
return ArrayPlotData(image=np.zeros((2,2)))
def _plot_data_line_default(self):
return ArrayPlotData(x=self.Z, y=self.data_z)
def _plot_data_drift_default(self):
return ArrayPlotData(t=self.drift_time, x=self.drift[:,0], y=self.drift[:,1], z=self.drift[:,2])
def _figure_image_default(self):
plot = Plot(self.plot_data_image, width=100, height=100, padding=8, padding_left=48, padding_bottom=32)
plot.img_plot('image', colormap=Spectral, name='image')
plot.aspect_ratio=1
plot.index_mapper.domain_limits = (self.confocal.scanner.getXRange()[0],self.confocal.scanner.getXRange()[1])
plot.value_mapper.domain_limits = (self.confocal.scanner.getYRange()[0],self.confocal.scanner.getYRange()[1])
container = HPlotContainer()
image = plot.plots['image'][0]
colormap = image.color_mapper
colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
color_mapper=colormap,
plot=plot,
orientation='v',
resizable='v',
width=16,
height=320,
padding=8,
padding_left=32)
container = HPlotContainer()
container.add(plot)
container.add(colorbar)
container.tools.append(SaveTool(container))
return container
def _figure_line_default(self):
plot = Plot(self.plot_data_line, width=100, height=100, padding=8, padding_left=64, padding_bottom=32)
plot.plot(('x','y'), color='blue')
plot.index_axis.title = 'z [micron]'
plot.value_axis.title = 'Fluorescence [ counts / s ]'
plot.tools.append(SaveTool(plot))
return plot
def _figure_drift_default(self):
plot = Plot(self.plot_data_drift, width=100, height=100, padding=8, padding_left=64, padding_bottom=32)
plot.plot(('t','x'), type='line', color='blue', name='x')
plot.plot(('t','y'), type='line', color='red', name='y')
plot.plot(('t','z'), type='line', color='green', name='z')
bottom_axis = PlotAxis(plot,
orientation="bottom",
tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
plot.index_axis=bottom_axis
plot.index_axis.title = 'time'
plot.value_axis.title = 'drift [micron]'
plot.legend.visible=True
plot.tools.append(SaveTool(plot))
return plot
def _image_plot_default(self):
return self.figure_image.components[0].plots['image'][0]
def update_plot_image(self):
self.plot_data_image.set_data('image', self.data_xy)
def update_plot_line_value(self):
self.plot_data_line.set_data('y', self.data_z)
def update_plot_line_index(self):
self.plot_data_line.set_data('x', self.Z)
def update_plot_drift_value(self):
if len(self.drift) == 1:
self.plot_data_drift.set_data('x', np.array(()))
self.plot_data_drift.set_data('y', np.array(()))
self.plot_data_drift.set_data('z', np.array(()))
else:
self.plot_data_drift.set_data('x', self.drift[:,0])
self.plot_data_drift.set_data('y', self.drift[:,1])
self.plot_data_drift.set_data('z', self.drift[:,2])
def update_plot_drift_index(self):
if len(self.drift_time) == 0:
self.plot_data_drift.set_data('t', np.array(()))
else:
self.plot_data_drift.set_data('t', self.drift_time - self.drift_time[0])
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('undo_button', show_label=False),
),
Group(VGroup(HGroup(Item('target_name'),
Item('add_target_button', show_label=False),
Item('remove_all_targets_button', show_label=False),
Item('forget_drift_button', show_label=False),
),
HGroup(Item('current_target'),
Item('next_target_button', show_label=False),
Item('remove_current_target_button', show_label=False),
),
HGroup(Item('periodic_focus'),
Item('focus_interval', enabled_when='not periodic_focus'),
),
label='tracking',
),
VGroup(Item('size_xy'),
Item('step_xy'),
Item('size_z'),
Item('step_z'),
HGroup(Item('seconds_per_point_xy'),
Item('seconds_per_point_z'),
),
label='Settings',
springy=True,
),
layout='tabbed'
),
VSplit(Item('figure_image', show_label=False, resizable=True),
Item('figure_line', show_label=False, resizable=True),
Item('figure_drift', show_label=False, resizable=True),
),
),
title='Auto Focus', width=500, height=700, buttons=[], resizable=True
)
get_set_items=['confocal','targets','current_target','current_drift','drift','drift_time','periodic_focus',
'size_xy', 'size_z', 'step_xy', 'step_z', 'seconds_per_point_xy', 'seconds_per_point_z',
'data_xy', 'data_z', 'X', 'Y', 'Z', 'focus_interval' ]
get_set_order=['confocal','targets']
# testing
if __name__ == '__main__':
logging.getLogger().setLevel(logging.DEBUG)
from emod import JobManager
JobManager().start()
from cron import CronDaemon
CronDaemon().start()
c = Confocal()
c.edit_traits()
a = AutoFocus(c)
a.edit_traits()
| Python |
import numpy
import threading
# enthought library imports
from traits.api import Instance, Int, Float, Range,\
Bool, Array, Enum, Button, on_trait_change
from traitsui.api import Handler, View, Item, Group, HGroup, VGroup, Tabbed, EnumEditor
from enable.api import ComponentEditor
from chaco.api import ArrayPlotData
from tools.chaco_addons import SavePlot as Plot, SaveTool
from tools.utility import GetSetItemsMixin
from tools.emod import Job
class StartThreadHandler( Handler ):
def init(self, info):
info.object.start()
class PhotonTimeTrace( Job, GetSetItemsMixin ):
TraceLength = Range(low=10, high=10000, value=100, desc='Length of Count Trace', label='Trace Length')
SecondsPerPoint = Range(low=0.001, high=1, value=0.1, desc='Seconds per point [s]', label='Seconds per point [s]')
RefreshRate = Range(low=0.01, high=1, value=0.1, desc='Refresh rate [s]', label='Refresh rate [s]')
# trace data
C0 = Array()
C1 = Array()
C2 = Array()
C3 = Array()
C4 = Array()
C5 = Array()
C6 = Array()
C7 = Array()
C0C1 = Array()
T = Array()
c_enable0 = Bool(False, label='channel 0', desc='enable channel 0')
c_enable1 = Bool(False, label='channel 1', desc='enable channel 1')
c_enable2 = Bool(False, label='channel 2', desc='enable channel 2')
c_enable3 = Bool(False, label='channel 3', desc='enable channel 3')
c_enable4 = Bool(False, label='channel 4', desc='enable channel 4')
c_enable5 = Bool(False, label='channel 5', desc='enable channel 5')
c_enable6 = Bool(False, label='channel 6', desc='enable channel 6')
c_enable7 = Bool(False, label='channel 7', desc='enable channel 7')
sum_enable = Bool(True, label='c0 + c1', desc='enable sum c0 + c1')
TracePlot = Instance( Plot )
TraceData = Instance( ArrayPlotData )
def __init__(self, time_tagger, **kwargs):
super(PhotonTimeTrace, self).__init__(**kwargs)
self.time_tagger = time_tagger
self.on_trait_change(self._update_T, 'T', dispatch='ui')
self.on_trait_change(self._update_C0, 'C0', dispatch='ui')
self.on_trait_change(self._update_C1, 'C1', dispatch='ui')
self.on_trait_change(self._update_C2, 'C2', dispatch='ui')
self.on_trait_change(self._update_C3, 'C3', dispatch='ui')
self.on_trait_change(self._update_C4, 'C4', dispatch='ui')
self.on_trait_change(self._update_C5, 'C5', dispatch='ui')
self.on_trait_change(self._update_C6, 'C6', dispatch='ui')
#self.on_trait_change(self._update_C7, 'C7', dispatch='ui')
self.on_trait_change(self._update_C0C1, 'C0C1', dispatch='ui')
self._create_counter()
def _create_counter(self):
self._counter0 = self.time_tagger.Counter(0, int(self.SecondsPerPoint*1e12), self.TraceLength)
self._counter1 = self.time_tagger.Counter(1, int(self.SecondsPerPoint*1e12), self.TraceLength)
self._counter2 = self.time_tagger.Counter(2, int(self.SecondsPerPoint*1e12), self.TraceLength)
self._counter3 = self.time_tagger.Counter(3, int(self.SecondsPerPoint*1e12), self.TraceLength)
self._counter4 = self.time_tagger.Counter(4, int(self.SecondsPerPoint*1e12), self.TraceLength)
self._counter5 = self.time_tagger.Counter(5, int(self.SecondsPerPoint*1e12), self.TraceLength)
self._counter6 = self.time_tagger.Counter(6, int(self.SecondsPerPoint*1e12), self.TraceLength)
#self._counter7 = self.time_tagger.Counter(7, int(self.SecondsPerPoint*1e12), self.TraceLength) # ToDo: does not work when using channel 7
def _C0_default(self):
return numpy.zeros((self.TraceLength,))
def _C1_default(self):
return numpy.zeros((self.TraceLength,))
def _C2_default(self):
return numpy.zeros((self.TraceLength,))
def _C3_default(self):
return numpy.zeros((self.TraceLength,))
def _C4_default(self):
return numpy.zeros((self.TraceLength,))
def _C5_default(self):
return numpy.zeros((self.TraceLength,))
def _C6_default(self):
return numpy.zeros((self.TraceLength,))
def _C7_default(self):
return numpy.zeros((self.TraceLength,))
def _C0C1_default(self):
return numpy.zeros((self.TraceLength,))
def _T_default(self):
return self.SecondsPerPoint*numpy.arange(self.TraceLength)
def _update_T(self):
self.TraceData.set_data('t', self.T)
def _update_C0(self):
self.TraceData.set_data('y0', self.C0)
#self.TracePlot.request_redraw()
def _update_C1(self):
self.TraceData.set_data('y1', self.C1)
#self.TracePlot.request_redraw()
def _update_C2(self):
self.TraceData.set_data('y2', self.C2)
#self.TracePlot.request_redraw()
def _update_C3(self):
self.TraceData.set_data('y3', self.C3)
#self.TracePlot.request_redraw()
def _update_C4(self):
self.TraceData.set_data('y4', self.C4)
#self.TracePlot.request_redraw()
def _update_C5(self):
self.TraceData.set_data('y5', self.C5)
#self.TracePlot.request_redraw()
def _update_C6(self):
self.TraceData.set_data('y6', self.C6)
#self.TracePlot.request_redraw()
def _update_C7(self):
self.TraceData.set_data('y7', self.C7)
#self.TracePlot.request_redraw()
def _update_C0C1(self):
self.TraceData.set_data('y8', self.C0C1)
#self.TracePlot.request_redraw()
def _TraceLength_changed(self):
self.C0 = self._C0_default()
self.C1 = self._C1_default()
self.C2 = self._C2_default()
self.C3 = self._C3_default()
self.C4 = self._C4_default()
self.C5 = self._C5_default()
self.C6 = self._C6_default()
self.C7 = self._C7_default()
self.C0C1 = self._C0C1_default()
self.T = self._T_default()
self._create_counter()
def _SecondsPerPoint_changed(self):
self.T = self._T_default()
self._create_counter()
def _TraceData_default(self):
return ArrayPlotData(t=self.T, y0=self.C0, y1=self.C1, y2=self.C2, y3=self.C3, y4=self.C4, y5=self.C5, y6=self.C6, y7=self.C7, y8=self.C0C1)
def _TracePlot_default(self):
plot = Plot(self.TraceData, width=500, height=500, resizable='hv')
plot.plot(('t','y0'), type='line', color='black')
plot.tools.append(SaveTool(plot))
return plot
#@on_trait_change('c_enable0,c_enable1,c_enable2,c_enable3,c_enable4,c_enable5,c_enable6,c_enable7,sum_enable') # ToDo: fix channel 7
@on_trait_change('c_enable0,c_enable1,c_enable2,c_enable3,c_enable4,c_enable5,c_enable6,sum_enable')
def _replot(self):
self.TracePlot = Plot(self.TraceData, width=500, height=500, resizable='hv')
self.TracePlot.legend.align = 'll'
n=0
if self.c_enable0:
self.TracePlot.plot(('t','y0'), type='line', color='blue', name='channel 0')
n+=1
if self.c_enable1:
self.TracePlot.plot(('t','y1'), type='line', color='red', name='channel 1')
n+=1
if self.c_enable2:
self.TracePlot.plot(('t','y2'), type='line', color='green', name='channel 2')
n+=1
if self.c_enable3:
self.TracePlot.plot(('t','y3'), type='line', color='black', name='channel 3')
n+=1
if self.c_enable4:
self.TracePlot.plot(('t','y4'), type='line', color='blue', name='channel 4')
n+=1
if self.c_enable5:
self.TracePlot.plot(('t','y5'), type='line', color='red', name='channel 5')
n+=1
if self.c_enable6:
self.TracePlot.plot(('t','y6'), type='line', color='green', name='channel 6')
n+=1
#if self.c_enable7:
# self.TracePlot.plot(('t','y7'), type='line', color='black', name='channel 7')
if self.sum_enable:
self.TracePlot.plot(('t','y8'), type='line', color='black', name='sum c0 + c1')
n+=1
if n > 1:
self.TracePlot.legend.visible = True
else:
self.TracePlot.legend.visible = False
def _run(self):
"""Acquire Count Trace"""
while True:
threading.current_thread().stop_request.wait(self.RefreshRate)
if threading.current_thread().stop_request.isSet():
break
self.C0 = self._counter0.getData() / self.SecondsPerPoint
self.C1 = self._counter1.getData() / self.SecondsPerPoint
self.C2 = self._counter2.getData() / self.SecondsPerPoint
self.C3 = self._counter3.getData() / self.SecondsPerPoint
self.C4 = self._counter4.getData() / self.SecondsPerPoint
self.C5 = self._counter5.getData() / self.SecondsPerPoint
self.C6 = self._counter6.getData() / self.SecondsPerPoint
#self.C7 = self._counter7.getData() / self.SecondsPerPoint
self.C0C1 = self.C0 + self.C1
traits_view = View( HGroup(Item('TracePlot', editor=ComponentEditor(), show_label=False),
#VGroup(Item('c_enable0'),Item('c_enable1'),Item('c_enable2'),Item('c_enable3'),Item('c_enable4'),Item('c_enable5'),Item('c_enable6'),Item('c_enable7'),Item('sum_enable'))
VGroup(Item('c_enable0'),Item('c_enable1'),Item('c_enable2'),Item('c_enable3'),Item('c_enable4'),Item('c_enable5'),Item('c_enable6'),Item('sum_enable'))
),
Item('TraceLength'),
Item ('SecondsPerPoint'),
Item ('RefreshRate'),
title='Counter', width=800, height=600, buttons=[], resizable=True,
handler=StartThreadHandler
)
if __name__=='__main__':
import logging
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
from tools.emod import JobManager
JobManager().start()
p = PhotonTimeTrace()
p.edit_traits()
| Python |
"""
This code is currently broken
small changes are required to adapt it to the new pulsed measurements (without hardware API).
See rabi.py as example.
"""
class PulseCal( Pulsed ):
"""Pulse Calibration."""
frequency = Range(low=1, high=20e9, value=2.8705e9, desc='microwave frequency', label='frequency [Hz]', mode='text', auto_set=False, enter_set=True)
power = Range(low=-100., high=25., value=-20, desc='microwave power', label='power [dBm]', mode='text', auto_set=False, enter_set=True)
switch = Enum( 'mw_x', 'mw_y', desc='switch to use for microwave pulses', label='switch', editor=EnumEditor(cols=3, values={'mw_x':'1:X', 'mw_y':'2:Y'}) )
laser = Range(low=1., high=100000., value=3000., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True)
wait = Range(low=1., high=100000., value=1000., desc='wait [ns]', label='wait [ns]', mode='text', auto_set=False, enter_set=True)
pulse = Range(low=1., high=100000., value=1000., desc='Length of the Pulse that is Calibrated', label='pulse [ns]', mode='text', auto_set=False, enter_set=True)
delay = Range(low=1., high=100000., value=100., desc='Delay between two pulses', label='delay [ns]', mode='text', auto_set=False, enter_set=True)
N = Range(low=0, high=100, value=6, desc='Maximum Number of pulses', label='N', mode='text', auto_set=False, enter_set=True)
def start_up(self):
PulseGenerator().Night()
Microwave().setOutput(self.power, self.frequency)
def shut_down(self):
PulseGenerator().Light()
Microwave().setOutput(None, self.frequency)
def generate_sequence(self):
mw = self.switch
laser = self.laser
wait = self.wait
delay = self.delay
pulse = self.pulse
N = self.N
sequence = []
for i in range(N):
sequence += i * [ ([mw],pulse), ([],delay) ] + [ (['detect','aom'],laser), ([],wait) ]
sequence += [ (['sequence'],100) ]
return sequence
get_set_items = Pulsed.get_set_items + ['frequency','power','laser','wait','pulse','delay','N','switch']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time',format_str='%.f'),
Item('stop_counts'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),
Item('switch', style='custom',)
),
HGroup(Item('pulse', width=-80, enabled_when='state != "run"'),
Item('delay', width=-80, enabled_when='state != "run"'),
Item('N', width=-80, enabled_when='state != "run"'),
Item('stop_time'),),
label='parameter'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'
),
),
),
title='Pulse Calibration',
)
class Pi2PiCal( Pulsed ):
"""Pulse Calibration with initial and final pi/2_x pulses, pi_x and pi_y pulse sequences and bright / dark reference."""
frequency = Range(low=1, high=20e9, value=2.8705e9, desc='microwave frequency', label='frequency [Hz]', mode='text', auto_set=False, enter_set=True)
power = Range(low=-100., high=25., value=-20, desc='microwave power', label='power [dBm]', mode='text', auto_set=False, enter_set=True)
laser = Range(low=1., high=100000., value=3000., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True)
wait = Range(low=1., high=100000., value=1000., desc='wait [ns]', label='wait [ns]', mode='text', auto_set=False, enter_set=True)
t_pi2_x = Range(low=0., high=100000., value=1000., desc='pi/2 pulse length (x)', label='pi/2 x [ns]', mode='text', auto_set=False, enter_set=True)
t_pi_y = Range(low=1., high=100000., value=1000., desc='pi pulse length (y)', label='pi y [ns]', mode='text', auto_set=False, enter_set=True)
t_pi_x = Range(low=1., high=100000., value=1000., desc='pi pulse length (x)', label='pi x [ns]', mode='text', auto_set=False, enter_set=True)
delay = Range(low=1., high=100000., value=100., desc='Delay between two pulses', label='delay [ns]', mode='text', auto_set=False, enter_set=True)
n_pi = Range(low=0, high=100, value=10, desc='number of pi pulses', label='n pi', mode='text', auto_set=False, enter_set=True)
n_ref = Range(low=1, high=100, value=10, desc='number of reference pulses', label='n ref', mode='text', auto_set=False, enter_set=True)
def start_up(self):
PulseGenerator().Night()
Microwave().setOutput(self.power, self.frequency)
def shut_down(self):
PulseGenerator().Light()
Microwave().setOutput(None, self.frequency)
def generate_sequence(self):
# parameters
laser = self.laser
wait = self.wait
t_pi2_x = self.t_pi2_x
t_pi_y = self.t_pi_y
t_pi_x = self.t_pi_x
n_pi = self.n_pi
n_ref = self.n_ref
t = self.delay
sequence = []
# first sequence
sequence += [ (['detect','aom'],laser), ([],wait) ]
for n in range(n_pi+1):
sequence += [ (['mw_x'],t_pi2_x), ([],t) ]
sequence += n * [ (['mw_x'],t_pi_x), ([],2*t) ]
sequence += [ (['detect','aom'],laser), ([],wait) ]
sequence += [ (['mw_x'],t_pi2_x), ([],t) ]
sequence += n * [ (['mw_x'],t_pi_x), ([],2*t) ]
sequence += [ (['mw_x'],t_pi2_x), ([],t) ]
sequence += [ (['detect','aom'],laser), ([],wait) ]
# second sequence
sequence += [ (['detect','aom'],laser), ([],wait) ]
for n in range(n_pi+1):
sequence += [ (['mw_x'],t_pi2_x), ([],t) ]
sequence += n * [ (['mw_y'],t_pi_y), ([],2*t) ]
sequence += [ (['detect','aom'],laser), ([],wait) ]
sequence += [ (['mw_x'],t_pi2_x), ([],t) ]
sequence += n * [ (['mw_y'],t_pi_y), ([],2*t) ]
sequence += [ (['mw_x'],t_pi2_x), ([],t) ]
sequence += [ (['detect','aom'],laser), ([],wait) ]
# bright state reference
sequence += n_ref * [ (['detect','aom'],laser), ([],wait) ]
# dark state reference
sequence += n_ref * [ (['mw_y'],t_pi_y), (['detect','aom'],laser), ([],wait) ]
# start trigger
sequence += [ (['sequence'],100) ]
return sequence
get_set_items = Pulsed.get_set_items + ['frequency','power','laser','wait','t_pi2_x','t_pi_x','t_pi_y','delay','n_pi','n_ref']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time',format_str='%.f'),
Item('stop_counts'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),),
HGroup(Item('t_pi2_x', width=-80, enabled_when='state != "run"'),
Item('t_pi_y', width=-80, enabled_when='state != "run"'),
Item('t_pi_x', width=-80, enabled_when='state != "run"'),),
HGroup(Item('delay', width=-80, enabled_when='state != "run"'),
Item('n_pi', width=-80, enabled_when='state != "run"'),
Item('n_ref', width=-80, enabled_when='state != "run"'),
Item('stop_time'),),
label='manipulation'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='detection'
),
),
),
title='Pi/2 Pi Calibration',
)
class Test( Pulsed ):
"""Test sequence."""
frequency = Range(low=1, high=20e9, value=2.8705e9, desc='microwave frequency', label='frequency [Hz]', mode='text', auto_set=False, enter_set=True)
power = Range(low=-100., high=25., value=-20, desc='microwave power', label='power [dBm]', mode='text', auto_set=False, enter_set=True)
laser = Range(low=1., high=100000., value=3000., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True)
wait = Range(low=1., high=100000., value=1000., desc='wait [ns]', label='wait [ns]', mode='text', auto_set=False, enter_set=True)
t_pi2_x = Range(low=1., high=100000., value=1000., desc='pi/2 pulse length (x)', label='pi/2 x [ns]', mode='text', auto_set=False, enter_set=True)
t_pi_x = Range(low=1., high=100000., value=1000., desc='pi pulse length (x)', label='pi x [ns]', mode='text', auto_set=False, enter_set=True)
n = Range(low=0, high=100, value=10, desc='number of pulses', label='n', mode='text', auto_set=False, enter_set=True)
def start_up(self):
PulseGenerator().Night()
Microwave().setOutput(self.power, self.frequency)
def shut_down(self):
PulseGenerator().Light()
Microwave().setOutput(None, self.frequency)
def generate_sequence(self):
# parameters
laser = self.laser
wait = self.wait
t_pi2_x = self.t_pi2_x
t_pi_x = self.t_pi_x
n = self.n
# start trigger
sequence = [ (['sequence'],100) ]
# three sequence
sequence += n * [ (['detect','aom'],laser), ([],wait) ]
sequence += n * [ (['mw_x'],t_pi_x), (['detect','aom'],laser), ([],wait) ]
sequence += n * [ (['mw_x'],t_pi2_x), (['detect','aom'],laser), ([],wait) ]
return sequence
get_set_items = Pulsed.get_set_items + ['frequency','power','laser','wait','t_pi2_x','t_pi_x','n']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),),
HGroup(Item('t_pi2_x', width=-80, enabled_when='state != "run"'),
Item('t_pi_x', width=-80, enabled_when='state != "run"'),
Item('n', width=-80, enabled_when='state != "run"'),),
label='manipulation'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='detection'
),
),
),
title='Test bright, dark and pi/2 reproducability',
)
class TestBright( Pulsed ):
"""Test sequence."""
laser = Range(low=1., high=100000., value=3000., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True)
wait = Range(low=1., high=100000., value=1000., desc='wait [ns]', label='wait [ns]', mode='text', auto_set=False, enter_set=True)
n = Range(low=0, high=100, value=10, desc='number of pulses', label='n', mode='text', auto_set=False, enter_set=True)
def start_up(self):
PulseGenerator().Night()
def shut_down(self):
PulseGenerator().Light()
def generate_sequence(self):
# parameters
laser = self.laser
wait = self.wait
n = self.n
sequence = [ (['sequence'],100) ] + n * [ (['detect','aom'],laser), ([],wait) ]
return sequence
get_set_items = Pulsed.get_set_items + ['laser','wait','n']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
),
Tabbed(VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('n', width=-80, enabled_when='state != "run"'),),
label='manipulation'),
VGroup(HGroup(Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='detection'
),
),
),
title='Bright state detection',
)
class CPMG3pi2( Rabi ):
"""
Defines a CPMG measurement with both pi/2 and 3pi/2 readout pulse,
using a second microwave switch for 90 degree phase shifted pi pulses.
Includes also bright (no pulse) and dark (pi_y pulse) reference points.
"""
t_pi2_x = Range(low=1., high=100000., value=1000., desc='pi/2 pulse length (x)', label='pi/2 x [ns]', mode='text', auto_set=False, enter_set=True)
t_pi_y = Range(low=1., high=100000., value=1000., desc='pi pulse length (y)', label='pi y [ns]', mode='text', auto_set=False, enter_set=True)
t_3pi2_x = Range(low=1., high=100000., value=1000., desc='3pi/2 pulse length (x)', label='3pi/2 x [ns]', mode='text', auto_set=False, enter_set=True)
n_pi = Range(low=1, high=100, value=5, desc='number of pi pulses', label='n pi', mode='text', auto_set=False, enter_set=True)
n_ref = Range(low=1, high=100, value=10, desc='number of reference pulses', label='n ref', mode='text', auto_set=False, enter_set=True)
def generate_sequence(self):
tau = self.tau
laser = self.laser
wait = self.wait
t_pi2_x = self.t_pi2_x
t_pi_y = self.t_pi_y
t_3pi2_x = self.t_3pi2_x
n_pi = self.n_pi
n_ref = self.n_ref
sequence = []
for t in tau:
sequence += [ (['mw_x'],t_pi2_x), ([],t/float(2*n_pi)) ]
sequence += (n_pi-1) * [ (['mw_y'],t_pi_y), ([],t/float(n_pi)) ]
sequence += [ (['mw_y'],t_pi_y), ([],t/float(2*n_pi)) ]
sequence += [ (['mw_x'],t_pi2_x) ]
sequence += [ (['detect','aom'],laser), ([],wait) ]
for t in tau:
sequence += [ (['mw_x'],t_pi2_x), ([],t/float(2*n_pi)) ]
sequence += (n_pi-1) * [ (['mw_y'],t_pi_y), ([],t/float(n_pi)) ]
sequence += [ (['mw_y'],t_pi_y), ([],t/float(2*n_pi)) ]
sequence += [ (['mw_x'],t_3pi2_x) ]
sequence += [ (['detect','aom'],laser), ([],wait) ]
sequence += n_ref * [ (['detect','aom'],laser), ([],wait) ]
sequence += n_ref * [ (['mw_y'],t_pi_y), (['detect','aom'],laser), ([],wait) ]
sequence += [ (['sequence'],100) ]
return sequence
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time',format_str='%.f'),
Item('stop_counts'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),),
HGroup(Item('t_pi2_x', width=-80, enabled_when='state != "run"'),
Item('t_pi_y', width=-80, enabled_when='state != "run"'),
Item('t_3pi2_x', width=-80, enabled_when='state != "run"'),
Item('n_pi', width=-80, enabled_when='state != "run"'),
Item('n_ref', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='parameter'
),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'
),
),
),
title='CPMG Measurement with both pi/2 and 3pi/2 readout pulse',
)
get_set_items = Rabi.get_set_items + ['t_pi2_x','t_pi_y','t_3pi2_x','n_pi','n_ref']
class CPMG( Rabi ):
"""Defines a basic CPMG measurement with a single sequence and bright / dark reference points."""
t_pi2_x = Range(low=1., high=100000., value=1000., desc='pi/2 x pulse length', label='pi/2 x [ns]', mode='text', auto_set=False, enter_set=True)
t_pi_y = Range(low=1., high=100000., value=1000., desc='pi y pulse length', label='pi y [ns]', mode='text', auto_set=False, enter_set=True)
n_pi = Range(low=1, high=100, value=5, desc='number of pi pulses', label='n pi', mode='text', auto_set=False, enter_set=True)
n_ref = Range(low=1, high=100, value=10, desc='number of reference pulses', label='n ref', mode='text', auto_set=False, enter_set=True)
def generate_sequence(self):
tau = self.tau
laser = self.laser
wait = self.wait
t_pi2_x = self.t_pi2_x
t_pi_y = self.t_pi_y
n_pi = self.n_pi
n_ref = self.n_ref
sequence = []
for t in tau:
sequence += [ (['mw_x'],t_pi2_x), ([],t/float(2*n_pi)) ]
sequence += (n_pi-1) * [ (['mw_y'],t_pi_y), ([],t/float(n_pi)) ]
sequence += [ (['mw_y'],t_pi_y), ([],t/float(2*n_pi)) ]
sequence += [ (['mw_x'],t_pi2_x) ]
sequence += [ (['detect','aom'],laser), ([],wait) ]
sequence += n_ref * [ (['detect','aom'],laser), ([],wait) ]
sequence += n_ref * [ (['mw_y'],t_pi_y), (['detect','aom'],laser), ([],wait) ]
sequence += [ (['sequence'],100) ]
return sequence
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time',format_str='%.f'),
Item('stop_counts'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),),
HGroup(Item('t_pi2_x', width=-80, enabled_when='state != "run"'),
Item('t_pi_y', width=-80, enabled_when='state != "run"'),
Item('n_pi', width=-80, enabled_when='state != "run"'),
Item('n_ref', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='parameter'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'),
),
),
title='Basic CPMG Measurement with pi/2 pulse on B and pi pulses on A',
)
get_set_items = Rabi.get_set_items + ['t_pi2_x','t_pi_y','n_pi','n_ref']
class CPMGxy( Rabi ):
"""
Defines a CPMG measurement with both pi_x and pi_y pulses.
Includes also bright (no pulse) and dark (pi_y pulse) reference points.
"""
t_pi2_x = Range(low=1., high=100000., value=1000., desc='pi/2 pulse length (x)', label='pi/2 x [ns]', mode='text', auto_set=False, enter_set=True)
t_pi_x = Range(low=1., high=100000., value=1000., desc='pi pulse length (x)', label='pi x [ns]', mode='text', auto_set=False, enter_set=True)
t_pi_y = Range(low=1., high=100000., value=1000., desc='pi pulse length (y, 90 degree)', label='pi y [ns]', mode='text', auto_set=False, enter_set=True)
n_pi = Range(low=1, high=100, value=5, desc='number of pi pulses', label='n pi', mode='text', auto_set=False, enter_set=True)
n_ref = Range(low=1, high=100, value=10, desc='number of reference pulses', label='n ref', mode='text', auto_set=False, enter_set=True)
def generate_sequence(self):
tau = self.tau
laser = self.laser
wait = self.wait
t_pi2_x = self.t_pi2_x
t_pi_x = self.t_pi_x
t_pi_y = self.t_pi_y
n_pi = self.n_pi
n_ref = self.n_ref
sequence = []
for t in tau:
sequence += [ (['mw_x'],t_pi2_x), ([],t/float(2*n_pi)) ]
sequence += (n_pi-1) * [ (['mw_x'],t_pi_x), ([],t/float(n_pi)) ]
sequence += [ (['mw_x'],t_pi_x), ([],t/float(2*n_pi)) ]
sequence += [ (['mw_x'],t_pi2_x) ]
sequence += [ (['detect','aom'],laser), ([],wait) ]
for t in tau:
sequence += [ (['mw_x'],t_pi2_x), ([],t/float(2*n_pi)) ]
sequence += (n_pi-1) * [ (['mw_y'],t_pi_y), ([],t/float(n_pi)) ]
sequence += [ (['mw_y'],t_pi_y), ([],t/float(2*n_pi)) ]
sequence += [ (['mw_x'],t_pi2_x) ]
sequence += [ (['detect','aom'],laser), ([],wait) ]
sequence += n_ref * [ (['detect','aom'],laser), ([],wait) ]
sequence += n_ref * [ (['mw_y'],t_pi_y), (['detect','aom'],laser), ([],wait) ]
sequence += [ (['sequence'],100) ]
return sequence
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time',format_str='%.f'),
Item('stop_counts'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),),
HGroup(Item('t_pi2_x', width=-80, enabled_when='state != "run"'),
Item('t_pi_x', width=-80, enabled_when='state != "run"'),
Item('t_pi_y', width=-80, enabled_when='state != "run"'),
Item('n_pi', width=-80, enabled_when='state != "run"'),
Item('n_ref', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='parameter'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'),
),
),
title='CPMG Measurement with both pix and piys pulses',
)
get_set_items = Rabi.get_set_items + ['t_pi2_x','t_pi_x','t_pi_y','n_pi','n_ref']
class PulsedToolTauRef( PulsedToolTau ):
"""
Analysis of a pulsed measurement with a 'tau' as index-data.
and bright / dark reference points at the end of the sequence.
"""
# overwrite the line_plot such that the bright and dark state reference lines are plotted
def _create_line_plot(self):
line_data = ArrayPlotData(index=np.array((0,1)),
spin_state=np.array((0,0)),
bright=np.array((1,1)),
dark=np.array((0,0)))
plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=36)
plot.plot(('index','spin_state'), color='blue', name='pulsed')
plot.plot(('index','bright'), color='red', name='bright')
plot.plot(('index','dark'), color='black', name='dark')
plot.index_axis.title = 'time [micro s]'
plot.value_axis.title = 'spin state'
self.line_data = line_data
self.line_plot = plot
# overwrite this one to provide splitting up of spin_state array and setting of bright and dark state data
def _update_line_plot_value(self):
y = self.spin_state
n_ref = self.measurement.n_ref
n = len(y)-2*n_ref
self.line_data.set_data('spin_state',y[:n])
self.line_data.set_data('bright',np.mean(y[n:n+n_ref])*np.ones(n))
self.line_data.set_data('dark',np.mean(y[n+n_ref:n+2*n_ref])*np.ones(n))
class PulsedToolDoubleTauRef( PulsedToolTau ):
"""
Analysis of a pulsed measurement with a 'tau' as index-data,
two subsequent pulsed sequences and bright / dark reference
measurement at the end of the sequence.
"""
measurement = Instance( mp.CPMG3pi2, factory=mp.CPMG3pi2 )
# overwrite __init__ such that change of 'run_sum' causes plot update
def __init__(self):
super(PulsedToolDoubleTauRef, self).__init__()
self.on_trait_change(self._update_line_plot_value, 'run_sum') # ToDo: fix this
# overwrite the line_plot such that the bright and dark state
# as well as reference lines are plotted
def _create_line_plot(self):
line_data = ArrayPlotData(index=np.array((0,1)),
first=np.array((0,0)),
second=np.array((0,0)),
bright=np.array((1,1)),
dark=np.array((0,0)))
plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=36)
plot.plot(('index','first'), color='blue', name='first')
plot.plot(('index','second'), color='green', name='second')
plot.plot(('index','bright'), color='red', name='bright')
plot.plot(('index','dark'), color='black', name='dark')
plot.index_axis.title = 'time [micro s]'
plot.value_axis.title = 'spin state'
self.line_data = line_data
self.line_plot = plot
# overwrite this one to provide splitting up of spin_state array
# and setting of bright and dark state data
def _update_line_plot_value(self):
y = self.spin_state
n_ref = self.measurement.n_ref
n = len(y)/2-n_ref
first = y[:n]
second = y[n:2*n]
bright = y[-2*n_ref:-n_ref].mean()*self.run_sum
dark = y[-n_ref:].mean()*self.run_sum
if self.run_sum > 1:
first = run_sum(first, self.run_sum)
second = run_sum(second, self.run_sum)
try:
self.line_data.set_data('first',first)
self.line_data.set_data('second',second)
self.line_data.set_data('bright',bright*np.ones(n))
self.line_data.set_data('dark',dark*np.ones(n))
except:
logging.getLogger().debug('Could not set data for spin_state plots.')
class PulsedToolDoubleRef( PulsedTool ):
"""
Analysis of a pulsed measurement with two
sequences and bright / dark reference
measurement at the end of the sequence.
"""
measurement = Instance( mp.Pulsed, factory=mp.Pi2PiCal )
# overwrite the line_plot such that the bright and dark state reference lines are plotted
def _create_line_plot(self):
line_data = ArrayPlotData(index=np.array((0,1)),
first=np.array((0,0)),
second=np.array((0,0)),
bright=np.array((1,1)),
dark=np.array((0,0)))
plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=36)
plot.plot(('index','first'), color='blue', name='first')
plot.plot(('index','second'), color='green', name='second')
plot.plot(('index','bright'), color='red', name='bright')
plot.plot(('index','dark'), color='black', name='dark')
plot.index_axis.title = 'pulse #'
plot.value_axis.title = 'spin state'
self.line_data = line_data
self.line_plot = plot
# overwrite this one to provide splitting up of spin_state array and setting of bright and dark state data
def _update_line_plot_value(self):
y = self.spin_state
n_ref = self.measurement.n_ref
n = len(y)/2-n_ref
old_index = self.line_data.get_data('index')
if old_index is not None and len(old_index) != n:
self.line_data.set_data('index',np.arange(n))
self.line_data.set_data('first',y[:n])
self.line_data.set_data('second',y[n:2*n])
self.line_data.set_data('bright',np.mean(y[2*n:2*n+n_ref])*np.ones(n))
self.line_data.set_data('dark',np.mean(y[2*n+n_ref:])*np.ones(n))
class PulseCalTool( PulsedTool ):
"""Provides calculation of RMS from PulseCal measurement."""
measurement = Instance( mp.PulseCal, factory=mp.PulseCal )
rms = Float()
get_set_items = PulsedTool.get_set_items + ['rms']
traits_view = View(VGroup(Item(name='measurement', style='custom', show_label=False),
HGroup(Item('integration_width'),
Item('position_signal'),
Item('position_normalize'),
Item('run_sum'),
Item('rms', style='readonly', format_str='%.1f'),
),
VSplit(Item('matrix_plot', show_label=False, width=500, height=300, resizable=True),
Item('line_plot', show_label=False, width=500, height=300, resizable=True),
Item('pulse_plot', show_label=False, width=500, height=300, resizable=True),
),
),
title='Pulse Calibration Analysis',
menubar = menubar,
buttons=[], resizable=True)
def __init__(self, **kwargs):
super(PulseCalTool, self).__init__(**kwargs)
self.on_trait_change(self._update_fit, 'spin_state', dispatch='ui')
def _update_fit(self, s):
"""compute relative rms"""
m = s.mean()
rms = 2*(np.sum((s-m)**2)/len(s))**0.5/float(s.max()-s.min())
self.rms = rms
self.line_plot.overlays[0].text = 'rms: %.2f'%rms
# overwrite the line_plot such that the x-axis label is time
def _create_line_plot(self):
line_data = ArrayPlotData(index=np.array((0,1)), spin_state=np.array((0,0)),)
plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=36)
plot.plot(('index','spin_state'), color='blue', name='spin_state')
plot.plot(('index','spin_state'), type='scatter', name='pulses')
plot.index_axis.title = 'pulse #'
plot.value_axis.title = 'spin state'
plot.overlays.insert(0, PlotLabel(text='', hjustify='left', vjustify='bottom', position=[70,40]) )
self.line_data = line_data
self.line_plot = plot
| Python |
"""
This code is currently broken
small changes are required to adapt it to the new pulsed measurements (without hardware API).
See rabi.py as example.
"""
class FID3pi2( Rabi ):
"""Defines a FID measurement with both pi/2 and 3pi/2 readout pulse."""
t_pi2 = Range(low=1., high=100000., value=1000., desc='pi/2 pulse length', label='pi/2 [ns]', mode='text', auto_set=False, enter_set=True)
t_3pi2 = Range(low=1., high=100000., value=1000., desc='3pi/2 pulse length', label='3pi/2 [ns]', mode='text', auto_set=False, enter_set=True)
def generate_sequence(self):
tau = self.tau
laser = self.laser
wait = self.wait
t_pi2 = self.t_pi2
t_3pi2 = self.t_3pi2
sequence = []
for t in tau:
sequence.append( (['mw' ], t_pi2 ) )
sequence.append( ([ ], t ) )
sequence.append( (['mw' ], t_pi2 ) )
sequence.append( (['detect','aom'], laser ) )
sequence.append( ([ ], wait ) )
for t in tau:
sequence.append( (['mw' ], t_pi2 ) )
sequence.append( ([ ], t ) )
sequence.append( (['mw' ], t_3pi2 ) )
sequence.append( (['detect','aom'], laser ) )
sequence.append( ([ ], wait ) )
sequence.append( (['sequence'], 100 ) )
return sequence
#items to be saved
get_set_items = Rabi.get_set_items + ['t_pi2','t_3pi2']
# gui elements
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time'),
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),
Item('t_pi2', width=-80, enabled_when='state != "run"'),
Item('t_3pi2', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='parameter'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'),
),
),
title='FID3pi2',
)
class HardDQTFID( Rabi ):
"""Defines a Double Quantum Transition FID Measurement with pi-tau-pi."""
t_pi = Range(low=1., high=100000., value=1000., desc='pi pulse length', label='pi [ns]', mode='text', auto_set=False, enter_set=True)
def generate_sequence(self):
tau = self.tau
laser = self.laser
wait = self.wait
t_pi = self.t_pi
sequence = []
for t in tau:
sequence.append( (['mw' ], t_pi ) )
sequence.append( ([ ], t ) )
sequence.append( (['mw' ], t_pi ) )
sequence.append( (['detect','aom'], laser ) )
sequence.append( ([ ], wait ) )
sequence.append( (['sequence'], 100 ) )
return sequence
get_set_items = Rabi.get_set_items + ['t_pi']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time'),
),
Tabbed(VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),
Item('t_pi', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='parameter'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'),
),
),
title='HardDQTFID',
)
"""
class HardDQTFIDTauMod( HardDQTFID ):
tau_gen = Code("tg = np.arange(self.tau_begin, self.tau_end, self.tau_delta)\ntf = np.arange(0., 500., 50.)\ntau = np.array(())\nfor t0 in tg:\n tau=np.append(tau,tf+t0)\nself.tau=tau")
def start_up(self):
# this needs to come first, because Pulsed.start_up() will
# generate the sequence and thereby call the generate_sequence method of RabiMeasurement
# and this method needs the correct tau
exec self.tau_gen
Pulsed.start_up(self)
PulseGenerator().Night()
Microwave().setOutput(self.power, self.frequency)
traits_view = View( VGroup( HGroup(Item('state', show_label=False, style='custom',
editor=EnumEditor(values={'idle':'1:idle','run':'2:run',},cols=2),),),
Tabbed( VGroup(HGroup(Item('frequency', width=-80, enabled_when='state != "run"'),
Item('power', width=-80, enabled_when='state != "run"'),
Item('t_pi', width=-80, enabled_when='state != "run"'),),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),),
label='parameter'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'),
VGroup(HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),),
Item('tau_gen', width=-200, height=-200, enabled_when='state != "run"'),
label='taumod'),
),
),
title='HardDQTFIDTauMod',
)
"""
class DQTFID3pi2( Pulsed ):
"""Defines a pulsed measurement with two microwave transitions and FID sequence including 3pi2 readout pulses.TODO: untested"""
frequency_a = Range(low=1, high=20e9, value=2.8705e9, desc='microwave frequency A', label='frequency A [Hz]', mode='text', auto_set=False, enter_set=True)
frequency_b = Range(low=1, high=20e9, value=2.8705e9, desc='microwave frequency B', label='frequency B [Hz]', mode='text', auto_set=False, enter_set=True)
power_a = Range(low=-100., high=25., value=-20, desc='microwave power A', label='power A [dBm]', mode='text', auto_set=False, enter_set=True)
power_b = Range(low=-100., high=25., value=-20, desc='microwave power B', label='power B [dBm]', mode='text', auto_set=False, enter_set=True)
tau_begin = Range(low=1., high=1e8, value=10.0, desc='tau begin [ns]', label='tau begin [ns]', mode='text', auto_set=False, enter_set=True)
tau_end = Range(low=1., high=1e8, value=500., desc='tau end [ns]', label='tau end [ns]', mode='text', auto_set=False, enter_set=True)
tau_delta = Range(low=1., high=1e6, value=50., desc='delta tau [ns]', label='delta tau [ns]', mode='text', auto_set=False, enter_set=True)
laser = Range(low=1., high=100000., value=3000., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True)
wait = Range(low=1., high=100000., value=1000., desc='wait [ns]', label='wait [ns]', mode='text', auto_set=False, enter_set=True)
t_pi2_a = Range(low=1., high=100000., value=1000., desc='pi/2 pulse length A', label='pi/2 A [ns]', mode='text', auto_set=False, enter_set=True)
t_pi_a = Range(low=1., high=100000., value=1000., desc='pi pulse length A', label='pi A [ns]', mode='text', auto_set=False, enter_set=True)
t_3pi2_a = Range(low=1., high=100000., value=1000., desc='3pi/2 pulse length A', label='3pi/2 A [ns]', mode='text', auto_set=False, enter_set=True)
t_pi2_b = Range(low=1., high=100000., value=1000., desc='pi/2 pulse length B', label='pi/2 B [ns]', mode='text', auto_set=False, enter_set=True)
t_pi_b = Range(low=1., high=100000., value=1000., desc='pi pulse length B', label='pi B [ns]', mode='text', auto_set=False, enter_set=True)
t_3pi2_b = Range(low=1., high=100000., value=1000., desc='3pi/2 pulse length B', label='3pi/2 B [ns]', mode='text', auto_set=False, enter_set=True)
tau = Array( value=np.array((0.,1.)) )
def start_up(self):
self.tau = np.arange(self.tau_begin, self.tau_end, self.tau_delta)
PulseGenerator().Night()
MicrowaveA().setOutput(self.power_a, self.frequency_a)
MicrowaveB().setOutput(self.power_b, self.frequency_b)
def shut_down(self):
PulseGenerator().Light()
MicrowaveA().setOutput(None, self.frequency_a)
MicrowaveB().setOutput(None, self.frequency_b)
def generate_sequence(self):
tau = self.tau
laser = self.laser
wait = self.wait
t_pi2_a = self.t_pi2_a
t_pi_a = self.t_pi_a
t_3pi2_a = self.t_3pi2_a
t_pi2_b = self.t_pi2_b
t_pi_b = self.t_pi_b
t_3pi2_b = self.t_3pi2_b
sequence = []
for t in tau:
sequence.append( (['mw_a' ], t_pi2_a ) )
sequence.append( (['mw_b' ], t_pi_b ) )
sequence.append( ([ ], t ) )
sequence.append( (['mw_b' ], t_pi_b ) )
sequence.append( (['mw_a' ], t_pi2_a ) )
sequence.append( (['detect','aom'], laser ) )
sequence.append( ([ ], wait ) )
for t in tau:
sequence.append( (['mw_a' ], t_pi2_a ) )
sequence.append( (['mw_b' ], t_pi_b ) )
sequence.append( ([ ], t ) )
sequence.append( (['mw_b' ], t_pi_b ) )
sequence.append( (['mw_a' ], t_3pi2_a ) )
sequence.append( (['detect','aom'], laser ) )
sequence.append( ([ ], wait ) )
sequence.append( (['sequence'], 100 ) )
return sequence
get_set_items = Pulsed.get_set_items + ['frequency_a','frequency_b','power_a','power_b',
't_pi2_a', 't_pi_a', 't_3pi2_a', 't_pi2_b', 't_pi_b', 't_3pi2_b',
'tau_begin','tau_end','tau_delta','laser','wait','tau']
traits_view = View(VGroup(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
),
Tabbed(VGroup(HGroup(Item('frequency_a', width=-80, enabled_when='state != "run"'),
Item('power_a', width=-80, enabled_when='state != "run"'),
Item('t_pi2_a', width=-80, enabled_when='state != "run"'),
Item('t_pi_a', width=-80, enabled_when='state != "run"'),
Item('t_3pi2_a', width=-80, enabled_when='state != "run"'),
),
HGroup(Item('frequency_b', width=-80, enabled_when='state != "run"'),
Item('power_b', width=-80, enabled_when='state != "run"'),
Item('t_pi2_b', width=-80, enabled_when='state != "run"'),
Item('t_pi_b', width=-80, enabled_when='state != "run"'),
Item('t_3pi2_b', width=-80, enabled_when='state != "run"'),
),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
Item('stop_time'),),
label='parameter'),
VGroup(HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('wait', width=-80, enabled_when='state != "run"'),
Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),),
label='settings'),
),
),
title='DQTFID3pi2 Measurement',
)
| Python |
import numpy as np
from pulsed import PulsedTau, sequence_remove_zeros, sequence_union
from traits.api import Range, Tuple, Int, Float, Bool, Array, Instance, Enum, on_trait_change, Button
from traitsui.api import View, Item, Group, Tabbed, HGroup, VGroup, VSplit, EnumEditor, TextEditor
class Rabi( PulsedTau ):
"""Defines a Rabi measurement."""
frequency = Range(low=1, high=20e9, value=2.8705e9, desc='microwave frequency', label='frequency [Hz]', mode='text', auto_set=False, enter_set=True, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%e'))
power = Range(low=-100., high=25., value=-20, desc='microwave power', label='power [dBm]', mode='text', auto_set=False, enter_set=True)
laser = Float(default_value=3000., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True)
decay_init = Float(default_value=1000., desc='time to let the system decay after laser pulse [ns]', label='decay init [ns]', mode='text', auto_set=False, enter_set=True)
decay_read = Float(default_value=0., desc='time to let the system decay before laser pulse [ns]', label='decay read [ns]', mode='text', auto_set=False, enter_set=True)
aom_delay = Float(default_value=0., desc='If set to a value other than 0.0, the aom triggers are applied\nearlier by the specified value. Use with care!', label='aom delay [ns]', mode='text', auto_set=False, enter_set=True)
def __init__(self, pulse_generator, time_tagger, microwave, **kwargs):
super(Rabi, self).__init__(pulse_generator, time_tagger, **kwargs)
self.microwave = microwave
def start_up(self):
self.pulse_generator.Night()
self.microwave.setOutput(self.power, self.frequency)
def shut_down(self):
self.pulse_generator.Light()
self.microwave.setOutput(None, self.frequency)
def generate_sequence(self):
tau = self.tau
laser = self.laser
decay_init = self.decay_init
decay_read = self.decay_read
aom_delay = self.aom_delay
if aom_delay == 0.0:
sequence = [ (['aom'],laser) ]
for t in tau:
sequence += [ ([],decay_init), (['microwave'],t), ([],decay_read), (['detect','aom'],laser) ]
sequence += [ (['sequence'], 100) ]
sequence = sequence_remove_zeros(sequence)
else:
s1 = [ (['aom'],laser) ]
s2 = [ ([],aom_delay+laser) ]
for t in tau:
s1 += [ ([], decay_init+t+decay_read), (['aom'], laser) ]
s2 += [ ([], decay_init), (['microwave'],t), ([],decay_read), (['detect'],laser) ]
s2 += [ (['sequence'],100) ]
s1 = sequence_remove_zeros(s1)
s2 = sequence_remove_zeros(s2)
sequence = sequence_union(s1,s2)
return sequence
get_set_items = PulsedTau.get_set_items + ['frequency','power','laser','decay_init','decay_read','aom_delay']
traits_view = View(VGroup(HGroup(Item('submit_button', width=-60, show_label=False),
Item('remove_button', width=-60, show_label=False),
Item('resubmit_button', width=-60, show_label=False),
Item('priority', width=-30),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time',format_str='%.f'),
Item('stop_counts'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
Tabbed(VGroup(HGroup(Item('frequency', width=-120, enabled_when='state != "run"'),
Item('power', width=-60, enabled_when='state != "run"'),
Item('aom_delay', width=-80, enabled_when='state != "run"'),
),
HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('decay_init', width=-80, enabled_when='state != "run"'),
Item('decay_read', width=-80, enabled_when='state != "run"'),
),
HGroup(Item('tau_begin', width=-80, enabled_when='state != "run"'),
Item('tau_end', width=-80, enabled_when='state != "run"'),
Item('tau_delta', width=-80, enabled_when='state != "run"'),
),
label='stimulation'),
VGroup(HGroup(Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),
),
label='acquisition'),
VGroup(HGroup(Item('integration_width'),
Item('position_signal'),
Item('position_normalize'),
),
label='analysis'),
),
),
title='Rabi',
)
from analysis.pulsed import PulsedToolTau, FitToolTau
from analysis import fitting
class RabiTool( FitToolTau ):
"""
Analysis of a Rabi measurement.
"""
measurement = Instance( Rabi )
# fit results
contrast = Tuple((np.nan,np.nan), editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str=' %.1f+-%.1f %%'))
period = Tuple((np.nan,np.nan), editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str=' %.2f+-%.2f'))
q = Float(np.nan, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_func=lambda x:(' %.3f' if x >= 0.001 else ' %.2e')%x))
t_pi2 = Tuple((np.nan,np.nan), editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str=' %.2f+-%.2f'))
t_pi = Tuple((np.nan,np.nan), editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str=' %.2f+-%.2f'))
t_3pi2 = Tuple((np.nan,np.nan), editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str=' %.2f+-%.2f'))
# add fit results to the get_set_items
get_set_items = FitToolTau.get_set_items + ['contrast','period','t_pi2','t_pi','t_3pi2']
def _update_fit(self):
y = self.measurement.spin_state
try:
fit_result = fitting.fit_rabi( self.measurement.tau, y, y**0.5 )
except:
fit_result = (np.NaN*np.zeros(3), np.NaN*np.zeros((3,3)), np.NaN, np.NaN)
p, v, q, chisqr = fit_result
a, T, c = p
a_var, T_var, c_var = v.diagonal()
# compute some relevant parameters from fit result
contrast = 200*a/(c+a)
contrast_delta = 200./c**2*(a_var*c**2+c_var*a**2)**0.5
T_delta = abs(T_var)**0.5
pi2 = 0.25*T
pi = 0.5*T
threepi2 = 0.75*T
pi2_delta = 0.25*T_delta
pi_delta = 0.5*T_delta
threepi2_delta = 0.75*T_delta
# set respective attributes
self.q = q
self.period = T, T_delta
self.contrast = contrast, contrast_delta
self.t_pi2 = pi2, pi2_delta
self.t_pi = pi, pi_delta
self.t_3pi2 = threepi2, threepi2_delta
# create a summary of fit result as a text string
s = 'q: %.2e\n'%q
s += 'contrast: %.1f+-%.1f%%\n'%(contrast, contrast_delta)
s += 'period: %.2f+-%.2f ns\n'%(T, T_delta)
#s += 'pi/2: %.2f+-%.2f ns\n'%(pi2, pi2_delta)
#s += 'pi: %.2f+-%.2f ns\n'%(pi, pi_delta)
#s += '3pi/2: %.2f+-%.2f ns\n'%(threepi2, threepi2_delta)
self.fit_result = fit_result
self.text = s
def _on_fit_result_change(self, new):
if len(new) > 0 and new[0][0] is not np.NaN:
self.line_data.set_data('fit',fitting.Cosinus(*new[0])(self.measurement.tau))
traits_view = View(VGroup(VGroup(Item(name='measurement', style='custom', show_label=False),
VGroup(HGroup(Item('contrast', style='readonly', width=-100),
Item('period', style='readonly', width=-100),
Item('q', style='readonly', width=-100),
),
HGroup(Item('t_pi2', style='readonly', width=-100),
Item('t_pi', style='readonly', width=-100),
Item('t_3pi2', style='readonly', width=-100),
),
label='fit_result',
),
),
VSplit(Item('matrix_plot', show_label=False, width=500, height=-300, resizable=True),
Item('line_plot', show_label=False, width=500, height=-300, resizable=True),
Item('pulse_plot', show_label=False, width=500, height=-300, resizable=True),
),
),
title='Rabi Tool',
buttons=[],
resizable=True,
height=-640
)
class PulseExtractTool( PulsedToolTau ):
"""
Provides extraction of pulses from a Rabi measurement.
"""
period = Float()
contrast = Float()
t_pi2 = Array()
t_pi = Array()
t_3pi2 = Array()
t_2pi = Array()
# add fit results to the get_set_items
get_set_items = PulsedToolTau.get_set_items + ['contrast','period','t_pi2','t_pi','t_3pi2','t_2pi']
traits_view = View(VGroup(VGroup(Item(name='measurement', style='custom', show_label=False),
Group(VGroup(HGroup(Item('contrast', style='readonly', format_str='%.1f'),
Item('period', style='readonly'),
),
HGroup(Item('t_pi2', style='readonly'),
Item('t_pi', style='readonly'),
Item('t_3pi2', style='readonly'),
Item('t_2pi', style='readonly'),
),
label='fit_result',
),
VGroup(HGroup(Item('integration_width'),
Item('position_signal'),
Item('position_normalize'),
),
label='fit_parameter',
),
orientation='horizontal', layout='tabbed', springy=False,
),
),
VSplit(Item('matrix_plot', show_label=False, width=500, height=300, resizable=True),
Item('line_plot', show_label=False, width=500, height=300, resizable=True),
Item('pulse_plot', show_label=False, width=500, height=300, resizable=True),
),
),
title='Pulse Extraction',
buttons=[], resizable=True)
# overwrite __init__ to trigger update events
def __init__(self, **kwargs):
super(PulseExtractTool, self).__init__(**kwargs)
self.on_trait_change(self._update_fit, 'spin_state', dispatch='ui')
def _update_fit(self, y):
# try to extract pulses from spin_state and tau.
tau = self.measurement.tau
try:
f,r,p,tp=fitting.extract_pulses(y)
except:
logging.getLogger().debug('Failed to compute fit.')
f=[0]
r=[0]
p=[0]
tp=[0]
pi2 = tau[f]
pi = tau[p]
three_pi2 = tau[r]
two_pi = tau[tp]
# compute some relevant parameters from the result
mi = y.min()
ma = y.max()
contrast = 100*(ma-mi)/ma
# simple rough estimate of the period to avoid index out of range Error
T = 4*(pi[0]-pi2[0])
# set respective attributes
self.period = T
self.contrast = contrast
self.t_pi2 = pi2
self.t_pi = pi
self.t_3pi2 = three_pi2
self.t_2pi = two_pi
# create a summary of the result as a text string
s = 'contrast: %.1f\n'%contrast
s += 'period: %.2f ns\n'%T
# markers in the plot that show the result of the pulse extraction
self.line_data.set_data('pulse_indices',np.hstack((pi2, pi, three_pi2, two_pi))*1e-3)
self.line_data.set_data('pulse_values',np.hstack((y[f], y[p], y[r], y[tp])))
self.line_plot.overlays[0].text = s
# overwrite the line_plot to include fit and text label
def _create_line_plot(self):
line_data = ArrayPlotData(index=np.array((0,1)),
spin_state=np.array((0,0)),
pulse_indices=np.array((0,0)),
pulse_values=np.array((0,0)))
plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=36)
plot.plot(('index','spin_state'), color='blue', name='spin_state')
plot.plot(('pulse_indices','pulse_values'),
type='scatter',
marker='circle',
color='none',
outline_color='red',
line_width=1.0,
name='pulses')
plot.index_axis.title = 'time [micro s]'
plot.value_axis.title = 'spin state'
plot.overlays.insert(0, PlotLabel(text=self.label_text, hjustify='left', vjustify='bottom', position=[64,32]) )
self.line_data = line_data
self.line_plot = plot
if __name__ == '__main__':
import logging
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
from tools.emod import JobManager
JobManager().start()
from hardware.dummy import PulseGenerator, TimeTagger, Microwave
rabi = Rabi(PulseGenerator(), TimeTagger(), Microwave())
rabi.edit_traits()
| Python |
import numpy as np
import cPickle
# enthought library imports
from traits.api import SingletonHasTraits, HasTraits, Trait, Instance, Property, Int, Float, Range,\
Bool, Array, Str, Enum, Button, on_trait_change
from traitsui.api import View, Item, Group, HGroup, VGroup, Tabbed, EnumEditor, Action, Menu, MenuBar
from enable.api import ComponentEditor, Component
from chaco.api import Plot, ArrayPlotData
from tools.utility import GetSetItemsHandler, GetSetItemsMixin
import threading
import time
import logging
import hardware.api as ha
from tools.emod import FreeJob
class CounterTimeTrace( FreeJob, GetSetItemsMixin ):
trace_length = Range(low=10, high=10000, value=100, desc='Length of Count Trace', label='Trace Length')
seconds_per_point = Range(low=0.001, high=1, value=0.1, desc='Seconds per point [s]', label='Seconds per point [s]')
refresh_interval = Range(low=0.01, high=1, value=0.1, desc='Refresh interval [s]', label='Refresh interval [s]')
# trace data
C = Array()
T = Array()
trace_plot = Instance( Plot )
trace_data = Instance( ArrayPlotData )
def __init__(self, counter, **kwargs):
super(CounterTimeTrace, self).__init__(**kwargs)
self.counter=counter
self.on_trait_change(self.update_T, 'T', dispatch='ui')
self.on_trait_change(self.update_C, 'C', dispatch='ui')
def _C_default(self):
return np.zeros((self.trace_length,))
def _T_default(self):
return self.seconds_per_point*np.arange(self.trace_length)
def update_T(self):
self.trace_data.set_data('t', self.T)
def update_C(self):
self.trace_data.set_data('y', self.C)
def _trace_length_changed(self):
self.C = self._C_default()
self.T = self._T_default()
def _seconds_per_point_changed(self):
self.T = self._T_default()
def _trace_data_default(self):
return ArrayPlotData(t=self.T, y=self.C)
def _trace_plot_default(self):
plot = Plot(self.trace_data, width=500, height=500, resizable='hv')
plot.plot(('t','y'), type='line', color='blue')
return plot
def _run(self):
"""Acquire Count Trace"""
try:
self.state='run'
counter = self.counter(self.seconds_per_point, self.trace_length)
except Exception as e:
logging.getLogger().exception(e)
raise
else:
while True:
threading.current_thread().stop_request.wait(self.refresh_interval)
if threading.current_thread().stop_request.isSet():
break
try:
self.C = counter.getData() / self.seconds_per_point
except Exception as e:
logging.getLogger().exception(e)
raise
finally:
self.state='idle'
traits_view = View(VGroup(HGroup(Item('start_button', show_label=False),
Item('stop_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),),
Item('trace_plot', editor=ComponentEditor(), show_label=False),
HGroup(Item('trace_length'),
Item ('seconds_per_point'),
Item ('refresh_interval'),
),
),
title='Counter Time Trace', width=800, height=600, buttons=[], resizable=True,
handler=GetSetItemsHandler()
)
if __name__ == '__main__':
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
c = CounterTimeTrace()
c.edit_traits()
c.trace_length = 10
c.bin_width = 1.0
c.refresh_interval = 1.0
| Python |
import numpy as np
from threading import currentThread
import logging
import time
from traits.api import Range, Array, Instance, Enum, on_trait_change, Bool, Button, Float
from traitsui.api import View, Item, HGroup #, EnumEditor
from enable.api import ComponentEditor
from chaco.api import ArrayPlotData
from tools.emod import ManagedJob
from tools.utility import GetSetItemsMixin
from tools.chaco_addons import SavePlot as Plot, SaveTool
class Autocorrelation( ManagedJob, GetSetItemsMixin):
window_size = Range(low=1., high=10000., value=500., desc='window_size in the time domain [ns]', label='window_size', mode='text', auto_set=False, enter_set=True)
bin_width = Range(low=0.01, high=1000., value=1., desc='bin width [ns]', label='bin width', mode='text', auto_set=False, enter_set=True)
chan1 = Enum(0,1,2,3,4,5,6,7, desc="the trigger channel", label="Channel 1")
chan2 = Enum(0,1,2,3,4,5,6,7, desc="the signal channel", label="Channel 2")
normalize = Bool(False, desc="normalize autocorrelation", label="normalize")
counts = Array()
time_bins = Array()
keep_data = Bool(False) # helper variable to decide whether to keep existing data
resubmit_button = Button(label='resubmit', desc='Submits the measurement to the job manager. Tries to keep previously acquired data. Behaves like a normal submit if sequence or time bins have changed since previous run.')
run_time = Float(value=0.0, label='run time [s]')
stop_time = Range(low=1., value=np.inf, desc='Time after which the experiment stops by itself [s]', label='Stop time [s]', mode='text', auto_set=False, enter_set=True)
plot = Instance( Plot )
plot_data = Instance( ArrayPlotData )
get_set_items=['window_size', 'bin_width', 'chan1', 'chan2', 'normalize', 'counts', 'time_bins', 'norm_factor']
def __init__(self, time_tagger, **kwargs):
self.time_tagger = time_tagger
super(Autocorrelation, self).__init__(**kwargs)
self._create_plot()
def submit(self):
"""Submit the job to the JobManager."""
self.keep_data = False
self.run_time = 0.0
ManagedJob.submit(self)
def resubmit(self):
"""Submit the job to the JobManager."""
self.keep_data = True
ManagedJob.submit(self)
def _resubmit_button_fired(self):
"""React to start button. Submit the Job."""
self.resubmit()
@on_trait_change('chan1,chan2,window_size,bin_width')
def _create_threads(self):
self.p1 = self.time_tagger.Pulsed(int(np.round(self.window_size/self.bin_width)),int(np.round(self.bin_width*1000)),1,self.chan1,self.chan2)
self.p2 = self.time_tagger.Pulsed(int(np.round(self.window_size/self.bin_width)),int(np.round(self.bin_width*1000)),1,self.chan2,self.chan1)
self.run_time = 0.0
def _run(self):
"""Acquire data."""
try: # run the acquisition
self.state='run'
if self.run_time >= self.stop_time:
logging.getLogger().debug('Runtime larger than stop_time. Returning')
self.state='done'
return
n_bins = int(np.round(self.window_size/self.bin_width))
time_bins = self.bin_width*np.arange(-n_bins+1,n_bins)
if self.keep_data:
try:
self.p1.start()
self.p2.start()
except:
self._create_threads()
else:
self._create_threads()
start_time = time.time()
self.time_bins = time_bins
self.n_bins = n_bins
self.keep_data = True # when job manager stops and starts the job, data should be kept. Only new submission should clear data.
while self.run_time < self.stop_time:
data1 = self.p1.getData()
data2 = self.p2.getData()
current_time = time.time()
self.run_time += current_time - start_time
start_time = current_time
data = np.append(np.append(data1[0][-1:0:-1], max(data1[0][0],data2[0][0])),data2[0][1:])
self.counts = data
try:
self.norm_factor = self.run_time/(self.bin_width*1e-9*self.p1.getCounts()*self.p2.getCounts())
except:
self.norm_factor = 1.0
self.thread.stop_request.wait(1.0)
if self.thread.stop_request.isSet():
logging.getLogger().debug('Caught stop signal. Exiting.')
break
self.p1.stop()
self.p2.stop()
if self.run_time < self.stop_time:
self.state = 'idle'
else:
self.state='done'
except: # if anything fails, recover
logging.getLogger().exception('Error in autocorrelation.')
self.state='error'
def _counts_default(self):
return np.zeros((int(np.round(self.window_size/self.bin_width))*2-1,))
def _time_bins_default(self):
return self.bin_width*np.arange(-int(np.round(self.window_size/self.bin_width))+1,int(np.round(self.window_size/self.bin_width)))
def _time_bins_changed(self):
self.plot_data.set_data('t', self.time_bins)
def _counts_changed(self):
if self.normalize:
self.plot_data.set_data('y', self.counts*self.norm_factor)
else:
self.plot_data.set_data('y', self.counts)
def _chan1_default(self):
return 0
def _chan2_default(self):
return 1
def _window_size_changed(self):
self.counts = self._counts_default()
self.time_bins = self._time_bins_default()
def _create_plot(self):
data = ArrayPlotData(t=self.time_bins, y=self.counts)
plot = Plot(data, width=500, height=500, resizable='hv')
plot.plot(('t','y'), type='line', color='blue')
plot.tools.append(SaveTool(plot))
self.plot_data=data
self.plot=plot
traits_view = View(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('resubmit_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
Item('plot', editor=ComponentEditor(), show_label=False),
HGroup(
Item('window_size'),
Item('bin_width'),
Item('chan1'),
Item('chan2'),
Item('normalize'),
),
title='Autocorrelation', width=900, height=800, buttons=[], resizable=True)
if __name__ == '__main__':
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
from tools.emod import JobManager
JobManager().start()
import hardware.dummy
time_tagger = hardware.dummy.TimeTagger()
a = Autocorrelation(time_tagger)
a.edit_traits()
| Python |
"""
There are several distinct ways to go through different NVs and perform
certain measurement tasks.
1. using the queue and 'SwitchTarget' and 'SaveJob' and 'SetJob'
For each task, create a job and submit it to the queue.
Provide a 'special' job for switching the NV. I.e., a queue might
look like this: [ ODMR, Rabi, SwitchTarget, ODMR, Rabi, SwitchTarget, ...]
pro: - very simple
- a different set of Jobs can be submitted for individual NVs
- every part of the 'code' is basically tested separately (uses only
existing jobs) --> very low chance for errors
- queue can be modified by user on run time, e.g., if an error in the tasks
is discovered, it can be corrected
- the submitted jobs can be run with lower priority than all the usual
jobs, i.e., the queue can be kept during daily business and will
automatically resume during any free time
con: - no complicated decision making on how subsequent tasks are executed,
e.g., no possibility to do first a coarse ESR, then decide in which range
to do a finer ESR, etc.
- it is easy to forget save jobs. If everything goes well this is not a problem,
because the jobs can be saved later at any time, but if there is a crash,
unsaved jobs are lost
2. using an independent MissionControl job that is not managed by the JobManager
Write a new job, that is not managed by the JobManager, i.e., that runs independently
of the queue. This Job will submit jobs to the queue as needed.
pro: - allows complex ways to submit jobs, e.g., depending on the result of previous
measurement, with analysis performed in between, etc.
con: - cannot be changed after started
- control job will often be 'new code' and thus may have errors. It is
difficult to test --> error prone
"""
import numpy as np
import threading
import logging
import time
from tools.emod import Job
from tools.utility import GetSetItemsMixin
#ToDo: maybe introduce lock for 'state' variable on each job?
from traits.api import Array, File, Instance, Button
from traitsui.api import View, Item, HGroup, VGroup, InstanceEditor
from chaco.api import ArrayPlotData
from tools.chaco_addons import SavePlot as Plot, SaveTool
from enable.api import ComponentEditor
from measurements.odmr import ODMR
class Zeeman( Job ):#, GetSetItemsMixin ):
"""Zeeman measurement."""
start_button = Button(label='start', desc='Start the measurement.')
stop_button = Button(label='stop', desc='Stop the measurement.')
def _start_button_fired(self):
"""React to submit button. Submit the Job."""
self.start()
def _stop_button_fired(self):
"""React to remove button. Remove the Job."""
self.stop()
current = Array(dtype=float)
basename = File()
odmr = Instance( ODMR, factory=ODMR )
frequency = Array()
line_data = Instance( ArrayPlotData )
line_plot = Instance( Plot, editor=ComponentEditor() )
traits_view = View(VGroup(HGroup(Item('start_button', show_label=False),
Item('stop_button', show_label=False),
Item('state', style='readonly'),
Item('odmr', editor=InstanceEditor(), show_label=False),
),
VGroup(Item('basename'),
#Item('current'), # ToDo: migrate to a custom TabularEditor
),
Item('line_plot', show_label=False, resizable=True),
),
title='Zeeman', buttons=[], resizable=True
)
get_set_items = ['current', 'frequency', 'odmr', '__doc__']
def __init__(self, coil, **kwargs):
self.coil=coil
super(Zeeman,self).__init__(**kwargs)
self._create_line_plot()
self.on_trait_change(self._update_plot, 'frequency', dispatch='ui')
def _run(self):
try:
self.state='run'
if self.basename == '':
raise ValueError('Filename missing. Please specify a filename and try again.')
odmr = self.odmr
if odmr.stop_time == np.inf:
raise ValueError('ODMR stop time set to infinity.')
#odmr.remove()
delta_f = (odmr.frequency_end-odmr.frequency_begin)
self.frequency = np.array(())
for i,current_i in enumerate(self.current):
self.coil.current = current_i
# turn off the coil to wait until the drift due to heating is stable
if current_i > 0.05:
# self.coil.current = 0.0
threading.currentThread().stop_request.wait(30.0)
if threading.currentThread().stop_request.isSet():
break
#odmr.perform_fit=False
odmr.submit()
while odmr.state != 'done':
threading.currentThread().stop_request.wait(1.0)
if threading.currentThread().stop_request.isSet():
odmr.remove()
break
if threading.currentThread().stop_request.isSet():
break
time.sleep(2) # make sure that the job is also done from the point of view of the JobManager
#odmr.perform_fit=True
basename = self.basename
try:
appendix = basename[-4:]
if appendix in ['.pyd','.pys','.asc','.txt']:
basename = basename[:-4]
else:
appendix = '.pys'
except:
appendix = '.pys'
filename = basename+'_'+str(current_i*1000)+'mA'+appendix
filename1 = basename+'_'+str(current_i*1000)+'mA.png'
#filename = basename+'_'+str(current_i)+'A'+appendix
#filename1 = basename+'_'+str(current_i)+'A.png'
odmr.save(filename)
odmr.save_line_plot(filename1)
# turn off the coil and wait for some time to prevent overheating
#if current_i > 0.150:
# self.coil.current = 0.0
# threading.currentThread().stop_request.wait(60.0)
# if threading.currentThread().stop_request.isSet():
# break
#f = odmr.fit_frequencies[0]
#self.frequency=np.append(self.frequency,f)
#odmr.frequency_begin = max(10e6,f-0.5*delta_f)
#odmr.frequency_end = odmr.frequency_begin + delta_f
self.state='done'
except:
logging.getLogger().exception('Error in Zeeman.')
self.state = 'error'
def _create_line_plot(self):
line_data = ArrayPlotData(current=np.array(()), frequency=np.array(()),)
plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=36)
plot.plot(('current','frequency'), color='blue', name='zeeman')
plot.index_axis.title = 'current [mA]'
plot.value_axis.title = 'frequency [MHz]'
plot.tools.append(SaveTool(plot))
self.line_data = line_data
self.line_plot = plot
def _update_plot(self,new):
n = len(new)
self.line_data.set_data('current',self.current[:n])
self.line_data.set_data('frequency',new*1e-6)
def save_line_plot(self, filename):
self.save_figure(self.line_plot, filename)
if __name__=='__main__':
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
from hardware.dummy import Counter, Microwave, Coil
microwave = Microwave()
counter = Counter()
coil = Coil()
from tools.emod import JobManager
JobManager().start()
from measurements.odmr import ODMR
odmr = ODMR(microwave, counter)
zeeman = Zeeman(coil, odmr=odmr, current=np.arange(0.052, 0.149, 0.002))
zeeman.edit_traits()
zeeman.basename='C:\\data\\2012-10-09\\0306-05\\Zeeman\\at-13.1-17.7\\D+E\\2012-10-18_0306-05_D+E_Zeeman'
#zeeman.start()
| Python |
"""
Provides NMR measurement based on pulsed measurement and step by step RF sweep.
"""
import numpy as np
from traits.api import Trait, Instance, Property, String, Range, Float, Int, Bool, Array, Enum
from traitsui.api import View, Item, HGroup, VGroup, VSplit, Tabbed, EnumEditor, TextEditor, Group, Label
import logging
import time
from pulsed import Pulsed, sequence_remove_zeros, sequence_union
class NMR( Pulsed ):
mw_power = Range(low=-100., high=25., value=-100, desc='microwave power', label='MW power [dBm]', mode='text', auto_set=False, enter_set=True)
mw_frequency = Float(default_value=2.883450e9, desc='microwave frequency', label='MW frequency [Hz]', mode='text', auto_set=False, enter_set=True)
mw_t_pi = Float(default_value=800., desc='length of pi pulse of MW[ns]', label='MW pi [ns]', mode='text', auto_set=False, enter_set=True)
rf_power = Range(low=-100., high=17., value=-60, desc='RF power', label='RF power [dBm]', mode='text', auto_set=False, enter_set=True)
rf_begin = Float(default_value=2.4e6, desc='Start Frequency [Hz]', label='RF Begin [Hz]', mode='text', auto_set=False, enter_set=True)
rf_end = Float(default_value=2.7e6, desc='Stop Frequency [Hz]', label='RF End [Hz]', mode='text', auto_set=False, enter_set=True)
rf_delta = Float(default_value=2.0e3, desc='frequency step [Hz]', label='Delta [Hz]', mode='text', auto_set=False, enter_set=True)
rf_t_pi = Float(default_value=1.e6, desc='length of pi pulse of RF[ns]', label='RF pi [ns]', mode='text', auto_set=False, enter_set=True)
laser = Float(default_value=3000., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True)
decay = Float(default_value=2.0e6, desc='decay [ns]', label='decay [ns]', mode='text', auto_set=False, enter_set=True)
aom_delay = Float(default_value=0.0, desc='If set to a value other than 0.0, the aom triggers are applied\nearlier by the specified value. Use with care!', label='aom delay [ns]', mode='text', auto_set=False, enter_set=True)
seconds_per_point = Float(default_value=0.5, desc='Seconds per point', label='Seconds per point', mode='text', auto_set=False, enter_set=True)
sweeps_per_point = Int()
frequencies = Array( value=np.array((0.,1.)) )
def __init__(self, pulse_generator, time_tagger, mw_source, rf_source, **kwargs):
super(NMR, self).__init__(pulse_generator, time_tagger, **kwargs)
self.mw_source = mw_source
self.rf_source = rf_source
def generate_sequence(self):
# ESR:
# return 100*[ (['aom','detect','microwave'], self.laser), (['sequence'], 18) ]
# decay - rf_pi-pulse - readout / polarize
aom_delay = self.aom_delay
laser = self.laser
decay = self.decay
rf_t_pi = self.rf_t_pi
s_aom = 100*[ ([],decay+rf_t_pi), (['aom'],laser), ([],18) ]
s_other = [ ([],aom_delay) ] + 100*[ ([],decay), (['rf'], rf_t_pi), (['detect'],laser), (['sequence'],18) ]
s_aom = sequence_remove_zeros(s_aom)
s_other = sequence_remove_zeros(s_other)
sequence = sequence_union(s_aom,s_other)
return sequence
def apply_parameters(self):
"""Apply the current parameters and decide whether to keep previous data."""
frequencies = np.arange(self.rf_begin, self.rf_end+self.rf_delta, self.rf_delta)
n_bins = int(self.record_length / self.bin_width)
time_bins = self.bin_width*np.arange(n_bins)
sequence = self.generate_sequence()
if not (self.keep_data and sequence == self.sequence and np.all(time_bins == self.time_bins) and np.all(frequencies == self.frequencies)): # if the sequence and time_bins are the same as previous, keep existing data
self.count_data = np.zeros((len(frequencies),n_bins))
self.run_time=0.0
self.frequencies = frequencies
self.sequence = sequence
self.time_bins = time_bins
self.n_bins = n_bins
# ESR:
#self.sweeps_per_point = int(self.seconds_per_point * 1e9 / (self.laser))
self.sweeps_per_point = int(np.max((1,int(self.seconds_per_point * 1e9 / (self.laser+self.decay+self.rf_t_pi)))))
self.keep_data = True # when job manager stops and starts the job, data should be kept. Only new submission should clear data.
def _run(self):
"""Acquire data."""
try: # try to run the acquisition from beginning to end
self.state='run'
self.apply_parameters()
if self.run_time >= self.stop_time:
logging.getLogger().debug('Runtime larger than stop_time. Returning')
self.state='done'
return
self.pulse_generator.Night()
self.mw_source.setOutput(self.mw_power,self.mw_frequency)
if self.channel_apd_0 > -1:
pulsed_0 = self.time_tagger.Pulsed(self.n_bins, int(np.round(self.bin_width*1000)), 1, self.channel_apd_0, self.channel_detect, self.channel_sequence)
pulsed_0.setMaxCounts(self.sweeps_per_point)
if self.channel_apd_1 > -1:
pulsed_1 = self.time_tagger.Pulsed(self.n_bins, int(np.round(self.bin_width*1000)), 1, self.channel_apd_1, self.channel_detect, self.channel_sequence)
pulsed_1.setMaxCounts(self.sweeps_per_point)
self.pulse_generator.Sequence(self.sequence)
if self.pulse_generator.checkUnderflow():
raise RuntimeError('Underflow in pulse generator.')
while self.run_time < self.stop_time:
new_counts = np.zeros_like(self.count_data)
start_time = time.time()
for i,fi in enumerate(self.frequencies):
if self.thread.stop_request.isSet():
break
self.rf_source.setOutput(self.rf_power,fi)
if self.channel_apd_0 > -1:
pulsed_0.clear()
if self.channel_apd_1 > -1:
pulsed_1.clear()
if self.channel_apd_0 > -1:
while not pulsed_0.ready():
time.sleep(1.1*self.seconds_per_point)
if self.channel_apd_1 > -1:
while not pulsed_1.ready():
time.sleep(1.1*self.seconds_per_point)
if self.pulse_generator.checkUnderflow():
raise RuntimeError('Underflow in pulse generator.')
if self.channel_apd_0 > -1:
new_counts[i,:] = pulsed_0.getData()[0]
if self.channel_apd_1 > -1:
new_counts[i,:] = pulsed_1.getData()[0]
else:
self.run_time += time.time() - start_time
self.count_data += new_counts
self.trait_property_changed('count_data', self.count_data)
if self.thread.stop_request.isSet():
break
if self.run_time < self.stop_time:
self.state = 'idle'
else:
try:
self.save(self.filename)
except:
logging.getLogger().exception('Failed to save the data to file.')
self.state='done'
if self.channel_apd_0 > -1:
del pulsed_0
if self.channel_apd_1 > -1:
del pulsed_1
self.pulse_generator.Light()
self.mw_source.setOutput(None,self.mw_frequency)
self.rf_source.setOutput(None,self.rf_begin)
except: # if anything fails, log the exception and set the state
logging.getLogger().exception('Something went wrong in pulsed loop.')
self.state='error'
get_set_items = Pulsed.get_set_items + ['mw_frequency','mw_power','mw_t_pi',
'rf_power', 'rf_begin', 'rf_end', 'rf_delta', 'rf_t_pi',
'laser','decay','aom_delay','seconds_per_point', 'frequencies', 'count_data', 'sequence']
traits_view = View(VGroup(HGroup(Item('submit_button', width=-60, show_label=False),
Item('remove_button', width=-60, show_label=False),
Item('resubmit_button', width=-60, show_label=False),
Item('priority', width=-30),
Item('state', style='readonly'),
Item('run_time', style='readonly',format_str='%.f'),
Item('stop_time',format_str='%.f'),
Item('stop_counts'),
),
HGroup(Item('filename',springy=True),
Item('save_button', show_label=False),
Item('load_button', show_label=False)
),
Tabbed(VGroup(HGroup(Item('mw_power', width=-40),
Item('mw_frequency', width=-80, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_func=lambda x:'%e'%x)),
Item('mw_t_pi', width=-80),
),
HGroup(Item('rf_power', width=-40),
Item('rf_begin', width=-80, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_func=lambda x:'%e'%x)),
Item('rf_end', width=-80, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_func=lambda x:'%e'%x)),
Item('rf_delta', width=-80, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_func=lambda x:'%e'%x)),
Item('rf_t_pi', width=-80),
),
HGroup(Item('laser', width=-80, enabled_when='state != "run"'),
Item('decay', width=-80, enabled_when='state != "run"'),
Item('aom_delay', width=-80, enabled_when='state != "run"'),
),
label='stimulation'),
VGroup(HGroup(Item('record_length', width=-80, enabled_when='state != "run"'),
Item('bin_width', width=-80, enabled_when='state != "run"'),
),
HGroup(Item('seconds_per_point', width=-120, enabled_when='state == "idle"'),
Item('sweeps_per_point', width=-120, style='readonly'),
),
label='acquisition'),
VGroup(HGroup(Item('integration_width'),
Item('position_signal'),
Item('position_normalize'),
),
label='analysis'),
),
),
title='NMR',
)
if __name__ == '__main__':
"""
Test code using dummy hardware
"""
#from hardware.dummy import PulseGenerator, TimeTagger, Microwave
#pulse_generator = PulseGenerator()
#time_tagger = TimeTagger()
#microwave = Microwave()
#from tools.emod import JobManager
#JobManager().start()
#nmr = NMR(pulse_generator,time_tagger,microwave,microwave)
nmr = NMR(pulse_generator,time_tagger,microwave,rf_source)
nmr.edit_traits()
| Python |
"""
Determination of magnetic field from the Zeeman shift of several NVs
Problem statement
Suppose we have a single crystalline bulk diamond. Suppose the crystal
is placed in a homogeneous magnetic field B. NV centers can have 4 possible
orientations with respect to the crystal lattice. We consider N single NVs
who's orientations are unknown. Using ODMR measurements we can determine
the ESR transitions of each NV.
v1_i=e1_i-e0_i
v2_i=e2_i-e0_i
From the spin Hamiltonian model we can compute the energies e0_i, e1_i, e2_i.
We assume the energies are ordered with increasing energy. Then we can directly relate
measured energies to calculated energies.
We will use a brute force method to find the magnetic field. To this end, we compute
the transition frequencies v1 and v2 for a predetermined
set of magnetic fields. For numerical efficiency, we will pre-compute the ESR transitions
and store the data on the disc.
The search will typically be performed in three steps:
1. coarse brute force search using pre-computed ESR data.
2. fine brute force search using on-demand calculation on a fine mesh
3. non-linear least-square fitting
Helmut Fedder <helmut.fedder@gmail.com>
first version: 31 May 2012
"""
import numpy as np
import scipy.optimize
import scipy.special
import cPickle
import sys
# transformations to NV coordinate systems
def axis_angle(n0,n1):
"""Compute the rotation axis and angle to transform n0 to n1.
n0 and n1 are of length 1."""
n = np.cross(n0,n1)
norm_n = np.linalg.norm(n)
if norm_n == 0.:
n = np.array((0.,0.,1.))
phi = 0.0
else:
n=n/norm_n
phi = np.arccos(np.dot(n0,n1))
return n, phi
def rotation_matrix(n,phi):
"""Compute the rotation axis from an axis and angle."""
x,y,z=n
c=np.cos(phi)
s=np.sin(phi)
t=1-c
R=np.array((( t*x*x + c , t*x*y - z*s, t*x*z + y*s),
( t*y*x + z*s, t*y*y + c , t*y*z - x*s),
( t*z*x - y*s, t*z*y + x*s, t*z*z + c )))
return R
class TripletSpin():
"""Triplet state Hamiltonian with D, E and Zeeman shift."""
def __init__(self,D=2870.6,E=0.0,g=2.0028*9.27400915/6.626068):
self.D=D
self.E=E
self.g=g
def energy_levels(self,B):
"""Calculate the energy levels for given magnetic field."""
D=self.D
E=self.E
g=self.g
H = np.array((( 0., 1j*g*B[1], -1j*g*B[0]),
( -1j*g*B[1], D-E, 1j*g*B[2]),
( 1j*g*B[0], -1j*g*B[2], D+E)))
e=np.linalg.eigvalsh(H)
e.sort()
return e
def transitions(self,B):
"""
Calculate the ESR transitions for given external field.
Note that this method of sorting the energies fails above the LAC.
"""
e=self.energy_levels(B)
return np.array((e[1]-e[0],e[2]-e[0]))
def v1v2_table(nvs,rotations,bx,by,bz):
table=np.empty((len(bx),len(by),len(bz),len(nvs),2))
for i,bxi in enumerate(bx):
sys.stdout.write('\r%i%%'%int(round(i/float(len(bx))*100)))
sys.stdout.flush()
for j,byj in enumerate(by):
for k,bzk in enumerate(bz):
b = np.array((bxi,byj,bzk))
for m in range(4):
table[i,j,k,m] = nvs[m].transitions(np.dot(rotations[m],b))
sys.stdout.write('\r')
sys.stdout.flush()
return table
def landscape_transitions(orientations,transitions,table):
return np.sum(np.sum((table[:,:,:,orientations,:]-transitions)**2,axis=-1),axis=-1)
def landscape_splittings(orientations,splittings,table):
return np.sum((table[:,:,:,orientations,1]-table[:,:,:,orientations,0]-splittings)**2,axis=-1)
def index_minimum(landscape):
i_flat=landscape.argmin()
return np.unravel_index(i_flat,landscape.shape)
def chi_transitions(nvs,rotations,orientations,transitions,s_transitions=None):
"""Chi for transition frequencies"""
if s_transitions is None:
def chi(b):
theo = np.empty_like(transitions)
for i in range(len(transitions)):
theo[i] = nvs[i].transitions(np.dot(rotations[orientations[i]],b))
return (theo-transitions).flatten()
else:
def chi(b):
theo = np.empty_like(transitions)
for i in range(len(transitions)):
theo[i] = nvs[i].transitions(np.dot(rotations[orientations[i]],b))
return ((theo-transitions)/s_transitions).flatten()
return chi
def chi_splittings(nvs,rotations,orientations,splittings,s_splittings=None):
"""Chi for splittings."""
if s_splittings is None:
def chi(b):
theo = np.empty((len(splittings),2))
for i in range(len(splittings)):
theo[i] = nvs[i].transitions(np.dot(rotations[orientations[i]],b))
return theo[:,1]-theo[:,0]-splittings
else:
def chi(b):
theo = np.empty((len(splittings),2))
for i in range(len(splittings)):
theo[i] = nvs[i].transitions(np.dot(rotations[orientations[i]],b))
return (theo[:,1]-theo[:,0]-splittings)/s_splittings
return chi
def generate_table(spin_models, rotations, b_range, b_delta, table_file):
# magnetic field range
b = np.arange(-b_range,b_range,b_delta)
table = v1v2_table(spin_models,rotations,b,b,b)
fil=open(table_file,'wb')
cPickle.dump((spin_models,rotations,b,b,b,table),fil,1)
fil.close()
def load_table(filename):
fil=open(table_file)
spin_models,rotations,bx,by,bz,table=cPickle.load(fil)
fil.close()
return spin_models,rotations,bx,by,bz,table
def find_field(spin_models, rotations, orientations, bx, by, bz, table, transitions, s_transitions=None, method='transitions'):
"""
Try to find the magnetic field from given ESR frequencies or alternatively ESR splittings
of 3 or four different NVs.
Input:
spin_models: 3- or 4-tuple of TripletSpin. Here you can pass
D,E, and g-factor for the individual NVs
orientations: list of orientations of the NVs ( 0-->(1,1,1), 1-->(-1,-1,1), 2-->(1,-1,-1), 3-->(-1,1,-1) )
bx, by, bz: The x,y,z magnetic field mesh over which the table was computed
table: table of pre-computed ESR transitions corresponding to the spi-models
and magnetic field meshes.
transitions: (3,2) or (4,2) array containing the ESR transition frequencies
of three or four different NVs.
s_transitions: standard deviations of the transitions frequencies or None
method: Determines the parameter used for the fitting. Can be either 'transitions'
or 'splittings'. In the prior case, the transitions are fitted
in the latter case, the splittings, i.e. the difference between
the transitions are fitted.
Returns:
b : 3-tuple of vectors: b-field vectors after the three stages
stage one: brute force using lookup table
stage two: refined brute force
stage three: nonlinear least-square minimization
s_b: standard deviation of b-field from least-square minimization (stage three)
chisqr: 3-tuple: chisqr deviations after the three stages
q: quality of fit from least-square minimization (only meaningful if
standard deviations of the transition frequencies were provided)
"""
if method=='transitions':
# stage one: lookup
i,j,k = index_minimum(landscape_transitions(orientations,transitions,table))
b1=np.array((bx[i],by[j],bz[k]))
# stage two: refined brute force
bxf=np.linspace(bx[i-1],bx[i+1],11)
byf=np.linspace(by[j-1],by[j+1],11)
bzf=np.linspace(bz[k-1],bz[k+1],11)
fine_table=v1v2_table(spin_models,rotations,bxf,byf,bzf)
i,j,k = index_minimum(landscape_transitions(orientations,transitions,fine_table))
b2=np.array((bxf[i],byf[j],bzf[k]))
# stage three: nonlinear least square minimization
result = scipy.optimize.leastsq(chi_transitions(spin_models,rotations,orientations,transitions,s_transitions), b2, full_output=True)
elif method=='splittings':
splittings = transitions[:,1]-transitions[:,0]
if s_transitions is not None:
s_splittings = (s_transitions[:,1]**2+s_transitions[:,0]**2)**0.5
else:
s_splittings = None
# stage one: lookup
i,j,k = index_minimum(landscape_splittings(orientations,splittings,table))
b1=np.array((bx[i],by[j],bz[k]))
# stage two: refined brute force
bxf=np.linspace(bx[i-1],bx[i+1],11)
byf=np.linspace(by[j-1],by[j+1],11)
bzf=np.linspace(bz[k-1],bz[k+1],11)
fine_table=v1v2_table(spin_models,rotations,bxf,byf,bzf)
i,j,k = index_minimum(landscape_splittings(orientations,splittings,fine_table))
b2=np.array((bxf[i],byf[j],bzf[k]))
# stage three: nonlinear least square minimization
result = scipy.optimize.leastsq(chi_splittings(spin_models,rotations,orientations,splittings), b2, full_output=True)
# resulting b
b3 = result[0]
# error of b
s_b3 = np.diag(result[1])**0.5
# goodness of fit analysis
chi0 = result[2]['fvec']
chisqr0 = np.sum(chi0**2)
nu = 2*len(transitions) - 3
# quality of the fit
q = scipy.special.gammaincc(0.5*nu,0.5*chisqr0)
if method=='transitions':
chisqr1=np.sum(chi_transitions(spin_models,rotations,orientations,transitions)(b1)**2)
chisqr2=np.sum(chi_transitions(spin_models,rotations,orientations,transitions)(b2)**2)
chisqr3=np.sum(chi_transitions(spin_models,rotations,orientations,transitions)(b3)**2)
elif method=='splittings':
chisqr1=np.sum(chi_splittings(spin_models,rotations,orientations,splittings)(b1)**2)
chisqr2=np.sum(chi_splittings(spin_models,rotations,orientations,splittings)(b2)**2)
chisqr3=np.sum(chi_splittings(spin_models,rotations,orientations,splittings)(b3)**2)
return (b1, b2, b3), s_b3, (chisqr1, chisqr2, chisqr3), q
if __name__=='__main__':
"""
# generate table_file
# use NV's with standard parameters D=2870.6 MHz, E=0.0 MHz, g=2.0028
# here you can pass individual parameters for each of the NVs
nvs=(TripletSpin(),TripletSpin(),TripletSpin(),TripletSpin())
# NV orientations
nv_axis = np.array(((1,1,1), (-1,-1,1), (1,-1,-1), (-1,1,-1))) / 3**0.5
n0=np.array((0,0,1))
rotations=np.empty((4,3,3))
for i,n in enumerate(nv_axis):
nr,phi = axis_angle(n,n0)
rotations[i] = rotation_matrix(nr,phi)
# generate table with magnetic field in the range -200 to 200 Gauss for bx, by, bz
generate_table(nvs,rotations,200.,2.,'table_200.pys')
"""
# load pre-computed data
if not 'table' in dir():
print 'loading table file...'
fil=open('table_200.pys')
spin_models,rotations,bx,by,bz,table=cPickle.load(fil)
fil.close()
# normally we have as experimental data the ESR resonance lines.
# in this case, we have only the splittings and compute 'fake'
# transition frequencies
splittings = np.array((31.99, 90.93, 103.5, 162.6))
transitions = np.vstack((np.zeros_like(splittings), splittings)).transpose()
orientations = [0,1,2,3]
b, s_b, chisqr, q = find_field(spin_models,orientations,bx,by,bz,table,transitions,method='splittings')
print np.linalg.norm(b[2])
| Python |
import numpy as np
from scipy.optimize import leastsq
from fitting import baseline
def lorentzian(x0, g, a):
"""Lorentzian centered at x0, with amplitude a, and HWHM g."""
return lambda x: a / np.pi * ( g / ( (x-x0)**2 + g**2 ) )
def n_lorentzians(*p):
N = (len(p)-1)/3
def f(x):
y = p[0]*np.ones(x.shape)
i = 0
for i in range(N):
y += lorentzian(*p[i*3+1:i*3+4])(x)
return y
return f
def grow(mask):
"""Grows regions in a 1D binary array in both directions.
Helper function to kill noise in odmr fit."""
return np.logical_or(np.logical_or(mask, np.append(mask[1:],False)), np.append(False,mask[:-1]))
def fit_odmr(x,y,threshold=0.5,number_of_lorentzians='auto'):
"""Attempts to fit a sum of multiple Lorentzians and returns the fit parameters (c, x0, g0, a0, x1, g1, a1,... )."""
# first re-scale the data to the range (0,1), such that the baseline is at 0.
# flip the data in y-direction if threshold is negative
y0 = baseline(y)
yp = y - y0
if threshold < 0:
yp = -yp
y_max = yp.max()
yp = yp / y_max
# compute crossings through a horizontal line at height 'threshold'
mask = yp>abs(threshold)
edges = np.where(np.logical_xor(mask, np.append(False,mask[:-1])))[0]
if len(edges)%2 != 0:
raise RuntimeError('found an uneven number of edges')
if len(edges) < 2:
raise RuntimeError('did not find a distinct peak with the given threshold')
if number_of_lorentzians is 'auto': # try to find N automatically
# attempt initial growth of connected regions to kill noise
while True:
mask = grow(mask)
new_edges = np.where(np.logical_xor(mask, np.append(False,mask[:-1])))[0]
if len(new_edges) < len(edges):
edges = new_edges
else:
break
else: # if N is specified grow until number of regions =< N
while len(edges)/2 > number_of_lorentzians:
mask = grow(mask)
edges = np.where(np.logical_xor(mask, np.append(False,mask[:-1])))[0]
if len(edges)%2 != 0:
raise RuntimeError('found an uneven number of edges')
if len(edges) < 2:
raise RuntimeError('did not find a distinct peak with the given threshold')
N = len(edges)/2
left_and_right_edges = edges.reshape((N,2))
p = [ 0 ]
# for every local maximum, estimate parameters of Lorentzian and append them to the list of parameters p
for left, right in left_and_right_edges:
g = abs(x[right] - x[left]) # FWHM
i = y[left:right].argmax()+left # index of local minimum
x0 = x[i] # position of local minimum
a = y[i] * np.pi * g # height of local minimum in terms of Lorentzian parameter a
p += [ x0, g, a ]
p = tuple(p)
# chi for N Lorentzians with a common baseline
def chi(p):
ypp = p[0]-yp
for i in range(N):
ypp += lorentzian(*p[i*3+1:i*3+4])(x)
return ypp
r = leastsq(chi, p, full_output=True)
if r[-1] == 0:
raise RuntimeError('least square fit did not work out')
p = np.array(r[0])
y_amp = y_max*np.sign(threshold)
# rescale fit parameters back to original data
p[0] = p[0]*y_amp + y0
p[3::3] *= y_amp
delta = np.diag(r[1])**0.5
delta[0] = delta[0]*y_max
delta[3::3] *= y_max
return p, delta
if __name__=='__main__':
import cPickle
fil = open('/home/helmut/projects/NewDefect/nuclear_polarization/alignement_at_LAC/2012-09-10/zeeman/D-E/2012-09-10_0306-05_DmE_zeeman_0.122A.pys','rb')
d=cPickle.load(fil)
x=d['frequency']
y=d['counts']
"""
y_max=y.max()
y_min=y.min()
N=int((y_max-y_min)/y_min**0.5)
print N
hist, bin_edges = np.histogram(y,N)
import pylab
pylab.close('all')
pylab.plot(bin_edges[:-1],hist)
pylab.show()
"""
y_max=y.max()
y_min=y.min()
threshold = 8*y_min**0.5 / (y_max-y_min)
print threshold
p,dp=fit_odmr(x,y,threshold=threshold)
import pylab
pylab.close('all')
pylab.plot(x,y)
pylab.plot(x,n_lorentzians(*p)(x),'r-')
pylab.show()
| Python |
"""
This module provides analysis of pulsed measurements.
The first part provides simple numeric functions.
The second part provides Trait GUIs
"""
import numpy as np
from fitting import find_edge
def spin_state(c, dt, T, t0=0.0, t1=-1.):
"""
Compute the spin state from a 2D array of count data.
Parameters:
c = count data
dt = time step
t0 = beginning of integration window relative to the edge
t1 = None or beginning of integration window for normalization relative to edge
T = width of integration window
Returns:
y = 1D array that contains the spin state
profile = 1D array that contains the pulse profile
edge = position of the edge that was found from the pulse profile
If t1<0, no normalization is performed. If t1>=0, each data point is divided by
the value from the second integration window and multiplied with the mean of
all normalization windows.
"""
profile = c.sum(0)
edge = find_edge(profile)
I = int(round(T/float(dt)))
i0 = edge + int(round(t0/float(dt)))
y = np.empty((c.shape[0],))
for i, slot in enumerate(c):
y[i] = slot[i0:i0+I].sum()
if t1 >= 0:
i1 = edge + int(round(t1/float(dt)))
y1 = np.empty((c.shape[0],))
for i, slot in enumerate(c):
y1[i] = slot[i1:i1+I].sum()
y = y/y1*y1.mean()
return y, profile, edge
#########################################
# Trait GUIs for pulsed fits
#########################################
from traits.api import Instance, Any, Property, Range, Float, Int, Bool, Array, List, Str, Tuple, Enum,\
on_trait_change, cached_property, DelegatesTo
from traitsui.api import View, Item, Tabbed, Group, HGroup, VGroup, VSplit, EnumEditor, TextEditor, InstanceEditor
from enable.api import ComponentEditor
from chaco.api import ArrayDataSource, LinePlot, LinearMapper, ArrayPlotData, Spectral, PlotLabel
from tools.chaco_addons import SavePlot as Plot, SaveTool
import threading
import time
import logging
import fitting
from tools.utility import GetSetItemsMixin
from measurements.pulsed import Pulsed, PulsedTau
class PulsedTool( GetSetItemsMixin ):
"""
Base class for a pulsed analysis. Provides calculation of spin state
and plotting.
Derive from this to create analysis tools for pulsed measurements.
"""
# the measurement to analyze
measurement = Any(editor=InstanceEditor)
# plotting
matrix_data = Instance( ArrayPlotData)
line_data = Instance( ArrayPlotData )
pulse_data = Instance( ArrayPlotData )
matrix_plot = Instance( Plot, editor=ComponentEditor() )
pulse_plot = Instance( Plot, editor=ComponentEditor() )
line_plot = Instance( Plot, editor=ComponentEditor() )
get_set_items = ['__doc__','measurement']
traits_view = View(VGroup(Item(name='measurement', style='custom', show_label=False),
VSplit(Item('matrix_plot', show_label=False, width=500, height=-300, resizable=True),
Item('line_plot', show_label=False, width=500, height=-300, resizable=True),
Item('pulse_plot', show_label=False, width=500, height=-300, resizable=True),
),
),
title='Pulsed Tool',
buttons=[],
resizable=True,
height=-640
)
def __init__(self, **kwargs):
super(PulsedTool, self).__init__(**kwargs)
self._create_matrix_plot()
self._create_pulse_plot()
self._create_line_plot()
self.on_trait_change(self._update_matrix_index, 'measurement.time_bins,measurement.n_laser', dispatch='ui')
self.on_trait_change(self._update_matrix_value, 'measurement.count_data', dispatch='ui')
self.on_trait_change(self._update_pulse_index, 'measurement.time_bins', dispatch='ui')
self.on_trait_change(self._update_pulse_value, 'measurement.pulse', dispatch='ui')
self.on_trait_change(self._update_line_plot_value, 'measurement.spin_state', dispatch='ui')
self.on_trait_change(self._on_edge_change, 'measurement.edge', dispatch='ui')
# plotting
def _create_matrix_plot(self):
matrix_data = ArrayPlotData(image=np.zeros((2,2)))
plot = Plot(matrix_data, width=500, height=500, resizable='hv', padding=8, padding_left=48, padding_bottom=36)
plot.index_axis.title = 'time [ns]'
plot.value_axis.title = 'laser pulse #'
plot.img_plot('image',
xbounds=(0,1),
ybounds=(0,1),
colormap=Spectral)[0]
plot.tools.append(SaveTool(plot))
self.matrix_data = matrix_data
self.matrix_plot = plot
def _create_pulse_plot(self):
pulse_data = ArrayPlotData(x=np.array((0.,0.1,0.2)),y=np.array((0,1,2)))
plot = Plot(pulse_data, padding=8, padding_left=64, padding_bottom=36)
line = plot.plot(('x','y'), style='line', color='blue', name='data')[0]
plot.index_axis.title = 'time [ns]'
plot.value_axis.title = 'intensity'
edge_marker = LinePlot(index = ArrayDataSource(np.array((0,0))),
value = ArrayDataSource(np.array((0,1e9))),
color = 'red',
index_mapper = LinearMapper(range=plot.index_range),
value_mapper = LinearMapper(range=plot.value_range),
name='marker')
plot.add(edge_marker)
plot.tools.append(SaveTool(plot))
self.pulse_data = pulse_data
self.pulse_plot = plot
def _create_line_plot(self):
line_data = ArrayPlotData(index=np.array((0,1)), spin_state=np.array((0,0)),)
plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=36)
plot.plot(('index','spin_state'), color='blue', name='spin_state')
plot.index_axis.title = 'pulse #'
plot.value_axis.title = 'spin state'
plot.tools.append(SaveTool(plot))
self.line_data = line_data
self.line_plot = plot
def _update_matrix_index(self):
if self.measurement is not None:
self.matrix_plot.components[0].index.set_data((self.measurement.time_bins[0], self.measurement.time_bins[-1]),(0.0,float(self.measurement.n_laser)))
def _update_matrix_value(self):
if self.measurement is not None:
s = self.measurement.count_data.shape
if not s[0]*s[1] > 1000000:
self.matrix_data.set_data('image', self.measurement.count_data)
def _update_pulse_index(self):
if self.measurement is not None:
self.pulse_data.set_data('x', self.measurement.time_bins)
def _update_pulse_value(self):
if self.measurement is not None:
self.pulse_data.set_data('y', self.measurement.pulse)
def _on_edge_change(self):
if self.measurement is not None:
y=self.measurement.edge
self.pulse_plot.components[1].index.set_data(np.array((y,y)))
def _update_line_plot_value(self):
if self.measurement is not None:
y=self.measurement.spin_state
n = len(y)
old_index = self.line_data.get_data('index')
if old_index is not None and len(old_index) != n:
self.line_data.set_data('index',np.arange(n))
self.line_data.set_data('spin_state',y)
def save_matrix_plot(self, filename):
save_figure(self.matrix_plot, filename)
def save_line_plot(self, filename):
save_figure(self.line_plot, filename)
class PulsedToolTau( PulsedTool ):
"""
Analysis of a pulsed measurement with a 'tau' as index-data.
"""
# overwrite __init__ such that change of 'tau' causes plot update
def __init__(self, **kwargs):
super(PulsedToolTau, self).__init__(**kwargs)
self.on_trait_change(self._on_tau_change, 'measurement.tau', dispatch='ui')
#self.on_trait_change(self._on_tau_change, 'measurement.tau') # ToDo: fix this
# overwrite the line_plot such that the x-axis label is time
def _create_line_plot(self):
line_data = ArrayPlotData(index=np.array((0,1)), spin_state=np.array((0,0)),)
plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=36)
plot.plot(('index','spin_state'), color='blue', name='spin_state')
plot.index_axis.title = 'time [micro s]'
plot.value_axis.title = 'spin state'
plot.tools.append(SaveTool(plot))
self.line_data = line_data
self.line_plot = plot
# overwrite this one to throw out setting of index data according to length of spin_state
def _update_line_plot_value(self):
y = self.measurement.spin_state
self.line_data.set_data('spin_state',y)
# provide method for update of tau
def _on_tau_change(self):
self.line_data.set_data('index',self.measurement.tau*1e-3)
# overwrite this to change the window title
traits_view = View(VGroup(Item(name='measurement', style='custom', show_label=False),
VSplit(Item('matrix_plot', show_label=False, width=500, height=300, resizable=True),
Item('line_plot', show_label=False, width=500, height=300, resizable=True),
Item('pulse_plot', show_label=False, width=500, height=300, resizable=True),
),
),
title='Pulsed Analysis Tau',
buttons=[], resizable=True
)
class FitToolTau( PulsedToolTau ):
"""
Base class for PulsedTool with a tau and fit.
"""
# fit results
fit_result = Tuple()
label_text = Str('')
# add fit results to the get_set_items
get_set_items = PulsedToolTau.get_set_items + ['fit_result','label_text']
# overwrite __init__ to trigger update events
def __init__(self, **kwargs):
super(FitToolTau, self).__init__(**kwargs)
self.on_trait_change(self._update_fit, 'measurement.spin_state', dispatch='ui')
self.on_trait_change(self._on_fit_result_change, 'fit_result', dispatch='ui')
self.on_trait_change(self._on_label_text_change, 'label_text', dispatch='ui')
def _update_fit(self):
pass
# overwrite the line_plot to include fit and text label
def _create_line_plot(self):
line_data = ArrayPlotData(index=np.array((0,1)),
spin_state=np.array((0,0)),
fit=np.array((0,0)))
plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=36)
plot.plot(('index','spin_state'), color='blue', name='spin_state')
plot.plot(('index','fit'), color='red', name='fit')
plot.index_axis.title = 'time [micro s]'
plot.value_axis.title = 'spin state'
plot.overlays.insert(0, PlotLabel(text=self.label_text, hjustify='left', vjustify='bottom', position=[64,32]) )
plot.tools.append(SaveTool(plot))
self.line_data = line_data
self.line_plot = plot
def _on_fit_result_change(self, new):
pass
def _on_label_text_change(self, new):
self.line_plot.overlays[0].text = new
#########################################
# testing
#########################################
if __name__ == '__main__':
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
from tools.emod import JobManager
JobManager().start()
import measurements.pulsed
# basic example to analyze a Rabi measurement
#m = measurements.pulsed.Rabi()
#a = PulsedTool()
#a = PulsedToolTau()
#a = PulsedToolDoubleTauRef()
a = RabiAna()
#a = PulseCalAna()
#a.measurement = measurements.pulsed.Rabi()
#a.measurement = mp.PulseCal()
a.edit_traits()
#a.load('')
#a.measurement = m
| Python |
"""
This file is part of Diamond. Diamond is a confocal scanner written
in python / Qt4. It combines an intuitive gui with flexible
hardware abstraction classes.
Diamond is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Diamond is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with diamond. If not, see <http://www.gnu.org/licenses/>.
Copyright (C) 2009 Helmut Rathgen <helmut.rathgen@gmail.com>
"""
import numpy as np
import scipy.optimize, scipy.stats
########################################################
# utility functions
########################################################
def baseline(y,n=None):
"""
Returns the baseline of 'y'. 'n' controls the discretization.
The difference between the maximum and the minimum of y is discretized into 'n' steps.
"""
if not n: # estimate a useful number for the histogram bins from shot noise
y_min = y.min()
y_max = y.max()
n = (y_max-y_min)/y_min**0.5
hist, bin_edges = np.histogram(y,n)
return bin_edges[hist.argmax()]
def find_edge(y,bins=20):
"""Returns edge of a step function"""
h,b=np.histogram(y,bins=bins)
i0 = bins/2
i = h[i0:].argmax()+i0
threshold = 0.5*(b[0]+b[i])
return np.where(y>threshold)[0][0]
def run_sum(y, n=10):
"""Calculates the running sum over 'y' (1D array) in a window with 'n' samples."""
N = len(y)
yp = np.empty(N)
for i in range(N):
if i+n > N:
yp[i]=yp[N-n] # pad the last array entries with the last real entry
else:
yp[i]=np.sum(y[i:i+n])
return yp
########################################################
# non-linear least square fitting
########################################################
def fit(x, y, model, estimator):
"""Perform least-squares fit of two dimensional data (x,y) to model 'Model' using Levenberg-Marquardt algorithm.\n
'Model' is a callable that takes as an argument the model parameters and returns a function representing the model.\n
'Estimator' can either be an N-tuple containing a starting guess of the fit parameters, or a callable that returns a respective N-tuple for given x and y."""
if callable(estimator):
#return scipy.optimize.leastsq(lambda pp: model(*pp)(x) - y, estimator(x,y), warning=False)[0]
return scipy.optimize.leastsq(lambda pp: model(*pp)(x) - y, estimator(x,y))[0]
else:
#return scipy.optimize.leastsq(lambda pp: model(*pp)(x) - y, estimator, warning=False)[0]
return scipy.optimize.leastsq(lambda pp: model(*pp)(x) - y, estimator)[0]
def nonlinear_model(x, y, s, model, estimator, message=False):
"""Performs a non-linear least-squares fit of two dimensional data and a primitive error analysis.
parameters:
x = x-data
y = y-data
s = standard deviation of y
model = the model to use for the fit. must be a factory function
that takes as parameters the parameters to fit and returns
a function y(x)
estimator = either an n-tuple (or array) containing the starting guess
of the fit parameters or a callable that takes x and y
as arguments and returns a starting guess
return values:
p = set of parameters that minimizes the chisqr
cov = covariance matrix
q = probability of obtaining a chisqr larger than the observed one
if 0.9 > q > 0.1 the fit is credible
if q > 0.001, the fit may be credible if we expect that the
reason for the small q are non-normal distributed errors
if q < 0.001, the fit must be questioned. Possible causes are
(i) the model is not suitable
(ii) the standard deviations s are underestimated
(iii) the standard deviations s are not normal distributed
if q > 0.9, the fit must be questioned. Possible causes are
(i) the standard deviations are overestimated
(ii) the data has been manipulated to fit the model
chisqr0 = sum over chisqr evaluated at the minimum
"""
chisqr = lambda p: ( model(*p)(x) - y ) / s
if callable(estimator):
p = estimator(x,y)
else:
p = estimator
result = scipy.optimize.leastsq(chisqr, p, full_output=True)
if message:
print result[4], result[3]
p = result[0]
cov = result[1]
# there are some cases where leastsq doesn't raise an exception, however returns None for
# the covariance matrix. To prevent 'invalid index' errors in functions that call nonlinear_model,
# we replace the 'None' by a matrix with right dimension filled with np.NaN.
if cov is None:
cov = np.NaN * np.empty( (len(p),len(p)) )
chi0 = result[2]['fvec']
chisqr0 = np.sum(chi0**2)
nu = len(x) - len(p)
q = scipy.special.gammaincc(0.5*nu,0.5*chisqr0)
return p, cov, q, chisqr0
########################################################
# standard factory function for non-linear fitting
########################################################
def Cosinus(a, T, c):
"""Returns a Cosinus function.
f = a\cos(2\pi(x-x0)/T)+c
Parameter:
a = amplitude
T = period
x0 = position
c = offset in y-direction
"""
return lambda x: a*np.cos( 2*np.pi*x/float(T) ) + c
setattr(Cosinus, 'formula', r'$cos(c,a,T;x)=a\cos(2\pi x/T)+c$')
def CosinusEstimator(x, y):
c = y.mean()
a = 2**0.5 * np.sqrt( ((y-c)**2).sum() )
# better to do estimation of period from
Y = np.fft.fft(y)
N = len(Y)
D = float(x[1] - x[0])
i = abs(Y[1:N/2+1]).argmax()+1
T = (N * D) / i
return a, T, c
def CosinusNoOffset(a, T):
"""Returns a Cosinus function without constant offset.
f = a\cos(2\pi(x-x0)/T)
Parameter:
a = amplitude
T = period
x0 = position
"""
return lambda x: a*np.cos( 2*np.pi*x/float(T) )
setattr(CosinusNoOffset, 'formula', r'$cos(a,T;x)=a\cos(2\pi x/T)$')
def CosinusNoOffsetEstimator(x, y):
a = 2**0.5 * np.sqrt( (y**2).sum() )
# better to do estimation of period from
Y = np.fft.fft(y)
N = len(Y)
D = float(x[1] - x[0])
i = abs(Y[1:N/2+1]).argmax()+1
T = (N * D) / i
return a, T
def ExponentialZero(a, w, c):
"""Exponential centered at zero.
f = a*exp(-x/w) + c
Parameter:
a = amplitude
w = width
c = offset in y-direction
"""
return lambda x: a*np.exp(-x/w)+c
def ExponentialZeroEstimator(x, y):
"""Exponential Estimator without offset. a*exp(-x/w) + c"""
c=y[-1]
a=y[0]-c
w=x[-1]*0.5
return a, w, c
def GaussianZero(a, w, c):
"""Gaussian function centered at zero.
f = a*exp(-(x/w)**2) + c
Parameter:
a = amplitude
w = width
c = offset in y-direction
"""
return lambda x: a*np.exp( -(x/w)**2 ) + c
setattr(GaussianZero, 'formula', r'$f(a,w,c;x)=a\exp(-(x/w)^2)+c$')
def GaussianZeroEstimator(x, y):
"""Estimator for GaussianZero: a*exp(-0.5*(x/w)**2) + c"""
c=y[-1]
a=y[0]-c
w=x[-1]*0.5
return a, w, c
def Gaussian(c, a, x0, w):
"""Gaussian function.
f = a*exp( -0.5(x-x0)**2 / w**2 ) + c
Parameter:
a = amplitude
w = width
c = offset in y-direction
"""
return lambda x: c + a*np.exp( -0.5*((x-x0)/w)**2 )
setattr(Gaussian, 'formula', r'$f(c,a,x0,w;x)=c+a\exp(-0.5(x-x0)^2/w^2)$')
def ExponentialPowerZero(a, w, p, c):
"""Exponential decay with variable power centered at zero.
f = a*exp(-(x/w)**p) + c
Parameter:
a = amplitude
w = width
p = power
c = offset in y-direction
"""
return lambda x: a*np.exp( -(x/w)**p ) + c
setattr(ExponentialPowerZero, 'formula', r'$f(a,w,p,c;x)=a\exp(-(x/w)^p)+c$')
def ExponentialPowerZeroEstimator(x, y):
"""Estimator for exponential decay with variable offset."""
c=y[-1]
a=y[0]-c
w=x[-1]*0.5
return a, w, 2, c
def GaussianZeroEstimator(x, y):
"""Gaussian Estimator without x offset. c+ a*exp( -0.5*(x/w)**2)"""
a=y.argmax()
#x0=x[y.argmax()]
w=x[(len(x)/2)]
c=(min(y)+max(y))/2
return a, w, c
def DoubleGaussian(a1, a2, x01, x02, w1, w2):
"""Gaussian function with offset."""
return lambda x: a1*np.exp( -0.5*((x-x01)/w1)**2 ) + a2*np.exp( -0.5*((x-x02)/w2)**2 )
setattr(DoubleGaussian, 'formula', r'$f(c,a1, a2,x01, x02,w1,w2;x)=a_1\exp(-0.5((x-x_{01})/w_1)^2)+a_2\exp(-0.5((x-x_{02})/w_2)^2)$')
def DoubleGaussianEstimator(x, y):
center = (x*y).sum() / y.sum()
ylow = y[x < center]
yhigh = y[x > center]
x01 = x[ylow.argmax()]
x02 = x[len(ylow)+yhigh.argmax()]
a1 = ylow.max()
a2 = yhigh.max()
w1 = w2 = center**0.5
return a1, a2, x01, x02, w1, w2
# important note: lorentzian can also be parametrized with an a' instead of a,
# such that a' is directly related to the amplitude (a'=f(x=x0)). In this case a'=a/(pi*g)
# and f = a * g**2 / ( (x-x0)**2 + g**2 ) + c.
# However, this results in much poorer fitting success. Probably the g**2 in the numerator
# causes problems in Levenberg-Marquardt algorithm when derivatives
# w.r.t the parameters are evaluated. Therefore it is strongly recommended
# to stick to the parametrization given below.
def Lorentzian(x0, g, a, c):
"""Lorentzian centered at x0, with amplitude a, offset y0 and HWHM g."""
return lambda x: a / np.pi * ( g / ( (x-x0)**2 + g**2 ) ) + c
setattr(Lorentzian, 'formula', r'$f(x0,g,a,c;x)=a/\pi (g/((x-x_0)^2+g^2)) + c$')
def LorentzianEstimator(x, y):
c = scipy.stats.mode(y)[0][0]
yp = y - c
Y = np.sum(yp) * (x[-1] - x[0]) / len(x)
ymin = yp.min()
ymax = yp.max()
if ymax > abs(ymin):
y0 = ymax
else:
y0 = ymin
x0 = x[y.argmin()]
g = Y / (np.pi * y0)
a = y0 * np.pi * g
return x0, g, a, c
def Antibunching(alpha, c, tau, t0):
"""Antibunching. g(2) accounting for Poissonian background."""
return lambda t: c*(1-alpha*np.exp(-(t-t0)/tau))
setattr(Antibunching, 'formula', r'$g(\alpha,c,\tau,t_0;t)=c(1 - \alpha \exp(-(t-t_0)/\tau))$')
def FCSTranslationRotation(alpha, tau_r, tau_t, N):
"""Fluorescence Correlation Spectroscopy. g(2) accounting for translational and rotational diffusion."""
return lambda t: (1 + alpha*np.exp(-t/tau_r) ) / (N * (1 + t/tau_t) )
setattr(FCSTranslationRotation, 'formula', r'$g(\alpha,\tau_R,\tau_T,N;t)=\frac{1 + \alpha \exp(-t/\tau_R)}{N (1 + t/\tau_T)}$')
def FCSTranslation(tau, N):
"""Fluorescence Correlation Spectroscopy. g(2) accounting for translational diffusion."""
return lambda t: 1. / (N * (1 + t/tau) )
setattr(FCSTranslation, 'formula', r'$g(\tau,N;t)=\frac{1}{N (1 + t/\tau)}$')
def SumOverFunctions( functions ):
"""Creates a factory that returns a function representing the sum over 'functions'.
'functions' is a list of functions.
The resulting factory takes as arguments the parameters to all functions,
flattened and in the same order as in 'functions'."""
def function_factory(*args):
def f(x):
y = np.zeros(x.shape)
i = 0
for func in functions:
n = func.func_code.co_argcount
y += func(*args[i,i+n])(x)
i += n
return f
return function_factory
def brot_transitions_upper(B, D, E, phase):
return lambda theta: 3./2. * B**2/D * np.sin(theta + phase)**2 + ( B**2 * np.cos(theta + phase)**2 + (E + B**2/(2*D) * np.sin(theta+phase)**2)**2)**0.5 + D
def brot_transitions_lower(B, D, E, phase):
return lambda theta: 3./2. * B**2/D * np.sin(theta + phase)**2 - ( B**2 * np.cos(theta + phase)**2 + (E + B**2/(2*D) * np.sin(theta+phase)**2)**2)**0.5 + D
#################################################################
# convenience functions for performing some frequently used fits
#################################################################
def find_local_maxima(y,n):
"Returns the indices of the n largest local maxima of y."
half = 0.5*y.max()
mask = y>half
# get left and right edges of connected regions
right_shifted = np.append(False, mask[:-1])
left_shifted = np.append(mask[1:], False)
left_edges = np.where( np.logical_and(mask,np.logical_not(right_shifted) ))[0]
right_edges = np.where( np.logical_and(mask,np.logical_not(left_shifted)) )[0] + 1
if len(left_edges) < n:
raise RuntimeError('did not find enough edges')
indices = []
for k in range(len(left_edges)):
left = left_edges[k]
right = right_edges[k]
indices.append( y[left:right].argmax()+left )
indices = np.array(indices)
maxima = y[indices]
indices = indices[maxima.argsort()][::-1]
return indices[:n]
"""
def fit_rabi(x, y, s):
y_offset=y.mean()
yp = y - y_offset
p = fit(x, yp, CosinusNoOffset, CosinusNoOffsetEstimator)
if p[0] < 0:
p[0] = -p[0]
p[2] = ( ( p[2]/p[1] + 0.5 ) % 1 ) * p[1]
p = fit(x, yp, CosinusNoOffset, p)
p = (p[0], p[1], p[2], y_offset)
result = nonlinear_model(x, y, s, Cosinus, p)
p = result[0]
if p[2]>0.5*p[1]:
while(p[2]>0.5*p[1]):
p[2] -= p[1]
result = nonlinear_model(x, y, s, Cosinus, p)
return result
"""
def fit_rabi(x, y, s):
y_offset=y.mean()
yp = y - y_offset
p = fit(x, yp, CosinusNoOffset, CosinusNoOffsetEstimator)
if p[0] < 0:
p[0] = -p[0]
p[2] = ( ( p[2]/p[1] + 0.5 ) % 1 ) * p[1]
#p = fit(x, yp, CosinusNoOffset, p)
p = (p[0], p[1], y_offset)
return nonlinear_model(x, y, s, Cosinus, p)
def extract_pulses(y):
"""
Extracts pi, pi/2 and 3pi/2 pulses from a Rabi measurement.
Parameters:
y = the arry containing y data
Returns:
f, r, pi, 2pi = arrays containing the indices of the respective pulses and their multiples
"""
# The goal is to find local the rising and falling edges and local minima and maxima.
# First we estimate the 'middle line' by the absolute minimum and maximum.
# Then we cut the data into sections below and above the middle line.
# For every section we compute the minimum, respectively maximum.
# The falling and rising edges mark multiples of pi/2, respectively 3pi/2 pulses.
# center line
m=0.5*(y.max()+y.min())
# boolean array containing positive and negative sections
b = y < m
# indices of rising and falling edges
# rising edges: last point below center line
# falling edges: last point above center line
rising = np.where(b[:-1]&~b[1:])[0]
falling = np.where(b[1:]&~b[:-1])[0]
# local minima and maxima
pi = [ y[:rising[0]].argmin() ]
two_pi = [ y[:falling[0]].argmax() ]
for i in range(1,len(rising)):
pi.append( rising[i-1] + y[rising[i-1]:rising[i]].argmin() )
for i in range(1,len(falling)):
two_pi.append(falling[i-1] + y[falling[i-1]:falling[i]].argmax() )
# For rising edged, we always use the last point below the center line,
# however due to finite sampling and shot noise, sometimes
# the first point above the line may be closer to the actual zero crossing
for i, edge in enumerate(rising):
if y[edge+1]-m < m-y[edge]:
rising[i] += 1
# similarly for the falling edges
for i, edge in enumerate(falling):
if m-y[edge+1] < y[edge]-m:
falling[i] += 1
return np.array(falling), np.array(rising), np.array(pi), np.array(two_pi)
if __name__ == '__main__':
import cPickle
d = cPickle.load(open('point14_ESR_102000cts_cwODMR04_ODMR.pys','rb'))
#d = cPickle.load(open('2012-01-25_tsukubac12_nv39_pulsed_precise_R_ODMR.pys','rb'))
x = d['frequency']
y = d['counts']
number_of_lorentzians='auto'
threshold=0.5
y0 = baseline(y)
yp = y - y0
if threshold < 0:
yp = -yp
y_max = yp.max()
yp = yp / y_max
mask = yp>abs(threshold)
# get left and right edges of connected regions
edges = np.where(np.logical_xor(mask, np.append(False,mask[:-1])))[0]
if len(edges)%2 != 0:
raise RuntimeError('uneven number of edges')
if len(edges) < 2:
raise RuntimeError('no peak to fit')
if number_of_lorentzians is 'auto': # try to find N automatically
# attempt initial growth to kill noise
while True:
mask = grow(mask)
new_edges = np.where(np.logical_xor(mask, np.append(False,mask[:-1])))[0]
if len(new_edges) < len(edges):
edges = new_edges
else:
break
if len(edges)%2 != 0:
raise RuntimeError('uneven number of edges')
# if there is more than one region, throw away small regions and
# keep only those regions that are larger than half of the largest region
# otherwise use all regions
N = len(edges)/2
left_and_right_edges = edges.reshape((N,2))
#if len(edges)/2 > 1:
# widths = left_and_right_edges[:,1] - left_and_right_edges[:,0]
# left_and_right_edges = left_and_right_edges[ np.where(widths>0.5*widths.max())[0], : ]
# N = left_and_right_edges.shape[0]
else: # if N is specified grow until number of regions =< N
while len(edges)/2 > number_of_lorentzians:
mask = grow(mask)
edges = np.where(np.logical_xor(mask, np.append(False,mask[:-1])))[0]
if len(edges)%2 != 0:
raise RuntimeError('uneven number of edges')
N = len(edges)/2
left_and_right_edges = edges.reshape((N,2))
p = [ 0 ]
# for every local maximum, estimate parameters of Lorentzian and append them to the list of parameters p
for left, right in left_and_right_edges:
g = abs(x[right] - x[left]) # FWHM
i = y[left:right].argmax()+left # index of local minimum
x0 = x[i] # position of local minimum
a = y[i] * np.pi * g # height of local minimum in terms of Lorentzian parameter a
p += [ x0, g, a ]
p = tuple(p)
# chi for N Lorentzians with a common baseline
def chi(p):
ypp = p[0]-yp
for i in range(N):
ypp += LorentzianWithoutOffset(*p[i*3+1:i*3+4])(x)
return ypp
r = scipy.optimize.leastsq(chi, p, full_output=True)
if r[-1] == 0:
raise RuntimeError('least square fit did not work out')
p = np.array(r[0])
p[0] = p[0]*y_max*np.sign(threshold) + baseline
p[3::3] *= y_max*np.sign(threshold)
yy=NLorentzians(*p)(x)
| Python |
"""
Determination of magnetic field from the Zeeman shift of several NVs
Problem statement
Suppose we have a single crystalline bulk diamond. Suppose the crystal
is placed in a homogeneous magnetic field B. NV centers can have 4 possible
orientations with respect to the crystal lattice. We consider N single NVs
whos orientations are unknown. Using ODMR measurements we can determine
the Zeeman shift of each NV. Assume that strain is small compared to
the Zeeman shift and non-axial Zeeman shifts are negligible.
Then, for every NV, we can estimate the absolute value of
the projection of the magnetic field b_i onto the NV axis from the
Zeeman splitting s_i through
|b_i| = s_i / ( 2 * 2.8 MHz / Gauss)
Below we will evaluate we can determine the field B and the orientations
o_i of all NVs from the |b_i|.
Unit vectors along the four possible NV axis.
We consider a cube with a tetrahedron inside. The center
of the tetrahedron coincides with the center of the cube.
The four possible NV directions point along diagonals of the cube.
A possible choice is
v_1 = (1,1,1)
v_2 = (-1,-1,1)
v_3 = (1,-1,-1)
v_4 = (-1,1,-1)
In the following we will use the normalized vectors
n_i = v_i / sqrt(3)
We enumerate the vectors in the following way
0 --> n_1
1 --> n_2
2 --> n_3
3 --> n_4
Finding NV orientations and magnetic field from given splittings.
Let B be the magnetic field. Let there be N NVs with orientations
n_i. Let b_i be the magnetic field components parallel to the NVs.
We have
n_1 * B = b_1
.
.
.
n_N * B = b_N
We write this in matrix form
A B = b
Where A is a Nx3 matrix, B is a 3-vector, b is an N-vector. In general
this is an over determined system. We can find the best solution
in the least square sense by singular value decomposition.
Singular value decomposition decomposes matrix A into three matrices
A = U S V
Where U and V are unitary and S is diagonal. U is Nx3, S is 3x3 and V is 3x3.
So, we have
U S V B = b
Thus
B = V^T S^-1 U^T b
We can use this to find the field B for a given set of orientations n_i.
Now assume that the NV orientations are not known. To find the right
NV orientations, we try all possible sets of orientations. For every
set of NV orientations we compute the chisqr as
A = { n_i }
A = U S V
B' = V^T S^-1 U^T b
b' = A B'
chisqr = (b - b')**2
Chisqr is minimal when the set of NV orientations is the correct one.
Now assume we do not know b (the field components parallel to the NV axis),
but rather their absolute values |b|.
To find the solution, we also have to try the two possible signs -b and b.
"""
import numpy as np
nv_axis = np.array(((1,1,1), (-1,-1,1), (1,-1,-1), (-1,1,-1))) / 3**0.5
def solve(o, b):
A = nv_axis[o]
U, s, V = np.linalg.svd(A,full_matrices=False)
Ainv = np.dot(V.transpose(),np.dot(np.diag(1./s),U.transpose()))
x = np.dot(Ainv,b)
return x
def deviation(o,b):
B = solve(o,b)
return np.sum((np.dot(nv_axis[o],B) - b)**2, axis=0)
def chisqr(os, bs):
result = np.empty((len(os), bs.shape[1]))
for i,oi in enumerate(os):
result[i] = deviation(oi,bs)
return result
def random_samples(N,M):
return np.random.randint(0, 4, (N,M))
def random_signs(N,M):
(-1)**np.random.randint(0,2,(N,M))
def systematic_samples(N):
os = []
for m in range(4**N):
l = []
for n in range(N-1,-1,-1):
k = 4**n
l.append(m/k)
m = m%k
os.append(l)
return os
def systematic_signs(N):
signs = []
for m in range(2**N):
l = []
for n in range(N-1,-1,-1):
k = 2**n
l.append(m/k)
m = m%k
signs.append(l)
return (-1)**np.array(signs)
def find_field(b):
"""
Compute the magnetic field (least square optimum).
Input:
b = measured B0 fields (from 3 or more differently oriented NVs)
Output:
o = orientations of the NV's (up to 180 deg. ambiguity) described by
an integer between 0 and 3, representing one of the four
possible NV axis defined above.
B = magnetic field vector in the cartesian coordinate system
(same coordinate system where the NV axis vectors are defined).
landscape = least square landscape that was evaluated during computation
"""
N = len(b)
M = 2**N
orientations = systematic_samples(N)
signs = systematic_signs(N)
landscape = chisqr(orientations,(signs*b).transpose())
ii = landscape.argmin()
i = ii / M
j = ii % M
o = orientations[i]
s = signs[j]
B = solve(o, s*b)
return o, B, landscape
def angles(o, B):
return np.arccos(np.dot(nv_axis[o],B)/np.linalg.norm(B))*180/np.pi
def angles_mod90(o, B):
"""
Convenience function to compute the angle between the NV axis
and the magnetic field for a set of NV orientations 'o'.
"""
phi = np.arccos(np.dot(nv_axis[o],B)/np.linalg.norm(B))*180/np.pi
return np.array([ p if p <= 90 else 180-p for p in phi ])
def components(o, B):
"""
Convenience function to compute the parallel and perpendicular
magnetic field components for a set of NV orientations 'o'.
"""
b_para = abs(np.dot(nv_axis[o],B))
b_perp = np.array([ np.linalg.norm(v) for v in np.cross(nv_axis[o],B) ])
return np.array((b_para, b_perp)).transpose()
if __name__ == '__main__':
# magnetic field in Gauss
B0 = np.array((10., 11., 12.))
# directions of NVs
directions = [0,1,2,3]
# splitting in MHz (two times the zeeman shift)
splittings = 2 * 2.8 * abs(np.dot(nv_axis[directions],B0))
b0 = splittings / (2*2.8)
o, B, landscape = find_field(b0)
print 'B0: ', B0
print 'B: ', B
print 'phi0: ', angles(directions, B0)
print 'phi: ', angles(o, B)
print 'compo0: ', components(directions, B0)
print 'compo: ', components(o, B)
directions = [0,1,2]
# NV 19:10.6, 20:0.9, 23:1.1
splittings = 2 * 2.8 * abs(np.array((10.6, 1.1, 0.9)))
b0 = splittings / (2*2.8)
o, B, landscape = find_field(b0)
print 'B: ', B
print 'phi: ', angles(o, B)
print 'compo: ', components(o, B)
| Python |
"""
Determination of magnetic field from the Zeeman shift of several NVs.
Problem statement
Suppose we have a single crystalline bulk diamond. Suppose the crystal
is placed in a homogeneous magnetic field B. NV centers can have 4 possible
orientations with respect to the crystal lattice. We consider N single NVs
who's orientations are known. If the orientations are unknown, we
can assume specific orientations. Thereby we fix how the the lab coordinate
system is related to the cartesian crystal coordinate. Using ODMR measurements
we can determine the ESR transitions of each NV.
v1_i=e1_i-e0_i
v2_i=e2_i-e0_i
From the spin Hamiltonian model we can compute the energies e0_i, e1_i, e2_i.
We assume the energies are ordered with increasing energy. Then we can directly relate
measured energies to calculated energies.
If E<<B<<D, (i.e. strain is small compared to the Zeeman shift and
non-axial Zeeman shifts are negligible) we can use the following
linear approxmation to estimate the magnetic field vector.
For every NV, we can estimate the absolute value of
the projection of the magnetic field b_i onto the NV axis from the
Zeeman splitting s_i through
|b_i| = s_i / ( 2 * 2.8 MHz / Gauss)
Below we will evaluate how we can estimate the field B from the |b_i|
(up to certain ambiguity of the solution coming from the | | in the equation).
Unit vectors along the four possible NV axis.
We consider a cube with a tetrahedron inside. The center
of the tetrahedron coincides with the center of the cube.
The four possible NV directions point along diagonals of the cube.
A possible choice is
v_1 = (1,1,1)
v_2 = (-1,-1,1)
v_3 = (1,-1,-1)
v_4 = (-1,1,-1)
In the following we will use the normalized vectors
n_i = v_i / sqrt(3)
Finding the magnetic field from given splittings.
Let B be the magnetic field. Let there be N NVs with orientations
n_i. Let b_i be the magnetic field components parallel to the NVs.
We have
n_1 * B = b_1
.
.
.
n_N * B = b_N
We write this in matrix form
A B = b
Where A is a Nx3 matrix, B is a 3-vector, b is an N-vector. If we use
4 different NVs, this is an over determined system. We can find
the best solution in the least square sense by singular value decomposition.
Singular value decomposition decomposes matrix A into three matrices
A = U S V
Where U and V are unitary and S is diagonal. U is Nx3, S is 3x3 and V is 3x3.
So, we have
U S V B = b
Thus
B = V^T S^-1 U^T b
We can use this to find the field B if we know the signs of each equation,
such that we can remove the | |. However, in reality, the signs are unknown,
so we have to try all possible combinations of signs.
For every set of signs we compute the chisqr as
A = { n_i }
A = U S V
B' = V^T S^-1 U^T b
b' = A B'
chisqr = (b - b')**2
Chisqr is minimal when the set of signs is the correct one.
Helmut Fedder <helmut.fedder@gmail.com>
first version: 31 May 2012
"""
import numpy as np
import scipy.optimize
import scipy.special
import cPickle
import sys
# transformations to NV coordinate systems
def axis_angle(n0,n1):
"""Compute the rotation axis and angle to transform n0 to n1.
n0 and n1 are of length 1."""
n = np.cross(n0,n1)
norm_n = np.linalg.norm(n)
if norm_n == 0.:
n = np.array((0.,0.,1.))
phi = 0.0
else:
n=n/norm_n
phi = np.arccos(np.dot(n0,n1))
return n, phi
def rotation_matrix(n,phi):
"""Compute the rotation axis from an axis and angle."""
x,y,z=n
c=np.cos(phi)
s=np.sin(phi)
t=1-c
R=np.array((( t*x*x + c , t*x*y - z*s, t*x*z + y*s),
( t*y*x + z*s, t*y*y + c , t*y*z - x*s),
( t*z*x - y*s, t*z*y + x*s, t*z*z + c )))
return R
class TripletSpin():
"""Triplet state Hamiltonian with D, E and Zeeman shift."""
def __init__(self,D=2870.6,E=0.0,g=2.0028*9.27400915/6.626068):
self.D=D
self.E=E
self.g=g
def energy_levels(self,B):
"""Calculate the energy levels for given magnetic field."""
D=self.D
E=self.E
g=self.g
H = np.array((( 0., 1j*g*B[1], -1j*g*B[0]),
( -1j*g*B[1], D-E, 1j*g*B[2]),
( 1j*g*B[0], -1j*g*B[2], D+E)))
e=np.linalg.eigvalsh(H)
e.sort()
return e
def transitions(self,B):
"""
Calculate the ESR transitions for given external field.
Note that this method of sorting the energies fails above the LAC.
"""
e=self.energy_levels(B)
return np.array((e[1]-e[0],e[2]-e[0]))
class Magnetometer():
axis = np.array(((1,1,1), (-1,-1,1), (1,-1,-1), (-1,1,-1))) / 3**0.5
rotations=np.empty((4,3,3))
for i,n in enumerate(axis):
nr,phi = axis_angle(n,np.array((0,0,1)))
rotations[i] = rotation_matrix(nr,phi)
def __init__(self, hamiltonians):
self.hamiltonians = hamiltonians
def get_field(self, transitions, full_output=False):
"""
Calculate the magnetic field from the +1 and -1
energy levels of three or four NVs.
Input:
transitions energies of the +1 and -1 level [MHz]
[full_output] defaults to 'False'. If 'True', return
also the estimated starting guesses
for the non-linear fitting and all
corresponding minimized fields and
chisqrs.
Returns:
b 3-vector containing the magnetic field
vector
[b_estimates] 4x3 or 8x3 array containing the magnetic
field vectors evaluated from linear
approximation of the hamiltonian that
are used as starting guesses for
non-linear minimization
[b_candidates] 4x3 or 8x3 array containing all magnetic
field vectors obtained from non-linear
minimization
[chisqr] 4 or 8 element array containing all
chisqrs obtained from non-linear
minimization
"""
# The strategy is to perform a non-linear fit
# using the spin Hamiltonians.
#
# The nonlinear fit converges quickly
# to the global minimum, provided that the starting
# guess is chosen properly.
#
# To find a starting guess of the field, a
# suitable linear approximation of the hamiltonian
# can be used.
#
# Currently only an estimate in the range
# E<<B<<D is implemented. In this case,
# the magnetic field can be estimated from
# the energy difference between the +1 and -1
# levels. However, this estimate is ambiguous
# and 4 or 8 possible magnetic fields are
# obtained.
#
# The global minimum can be found by trying
# all different estimates as starting guess
# and afterwards choosing the one that has the
# smallest chisqr.
# calculate parallel magnetic field components from transitions
# and individual g_factors of the spin hamiltonians
# (usually the g_factors will be all the same).
g_factors = [ham.g for ham in self.hamiltonians]
if len(transitions) == 3:
g_factors = g_factors[:3]
b_parallel = 0.5*(transitions[:,1]-transitions[:,0])/g_factors
# get all possible (ambiguous) estimates of the magnetic
# field
b_estimates = self.intermediate_field_estimate(b_parallel)
# construct the chi
theo = np.empty_like(transitions)
rotations = self.rotations
hamiltonians = self.hamiltonians
def chi(b):
for i in range(len(transitions)):
theo[i] = hamiltonians[i].transitions(np.dot(rotations[i],b))
return (theo-transitions).flatten()
# perform non-linear fit with all possible starting guesses and
# evaluate the chisqr for each of them
b_candidates = np.empty_like(b_estimates)
chisqr = np.empty((len(b_estimates)))
for i,b0 in enumerate(b_estimates):
b = scipy.optimize.leastsq(chi, b0, full_output=True)[0]
b_candidates[i] = b
chisqr[i] = np.sum(chi(b)**2)
b = b_candidates[chisqr.argmin()]
if full_output:
return b, b_estimates, b_candidates, chisqr
else:
return b
def intermediate_field_estimate(self, b_parallel):
"""
Linear estimate of the field vector from the energy
difference between +1 and -1 level. Valid as long as
E<<B<<D. The solution is ambiguous due to the
unknown sign in each of the linear equations.
This function returns all possible solutions.
Input:
b_parallel parallel magnetic field component
in Gauss for three or four NVs.
Returns:
b (Nx3) array containing the ambiguous solutions for b.
"""
b = np.empty((4,3))
n_nvs = len(b_parallel)
if n_nvs == 4: # use nv_s with largest splittings
mask = np.arange(4)!=b_parallel.argmin()
b_parallel = b_parallel[mask]
elif n_nvs == 3:
mask = np.array((True, True, True))
else:
raise ValueError('Array of NV-axis must be of length 3 or 4.')
signs = np.array( ((1, 1, 1),
(1, 1,-1),
(1,-1, 1),
(1,-1,-1)
)
)
n_signs=4
b = np.empty((n_signs,3))
for i,sign in enumerate(signs):
A = (self.axis[mask].transpose()*sign).transpose()
U, s, V = np.linalg.svd(A,full_matrices=False)
Ainv = np.dot(V.transpose(),np.dot(np.diag(1./s),U.transpose()))
b[i] = np.dot(Ainv,b_parallel)
return b
if __name__=='__main__':
"""
Simulate the fitting process.
"""
# use NV Hamiltonians with default values for D,E, and g
hams = (TripletSpin(),TripletSpin(),TripletSpin(),TripletSpin())
magnetometer = Magnetometer(hams)
# chose an applied magnetic field
#b_input=np.array((0.5,10.,20.1))
b_input=np.array((0.0,10.0,20.1)) # when one of the field components is 0, there are two possible solutions
b_input=np.array((0.0,10.0,20.1)) # when two of the field components are 0, there are three possible solutions
# ToDo: check for this case in the method and issue a warning
b_parallel_input = np.array([ np.dot(b_input,axis) for axis in magnetometer.axis ])
# calculate the resulting ESR transitions [MHz]
transitions = np.array([ham.transitions(np.dot(magnetometer.rotations[i],b_input)) for i,ham in enumerate(hams[:-1])]).astype(float)
g_factors = [ham.g for ham in magnetometer.hamiltonians]
if len(transitions) == 3:
g_factors = g_factors[:3]
b_parallel = 0.5*(transitions[:,1]-transitions[:,0])/g_factors
# put an error on the transitions, such as a global shift of the resonances (due to temperature drift --> D changes)
# or random error due to measurement uncertainity
#transitions += .1*np.random.random((4,2))
#transitions += .1*np.ones((4,2))
b_output,b_est,b_cand,chisqr = magnetometer.get_field(transitions,full_output=True)
print b_input
print b_output
print np.linalg.norm(b_input)
print [np.linalg.norm(b_i) for b_i in b_est]
print [np.linalg.norm(b_i) for b_i in b_cand]
print chisqr
print b_est
print b_cand
| Python |
import numpy
from scipy import ndimage
# Enthought library imports
from traits.api import Instance, Property, Range, Float, Array,\
Tuple, Button, on_trait_change, cached_property
from traitsui.api import View, Item, HGroup, Tabbed
from enable.api import ComponentEditor, Component
from chaco.api import ArrayPlotData, ColorBar, LinearMapper, gray
from chaco.tools.api import ZoomTool
from tools.chaco_addons import SavePlot as Plot, SaveHPlotContainer as HPlotContainer, SaveTool
from tools.emod import ManagedJob
import logging
class NVFinder( ManagedJob ):
submit_button = Button(label='correct targets', desc='Performs a refocus for all targets in auto focus (without recording the drift).')
remove_button = Button(label='abort', desc='Stop the running refocus measurement.')
Sigma = Range(low=0.01, high=10., value=0.1, desc='Sigma of Gaussian for smoothing [micron]', label='sigma [micron]', mode='slider', auto_set = False, enter_set = True)
Threshold = Range(low=0, high=1000000, value=50000, desc='Threshold [counts/s]', label='threshold [counts/s]', auto_set = False, enter_set = True)
Margin = Range(low=0.0, high=100., value=4., desc='Margin [micron]', label='margin [micron]', auto_set = False, enter_set = True)
RawPlot = Instance( Component )
SmoothPlot = Instance( Component )
RegionsPlot = Instance( Component )
X = Array(dtype=numpy.float)
Y = Array(dtype=numpy.float)
z = Float()
Raw = Array(dtype=numpy.float)
Smooth = Property( trait=Array(), depends_on='Raw,Sigma' )
Thresh = Property( trait=Array(), depends_on='Raw,Smooth,Sigma,Threshold' )
RegionsAndLabels = Property( trait=Tuple(Array(),Array()), depends_on='Raw,Smooth,Thresh,Sigma,Threshold' )
Positions = Property( trait=Array(), depends_on='Raw,X,Y,Sigma,Threshold' )
XPositions = Property( trait=Array() )
YPositions = Property( trait=Array() )
ImportData = Button()
ExportTargets = Button()
traits_view = View( HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('priority', enabled_when='state != "run"'),
Item('state', style='readonly'),
),
Tabbed( Item('RawPlot', editor=ComponentEditor(), show_label=False, resizable=True),
Item('SmoothPlot', editor=ComponentEditor(), show_label=False, resizable=True),
Item('RegionsPlot', editor=ComponentEditor(), show_label=False, resizable=True) ),
HGroup( Item('ImportData', show_label=False), Item('ExportTargets', show_label=False), Item('Margin') ),
Item('Sigma'),
Item('Threshold'),
title='NV Finder', width=800, height=700, buttons=['OK'], resizable=True)
def __init__(self, confocal, auto_focus):
super(NVFinder, self).__init__()
self.confocal=confocal
self.auto_focus=auto_focus
def _run(self):
try: # refocus all targets
self.state='run'
af = self.auto_focus
confocal = af.confocal
af.periodic_focus=False
af.forget_drift()
af.current_target=None
for target in af.targets.iterkeys():
if threading.current_thread().stop_request.isSet():
break
coordinates = af.targets[target]
confocal.x, confocal.y, confocal.z = coordinates
corrected_coordinates = af.focus()
af.targets[target] = corrected_coordinates
af.trait_property_changed('targets', af.targets)
logging.getLogger().debug('NV finder: auto focus target '+str(target)+': %.2f, %.2f, %.2f'%tuple(corrected_coordinates))
self.state='idle'
except: # if anything fails, recover
logging.getLogger().exception('Error in NV finder.')
self.state='error'
@cached_property
def _get_RegionsAndLabels(self):
s = [[1,1,1], [1,1,1], [1,1,1]]
regions, labels = ndimage.label(self.Thresh, s)
return regions, labels
@cached_property
def _get_Positions(self):
positions = []
for i in range(1,self.RegionsAndLabels[1]+1):
y, x = ndimage.center_of_mass( (self.RegionsAndLabels[0] == i).astype(int) )
if y < 0:
y = 0
if y >= len(self.Y):
y = len(self.Y) - 1
if x < 0:
x = 0
if x >= len(self.X):
x = len(self.X) - 1
positions.append((self.Y[int(y)],self.X[int(x)]))
return numpy.array(positions)
def _get_XPositions(self):
if len(self.Positions) == 0:
return numpy.array(())
else:
return self.Positions[:,1]
def _get_YPositions(self):
if len(self.Positions) == 0:
return numpy.array(())
else:
return self.Positions[:,0]
@cached_property
def _get_Thresh(self):
return (self.Smooth > self.Threshold).astype(int)
@cached_property
def _get_Smooth(self):
return ndimage.gaussian_filter(self.Raw, int(self.Sigma/(self.X[1]-self.X[0])))
def _Raw_default(self):
return self.confocal.image
#return numpy.asarray(Image.open('original.png'))[:,:,0]
def _X_default(self):
return self.confocal.X
#return numpy.arange(self.Raw.shape[1])/100.
def _Y_default(self):
return self.confocal.Y
#return numpy.arange(self.Raw.shape[0])/100.
def _z_default(self):
return self.confocal.z
#return 0.0
def _RawPlot_default(self):
plotdata = ArrayPlotData(imagedata=self.Raw, x=self.XPositions, y=self.YPositions)
plot = Plot(plotdata, width=500, height=500, resizable='hv')
RawImage = plot.img_plot('imagedata', colormap=gray, xbounds=(self.X[0],self.X[-1]), ybounds=(self.Y[0],self.Y[-1]),)[0]
RawImage.x_mapper.domain_limits = (self.X[0],self.X[-1])
RawImage.y_mapper.domain_limits = (self.Y[0],self.Y[-1])
RawImage.overlays.append(ZoomTool(RawImage))
scatterplot = plot.plot( ('x', 'y'), type='scatter', marker='plus', color='yellow')
colormap = RawImage.color_mapper
colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
color_mapper=colormap,
plot=plot,
orientation='v',
resizable='v',
width=10,
padding=20)
colorbar.padding_top = plot.padding_top
colorbar.padding_bottom = plot.padding_bottom
self.RawData = plotdata
self.RawImage = RawImage
container = HPlotContainer(padding=20, fill_padding=True, use_backbuffer=True)
container.add(colorbar)
container.add(plot)
container.tools.append(SaveTool(container))
return container
def _SmoothPlot_default(self):
plotdata = ArrayPlotData(imagedata=self.Smooth)
plot = Plot(plotdata, width=500, height=500, resizable='hv')
SmoothImage = plot.img_plot('imagedata', colormap=gray, xbounds=(self.X[0],self.X[-1]), ybounds=(self.Y[0],self.Y[-1]),)[0]
SmoothImage.x_mapper.domain_limits = (self.X[0],self.X[-1])
SmoothImage.y_mapper.domain_limits = (self.Y[0],self.Y[-1])
SmoothImage.overlays.append(ZoomTool(SmoothImage))
colormap = SmoothImage.color_mapper
colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
color_mapper=colormap,
plot=plot,
orientation='v',
resizable='v',
width=10,
padding=20)
colorbar.padding_top = plot.padding_top
colorbar.padding_bottom = plot.padding_bottom
self.SmoothImage = SmoothImage
container = HPlotContainer(padding=20, fill_padding=True, use_backbuffer=True)
container.add(colorbar)
container.add(plot)
container.tools.append(SaveTool(container))
return container
def _RegionsPlot_default(self):
plotdata = ArrayPlotData(imagedata=self.RegionsAndLabels[0], x=self.XPositions, y=self.YPositions)
plot = Plot(plotdata, width=500, height=500, resizable='hv')
RegionsImage = plot.img_plot('imagedata', colormap=gray, xbounds=(self.X[0],self.X[-1]), ybounds=(self.Y[0],self.Y[-1]),)[0]
RegionsImage.x_mapper.domain_limits = (self.X[0],self.X[-1])
RegionsImage.y_mapper.domain_limits = (self.Y[0],self.Y[-1])
RegionsImage.overlays.append(ZoomTool(RegionsImage))
scatterplot = plot.plot( ('x', 'y'), type='scatter', marker='plus', color='yellow')
colormap = RegionsImage.color_mapper
colorbar = ColorBar(index_mapper=LinearMapper(range=colormap.range),
color_mapper=colormap,
plot=plot,
orientation='v',
resizable='v',
width=10,
padding=20)
colorbar.padding_top = plot.padding_top
colorbar.padding_bottom = plot.padding_bottom
self.RegionsData = plotdata
self.RegionsImage = RegionsImage
container = HPlotContainer(padding=20, fill_padding=True, use_backbuffer=True)
container.add(colorbar)
container.add(plot)
container.tools.append(SaveTool(container))
return container
def _Sigma_changed(self):
self._get_Positions()
def _Threshold_changed(self):
self._get_Positions()
# automatic update of plots
def _Smooth_changed(self):
self.SmoothImage.value.set_data(self.Smooth)
def _RegionsAndLabels_changed(self):
self.RegionsData.set_data('imagedata',self.RegionsAndLabels[0])
def _Positions_changed(self):
self.RegionsData.set_data('x',self.XPositions)
self.RegionsData.set_data('y',self.YPositions)
self.RawData.set_data('x',self.XPositions)
self.RawData.set_data('y',self.YPositions)
@on_trait_change( 'ImportData' )
def Import(self):
self.Raw = self._Raw_default()
self.X = self._X_default()
self.Y = self._Y_default()
self.z = self._z_default()
self.RawImage.index.set_data(self.X, self.Y)
self.SmoothImage.index.set_data(self.X, self.Y)
self.RegionsImage.index.set_data(self.X, self.Y)
self.RawData.set_data('imagedata', self.Raw)
self._get_Positions()
@on_trait_change( 'ExportTargets' )
def Export(self):
z = self.z
for i, pos in enumerate(self.Positions):
y, x = pos
if x > self.X[0] + self.Margin and x < self.X[-1] - self.Margin and y > self.Y[0] + self.Margin and y < self.Y[-1] - self.Margin:
self.auto_focus.add_target( str(i), np.array((x, y, z)) )
if __name__ == '__main__':
nv_finder=NVFinder(confocal,auto_focus)
nv_finder.edit_traits()
| Python |
"""
There are several distinct ways to go through different NVs and perform
certain measurement tasks.
1. using the queue and 'SwitchTarget' and 'SaveJob' and 'SetJob'
For each task, create a job and submit it to the queue.
Provide a 'special' job for switching the NV. I.e., a queue might
look like this: [ ODMR, Rabi, SwitchTarget, ODMR, Rabi, SwitchTarget, ...]
pro: - very simple
- a different set of Jobs can be submitted for individual NVs
- every part of the 'code' is basically tested separately (uses only
existing jobs) --> very low chance for errors
- queue can be modified by user on run time, e.g., if an error in the tasks
is discovered, it can be corrected
- the submitted jobs can be run with lower priority than all the usual
jobs, i.e., the queue can be kept during daily business and will
automatically resume during any free time
con: - no complicated decision making on how subsequent tasks are executed,
e.g., no possibility to do first a coarse ESR, then decide in which range
to do a finer ESR, etc.
- it is easy to forget save jobs. If everything goes well this is not a problem,
because the jobs can be saved later at any time, but if there is a crash,
unsaved jobs are lost
2. using an independent MissionControl job that is not managed by the JobManager
Write a new job, that is not managed by the JobManager, i.e., that runs independently
of the queue. This Job will submit jobs to the queue as needed.
pro: - allows complex ways to submit jobs, e.g., depending on the result of previous
measurement, with analysis performed in between, etc.
con: - cannot be changed after started
- control job will often be 'new code' and thus may have errors. It is
difficult to test --> error prone
"""
from tools.emod import Job, JobManager
from tools.utility import timestamp
import threading
#ToDo: maybe introduce lock for 'state' variable on each job?
class Mission( Job ):
def _run(self):
try:
self.state='run'
for target in auto_focus.targets.keys():
auto_focus.periodic_focus=False
while auto_focus.state != 'idle':
threading.currentThread().stop_request.wait(1.0)
if threading.currentThread().stop_request.isSet():
break
auto_focus.current_target=target
auto_focus.submit()
auto_focus.periodic_focus=True
odmr = me.odmr.ODMR()
odmr.stop_time=60
odmr.submit()
while odmr.state != 'done':
threading.currentThread().stop_request.wait(1.0)
if threading.currentThread().stop_request.isSet():
break
odmr.save(timestamp()+'_'+target+'_odmr.pys')
self.state='done'
finally:
self.state='error'
if __name__=='__main__':
mission = Mission()
mission.start()
| Python |
"""
There are several distinct ways to go through different NVs and perform
certain measurement tasks.
1. using the queue and 'SwitchTarget' and 'SaveJob' and 'SetJob'
For each task, create a job and submit it to the queue.
Provide a 'special' job for switching the NV. I.e., a queue might
look like this: [ ODMR, Rabi, SwitchTarget, ODMR, Rabi, SwitchTarget, ...]
pro: - very simple
- a different set of Jobs can be submitted for individual NVs
- every part of the 'code' is basically tested separately (uses only
existing jobs) --> very low chance for errors
- queue can be modified by user on run time, e.g., if an error in the tasks
is discovered, it can be corrected
- the submitted jobs can be run with lower priority than all the usual
jobs, i.e., the queue can be kept during daily business and will
automatically resume during any free time
con: - no complicated decision making on how subsequent tasks are executed,
e.g., no possibility to do first a coarse ESR, then decide in which range
to do a finer ESR, etc.
- it is easy to forget save jobs. If everything goes well this is not a problem,
because the jobs can be saved later at any time, but if there is a crash,
unsaved jobs are lost
2. using an independent MissionControl job that is not managed by the JobManager
Write a new job, that is not managed by the JobManager, i.e., that runs independently
of the queue. This Job will submit jobs to the queue as needed.
pro: - allows complex ways to submit jobs, e.g., depending on the result of previous
measurement, with analysis performed in between, etc.
con: - cannot be changed after started
- control job will often be 'new code' and thus may have errors. It is
difficult to test --> error prone
"""
from tools.emod import ManagedJob, JobManager
from tools.utility import timestamp
class SwitchTarget( ManagedJob ):
def __init__(self, name=None):
super(SwitchTarget, self).__init__()
self.name=name
def _run(self):
try:
self.state='run'
if self.name is None:
auto_focus.next_target()
else:
auto_focus.current_target=self.name
auto_focus._run()
finally:
self.state='idle'
def __repr__(self):
if self.name is None:
return 'Switch to next Target'
else:
return 'Switch to '+str(self.name)
class SaveJob( ManagedJob ):
def __init__(self, job, filename=None, timestamp=False):
super(SaveJob, self).__init__()
self.job = job
self.filename = filename
self.timestamp = timestamp
def _run(self):
try:
self.state='run'
job = self.job
if self.filename is None:
filename=str(job)
else:
filename=self.filename
if self.timestamp:
filename = timestamp() + '_' + filename
job.save(filename)
finally:
self.state='idle'
def __repr__(self):
if self.filename is None:
filename = str(self.job)
else:
filename = self.filename
if self.timestamp:
filename = '<timestamp>_' + filename
return 'Save '+str(self.job)+' to '+filename
class SetJob( ManagedJob ):
def __init__(self, job, d):
super(SetJob, self).__init__()
self.job = job
self.d = d
def _run(self):
try:
self.state='run'
self.job.set_items(self.d)
finally:
self.state='idle'
def __repr__(self):
return 'Set items '+str(self.d)+' of job '+str(self.job)
for target in auto_focus.targets.keys():
JobManager().submit(SwitchTarget(target))
odmr = me.odmr.ODMR()
odmr.stop_time=360
JobManager().submit(odmr)
JobManager().submit(SaveJob(odmr,target+'_odmr.pys',timestamp=True))
| Python |
import ctypes
import numpy
import traceback
map = {'laser':2, 'mw':1, 'microwave':1, 'trigger':3, 'SequenceTrigger':0, 'awgTrigger':0}
CLOCK = 400.0
DT = 2.5
dll = ctypes.cdll.LoadLibrary('spinapi.dll')
PULSE_PROGRAM = 0
CONTINUE = 0
STOP = 1
LOOP = 2
END_LOOP = 3
LONG_DELAY = 7
BRANCH = 6
#ON = 6<<21 # this doesn't work even though it is according to documentation
ON = 0xE00000
def chk(err):
"""a simple error checking routine"""
if err < 0:
dll.pb_get_error.restype = ctypes.c_char_p
err_str = dll.pb_get_error()
#raise RuntimeError('PulseBlaster error: %s' % err_str)
print err_str
pi3d.get_logger().error('PulseBlaster error: ' + err_str + ''.join(traceback.format_stack()))
def High(channels):
"""Set specified channels to high, all others to low."""
pi3d.get_logger().debug(str(channels))
dll.pb_close()
chk(dll.pb_init())
chk(dll.pb_set_clock(ctypes.c_double(CLOCK)))
chk(dll.pb_start_programming(PULSE_PROGRAM))
chk(dll.pb_inst_pbonly(ON|flags(channels), STOP, None, ctypes.c_double(100)))
chk(dll.stop_programming())
chk(dll.start_pb())
chk(dll.pb_close())
def Sequence(sequence, loop=True):
"""Run sequence of instructions"""
pi3d.get_logger().debug(str(sequence))
#we pb_close() without chk(): this might create an error if board was already closed, but resets it if it was still open
dll.pb_close()
chk(dll.pb_init())
chk(dll.pb_set_clock(ctypes.c_double(CLOCK)))
chk(dll.pb_start_programming(PULSE_PROGRAM))
start = write(*sequence[0])
for step in sequence[1:]:
label = write(*step)
if label > 2**12 - 2:
print 'WARNING in PulseBlaster: command %i exceeds maximum number of commands.' % label
channels, dt = sequence[-1]
# N = int(numpy.round(dt/DT))
# if N > 256:
# raise RuntimeError, 'Length in STOP / BRANCH exceeds maximum value.'
if loop == False:
label = chk(dll.pb_inst_pbonly(ON|flags(channels), STOP, None, ctypes.c_double( 12.5 ) ))
else:
label = chk(dll.pb_inst_pbonly(ON|flags([]), BRANCH, start, ctypes.c_double( 12.5 ) ))
if label > 2**12 - 2 :
print 'WARNING in PulseBlaster: command %i exceeds maximum number of commands.' % label
chk(dll.stop_programming())
chk(dll.start_pb())
chk(dll.pb_close())
def write(channels, dt):
channel_bits = flags(channels)
N = int(numpy.round( dt / DT ))
# if N == 0 or N == 1:
# label = chk(dll.pb_inst_direct( ctypes.byref(ctypes.c_int(1<<21|channel_bits)), CONTINUE, None, 2 ))
# elif N == 2:
# label = chk(dll.pb_inst_pbonly( 2<<21|channel_bits, CONTINUE, None, ctypes.c_double( 2*DT ) ))
# elif N == 3:
# label = chk(dll.pb_inst_pbonly( 3<<21|channel_bits, CONTINUE, None, ctypes.c_double( 2*DT ) ))
# elif N == 4:
# label = chk(dll.pb_inst_pbonly( 4<<21|channel_bits, CONTINUE, None, ctypes.c_double( 2*DT ) ))
# elif N == 5:
# label = chk(dll.pb_inst_direct( ctypes.byref(ctypes.c_int(5<<21|channel_bits)), CONTINUE, None, 3 ))
if N <= 256:
label = chk(dll.pb_inst_pbonly( ON|channel_bits, CONTINUE, None, ctypes.c_double( N*DT ) ))
else:
# successively try factorization, reducing N, and putting the subtracted amount into an additional short command if necessary
B = N
i = 4
while True:
M, K = factor(N)
#print M, K, i
if M > 4:
if K == 1:
label = chk(dll.pb_inst_pbonly( ON|channel_bits, CONTINUE, None, ctypes.c_double( M*DT ) ))
elif K < 1048577:
label = chk(dll.pb_inst_pbonly( ON|channel_bits, LONG_DELAY, K, ctypes.c_double( M*DT ) ))
else:
raise RuntimeError, 'Loop count in LONG_DELAY exceedes maximum value.'
if i > 4:
chk(dll.pb_inst_pbonly( ON|channel_bits, CONTINUE, None, ctypes.c_double( i*DT ) ))
break
i += 1
N = B - i
return label
def flags(channels):
bits = 0
for channel in channels:
bits = bits | 1<<map[channel]
return bits
#def flags(channels):
# bits = numpy.zeros((24,), dtype=numpy.bool)
# for channel in channels:
# bits[map[channel]] = 1
# s = ''
# for bit in bits:
# s = '%i'%bit + s
# return int(s,2)
def factor(x):
i = 256
while i > 4:
if x % i == 0:
return i, x/i
i -= 1
return 1, x
def Light():
High(['laser'])
def Night():
High([])
def Open():
High(['laser','mw'])
def test():
Sequence([ (['laser'], 642.5),
([ ], 12.5),
#(['laser'], 642.5),
#([ ], 12.5),
#(['laser'], 1282.5),
#([ ], 12.5),
#(['laser'], 3000),
#([ ], 12.5),
], loop=True)
if __name__ == '__main__':
pass | Python |
# ToDo: convert to class
import numpy
from visa import instrument
import struct
import dtg_io
DTG = instrument('GPIB0::1::INSTR')
#DTG.chunk_size=2**20
DTG.timeout=100
ChunkSize = 1000000
# block_granularity and min_block_size: Constants of the DTG.
block_granularity = 4
min_block_size = 1000 #bytes
#DTG.write('TBAS:CRAN 15')
#DTG.write('TBAS:SMODe SOFTware')
#def WriteVector(Block, Channel, data, offset ):
# s = '"'
# for n in data:
# s+= str(n)
# s += '"'
# DTG.write('BLOC:SEL "'+Block+'"')
# DTG.write('SIGN:DATA "Group1['+str(Channel)+']", %i, %i, '%(offset, len(data)) + s )
ChannelMap = {'laser':0, 'mw':1, 'mw_a':1, 'mw_b':4, 'mw_y':1, 'mw_x':4, 'sequence':3, 'aom':2, 'ch0':0, 'ch1':1, 'ch2':2, 'ch3':3}
path_on_this_pc = 'Z:\setup.dtg'
path_on_dtg = 'C:\pulsefiles\setup.dtg'
#ChannelMapBin = {'laser':'\x00', 'mw':'\x01', 'trigger':'\x04', 'SequenceTrigger':'\x02'}
def ChannelsToInt(channels):
bits = 0
for channel in channels:
bits |= 1 << ChannelMap[channel]
return bits
def gen_block(length, id, name):
"""
gen_block: generate a tree for a DTG block of given length, id and name
'name' is assumed to be packed into a numpy array.
'length' and 'id' are integers
"""
length_entry = numpy.array([int(length)])
return [
['DTG_BLOCK_RECID',
30,
[
['DTG_ID_RECID', 2, numpy.array([id], dtype=numpy.int16)],
['DTG_NAME_RECID', name.nbytes, name],
['DTG_SIZE_RECID', length_entry.nbytes, length_entry]]]
]
def gen_pattern(blockid, pulses):
"""
gen_pattern: generate a python tree for a pattern command to fill block 'blockid'
with the binary sequence 'pulses'
"""
return [
['DTG_PATTERN_RECID',
1,
[['DTG_GROUPID_RECID', 2, numpy.array([0], dtype=numpy.int16)],
['DTG_BLOCKID_RECID', 2, numpy.array([blockid], dtype=numpy.int16)],
['DTG_PATTERNDATA_RECID',
1,
pulses]
]]
]
def gen_sequence(label, subname, Nrep, goto):
"""
gen_sequence: generate a python tree for a sequence entry of a given label,
name of the subsequence, number of repetitions 'Nrep' and goto label 'goto'.
all strings are assumed to by numpy arrays. Nrep is an int
"""
return [
['DTG_MAINSEQUENCE_RECID',
51,
[
['DTG_LABEL_RECID', label.nbytes, label],
['DTG_WAITTRIGGER_RECID', 2, numpy.array([0], dtype=numpy.int16)],
['DTG_SUBNAME_RECID', subname.nbytes, subname],
['DTG_REPEATCOUNT_RECID', 4, numpy.array([Nrep], dtype=numpy.int32)], # was 0,0
['DTG_JUMPTO_RECID', 1, numpy.array([0], dtype=numpy.int8)],
['DTG_GOTO_RECID', goto.nbytes, goto]]
],
]
def BlockToDtgTree(BLOCK):
pulses = numpy.array([], dtype=numpy.int8)
total = 0 # total length of last subsequence
subseq = 2 #index to the current subsequence
break_len = 1000 # length of the macrobreak
break_entry = numpy.array([int(break_len)])
start_label = numpy.array('START\x00', dtype='|S')
#blocks, sequence, patterns: trees holding the sequence data.
#After initialization, they contain the break block only
blocks = [
['DTG_BLOCK_RECID',
30,
[['DTG_ID_RECID', 2, numpy.array([0], dtype=numpy.int16)],
['DTG_NAME_RECID', 6, numpy.array('BREAK\x00', dtype='|S')],
['DTG_SIZE_RECID', break_entry.nbytes, break_entry]]],
]
sequence = [
]
patterns = [
['DTG_PATTERN_RECID',
1,
[['DTG_GROUPID_RECID', 2, numpy.array([0], dtype=numpy.int16)],
['DTG_BLOCKID_RECID', 2, numpy.array([0], dtype=numpy.int16)],
['DTG_PATTERNDATA_RECID',
1,
numpy.zeros((1,break_len), dtype = numpy.int8)]
]]
]
complete = numpy.sum([length for channels,length in BLOCK])
consumed = 0
for channels, length in BLOCK:
length = round(length)
consumed += length
#check whether the current step is a break. If so, split it up into a macrobreak (using the BREAK blcok)
#and its remainder. Start a new sequence from the remainder
#Do not do this for the last min_block_size part of the sequence. This will be appended as a single block
if channels == [] and consumed < complete - min_block_size:
#if the current sequence ('pulses' of length 'total') is not a multiple of block_granularity
#and not long enough yet, extend it by deducing a tax from the break
tax = (block_granularity - total%block_granularity) % block_granularity
tax += max(min_block_size - (total+tax), 0)
tax = min(tax, length) # do not tax more than the whole break
total += tax
length -= tax
pulses = numpy.append(pulses, ChannelsToInt(channels)*numpy.ones((1,tax), dtype=numpy.int8))
Tmacro = int(length/break_len)
if Tmacro > 0:
# if we have accumulated a sequence, dump it into the tree
if total > 0:
blockname = numpy.array('BLOCK' + str(subseq) + '\x00', dtype='|S')
blocks.extend(gen_block(int(total), subseq, blockname))
patterns.extend(gen_pattern(subseq, pulses))
sequence.extend(gen_sequence(numpy.array('\x00', dtype='|S'),
blockname,
numpy.array([1], dtype=numpy.int32),
numpy.array('\x00', dtype='|S')
))
total = 0
# append Tmacro repetitions of the macrobreak
sequence.append(
['DTG_MAINSEQUENCE_RECID',
51,
[
['DTG_LABEL_RECID', 1, numpy.array([0], dtype=numpy.int8)],
['DTG_WAITTRIGGER_RECID', 2, numpy.array([0], dtype=numpy.int16)],
['DTG_SUBNAME_RECID', 6, numpy.array('BREAK\x00', dtype='|S')],
['DTG_REPEATCOUNT_RECID', 4, numpy.array([Tmacro], dtype=numpy.int32)], # was 0,0
['DTG_JUMPTO_RECID', 1, numpy.array([0], dtype=numpy.int8)],
['DTG_GOTO_RECID', 1, numpy.array([0], dtype=numpy.int8)]
]]
)
# append the remainder to the binary sequence
length = length - Tmacro*break_len
total = length
subseq +=1
pulses = ChannelsToInt(channels)*numpy.ones((1,length), dtype=numpy.int8)
else: # Tmacro=0, append the whole break to the sequence
total += length
pulses = numpy.append(pulses, ChannelsToInt(channels)*numpy.ones((1,length), dtype=numpy.int8))
else: # mw or laser pulse. Append it to the sequence
total += length
pulses = numpy.append(pulses, ChannelsToInt(channels)*numpy.ones((1,length), dtype=numpy.int8))
#append the accumulated pulse sequence
if total > 0:
blockname = numpy.array('BLOCK' + str(subseq) + '\x00', dtype='|S')
blocks.extend(gen_block(int(total), subseq, blockname))
patterns.extend(gen_pattern(subseq, pulses))
sequence.extend(gen_sequence(numpy.array('\x00', dtype='|S'),
blockname,
numpy.array([1], dtype=numpy.int32),
numpy.array('\x00', dtype='|S')
))
#finally, label the first subsequence as "start", point the goto of the last subsequence there
sequence[0][2] = dtg_io.change_leaf(sequence[0][2], 'DTG_LABEL_RECID', 5, numpy.array('START\x00', dtype='|S'))
sequence[-1][2] = dtg_io.change_leaf(sequence[-1][2], 'DTG_GOTO_RECID', 5, numpy.array('START\x00', dtype='|S'))
binary_pattern = []
binary_pattern.extend(blocks)
binary_pattern.extend(sequence)
binary_pattern.extend(patterns)
# construct a DTG tree by appending binary_pattern to the scaffold tree.
dtgfile = dtg_io.load_scaffold()
view = dtgfile[-1][-1].pop()
for node in binary_pattern:
dtgfile[-1][-1].append(node)
dtgfile[-1][-1].append(view)
dtgfile = dtg_io.recalculate_space(dtgfile)[1]
return dtgfile
def Sequence(BLOCK, loop=False):
Stop()
# set sequence length
#if loop:
# DTG.write('SEQ:LENG inf')
#else:
length = sum([round(plen) for (mask, plen) in BLOCK])
m = length % 4
#if block size is not a multiple of 4, increase first laser wait to avoid block size granularity error
if length % 4:
BLOCK[2] = (BLOCK[2][0], BLOCK[2][1] + 4-m)
nlength = sum([round(plen) for (mask, plen) in BLOCK])
#print "adjusted length from " + str(length) + " to " + str(nlength) + "\n"
# generate a setup tree for the DTG containing the new pulse sequence
dtgtree = BlockToDtgTree(BLOCK)
# write this file onto the DTG (via Samba)
fil = open(path_on_this_pc, 'wb')
dtg_io.dump_tree(dtgtree, fil)
fil.close()
# fil = open('D:/Python/pi3diamond/current_pattern.dtg', 'wb')
# dtg_io.dump_tree(dtgtree, fil)
# fil.close()
#load and execute the generated setup file
DTG.write('MMEM:LOAD "'+path_on_dtg+'"')
DTG.write('OUTP:STAT:ALL ON')
while not int(DTG.ask('TBAS:RUN?')):
DTG.write('TBAS:RUN ON')
return nlength
def State(flag = None):
if flag is not None:
if (flag):
DTG.write('TBAS:RUN ON')
else:
DTG.write('TBAS:RUN OFF')
return DTG.ask('TBAS:RUN?')
def Run():
DTG.write('OUTP:STAT:ALL ON')
DTG.write('TBAS:RUN ON')
return DTG.ask('TBAS:RUN?')
def Stop():
DTG.write('TBAS:RUN OFF')
DTG.write('OUTP:STAT:ALL OFF')
return DTG.ask('TBAS:RUN?')
def Light():
Stop()
Sequence( [ (['laser'], 1000), ] )
def Night():
Stop()
Sequence( [ ([], 1000), ] )
def Open():
Stop()
Sequence( [ (['laser','mw'], 1000), ] )
def High(chans): #chans: sequence of channel id strings, like ['laser', 'mw']
Stop()
Sequence( [ (chans, 1000), ] )
| Python |
"""
This file is part of pi3diamond.
pi3diamond is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pi3diamond is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with diamond. If not, see <http://www.gnu.org/licenses/>.
Copyright (C) 2009-2011 Helmut Fedder <helmut.fedder@gmail.com>
"""
import visa
import numpy
import logging
class SMIQ():
"""Provides control of SMIQ family microwave sources from Rhode und Schwarz with GPIB via visa."""
_output_threshold = -90.0
def __init__(self, visa_address='GPIB0::28'):
self.visa_address = visa_address
def _write(self, string):
try: # if the connection is already open, this will work
self.instr.write(string)
except: # else we attempt to open the connection and try again
try: # silently ignore possible exceptions raised by del
del self.instr
except Exception:
pass
self.instr = visa.instrument(self.visa_address)
self.instr.write(string)
def _ask(self, str):
try:
val = self.instr.ask(str)
except:
self.instr = visa.instrument(self.visa_address)
val = self.instr.ask(str)
return val
def getPower(self):
return float(self._ask(':POW?'))
def setPower(self, power):
if power is None or power < self._output_threshold:
logging.getLogger().debug('SMIQ at '+str(self.visa_address)+' turning off.')
self._write(':FREQ:MODE CW')
self._write(':OUTP OFF')
return
logging.getLogger().debug('SMIQ at '+str(self.visa_address)+' setting power to '+str(power))
self._write(':FREQ:MODE CW')
self._write(':POW %f' % float(power))
self._write(':OUTP ON')
def getFrequency(self):
return float(self._ask(':FREQ?'))
def setFrequency(self, frequency):
self._write(':FREQ:MODE CW')
self._write(':FREQ %e' % frequency)
def setOutput(self, power, frequency):
self.setPower(power)
self.setFrequency(frequency)
def initSweep(self, frequency, power):
if len(frequency) != len(power):
raise ValueError('Length mismatch between list of frequencies and list of powers.')
self._write(':FREQ:MODE CW')
self._write(':LIST:DEL:ALL')
self._write('*WAI')
self._write(":LIST:SEL 'ODMR'")
FreqString = ''
for f in frequency[:-1]:
FreqString += ' %f,' % f
FreqString += ' %f' % frequency[-1]
self._write(':LIST:FREQ' + FreqString)
self._write('*WAI')
PowerString = ''
for p in power[:-1]:
PowerString += ' %f,' % p
PowerString += ' %f' % power[-1]
self._write(':LIST:POW' + PowerString)
self._write(':LIST:LEAR')
self._write(':TRIG1:LIST:SOUR EXT')
# we switch frequency on negative edge. Thus, the first square pulse of the train
# is first used for gated count and then the frequency is increased. In this way
# the first frequency in the list will correspond exactly to the first acquired count.
self._write(':TRIG1:SLOP NEG')
self._write(':LIST:MODE STEP')
self._write(':FREQ:MODE LIST')
self._write('*WAI')
N = int(numpy.round(float(self._ask(':LIST:FREQ:POIN?'))))
if N != len(frequency):
raise RuntimeError, 'Error in SMIQ with List Mode'
def resetListPos(self):
self._write(':ABOR:LIST')
self._write('*WAI')
class SMR20():
"""Provides control of SMR20 microwave source from Rhode und Schwarz with GPIB via visa."""
_output_threshold = -90.0
def __init__(self, visa_address='GPIB0::28'):
self.visa_address = visa_address
def _write(self, string):
try: # if the connection is already open, this will work
self.instr.write(string)
except: # else we attempt to open the connection and try again
try: # silently ignore possible exceptions raised by del
del self.instr
except Exception:
pass
self.instr = visa.instrument(self.visa_address)
self.instr.write(string)
def _ask(self, str):
try:
val = self.instr.ask(str)
except:
self.instr = visa.instrument(self.visa_address)
val = self.instr.ask(str)
return val
def getPower(self):
return float(self._ask(':POW?'))
def setPower(self, power):
if power is None or power < self._output_threshold:
self._write(':OUTP OFF')
return
self._write(':FREQ:MODE CW')
self._write(':POW %f' % float(power))
self._write(':OUTP ON')
def getFrequency(self):
return float(self._ask(':FREQ?'))
def setFrequency(self, frequency):
self._write(':FREQ:MODE CW')
self._write(':FREQ %e' % frequency)
def setOutput(self, power, frequency):
self.setPower(power)
self.setFrequency(frequency)
def initSweep(self, frequency, power):
if len(frequency) != len(power):
raise ValueError('Length mismatch between list of frequencies and list of powers.')
self._write(':FREQ:MODE CW')
self._write(':LIST:DEL:ALL')
self._write('*WAI')
self._write(":LIST:SEL 'ODMR'")
FreqString = ''
for f in frequency[:-1]:
FreqString += ' %f,' % f
FreqString += ' %f' % frequency[-1]
self._write(':LIST:FREQ' + FreqString)
self._write('*WAI')
PowerString = ''
for p in power[:-1]:
PowerString += ' %f,' % p
PowerString += ' %f' % power[-1]
self._write(':LIST:POW' + PowerString)
self._write(':TRIG1:LIST:SOUR EXT')
self._write(':TRIG1:SLOP NEG')
self._write(':LIST:MODE STEP')
self._write(':FREQ:MODE LIST')
self._write('*WAI')
N = int(numpy.round(float(self._ask(':LIST:FREQ:POIN?'))))
if N != len(frequency):
raise RuntimeError, 'Error in SMIQ with List Mode'
def resetListPos(self):
self._write(':ABOR:LIST')
self._write('*WAI')
from nidaq import SquareWave
class HybridMicrowaveSourceSMIQNIDAQ():
"""Provides a microwave source that can do frequency sweeps
with pixel clock output using SMIQ and nidaq card."""
def __init__(self, visa_address, square_wave_device):
self.source = SMIQ( visa_address )
self.square_wave = SquareWave( square_wave_device )
def setOutput(self, power, frequency, seconds_per_point=1e-2):
"""Sets the output of the microwave source.
'power' specifies the power in dBm. 'frequency' specifies the
frequency in Hz. If 'frequency' is a single number, the source
is set to cw. If 'frequency' contains multiple values, the
source sweeps over the frequencies. 'seconds_per_point' specifies
the time in seconds that the source spends on each frequency step.
A sweep is excecute by the 'doSweep' method."""
# in any case set the CW power
self.source.setPower(power)
self.square_wave.setTiming(seconds_per_point)
try: length=len(frequency)
except TypeError: length=0
self._length=length
if length:
self.source.setFrequency(frequency[0])
self.source.initSweep(frequency, power*numpy.ones(length))
else:
self.source.setFrequency(frequency)
def doSweep(self):
"""Perform a single sweep."""
if not self._length:
raise RuntimeError('Not in sweep mode. Change to sweep mode and try again.')
#self.source.resetListPos()
self.square_wave.setLength(self._length)
self.square_wave.output()
| Python |
"""
This file is part of Diamond. Diamond is a confocal scanner written
in python / Qt4. It combines an intuitive gui with flexible
hardware abstraction classes.
Diamond is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Diamond is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with diamond. If not, see <http://www.gnu.org/licenses/>.
Copyright (C) 2009 Helmut Rathgen <helmut.rathgen@gmail.com>
"""
from visa import instrument
ANRITSU = instrument('TCPIP::192.168.0.3::inst0::INSTR')
def On():
ANRITSU.write('OUTP:STAT ON')
ANRITSU.write('*WAI')
return ANRITSU.ask('OUTP:STAT?')
def Off():
ANRITSU.write('OUTP:STAT OFF')
return ANRITSU.ask('OUTP:STAT?')
def Power(power=None):
if power != None:
ANRITSU.write(':POW %f' % power)
return float(ANRITSU.ask(':POW?'))
def Freq(f=None):
if f != None:
ANRITSU.write(':FREQ %e' % f)
return float(ANRITSU.ask(':FREQ?'))
def CW(f=None, power=None):
ANRITSU.write(':FREQ:MODE CW')
if f != None:
ANRITSU.write(':FREQ %e' % f)
if power != None:
ANRITSU.write(':POW %f' % power)
def List(freq, power):
ANRITSU.write(':POW %f' % power)
ANRITSU.write(':LIST:TYPE FREQ')
ANRITSU.write(':LIST:IND 0')
s = ''
for f in freq[:-1]:
s += ' %f,' % f
s += ' %f' % freq[-1]
ANRITSU.write(':LIST:FREQ' + s)
ANRITSU.write(':LIST:STAR 0')
ANRITSU.write(':LIST:STOP %i' % (len(freq)-1) )
ANRITSU.write(':LIST:MODE MAN')
ANRITSU.write('*WAI')
def Trigger(source, pol):
ANRITSU.write(':TRIG:SOUR '+source)
ANRITSU.write(':TRIG:SLOP '+pol)
ANRITSU.write('*WAI')
def ResetListPos():
ANRITSU.write(':LIST:IND 0')
ANRITSU.write('*WAI')
def ListOn():
ANRITSU.write(':FREQ:MODE LIST')
ANRITSU.write(':OUTP ON')
ANRITSU.write('*WAI')
def Modulation(flag=None):
if flag is not None:
if flag:
ANRITSU.write('PULM:SOUR EXT')
ANRITSU.write('PULM:STAT ON')
else:
ANRITSU.write('PULM:STAT OFF')
return ANRITSU.ask('PULM:STAT?')
Modulation(True)
| Python |
'''
Created on 20.04.2012
author: Helmut Fedder
'''
import time
import numpy as np
# helper class to represent a visa instrument via a socket
class SocketInstrument():
def __init__(self, device):
import socket
host,port = device.split(':')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
self.sock = sock
def write(self, cmd):
"""Sends a command over the socket"""
cmd_string = cmd + '\n'
sent = self.sock.sendall(cmd_string)
if sent != None:
raise RuntimeError('Transmission failed')
time.sleep(.1) #add a timeout for the transfer to take place. Should be replaced by a proper error handling at some point
def ask(self,question):
"""sends the question and receives the answer"""
self.write(question)
answer = self.sock.recv(2048)#2000
return answer[:-2]
def close(self):
self.sock.close()
class HMP2030():
def __init__(self,device, voltage_max=20.0, current_max=2.0, fuse_voltage_max=20.0, fuse_current_max=2.5):
"""
Provides communication with a HMP2030 power supply
via USB (virtual COM) or LAN.
Usage Examples:
hmp = HMP2030('ASRL11::INSTR')
hmp = HMP2030('192.168.0.11:50000')
Parameters:
device: string that describes the device (see examples above)
Optional Parameters:
voltage_max: maximum allowed voltage
current_max: maximum allowed current
fuse_voltage_max: maximum allowed fuse voltage
fuse_current_max: maximum allowed fuse current
"""
if '::' in device:
self._connect_serial(device)
else:
self._connect_lan(device)
self.voltage_max=voltage_max
self.current_max=current_max
self.fuse_voltage_max=fuse_voltage_max
self.fuse_current_max=fuse_current_max
def _connect_serial(self, device):
import visa
instr=visa.instrument('ASRL11::INSTR')
instr.term_chars='\n'
instr.chunk_size=4096
instr.timeout=1.0
self.instr = instr
def _connect_lan(self, device):
"""connects to the hameg powersupply"""
self.instr=SocketInstrument(device)
# convenience method
def set_output(self,channel,current):
"""Set the current on the given channel. Turn output on or off depending on the specified current."""
self.set_ch(channel)
if current<=0 or current is None:
self.stop()
else:
self.set_current(current)
self.run()
#functions to perform different SCPI-commands
def set_ch(self,ch):
"""sets the channel 1, 2 or 3"""
if ch in [1,2,3]:
self.instr.write('INST OUPT' + str(ch))
else:
raise ValueError('Wrong channel number. Chose 1, 2 or 3.')
def get_ch(self):
"""asks for the selected channel"""
channel = int(self.instr.ask('INST:NSEL?'))
return channel
def status(self,ch):
"""gets the current status of the selected channel (CC or CV)"""
state = self.instr.ask('STAT:QUES:INST:ISUM' + str(ch) + ':COND?')
if state == 1:
return 'CC'
elif state == 2:
return 'CV'
else:
print "Couldn't read the status of the selected channel."
def set_voltage(self,volt):
"""sets the voltage to the desired value"""
if volt < 0:
print 'The selected voltage cannot be set.'
elif volt > self.voltage_max : #the voltage_max will be set on the power supply if volt exceed voltage_max
self.instr.write('VOLT %1.3f' %self.voltage_max)
print 'The set voltage exceed the maximum voltage: %1.3f' %self.voltage_max
else:
self.instr.write('VOLT %1.3f' %volt)
def set_voltage_step(self,vstep):
"""increases the voltage by a desired step"""
vset = get_voltage()
set_voltage(vset + vstep)
def get_voltage(self):
"""measures the voltage"""
voltage = float(self.instr.ask('MEAS:VOLT?'))
return voltage
def set_current(self,curr):
"""sets the current to the desired value"""
if curr < 0:
print 'The selected current cannot be set.'
elif curr > self.current_max : #the voltage_max will be set on the power supply if volt exceed voltage_max
self.instr.write('CURR %1.3f' %self.current_max)
print 'The set current exceed the maximum current: %1.3f' %self.current_max
else:
self.instr.write('CURR %1.3f' %curr)
def set_current_step(self,cstep):
"""increases the current by a desired step"""
cset = get_current()
set_current(cset + cstep)
def get_current(self):
"""measures the current"""
current = float(self.instr.ask('MEAS:CURR?'))
return current
def set_arbitrary(self,ch, seq, N):
"""performs a sequence of voltage and current values for a given time on one channel with a number of repetitions.
ch: channel for output
seq: sequence to be set in form of a nested list = [(voltage,current,time),(..),(..),...]
N: number of repetitions [1..255]. 0 means infinite repetitions."""
seq_ary = np.array(seq)
if max(seq_ary[:,0]) > self.voltage_max:
print 'The set voltage exceed the maximum voltage: %1.3f' %self.voltage_max
elif max(seq_ary[:,1]) > self.current_max:
print 'The set current exceed the maximum current: %1.3f' %self.current_max
elif min(seq_ary[:,2]) < .5:
print 'The set time is shorter than 0.5s.'
elif seq >= 0:
print 'Negative value of voltage, current or time.'
elif ch != [1,2,3]:
print 'Wrong channel number. Chose 1, 2 or 3.'
elif N != range(0,256):
print 'The set repetitions are outside the range [0,255].'
else:
self.instr.write('ARB:DATA' + ' ' + str(seq).translate(None, '[()] '))
self.instr.write('ARB:REP' + ' ' + str(N))
self.instr.write('ARB:TRANS' + ' ' + str(ch))
self.instr.write('ARB:STAR' + ' ' + str(ch))
set_ch(ch)
run()
def stop_arbitrary(self,ch):
"""stops the arbitrary sequence of a specified channel ch, but leafs the output on."""
self.instr.write('ARB:STOP' + ' ' + str(ch))
def get_arbitrary(self,ch):
"""gets the number of performed repetitions of the arbitrary sequence"""
set_ch(ch)
num = int(self.instr.ask('ARB:REP?'))
return num
def get_all(self):
"""gets the measured values for all channels in the form [(ch,V,A),]"""
l = []
for i in [1,2,3]:
set_ch(i)
vset = get_voltage()
cset = get_current()
l.append((i,vset,cset))
return l
def run(self):
"""turns the output from the chosen channel on"""
self.instr.write('OUTP ON')
def run_all(self):
"""turns the output from all channels on"""
set_ch(1)
self.instr.write('OUTP:SEL ON')
set_ch(2)
self.instr.write('OUTP:SEL ON')
set_ch(3)
self.instr.write('OUTP:SEL ON')
self.instr.write('OUTP:GEN ON')
def stop(self):
"""turns the output from the chosen channel off"""
self.instr.write('OUTP OFF')
def stop_all(self):
"""stops the output of all channels"""
set_ch(1)
self.instr.write('OUTP:SEL OFF')
set_ch(2)
self.instr.write('OUTP:SEL OFF')
set_ch(3)
self.instr.write('OUTP:SEL OFF')
self.instr.write('OUTP:GEN OFF')
def start(self):
"""starts up the whole system"""
self.instr.write('*RST') #resets the device
self.instr.write('SYST:REM') #sets the instrument to remote control
def close(self):
"""stops and disconnects the device"""
stop_all()
self.instr.close()
def beep(self):
"""gives an acoustical signal from the device"""
self.instr.write('SYST:BEEP')
def error_list(self):
"""prints all errors from the error register."""
error = str(self.instr.ask('SYST:ERR?'))
return error
def OVP(self,fuse_voltage_max):
"""sets the Over-Voltage-Protection to the value fuse_voltage_max for a selected channel"""
if fuse_voltage_max < 0:
print 'The selected value for voltage protection cannot be set.'
elif fuse_voltage_max > 32.0: #the maximal voltage which the HMP2030 supplies
print 'The set voltage exceed the maximum voltage: 32V'
else:
self.instr.write('VOLT:PROT %1.3f' %fuse_voltage_max)
def FUSE(self,fuse_current_max):
"""sets the fuse to the value fuse_current_max and the delay time to 0ms for a selected channel"""
self.instr.write('FUSE ON')
if fuse_current_max < 0:
print 'The selected value for current fuse cannot be set.'
elif fuse_current_max > 5.0: #the maximal current which the HMP2030 supplies
print 'The set current exceed the maximum current: 5A'
else:
self.instr.write('CURR %1.3f' %fuse_current_max)
self.instr.write('FUSE:DEL 0')
class BipolarHMP2030(HMP2030):
#funktions to reverse the polarity
def set_polarity(self,ch,p):
"""sets the polarity p of a given channel"""
pass
def get_polarity(self,ch):
"""gets the polarity p of a given channel"""
pass
from traits.api import HasTraits, Range
from traitsui.api import View, Item
class HMP2030Traits( HMP2030, HasTraits ):
def __init__(self, device, voltage_max=20.0, current_max=2.0, fuse_voltage_max=20.0, fuse_current_max=2.5, **kwargs):
HMP2030.__init__(self, device, voltage_max, current_max, fuse_voltage_max, fuse_current_max)
self.add_trait('current', Range(low=0.0, high=current_max, value=self.get_current(), label='Current [A]', auto_set=False, enter_set=True))
HasTraits.__init__(self, **kwargs)
def _current_changed(self, new):
self.set_output(1, new)
traits_view = View(Item('current'),title='HMP2030')
#-------------------------------------------------------------------------------------------------------------------------
#define the sub-function including:set_channel, set_voltage, set_current and run
#def set(ch):
# write('SYST REM')
# write('INST OUPT1')
# write('OUTP OFF')
#
#write('SYST REM') #to remote control
#write('INST OUPT1') #select channel 1
#stop()
| Python |
# -*- coding: utf-8 -*-
import logging
import ok
import os
bitfile = os.path.join(os.path.dirname(__file__),'pulser.bit')
class Pulser():
"""LOWLEVEL PULSER CONTROL"""
command_map = {'IDLE':0,'RUN':1,'LOAD':2,'RESET_READ':3,'RESET_SDRAM':4,'RESET_WRITE':5}
def __init__(self, serial=''):
xem = ok.FrontPanel()
if (xem.OpenBySerial(serial) != 0):
raise RuntimeError, 'Failed to open USB connection.'
PLL = ok.PLL22150()
xem.GetPLL22150Configuration(PLL)
PLL.SetVCOParameters(333,48) #set VCO to 333MHz
PLL.SetOutputSource(0,5) #clk0@166MHz
PLL.SetDiv1(1,6) #needs to be set for DIV1=3
PLL.SetOutputEnable(0,1)
logging.getLogger().info('Pulser base clock input (clk2xin, stage two): '+str(PLL.GetOutputFrequency(0)))
xem.SetPLL22150Configuration(PLL)
if (xem.ConfigureFPGA(bitfile) != 0):
raise RuntimeError, 'Failed to upload bit file to fpga.'
self.xem = xem
def getInfo(self):
self.xem.UpdateWireOuts()
return self.xem.GetWireOutValue(0x20)
def ctrlPulser(self,command):
self.xem.SetWireInValue(0x00,self.command_map[command], 0x07)
self.xem.UpdateWireIns()
def enableDecoder(self):
self.xem.SetWireInValue(0x00,0x00,0x08)
self.xem.UpdateWireIns()
def disableDecoder(self):
self.xem.SetWireInValue(0x00,0xFF,0x08)
self.xem.UpdateWireIns()
def run(self):
self.ctrlPulser('RUN')
self.enableDecoder()
def halt(self):
self.disableDecoder()
self.ctrlPulser('IDLE')
def loadPages(self,buf):
if len(buf) % 1024 != 0:
raise RuntimeError('Only full SDRAM pages supported. Pad your buffer with zeros such that its length is a multiple of 1024.')
self.disableDecoder()
self.ctrlPulser('RESET_WRITE')
self.ctrlPulser('RESET_READ')
self.ctrlPulser('LOAD')
bytes = self.xem.WriteToBlockPipeIn(0x80,1024,buf)
self.ctrlPulser('IDLE')
return bytes
def reset(self):
self.disableDecoder()
self.ctrlPulser('RESET_WRITE')
self.ctrlPulser('RESET_READ')
self.ctrlPulser('RESET_SDRAM')
self.ctrlPulser('IDLE')
def setResetValue(self,bits):
self.xem.SetWireInValue(0x00,bits<<4,0xfff0)
self.xem.UpdateWireIns()
def checkUnderflow(self):
self.xem.UpdateTriggerOuts()
return self.xem.IsTriggered(0x60,1)
########OLD CONTROL UNIT######
"""
def enableDecoder(self, state=False):
if(state==True):
self.xem.SetWireInValue(0x00,0x00,0x40)
else:
self.xem.SetWireInValue(0x00,0xFF,0x40)
self.xem.UpdateWireIns()
def enableRun(self, state=False):
if( state==True ):
self.xem.SetWireInValue(0x00,0xFF,0x20)
else:
self.xem.SetWireInValue(0x00,0x00,0x20)
self.xem.UpdateWireIns()
def enableLoad(self, state=False):
if( state==True ):
self.xem.SetWireInValue(0x00,0xFF,0x10)
else:
self.xem.SetWireInValue(0x00,0x00,0x10)
self.xem.UpdateWireIns()
def resetRead(self, state=True):
if( state==True ):
self.xem.SetWireInValue(0x00,0xFF,0x08)
else:
self.xem.SetWireInValue(0x00,0x00,0x08)
self.xem.UpdateWireIns()
def resetWrite(self,state=True):
if( state==True ):
self.xem.SetWireInValue(0x00,0xFF,0x04)
else:
self.xem.SetWireInValue(0x00,0x00,0x04)
self.xem.UpdateWireIns()
def resetSDRAM(self,state=True):
if( state==True ):
self.xem.SetWireInValue(0x00,0xFF,0x02)
else:
self.xem.SetWireInValue(0x00,0x00,0x02)
self.xem.UpdateWireIns()
def setIdle(self,state=True):
if( state==True ):
self.xem.SetWireInValue(0x00,0xFF,0x01)
else:
self.xem.SetWireInValue(0x00,0x00,0x01)
self.xem.UpdateWireIns()
def resetState(self,state):
if( state==True):
self.xem.SetWireInValue(0x00,0xFF,0x80)
else:
self.xem.SetWireInValue(0x00,0x00,0x80)
self.xem.UpdateWireIns()
"""
| Python |
import ctypes
import numpy, numpy.fft
import time
dll = ctypes.windll.LoadLibrary('dp7889.dll')
class ACQSETTING(ctypes.Structure):
_fields_ = [('range', ctypes.c_ulong),
('prena', ctypes.c_long),
('cftfak', ctypes.c_long),
('roimin', ctypes.c_ulong),
('roimax', ctypes.c_ulong),
('eventpreset', ctypes.c_double),
('timepreset', ctypes.c_double),
('savedata', ctypes.c_long),
('fmt', ctypes.c_long),
('autoinc', ctypes.c_long),
('cycles', ctypes.c_long),
('sweepmode', ctypes.c_long),
('syncout', ctypes.c_long),
('bitshift', ctypes.c_long),
('digval', ctypes.c_long),
('digio', ctypes.c_long),
('dac0', ctypes.c_long),
('dac1', ctypes.c_long),
('swpreset', ctypes.c_double),
('nregions', ctypes.c_long),
('caluse', ctypes.c_long),
('fstchan', ctypes.c_double),
('active', ctypes.c_long),
('calpoints', ctypes.c_long), ]
class ACQDATA(ctypes.Structure):
_fields_ = [('s0', ctypes.POINTER(ctypes.c_ulong)),
('region', ctypes.POINTER(ctypes.c_ulong)),
('comment', ctypes.c_char_p),
('cnt', ctypes.POINTER(ctypes.c_double)),
('hs0', ctypes.c_int),
('hrg', ctypes.c_int),
('hcm', ctypes.c_int),
('hct', ctypes.c_int), ]
class ACQSTATUS(ctypes.Structure):
_fields_ = [('started', ctypes.c_int),
('runtime', ctypes.c_double),
('totalsum', ctypes.c_double),
('roisum', ctypes.c_double),
('roirate', ctypes.c_double),
('ofls', ctypes.c_double),
('sweeps', ctypes.c_double),
('stevents', ctypes.c_double),
('maxval', ctypes.c_ulong), ]
class FastComTec(object):
def __init__(self):
self.BINWIDTH = 0.1
def Configure(self, t, dt, triggers=1, SoftwareStart=False):
self.SetSlots(triggers)
self.SetSoftwareStart(SoftwareStart)
N, DT = self.SetRange(t, dt)
dll.RunCmd(0, 'ROIMAX=%i' % (N/triggers))
self.Erase()
return N, DT
def SetRange(self, T, dT):
self.SetBitshift( int(numpy.round(numpy.log2(dT / self.BINWIDTH))) )
DT = self.BINWIDTH * 2**self.GetBitshift()
self.SetLength( int(T / DT) )
return self.GetLength(), DT
def GetRange(self):
return self.GetLength(), self.BINWIDTH * 2**self.GetBitshift()
def SetLength(self, N):
dll.RunCmd(0, 'RANGE=%i' % N)
return self.GetLength()
def GetLength(self):
setting = ACQSETTING()
dll.GetSettingData(ctypes.byref(setting), 0)
return int(setting.range)
def SetBitshift(self, BITSHIFT):
#~ setting = ACQSETTING()
#~ dll.GetSettingData(ctypes.byref(setting), 0)
#~ setting.bitshift = BITSHIFT
#~ dll.StoreSettingData(ctypes.byref(setting), 0)
#~ dll.NewSetting(0)
dll.RunCmd(0,'BITSHIFT=%i'%BITSHIFT)
return self.GetBitshift()
def GetBitshift(self):
setting = ACQSETTING()
dll.GetSettingData(ctypes.byref(setting), 0)
return int(setting.bitshift)
def SetSlots(self, M):
setting = ACQSETTING()
dll.GetSettingData(ctypes.byref(setting), 0)
if M == 1:
setting.sweepmode = int('10100000', 2)
#~ dll.RunCmd(0, 'SWEEPMODE=' + hex(int('10100000', 2)))
elif M > 1:
setting.sweepmode = int('10100100',2)
#~ dll.RunCmd(0, 'SWEEPMODE=' + hex(int('10100100',2)))
#~ dll.RunCmd(0, 'SWPRESET=1')
setting.prena = setting.prena | 16
setting.prena = setting.prena &~ 4
setting.swpreset = 1
setting.cycles = M
#~ dll.RunCmd(0, 'CYCLES=%i' % M)
dll.StoreSettingData(ctypes.byref(setting), 0)
dll.NewSetting(0)
def SetCycles(self, cycles):
cycles = numpy.min((int('ffffffff', 16)/2, cycles))
dll.RunCmd(0, 'SEQUENCES=%i' % cycles)
def SetSweeps(self, sweeps):
setting = ACQSETTING()
dll.GetSettingData(ctypes.byref(setting), 0)
if sweeps == numpy.Inf:
setting.prena = setting.prena &~ 16
setting.prena = setting.prena &~ 4
#~ dll.RunCmd(0, 'PRENA=' + hex((setting.prena &~ 16)))
#~ dll.RunCmd(0, 'PRENA=' + hex((setting.prena &~ 4)))
else:
# if start event generation is set, set 'start presets'
# else set 'sweep presets'
if ( setting.sweepmode & int('10000000',2) ) >> 7:
setting.prena = setting.prena | 16
setting.prena = setting.prena &~ 4
#~ dll.RunCmd(0, 'PRENA=' + hex((setting.prena | 16)))
else:
setting.prena = setting.prena &~ 16
setting.prena = setting.prena | 4
#~ dll.RunCmd(0, 'PRENA=' + hex((setting.prena | 4)))
setting.swpreset = float(sweeps)
#~ dll.RunCmd(0, 'SWPRESET=%i' % sweeps)
dll.StoreSettingData(ctypes.byref(setting), 0)
dll.NewSetting(0)
def SetTime(self, time):
setting = ACQSETTING()
dll.GetSettingData(ctypes.byref(setting), 0)
if time == numpy.Inf:
#~ setting.prena = setting.prena &~1
dll.RunCmd(0, 'PRENA=' + hex((setting.prena &~ 1)))
else:
#~ setting.prena = setting.prena|1
#~ setting.timepreset = time
dll.RunCmd(0, 'PRENA=' + hex((setting.prena | 1)))
dll.RunCmd(0, 'RTPRESET=%f' % time)
#~ dll.StoreSettingData(ctypes.byref(setting), 0)
#~ dll.NewSetting(0)
def SetSoftwareStart(self,b):
setting = ACQSETTING()
dll.GetSettingData(ctypes.byref(setting), 0)
if b:
setting.sweepmode = setting.sweepmode | int('10000',2)
setting.sweepmode = setting.sweepmode &~ int('10000000',2)
else:
setting.sweepmode = setting.sweepmode &~ int('10000',2)
setting.sweepmode = setting.sweepmode | int('10000000',2)
dll.StoreSettingData(ctypes.byref(setting), 0)
dll.NewSetting(0)
def SetDelay(self, t):
#~ setting = ACQSETTING()
#~ dll.GetSettingData(ctypes.byref(setting), 0)
#~ setting.fstchan = t/6.4
#~ dll.StoreSettingData(ctypes.byref(setting), 0)
#~ dll.NewSetting(0)
dll.RunCmd(0, 'DELAY=%f' % t)
return self.GetDelay()
def GetDelay(self):
setting = ACQSETTING()
dll.GetSettingData(ctypes.byref(setting), 0)
return setting.fstchan * 6.4
def Start(self):
dll.Start(0)
status = ACQSTATUS()
status.started = 0
while not status.started:
time.sleep(0.1)
dll.GetStatusData(ctypes.byref(status), 0)
def Halt(self):
dll.Halt(0)
def Erase(self):
dll.Erase(0)
def Continue(self):
return dll.Continue(0)
def GetData(self):
setting = ACQSETTING()
dll.GetSettingData(ctypes.byref(setting), 0)
N = setting.range
M = setting.cycles
data = numpy.empty((N,), dtype=numpy.uint32 )
dll.LVGetDat(data.ctypes.data, 0)
if M == 1:
return data
else:
return data.reshape((M,N/M))
def GetFFT(self):
StartTime = time.time()
self.Start()
while self.Running():
time.sleep(0.1)
data = numpy.zeros((2*self.GetLength(),), dtype=numpy.uint32 )
dll.LVGetDat(data.ctypes.data, 0)
r = data.astype(numpy.float)
F = numpy.fft.rfft(r)
return F
def AccumulateFFT(self, N):
Y = numpy.zeros((self.GetLength()+1,))
i = 0
while i < N:
self.Start()
while self.Running():
time.sleep(0.1)
Y += abs(self.GetFFT())
i += 1
return Y
def GetState(self):
status = ACQSTATUS()
dll.GetStatusData(ctypes.byref(status), 0)
return status.runtime, status.sweeps
def Running(self):
s = self.GetStatus()
return s.started
def SetLevel(self, start, stop):
setting = ACQSETTING()
dll.GetSettingData(ctypes.byref(setting), 0)
def FloatToWord(r):
return int((r+2.048)/4.096*int('ffff',16))
setting.dac0 = ( setting.dac0 & int('ffff0000',16) ) | FloatToWord(start)
setting.dac1 = ( setting.dac1 & int('ffff0000',16) ) | FloatToWord(stop)
dll.StoreSettingData(ctypes.byref(setting), 0)
dll.NewSetting(0)
return self.GetLevel()
def GetLevel(self):
setting = ACQSETTING()
dll.GetSettingData(ctypes.byref(setting), 0)
def WordToFloat(word):
return (word & int('ffff',16)) * 4.096 / int('ffff',16) - 2.048
return WordToFloat(setting.dac0), WordToFloat(setting.dac1)
def ReadSetting(self):
setting = ACQSETTING()
dll.GetSettingData(ctypes.byref(setting), 0)
return setting
def WriteSetting(self, setting):
dll.StoreSettingData(ctypes.byref(setting), 0)
dll.NewSetting(0)
def GetStatus(self):
status = ACQSTATUS()
dll.GetStatusData(ctypes.byref(status), 0)
return status
| Python |
"""
Dummy hardware classes for testing.
"""
import numpy as np
import logging
import time
class Scanner( ):
def getXRange(self):
return (0.,100.)
def getYRange(self):
return (0.,100.)
def getZRange(self):
return (-20.,20.)
def setx(self, x):
pass
def sety(self, y):
pass
def setz(self, z):
pass
def setPosition(self, x, y, z):
"""Move stage to x, y, z"""
pass
def scanLine(self, Line, SecondsPerPoint, return_speed=None):
time.sleep(0.1)
return (1000*np.sin(Line[0,:])*np.sin(Line[1,:])*np.exp(-Line[2,:]**2)).astype(int)
#return np.random.random(Line.shape[1])
class Counter( ):
def configure(self, n, SecondsPerPoint, DutyCycle=0.8):
x = np.arange(n)
a = 100.
c = 50.
x0 = n/2.
g = n/10.
y = np.int32( c - a / np.pi * ( g**2 / ( (x-x0)**2 + g**2 ) ) )
Counter._sweeps = 0
Counter._y = y
def run(self):
time.sleep(1)
Counter._sweeps+=1
return np.random.poisson(Counter._sweeps*Counter._y)
def clear(self):
pass
class Microwave( ):
def setPower(self, power):
logging.getLogger().debug('Setting microwave power to '+str(power)+'.')
def setOutput(self, power, frequency):
logging.getLogger().debug('Setting microwave to p='+str(power)+' f='+str(frequency)+'.')
def initSweep(self, f, p):
logging.getLogger().debug('Setting microwave to sweep between frequencies %e .. %e with power %f.'%(f[0],f[-1],p[0]))
def resetListPos(self):
pass
class PulseGenerator():
def Sequence(self, sequence, loop=True):
pass
def Light(self):
pass
def Night(self):
pass
def Open(self):
pass
def High(self):
pass
def checkUnderflow(self):
return False
#return np.random.random()<0.1
class Laser():
"""Provides control of the laser power."""
voltage = 0.
class PowerMeter():
"""Provides an optical power meter."""
power = 0.
def getPower(self):
"""Return the optical power in Watt."""
PowerMeter.power += 1
return PowerMeter.power*1e-3
class Coil():
def set_output(self,channel,current):
pass
class RotationStage():
def set_angle(self, angle):
pass
class TimeTagger( ):
class Pulsed( ):
def __init__(self, n_bins, bin_width, n_slots, channel, shot_trigger, sequence_trigger=None):
self.n_bins = n_bins
self.n_slots = n_slots
self.clear()
def clear(self):
n_slots = self.n_slots
n_bins = self.n_bins
data = np.zeros((n_slots,n_bins))
m0 = int(n_bins/5)
m = float(n_bins-m0)
M = np.arange(m, dtype=float)
n = float(n_slots)
k = n_slots/2
for i in range(n_slots):
"""Rabi Data"""
data[i,m0:] = 30*np.cos(3*2*np.pi*i/n)*np.exp(-5*M/m)+100
"""Hahn Data
data[i,m0:] = 30*np.exp(-9*i**2/n**2)*np.exp(-5*M/m)+100
"""
"""Hahn 3pi2 Data
if i < k:
data[i,m0:] = 30*np.exp(-9*i**2/float(k**2))*np.exp(-5*M/m)+100
else:
data[i,m0:] = -30*np.exp(-9*(i-k)**2/float(k**2))*np.exp(-5*M/m)+100
"""
"""T1 Data
data[i,m0:] = 30*np.exp(-3*i/n)*np.exp(-5*M/m)+100
"""
self.data = data
self.counter = 1
def setMaxCounts(self,arg):
pass
def ready(self):
time.sleep(0.1)
return True
def getData(self):
self.counter += 1
return np.random.poisson(self.counter*self.data)
def getCounts(self):
return self.counter
def start(self):
pass
def stop(self):
pass
class Countrate( ):
def __init__(self, channel):
self.rate = 0.
def getData(self):
self.rate += 1.
return 1e5/(1+20./self.rate)
def clear(self):
pass
class Counter( ):
def __init__(self, channel, bins_per_point, length):
self.channel = channel
self.seconds_per_point = float(bins_per_point)/800000000
self.length = length
def getData(self):
return np.random.random_integers(100000,120000, self.length)*self.seconds_per_point
| Python |
"""
This file is part of pi3diamond.
pi3diamond is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pi3diamond is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with diamond. If not, see <http://www.gnu.org/licenses/>.
Copyright (C) 2009-2011 Helmut Fedder <helmut.fedder@gmail.com>
"""
import visa
class PM100D():
"""Provides control of thorlabs powermeter PM100D."""
def __init__(self, visa_address='USB0::0x1313::0x8078::PM002838::INSTR'):
self.visa_address = visa_address
def _write(self, string):
try: # if the connection is already open, this will work
self.instr.write(string)
except: # else we attempt to open the connection and try again
try: # silently ignore possible exceptions raised by del
del self.instr
except Exception:
pass
self.instr = visa.instrument(self.visa_address)
self.instr.write(string)
def _ask(self, str):
try:
val = self.instr.ask(str)
except:
self.instr = visa.instrument(self.visa_address)
val = self.instr.ask(str)
return val
def getPower(self):
return float(self._ask('read?'))
def __del__(self):
self.instr.close()
| Python |
import numpy as np
import time
from traits.api import HasTraits, Button
from traitsui.api import View, Item
from enthought.traits.ui.menu import Action, Menu, MenuBar
from nidaq import DOTask
class FlipMirror( HasTraits ):
flip = Button(desc="flip the mirror")
def __init__(self, trigger_channels):
super(HasTraits, self).__init__()
self._trigger_task = DOTask(trigger_channels)
def _flip_changed(self):
self._trigger_task.Write(np.array((1,), dtype=np.uint8) )
time.sleep(0.001)
self._trigger_task.Write(np.array((0,), dtype=np.uint8) )
view = View(Item('flip', show_label=False),
title='Flip mirror',
buttons=[],
resizable=True)
| Python |
import ctypes
import time
import struct
dll=ctypes.WinDLL('ftd2xx.dll')
class RotationStage():
"""Provide control over a thorlabs rotation stage."""
def __init__(self, serial='83838311'):
self._open_usb(serial)
def _open_usb(self, serial):
"""Open a USB connection to the controller with the specified serial number."""
handle=ctypes.c_ulong()
if dll.FT_OpenEx(serial, 1, ctypes.byref(handle)):
raise RuntimeError('USB open failed.')
if dll.FT_SetBaudRate(handle ,ctypes.c_ulong(115200)):
raise RuntimeError('USB baud rate failed.')
if dll.FT_SetDataCharacteristics(handle, ctypes.c_uint8(8), ctypes.c_uint8(0), ctypes.c_uint8(0)):
raise RuntimeError('USB set data format failed.')
time.sleep(0.1)
if dll.FT_Purge(handle, ctypes.c_ulong(1|2)):
raise RuntimeError('USB purge failed.')
time.sleep(0.1)
if dll.FT_ResetDevice(handle):
raise RuntimeError('USB reset failed.')
if dll.FT_SetFlowControl(handle, ctypes.c_ushort(0x0100), ctypes.c_uint8(0), ctypes.c_uint8(0)):
raise RuntimeError('USB set flow control failed.')
if dll.FT_SetRts(handle):
raise RuntimeError('USB set RTS failed.')
if dll.FT_SetTimeouts(handle,1000,0):
raise RuntimeError('USB set timeouts failed.')
self.usb = handle
def _close_usb(self):
"""Close the USB connection to the controller."""
if dll.FT_Close(self.usb):
raise RuntimeError('USB close connection failed.')
def get_info(self):
"""Read the device information from the controller USB chip."""
dev_type=ctypes.c_ulong()
dev_id=ctypes.c_ulong()
ser_buf = ctypes.create_string_buffer(16)
desc_buf = ctypes.create_string_buffer(64)
if dll.FT_GetDeviceInfo(self.usb, ctypes.byref(dev_type), ctypes.byref(dev_id), ser_buf, desc_buf, None):
raise RuntimeError('USB get device info failed.')
return dev_type.value, dev_id.value, ser_buf.value, desc_buf.value
def send(self,command):
"""Send a 'set'-type command to the controller."""
written = ctypes.c_ulong()
wr_buf = ctypes.create_string_buffer(command,len(command))
if dll.FT_Write(self.usb, wr_buf, ctypes.c_ulong(len(wr_buf)), ctypes.byref(written)):
raise RuntimeError('USB write failed.')
return written.value
def wait(self,n,timeout=0.1):
"""Wait until n bytes are in the receive buffer or timeout is passed."""
amount_rx=ctypes.c_ulong(0)
amount_tx=ctypes.c_ulong(0)
event_stat=ctypes.c_ulong(0)
start_time = time.time()
while amount_rx.value<n and time.time()-start_time<timeout:
if dll.FT_GetStatus(self.usb, ctypes.byref(amount_rx), ctypes.byref(amount_tx), ctypes.byref(event_stat)):
raise RuntimeError('USB get status failed.')
time.sleep(0.1)
return amount_rx.value
def ack(self):
self.send('\x92\x04\x00\x00\x05\x01')
def request(self,command,timeout=0.1):
"""Send a 'get'-type command to the controller and return the reply."""
written = ctypes.c_ulong()
read = ctypes.c_ulong()
wr_buf = ctypes.create_string_buffer(command,len(command))
time.sleep(0.1)
if dll.FT_Write(self.usb, wr_buf, ctypes.c_ulong(len(wr_buf)), ctypes.byref(written)):
raise RuntimeError('USB write failed.')
if self.wait(6,timeout) < 6: # wait for 6 bytes reply message
raise RuntimeError('USB request timed out after %fs.'%timeout)
head_buf = ctypes.create_string_buffer(6)
if dll.FT_Read(self.usb, head_buf, ctypes.c_ulong(6), ctypes.byref(read)):
raise RuntimeError('USB read failed.')
id,length,dest,source=struct.unpack('<2H2B',head_buf.raw) # convert message assuming that it is the header for a data
if dest>>7: # a data packet will follow
if self.wait(length,timeout) < length: # wait for expected number of bytes
raise RuntimeError('USB request timed out after %fs.'%timeout)
rd_buf = ctypes.create_string_buffer(length)
if dll.FT_Read(self.usb, rd_buf, ctypes.c_ulong(length), ctypes.byref(read)):
raise RuntimeError('USB read failed.')
self.ack()
return head_buf.raw+rd_buf.raw
else: # simple 6 byte message
self.ack()
return head_buf.raw
# if dll.FT_GetStatus(self.usb, ctypes.byref(amount_rx), ctypes.byref(amount_tx), ctypes.byref(event_stat)):
# raise RuntimeError('USB get status failed.')
# time.sleep(0.1)
# print 'rx', amount_rx.value
# #print 'tx', amount_tx.value
# rd_buf = ctypes.create_string_buffer(amount_rx.value)
# #print 'len(rd_buf)', len(rd_buf)
# time.sleep(0.1)
# if dll.FT_Read(self.usb, rd_buf, amount_rx, ctypes.byref(read)):
# raise RuntimeError('USB read failed.')
# if read.value != amount_rx.value:
# raise RuntimeError('USB requested %i bytes but received %i.'%(amount_rx.value,read.value))
#print read.value
# print rd_buf.value.__repr__()
# id,length,dest,source = struct.unpack('<2H2B',rd_buf.value)
# print length
# print dest
# if dest>>7:
# print length
# time.sleep(0.1)
# rd_buf_dat = ctypes.create_string_buffer(length)
# if dll.FT_Read(self.usb, rd_buf_dat, ctypes.c_ulong(length), ctypes.byref(read)):
# raise RuntimeError('USB read failed.')
# print 'return message and data'
# return rd_buf.value+rd_buf_dat.value
# else:
# print 'return message'
# return rd_buf.value
def go_home(self, timeout=60.):
#start_time=time.time()
return self.request('\x43\x04\x01\x00\x05\x01', timeout=timeout) # worst case homing takes about 45 seconds with standard speed parameters
#return time.time()-start_time
## not available with TDC001 controller
# def get_stage_info(self):
# buf=self.request('\xf1\x04\x01\x00\x05\x01')
# return struct.unpack('<6s3H16s7i24s',buf)[1:-1]
def blink(self):
self.send('\x23\x02\x00\x00\x05\x01')
def get_status(self):
buf=self.request('\x90\x04\x01\x00\x05\x01')
chan, pos, count, status = struct.unpack('<6sH3L',buf)[1:]
return chan, pos, count, status
def get_status_bits(self):
buf=self.request('\x29\x04\x01\x00\x05\x01')
status = struct.unpack('<6sHL',buf)[2]
return status
def get_backlash(self):
buf=self.request('\x3b\x04\x01\x00\x05\x01')
return struct.unpack('<6sHL',buf)[1:]
def get_pid(self):
buf=self.request('\xa1\x04\x01\x00\x05\x01')
return struct.unpack('<6sH4LH',buf)[1:]
# def set_angle(self,angle):
# """Set the absolute angle [deg]."""
# counts=1919.641857862339*(angle%360.) # pitch (deg / rev)=17.87, (counts / rev)=34304
# self.send('\x53\x04\x06\x00\x85\x01'+'\x01\x00'+struct.pack('<l',counts))
def set_angle(self,angle, timeout=60.):
"""Set the absolute angle [deg]."""
#start_time=time.time()
counts=1919.641857862339*(angle%360.) # pitch (deg / rev)=17.87, (counts / rev)=34304
return self.request('\x53\x04\x06\x00\x85\x01'+'\x01\x00'+struct.pack('<l',counts), timeout=timeout)
#return time.time()-start_time
from traits.api import HasTraits, Str, Float, Button
from traitsui.api import View, Item
class RotationStageTraits( RotationStage, HasTraits ):
home = Button()
angle = Float(default_value=0.0, label='angle [deg]', auto_set=False, enter_set=True)
def __init__(self, serial, **kwargs):
HasTraits.__init__(self, **kwargs)
RotationStage.__init__(self, serial)
def _home_changed(self):
self.go_home()
def _angle_changed(self, new):
self.set_angle(new)
traits_view = View(Item('angle'),
Item('home', show_label=False),
title='Rotation Stage'
)
if __name__=='__main__':
stage=RotationStage()
#d=stage.move_home()
#print stage.get_pid()
#stage.set_angle(0)
| Python |
import numpy
import ctypes
import time
dll = ctypes.windll.LoadLibrary('nicaiu.dll')
import logging
DAQmx_Val_ContSamps = 10123
DAQmx_Val_FiniteSamps = 10178
DAQmx_Val_Hz = 10373
DAQmx_Val_Low = 10214
DAQmx_Val_MostRecentSamp = 10428
DAQmx_Val_OverwriteUnreadSamps = 10252
DAQmx_Val_Rising = 10280
DAQmx_Val_Ticks = 10304
def CHK(err):
"""a simple error checking routine"""
if err < 0:
buf_size = 1000
buf = ctypes.create_string_buffer('\000' * buf_size)
dll.DAQmxGetErrorString(err,ctypes.byref(buf),buf_size)
raise RuntimeError('nidaq call failed with error %d: %s'%(err,repr(buf.value)))
class Counter( ):
def __init__(self, counter_out_device, counter_in_device, input_pad, bin_width, length):
self.length = length
self.bin_width = bin_width
f = 1./bin_width
buffer_size = max(1000, length)
self.COTask = ctypes.c_ulong()
self.CITask = ctypes.c_ulong()
CHK( dll.DAQmxCreateTask('', ctypes.byref(self.COTask)) )
CHK( dll.DAQmxCreateTask('', ctypes.byref(self.CITask)) )
CHK( dll.DAQmxCreateCOPulseChanFreq( self.COTask,
counter_out_device, '',
DAQmx_Val_Hz, DAQmx_Val_Low, ctypes.c_double(0),
ctypes.c_double(f),
ctypes.c_double(0.9) )
)
CHK( dll.DAQmxCreateCIPulseWidthChan( self.CITask,
counter_in_device, '',
ctypes.c_double(0),
ctypes.c_double(1e7),
DAQmx_Val_Ticks, DAQmx_Val_Rising, '')
)
CHK( dll.DAQmxSetCIPulseWidthTerm( self.CITask, counter_in_device, counter_out_device+'InternalOutput' ) )
CHK( dll.DAQmxSetCICtrTimebaseSrc( self.CITask, counter_in_device, input_pad ) )
CHK( dll.DAQmxCfgImplicitTiming( self.COTask, DAQmx_Val_ContSamps, ctypes.c_ulonglong(buffer_size)) )
CHK( dll.DAQmxCfgImplicitTiming( self.CITask, DAQmx_Val_ContSamps, ctypes.c_ulonglong(buffer_size)) )
# read most recent samples, overwrite buffer
CHK( dll.DAQmxSetReadRelativeTo(self.CITask, DAQmx_Val_MostRecentSamp) )
CHK( dll.DAQmxSetReadOffset(self.CITask, -length) )
CHK( dll.DAQmxSetReadOverWrite(self.CITask, DAQmx_Val_OverwriteUnreadSamps) )
CHK( dll.DAQmxStartTask(self.COTask) )
CHK( dll.DAQmxStartTask(self.CITask) )
self.n_read = ctypes.c_int32()
self.data = numpy.empty((length,), dtype=numpy.uint32)
self.timeout = 4*length*bin_width
def getData(self):
try:
CHK( dll.DAQmxReadCounterU32(self.CITask,
ctypes.c_int32(self.length),
ctypes.c_double(self.timeout),
self.data.ctypes.data,
ctypes.c_uint32(self.length),
ctypes.byref(self.n_read), None)
)
except:
time.sleep(self.timeout)
CHK( dll.DAQmxReadCounterU32(self.CITask,
ctypes.c_int32(self.length),
ctypes.c_double(self.timeout),
self.data.ctypes.data,
ctypes.c_uint32(self.length),
ctypes.byref(self.n_read), None)
)
return self.data
def __del__(self):
try:
CHK( dll.DAQmxStopTask(self.COTask) )
CHK( dll.DAQmxStopTask(self.CITask) )
CHK( dll.DAQmxClearTask(self.COTask) )
CHK( dll.DAQmxClearTask(self.CITask) )
except:
pass
if __name__ == '__main__':
c = Counter( counter_out_device='/Dev1/Ctr2', counter_in_device='/Dev1/Ctr3', input_pad='/Dev1/PFI3', bin_width=0.01, length=1000)
| Python |
#DTG_recids.py - definitions of binary codes for the .dtg file format. See the Tektronix Programmer's Manual for details
internal_node = 0x8000
leaf_node = 0x0000
recids = {
'DTG_ROOT_RECID':0x0001 | internal_node,
'DTG_MAGIC_RECID':0x0002 | leaf_node,
'DTG_TB_OPERATION_RECID':0x0003 | leaf_node,
'DTG_TB_RUNMODE_RECID':0x0004 | leaf_node,
'DTG_TB_BURSTCOUNT_RECID':0x0005 | leaf_node,
'DTG_TB_CLOCKSOURCE_RECID':0x0006 | leaf_node,
'DTG_TB_CLOCKSETTYPE_RECID':0x005D | leaf_node,
'DTG_TB_CLOCK_RECID':0x0007 | leaf_node,
'DTG_TB_JITTERINPUT_RECID':0x0008 | leaf_node,
'DTG_TB_LONGDELAY_RECID':0x0009 | leaf_node,
'DTG_TB_CLOCKRANGE_RECID':0x000A | leaf_node,
'DTG_TB_DELAYOFFSET_RECID':0x000B | leaf_node,
'DTG_TB_CLOCKOUTPUT_RECID':0x000C | leaf_node,
'DTG_TB_CLOCKOUTPUTAMPLITUDE_RECID':0x000D | leaf_node,
'DTG_TB_CLOCKOUTPUTOFFSET_RECID':0x000E | leaf_node,
'DTG_TB_CLOCKOUTPUTTERMZ_RECID':0x0061 | leaf_node,
'DTG_TB_CLOCKOUTPUTTERMV_RECID':0x0062 | leaf_node,
'DTG_TRIGGER_SOURCE_RECID':0x000F | leaf_node,
'DTG_TRIGGER_SLOPE_RECID':0x0010 | leaf_node,
'DTG_TRIGGER_LEVEL_RECID':0x0011 | leaf_node,
'DTG_TRIGGER_IMPEDANCE_RECID':0x0012 | leaf_node,
'DTG_TRIGGER_INTERVAL_RECID':0x0013 | leaf_node,
'DTG_EVENT_INPUTPOLARITY_RECID':0x0014 | leaf_node,
'DTG_EVENT_INPUTTHRESHOLD_RECID':0x0015 | leaf_node,
'DTG_EVENT_INPUTIMPEDANCE_RECID':0x0016 | leaf_node,
'DTG_SEQ_MODE_RECID':0x0017 | leaf_node,
'DTG_SEQ_JUMPMODE_RECID':0x0018 | leaf_node,
'DTG_SEQ_JUMPTIMING_RECID':0x0019 | leaf_node,
'DTG_JITTER_GENERATION_RECID':0x001A | leaf_node,
'DTG_JITTER_MODE_RECID':0x001B | leaf_node,
'DTG_JITTER_LOGICALCH_RECID':0x001C | leaf_node,
'DTG_JITTER_GATINGSOURCE_RECID':0x001D | leaf_node,
'DTG_JITTER_EDGE_RECID':0x001E | leaf_node,
'DTG_JITTER_FREQUENCY_RECID':0x001F | leaf_node,
'DTG_JITTER_AMPUNITSETTYPE_RECID':0x005E | leaf_node,
'DTG_JITTER_AMPMODESETTYPE_RECID':0x005F | leaf_node,
'DTG_JITTER_AMPLITUDE_RECID':0x0020 | leaf_node,
'DTG_DCOUTPUT_RECID':0x0021 | leaf_node,
'DTG_DCOUTPUTTABLE_RECID':0x0022 | leaf_node,
'DTG_ASSIGN_RECID':0x0023 | leaf_node,
'DTG_GROUP_RECID':0x0024| internal_node,
'DTG_ID_RECID':0x0025 | leaf_node,
'DTG_NAME_RECID':0x0026 | leaf_node,
'DTG_NBITS_RECID':0x0027 | leaf_node,
'DTG_LOGICALCHANNEL_RECID':0x0028 | leaf_node,
'DTG_RADIX_RECID':0x0029 | leaf_node,
'DTG_SIGNED_RECID':0x002A | leaf_node,
'DTG_MAGNITUDE_RECID':0x002B | leaf_node,
'DTG_LOGICALCH_RECID':0x002C | internal_node,
'DTG_TERMZ_RECID':0x002E | leaf_node,
'DTG_TERMV_RECID':0x002F | leaf_node,
'DTG_LIMIT_RECID':0x0030 | leaf_node,
'DTG_LIMITHIGH_RECID':0x0031 | leaf_node,
'DTG_LIMITLOW_RECID':0x0032 | leaf_node,
'DTG_LEVELSETTYPE_RECID':0x0060 | leaf_node,
'DTG_LEVELHIGHORAMP_RECID':0x0033 | leaf_node,
'DTG_LEVELLOWOROFFSET_RECID':0x0034 | leaf_node,
'DTG_OUTPUT_RECID':0x0037 | leaf_node,
'DTG_POLARITY_RECID':0x0038 | leaf_node,
'DTG_JITTERRANGE_RECID':0x0064 | leaf_node,
'DTG_FORMAT_RECID':0x0039 | leaf_node,
'DTG_DELAYUNIT_RECID':0x003A | leaf_node,
'DTG_DELAYDATA_RECID':0x003B | leaf_node,
'DTG_WIDTHUNIT_RECID':0x003C | leaf_node,
'DTG_WIDTHDATA_RECID':0x003D | leaf_node,
'DTG_SLEWRATE_RECID':0x003E | leaf_node,
'DTG_CHMIX_RECID':0x003F | leaf_node,
'DTG_DTO_RECID':0x0040 | leaf_node,
'DTG_DTOOFFSET_RECID':0x0041 | leaf_node,
'DTG_PULSERATE_RECID':0x0042 | leaf_node,
'DTG_CROSS_POINT_RECID':0x0063 | leaf_node,
'DTG_BLOCK_RECID':0x0043 | internal_node,
'DTG_SIZE_RECID':0x0046 | leaf_node,
'DTG_SUBSEQUENCE_RECID':0x0047 | internal_node,
'DTG_SUBSEQUENCESTEP_RECID':0x0049 | internal_node,
'DTG_SUBNAME_RECID':0x004A | leaf_node,
'DTG_REPEATCOUNT_RECID':0x004B | leaf_node,
'DTG_MAINSEQUENCE_RECID':0x004C | internal_node,
'DTG_LABEL_RECID':0x004D | leaf_node,
'DTG_WAITTRIGGER_RECID':0x004E | leaf_node,
'DTG_JUMPTO_RECID':0x0051 | leaf_node,
'DTG_GOTO_RECID':0x0052 | leaf_node,
'DTG_PATTERN_RECID':0x0053 | internal_node,
'DTG_GROUPID_RECID':0x0054 | leaf_node,
'DTG_BLOCKID_RECID':0x0055 | leaf_node,
'DTG_PATTERNDATA_RECID':0x0056 | leaf_node,
'DTG_VIEW_RECID':0x0057 | internal_node,
'DTG_BLOCKLIST_RECID':0x0058 | leaf_node,
'DTG_GROUPLIST_RECID':0x0059 | leaf_node,
'DTG_BYCHANNELLIST_RECID':0x005A | leaf_node,
'DTG_BYGROUPLIST_RECID':0x005B | leaf_node,
'DTG_SUBSEQLIST_RECID':0x005C | leaf_node
}
| Python |
import struct
import numpy
import binascii
import os
from dtg_recids import *
def read_tree(N, bytes):
"""
read N bytes from a string 'bytes' and build up a tree
"""
tree = []
while N>0 and len(bytes) > 0:
try:
recid = struct.unpack('<H', bytes[:2])[0]
except:
print "unpack impossible. offending string " + bytes[:2]
return bytes, tree
bytes = bytes[2:]
N -= 2
if (recid & internal_node):
lint = struct.unpack('<I', bytes[:4])[0]
bytes, subtree = read_tree(lint, bytes[4:])
hr_recid = [key for key in recids.keys() if recids[key]==recid ]
tree.append([hr_recid[0], lint, subtree])
N -= lint + 4
else: #leaf node
data, lleaf, bytes = read_leaf_data(bytes)
hr_recid = [key for key in recids.keys() if recids[key]==recid ]
tree.append([hr_recid[0], lleaf-4, data])
N -= lleaf
return bytes, tree
def read_leaf_data(bytes):
"""
read data from a leaf node,
bytes must start with an entry of type "length, data" (RECID must be chopped before)
"""
len = struct.unpack('<I', bytes[:4])[0]
if (len %2):
data = numpy.array(struct.unpack('<' + str(len) + 'B', bytes[4:4+len]), dtype=numpy.int8)
else:
data = numpy.array(struct.unpack('<' + str(len/2) + 'h', bytes[4:4+len]), dtype=numpy.short)
return [data, len + 4, bytes[4+len:]]
def dump_tree(tree, fil):
"""
accept a DTG setup tree 'tree' and dump it into the file fil
"""
for node in tree:
recid_hr, len, data = node
recid = recids[recid_hr]
if recid & internal_node:
fil.write(struct.pack('<H', recid))
fil.write(struct.pack('<I', len))
dump_tree(data, fil)
else: #leaf node
fil.write(struct.pack('<H', recid))
fil.write(struct.pack('<I', len))
fil.write(data.tostring())
def recalculate_space(tree):
"""
given a DTG setup tree 'tree', update the size value of each node
"""
total = 0
for i, node in enumerate(tree):
try:
recid_hr, length, data = node
except:
print "could not unpack " + str(node) + '\n'
recid = recids[recid_hr]
if recid & internal_node:
node[1], node[2] = recalculate_space(data)
tree[i] = node
else: #leaf node
node[1] = len(data.tostring())
tree[i] = node
total += node[1]+6 # add length of the treated node to total length
return total, tree
def get_leaf(tree, leaf):
"""
get_leaf: search a DTG tree 'tree' for a leaf with (human readable) recid 'leaf' and return it
"""
for node in tree:
recid_hr, dlen, data = node
recid = recids[recid_hr]
if recid & internal_node:
res = get_leaf(data, leaf)
if len(res):
return res
else:
if recid_hr == leaf:
return [dlen, data]
return []
def change_leaf(leafs, leaf_id, newlen, newval):
"""
change_leaf: descend the list of leafs 'leafs' and look for all leafs with (human readable string) id 'leaf_id'.
Once found, replace their content by 'newlen', 'newval'
"""
for i, leaf in enumerate(leafs):
if leaf[0] == leaf_id:
leafs[i][1] = newlen
leafs[i][2] = newval
return leafs
def load_scaffold():
"""
load_scaffold: load and return the DTG config scaffold
"""
fil = open('scaffold.dtg', 'rb')
bytes = fil.read()
fil.close()
return read_tree(12000, bytes)[1]
# global variable holding the DTG scaffold
scaffold = load_scaffold()
#test code to reorder entries in the file and dump it to disk
#view = tree[0][-1].pop()
#pattern = tree[0][-1].pop()
#tree[0][-1].append(view)
#tree[0][-1].append(pattern)
#pattern = get_leaf(tree, 'DTG_PATTERNDATA_RECID')[1]
#total, tree = recalculate_space(tree)
#fil = open('dtg.reversed.dat', 'wb')
#dump_tree(tree, fil)
#fil.close()
| Python |
# -*- coding: utf-8 -*-
import numpy
import struct
from pulser import Pulser
import logging
class PulseGenerator():
def __init__(self, serial='', channel_map={'ch0':0,'ch1':1,'ch2':2,'ch3':3,'ch4':4,'ch5':5,'ch6':6,'ch7':7,'ch8':8,'ch9':9,'ch10':10,'ch11':11} ):
self.channel_map = channel_map
pulser=Pulser(serial=serial)
self.N_CHANNELS = pulser.getInfo()
pulser.setResetValue(0x0000)
pulser.disableDecoder()
pulser.reset()
self.pulser=pulser
def Sequence(self,seq,loop=None):
#print self.pulser.loadPages(self.convertSequenceToBinary(seq)), "Bytes written."
self.pulser.loadPages(self.convertSequenceToBinary(seq))
self.pulser.run()
def Run(self):
self.pulser.run()
def Halt(self):
self.pulser.halt()
def Night(self):
self.pulser.setResetValue(0x0000)
self.pulser.halt()
def Light(self):
self.pulser.setResetValue(0x0001)
self.pulser.halt()
def Open(self):
self.pulser.setResetValue(0xffff)
self.pulser.halt()
def Continuous(self, channels):
bits = 0
for channel in channels:
bits = bits | (1 << self.channel_map[channel])
self.pulser.setResetValue(bits)
self.pulser.halt()
def checkUnderflow(self):
return self.pulser.checkUnderflow()
#########PATTERN CALCULATION##########
# time is specified in ns
dt=1.5 # timing step length (1.6ns)
def createBitsFromChannels(self,channels):
bits = numpy.zeros(self.N_CHANNELS,dtype=bool)
for channel in channels:
bits[self.channel_map[channel]] = True
return bits
def setBits(self,integers,start,count,bits):
"""Sets the bits in the range start:start+count in integers[i] to bits[i]."""
# ToDo: check bit order (depending on whether least significant or most significant bit is shifted out first from serializer)
for i in range(self.N_CHANNELS):
if bits[i]:
integers[i] = integers[i] | (2**count-1) << start
def pack(self,mult,pattern):
s = struct.pack('>I%iB'%len(pattern), mult, *pattern[::-1])
swap = ''
for i in range(len(s)):
swap += s[i-1 if i%2 else i+1]
return swap
def convertSequenceToBinary(self,sequence):
"""Converts a pulse sequence into a series of pulser instructions,
taking into account the 8bit minimal pattern length. The pulse sequence
is described as a list of tuples (channels, time). The pulser instructions
are of the form 'repetition (32 bit) | ch0 pattern (8bit), ..., ch3 pattern (8bit)'.
If necessary, high level pulse commands are split into a series of
suitable low level pulser instructions."""
buf = ''
blank = numpy.zeros(self.N_CHANNELS,dtype=int)
pattern = blank.copy()
index = 0
for channels, time in sequence:
ticks = int(round(time/self.dt))
if ticks is 0:
continue
bits = self.createBitsFromChannels(channels)
if index + ticks < 8: # if pattern does not fill current block, append to current block and continue
self.setBits(pattern,index,ticks,bits)
index += ticks
continue
if index > 0: # else fill current block with pattern, reduce ticks accordingly, write block and start a new block
self.setBits(pattern,index,8-index,bits)
buf += self.pack(0,pattern)
ticks -= ( 8 - index )
pattern = blank.copy()
repetitions = ticks / 8 # number of full blocks
index = ticks % 8 # remainder will make the beginning of a new block
if repetitions > 0:
buf += self.pack(repetitions-1,255*bits)
if index > 0:
pattern = blank.copy()
self.setBits(pattern,0,index,bits)
if index > 0: # fill up incomplete block with zeros and write it
self.setBits(pattern,index,8-index,numpy.zeros(self.N_CHANNELS,dtype=bool))
buf += self.pack(0,pattern)
#print "buf has",len(buf)," bytes"
buf=buf+((1024-len(buf))%1024)*'\x00' # pad buffer with zeros so it matches SDRAM / FIFO page size
#logging.getLogger().debug('buffer: '+buf)
#print "buf has",len(buf)," bytes"
return buf
########## TESTCODE############
if __name__ == '__main__':
PG = PulseGenerator()
PG.Sequence(100*[(['ch0'],1000.),([],1000.)])
# PG.Sequence([(['laser'],3),([],6*1.5),(['mw'],127)] )
# def high(self,x):
# return([(['laser'],x) , ( ['mw'],x ) ] )
#
# def low(self,x):
# return([ (['mw'],x), ( ['laser'],x ) ] )
| Python |
import numpy as np
from traits.api import HasTraits, Range
from traitsui.api import View, Item, RangeEditor
from hardware.nidaq import AOTask
class Laser( HasTraits ):
def __init__(self, AO_channel='/Dev1/ao3', voltage_range=(0.,5.), **kwargs):
self.AOTask = AOTask(Channels=AO_channel, range=voltage_range)
self.AOTask.Write(np.array((float(voltage_range[0]),)))
self.add_trait('voltage', Range(low=float(voltage_range[0]), high=float(voltage_range[1]), value=float(voltage_range[0]), desc='output voltage', label='Voltage [V]'))
self.on_trait_change(self.write_voltage, 'voltage')
HasTraits.__init__(self, **kwargs)
def write_voltage(self, new):
self.AOTask.Write(np.array((new,)))
view = View(Item('voltage'),
title='Laser', width=400, buttons=[], resizable=True)
if __name__=='__main__':
laser = Laser()
laser.edit_traits()
| Python |
import visa
class DanFysik:
def __init__(self, device='GPIB0::7::INSTR', limit_current=10.0, maximum_current=20.0):
self.maximum_current=maximum_current
self.limit_current=limit_current
instr = visa.instrument(device)
instr.timeout=1.0
instr.term_chars='\r'
self.instr=instr
def set_current(self, current):
"""Sets the current in Ampere."""
if current > self.limit_current:
raise ValueError('Limit current exceeded.')
ppm = int(current / self.maximum_current * 1000000)
if ( ppm == 0 ):
self.instr.write('DA 0,%i'%ppm)
self.instr.write('F')
else:
self.instr.write('DA 0,%i'%ppm)
self.instr.write('N')
def get_current(self):
s = self.instr.ask('DA 0')
return float(s.split()[1])*1e-6*self.maximum_current
| Python |
from nidaq import *
import TimeTagger
import numpy
import time
class PulsedAO(object):
"""Provides pulsed analog output. Provides two output forms: 1. set ao channels permanently to a given value.
2. Output N values along with a square wave with given seconds per point."""
def __init__(self, channels, square_wave_device, seconds_per_point, duty_cycle=0.5, range=(-10,10), transfer_timeout=1.0):
# we start with unknown length
self._length = None
self._square_wave_device = square_wave_device
self._seconds_per_point = seconds_per_point
self._duty_cycle = duty_cycle
self._channels = channels
self._transfer_timeout = transfer_timeout
self._n_written = ctypes.c_long()
# create nidaq tasks
self._ao_task = ctypes.c_ulong()
self._co_task = ctypes.c_ulong()
CHK( dll.DAQmxCreateTask('', ctypes.byref(self._ao_task)) )
CHK( dll.DAQmxCreateTask('', ctypes.byref(self._co_task)) )
CHK( dll.DAQmxCreateAOVoltageChan(self._ao_task, self._channels, '', ctypes.c_double(range[0]), ctypes.c_double(range[1]), DAQmx_Val_Volts,'') )
CHK( dll.DAQmxCreateCOPulseChanFreq( self._co_task,
self._square_wave_device, '',
DAQmx_Val_Hz, DAQmx_Val_Low, ctypes.c_double(0),
ctypes.c_double(1./seconds_per_point),
ctypes.c_double(duty_cycle) ) )
def output(self, data):
"""If len(data)==1, output one point. Else output sequence of points.
The shape of data is (n_channels,n_points)."""
if data.ndim == 1:
N = 1
else:
N = data.shape[1]
self.setLength(N)
if N == 1:
CHK( dll.DAQmxWriteAnalogF64(self._ao_task, ctypes.c_long(1), 1, ctypes.c_double(self._transfer_timeout), DAQmx_Val_GroupByChannel, data.ctypes.data, ctypes.byref(self._n_written), None) )
else:
CHK( dll.DAQmxWriteAnalogF64(self._ao_task, ctypes.c_long(N), 0, ctypes.c_double(self._transfer_timeout), DAQmx_Val_GroupByChannel, data.ctypes.data, ctypes.byref(self._n_written), None) )
CHK( dll.DAQmxStartTask(self._ao_task) )
CHK( dll.DAQmxStartTask(self._co_task) )
CHK( dll.DAQmxWaitUntilTaskDone(self._ao_task, ctypes.c_double(4*(N+1)*self._seconds_per_point)) )
time.sleep(4.*self._seconds_per_point)
CHK( dll.DAQmxStopTask(self._co_task) )
CHK( dll.DAQmxStopTask(self._ao_task) )
return self._n_written
def setLength(self, N):
if self._length == N:
return
if N == 1:
CHK( dll.DAQmxSetSampTimingType( self._ao_task, DAQmx_Val_OnDemand) )
else:
CHK( dll.DAQmxSetSampTimingType( self._ao_task, DAQmx_Val_SampClk) )
CHK( dll.DAQmxCfgSampClkTiming( self._ao_task,
self._square_wave_device+'InternalOutput',
ctypes.c_double(1./self._seconds_per_point),
DAQmx_Val_Rising,
DAQmx_Val_FiniteSamps,
ctypes.c_ulonglong(N)) )
CHK( dll.DAQmxCfgImplicitTiming( self._co_task, DAQmx_Val_FiniteSamps, ctypes.c_ulonglong(N+1)) )
self._length = N
def getLength(self):
return self._length
def setTiming(self, seconds_per_point, duty_cycle=0.5):
if seconds_per_point == self._seconds_per_point and duty_cycle == self._duty_cycle:
return
CHK( dll.DAQmxSetCOPulseFreq( self._co_task, self._square_wave_device, ctypes.c_double(1./seconds_per_point) ) )
CHK( dll.DAQmxSetCOPulseDutyCyc( self._co_task, self._square_wave_device, ctypes.c_double(duty_cycle) ) )
self._seconds_per_point = seconds_per_point
self._duty_cycle = duty_cycle
def getTiming(self):
return self._seconds_per_point, self._duty_cycle
def __del__(self):
CHK( dll.DAQmxClearTask(self._ao_task) )
CHK( dll.DAQmxClearTask(self._co_task) )
class HybridScannerTimeTaggerNI():
def __init__(self, analog_channels, square_wave_device, time_tagger_serial, time_tagger_count_channel, time_tagger_marker_channel, seconds_per_point=1e-3, duty_cycle=0.5, voltage_range=(0.,10.), x_range=(0.,100.), y_range=(0.,100), z_range=(0.,20.)):
self._pulsed_ao = PulsedAO(channels=analog_channels, square_wave_device=square_wave_device, seconds_per_point=seconds_per_point, duty_cycle=duty_cycle, range=voltage_range)
TimeTagger._Tagger.setSerial(time_tagger_serial)
self._N = None # we do not know the length of scan line yet
self._x0 = x_range[0]
self._x1 = x_range[1]
self._y0 = y_range[0]
self._y1 = y_range[1]
self._z0 = z_range[0]
self._z1 = z_range[1]
self._position = numpy.zeros(3)
self.setPosition(self._x0, self._y0, self._z0)
self._time_tagger_count_channel=time_tagger_count_channel
self._time_tagger_marker_channel=time_tagger_marker_channel
self.overflow = TimeTagger.OverFlow()
def getXRange(self):
return self._x0, self._x1
def getYRange(self):
return self._y0, self._y1
def getZRange(self):
return self._z0, self._z1
def setPosition(self, x, y, z):
"""Move stage to x, y, z"""
self._pulsed_ao.output(self._convPosToVolt((x, y, z)))
self._position[0] = x
self._position[1] = y
self._position[2] = z
def getPosition(self):
return self._position
def _prepareCounter(self, N):
if self._N == N:
self._count_between_markers.clean()
else:
self._count_between_markers = TimeTagger.CountBetweenMarkers(self._time_tagger_count_channel, self._time_tagger_marker_channel, N)
time.sleep(0.5)
def initImageScan(self, rows, lines, seconds_per_point, return_speed=None):
self.return_speed = return_speed
self.seconds_per_point = seconds_per_point
self.first_line = 1
if return_speed:
self._prepareCounter((rows+1)*lines*2-1)
self.pixel_per_line = (rows+1)*2
else:
self._prepareCounter((rows+1)*lines-1)
self.pixel_per_line = (rows+1)
def doImageLine(self, line):
if self.first_line:
self._pulsed_ao.output( self._convPosToVolt(line[:,0]) )
time.sleep(0.1)
self.first_line = 0
if self.return_speed:
if (line.shape[1]+1)*2 != self.pixel_per_line:
raise ValueError("analog out line length wrong")
self._pulsed_ao.setTiming(self.seconds_per_point, 0.5)
self._pulsed_ao.output( self._convPosToVolt(line) )
self._pulsed_ao.setTiming(self.seconds_per_point/float(self.return_speed), 0.5)
self._pulsed_ao.output( self._convPosToVolt(line[:,::-1]) )
else:
if line.shape[1]+1 != self.pixel_per_line:
raise ValueError("analog out line length wrong")
self._pulsed_ao.setTiming(self.seconds_per_point, 0.5)
self._pulsed_ao.output( self._convPosToVolt(line) )
def getImage(self, blocking=0):
if blocking:
timeout = 3.
start_time = time.time()
while not self._count_between_markers.ready():
time.sleep(0.1)
if time.time() - start_time > timeout:
print "count between markers timeout in scanner.py"
break
image = numpy.append(self._count_between_markers.getData(),0).reshape((-1, self.pixel_per_line))
if self.return_speed is not None:
imageout = image[:,:image.shape[1]/2-1].astype(float)
else:
imageout = numpy.zeros((image.shape[0],image.shape[1]-1))
for i in range(1,image.shape[0],2):
imageout[i,:] = image[i,-2::-1]
for i in range(0,image.shape[0],2):
imageout[i,:] = image[i,0:-1:1]
return imageout / float(self.seconds_per_point)
def scanLine(self, line, seconds_per_point, return_speed=None):
"""Perform a line scan. If return_speed is not None, return to beginning of line
with a speed 'return_speed' times faster than the speed currently set.
"""
self._pulsed_ao.output( self._convPosToVolt(line[:,0]) )
time.sleep(0.1)
N = line.shape[1]
self._prepareCounter(N)
self._pulsed_ao.setTiming(seconds_per_point, 0.5)
start_time = time.time()
self._pulsed_ao.output( self._convPosToVolt(line) )
timeout = 1.
start_time = time.time()
while not self._count_between_markers.ready():
time.sleep(0.1)
if time.time() - start_time > timeout:
break
if return_speed is not None:
self._pulsed_ao.setTiming(seconds_per_point/float(return_speed), 0.5)
self._pulsed_ao.output( self._convPosToVolt(line[:,::-1]) )
return self._count_between_markers.getData() / float(seconds_per_point)
def _convPosToVolt(self, Pos):
x0 = self._x0
x1 = self._x1
y0 = self._y0
y1 = self._y1
z0 = self._z0
z1 = self._z1
return numpy.vstack( ( 10.0 / (x1-x0) * (Pos[0]-x0),
10.0 / (y1-y0) * (Pos[1]-y0),
10.0 / (z1-z0) * (Pos[2]-z0) ) )
def Count(self):
"""Return a single count."""
if not 'counter' in dir(self):
self.counter = TimeTagger.Counter(self._time_tagger_count_channel,80000000)
return self.counter.getData()[0]*10
if __name__ == '__main__':
#PO = PulsedAO(channels='/Dev1/ao0:2', square_wave_device='/Dev1/Ctr0', seconds_per_point=1e-3, duty_cycle=0.5)
scanner = HybridScannerTimeTaggerNI(analog_channels='/Dev1/ao0:2',
square_wave_device='/Dev1/Ctr0',
time_tagger_serial='VJaAMgsRxh',
time_tagger_count_channel=0,
time_tagger_marker_channel=1,
seconds_per_point=1e-3,
duty_cycle=0.5,
voltage_range=(0.,10.),
x_range=(0.,75.),
y_range=(0.,75),
z_range=(-25.,25.))
| Python |
"""
This file is part of pi3diamond.
pi3diamond is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pi3diamond is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with diamond. If not, see <http://www.gnu.org/licenses/>.
Copyright (C) 2009-2011 Helmut Fedder <helmut.fedder@gmail.com>
"""
import ctypes
import numpy
import time
dll = ctypes.windll.LoadLibrary('nicaiu.dll')
DAQmx_Val_Cfg_Default = ctypes.c_int32(-1)
DAQmx_Val_DoNotInvertPolarity = ctypes.c_int32(0)
DAQmx_Val_GroupByChannel = ctypes.c_int32(0)
DAQmx_Val_GroupByScanNumber = ctypes.c_int32(1)
DAQmx_Val_ChanPerLine = ctypes.c_int32(0)
DAQmx_Val_ChanForAllLines = ctypes.c_int32(1)
DAQmx_Val_Acquired_Into_Buffer = ctypes.c_int32(1)
DAQmx_Val_Ticks = ctypes.c_int32(10304)
DAQmx_Val_Rising = ctypes.c_int32(10280)
DAQmx_Val_Falling = ctypes.c_int32(10171)
DAQmx_Val_CountUp = ctypes.c_int32(10128)
DAQmx_Val_ContSamps = ctypes.c_int32(10123)
DAQmx_Val_FiniteSamps = ctypes.c_int32(10178)
DAQmx_Val_Hz = ctypes.c_int32(10373)
DAQmx_Val_Low = ctypes.c_int32(10214)
DAQmx_Val_Volts = ctypes.c_int32(10348)
DAQmx_Val_MostRecentSamp = ctypes.c_uint32(10428)
DAQmx_Val_OverwriteUnreadSamps = ctypes.c_uint32(10252)
DAQmx_Val_HWTimedSinglePoint = ctypes.c_int32(12522)
DAQmx_Val_SampClk = ctypes.c_int32(10388)
DAQmx_Val_OnDemand = ctypes.c_int32(10390)
DAQmx_Val_CurrReadPos = ctypes.c_int32(10425)
DAQmx_Val_MostRecentSamp = ctypes.c_int32(10428)
DAQmx_Val_OverwriteUnreadSamps = ctypes.c_int32(10252)
DAQmx_Val_DoNotOverwriteUnreadSamps = ctypes.c_int32(10159)
c_uint32_p = c_ulong_p = ctypes.POINTER(ctypes.c_uint32)
c_float64_p = c_double_p = ctypes.POINTER(ctypes.c_double)
def CHK(err):
"""a simple error checking routine"""
if err < 0:
buf_size = 1000
buf = ctypes.create_string_buffer('\000' * buf_size)
dll.DAQmxGetErrorString(err,ctypes.byref(buf),buf_size)
raise RuntimeError('nidaq call failed with error %d: %s'%(err,repr(buf.value)))
# route signal
def Connect(source, destination):
"""Connect terminal 'source' to terminal 'destination'."""
CHK( dll.DAQmxConnectTerms(source, destination, DAQmx_Val_DoNotInvertPolarity ) )
def Disconnect(source, destination):
"""Connect terminal 'source' to terminal 'destination'."""
CHK( dll.DAQmxDisconnectTerms(source, destination) )
class CounterBoard:
"""nidaq Counter board.
"""
_CountAverageLength = 10
_MaxCounts = 1e7
_DefaultCountLength = 1000
_RWTimeout = 1.0
def __init__(self, CounterIn, CounterOut, TickSource, SettlingTime=2e-3, CountTime=8e-3):
self._CODevice = CounterOut
self._CIDevice = CounterIn
self._PulseTrain = self._CODevice+'InternalOutput' # counter bins are triggered by CTR1
self._TickSource = TickSource #the signal: ticks coming from the APDs
# nidaq Tasks
self.COTask = ctypes.c_ulong()
self.CITask = ctypes.c_ulong()
CHK( dll.DAQmxCreateTask('', ctypes.byref(self.COTask)) )
CHK( dll.DAQmxCreateTask('', ctypes.byref(self.CITask)) )
f = 1. / ( CountTime + SettlingTime )
DutyCycle = CountTime * f
# ctr1 generates a continuous square wave with given duty cycle. This serves simultaneously
# as sampling clock for AO (update DAC at falling edge), and as gate for counter (count between
# rising and falling edge)
CHK( dll.DAQmxCreateCOPulseChanFreq( self.COTask,
self._CODevice, '',
DAQmx_Val_Hz, DAQmx_Val_Low, ctypes.c_double(0),
ctypes.c_double(f),
ctypes.c_double(DutyCycle) ) )
# ctr0 is used to count photons. Used to count ticks in N+1 gates
CHK( dll.DAQmxCreateCIPulseWidthChan( self.CITask,
self._CIDevice, '',
ctypes.c_double(0),
ctypes.c_double(self._MaxCounts*DutyCycle/f),
DAQmx_Val_Ticks, DAQmx_Val_Rising, '') )
CHK( dll.DAQmxSetCIPulseWidthTerm( self.CITask, self._CIDevice, self._PulseTrain ) )
CHK( dll.DAQmxSetCICtrTimebaseSrc( self.CITask, self._CIDevice, self._TickSource ) )
self._SettlingTime = None
self._CountTime = None
self._DutyCycle = None
self._f = None
self._CountSamples = self._DefaultCountLength
self.setTiming(SettlingTime, CountTime)
self._CINread = ctypes.c_int32()
self.setCountLength(self._DefaultCountLength)
def setCountLength(self, N, BufferLength=None, SampleLength=None):
"""
Set the number of counter samples / length of pulse train. If N is finite, a finite pulse train
of length N is generated and N count samples are acquired. If N is infinity, an infinite pulse
train is generated. BufferLength and SampleLength specify the length of the buffer and the length
of a sample that is read in one read operation. In this case, always the most recent samples are read.
"""
if N < numpy.inf:
CHK( dll.DAQmxCfgImplicitTiming( self.COTask, DAQmx_Val_ContSamps, ctypes.c_ulonglong(N)) )
CHK( dll.DAQmxCfgImplicitTiming( self.CITask, DAQmx_Val_FiniteSamps, ctypes.c_ulonglong(N)) )
# read samples from beginning of acquisition, do not overwrite
CHK( dll.DAQmxSetReadRelativeTo(self.CITask, DAQmx_Val_CurrReadPos) )
CHK( dll.DAQmxSetReadOffset(self.CITask, 0) )
CHK( dll.DAQmxSetReadOverWrite(self.CITask, DAQmx_Val_DoNotOverwriteUnreadSamps) )
self._CountSamples = N
self._TaskTimeout = 4 * N / self._f
else:
CHK( dll.DAQmxCfgImplicitTiming( self.COTask, DAQmx_Val_ContSamps, ctypes.c_ulonglong(BufferLength)) )
CHK( dll.DAQmxCfgImplicitTiming( self.CITask, DAQmx_Val_ContSamps, ctypes.c_ulonglong(BufferLength)) )
# read most recent samples, overwrite buffer
CHK( dll.DAQmxSetReadRelativeTo(self.CITask, DAQmx_Val_MostRecentSamp) )
CHK( dll.DAQmxSetReadOffset(self.CITask, -SampleLength) )
CHK( dll.DAQmxSetReadOverWrite(self.CITask, DAQmx_Val_OverwriteUnreadSamps) )
self._CountSamples = SampleLength
self._CountLength = N
self._CIData = numpy.empty((self._CountSamples,), dtype=numpy.uint32)
def CountLength(self):
return self._CountLength
def setTiming(self, SettlingTime, CountTime):
if SettlingTime != self._SettlingTime or CountTime != self._CountTime:
f = 1. / ( CountTime + SettlingTime )
DutyCycle = CountTime * f
CHK( dll.DAQmxSetCOPulseFreq( self.COTask, self._CODevice, ctypes.c_double(f) ) )
CHK( dll.DAQmxSetCOPulseDutyCyc( self.COTask, self._CODevice, ctypes.c_double(DutyCycle) ) )
self._SettlingTime = SettlingTime
self._CountTime = CountTime
self._f = f
self._DutyCycle = DutyCycle
if self._CountSamples is not None:
self._TaskTimeout = 4 * self._CountSamples / self._f
def getTiming(self):
return self._SettlingTime, self._CountTime
def StartCO(self):
CHK( dll.DAQmxStartTask(self.COTask) )
def StartCI(self):
CHK( dll.DAQmxStartTask(self.CITask) )
def StopCO(self):
CHK( dll.DAQmxStopTask(self.COTask) )
def StopCI(self):
CHK( dll.DAQmxStopTask(self.CITask) )
def ReadCI(self):
CHK( dll.DAQmxReadCounterU32(self.CITask
, ctypes.c_int32(self._CountSamples)
, ctypes.c_double(self._RWTimeout)
, self._CIData.ctypes.data_as(c_uint32_p)
, ctypes.c_uint32(self._CountSamples)
, ctypes.byref(self._CINread), None) )
return self._CIData
def WaitCI(self):
CHK( dll.DAQmxWaitUntilTaskDone(self.CITask, ctypes.c_double(self._TaskTimeout)) )
def startCounter(self, SettlingTime, CountTime):
if self.CountLength() != numpy.inf:
self.setCountLength(numpy.inf, max(1000, self._CountAverageLength), self._CountAverageLength)
self.setTiming(SettlingTime, CountTime)
self.StartCI()
self.StartCO()
time.sleep(self._CountSamples / self._f)
def Count(self):
"""Return a single count."""
return self.ReadCI().mean() * self._f / self._DutyCycle
def stopCounter(self):
self.StopCI()
self.StopCO()
# def __del__(self):
# CHK( dll.DAQmxClearTask(self.CITask) )
# CHK( dll.DAQmxClearTask(self.COTask) )
class MultiBoard( CounterBoard ):
"""nidaq Multifuntion board."""
_DefaultAOLength = 1000
def __init__(self, CounterIn, CounterOut, TickSource, AOChannels, v_range=(0.,10.)):
CounterBoard.__init__(self, CounterIn, CounterOut, TickSource)
self._AODevice = AOChannels
self.AOTask = ctypes.c_ulong()
CHK( dll.DAQmxCreateTask('', ctypes.byref(self.AOTask)) )
CHK( dll.DAQmxCreateAOVoltageChan( self.AOTask,
self._AODevice, '',
ctypes.c_double(v_range[0]),
ctypes.c_double(v_range[1]),
DAQmx_Val_Volts,'') )
self._AONwritten = ctypes.c_int32()
self.setAOLength(self._DefaultAOLength)
def setAOLength(self, N):
if N == 1:
CHK( dll.DAQmxSetSampTimingType( self.AOTask, DAQmx_Val_OnDemand) )
else:
CHK( dll.DAQmxSetSampTimingType( self.AOTask, DAQmx_Val_SampClk) )
if N < numpy.inf:
CHK( dll.DAQmxCfgSampClkTiming( self.AOTask,
self._PulseTrain,
ctypes.c_double(self._f),
DAQmx_Val_Falling, DAQmx_Val_FiniteSamps,
ctypes.c_ulonglong(N)) )
self._AOLength = N
def AOLength(self):
return self._AOLength
def StartAO(self):
CHK( dll.DAQmxStartTask(self.AOTask) )
def StopAO(self):
CHK( dll.DAQmxStopTask(self.AOTask) )
def WriteAO(self, data, start=False):
CHK( dll.DAQmxWriteAnalogF64( self.AOTask,
ctypes.c_int32(self._AOLength),
start,
ctypes.c_double(self._RWTimeout),
DAQmx_Val_GroupByChannel,
data.ctypes.data_as(c_float64_p),
ctypes.byref(self._AONwritten), None) )
return self._AONwritten.value
class AOBoard():
"""nidaq Multifuntion board."""
def __init__(self, AOChannels):
self._AODevice = AOChannels
self.Task = ctypes.c_ulong()
CHK( dll.DAQmxCreateTask('', ctypes.byref(self.Task)) )
CHK( dll.DAQmxCreateAOVoltageChan( self.Task,
self._AODevice, '',
ctypes.c_double(0.),
ctypes.c_double(10.),
DAQmx_Val_Volts,'') )
CHK( dll.DAQmxSetSampTimingType( self.Task, DAQmx_Val_OnDemand) )
self._Nwritten = ctypes.c_int32()
def Write(self, data):
CHK( dll.DAQmxWriteAnalogF64(self.Task,
ctypes.c_long(1),
1,
ctypes.c_double(1.0),
DAQmx_Val_GroupByChannel,
data.ctypes.data_as(c_float64_p),
ctypes.byref(self._Nwritten),
None) )
def Start(self):
CHK( dll.DAQmxStartTask(self.Task) )
def Wait(self, timeout):
CHK( dll.DAQmxWaitUntilTaskDone(self.Task, ctypes.c_double(timeout)) )
def Stop(self):
CHK( dll.DAQmxStopTask(self.Task) )
def __del__(self):
CHK( dll.DAQmxClearTask(self.Task) )
class Scanner( MultiBoard ):
def __init__(self, CounterIn, CounterOut, TickSource, AOChannels,
x_range, y_range, z_range, v_range=(0.,10.),
invert_x=False, invert_y=False, invert_z=False, swap_xy=False, TriggerChannels=None):
MultiBoard.__init__(self, CounterIn=CounterIn,
CounterOut=CounterOut,
TickSource=TickSource,
AOChannels=AOChannels,
v_range=v_range)
if TriggerChannels is not None:
self._trigger_task = DOTask(TriggerChannels)
self.xRange = x_range
self.yRange = y_range
self.zRange = z_range
self.vRange = v_range
self.x = 0.0
self.y = 0.0
self.z = 0.0
self.invert_x = invert_x
self.invert_y = invert_y
self.invert_z = invert_z
self.swap_xy = swap_xy
def getXRange(self):
return self.xRange
def getYRange(self):
return self.yRange
def getZRange(self):
return self.zRange
def setx(self, x):
"""Move stage to x, y, z
"""
if self.AOLength() != 1:
self.setAOLength(1)
self.WriteAO(self.PosToVolt((x, self.y, self.z)), start=True)
self.x = x
def sety(self, y):
"""Move stage to x, y, z
"""
if self.AOLength() != 1:
self.setAOLength(1)
self.WriteAO(self.PosToVolt((self.x, y, self.z)), start=True)
self.y = y
def setz(self, z):
"""Move stage to x, y, z
"""
if self.AOLength() != 1:
self.setAOLength(1)
self.WriteAO(self.PosToVolt((self.x, self.y, z)), start=True)
self.z = z
def scanLine(self, Line, SecondsPerPoint, return_speed=None):
"""Perform a line scan. If return_speed is not None, return to beginning of line
with a speed 'return_speed' times faster than the speed currently set.
"""
self.setTiming(SecondsPerPoint*0.1, SecondsPerPoint*0.9)
N = Line.shape[1]
if self.AOLength() != N: # set buffers of nidaq Tasks, data read buffer and timeout if needed
self.setAOLength(N)
if self.CountLength() != N+1:
self.setCountLength(N+1)
# send line start trigger
if hasattr(self, '_trigger_task'):
self._trigger_task.Write(numpy.array((1,0), dtype=numpy.uint8) )
time.sleep(0.001)
self._trigger_task.Write(numpy.array((0,0), dtype=numpy.uint8) )
# acquire line
self.WriteAO( self.PosToVolt(Line) )
self.StartAO()
self.StartCI()
self.StartCO()
self.WaitCI()
# send line stop trigger
if hasattr(self, '_trigger_task'):
self._trigger_task.Write(numpy.array((0,1), dtype=numpy.uint8) )
time.sleep(0.001)
self._trigger_task.Write(numpy.array((0,0), dtype=numpy.uint8) )
data = self.ReadCI()
self.StopAO()
self.StopCI()
self.StopCO()
if return_speed is not None:
self.setTiming(SecondsPerPoint*0.5/return_speed, SecondsPerPoint*0.5/return_speed)
self.WriteAO( self.PosToVolt(Line[:,::-1]) )
self.StartAO()
self.StartCI()
self.StartCO()
self.WaitCI()
self.StopAO()
self.StopCI()
self.StopCO()
self.setTiming(SecondsPerPoint*0.1, SecondsPerPoint*0.9)
return data[1:] * self._f / self._DutyCycle
def setPosition(self, x, y, z):
"""Move stage to x, y, z"""
if self.AOLength() != 1:
self.setAOLength(1)
self.WriteAO(self.PosToVolt((x, y, z)), start=True)
self.x, self.y, self.z = x, y, z
def PosToVolt(self, r):
x = self.xRange
y = self.yRange
z = self.zRange
v = self.vRange
v0 = v[0]
dv = v[1]-v[0]
if self.invert_x:
vx = v0+(x[1]-r[0])/(x[1]-x[0])*dv
else:
vx = v0+(r[0]-x[0])/(x[1]-x[0])*dv
if self.invert_y:
vy = v0+(y[1]-r[1])/(y[1]-y[0])*dv
else:
vy = v0+(r[1]-y[0])/(y[1]-y[0])*dv
if self.invert_z:
vz = v0+(z[1]-r[2])/(z[1]-z[0])*dv
else:
vz = v0+(r[2]-z[0])/(z[1]-z[0])*dv
if self.swap_xy:
vt = vx
vx = vy
vy = vt
return numpy.vstack( (vx,vy,vz) )
class SquareWave(object):
"""Provides output of a square wave of finite length."""
def __init__(self, square_wave_device, length=100, seconds_per_point=1e-3, duty_cycle=0.5):
self._square_wave_device = square_wave_device
self._length = length
self._seconds_per_point = seconds_per_point
self._duty_cycle = duty_cycle
self._co_task = ctypes.c_ulong()
CHK( dll.DAQmxCreateTask('', ctypes.byref(self._co_task)) )
CHK( dll.DAQmxCreateCOPulseChanFreq( self._co_task,
self._square_wave_device, '',
DAQmx_Val_Hz, DAQmx_Val_Low, ctypes.c_double(0),
ctypes.c_double(1./seconds_per_point),
ctypes.c_double(duty_cycle) ) )
CHK( dll.DAQmxCfgImplicitTiming( self._co_task, DAQmx_Val_FiniteSamps, ctypes.c_ulonglong(length)) )
def setTiming(self, seconds_per_point, duty_cycle=0.5):
CHK( dll.DAQmxSetCOPulseFreq( self._co_task, self._square_wave_device, ctypes.c_double(1./seconds_per_point) ) )
CHK( dll.DAQmxSetCOPulseDutyCyc( self._co_task, self._square_wave_device, ctypes.c_double(duty_cycle) ) )
self._seconds_per_point = seconds_per_point
self._duty_cycle = duty_cycle
def getTiming(self):
return self._seconds_per_point, self._duty_cycle
def setLength(self, length):
CHK( dll.DAQmxCfgImplicitTiming( self._co_task, DAQmx_Val_FiniteSamps, ctypes.c_ulonglong(length)) )
self._length = length
def getLength(self):
return self._length
def output(self):
try: # if nidaq behaves normal, this should work
CHK( dll.DAQmxStartTask(self._co_task) )
except: # else, try to re-create the task and try again
self.__init__(self._square_wave_device, self._length, self._seconds_per_point, self._duty_cycle)
CHK( dll.DAQmxStartTask(self._co_task) )
CHK( dll.DAQmxWaitUntilTaskDone(self._co_task, ctypes.c_double(4*self._length*self._seconds_per_point)) )
CHK( dll.DAQmxStopTask(self._co_task) )
def __del__(self):
CHK( dll.DAQmxClearTask(self._co_task) )
class AnalogOutSyncCount():
"""
Analog output waveform or single point.
Count synchronous with waveform.
"""
def __init__(self, ao_chan, co_dev, ci_dev, ci_port, ao_range=(-10,10), duty_cycle=0.96):
ao_task = ctypes.c_ulong() # analog out
co_task = ctypes.c_ulong() # finite pulse train
ci_task = ctypes.c_ulong() # count photons
CHK( dll.DAQmxCreateTask('', ctypes.byref(ao_task)) )
CHK( dll.DAQmxCreateTask('', ctypes.byref(co_task)) )
CHK( dll.DAQmxCreateTask('', ctypes.byref(ci_task)) )
# ni task for analog out
CHK( dll.DAQmxCreateAOVoltageChan(ao_task,
ao_chan,
'',
ctypes.c_double(ao_range[0]),
ctypes.c_double(ao_range[1]),
DAQmx_Val_Volts,
''
))
CHK( dll.DAQmxCreateCOPulseChanFreq(co_task,
co_dev,
'',
DAQmx_Val_Hz,
DAQmx_Val_Low,
ctypes.c_double(0), # initial delay
ctypes.c_double(1000), # frequency
ctypes.c_double(duty_cycle)
))
CHK( dll.DAQmxCreateCIPulseWidthChan(ci_task,
ci_dev,
'',
ctypes.c_double(0), # expected min
ctypes.c_double(10000.), # expected max
DAQmx_Val_Ticks,
DAQmx_Val_Rising,
''
))
"""
CHK( dll.DAQmxCreateCICountEdgesChan(ci_task,
ci_dev,
'',
DAQmx_Val_Rising,
0, # initial count
DAQmx_Val_CountUp
))
"""
CHK( dll.DAQmxSetCICountEdgesTerm(ci_task, ci_dev, co_dev+'InternalOutput') )
CHK( dll.DAQmxSetCICtrTimebaseSrc(ci_task, ci_dev, ci_port) )
# read samples from beginning of acquisition, do not overwrite
CHK( dll.DAQmxSetReadRelativeTo(ci_task, DAQmx_Val_CurrReadPos) )
CHK( dll.DAQmxSetReadOffset(ci_task, 0) )
CHK( dll.DAQmxSetReadOverWrite(ci_task, DAQmx_Val_DoNotOverwriteUnreadSamps) )
self.ao_task = ao_task
self.co_task = co_task
self.ci_task = ci_task
self.co_dev = co_dev
self.duty_cycle = duty_cycle
def configure(self, n_samples, seconds_per_point):
"""
Configures the sampling length and rate.
n==0: single point
0<n<Inf: single waveform
"""
if n_samples == 0:
CHK( dll.DAQmxSetSampTimingType(self.ao_task, DAQmx_Val_OnDemand) )
elif n_samples < numpy.inf:
f = 1./seconds_per_point
CHK( dll.DAQmxSetSampTimingType(self.ao_task, DAQmx_Val_SampClk) )
CHK( dll.DAQmxCfgSampClkTiming(self.ao_task,
self.co_dev+'InternalOutput',
ctypes.c_double(f),
DAQmx_Val_Falling,
DAQmx_Val_FiniteSamps,
ctypes.c_ulonglong(n_samples)) )
CHK( dll.DAQmxSetCOPulseFreq(self.co_task,
self.co_dev,
ctypes.c_double(f)
))
CHK( dll.DAQmxCfgImplicitTiming(self.co_task,
DAQmx_Val_ContSamps,
ctypes.c_ulonglong(n_samples+1)
))
CHK( dll.DAQmxCfgImplicitTiming(self.ci_task,
DAQmx_Val_FiniteSamps,
ctypes.c_ulonglong(n_samples+1)
))
self.ci_data = numpy.empty((n_samples+1,), dtype=numpy.uint32)
def point(self, voltage):
"""Set the analog out channel(s) to the given value(s)."""
data = numpy.array(voltage)
if self.n_samples != 0:
self.configure(0, None)
self.n_samples = 0
n_written = ctypes.c_long()
CHK( dll.DAQmxWriteAnalogF64(ao_task,
ctypes.c_int32(1),
True,
ctypes.c_double(1.0),
DAQmx_Val_GroupByChannel,
data.ctypes.data_as(c_float64_p),
ctypes.byref(n_written),
None
))
def line(self, voltage, seconds_per_point):
"""Output a waveform and perform synchronous counting."""
data = numpy.array(voltage)
n = len(data)
if n != self.n_samples or seconds_per_point != self.seconds_per_point:
self.configure(n, seconds_per_point)
self.n_samples = n
self.seconds_per_point = seconds_per_point
ao_task = self.ao_task
ci_task = self.ci_task
co_task = self.co_task
n_written = ctypes.c_long()
CHK( dll.DAQmxWriteAnalogF64(ao_task,
ctypes.c_int32(n),
False,
ctypes.c_double(1.0),
DAQmx_Val_GroupByChannel,
data.ctypes.data_as(c_float64_p),
ctypes.byref(n_written),
None
))
ci_data = self.ci_data
n_read = ctypes.c_int32()
timeout = 4 * n * seconds_per_point
CHK( dll.DAQmxStartTask(ao_task) )
CHK( dll.DAQmxStartTask(ci_task) )
CHK( dll.DAQmxStartTask(co_task) )
CHK( dll.DAQmxWaitUntilTaskDone(ci_task, ctypes.c_double(timeout)) )
CHK( dll.DAQmxReadCounterU32(ci_task,
ctypes.c_int32(n+1),
ctypes.c_double(1.0),
ci_data.ctypes.data_as(c_uint32_p),
ctypes.c_uint32(n+1),
ctypes.byref(n_read),
None
))
CHK( dll.DAQmxStopTask(ao_task) )
CHK( dll.DAQmxStopTask(ci_task) )
CHK( dll.DAQmxStopTask(co_task) )
return ci_data[:-1] / ( self.seconds_per_point * self.duty_cycle ) # -ci_data[:-1]
class AOTask(object):
"""Analog output N values with frequency f"""
def __init__(self, Channels, N=numpy.inf, f=None, range=(-10,10), write_timeout=1.0):
self.Channels = Channels
self.N = N
self.f = f
self.write_timeout = write_timeout
self.Nwritten = ctypes.c_long()
self.Task = ctypes.c_ulong()
CHK( dll.DAQmxCreateTask('', ctypes.byref(self.Task)) )
CHK( dll.DAQmxCreateAOVoltageChan(self.Task, self.Channels, '', ctypes.c_double(range[0]), ctypes.c_double(range[1]), DAQmx_Val_Volts,'') )
if N < numpy.inf:
CHK( dll.DAQmxCfgSampClkTiming(self.Task, GateSource, ctypes.c_double(f), DAQmx_Val_Falling, DAQmx_Val_FiniteSamps, ctypes.c_ulonglong(N)) )
def Write(self, data):
if self.N < numpy.inf:
CHK( dll.DAQmxWriteAnalogF64(self.Task,
ctypes.c_long(self.N),
0,
ctypes.c_double(self.write_timeout),
DAQmx_Val_GroupByChannel,
data.ctypes.data_as(c_float64_p),
ctypes.byref(self.Nwritten),
None) )
else:
CHK( dll.DAQmxWriteAnalogF64(self.Task,
ctypes.c_long(1),
1,
ctypes.c_double(self.write_timeout),
DAQmx_Val_GroupByChannel,
data.ctypes.data_as(c_float64_p),
ctypes.byref(self.Nwritten),
None) )
def Start(self):
CHK( dll.DAQmxStartTask(self.Task) )
def Wait(self, timeout):
CHK( dll.DAQmxWaitUntilTaskDone(self.Task, ctypes.c_double(timeout)) )
def Stop(self):
CHK( dll.DAQmxStopTask(self.Task) )
def __del__(self):
CHK( dll.DAQmxClearTask(self.Task) )
class DOTask(object):
def __init__(self, DOChannels, write_timeout=1.0):
self.write_timeout = write_timeout
self.Nwritten = ctypes.c_long()
self.Task = ctypes.c_ulong()
CHK( dll.DAQmxCreateTask('', ctypes.byref(self.Task)) )
CHK( dll.DAQmxCreateDOChan(self.Task, DOChannels, '', DAQmx_Val_ChanPerLine) )
def Write(self, data):
#CHK( dll.DAQmxWriteDigitalScalarU32(self.Task, ctypes.c_long(1), ctypes.c_double(self.write_timeout), ctypes.c_uint32(value), None) )
CHK( dll.DAQmxWriteDigitalLines(self.Task,
ctypes.c_long(1),
1,
ctypes.c_double(self.write_timeout),
1,
data.ctypes.data_as(c_uint32_p),
ctypes.byref(self.Nwritten),
None ) )
#CHK( dll.DAQmxWriteDigitalU32(self.Task, ctypes.c_long(1), 1, ctypes.c_double(self.write_timeout), DAQmx_Val_GroupByChannel, data.ctypes.data, ctypes.byref(self.Nwritten), None ) )
def Start(self):
CHK( dll.DAQmxStartTask(self.Task) )
def Wait(self, timeout):
CHK( dll.DAQmxWaitUntilTaskDone(self.Task, ctypes.c_double(timeout)) )
def Stop(self):
CHK( dll.DAQmxStopTask(self.Task) )
def __del__(self):
CHK( dll.DAQmxClearTask(self.Task) )
class AITask(object):
"""Analog input N values with frequency f"""
def __init__(self, Channels, N, f, read_timeout=1.0, range=(-10, 10)):
self.Channels = Channels
self.N = N
self.f = f
self.clock_source = 'OnboardClock'
self.read_timeout = read_timeout
self.range = range
self.timeout = ctypes.c_double(4.*N/f)
self.Nread = ctypes.c_long()
self.data = numpy.zeros((3,N), dtype=numpy.double )
self.Task = ctypes.c_ulong()
CHK( dll.DAQmxCreateTask('', ctypes.byref(self.Task)) )
CHK( dll.DAQmxCreateAIVoltageChan(self.Task, self.Channels, '', DAQmx_Val_Cfg_Default, ctypes.c_double(self.range[0]), ctypes.c_double(self.range[1]), DAQmx_Val_Volts, ''))
CHK( dll.DAQmxCfgSampClkTiming(self.Task, self.clock_source, ctypes.c_double(f), DAQmx_Val_Rising, DAQmx_Val_FiniteSamps, ctypes.c_ulonglong(N)) )
def Read(self):
CHK( dll.DAQmxReadAnalogF64(self.Task,
ctypes.c_long(self.N),
ctypes.c_double(self.read_timeout),
DAQmx_Val_GroupByChannel,
self.data.ctypes.data_as(c_float64_p),
ctypes.c_ulong(3*self.N),
ctypes.byref(self.Nread),
None) )
return self.data
def Start(self):
CHK( dll.DAQmxStartTask(self.Task) )
def Wait(self):
CHK( dll.DAQmxWaitUntilTaskDone(self.Task, self.timeout) )
def Stop(self):
CHK( dll.DAQmxStopTask(self.Task) )
def __del__(self):
CHK( dll.DAQmxClearTask(self.Task) )
class PulseTrainCounter:
"""Outputs pulsed train and performs gated count."""
def __init__(self, CounterIn, CounterOut, TickSource):
self._CounterIn = CounterIn
self._CounterOut = CounterOut
self._TickSource = TickSource
def configure(self, SampleLength, SecondsPerPoint, DutyCycle=0.9, MaxCounts=1e7, RWTimeout=1.0):
if hasattr(self, '_CITask') or hasattr(self, '_COTask'):
self.clear()
f = 1. / SecondsPerPoint
# nidaq Tasks
self._COTask = ctypes.c_ulong()
self._CITask = ctypes.c_ulong()
CHK( dll.DAQmxCreateTask('', ctypes.byref(self._COTask)) )
CHK( dll.DAQmxCreateTask('', ctypes.byref(self._CITask)) )
# ctr1 generates a continuous square wave with given duty cycle. This serves simultaneously
# as sampling clock for AO (update DAC at falling edge), and as gate for counter (count between
# rising and falling edge)
CHK( dll.DAQmxCreateCOPulseChanFreq( self._COTask,
self._CounterOut, '',
DAQmx_Val_Hz, DAQmx_Val_Low, ctypes.c_double(0),
ctypes.c_double(f),
ctypes.c_double(DutyCycle) ) )
# ctr0 is used to count photons. Used to count ticks in N+1 gates
CHK( dll.DAQmxCreateCIPulseWidthChan( self._CITask,
self._CounterIn, '',
ctypes.c_double(0),
ctypes.c_double(MaxCounts*DutyCycle/f),
DAQmx_Val_Ticks, DAQmx_Val_Rising, '') )
CHK( dll.DAQmxSetCIPulseWidthTerm( self._CITask, self._CounterIn, self._CounterOut+'InternalOutput' ) )
CHK( dll.DAQmxSetCICtrTimebaseSrc( self._CITask, self._CounterIn, self._TickSource ) )
CHK( dll.DAQmxCfgImplicitTiming( self._COTask, DAQmx_Val_ContSamps, ctypes.c_ulonglong(SampleLength)) )
CHK( dll.DAQmxCfgImplicitTiming( self._CITask, DAQmx_Val_FiniteSamps, ctypes.c_ulonglong(SampleLength)) )
# read samples from beginning of acquisition, do not overwrite
CHK( dll.DAQmxSetReadRelativeTo(self._CITask, DAQmx_Val_CurrReadPos) )
CHK( dll.DAQmxSetReadOffset(self._CITask, 0) )
CHK( dll.DAQmxSetReadOverWrite(self._CITask, DAQmx_Val_DoNotOverwriteUnreadSamps) )
self._CIData = numpy.empty((SampleLength,), dtype=numpy.uint32)
self._CINread = ctypes.c_int32()
self._SampleLength = SampleLength
self._TaskTimeout = 4 * SampleLength / f
self._RWTimeout = RWTimeout
def run(self):
CHK( dll.DAQmxStartTask(self._CITask) )
CHK( dll.DAQmxStartTask(self._COTask) )
CHK( dll.DAQmxWaitUntilTaskDone(self._CITask, ctypes.c_double(self._TaskTimeout)) )
CHK( dll.DAQmxReadCounterU32(self._CITask,
ctypes.c_int32(self._SampleLength),
ctypes.c_double(self._RWTimeout),
self._CIData.ctypes.data_as(c_uint32_p),
ctypes.c_uint32(self._SampleLength),
ctypes.byref(self._CINread), None) )
CHK( dll.DAQmxStopTask(self._COTask) )
CHK( dll.DAQmxStopTask(self._CITask) )
return self._CIData
def clear(self):
CHK( dll.DAQmxClearTask((self._CITask)) )
CHK( dll.DAQmxClearTask((self._COTask)) )
del self._CITask
del self._COTask
def __del__(self):
try:
self.clear()
except Exception as e:
print str(e)
def test():
#stage = nidaqStage(1, 1, 0, '0:2')
stage = 1
x = stage._xRange
y = stage._yRange
z = stage._zRange
stage.setPosition(0.3*(x[0]+x[1]), y[0], z[0])
stage.startCounter()
time.sleep(0.1)
print stage.Count()
stage.stopCounter()
X = numpy.linspace(x[0], x[1], 100)
Y = numpy.linspace(y[0], y[1], 100)
Z = numpy.linspace(z[0], z[1], 100)
print stage.ScanLine( numpy.vstack((X,Y,Z)) )
stage.setPosition(0.7*(x[0]+x[1]), y[0], z[0])
print 'board 2'
Connect('/dev1/pfi8', '/dev2/pfi8')
counter = CounterBoard(2,1,0)
counter.startCounter()
time.sleep(0.1)
print counter.Count()
counter.stopCounter()
del stage
del counter
if __name__=='__main__':
test()
| Python |
import time
import os
import cPickle
from exceptions import IOError
# Enthought library imports
from traits.api import Float, HasTraits, HasPrivateTraits, Str, Tuple, File, Button
from traitsui.api import Handler, View, Item, OKButton, CancelButton
from traitsui.file_dialog import open_file, save_file
from chaco.tools.simple_zoom import SimpleZoom
import logging
from data_toolbox import writeDictToFile
import threading
def timestamp():
"""Returns the current time as a human readable string."""
return time.strftime('%y-%m-%d_%Hh%Mm%S', time.localtime())
class Singleton(type):
"""
Singleton using metaclass.
Usage:
class Myclass( MyBaseClass )
__metaclass__ = Singleton
Taken from stackoverflow.com.
http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
"""
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
#class Singleton(object):
# """
# Singleton overwriting __new__.
#
# Cons: multiple inheritance
# __new__ could be overwritten
# __init__ is called upon every 'instantiation'
# """
# def __new__(cls, *a, **k):
# if not hasattr(cls, '_inst'):
# cls._inst = super(Singleton, cls).__new__(cls)
# return cls._inst
class History(object):
"""History of length 'length'."""
def __init__(self, length):
self.length = length
self.items = [ ]
self.i = 0
def get(self):
return self.items[self.i]
def back(self):
if self.i != 0:
self.i = self.i - 1
return self.items[self.i]
def forward(self):
if self.i != len(self.items) - 1:
self.i = self.i + 1
return self.items[self.i]
def put(self, item):
while self.i < len(self.items) - 1:
self.items.pop()
if self.i == self.length - 1:
self.items.pop(0)
self.items.append(item)
self.i = len(self.items) - 1
def setlength(self, length):
while len(self.items) > length:
self.items.pop(0)
self.i = self.i - 1
self.length = length
class StoppableThread( threading.Thread ):
"""
A thread that can be stopped.
Parameters:
target: callable that will be execute by the thread
name: string that will be used as a name for the thread
Methods:
stop(): stop the thread
Use threading.currentThread().stop_request.isSet()
or threading.currentThread().stop_request.wait([timeout])
in your target callable to react to a stop request.
"""
def __init__(self, target=None, name=None):
threading.Thread.__init__(self, target=target, name=name)
self.stop_request = threading.Event()
def stop(self, timeout=10.):
name = str(self)
logging.getLogger().debug('attempt to stop thread '+name)
if threading.currentThread() is self:
logging.getLogger().debug('Thread '+name+' attempted to stop itself. Ignoring stop request...')
return
elif not self.is_alive():
logging.getLogger().debug('Thread '+name+' is not running. Continuing...')
return
self.stop_request.set()
self.join(timeout)
if self.is_alive():
logging.getLogger().warning('Thread '+name+' failed to join after '+str(timeout)+' s. Continuing anyway...')
from traits.api import HasPrivateTraits, SingletonHasPrivateTraits
class DialogBox( HasPrivateTraits ):
"""Dialog box for showing a message."""
message = Str
class FileDialogBox( SingletonHasPrivateTraits ):
"""Dialog box for selection of a filename string."""
filename = File
def warning( message='', buttons=[OKButton, CancelButton] ):
"""
Displays 'message' in a dialog box and returns True or False
if 'OK' respectively 'Cancel' button pressed.
"""
dialog_box = DialogBox( message=message )
ui = dialog_box.edit_traits(view=View(Item('message', show_label=False, style='readonly'),
buttons=buttons,
width=400, height=150,
kind='modal'
)
)
return ui.result
def save_file(title=''):
"""
Displays a dialog box that lets the user select a file name.
Returns None if 'Cancel' button is pressed or overwriting
an existing file is canceled.
The title of the window is set to 'title'.
"""
dialog_box = FileDialogBox()
ui = dialog_box.edit_traits(View(Item('filename'),
buttons = [OKButton, CancelButton],
width=400, height=150,
kind='modal',
title=title
)
)
if ui.result:
if not os.access(dialog_box.filename, os.F_OK) or warning('File exists. Overwrite?'):
return dialog_box.filename
else:
return
class GetSetItemsMixin( HasTraits ):
"""
Provides save, load, save figure methods. Useful with HasTraits models.
Data is stored in a dictionary with keys that are strings and identical to
class attribute names. To save, pass a list of strings that denote attribute names.
Load methods accept a filename. The dictionary is read from file and attributes
on the class are set (if necessary created) according to the dictionary content.
"""
filename = File()
save_button = Button(label='save', show_label=False)
load_button = Button(label='load', show_label=False)
get_set_items = [] # Put class members that will be saved upon calling 'save' here.
# BIG FAT WARNING: do not include List() traits here. This will cause inclusion of the entire class definition during pickling
# and will result in completely uncontrolled behavior. Normal [] lists are OK.
def set_items(self, d):
# In order to set items in the order in which they appear
# in the get_set_items, we first iterate through the get_set_items
# and check whether there are corresponding values in the dictionary.
for key in self.get_set_items:
try:
if key in d:
val = d[key]
attr = getattr(self, key)
if isinstance(val,dict) and isinstance(attr, GetSetItemsMixin): # iterate to the instance
attr.set_items(val)
else:
setattr(self, key, val)
except:
logging.getLogger().warning("failed to set item '"+key+"'")
def get_items(self, keys=None):
if keys is None:
keys = self.get_set_items
d = {}
for key in keys:
attr = getattr(self, key)
if isinstance(attr, GetSetItemsMixin): # iterate to the instance
d[key] = attr.get_items()
else:
d[key] = attr
return d
def save(self, filename):
"""detects the format of the savefile and saves it according to the file-ending. .txt and .asc result in an ascii sav,
.pyd in a pickled python save with mode='asc' and .pys in a pickled python file with mode='bin'"""
if not filename:
raise IOError('Empty filename. Specify a filename and try again!')
writeDictToFile(self.get_items(),filename)
def load(self, filename):
if filename == '':
raise IOError('Empty filename. Specify a filename and try again!')
if os.access(filename, os.F_OK):
logging.getLogger().debug('attempting to restore state of '+self.__str__()+' from '+filename+'...')
try:
logging.getLogger().debug('trying binary mode...')
self.set_items(cPickle.load(open(filename,'rb')))
except:
try:
logging.getLogger().debug('trying text mode...')
self.set_items(cPickle.load(open(filename,'r')))
except:
try:
logging.getLogger().debug('trying unicode text mode...')
self.set_items(cPickle.load(open(filename,'rU')))
except:
logging.getLogger().debug('failed to restore state of '+self.__str__()+'.')
raise IOError('Load failed.')
logging.getLogger().debug('state of '+self.__str__()+' restored.')
else:
raise IOError('File does not exist.')
def _save_button_fired(self):
if os.access(self.filename, os.F_OK):
if not warning('File exists. Overwrite?'):
return
try:
self.save(self.filename)
except IOError as err:
warning(err.message, buttons=[OKButton])
def _load_button_fired(self):
try:
self.load(self.filename)
except IOError as err:
warning(err.message, buttons=[OKButton])
def copy_items(self, keys):
d = {}
for key in keys:
item = getattr(self, key)
if hasattr(item,'copy'):
d[key] = item.copy()
else:
d[key] = item
return d
class GetSettableHistory(History,GetSetItemsMixin):
"""
Implements a history that can be pickled and unpickled
in a generic way using GetSetItems. When this class is used,
the data attached to the history is saved instead of
the history object, which otherwise would require the definition
of the history class to be present when unpickling the file.
"""
get_set_items=['items','length','i']
if __name__ is '__main__':
pass
| Python |
"""
Implements a Cron Scheduler in python.
Taken from stackoverflow.com:
http://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python
"""
# ToDo: maybe add auto_start functionality of the CronDaemon (e.g. self.start within submit() method)?
import threading
import logging
import time
from datetime import datetime, timedelta
from tools.utility import Singleton, StoppableThread, timestamp
# Some utility classes / functions first
class AllMatch(set):
"""Universal set - match everything"""
def __contains__(self, item): return True
allMatch = AllMatch()
def conv_to_set(obj): # Allow single integer to be provided
if isinstance(obj, (int,long)):
return set([obj]) # Single item
if not isinstance(obj, set):
obj = set(obj)
return obj
# The actual Event class
class CronEvent(object):
def __init__(self, action, min=allMatch, hour=allMatch,
day=allMatch, month=allMatch, dow=allMatch,
args=(), kwargs={}):
self.mins = conv_to_set(min)
self.hours= conv_to_set(hour)
self.days = conv_to_set(day)
self.months = conv_to_set(month)
self.dow = conv_to_set(dow)
self.action = action
self.args = args
self.kwargs = kwargs
def matchtime(self, t):
"""Return True if this event should trigger at the specified datetime"""
return ((t.minute in self.mins) and
(t.hour in self.hours) and
(t.day in self.days) and
(t.month in self.months) and
(t.weekday() in self.dow))
def check(self, t):
if self.matchtime(t):
logging.getLogger().debug('Time match at cron event '+str(self)+' at time '+str(t)+'. Executing '+str(self.action)+'.')
self.action(*self.args, **self.kwargs)
def __repr__(self):
return 'Cron Event on callable '+str(self.action)
class CronDaemon( ):
__metaclass__ = Singleton
def __init__(self, *events):
self.events = list(events)
self.lock = threading.Lock()
self.thread = StoppableThread() # the thread the manager loop is running in
def register(self, event):
self.lock.acquire()
try:
self.events.append(event)
finally:
self.lock.release()
def remove(self, event):
self.lock.acquire()
try:
self.events.remove(event)
finally:
self.lock.release()
def start(self):
"""Start the process loop in a thread."""
if self.thread.is_alive():
return
self.thread = StoppableThread(target = self.run, name=self.__class__.__name__ + timestamp())
self.thread.start()
def stop(self, timeout=None):
"""Stop the process loop."""
self.thread.stop(timeout=timeout)
def run(self):
logging.getLogger().info('Starting Cron Daemon.')
t=datetime(*datetime.now().timetuple()[:5])
while 1:
self.lock.acquire()
try:
logging.getLogger().log(5,'Checking events at '+str(datetime.now())+' with '+str(t)+'.')
for e in self.events:
e.check(t)
finally:
self.lock.release()
t += timedelta(minutes=1)
while datetime.now() < t:
delta = (t - datetime.now()).total_seconds()
self.thread.stop_request.wait(delta)
if self.thread.stop_request.isSet():
return
logging.getLogger().info('Shutting down Cron Daemon.')
if __name__ == '__main__':
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
def act():
print 'a'
def bct():
print 'b'
CronDaemon().start()
CronDaemon().register( CronEvent(act, min=range(60)) )
CronDaemon().register( CronEvent(bct, min=range(0,60,2)) )
| Python |
"""
The execution model.
"""
import threading
import logging
from tools.utility import Singleton, StoppableThread, timestamp
from traits.api import HasTraits, Instance, Enum, Range, Button
from traitsui.api import View, Item, HGroup
# ToDo: maybe add auto_start functionality of the JobManager (e.g. self.start within submit() method)?
class Job( HasTraits ):
"""
Defines a job.
Methods:
start(): starts the job
stop(timeout): stops the job
_run(): actual function that is run in a thread
Data:
priority: priority of the job (used by a job manager to schedule the job)
state: shows the current state of the job, 'idle', 'run' or 'wait'
In the current execution model, a job should be re-startable.
I.e., when a job is stopped before it is finished, upon next
start, the work should be continued e.g. previously acquired
data should be kept and accumulated.
It is the user's task to ensure that previous data is
handled correctly and to decide when a job should be continued
and when it should be restarted as a new measurement.
A job can be in one of three states 'idle': doing nothing,
'run': running, 'wait': waiting to be executed. The latter state
is typically set by a Job manager to show that the job is
scheduled for execution. The
"""
priority = Range(low=0, high=10, value=0, desc='priority of the job', label='priority', mode='text', auto_set=False, enter_set=True)
state = Enum('idle', 'run', 'wait', 'done', 'error') # only for display. Shows the state of the job. 'idle': not submitted, 'run': running, 'wait':in queue
thread = Instance( StoppableThread, factory=StoppableThread )
def start(self):
"""Start the thread."""
if self.thread.is_alive():
return
self.thread = StoppableThread(target = self._run, name=self.__class__.__name__ + timestamp())
self.thread.start()
def stop(self, timeout=None):
"""Stop the thread."""
self.thread.stop(timeout=timeout)
def _run(self):
"""Method that is run in a thread."""
try:
self.state='run'
while(True):
#logging.getLogger().debug("Yeah, still taking data like the LHC!")
self.thread.stop_request.wait(1.0) # little trick to have a long (1 s) refresh interval but still react immediately to a stop request
if self.thread.stop_request.isSet():
logging.getLogger().debug('Received stop signal. Returning from thread.')
break
if True:
self.state='idle'
else:
self.state='done'
except:
logging.getLogger().exception('Error in job.')
self.state='error'
finally:
logging.getLogger().debug('Turning off all instruments.')
class JobManager( ): # ToDo: In principle this need not be a singleton. Then there could be different job managers handling different sets of resources. However currently we need singleton since the JobManager is called explicitly on ManagedJob class.
__metaclass__ = Singleton
"""Provides a queue for starting and stopping jobs according to their priority."""
def __init__(self):
self.thread = StoppableThread() # the thread the manager loop is running in
self.lock = threading.Condition() # lock to control access to 'queue' and 'running'
self.queue = []
self.running = None
self.refresh_interval = 0.1 # seconds
def submit(self, job):
"""
Submit a job.
If there is no job running, the job is appended to the queue.
If the job is the running job or the job is already in the queue, do nothing.
If job.priority =< priority of the running job,
the job is appended to the queue and the queue sorted according to priority.
If job.priority > priority of the running job,
the job is inserted at the first position of the queue, the running job is stopped
and inserted again at the first position of the queue.
"""
logging.debug('Attempt to submit job '+str(job))
self.lock.acquire()
running = self.running
queue = self.queue
if job is running or job in queue:
logging.info('The job '+str(job)+' is already running or in the queue.')
self.lock.release()
return
queue.append(job)
queue.sort(cmp=lambda x,y: cmp(x.priority,y.priority), reverse=True) # ToDo: Job sorting not thoroughly tested
job.state='wait'
logging.debug('Notifying process thread.')
self.lock.notify()
self.lock.release()
logging.debug('Job '+str(job)+' submitted.')
def remove(self, job):
"""
Remove a job.
If the job is running, stop it.
If the job is in the queue, remove it.
If the job is not found, this will result in an exception.
"""
logging.debug('Attempt to remove job '+str(job))
self.lock.acquire()
try:
if job is self.running:
logging.debug('Job '+str(job)+' is running. Attempt stop.')
job.stop()
logging.debug('Job '+str(job)+' removed.')
else:
if not job in self.queue:
logging.debug('Job '+str(job)+' neither running nor in queue. Returning.')
else:
logging.debug('Job '+str(job)+' is in queue. Attempt remove.')
self.queue.remove(job)
logging.debug('Job '+str(job)+' removed.')
job.state='idle' # ToDo: improve handling of state. Move handling to Job?
finally:
self.lock.release()
def start(self):
"""Start the process loop in a thread."""
if self.thread.is_alive():
return
logging.getLogger().info('Starting Job Manager.')
self.thread = StoppableThread(target = self._process, name=self.__class__.__name__ + timestamp())
self.thread.start()
def stop(self, timeout=None):
"""Stop the process loop."""
self.thread.stop_request.set()
self.lock.acquire()
self.lock.notify()
self.lock.release()
self.thread.stop(timeout=timeout)
def _process(self):
"""
The process loop.
Use .start() and .stop() methods to start and stop processing of the queue.
"""
while True:
self.thread.stop_request.wait(self.refresh_interval)
if self.thread.stop_request.isSet():
break
# ToDo: jobs can be in queue before process loop is started
# what happens when manager is stopped while jobs are running?
self.lock.acquire()
if self.running is None:
if self.queue == []:
logging.debug('No job running. No job in queue. Waiting for notification.')
self.lock.wait()
logging.debug('Caught notification.')
if self.thread.stop_request.isSet():
self.lock.release()
break
logging.debug('Attempt to fetch first job in queue.')
self.running = self.queue.pop(0)
logging.debug('Found job '+str(self.running)+'. Starting.')
self.running.start()
elif not self.running.thread.is_alive():
logging.debug('Job '+str(self.running)+' stopped.')
self.running=None
if self.queue != []:
logging.debug('Attempt to fetch first job in queue.')
self.running = self.queue.pop(0)
logging.debug('Found job '+str(self.running)+'. Starting.')
self.running.start()
elif self.queue != [] and self.queue[0].priority > self.running.priority:
logging.debug('Found job '+str(self.queue[0])+' in queue with higher priority than running job. Attempt to stop running job.')
self.running.stop()
if self.running.state != 'done':
logging.debug('Reinserting job '+str(self.running)+' in queue.')
self.queue.insert(0,self.running)
self.queue.sort(cmp=lambda x,y: cmp(x.priority,y.priority), reverse=True) # ToDo: Job sorting not thoroughly tested
self.running.state='wait'
self.running = self.queue.pop(0)
logging.debug('Found job '+str(self.running)+'. Starting.')
self.running.start()
self.lock.release()
class ManagedJob( Job ):
"""
Job with methods and buttons that submit the job to the JobManager.
Methods:
submit(): submit the job to the JobManager.
remove(): remove the job from the JobManager.
Data:
state: shows the current state of the job, 'idle', 'run', 'wait' or 'error'
GUI:
submit_button: calls submit()
remove_button: calls remove()
"""
submit_button = Button(label='submit', desc='Submit the measurement to the job manager.')
remove_button = Button(label='remove', desc='Remove the measurement from the job manager. Stop it if necessary.')
def submit(self):
"""Submit the job to the JobManager."""
JobManager().submit(self) # we just submit again and again. The JobManager takes care that duplicate submissions are ignored
def remove(self):
"""Remove the job from the JobManager. Stop job if necessary."""
JobManager().remove(self) # we just try to remove. The JobManager takes care that unknown jobs are ignored
def _submit_button_fired(self):
"""React to submit button. Submit the Job."""
self.submit()
def _remove_button_fired(self):
"""React to remove button. Remove the Job."""
self.remove()
traits_view=View(HGroup(Item('submit_button', show_label=False),
Item('remove_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),),
resizable=True)
class FreeJob( Job ):
"""
Job with buttons that start the job without the JobManager.
GUI:
start_button: calls start()
stop_button: calls stop()
"""
start_button = Button(label='start', desc='Starts the measurement.')
stop_button = Button(label='stop', desc='Stops the measurement.')
def _start_button_fired(self):
"""React to submit button. Submit the Job."""
self.start()
def _stop_button_fired(self):
"""React to remove button. Remove the Job."""
self.stop()
traits_view=View(HGroup(Item('start_button', show_label=False),
Item('stop_button', show_label=False),
Item('priority'),
Item('state', style='readonly'),),
resizable=True)
# ToDo: 1. integration of Job with typical experiments (HasTraits) and JobManager (class 'ManagedJob' ?)
# 2. fix JobManager
# 3. CRON Daemon
# 4. provide changing of priority after submission
# ToDo: there is a fundamental problem with the execution model: a user could start to play with priorities of his measurements
# and eventually give them priorities that are higher than the tracker priority --> this is a bit difficult to see
# ToDo: migrate Job to a subclass of Thread?
if __name__ == '__main__':
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
JobManager().start()
import time
time.sleep(0.1)
jobs = [ Job() for i in range(5)]
jobs[0].priority = 0
jobs[1].priority = 1
jobs[2].priority = 0
jobs[3].priority = 3
jobs[4].priority = 0
[JobManager().submit(job) for job in jobs ]
time.sleep(0.1)
q = JobManager().queue
print [job.priority for job in q]
print [q.index(job) if job in q else None for job in jobs]
#import time
#time.sleep(0.1)
#j3 = Job()
#j3.priority = 1
#JobManager().submit(j3)
| Python |
#rev 1.2
import pickle #works better than cPickle
import cPickle
_file_mode_map = {'asc':'', 'bin':'b'}
_pickle_mode_map = {'asc':0, 'bin':1}
def writeDictToFile(dict, filename):
if filename.find('.txt')!=-1 or filename.find('.asc')!=-1:
d=dictToAscii(dict)
stringToFile(d,filename)
elif filename.find('.pys')!=-1:
mode='bin'
fil = open(filename,'w'+_file_mode_map[mode])
cPickle.dump(dict, fil, _pickle_mode_map[mode])
fil.close()
elif filename.find('.pyd')!=-1:
mode='asc'
fil = open(filename,'w'+_file_mode_map[mode])
cPickle.dump(dict, fil, _pickle_mode_map[mode])
fil.close()
else:
filename=filename+'.pys'
mode='bin'
fil = open(filename,'w'+_file_mode_map[mode])
cPickle.dump(dict, fil, _pickle_mode_map[mode])
fil.close()
#interacts with __get_state__
def keysFromDict(dict, keys=None):
"""extract any number of keys from a dictionary"""
d={}
if keys==None: # return entire dict
return dict
else:
if not hasattr(keys,'__iter__'): # only one key
d[keys]=dict[keys]
else: # tuple of keys
for key in keys:
d[key]=dict[key]
return d
def pickleFileToDict(path, keys=None):
"""(path, [(keys)]) Extracts the whole or a key of a dictionary from a pickled file"""
dict={}
try:
fileh=open(path,'rU')
try:
dict=pickle.load(fileh)
finally:
fileh.close()
except IOError:
print 'Error importing data'
d=KeysFromDict(dict,keys)
return d
def blub(value):
if hasattr(value,'__iter__'):
blub(value.subitem)
def dictToAscii(dict, keys=None):
"""Converts a dictionary or parts of it to a string"""
try: # if there is a doc string put it up front
datastring= '#__doc__\n'+dict['__doc__']+'\n'
del dict['__doc__']
except:
datastring=''
for key, value in dict.items():
datastring+= '#'+key+'\n' # header for each key
#blub(value)
if hasattr(value,'__iter__'): # array?
if value!=[]:
if hasattr(value[0],'__iter__'): # 2d array?
#2d array
for i in range(value.shape[0]):
for j in range(value.shape[1]):
datastring+=(str(value[i,j])+', ')
if j==value.shape[1]-1:
datastring+='\n'
else:
#1d array
try:
n=value.shape[0]
except:
n=len(value)
for i in range(n):
datastring+=(str(value[i])+'\n')
else:
datastring=datastring+' '+'/n'
else:
# value no array
datastring=datastring+str(value)+'\n'
return datastring
#def write(item, string):
# if hasattr(value,'__iter__'): # array?
# for subitem in item:
# write(subitem, string)
# else:
# string=string+str(value)+'\n'
# return string
def stringToFile(datastring, path):
"""writes datastring to file"""
try:
f=open(path,'w')
try:
f.write(datastring)
finally:
f.close()
except IOError:
print 'Error exporting data'
return False
return True
def pickleFileToAscFile(sourcefile, targetfile=None, keys=None):
"""dump pickle from pickled file to ascii file (source, [target], [(keys)])"""
dict={}
dict=PickleFile2Dict(sourcefile, keys)
datastring=Dict2Ascii(dict, keys)
if targetfile==None:
String2File(datastring, sourcefile+'.asc')
else:
String2File(datastring, targetfile)
| Python |
# Enthought library imports
from traits.api import Float, HasTraits, HasPrivateTraits, Str, Tuple, File, Button
from traitsui.api import Handler, View, Item, OKButton, CancelButton
from exceptions import IOError
class ChacoSaveMixin:
"""
Provides a 'save' method, that saves the enable component as graphics file.
"""
def save_raster(self, filename):
"""
Saves an image of a chaco component (e.g. 'Plot' or 'Container')
to a raster file, such as .jpg or .png. The file type is terermined
by the extension.
"""
from chaco.api import PlotGraphicsContext
gc = PlotGraphicsContext(self.outer_bounds, dpi=72)
self.draw(gc, mode="normal")
#gc.render_component(self)
gc.save(filename)
return
def save_pdf(self, filename):
"""
Saves an image of a chaco component (e.g. 'Plot' or 'Container')
to a .pdf file.
"""
from chaco.pdf_graphics_context import PdfPlotGraphicsContext
gc = PdfPlotGraphicsContext(filename=filename)
#pagesize = self.pagesize,
#dest_box = self.dest_box,
#dest_box_units = self.dest_box_units)
gc.render_component(self)
gc.save()
def save(self, filename):
"""
Saves the plot to a graphics file, e.g. .png or .pdf.
Example of usage:
plot = my_instance.line_plot
filename = 'foo.png'
save_figure(plot, filename)
"""
if filename:
if os.path.splitext(filename)[-1] == ".pdf":
self.save_pdf(filename)
else:
self.save_raster(filename)
else:
raise IOError('Empty filename.')
from chaco.api import Plot, HPlotContainer
class SavePlot(Plot, ChacoSaveMixin):
pass
class SaveHPlotContainer(HPlotContainer, ChacoSaveMixin):
pass
# Major library imports
import os.path
# Enthought library imports
from enable.api import BaseTool
from utility import save_file
class SaveTool(BaseTool):
"""
This tool allows the user to press Ctrl+S to save a snapshot image of
the plot component.
"""
#-------------------------------------------------------------------------
# Override default trait values inherited from BaseTool
#-------------------------------------------------------------------------
# This tool does not have a visual representation (overrides BaseTool).
draw_mode = "none"
# This tool is not visible (overrides BaseTool).
visible = False
def normal_key_pressed(self, event):
""" Handles a key-press when the tool is in the 'normal' state.
Saves an image of the plot if the keys pressed are Control and S.
"""
if self.component is None:
return
if event.character == "s" and event.control_down:
filename = save_file(title='Save plot as png or pdf.')
if filename:
self.component.save(filename)
event.handled = True
return
from chaco.tools.simple_zoom import SimpleZoom
class AspectZoomTool(SimpleZoom):
box = Tuple()
def _do_zoom(self):
""" Does the zoom operation.
"""
# Sets the bounds on the component using _cur_stack_index
low, high = self._current_state()
orig_low, orig_high = self._history[0]
if self._history_index == 0:
if self.tool_mode == "range":
mapper = self._get_mapper()
mapper.range.low_setting = self._orig_low_setting
mapper.range.high_setting = self._orig_high_setting
else:
x_range = self.component.x_mapper.range
y_range = self.component.y_mapper.range
x_range.low_setting, y_range.low_setting = \
self._orig_low_setting
x_range.high_setting, y_range.high_setting = \
self._orig_high_setting
# resetting the ranges will allow 'auto' to pick the values
x_range.reset()
y_range.reset()
else:
if self.tool_mode == "range":
mapper = self._get_mapper()
if self._zoom_limit_reached(orig_low, orig_high, low, high, mapper):
self._pop_state()
return
mapper.range.low = low
mapper.range.high = high
else:
for ndx in (0, 1):
mapper = (self.component.x_mapper, self.component.y_mapper)[ndx]
if self._zoom_limit_reached(orig_low[ndx], orig_high[ndx],
low[ndx], high[ndx], mapper):
# pop _current_state off the stack and leave the actual
# bounds unmodified.
self._pop_state()
return
x_range = self.component.x_mapper.range
y_range = self.component.y_mapper.range
x_range.low, y_range.low = low
x_range.high, y_range.high = high
plot = self.component.container
plot.aspect_ratio = (x_range.high - x_range.low) / (y_range.high - y_range.low)
self.box=(low[0],low[1],high[0],high[1])
self.component.request_redraw()
return
| Python |
"""
pi3diamond example startup script
Please do not modify this file. Instead copy it to a new file -
e.g. named pi3diamond.py - that is not tracked in the repository
and modify it according to your needs.
"""
import logging, logging.handlers
import os
import inspect
path = os.path.dirname(inspect.getfile(inspect.currentframe()))
# First thing we do is start the logger
file_handler = logging.handlers.TimedRotatingFileHandler(path+'/log/diamond_log.txt', 'W6') # start new file every sunday, keeping all the old ones
file_handler.setFormatter(logging.Formatter("%(asctime)s - %(module)s.%(funcName)s - %(levelname)s - %(message)s"))
file_handler.setLevel(logging.DEBUG)
stream_handler=logging.StreamHandler()
stream_handler.setLevel(logging.INFO) # we don't want the console to be swamped with debug messages
logging.getLogger().addHandler(file_handler)
logging.getLogger().addHandler(stream_handler) # also log to stderr
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().info('Starting logger.')
# start the JobManager
from tools import emod
emod.JobManager().start()
# start the CronDaemon
from tools import cron
cron.CronDaemon().start()
# define a shutdown function
from tools.utility import StoppableThread
import threading
def shutdown(timeout=1.0):
"""Terminate all threads."""
cron.CronDaemon().stop()
emod.JobManager().stop()
for t in threading.enumerate():
if isinstance(t, StoppableThread):
t.stop(timeout=timeout)
# numerical classes that are used everywhere
import numpy as np
#########################################
# hardware
#########################################
import hardware.pulse_generator
import hardware.TimeTagger as time_tagger
import hardware.microwave_sources
import hardware.nidaq
import hardware.laser
import hardware.hameg
import hardware.flip_mirror
import hardware.apt_stage
import hardware.power_meter
# create hardware backends
scanner = hardware.nidaq.Scanner(CounterIn='/Dev1/Ctr2',
CounterOut='/Dev1/Ctr3',
TickSource='/Dev1/PFI0',
AOChannels='/Dev1/ao0:2',
TriggerChannels='/Dev1/port0/line0:1',
x_range=(0.,100.),
y_range=(0.,100.),
z_range=(-10.,10.),
)
odmr_counter = hardware.nidaq.PulseTrainCounter(CounterIn='/Dev1/Ctr1',
CounterOut='/Dev1/Ctr0',
TickSource='/Dev1/PFI0'
)
pulse_generator = hardware.pulse_generator.PulseGenerator(serial='XpoJYaysTt', channel_map={'aom':0, 'detect':1, 'sequence':2, 'microwave':3, 'rf':4,})
microwave = hardware.microwave_sources.SMIQ(visa_address='GPIB0::28')
#microwave_1 = microwave
rf_source = hardware.microwave_sources.SMIQ(visa_address='GPIB0::30')
laser = hardware.laser.Laser(voltage_range=(-10.,+10), voltage=-4)
coil = hardware.hameg.HMP2030Traits('ASRL11::INSTR', voltage_max=24.0, current_max=0.15)
flip_mirror = hardware.flip_mirror.FlipMirror('/Dev1/port2/line5')
rotation_stage = hardware.apt_stage.RotationStageTraits(serial='83838311')
#power_meter = hardware.power_meter.PM100D()
#########################################
# configure hardware
#########################################
pulse_generator.Light()
#########################################
# create measurements
#########################################
import measurements.confocal
import measurements.auto_focus_dim
import measurements.photon_time_trace
import measurements.odmr
import measurements.autocorrelation
import measurements.polarization
import measurements.rabi
import analysis.pulsed
confocal = measurements.confocal.Confocal(scanner)
auto_focus = measurements.auto_focus.AutoFocus(confocal)
time_trace = measurements.photon_time_trace.PhotonTimeTrace(time_tagger)
odmr = measurements.odmr.ODMR(microwave, odmr_counter, pulse_generator)
autocorrelation = measurements.autocorrelation.Autocorrelation(time_tagger)
polarization = measurements.polarization.Polarization(time_tagger, rotation_stage)
rabi_measurement = measurements.rabi.Rabi(pulse_generator,time_tagger,microwave)
pulsed_tool_tau = analysis.pulsed.PulsedToolTau(measurement=rabi_measurement)
try:
auto_focus.load('defaults/auto_focus.pys')
except:
pass
#########################################
# fire up the GUI
#########################################
# define a panel for laser and mirror hardware controls
from traits.api import HasTraits, Instance
from traitsui.api import View, Item, Group
class HardwarePanel( HasTraits ):
laser = Instance( hardware.laser.Laser )
mirror = Instance( hardware.flip_mirror.FlipMirror )
stage = Instance( hardware.apt_stage.RotationStageTraits )
coil = Instance( hardware.hameg.HMP2030Traits )
traits_view = View(Group(Item('laser', style='custom', show_label=False),
Item('mirror', style='custom', show_label=False),
Item('stage', style='custom', show_label=False),
Item('coil', style='custom', show_label=False),
),
title='Hardware Panel'
)
hardware_panel = HardwarePanel(laser=laser, mirror=flip_mirror, stage=rotation_stage, coil=coil)
hardware_panel.edit_traits()
confocal.edit_traits()
time_trace.edit_traits()
auto_focus.edit_traits()
odmr.edit_traits()
autocorrelation.edit_traits()
polarization.edit_traits()
pulsed_tool_tau.edit_traits()
| Python |
#!/usr/bin/env python
#**** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is PyShell code.
#
# The Initial Developer of the Original Code is Todd Whiteman.
# Portions created by the Initial Developer are Copyright (C) 2007-2008.
# All Rights Reserved.
#
# Contributor(s):
# Todd Whiteman
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
#**** END LICENSE BLOCK *****
#
# Overview:
# Provides Python evaluation and completions for the PyShell UI.
#
import os
import sys
import time
import traceback
from cStringIO import StringIO
from xpcom import components, ServerException, nsError
from xpcom.server import WrapObject
class pyShell:
_com_interfaces_ = [components.interfaces.pyIShell]
_reg_clsid_ = "{4e5c9764-d465-4fef-ae24-8032f257d174}"
_reg_contractid_ = "@twhiteman.netfirms.com/pyShell;1"
_reg_desc_ = "Python shell service"
pyshellGlobals = {
# Give away some free items...
"os": os,
"sys": sys,
"time": time,
# And xpcom accessors.
"components": components,
"Components": components
}
def __init__(self):
pass
def _eval_code_and_return_result(self, code):
return eval(code, self.pyshellGlobals, self.pyshellGlobals)
# This little exec snippet comes from the python mailing list, see:
# http://mail.python.org/pipermail/python-list/2005-June/328628.html
def _exec_code_and_get_output(self, code):
old_stdout = sys.stdout
sys.stdout = StringIO()
try:
exec code in self.pyshellGlobals, self.pyshellGlobals
return sys.stdout.getvalue()
finally:
sys.stdout = old_stdout
def evalPythonString(self, code):
# Ensure the code ends with an empty newline
code += '\n\n'
try:
try:
result = self._eval_code_and_return_result(code)
try:
# See if the result can be turned into an xpcom object
return WrapObject(result, components.interfaces.nsIVariant)
except ValueError:
# else, we'll just return a string representation
return repr(result)
except SyntaxError:
return self._exec_code_and_get_output(code)
except Exception, e:
# Format the exception, removing the exec/eval sections.
exc_tb = traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)
return "".join(exc_tb[:1] + exc_tb[3:])
def getCompletionsForName(self, objname, prefix):
#print "getCompletionsForName:: obname: %r, prefix: %r" % (objname, prefix, )
# Global scope.
if not objname:
cplns = self.pyshellGlobals.keys()
# Hack for nice xpcom completions.
elif objname.lower() == "components.interfaces":
cplns = components.interfaces.keys()
elif objname.lower() == "components.classes":
cplns = components.classes.keys()
# Object scope.
else:
foundObject = None
names = objname.split(".")
foundObject = self.pyshellGlobals[names[0]]
for name in names[1:]:
foundObject = getattr(foundObject, name)
# Got the object, now return the matches
cplns = dir(foundObject)
if prefix:
cplns = [x for x in cplns if x.startswith(prefix)]
return cplns
# The static list of PyXPCOM classes in this module:
PYXPCOM_CLASSES = [
pyShell,
]
| Python |
#!/usr/bin/env python
#**** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is pyxpcomext.mozdev.org code.
#
# The Initial Developer of the Original Code is Todd Whiteman.
# Portions created by the Initial Developer are Copyright (C) 2007-2008.
# All Rights Reserved.
#
# Contributor(s):
# Todd Whiteman
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
#**** END LICENSE BLOCK *****
import sys
import socket
import struct
import time
import threading
from xpcom import components, ServerException, nsError
from xpcom._xpcom import getProxyForObject
try:
# Mozilla 1.9
from xpcom._xpcom import NS_PROXY_SYNC, NS_PROXY_ALWAYS, NS_PROXY_ASYNC
except ImportError:
# Mozilla 1.8 used different naming for these items.
from xpcom._xpcom import PROXY_SYNC as NS_PROXY_ASYNC
from xpcom._xpcom import PROXY_ALWAYS as NS_PROXY_ALWAYS
from xpcom._xpcom import PROXY_ASYNC as NS_PROXY_ASYNC
##
# This is a simple UDP time protocol request class.
# This time code is based on the ASPN Python setclock code found here:
# http://www.nightsong.com/phr/python/setclock.py
#
#class pyNTPRequest(threading.Thread):
class pyNTPRequest:
# XPCOM registration attributes.
_com_interfaces_ = [components.interfaces.pyINTPRequest]
_reg_clsid_ = "{c37c49ee-6f82-48cf-b8bf-f7e3fc34a5c5}"
_reg_contractid_ = "@twhiteman.netfirms.com/pyNTPRequest;1"
_reg_desc_ = "Python NTP time request"
# time.apple.com is a stratum 2 time server. (123 is the SNTP port number).
# More servers info can be found at:
# http://www.eecis.udel.edu/~mills/ntp/servers.htm
time_server = ('time.apple.com', 123)
TIME1970 = 2208988800L # Thanks to F.Lundh
def __init__(self):
#threading.Thread.__init__(self, name="NTP request handler")
# setDaemon ensures the main thread will exit without having
# to wait for this thread to die first, it just exits.
#self.setDaemon(True)
self._listener = None
def asyncOpen(self, aListener):
# We need to have a pyINTPRequestListener to send data notifications to.
assert(aListener is not None)
self._listener = aListener
# Kick off the listening/processing in a thread (calls run() method).
#self.start()
t = threading.Thread(name="NTP request handler",
target=self.runAsync)
t.setDaemon(True)
t.start()
def runAsync(self):
# Important!!
# Setup the data notification proxy. As we are running in the thread's
# context, we *must* use a proxy when notifying the listener, otherwise
# we end up trying to run the listener code in our thread's context
# which will cause major problems and likely crash!
listenerProxy = getProxyForObject(1, components.interfaces.pyINTPRequestListener,
self._listener, NS_PROXY_SYNC | NS_PROXY_ALWAYS)
listenerProxy.onStartRequest(None)
# The sleep call is here just so the user has a chance to see the
# listenerProxy notification updates.
time.sleep(1)
s = None
context = None
status = nsError.NS_OK
try:
# Setup the UDP socket and connect to the timeserver host.
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = '\x1b' + 47 * '\0'
s.sendto(data, self.time_server)
data, address = s.recvfrom( 1024 )
if data:
t = struct.unpack( '!12I', data )[10]
if t == 0:
timedata = "Error processing time result."
else:
timedata = time.ctime(t - self.TIME1970)
# Turn the addr (str, num) into a list of strings.
context = map(str, address)
listenerProxy.onDataAvailable(context, timedata)
context = None
# The sleep call is here just so the user has a chance to see the
# listenerProxy notification updates.
time.sleep(2)
except Exception, ex:
context = str(ex)
status = nsError.NS_ERROR_FAILURE
finally:
if s is not None:
s.close()
listenerProxy.onStopRequest(context, status)
self._listener = None
# The static list of PyXPCOM classes in this module:
PYXPCOM_CLASSES = [
pyNTPRequest,
]
| Python |
#!/usr/bin/python
#
# Copyright (C) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'afshar@google.com (Ali Afshar)'
import os
import httplib2
import sessions
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from apiclient.discovery import build_from_document
from apiclient.http import MediaUpload
from oauth2client import client
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.appengine import simplejson as json
APIS_BASE = 'https://www.googleapis.com'
ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file '
'https://www.googleapis.com/auth/userinfo.email '
'https://www.googleapis.com/auth/userinfo.profile')
CODE_PARAMETER = 'code'
STATE_PARAMETER = 'state'
SESSION_SECRET = open('session.secret').read()
DRIVE_DISCOVERY_DOC = open('drive.json').read()
USERS_DISCOVERY_DOC = open('users.json').read()
class Credentials(db.Model):
"""Datastore entity for storing OAuth2.0 credentials."""
credentials = CredentialsProperty()
def CreateOAuthFlow(request):
"""Create OAuth2.0 flow controller
Args:
request: HTTP request to create OAuth2.0 flow for
Returns:
OAuth2.0 Flow instance suitable for performing OAuth2.0.
"""
flow = client.flow_from_clientsecrets('client-debug.json', scope='')
flow.redirect_uri = request.url.split('?', 1)[0].rstrip('/')
return flow
def GetCodeCredentials(request):
"""Create OAuth2.0 credentials by extracting a code and performing OAuth2.0.
Args:
request: HTTP request used for extracting an authorization code.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
code = request.get(CODE_PARAMETER)
if code:
oauth_flow = CreateOAuthFlow(request)
creds = oauth_flow.step2_exchange(code)
users_service = CreateService(USERS_DISCOVERY_DOC, creds)
userid = users_service.userinfo().get().execute().get('id')
request.session.set_secure_cookie(name='userid', value=userid)
StorageByKeyName(Credentials, userid, 'credentials').put(creds)
return creds
def GetSessionCredentials(request):
"""Get OAuth2.0 credentials for an HTTP session.
Args:
request: HTTP request to use session from.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
userid = request.session.get_secure_cookie(name='userid')
if userid:
creds = StorageByKeyName(Credentials, userid, 'credentials').get()
if creds and not creds.invalid:
return creds
def CreateService(discovery_doc, creds):
"""Create a Google API service.
Args:
discovery_doc: Discovery doc used to configure service.
creds: Credentials used to authorize service.
Returns:
Authorized Google API service.
"""
http = httplib2.Http()
creds.authorize(http)
return build_from_document(discovery_doc, APIS_BASE, http=http)
def RedirectAuth(handler):
"""Redirect a handler to an authorization page.
Args:
handler: webapp.RequestHandler to redirect.
"""
flow = CreateOAuthFlow(handler.request)
flow.scope = ALL_SCOPES
uri = flow.step1_get_authorize_url(flow.redirect_uri)
handler.redirect(uri)
def CreateDrive(handler):
"""Create a fully authorized drive service for this handler.
Args:
handler: RequestHandler from which drive service is generated.
Returns:
Authorized drive service, generated from the handler request.
"""
request = handler.request
request.session = sessions.LilCookies(handler, SESSION_SECRET)
creds = GetCodeCredentials(request) or GetSessionCredentials(request)
if creds:
return CreateService(DRIVE_DISCOVERY_DOC, creds)
else:
RedirectAuth(handler)
def ServiceEnabled(view):
"""Decorator to inject an authorized service into an HTTP handler.
Args:
view: HTTP request handler method.
Returns:
Decorated handler which accepts the service as a parameter.
"""
def ServiceDecoratedView(handler, view=view):
service = CreateDrive(handler)
response_data = view(handler, service)
handler.response.headers['Content-Type'] = 'text/html'
handler.response.out.write(response_data)
return ServiceDecoratedView
def ServiceEnabledJson(view):
"""Decorator to inject an authorized service into a JSON HTTP handler.
Args:
view: HTTP request handler method.
Returns:
Decorated handler which accepts the service as a parameter.
"""
def ServiceDecoratedView(handler, view=view):
service = CreateDrive(handler)
if handler.request.body:
data = json.loads(handler.request.body)
else:
data = None
response_data = json.dumps(view(handler, service, data))
handler.response.headers['Content-Type'] = 'application/json'
handler.response.out.write(response_data)
return ServiceDecoratedView
class DriveState(object):
"""Store state provided by Drive."""
def __init__(self, state):
self.ParseState(state)
@classmethod
def FromRequest(cls, request):
"""Create a Drive State instance from an HTTP request.
Args:
cls: Type this class method is called against.
request: HTTP request.
"""
return DriveState(request.get(STATE_PARAMETER))
def ParseState(self, state):
"""Parse a state parameter and set internal values.
Args:
state: State parameter to parse.
"""
if state.startswith('{'):
self.ParseJsonState(state)
else:
self.ParsePlainState(state)
def ParseJsonState(self, state):
"""Parse a state parameter that is JSON.
Args:
state: State parameter to parse
"""
state_data = json.loads(state)
self.action = state_data['action']
self.ids = map(str, state_data.get('ids', []))
def ParsePlainState(self, state):
"""Parse a state parameter that is a plain resource id or missing.
Args:
state: State parameter to parse
"""
if state:
self.action = 'open'
self.ids = [state]
else:
self.action = 'create'
self.ids = []
class MediaInMemoryUpload(MediaUpload):
"""MediaUpload for a chunk of bytes.
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed plain text:
"""
def __init__(self, body, mimetype='application/octet-stream',
chunksize=256*1024, resumable=False):
"""Create a new MediaBytesUpload.
Args:
body: string, Bytes of body content.
mimetype: string, Mime-type of the file or default of
'application/octet-stream'.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._body = body
self._mimetype = mimetype
self._resumable = resumable
self._chunksize = chunksize
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body.
"""
return len(self._body)
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
return self._body[begin:begin + length]
def RenderTemplate(name, **context):
"""Render a named template in a context.
Args:
name: Template name.
context: Keyword arguments to render as template variables.
"""
return template.render(name, context)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'afshar@google.com (Ali Afshar)'
# Add the library location to the path
import sys
sys.path.insert(0, 'lib')
import os
import httplib2
import sessions
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from apiclient.discovery import build
from apiclient.http import MediaUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from oauth2client.client import AccessTokenRefreshError
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.appengine import simplejson as json
ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file '
'https://www.googleapis.com/auth/userinfo.email '
'https://www.googleapis.com/auth/userinfo.profile')
def SibPath(name):
"""Generate a path that is a sibling of this file.
Args:
name: Name of sibling file.
Returns:
Path to sibling file.
"""
return os.path.join(os.path.dirname(__file__), name)
# Load the secret that is used for client side sessions
# Create one of these for yourself with, for example:
# python -c "import os; print os.urandom(64)" > session-secret
SESSION_SECRET = open(SibPath('session.secret')).read()
INDEX_HTML = open(SibPath('index.html')).read()
class Credentials(db.Model):
"""Datastore entity for storing OAuth2.0 credentials.
The CredentialsProperty is provided by the Google API Python Client, and is
used by the Storage classes to store OAuth 2.0 credentials in the data store."""
credentials = CredentialsProperty()
def CreateService(service, version, creds):
"""Create a Google API service.
Load an API service from a discovery document and authorize it with the
provided credentials.
Args:
service: Service name (e.g 'drive', 'oauth2').
version: Service version (e.g 'v1').
creds: Credentials used to authorize service.
Returns:
Authorized Google API service.
"""
# Instantiate an Http instance
http = httplib2.Http()
# Authorize the Http instance with the passed credentials
creds.authorize(http)
# Build a service from the passed discovery document path
return build(service, version, http=http)
class DriveState(object):
"""Store state provided by Drive."""
def __init__(self, state):
"""Create a new instance of drive state.
Parse and load the JSON state parameter.
Args:
state: State query parameter as a string.
"""
if state:
state_data = json.loads(state)
self.action = state_data['action']
self.ids = map(str, state_data.get('ids', []))
else:
self.action = 'create'
self.ids = []
@classmethod
def FromRequest(cls, request):
"""Create a Drive State instance from an HTTP request.
Args:
cls: Type this class method is called against.
request: HTTP request.
"""
return DriveState(request.get('state'))
class BaseDriveHandler(webapp.RequestHandler):
"""Base request handler for drive applications.
Adds Authorization support for Drive.
"""
def CreateOAuthFlow(self):
"""Create OAuth2.0 flow controller
This controller can be used to perform all parts of the OAuth 2.0 dance
including exchanging an Authorization code.
Args:
request: HTTP request to create OAuth2.0 flow for
Returns:
OAuth2.0 Flow instance suitable for performing OAuth2.0.
"""
flow = flow_from_clientsecrets('client_secrets.json', scope='')
# Dynamically set the redirect_uri based on the request URL. This is extremely
# convenient for debugging to an alternative host without manually setting the
# redirect URI.
flow.redirect_uri = self.request.url.split('?', 1)[0].rsplit('/', 1)[0]
return flow
def GetCodeCredentials(self):
"""Create OAuth 2.0 credentials by extracting a code and performing OAuth2.0.
The authorization code is extracted form the URI parameters. If it is absent,
None is returned immediately. Otherwise, if it is present, it is used to
perform step 2 of the OAuth 2.0 web server flow.
Once a token is received, the user information is fetched from the userinfo
service and stored in the session. The token is saved in the datastore against
the user ID received from the userinfo service.
Args:
request: HTTP request used for extracting an authorization code and the
session information.
Returns:
OAuth2.0 credentials suitable for authorizing clients or None if
Authorization could not take place.
"""
# Other frameworks use different API to get a query parameter.
code = self.request.get('code')
if not code:
# returns None to indicate that no code was passed from Google Drive.
return None
# Auth flow is a controller that is loaded with the client information,
# including client_id, client_secret, redirect_uri etc
oauth_flow = self.CreateOAuthFlow()
# Perform the exchange of the code. If there is a failure with exchanging
# the code, return None.
try:
creds = oauth_flow.step2_exchange(code)
except FlowExchangeError:
return None
# Create an API service that can use the userinfo API. Authorize it with our
# credentials that we gained from the code exchange.
users_service = CreateService('oauth2', 'v2', creds)
# Make a call against the userinfo service to retrieve the user's information.
# In this case we are interested in the user's "id" field.
userid = users_service.userinfo().get().execute().get('id')
# Store the user id in the user's cookie-based session.
session = sessions.LilCookies(self, SESSION_SECRET)
session.set_secure_cookie(name='userid', value=userid)
# Store the credentials in the data store using the userid as the key.
StorageByKeyName(Credentials, userid, 'credentials').put(creds)
return creds
def GetSessionCredentials(self):
"""Get OAuth 2.0 credentials for an HTTP session.
If the user has a user id stored in their cookie session, extract that value
and use it to load that user's credentials from the data store.
Args:
request: HTTP request to use session from.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
# Try to load the user id from the session
session = sessions.LilCookies(self, SESSION_SECRET)
userid = session.get_secure_cookie(name='userid')
if not userid:
# return None to indicate that no credentials could be loaded from the
# session.
return None
# Load the credentials from the data store, using the userid as a key.
creds = StorageByKeyName(Credentials, userid, 'credentials').get()
# if the credentials are invalid, return None to indicate that the credentials
# cannot be used.
if creds and creds.invalid:
return None
return creds
def RedirectAuth(self):
"""Redirect a handler to an authorization page.
Used when a handler fails to fetch credentials suitable for making Drive API
requests. The request is redirected to an OAuth 2.0 authorization approval
page and on approval, are returned to application.
Args:
handler: webapp.RequestHandler to redirect.
"""
flow = self.CreateOAuthFlow()
# Manually add the required scopes. Since this redirect does not originate
# from the Google Drive UI, which authomatically sets the scopes that are
# listed in the API Console.
flow.scope = ALL_SCOPES
# Create the redirect URI by performing step 1 of the OAuth 2.0 web server
# flow.
uri = flow.step1_get_authorize_url(flow.redirect_uri)
# Perform the redirect.
self.redirect(uri)
def RespondJSON(self, data):
"""Generate a JSON response and return it to the client.
Args:
data: The data that will be converted to JSON to return.
"""
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(data))
def CreateAuthorizedService(self, service, version):
"""Create an authorize service instance.
The service can only ever retrieve the credentials from the session.
Args:
service: Service name (e.g 'drive', 'oauth2').
version: Service version (e.g 'v1').
Returns:
Authorized service or redirect to authorization flow if no credentials.
"""
# For the service, the session holds the credentials
creds = self.GetSessionCredentials()
if creds:
# If the session contains credentials, use them to create a Drive service
# instance.
return CreateService(service, version, creds)
else:
# If no credentials could be loaded from the session, redirect the user to
# the authorization page.
self.RedirectAuth()
def CreateDrive(self):
"""Create a drive client instance."""
return self.CreateAuthorizedService('drive', 'v2')
def CreateUserInfo(self):
"""Create a user info client instance."""
return self.CreateAuthorizedService('oauth2', 'v2')
class MainPage(BaseDriveHandler):
"""Web handler for the main page.
Handles requests and returns the user interface for Open With and Create
cases. Responsible for parsing the state provided from the Drive UI and acting
appropriately.
"""
def get(self):
"""Handle GET for Create New and Open With.
This creates an authorized client, and checks whether a resource id has
been passed or not. If a resource ID has been passed, this is the Open
With use-case, otherwise it is the Create New use-case.
"""
# Generate a state instance for the request, this includes the action, and
# the file id(s) that have been sent from the Drive user interface.
drive_state = DriveState.FromRequest(self.request)
if drive_state.action == 'open' and len(drive_state.ids) > 0:
code = self.request.get('code')
if code:
code = '?code=%s' % code
self.redirect('/#edit/%s%s' % (drive_state.ids[0], code))
return
# Fetch the credentials by extracting an OAuth 2.0 authorization code from
# the request URL. If the code is not present, redirect to the OAuth 2.0
# authorization URL.
creds = self.GetCodeCredentials()
if not creds:
return self.RedirectAuth()
# Extract the numerical portion of the client_id from the stored value in
# the OAuth flow. You could also store this value as a separate variable
# somewhere.
client_id = self.CreateOAuthFlow().client_id.split('.')[0].split('-')[0]
self.RenderTemplate()
def RenderTemplate(self):
"""Render a named template in a context."""
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write(INDEX_HTML)
class ServiceHandler(BaseDriveHandler):
"""Web handler for the service to read and write to Drive."""
def post(self):
"""Called when HTTP POST requests are received by the web application.
The POST body is JSON which is deserialized and used as values to create a
new file in Drive. The authorization access token for this action is
retreived from the data store.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
# Load the data that has been posted as JSON
data = self.RequestJSON()
# Create a new file data structure.
resource = {
'title': data['title'],
'description': data['description'],
'mimeType': data['mimeType'],
}
try:
# Make an insert request to create a new file. A MediaInMemoryUpload
# instance is used to upload the file body.
resource = service.files().insert(
body=resource,
media_body=MediaInMemoryUpload(
data.get('content', ''),
data['mimeType'],
resumable=True)
).execute()
# Respond with the new file id as JSON.
self.RespondJSON(resource['id'])
except AccessTokenRefreshError:
# In cases where the access token has expired and cannot be refreshed
# (e.g. manual token revoking) redirect the user to the authorization page
# to authorize.
self.RedirectAuth()
def get(self):
"""Called when HTTP GET requests are received by the web application.
Use the query parameter file_id to fetch the required file's metadata then
content and return it as a JSON object.
Since DrEdit deals with text files, it is safe to dump the content directly
into JSON, but this is not the case with binary files, where something like
Base64 encoding is more appropriate.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
try:
# Requests are expected to pass the file_id query parameter.
file_id = self.request.get('file_id')
if file_id:
# Fetch the file metadata by making the service.files().get method of
# the Drive API.
f = service.files().get(fileId=file_id).execute()
downloadUrl = f.get('downloadUrl')
# If a download URL is provided in the file metadata, use it to make an
# authorized request to fetch the file ontent. Set this content in the
# data to return as the 'content' field. If there is no downloadUrl,
# just set empty content.
if downloadUrl:
resp, f['content'] = service._http.request(downloadUrl)
else:
f['content'] = ''
else:
f = None
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(f)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
def put(self):
"""Called when HTTP PUT requests are received by the web application.
The PUT body is JSON which is deserialized and used as values to update
a file in Drive. The authorization access token for this action is
retreived from the data store.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
# Load the data that has been posted as JSON
data = self.RequestJSON()
try:
# Create a new file data structure.
content = data.get('content')
if 'content' in data:
data.pop('content')
if content is not None:
# Make an update request to update the file. A MediaInMemoryUpload
# instance is used to upload the file body. Because of a limitation, this
# request must be made in two parts, the first to update the metadata, and
# the second to update the body.
resource = service.files().update(
fileId=data['resource_id'],
newRevision=self.request.get('newRevision', False),
body=data,
media_body=MediaInMemoryUpload(
content, data['mimeType'], resumable=True)
).execute()
else:
# Only update the metadata, a patch request is prefered but not yet
# supported on Google App Engine; see
# http://code.google.com/p/googleappengine/issues/detail?id=6316.
resource = service.files().update(
fileId=data['resource_id'],
newRevision=self.request.get('newRevision', False),
body=data).execute()
# Respond with the new file id as JSON.
self.RespondJSON(resource['id'])
except AccessTokenRefreshError:
# In cases where the access token has expired and cannot be refreshed
# (e.g. manual token revoking) redirect the user to the authorization page
# to authorize.
self.RedirectAuth()
def RequestJSON(self):
"""Load the request body as JSON.
Returns:
Request body loaded as JSON or None if there is no request body.
"""
if self.request.body:
return json.loads(self.request.body)
class UserHandler(BaseDriveHandler):
"""Web handler for the service to read user information."""
def get(self):
"""Called when HTTP GET requests are received by the web application."""
# Create a Drive service
service = self.CreateUserInfo()
if service is None:
return
try:
result = service.userinfo().get().execute()
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(result)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
class AboutHandler(BaseDriveHandler):
"""Web handler for the service to read user information."""
def get(self):
"""Called when HTTP GET requests are received by the web application."""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
try:
result = service.about().get().execute()
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(result)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
class MediaInMemoryUpload(MediaUpload):
"""MediaUpload for a chunk of bytes.
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed plain text:
"""
def __init__(self, body, mimetype='application/octet-stream',
chunksize=256*1024, resumable=False):
"""Create a new MediaBytesUpload.
Args:
body: string, Bytes of body content.
mimetype: string, Mime-type of the file or default of
'application/octet-stream'.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._body = body
self._mimetype = mimetype
self._resumable = resumable
self._chunksize = chunksize
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body.
"""
return len(self._body)
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
return self._body[begin:begin + length]
# Create an WSGI application suitable for running on App Engine
application = webapp.WSGIApplication(
[('/', MainPage), ('/svc', ServiceHandler), ('/about', AboutHandler),
('/user', UserHandler)],
# XXX Set to False in production.
debug=True
)
def main():
"""Main entry point for executing a request with this handler."""
run_wsgi_app(application)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
#
# Copyright (c) 2002, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ---
# Author: Chad Lester
# Design and style contributions by:
# Amit Patel, Bogdan Cocosel, Daniel Dulitz, Eric Tiedemann,
# Eric Veach, Laurence Gonsalves, Matthew Springer
# Code reorganized a bit by Craig Silverstein
"""This module is used to define and parse command line flags.
This module defines a *distributed* flag-definition policy: rather than
an application having to define all flags in or near main(), each python
module defines flags that are useful to it. When one python module
imports another, it gains access to the other's flags. (This is
implemented by having all modules share a common, global registry object
containing all the flag information.)
Flags are defined through the use of one of the DEFINE_xxx functions.
The specific function used determines how the flag is parsed, checked,
and optionally type-converted, when it's seen on the command line.
IMPLEMENTATION: DEFINE_* creates a 'Flag' object and registers it with a
'FlagValues' object (typically the global FlagValues FLAGS, defined
here). The 'FlagValues' object can scan the command line arguments and
pass flag arguments to the corresponding 'Flag' objects for
value-checking and type conversion. The converted flag values are
available as attributes of the 'FlagValues' object.
Code can access the flag through a FlagValues object, for instance
gflags.FLAGS.myflag. Typically, the __main__ module passes the command
line arguments to gflags.FLAGS for parsing.
At bottom, this module calls getopt(), so getopt functionality is
supported, including short- and long-style flags, and the use of -- to
terminate flags.
Methods defined by the flag module will throw 'FlagsError' exceptions.
The exception argument will be a human-readable string.
FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags
take a name, default value, help-string, and optional 'short' name
(one-letter name). Some flags have other arguments, which are described
with the flag.
DEFINE_string: takes any input, and interprets it as a string.
DEFINE_bool or
DEFINE_boolean: typically does not take an argument: say --myflag to
set FLAGS.myflag to true, or --nomyflag to set
FLAGS.myflag to false. Alternately, you can say
--myflag=true or --myflag=t or --myflag=1 or
--myflag=false or --myflag=f or --myflag=0
DEFINE_float: takes an input and interprets it as a floating point
number. Takes optional args lower_bound and upper_bound;
if the number specified on the command line is out of
range, it will raise a FlagError.
DEFINE_integer: takes an input and interprets it as an integer. Takes
optional args lower_bound and upper_bound as for floats.
DEFINE_enum: takes a list of strings which represents legal values. If
the command-line value is not in this list, raise a flag
error. Otherwise, assign to FLAGS.flag as a string.
DEFINE_list: Takes a comma-separated list of strings on the commandline.
Stores them in a python list object.
DEFINE_spaceseplist: Takes a space-separated list of strings on the
commandline. Stores them in a python list object.
Example: --myspacesepflag "foo bar baz"
DEFINE_multistring: The same as DEFINE_string, except the flag can be
specified more than once on the commandline. The
result is a python list object (list of strings),
even if the flag is only on the command line once.
DEFINE_multi_int: The same as DEFINE_integer, except the flag can be
specified more than once on the commandline. The
result is a python list object (list of ints), even if
the flag is only on the command line once.
SPECIAL FLAGS: There are a few flags that have special meaning:
--help prints a list of all the flags in a human-readable fashion
--helpshort prints a list of all key flags (see below).
--helpxml prints a list of all flags, in XML format. DO NOT parse
the output of --help and --helpshort. Instead, parse
the output of --helpxml. For more info, see
"OUTPUT FOR --helpxml" below.
--flagfile=foo read flags from file foo.
--undefok=f1,f2 ignore unrecognized option errors for f1,f2.
For boolean flags, you should use --undefok=boolflag, and
--boolflag and --noboolflag will be accepted. Do not use
--undefok=noboolflag.
-- as in getopt(), terminates flag-processing
FLAGS VALIDATORS: If your program:
- requires flag X to be specified
- needs flag Y to match a regular expression
- or requires any more general constraint to be satisfied
then validators are for you!
Each validator represents a constraint over one flag, which is enforced
starting from the initial parsing of the flags and until the program
terminates.
Also, lower_bound and upper_bound for numerical flags are enforced using flag
validators.
Howto:
If you want to enforce a constraint over one flag, use
gflags.RegisterValidator(flag_name,
checker,
message='Flag validation failed',
flag_values=FLAGS)
After flag values are initially parsed, and after any change to the specified
flag, method checker(flag_value) will be executed. If constraint is not
satisfied, an IllegalFlagValue exception will be raised. See
RegisterValidator's docstring for a detailed explanation on how to construct
your own checker.
EXAMPLE USAGE:
FLAGS = gflags.FLAGS
gflags.DEFINE_integer('my_version', 0, 'Version number.')
gflags.DEFINE_string('filename', None, 'Input file name', short_name='f')
gflags.RegisterValidator('my_version',
lambda value: value % 2 == 0,
message='--my_version must be divisible by 2')
gflags.MarkFlagAsRequired('filename')
NOTE ON --flagfile:
Flags may be loaded from text files in addition to being specified on
the commandline.
Any flags you don't feel like typing, throw them in a file, one flag per
line, for instance:
--myflag=myvalue
--nomyboolean_flag
You then specify your file with the special flag '--flagfile=somefile'.
You CAN recursively nest flagfile= tokens OR use multiple files on the
command line. Lines beginning with a single hash '#' or a double slash
'//' are comments in your flagfile.
Any flagfile=<file> will be interpreted as having a relative path from
the current working directory rather than from the place the file was
included from:
myPythonScript.py --flagfile=config/somefile.cfg
If somefile.cfg includes further --flagfile= directives, these will be
referenced relative to the original CWD, not from the directory the
including flagfile was found in!
The caveat applies to people who are including a series of nested files
in a different dir than they are executing out of. Relative path names
are always from CWD, not from the directory of the parent include
flagfile. We do now support '~' expanded directory names.
Absolute path names ALWAYS work!
EXAMPLE USAGE:
FLAGS = gflags.FLAGS
# Flag names are globally defined! So in general, we need to be
# careful to pick names that are unlikely to be used by other libraries.
# If there is a conflict, we'll get an error at import time.
gflags.DEFINE_string('name', 'Mr. President', 'your name')
gflags.DEFINE_integer('age', None, 'your age in years', lower_bound=0)
gflags.DEFINE_boolean('debug', False, 'produces debugging output')
gflags.DEFINE_enum('gender', 'male', ['male', 'female'], 'your gender')
def main(argv):
try:
argv = FLAGS(argv) # parse flags
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS)
sys.exit(1)
if FLAGS.debug: print 'non-flag arguments:', argv
print 'Happy Birthday', FLAGS.name
if FLAGS.age is not None:
print 'You are a %d year old %s' % (FLAGS.age, FLAGS.gender)
if __name__ == '__main__':
main(sys.argv)
KEY FLAGS:
As we already explained, each module gains access to all flags defined
by all the other modules it transitively imports. In the case of
non-trivial scripts, this means a lot of flags ... For documentation
purposes, it is good to identify the flags that are key (i.e., really
important) to a module. Clearly, the concept of "key flag" is a
subjective one. When trying to determine whether a flag is key to a
module or not, assume that you are trying to explain your module to a
potential user: which flags would you really like to mention first?
We'll describe shortly how to declare which flags are key to a module.
For the moment, assume we know the set of key flags for each module.
Then, if you use the app.py module, you can use the --helpshort flag to
print only the help for the flags that are key to the main module, in a
human-readable format.
NOTE: If you need to parse the flag help, do NOT use the output of
--help / --helpshort. That output is meant for human consumption, and
may be changed in the future. Instead, use --helpxml; flags that are
key for the main module are marked there with a <key>yes</key> element.
The set of key flags for a module M is composed of:
1. Flags defined by module M by calling a DEFINE_* function.
2. Flags that module M explictly declares as key by using the function
DECLARE_key_flag(<flag_name>)
3. Key flags of other modules that M specifies by using the function
ADOPT_module_key_flags(<other_module>)
This is a "bulk" declaration of key flags: each flag that is key for
<other_module> becomes key for the current module too.
Notice that if you do not use the functions described at points 2 and 3
above, then --helpshort prints information only about the flags defined
by the main module of our script. In many cases, this behavior is good
enough. But if you move part of the main module code (together with the
related flags) into a different module, then it is nice to use
DECLARE_key_flag / ADOPT_module_key_flags and make sure --helpshort
lists all relevant flags (otherwise, your code refactoring may confuse
your users).
Note: each of DECLARE_key_flag / ADOPT_module_key_flags has its own
pluses and minuses: DECLARE_key_flag is more targeted and may lead a
more focused --helpshort documentation. ADOPT_module_key_flags is good
for cases when an entire module is considered key to the current script.
Also, it does not require updates to client scripts when a new flag is
added to the module.
EXAMPLE USAGE 2 (WITH KEY FLAGS):
Consider an application that contains the following three files (two
auxiliary modules and a main module)
File libfoo.py:
import gflags
gflags.DEFINE_integer('num_replicas', 3, 'Number of replicas to start')
gflags.DEFINE_boolean('rpc2', True, 'Turn on the usage of RPC2.')
... some code ...
File libbar.py:
import gflags
gflags.DEFINE_string('bar_gfs_path', '/gfs/path',
'Path to the GFS files for libbar.')
gflags.DEFINE_string('email_for_bar_errors', 'bar-team@google.com',
'Email address for bug reports about module libbar.')
gflags.DEFINE_boolean('bar_risky_hack', False,
'Turn on an experimental and buggy optimization.')
... some code ...
File myscript.py:
import gflags
import libfoo
import libbar
gflags.DEFINE_integer('num_iterations', 0, 'Number of iterations.')
# Declare that all flags that are key for libfoo are
# key for this module too.
gflags.ADOPT_module_key_flags(libfoo)
# Declare that the flag --bar_gfs_path (defined in libbar) is key
# for this module.
gflags.DECLARE_key_flag('bar_gfs_path')
... some code ...
When myscript is invoked with the flag --helpshort, the resulted help
message lists information about all the key flags for myscript:
--num_iterations, --num_replicas, --rpc2, and --bar_gfs_path.
Of course, myscript uses all the flags declared by it (in this case,
just --num_replicas) or by any of the modules it transitively imports
(e.g., the modules libfoo, libbar). E.g., it can access the value of
FLAGS.bar_risky_hack, even if --bar_risky_hack is not declared as a key
flag for myscript.
OUTPUT FOR --helpxml:
The --helpxml flag generates output with the following structure:
<?xml version="1.0"?>
<AllFlags>
<program>PROGRAM_BASENAME</program>
<usage>MAIN_MODULE_DOCSTRING</usage>
(<flag>
[<key>yes</key>]
<file>DECLARING_MODULE</file>
<name>FLAG_NAME</name>
<meaning>FLAG_HELP_MESSAGE</meaning>
<default>DEFAULT_FLAG_VALUE</default>
<current>CURRENT_FLAG_VALUE</current>
<type>FLAG_TYPE</type>
[OPTIONAL_ELEMENTS]
</flag>)*
</AllFlags>
Notes:
1. The output is intentionally similar to the output generated by the
C++ command-line flag library. The few differences are due to the
Python flags that do not have a C++ equivalent (at least not yet),
e.g., DEFINE_list.
2. New XML elements may be added in the future.
3. DEFAULT_FLAG_VALUE is in serialized form, i.e., the string you can
pass for this flag on the command-line. E.g., for a flag defined
using DEFINE_list, this field may be foo,bar, not ['foo', 'bar'].
4. CURRENT_FLAG_VALUE is produced using str(). This means that the
string 'false' will be represented in the same way as the boolean
False. Using repr() would have removed this ambiguity and simplified
parsing, but would have broken the compatibility with the C++
command-line flags.
5. OPTIONAL_ELEMENTS describe elements relevant for certain kinds of
flags: lower_bound, upper_bound (for flags that specify bounds),
enum_value (for enum flags), list_separator (for flags that consist of
a list of values, separated by a special token).
6. We do not provide any example here: please use --helpxml instead.
This module requires at least python 2.2.1 to run.
"""
import cgi
import getopt
import os
import re
import string
import struct
import sys
# pylint: disable-msg=C6204
try:
import fcntl
except ImportError:
fcntl = None
try:
# Importing termios will fail on non-unix platforms.
import termios
except ImportError:
termios = None
import gflags_validators
# pylint: enable-msg=C6204
# Are we running under pychecker?
_RUNNING_PYCHECKER = 'pychecker.python' in sys.modules
def _GetCallingModuleObjectAndName():
"""Returns the module that's calling into this module.
We generally use this function to get the name of the module calling a
DEFINE_foo... function.
"""
# Walk down the stack to find the first globals dict that's not ours.
for depth in range(1, sys.getrecursionlimit()):
if not sys._getframe(depth).f_globals is globals():
globals_for_frame = sys._getframe(depth).f_globals
module, module_name = _GetModuleObjectAndName(globals_for_frame)
if module_name is not None:
return module, module_name
raise AssertionError("No module was found")
def _GetCallingModule():
"""Returns the name of the module that's calling into this module."""
return _GetCallingModuleObjectAndName()[1]
def _GetThisModuleObjectAndName():
"""Returns: (module object, module name) for this module."""
return _GetModuleObjectAndName(globals())
# module exceptions:
class FlagsError(Exception):
"""The base class for all flags errors."""
pass
class DuplicateFlag(FlagsError):
"""Raised if there is a flag naming conflict."""
pass
class CantOpenFlagFileError(FlagsError):
"""Raised if flagfile fails to open: doesn't exist, wrong permissions, etc."""
pass
class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag):
"""Special case of DuplicateFlag -- SWIG flag value can't be set to None.
This can be raised when a duplicate flag is created. Even if allow_override is
True, we still abort if the new value is None, because it's currently
impossible to pass None default value back to SWIG. See FlagValues.SetDefault
for details.
"""
pass
class DuplicateFlagError(DuplicateFlag):
"""A DuplicateFlag whose message cites the conflicting definitions.
A DuplicateFlagError conveys more information than a DuplicateFlag,
namely the modules where the conflicting definitions occur. This
class was created to avoid breaking external modules which depend on
the existing DuplicateFlags interface.
"""
def __init__(self, flagname, flag_values, other_flag_values=None):
"""Create a DuplicateFlagError.
Args:
flagname: Name of the flag being redefined.
flag_values: FlagValues object containing the first definition of
flagname.
other_flag_values: If this argument is not None, it should be the
FlagValues object where the second definition of flagname occurs.
If it is None, we assume that we're being called when attempting
to create the flag a second time, and we use the module calling
this one as the source of the second definition.
"""
self.flagname = flagname
first_module = flag_values.FindModuleDefiningFlag(
flagname, default='<unknown>')
if other_flag_values is None:
second_module = _GetCallingModule()
else:
second_module = other_flag_values.FindModuleDefiningFlag(
flagname, default='<unknown>')
msg = "The flag '%s' is defined twice. First from %s, Second from %s" % (
self.flagname, first_module, second_module)
DuplicateFlag.__init__(self, msg)
class IllegalFlagValue(FlagsError):
"""The flag command line argument is illegal."""
pass
class UnrecognizedFlag(FlagsError):
"""Raised if a flag is unrecognized."""
pass
# An UnrecognizedFlagError conveys more information than an UnrecognizedFlag.
# Since there are external modules that create DuplicateFlags, the interface to
# DuplicateFlag shouldn't change. The flagvalue will be assigned the full value
# of the flag and its argument, if any, allowing handling of unrecognized flags
# in an exception handler.
# If flagvalue is the empty string, then this exception is an due to a
# reference to a flag that was not already defined.
class UnrecognizedFlagError(UnrecognizedFlag):
def __init__(self, flagname, flagvalue=''):
self.flagname = flagname
self.flagvalue = flagvalue
UnrecognizedFlag.__init__(
self, "Unknown command line flag '%s'" % flagname)
# Global variable used by expvar
_exported_flags = {}
_help_width = 80 # width of help output
def GetHelpWidth():
"""Returns: an integer, the width of help lines that is used in TextWrap."""
if (not sys.stdout.isatty()) or (termios is None) or (fcntl is None):
return _help_width
try:
data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')
columns = struct.unpack('hh', data)[1]
# Emacs mode returns 0.
# Here we assume that any value below 40 is unreasonable
if columns >= 40:
return columns
# Returning an int as default is fine, int(int) just return the int.
return int(os.getenv('COLUMNS', _help_width))
except (TypeError, IOError, struct.error):
return _help_width
def CutCommonSpacePrefix(text):
"""Removes a common space prefix from the lines of a multiline text.
If the first line does not start with a space, it is left as it is and
only in the remaining lines a common space prefix is being searched
for. That means the first line will stay untouched. This is especially
useful to turn doc strings into help texts. This is because some
people prefer to have the doc comment start already after the
apostrophe and then align the following lines while others have the
apostrophes on a separate line.
The function also drops trailing empty lines and ignores empty lines
following the initial content line while calculating the initial
common whitespace.
Args:
text: text to work on
Returns:
the resulting text
"""
text_lines = text.splitlines()
# Drop trailing empty lines
while text_lines and not text_lines[-1]:
text_lines = text_lines[:-1]
if text_lines:
# We got some content, is the first line starting with a space?
if text_lines[0] and text_lines[0][0].isspace():
text_first_line = []
else:
text_first_line = [text_lines.pop(0)]
# Calculate length of common leading whitespace (only over content lines)
common_prefix = os.path.commonprefix([line for line in text_lines if line])
space_prefix_len = len(common_prefix) - len(common_prefix.lstrip())
# If we have a common space prefix, drop it from all lines
if space_prefix_len:
for index in xrange(len(text_lines)):
if text_lines[index]:
text_lines[index] = text_lines[index][space_prefix_len:]
return '\n'.join(text_first_line + text_lines)
return ''
def TextWrap(text, length=None, indent='', firstline_indent=None, tabs=' '):
"""Wraps a given text to a maximum line length and returns it.
We turn lines that only contain whitespace into empty lines. We keep
new lines and tabs (e.g., we do not treat tabs as spaces).
Args:
text: text to wrap
length: maximum length of a line, includes indentation
if this is None then use GetHelpWidth()
indent: indent for all but first line
firstline_indent: indent for first line; if None, fall back to indent
tabs: replacement for tabs
Returns:
wrapped text
Raises:
FlagsError: if indent not shorter than length
FlagsError: if firstline_indent not shorter than length
"""
# Get defaults where callee used None
if length is None:
length = GetHelpWidth()
if indent is None:
indent = ''
if len(indent) >= length:
raise FlagsError('Indent must be shorter than length')
# In line we will be holding the current line which is to be started
# with indent (or firstline_indent if available) and then appended
# with words.
if firstline_indent is None:
firstline_indent = ''
line = indent
else:
line = firstline_indent
if len(firstline_indent) >= length:
raise FlagsError('First line indent must be shorter than length')
# If the callee does not care about tabs we simply convert them to
# spaces If callee wanted tabs to be single space then we do that
# already here.
if not tabs or tabs == ' ':
text = text.replace('\t', ' ')
else:
tabs_are_whitespace = not tabs.strip()
line_regex = re.compile('([ ]*)(\t*)([^ \t]+)', re.MULTILINE)
# Split the text into lines and the lines with the regex above. The
# resulting lines are collected in result[]. For each split we get the
# spaces, the tabs and the next non white space (e.g. next word).
result = []
for text_line in text.splitlines():
# Store result length so we can find out whether processing the next
# line gave any new content
old_result_len = len(result)
# Process next line with line_regex. For optimization we do an rstrip().
# - process tabs (changes either line or word, see below)
# - process word (first try to squeeze on line, then wrap or force wrap)
# Spaces found on the line are ignored, they get added while wrapping as
# needed.
for spaces, current_tabs, word in line_regex.findall(text_line.rstrip()):
# If tabs weren't converted to spaces, handle them now
if current_tabs:
# If the last thing we added was a space anyway then drop
# it. But let's not get rid of the indentation.
if (((result and line != indent) or
(not result and line != firstline_indent)) and line[-1] == ' '):
line = line[:-1]
# Add the tabs, if that means adding whitespace, just add it at
# the line, the rstrip() code while shorten the line down if
# necessary
if tabs_are_whitespace:
line += tabs * len(current_tabs)
else:
# if not all tab replacement is whitespace we prepend it to the word
word = tabs * len(current_tabs) + word
# Handle the case where word cannot be squeezed onto current last line
if len(line) + len(word) > length and len(indent) + len(word) <= length:
result.append(line.rstrip())
line = indent + word
word = ''
# No space left on line or can we append a space?
if len(line) + 1 >= length:
result.append(line.rstrip())
line = indent
else:
line += ' '
# Add word and shorten it up to allowed line length. Restart next
# line with indent and repeat, or add a space if we're done (word
# finished) This deals with words that cannot fit on one line
# (e.g. indent + word longer than allowed line length).
while len(line) + len(word) >= length:
line += word
result.append(line[:length])
word = line[length:]
line = indent
# Default case, simply append the word and a space
if word:
line += word + ' '
# End of input line. If we have content we finish the line. If the
# current line is just the indent but we had content in during this
# original line then we need to add an empty line.
if (result and line != indent) or (not result and line != firstline_indent):
result.append(line.rstrip())
elif len(result) == old_result_len:
result.append('')
line = indent
return '\n'.join(result)
def DocToHelp(doc):
"""Takes a __doc__ string and reformats it as help."""
# Get rid of starting and ending white space. Using lstrip() or even
# strip() could drop more than maximum of first line and right space
# of last line.
doc = doc.strip()
# Get rid of all empty lines
whitespace_only_line = re.compile('^[ \t]+$', re.M)
doc = whitespace_only_line.sub('', doc)
# Cut out common space at line beginnings
doc = CutCommonSpacePrefix(doc)
# Just like this module's comment, comments tend to be aligned somehow.
# In other words they all start with the same amount of white space
# 1) keep double new lines
# 2) keep ws after new lines if not empty line
# 3) all other new lines shall be changed to a space
# Solution: Match new lines between non white space and replace with space.
doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M)
return doc
def _GetModuleObjectAndName(globals_dict):
"""Returns the module that defines a global environment, and its name.
Args:
globals_dict: A dictionary that should correspond to an environment
providing the values of the globals.
Returns:
A pair consisting of (1) module object and (2) module name (a
string). Returns (None, None) if the module could not be
identified.
"""
# The use of .items() (instead of .iteritems()) is NOT a mistake: if
# a parallel thread imports a module while we iterate over
# .iteritems() (not nice, but possible), we get a RuntimeError ...
# Hence, we use the slightly slower but safer .items().
for name, module in sys.modules.items():
if getattr(module, '__dict__', None) is globals_dict:
if name == '__main__':
# Pick a more informative name for the main module.
name = sys.argv[0]
return (module, name)
return (None, None)
def _GetMainModule():
"""Returns: string, name of the module from which execution started."""
# First, try to use the same logic used by _GetCallingModuleObjectAndName(),
# i.e., call _GetModuleObjectAndName(). For that we first need to
# find the dictionary that the main module uses to store the
# globals.
#
# That's (normally) the same dictionary object that the deepest
# (oldest) stack frame is using for globals.
deepest_frame = sys._getframe(0)
while deepest_frame.f_back is not None:
deepest_frame = deepest_frame.f_back
globals_for_main_module = deepest_frame.f_globals
main_module_name = _GetModuleObjectAndName(globals_for_main_module)[1]
# The above strategy fails in some cases (e.g., tools that compute
# code coverage by redefining, among other things, the main module).
# If so, just use sys.argv[0]. We can probably always do this, but
# it's safest to try to use the same logic as _GetCallingModuleObjectAndName()
if main_module_name is None:
main_module_name = sys.argv[0]
return main_module_name
class FlagValues:
"""Registry of 'Flag' objects.
A 'FlagValues' can then scan command line arguments, passing flag
arguments through to the 'Flag' objects that it owns. It also
provides easy access to the flag values. Typically only one
'FlagValues' object is needed by an application: gflags.FLAGS
This class is heavily overloaded:
'Flag' objects are registered via __setitem__:
FLAGS['longname'] = x # register a new flag
The .value attribute of the registered 'Flag' objects can be accessed
as attributes of this 'FlagValues' object, through __getattr__. Both
the long and short name of the original 'Flag' objects can be used to
access its value:
FLAGS.longname # parsed flag value
FLAGS.x # parsed flag value (short name)
Command line arguments are scanned and passed to the registered 'Flag'
objects through the __call__ method. Unparsed arguments, including
argv[0] (e.g. the program name) are returned.
argv = FLAGS(sys.argv) # scan command line arguments
The original registered Flag objects can be retrieved through the use
of the dictionary-like operator, __getitem__:
x = FLAGS['longname'] # access the registered Flag object
The str() operator of a 'FlagValues' object provides help for all of
the registered 'Flag' objects.
"""
def __init__(self):
# Since everything in this class is so heavily overloaded, the only
# way of defining and using fields is to access __dict__ directly.
# Dictionary: flag name (string) -> Flag object.
self.__dict__['__flags'] = {}
# Dictionary: module name (string) -> list of Flag objects that are defined
# by that module.
self.__dict__['__flags_by_module'] = {}
# Dictionary: module id (int) -> list of Flag objects that are defined by
# that module.
self.__dict__['__flags_by_module_id'] = {}
# Dictionary: module name (string) -> list of Flag objects that are
# key for that module.
self.__dict__['__key_flags_by_module'] = {}
# Set if we should use new style gnu_getopt rather than getopt when parsing
# the args. Only possible with Python 2.3+
self.UseGnuGetOpt(False)
def UseGnuGetOpt(self, use_gnu_getopt=True):
"""Use GNU-style scanning. Allows mixing of flag and non-flag arguments.
See http://docs.python.org/library/getopt.html#getopt.gnu_getopt
Args:
use_gnu_getopt: wether or not to use GNU style scanning.
"""
self.__dict__['__use_gnu_getopt'] = use_gnu_getopt
def IsGnuGetOpt(self):
return self.__dict__['__use_gnu_getopt']
def FlagDict(self):
return self.__dict__['__flags']
def FlagsByModuleDict(self):
"""Returns the dictionary of module_name -> list of defined flags.
Returns:
A dictionary. Its keys are module names (strings). Its values
are lists of Flag objects.
"""
return self.__dict__['__flags_by_module']
def FlagsByModuleIdDict(self):
"""Returns the dictionary of module_id -> list of defined flags.
Returns:
A dictionary. Its keys are module IDs (ints). Its values
are lists of Flag objects.
"""
return self.__dict__['__flags_by_module_id']
def KeyFlagsByModuleDict(self):
"""Returns the dictionary of module_name -> list of key flags.
Returns:
A dictionary. Its keys are module names (strings). Its values
are lists of Flag objects.
"""
return self.__dict__['__key_flags_by_module']
def _RegisterFlagByModule(self, module_name, flag):
"""Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we
can later sort the flags by module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module.
"""
flags_by_module = self.FlagsByModuleDict()
flags_by_module.setdefault(module_name, []).append(flag)
def _RegisterFlagByModuleId(self, module_id, flag):
"""Records the module that defines a specific flag.
Args:
module_id: An int, the ID of the Python module.
flag: A Flag object, a flag that is key to the module.
"""
flags_by_module_id = self.FlagsByModuleIdDict()
flags_by_module_id.setdefault(module_id, []).append(flag)
def _RegisterKeyFlagForModule(self, module_name, flag):
"""Specifies that a flag is a key flag for a module.
Args:
module_name: A string, the name of a Python module.
flag: A Flag object, a flag that is key to the module.
"""
key_flags_by_module = self.KeyFlagsByModuleDict()
# The list of key flags for the module named module_name.
key_flags = key_flags_by_module.setdefault(module_name, [])
# Add flag, but avoid duplicates.
if flag not in key_flags:
key_flags.append(flag)
def _GetFlagsDefinedByModule(self, module):
"""Returns the list of flags defined by a module.
Args:
module: A module object or a module name (a string).
Returns:
A new list of Flag objects. Caller may update this list as he
wishes: none of those changes will affect the internals of this
FlagValue object.
"""
if not isinstance(module, str):
module = module.__name__
return list(self.FlagsByModuleDict().get(module, []))
def _GetKeyFlagsForModule(self, module):
"""Returns the list of key flags for a module.
Args:
module: A module object or a module name (a string)
Returns:
A new list of Flag objects. Caller may update this list as he
wishes: none of those changes will affect the internals of this
FlagValue object.
"""
if not isinstance(module, str):
module = module.__name__
# Any flag is a key flag for the module that defined it. NOTE:
# key_flags is a fresh list: we can update it without affecting the
# internals of this FlagValues object.
key_flags = self._GetFlagsDefinedByModule(module)
# Take into account flags explicitly declared as key for a module.
for flag in self.KeyFlagsByModuleDict().get(module, []):
if flag not in key_flags:
key_flags.append(flag)
return key_flags
def FindModuleDefiningFlag(self, flagname, default=None):
"""Return the name of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module which registered the flag with this name.
If no such module exists (i.e. no flag with this name exists),
we return default.
"""
for module, flags in self.FlagsByModuleDict().iteritems():
for flag in flags:
if flag.name == flagname or flag.short_name == flagname:
return module
return default
def FindModuleIdDefiningFlag(self, flagname, default=None):
"""Return the ID of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The ID of the module which registered the flag with this name.
If no such module exists (i.e. no flag with this name exists),
we return default.
"""
for module_id, flags in self.FlagsByModuleIdDict().iteritems():
for flag in flags:
if flag.name == flagname or flag.short_name == flagname:
return module_id
return default
def AppendFlagValues(self, flag_values):
"""Appends flags registered in another FlagValues instance.
Args:
flag_values: registry to copy from
"""
for flag_name, flag in flag_values.FlagDict().iteritems():
# Each flags with shortname appears here twice (once under its
# normal name, and again with its short name). To prevent
# problems (DuplicateFlagError) with double flag registration, we
# perform a check to make sure that the entry we're looking at is
# for its normal name.
if flag_name == flag.name:
try:
self[flag_name] = flag
except DuplicateFlagError:
raise DuplicateFlagError(flag_name, self,
other_flag_values=flag_values)
def RemoveFlagValues(self, flag_values):
"""Remove flags that were previously appended from another FlagValues.
Args:
flag_values: registry containing flags to remove.
"""
for flag_name in flag_values.FlagDict():
self.__delattr__(flag_name)
def __setitem__(self, name, flag):
"""Registers a new flag variable."""
fl = self.FlagDict()
if not isinstance(flag, Flag):
raise IllegalFlagValue(flag)
if not isinstance(name, type("")):
raise FlagsError("Flag name must be a string")
if len(name) == 0:
raise FlagsError("Flag name cannot be empty")
# If running under pychecker, duplicate keys are likely to be
# defined. Disable check for duplicate keys when pycheck'ing.
if (name in fl and not flag.allow_override and
not fl[name].allow_override and not _RUNNING_PYCHECKER):
module, module_name = _GetCallingModuleObjectAndName()
if (self.FindModuleDefiningFlag(name) == module_name and
id(module) != self.FindModuleIdDefiningFlag(name)):
# If the flag has already been defined by a module with the same name,
# but a different ID, we can stop here because it indicates that the
# module is simply being imported a subsequent time.
return
raise DuplicateFlagError(name, self)
short_name = flag.short_name
if short_name is not None:
if (short_name in fl and not flag.allow_override and
not fl[short_name].allow_override and not _RUNNING_PYCHECKER):
raise DuplicateFlagError(short_name, self)
fl[short_name] = flag
fl[name] = flag
global _exported_flags
_exported_flags[name] = flag
def __getitem__(self, name):
"""Retrieves the Flag object for the flag --name."""
return self.FlagDict()[name]
def __getattr__(self, name):
"""Retrieves the 'value' attribute of the flag --name."""
fl = self.FlagDict()
if name not in fl:
raise AttributeError(name)
return fl[name].value
def __setattr__(self, name, value):
"""Sets the 'value' attribute of the flag --name."""
fl = self.FlagDict()
fl[name].value = value
self._AssertValidators(fl[name].validators)
return value
def _AssertAllValidators(self):
all_validators = set()
for flag in self.FlagDict().itervalues():
for validator in flag.validators:
all_validators.add(validator)
self._AssertValidators(all_validators)
def _AssertValidators(self, validators):
"""Assert if all validators in the list are satisfied.
Asserts validators in the order they were created.
Args:
validators: Iterable(gflags_validators.Validator), validators to be
verified
Raises:
AttributeError: if validators work with a non-existing flag.
IllegalFlagValue: if validation fails for at least one validator
"""
for validator in sorted(
validators, key=lambda validator: validator.insertion_index):
try:
validator.Verify(self)
except gflags_validators.Error, e:
message = validator.PrintFlagsWithValues(self)
raise IllegalFlagValue('%s: %s' % (message, str(e)))
def _FlagIsRegistered(self, flag_obj):
"""Checks whether a Flag object is registered under some name.
Note: this is non trivial: in addition to its normal name, a flag
may have a short name too. In self.FlagDict(), both the normal and
the short name are mapped to the same flag object. E.g., calling
only "del FLAGS.short_name" is not unregistering the corresponding
Flag object (it is still registered under the longer name).
Args:
flag_obj: A Flag object.
Returns:
A boolean: True iff flag_obj is registered under some name.
"""
flag_dict = self.FlagDict()
# Check whether flag_obj is registered under its long name.
name = flag_obj.name
if flag_dict.get(name, None) == flag_obj:
return True
# Check whether flag_obj is registered under its short name.
short_name = flag_obj.short_name
if (short_name is not None and
flag_dict.get(short_name, None) == flag_obj):
return True
# The flag cannot be registered under any other name, so we do not
# need to do a full search through the values of self.FlagDict().
return False
def __delattr__(self, flag_name):
"""Deletes a previously-defined flag from a flag object.
This method makes sure we can delete a flag by using
del flag_values_object.<flag_name>
E.g.,
gflags.DEFINE_integer('foo', 1, 'Integer flag.')
del gflags.FLAGS.foo
Args:
flag_name: A string, the name of the flag to be deleted.
Raises:
AttributeError: When there is no registered flag named flag_name.
"""
fl = self.FlagDict()
if flag_name not in fl:
raise AttributeError(flag_name)
flag_obj = fl[flag_name]
del fl[flag_name]
if not self._FlagIsRegistered(flag_obj):
# If the Flag object indicated by flag_name is no longer
# registered (please see the docstring of _FlagIsRegistered), then
# we delete the occurrences of the flag object in all our internal
# dictionaries.
self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj)
self.__RemoveFlagFromDictByModule(self.FlagsByModuleIdDict(), flag_obj)
self.__RemoveFlagFromDictByModule(self.KeyFlagsByModuleDict(), flag_obj)
def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj):
"""Removes a flag object from a module -> list of flags dictionary.
Args:
flags_by_module_dict: A dictionary that maps module names to lists of
flags.
flag_obj: A flag object.
"""
for unused_module, flags_in_module in flags_by_module_dict.iteritems():
# while (as opposed to if) takes care of multiple occurrences of a
# flag in the list for the same module.
while flag_obj in flags_in_module:
flags_in_module.remove(flag_obj)
def SetDefault(self, name, value):
"""Changes the default value of the named flag object."""
fl = self.FlagDict()
if name not in fl:
raise AttributeError(name)
fl[name].SetDefault(value)
self._AssertValidators(fl[name].validators)
def __contains__(self, name):
"""Returns True if name is a value (flag) in the dict."""
return name in self.FlagDict()
has_key = __contains__ # a synonym for __contains__()
def __iter__(self):
return iter(self.FlagDict())
def __call__(self, argv):
"""Parses flags from argv; stores parsed flags into this FlagValues object.
All unparsed arguments are returned. Flags are parsed using the GNU
Program Argument Syntax Conventions, using getopt:
http://www.gnu.org/software/libc/manual/html_mono/libc.html#Getopt
Args:
argv: argument list. Can be of any type that may be converted to a list.
Returns:
The list of arguments not parsed as options, including argv[0]
Raises:
FlagsError: on any parsing error
"""
# Support any sequence type that can be converted to a list
argv = list(argv)
shortopts = ""
longopts = []
fl = self.FlagDict()
# This pre parses the argv list for --flagfile=<> options.
argv = argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False)
# Correct the argv to support the google style of passing boolean
# parameters. Boolean parameters may be passed by using --mybool,
# --nomybool, --mybool=(true|false|1|0). getopt does not support
# having options that may or may not have a parameter. We replace
# instances of the short form --mybool and --nomybool with their
# full forms: --mybool=(true|false).
original_argv = list(argv) # list() makes a copy
shortest_matches = None
for name, flag in fl.items():
if not flag.boolean:
continue
if shortest_matches is None:
# Determine the smallest allowable prefix for all flag names
shortest_matches = self.ShortestUniquePrefixes(fl)
no_name = 'no' + name
prefix = shortest_matches[name]
no_prefix = shortest_matches[no_name]
# Replace all occurrences of this boolean with extended forms
for arg_idx in range(1, len(argv)):
arg = argv[arg_idx]
if arg.find('=') >= 0: continue
if arg.startswith('--'+prefix) and ('--'+name).startswith(arg):
argv[arg_idx] = ('--%s=true' % name)
elif arg.startswith('--'+no_prefix) and ('--'+no_name).startswith(arg):
argv[arg_idx] = ('--%s=false' % name)
# Loop over all of the flags, building up the lists of short options
# and long options that will be passed to getopt. Short options are
# specified as a string of letters, each letter followed by a colon
# if it takes an argument. Long options are stored in an array of
# strings. Each string ends with an '=' if it takes an argument.
for name, flag in fl.items():
longopts.append(name + "=")
if len(name) == 1: # one-letter option: allow short flag type also
shortopts += name
if not flag.boolean:
shortopts += ":"
longopts.append('undefok=')
undefok_flags = []
# In case --undefok is specified, loop to pick up unrecognized
# options one by one.
unrecognized_opts = []
args = argv[1:]
while True:
try:
if self.__dict__['__use_gnu_getopt']:
optlist, unparsed_args = getopt.gnu_getopt(args, shortopts, longopts)
else:
optlist, unparsed_args = getopt.getopt(args, shortopts, longopts)
break
except getopt.GetoptError, e:
if not e.opt or e.opt in fl:
# Not an unrecognized option, re-raise the exception as a FlagsError
raise FlagsError(e)
# Remove offender from args and try again
for arg_index in range(len(args)):
if ((args[arg_index] == '--' + e.opt) or
(args[arg_index] == '-' + e.opt) or
(args[arg_index].startswith('--' + e.opt + '='))):
unrecognized_opts.append((e.opt, args[arg_index]))
args = args[0:arg_index] + args[arg_index+1:]
break
else:
# We should have found the option, so we don't expect to get
# here. We could assert, but raising the original exception
# might work better.
raise FlagsError(e)
for name, arg in optlist:
if name == '--undefok':
flag_names = arg.split(',')
undefok_flags.extend(flag_names)
# For boolean flags, if --undefok=boolflag is specified, then we should
# also accept --noboolflag, in addition to --boolflag.
# Since we don't know the type of the undefok'd flag, this will affect
# non-boolean flags as well.
# NOTE: You shouldn't use --undefok=noboolflag, because then we will
# accept --nonoboolflag here. We are choosing not to do the conversion
# from noboolflag -> boolflag because of the ambiguity that flag names
# can start with 'no'.
undefok_flags.extend('no' + name for name in flag_names)
continue
if name.startswith('--'):
# long option
name = name[2:]
short_option = 0
else:
# short option
name = name[1:]
short_option = 1
if name in fl:
flag = fl[name]
if flag.boolean and short_option: arg = 1
flag.Parse(arg)
# If there were unrecognized options, raise an exception unless
# the options were named via --undefok.
for opt, value in unrecognized_opts:
if opt not in undefok_flags:
raise UnrecognizedFlagError(opt, value)
if unparsed_args:
if self.__dict__['__use_gnu_getopt']:
# if using gnu_getopt just return the program name + remainder of argv.
ret_val = argv[:1] + unparsed_args
else:
# unparsed_args becomes the first non-flag detected by getopt to
# the end of argv. Because argv may have been modified above,
# return original_argv for this region.
ret_val = argv[:1] + original_argv[-len(unparsed_args):]
else:
ret_val = argv[:1]
self._AssertAllValidators()
return ret_val
def Reset(self):
"""Resets the values to the point before FLAGS(argv) was called."""
for f in self.FlagDict().values():
f.Unparse()
def RegisteredFlags(self):
"""Returns: a list of the names and short names of all registered flags."""
return list(self.FlagDict())
def FlagValuesDict(self):
"""Returns: a dictionary that maps flag names to flag values."""
flag_values = {}
for flag_name in self.RegisteredFlags():
flag = self.FlagDict()[flag_name]
flag_values[flag_name] = flag.value
return flag_values
def __str__(self):
"""Generates a help string for all known flags."""
return self.GetHelp()
def GetHelp(self, prefix=''):
"""Generates a help string for all known flags."""
helplist = []
flags_by_module = self.FlagsByModuleDict()
if flags_by_module:
modules = sorted(flags_by_module)
# Print the help for the main module first, if possible.
main_module = _GetMainModule()
if main_module in modules:
modules.remove(main_module)
modules = [main_module] + modules
for module in modules:
self.__RenderOurModuleFlags(module, helplist)
self.__RenderModuleFlags('gflags',
_SPECIAL_FLAGS.FlagDict().values(),
helplist)
else:
# Just print one long list of flags.
self.__RenderFlagList(
self.FlagDict().values() + _SPECIAL_FLAGS.FlagDict().values(),
helplist, prefix)
return '\n'.join(helplist)
def __RenderModuleFlags(self, module, flags, output_lines, prefix=""):
"""Generates a help string for a given module."""
if not isinstance(module, str):
module = module.__name__
output_lines.append('\n%s%s:' % (prefix, module))
self.__RenderFlagList(flags, output_lines, prefix + " ")
def __RenderOurModuleFlags(self, module, output_lines, prefix=""):
"""Generates a help string for a given module."""
flags = self._GetFlagsDefinedByModule(module)
if flags:
self.__RenderModuleFlags(module, flags, output_lines, prefix)
def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""):
"""Generates a help string for the key flags of a given module.
Args:
module: A module object or a module name (a string).
output_lines: A list of strings. The generated help message
lines will be appended to this list.
prefix: A string that is prepended to each generated help line.
"""
key_flags = self._GetKeyFlagsForModule(module)
if key_flags:
self.__RenderModuleFlags(module, key_flags, output_lines, prefix)
def ModuleHelp(self, module):
"""Describe the key flags of a module.
Args:
module: A module object or a module name (a string).
Returns:
string describing the key flags of a module.
"""
helplist = []
self.__RenderOurModuleKeyFlags(module, helplist)
return '\n'.join(helplist)
def MainModuleHelp(self):
"""Describe the key flags of the main module.
Returns:
string describing the key flags of a module.
"""
return self.ModuleHelp(_GetMainModule())
def __RenderFlagList(self, flaglist, output_lines, prefix=" "):
fl = self.FlagDict()
special_fl = _SPECIAL_FLAGS.FlagDict()
flaglist = [(flag.name, flag) for flag in flaglist]
flaglist.sort()
flagset = {}
for (name, flag) in flaglist:
# It's possible this flag got deleted or overridden since being
# registered in the per-module flaglist. Check now against the
# canonical source of current flag information, the FlagDict.
if fl.get(name, None) != flag and special_fl.get(name, None) != flag:
# a different flag is using this name now
continue
# only print help once
if flag in flagset: continue
flagset[flag] = 1
flaghelp = ""
if flag.short_name: flaghelp += "-%s," % flag.short_name
if flag.boolean:
flaghelp += "--[no]%s" % flag.name + ":"
else:
flaghelp += "--%s" % flag.name + ":"
flaghelp += " "
if flag.help:
flaghelp += flag.help
flaghelp = TextWrap(flaghelp, indent=prefix+" ",
firstline_indent=prefix)
if flag.default_as_str:
flaghelp += "\n"
flaghelp += TextWrap("(default: %s)" % flag.default_as_str,
indent=prefix+" ")
if flag.parser.syntactic_help:
flaghelp += "\n"
flaghelp += TextWrap("(%s)" % flag.parser.syntactic_help,
indent=prefix+" ")
output_lines.append(flaghelp)
def get(self, name, default):
"""Returns the value of a flag (if not None) or a default value.
Args:
name: A string, the name of a flag.
default: Default value to use if the flag value is None.
"""
value = self.__getattr__(name)
if value is not None: # Can't do if not value, b/c value might be '0' or ""
return value
else:
return default
def ShortestUniquePrefixes(self, fl):
"""Returns: dictionary; maps flag names to their shortest unique prefix."""
# Sort the list of flag names
sorted_flags = []
for name, flag in fl.items():
sorted_flags.append(name)
if flag.boolean:
sorted_flags.append('no%s' % name)
sorted_flags.sort()
# For each name in the sorted list, determine the shortest unique
# prefix by comparing itself to the next name and to the previous
# name (the latter check uses cached info from the previous loop).
shortest_matches = {}
prev_idx = 0
for flag_idx in range(len(sorted_flags)):
curr = sorted_flags[flag_idx]
if flag_idx == (len(sorted_flags) - 1):
next = None
else:
next = sorted_flags[flag_idx+1]
next_len = len(next)
for curr_idx in range(len(curr)):
if (next is None
or curr_idx >= next_len
or curr[curr_idx] != next[curr_idx]):
# curr longer than next or no more chars in common
shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1]
prev_idx = curr_idx
break
else:
# curr shorter than (or equal to) next
shortest_matches[curr] = curr
prev_idx = curr_idx + 1 # next will need at least one more char
return shortest_matches
def __IsFlagFileDirective(self, flag_string):
"""Checks whether flag_string contain a --flagfile=<foo> directive."""
if isinstance(flag_string, type("")):
if flag_string.startswith('--flagfile='):
return 1
elif flag_string == '--flagfile':
return 1
elif flag_string.startswith('-flagfile='):
return 1
elif flag_string == '-flagfile':
return 1
else:
return 0
return 0
def ExtractFilename(self, flagfile_str):
"""Returns filename from a flagfile_str of form -[-]flagfile=filename.
The cases of --flagfile foo and -flagfile foo shouldn't be hitting
this function, as they are dealt with in the level above this
function.
"""
if flagfile_str.startswith('--flagfile='):
return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip())
elif flagfile_str.startswith('-flagfile='):
return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip())
else:
raise FlagsError('Hit illegal --flagfile type: %s' % flagfile_str)
def __GetFlagFileLines(self, filename, parsed_file_list):
"""Returns the useful (!=comments, etc) lines from a file with flags.
Args:
filename: A string, the name of the flag file.
parsed_file_list: A list of the names of the files we have
already read. MUTATED BY THIS FUNCTION.
Returns:
List of strings. See the note below.
NOTE(springer): This function checks for a nested --flagfile=<foo>
tag and handles the lower file recursively. It returns a list of
all the lines that _could_ contain command flags. This is
EVERYTHING except whitespace lines and comments (lines starting
with '#' or '//').
"""
line_list = [] # All line from flagfile.
flag_line_list = [] # Subset of lines w/o comments, blanks, flagfile= tags.
try:
file_obj = open(filename, 'r')
except IOError, e_msg:
raise CantOpenFlagFileError('ERROR:: Unable to open flagfile: %s' % e_msg)
line_list = file_obj.readlines()
file_obj.close()
parsed_file_list.append(filename)
# This is where we check each line in the file we just read.
for line in line_list:
if line.isspace():
pass
# Checks for comment (a line that starts with '#').
elif line.startswith('#') or line.startswith('//'):
pass
# Checks for a nested "--flagfile=<bar>" flag in the current file.
# If we find one, recursively parse down into that file.
elif self.__IsFlagFileDirective(line):
sub_filename = self.ExtractFilename(line)
# We do a little safety check for reparsing a file we've already done.
if not sub_filename in parsed_file_list:
included_flags = self.__GetFlagFileLines(sub_filename,
parsed_file_list)
flag_line_list.extend(included_flags)
else: # Case of hitting a circularly included file.
sys.stderr.write('Warning: Hit circular flagfile dependency: %s\n' %
(sub_filename,))
else:
# Any line that's not a comment or a nested flagfile should get
# copied into 2nd position. This leaves earlier arguments
# further back in the list, thus giving them higher priority.
flag_line_list.append(line.strip())
return flag_line_list
def ReadFlagsFromFiles(self, argv, force_gnu=True):
"""Processes command line args, but also allow args to be read from file.
Args:
argv: A list of strings, usually sys.argv[1:], which may contain one or
more flagfile directives of the form --flagfile="./filename".
Note that the name of the program (sys.argv[0]) should be omitted.
force_gnu: If False, --flagfile parsing obeys normal flag semantics.
If True, --flagfile parsing instead follows gnu_getopt semantics.
*** WARNING *** force_gnu=False may become the future default!
Returns:
A new list which has the original list combined with what we read
from any flagfile(s).
References: Global gflags.FLAG class instance.
This function should be called before the normal FLAGS(argv) call.
This function scans the input list for a flag that looks like:
--flagfile=<somefile>. Then it opens <somefile>, reads all valid key
and value pairs and inserts them into the input list between the
first item of the list and any subsequent items in the list.
Note that your application's flags are still defined the usual way
using gflags DEFINE_flag() type functions.
Notes (assuming we're getting a commandline of some sort as our input):
--> Flags from the command line argv _should_ always take precedence!
--> A further "--flagfile=<otherfile.cfg>" CAN be nested in a flagfile.
It will be processed after the parent flag file is done.
--> For duplicate flags, first one we hit should "win".
--> In a flagfile, a line beginning with # or // is a comment.
--> Entirely blank lines _should_ be ignored.
"""
parsed_file_list = []
rest_of_args = argv
new_argv = []
while rest_of_args:
current_arg = rest_of_args[0]
rest_of_args = rest_of_args[1:]
if self.__IsFlagFileDirective(current_arg):
# This handles the case of -(-)flagfile foo. In this case the
# next arg really is part of this one.
if current_arg == '--flagfile' or current_arg == '-flagfile':
if not rest_of_args:
raise IllegalFlagValue('--flagfile with no argument')
flag_filename = os.path.expanduser(rest_of_args[0])
rest_of_args = rest_of_args[1:]
else:
# This handles the case of (-)-flagfile=foo.
flag_filename = self.ExtractFilename(current_arg)
new_argv.extend(
self.__GetFlagFileLines(flag_filename, parsed_file_list))
else:
new_argv.append(current_arg)
# Stop parsing after '--', like getopt and gnu_getopt.
if current_arg == '--':
break
# Stop parsing after a non-flag, like getopt.
if not current_arg.startswith('-'):
if not force_gnu and not self.__dict__['__use_gnu_getopt']:
break
if rest_of_args:
new_argv.extend(rest_of_args)
return new_argv
def FlagsIntoString(self):
"""Returns a string with the flags assignments from this FlagValues object.
This function ignores flags whose value is None. Each flag
assignment is separated by a newline.
NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString
from http://code.google.com/p/google-gflags
"""
s = ''
for flag in self.FlagDict().values():
if flag.value is not None:
s += flag.Serialize() + '\n'
return s
def AppendFlagsIntoFile(self, filename):
"""Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile
from http://code.google.com/p/google-gflags
"""
out_file = open(filename, 'a')
out_file.write(self.FlagsIntoString())
out_file.close()
def WriteHelpInXMLFormat(self, outfile=None):
"""Outputs flag documentation in XML format.
NOTE: We use element names that are consistent with those used by
the C++ command-line flag library, from
http://code.google.com/p/google-gflags
We also use a few new elements (e.g., <key>), but we do not
interfere / overlap with existing XML elements used by the C++
library. Please maintain this consistency.
Args:
outfile: File object we write to. Default None means sys.stdout.
"""
outfile = outfile or sys.stdout
outfile.write('<?xml version=\"1.0\"?>\n')
outfile.write('<AllFlags>\n')
indent = ' '
_WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]),
indent)
usage_doc = sys.modules['__main__'].__doc__
if not usage_doc:
usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0]
else:
usage_doc = usage_doc.replace('%s', sys.argv[0])
_WriteSimpleXMLElement(outfile, 'usage', usage_doc, indent)
# Get list of key flags for the main module.
key_flags = self._GetKeyFlagsForModule(_GetMainModule())
# Sort flags by declaring module name and next by flag name.
flags_by_module = self.FlagsByModuleDict()
all_module_names = list(flags_by_module.keys())
all_module_names.sort()
for module_name in all_module_names:
flag_list = [(f.name, f) for f in flags_by_module[module_name]]
flag_list.sort()
for unused_flag_name, flag in flag_list:
is_key = flag in key_flags
flag.WriteInfoInXMLFormat(outfile, module_name,
is_key=is_key, indent=indent)
outfile.write('</AllFlags>\n')
outfile.flush()
def AddValidator(self, validator):
"""Register new flags validator to be checked.
Args:
validator: gflags_validators.Validator
Raises:
AttributeError: if validators work with a non-existing flag.
"""
for flag_name in validator.GetFlagsNames():
flag = self.FlagDict()[flag_name]
flag.validators.append(validator)
# end of FlagValues definition
# The global FlagValues instance
FLAGS = FlagValues()
def _StrOrUnicode(value):
"""Converts value to a python string or, if necessary, unicode-string."""
try:
return str(value)
except UnicodeEncodeError:
return unicode(value)
def _MakeXMLSafe(s):
"""Escapes <, >, and & from s, and removes XML 1.0-illegal chars."""
s = cgi.escape(s) # Escape <, >, and &
# Remove characters that cannot appear in an XML 1.0 document
# (http://www.w3.org/TR/REC-xml/#charsets).
#
# NOTE: if there are problems with current solution, one may move to
# XML 1.1, which allows such chars, if they're entity-escaped (&#xHH;).
s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', s)
# Convert non-ascii characters to entities. Note: requires python >=2.3
s = s.encode('ascii', 'xmlcharrefreplace') # u'\xce\x88' -> 'uΈ'
return s
def _WriteSimpleXMLElement(outfile, name, value, indent):
"""Writes a simple XML element.
Args:
outfile: File object we write the XML element to.
name: A string, the name of XML element.
value: A Python object, whose string representation will be used
as the value of the XML element.
indent: A string, prepended to each line of generated output.
"""
value_str = _StrOrUnicode(value)
if isinstance(value, bool):
# Display boolean values as the C++ flag library does: no caps.
value_str = value_str.lower()
safe_value_str = _MakeXMLSafe(value_str)
outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name))
class Flag:
"""Information about a command-line flag.
'Flag' objects define the following fields:
.name - the name for this flag
.default - the default value for this flag
.default_as_str - default value as repr'd string, e.g., "'true'" (or None)
.value - the most recent parsed value of this flag; set by Parse()
.help - a help string or None if no help is available
.short_name - the single letter alias for this flag (or None)
.boolean - if 'true', this flag does not accept arguments
.present - true if this flag was parsed from command line flags.
.parser - an ArgumentParser object
.serializer - an ArgumentSerializer object
.allow_override - the flag may be redefined without raising an error
The only public method of a 'Flag' object is Parse(), but it is
typically only called by a 'FlagValues' object. The Parse() method is
a thin wrapper around the 'ArgumentParser' Parse() method. The parsed
value is saved in .value, and the .present attribute is updated. If
this flag was already present, a FlagsError is raised.
Parse() is also called during __init__ to parse the default value and
initialize the .value attribute. This enables other python modules to
safely use flags even if the __main__ module neglects to parse the
command line arguments. The .present attribute is cleared after
__init__ parsing. If the default value is set to None, then the
__init__ parsing step is skipped and the .value attribute is
initialized to None.
Note: The default value is also presented to the user in the help
string, so it is important that it be a legal value for this flag.
"""
def __init__(self, parser, serializer, name, default, help_string,
short_name=None, boolean=0, allow_override=0):
self.name = name
if not help_string:
help_string = '(no help available)'
self.help = help_string
self.short_name = short_name
self.boolean = boolean
self.present = 0
self.parser = parser
self.serializer = serializer
self.allow_override = allow_override
self.value = None
self.validators = []
self.SetDefault(default)
def __hash__(self):
return hash(id(self))
def __eq__(self, other):
return self is other
def __lt__(self, other):
if isinstance(other, Flag):
return id(self) < id(other)
return NotImplemented
def __GetParsedValueAsString(self, value):
if value is None:
return None
if self.serializer:
return repr(self.serializer.Serialize(value))
if self.boolean:
if value:
return repr('true')
else:
return repr('false')
return repr(_StrOrUnicode(value))
def Parse(self, argument):
try:
self.value = self.parser.Parse(argument)
except ValueError, e: # recast ValueError as IllegalFlagValue
raise IllegalFlagValue("flag --%s=%s: %s" % (self.name, argument, e))
self.present += 1
def Unparse(self):
if self.default is None:
self.value = None
else:
self.Parse(self.default)
self.present = 0
def Serialize(self):
if self.value is None:
return ''
if self.boolean:
if self.value:
return "--%s" % self.name
else:
return "--no%s" % self.name
else:
if not self.serializer:
raise FlagsError("Serializer not present for flag %s" % self.name)
return "--%s=%s" % (self.name, self.serializer.Serialize(self.value))
def SetDefault(self, value):
"""Changes the default value (and current value too) for this Flag."""
# We can't allow a None override because it may end up not being
# passed to C++ code when we're overriding C++ flags. So we
# cowardly bail out until someone fixes the semantics of trying to
# pass None to a C++ flag. See swig_flags.Init() for details on
# this behavior.
# TODO(olexiy): Users can directly call this method, bypassing all flags
# validators (we don't have FlagValues here, so we can not check
# validators).
# The simplest solution I see is to make this method private.
# Another approach would be to store reference to the corresponding
# FlagValues with each flag, but this seems to be an overkill.
if value is None and self.allow_override:
raise DuplicateFlagCannotPropagateNoneToSwig(self.name)
self.default = value
self.Unparse()
self.default_as_str = self.__GetParsedValueAsString(self.value)
def Type(self):
"""Returns: a string that describes the type of this Flag."""
# NOTE: we use strings, and not the types.*Type constants because
# our flags can have more exotic types, e.g., 'comma separated list
# of strings', 'whitespace separated list of strings', etc.
return self.parser.Type()
def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''):
"""Writes common info about this flag, in XML format.
This is information that is relevant to all flags (e.g., name,
meaning, etc.). If you defined a flag that has some other pieces of
info, then please override _WriteCustomInfoInXMLFormat.
Please do NOT override this method.
Args:
outfile: File object we write to.
module_name: A string, the name of the module that defines this flag.
is_key: A boolean, True iff this flag is key for main module.
indent: A string that is prepended to each generated line.
"""
outfile.write(indent + '<flag>\n')
inner_indent = indent + ' '
if is_key:
_WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent)
_WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent)
# Print flag features that are relevant for all flags.
_WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent)
if self.short_name:
_WriteSimpleXMLElement(outfile, 'short_name', self.short_name,
inner_indent)
if self.help:
_WriteSimpleXMLElement(outfile, 'meaning', self.help, inner_indent)
# The default flag value can either be represented as a string like on the
# command line, or as a Python object. We serialize this value in the
# latter case in order to remain consistent.
if self.serializer and not isinstance(self.default, str):
default_serialized = self.serializer.Serialize(self.default)
else:
default_serialized = self.default
_WriteSimpleXMLElement(outfile, 'default', default_serialized, inner_indent)
_WriteSimpleXMLElement(outfile, 'current', self.value, inner_indent)
_WriteSimpleXMLElement(outfile, 'type', self.Type(), inner_indent)
# Print extra flag features this flag may have.
self._WriteCustomInfoInXMLFormat(outfile, inner_indent)
outfile.write(indent + '</flag>\n')
def _WriteCustomInfoInXMLFormat(self, outfile, indent):
"""Writes extra info about this flag, in XML format.
"Extra" means "not already printed by WriteInfoInXMLFormat above."
Args:
outfile: File object we write to.
indent: A string that is prepended to each generated line.
"""
# Usually, the parser knows the extra details about the flag, so
# we just forward the call to it.
self.parser.WriteCustomInfoInXMLFormat(outfile, indent)
# End of Flag definition
class _ArgumentParserCache(type):
"""Metaclass used to cache and share argument parsers among flags."""
_instances = {}
def __call__(mcs, *args, **kwargs):
"""Returns an instance of the argument parser cls.
This method overrides behavior of the __new__ methods in
all subclasses of ArgumentParser (inclusive). If an instance
for mcs with the same set of arguments exists, this instance is
returned, otherwise a new instance is created.
If any keyword arguments are defined, or the values in args
are not hashable, this method always returns a new instance of
cls.
Args:
args: Positional initializer arguments.
kwargs: Initializer keyword arguments.
Returns:
An instance of cls, shared or new.
"""
if kwargs:
return type.__call__(mcs, *args, **kwargs)
else:
instances = mcs._instances
key = (mcs,) + tuple(args)
try:
return instances[key]
except KeyError:
# No cache entry for key exists, create a new one.
return instances.setdefault(key, type.__call__(mcs, *args))
except TypeError:
# An object in args cannot be hashed, always return
# a new instance.
return type.__call__(mcs, *args)
class ArgumentParser(object):
"""Base class used to parse and convert arguments.
The Parse() method checks to make sure that the string argument is a
legal value and convert it to a native type. If the value cannot be
converted, it should throw a 'ValueError' exception with a human
readable explanation of why the value is illegal.
Subclasses should also define a syntactic_help string which may be
presented to the user to describe the form of the legal values.
Argument parser classes must be stateless, since instances are cached
and shared between flags. Initializer arguments are allowed, but all
member variables must be derived from initializer arguments only.
"""
__metaclass__ = _ArgumentParserCache
syntactic_help = ""
def Parse(self, argument):
"""Default implementation: always returns its argument unmodified."""
return argument
def Type(self):
return 'string'
def WriteCustomInfoInXMLFormat(self, outfile, indent):
pass
class ArgumentSerializer:
"""Base class for generating string representations of a flag value."""
def Serialize(self, value):
return _StrOrUnicode(value)
class ListSerializer(ArgumentSerializer):
def __init__(self, list_sep):
self.list_sep = list_sep
def Serialize(self, value):
return self.list_sep.join([_StrOrUnicode(x) for x in value])
# Flags validators
def RegisterValidator(flag_name,
checker,
message='Flag validation failed',
flag_values=FLAGS):
"""Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_name: string, name of the flag to be checked.
checker: method to validate the flag.
input - value of the corresponding flag (string, boolean, etc.
This value will be passed to checker by the library). See file's
docstring for examples.
output - Boolean.
Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise gflags_validators.Error(desired_error_message).
message: error text to be shown to the user if checker returns False.
If checker raises gflags_validators.Error, message from the raised
Error will be shown.
flag_values: FlagValues
Raises:
AttributeError: if flag_name is not registered as a valid flag name.
"""
flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name,
checker,
message))
def MarkFlagAsRequired(flag_name, flag_values=FLAGS):
"""Ensure that flag is not None during program execution.
Registers a flag validator, which will follow usual validator
rules.
Args:
flag_name: string, name of the flag
flag_values: FlagValues
Raises:
AttributeError: if flag_name is not registered as a valid flag name.
"""
RegisterValidator(flag_name,
lambda value: value is not None,
message='Flag --%s must be specified.' % flag_name,
flag_values=flag_values)
def _RegisterBoundsValidatorIfNeeded(parser, name, flag_values):
"""Enforce lower and upper bounds for numeric flags.
Args:
parser: NumericParser (either FloatParser or IntegerParser). Provides lower
and upper bounds, and help text to display.
name: string, name of the flag
flag_values: FlagValues
"""
if parser.lower_bound is not None or parser.upper_bound is not None:
def Checker(value):
if value is not None and parser.IsOutsideBounds(value):
message = '%s is not %s' % (value, parser.syntactic_help)
raise gflags_validators.Error(message)
return True
RegisterValidator(name,
Checker,
flag_values=flag_values)
# The DEFINE functions are explained in mode details in the module doc string.
def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None,
**args):
"""Registers a generic Flag object.
NOTE: in the docstrings of all DEFINE* functions, "registers" is short
for "creates a new flag and registers it".
Auxiliary function: clients should use the specialized DEFINE_<type>
function instead.
Args:
parser: ArgumentParser that is used to parse the flag arguments.
name: A string, the flag name.
default: The default value of the flag.
help: A help string.
flag_values: FlagValues object the flag will be registered with.
serializer: ArgumentSerializer that serializes the flag value.
args: Dictionary with extra keyword args that are passes to the
Flag __init__.
"""
DEFINE_flag(Flag(parser, serializer, name, default, help, **args),
flag_values)
def DEFINE_flag(flag, flag_values=FLAGS):
"""Registers a 'Flag' object with a 'FlagValues' object.
By default, the global FLAGS 'FlagValue' object is used.
Typical users will use one of the more specialized DEFINE_xxx
functions, such as DEFINE_string or DEFINE_integer. But developers
who need to create Flag objects themselves should use this function
to register their flags.
"""
# copying the reference to flag_values prevents pychecker warnings
fv = flag_values
fv[flag.name] = flag
# Tell flag_values who's defining the flag.
if isinstance(flag_values, FlagValues):
# Regarding the above isinstance test: some users pass funny
# values of flag_values (e.g., {}) in order to avoid the flag
# registration (in the past, there used to be a flag_values ==
# FLAGS test here) and redefine flags with the same name (e.g.,
# debug). To avoid breaking their code, we perform the
# registration only if flag_values is a real FlagValues object.
module, module_name = _GetCallingModuleObjectAndName()
flag_values._RegisterFlagByModule(module_name, flag)
flag_values._RegisterFlagByModuleId(id(module), flag)
def _InternalDeclareKeyFlags(flag_names,
flag_values=FLAGS, key_flag_values=None):
"""Declares a flag as key for the calling module.
Internal function. User code should call DECLARE_key_flag or
ADOPT_module_key_flags instead.
Args:
flag_names: A list of strings that are names of already-registered
Flag objects.
flag_values: A FlagValues object that the flags listed in
flag_names have registered with (the value of the flag_values
argument from the DEFINE_* calls that defined those flags).
This should almost never need to be overridden.
key_flag_values: A FlagValues object that (among possibly many
other things) keeps track of the key flags for each module.
Default None means "same as flag_values". This should almost
never need to be overridden.
Raises:
UnrecognizedFlagError: when we refer to a flag that was not
defined yet.
"""
key_flag_values = key_flag_values or flag_values
module = _GetCallingModule()
for flag_name in flag_names:
if flag_name not in flag_values:
raise UnrecognizedFlagError(flag_name)
flag = flag_values.FlagDict()[flag_name]
key_flag_values._RegisterKeyFlagForModule(module, flag)
def DECLARE_key_flag(flag_name, flag_values=FLAGS):
"""Declares one flag as key to the current module.
Key flags are flags that are deemed really important for a module.
They are important when listing help messages; e.g., if the
--helpshort command-line flag is used, then only the key flags of the
main module are listed (instead of all flags, as in the case of
--help).
Sample usage:
gflags.DECLARED_key_flag('flag_1')
Args:
flag_name: A string, the name of an already declared flag.
(Redeclaring flags as key, including flags implicitly key
because they were declared in this module, is a no-op.)
flag_values: A FlagValues object. This should almost never
need to be overridden.
"""
if flag_name in _SPECIAL_FLAGS:
# Take care of the special flags, e.g., --flagfile, --undefok.
# These flags are defined in _SPECIAL_FLAGS, and are treated
# specially during flag parsing, taking precedence over the
# user-defined flags.
_InternalDeclareKeyFlags([flag_name],
flag_values=_SPECIAL_FLAGS,
key_flag_values=flag_values)
return
_InternalDeclareKeyFlags([flag_name], flag_values=flag_values)
def ADOPT_module_key_flags(module, flag_values=FLAGS):
"""Declares that all flags key to a module are key to the current module.
Args:
module: A module object.
flag_values: A FlagValues object. This should almost never need
to be overridden.
Raises:
FlagsError: When given an argument that is a module name (a
string), instead of a module object.
"""
# NOTE(salcianu): an even better test would be if not
# isinstance(module, types.ModuleType) but I didn't want to import
# types for such a tiny use.
if isinstance(module, str):
raise FlagsError('Received module name %s; expected a module object.'
% module)
_InternalDeclareKeyFlags(
[f.name for f in flag_values._GetKeyFlagsForModule(module.__name__)],
flag_values=flag_values)
# If module is this flag module, take _SPECIAL_FLAGS into account.
if module == _GetThisModuleObjectAndName()[0]:
_InternalDeclareKeyFlags(
# As we associate flags with _GetCallingModuleObjectAndName(), the
# special flags defined in this module are incorrectly registered with
# a different module. So, we can't use _GetKeyFlagsForModule.
# Instead, we take all flags from _SPECIAL_FLAGS (a private
# FlagValues, where no other module should register flags).
[f.name for f in _SPECIAL_FLAGS.FlagDict().values()],
flag_values=_SPECIAL_FLAGS,
key_flag_values=flag_values)
#
# STRING FLAGS
#
def DEFINE_string(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value can be any string."""
parser = ArgumentParser()
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
#
# BOOLEAN FLAGS
#
class BooleanParser(ArgumentParser):
"""Parser of boolean values."""
def Convert(self, argument):
"""Converts the argument to a boolean; raise ValueError on errors."""
if type(argument) == str:
if argument.lower() in ['true', 't', '1']:
return True
elif argument.lower() in ['false', 'f', '0']:
return False
bool_argument = bool(argument)
if argument == bool_argument:
# The argument is a valid boolean (True, False, 0, or 1), and not just
# something that always converts to bool (list, string, int, etc.).
return bool_argument
raise ValueError('Non-boolean argument to boolean flag', argument)
def Parse(self, argument):
val = self.Convert(argument)
return val
def Type(self):
return 'bool'
class BooleanFlag(Flag):
"""Basic boolean flag.
Boolean flags do not take any arguments, and their value is either
True (1) or False (0). The false value is specified on the command
line by prepending the word 'no' to either the long or the short flag
name.
For example, if a Boolean flag was created whose long name was
'update' and whose short name was 'x', then this flag could be
explicitly unset through either --noupdate or --nox.
"""
def __init__(self, name, default, help, short_name=None, **args):
p = BooleanParser()
Flag.__init__(self, p, None, name, default, help, short_name, 1, **args)
if not self.help: self.help = "a boolean value"
def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args):
"""Registers a boolean flag.
Such a boolean flag does not take an argument. If a user wants to
specify a false value explicitly, the long option beginning with 'no'
must be used: i.e. --noflag
This flag will have a value of None, True or False. None is possible
if default=None and the user does not specify the flag on the command
line.
"""
DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values)
# Match C++ API to unconfuse C++ people.
DEFINE_bool = DEFINE_boolean
class HelpFlag(BooleanFlag):
"""
HelpFlag is a special boolean flag that prints usage information and
raises a SystemExit exception if it is ever found in the command
line arguments. Note this is called with allow_override=1, so other
apps can define their own --help flag, replacing this one, if they want.
"""
def __init__(self):
BooleanFlag.__init__(self, "help", 0, "show this help",
short_name="?", allow_override=1)
def Parse(self, arg):
if arg:
doc = sys.modules["__main__"].__doc__
flags = str(FLAGS)
print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])
if flags:
print "flags:"
print flags
sys.exit(1)
class HelpXMLFlag(BooleanFlag):
"""Similar to HelpFlag, but generates output in XML format."""
def __init__(self):
BooleanFlag.__init__(self, 'helpxml', False,
'like --help, but generates XML output',
allow_override=1)
def Parse(self, arg):
if arg:
FLAGS.WriteHelpInXMLFormat(sys.stdout)
sys.exit(1)
class HelpshortFlag(BooleanFlag):
"""
HelpshortFlag is a special boolean flag that prints usage
information for the "main" module, and rasies a SystemExit exception
if it is ever found in the command line arguments. Note this is
called with allow_override=1, so other apps can define their own
--helpshort flag, replacing this one, if they want.
"""
def __init__(self):
BooleanFlag.__init__(self, "helpshort", 0,
"show usage only for this module", allow_override=1)
def Parse(self, arg):
if arg:
doc = sys.modules["__main__"].__doc__
flags = FLAGS.MainModuleHelp()
print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0])
if flags:
print "flags:"
print flags
sys.exit(1)
#
# Numeric parser - base class for Integer and Float parsers
#
class NumericParser(ArgumentParser):
"""Parser of numeric values.
Parsed value may be bounded to a given upper and lower bound.
"""
def IsOutsideBounds(self, val):
return ((self.lower_bound is not None and val < self.lower_bound) or
(self.upper_bound is not None and val > self.upper_bound))
def Parse(self, argument):
val = self.Convert(argument)
if self.IsOutsideBounds(val):
raise ValueError("%s is not %s" % (val, self.syntactic_help))
return val
def WriteCustomInfoInXMLFormat(self, outfile, indent):
if self.lower_bound is not None:
_WriteSimpleXMLElement(outfile, 'lower_bound', self.lower_bound, indent)
if self.upper_bound is not None:
_WriteSimpleXMLElement(outfile, 'upper_bound', self.upper_bound, indent)
def Convert(self, argument):
"""Default implementation: always returns its argument unmodified."""
return argument
# End of Numeric Parser
#
# FLOAT FLAGS
#
class FloatParser(NumericParser):
"""Parser of floating point values.
Parsed value may be bounded to a given upper and lower bound.
"""
number_article = "a"
number_name = "number"
syntactic_help = " ".join((number_article, number_name))
def __init__(self, lower_bound=None, upper_bound=None):
super(FloatParser, self).__init__()
self.lower_bound = lower_bound
self.upper_bound = upper_bound
sh = self.syntactic_help
if lower_bound is not None and upper_bound is not None:
sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound))
elif lower_bound == 0:
sh = "a non-negative %s" % self.number_name
elif upper_bound == 0:
sh = "a non-positive %s" % self.number_name
elif upper_bound is not None:
sh = "%s <= %s" % (self.number_name, upper_bound)
elif lower_bound is not None:
sh = "%s >= %s" % (self.number_name, lower_bound)
self.syntactic_help = sh
def Convert(self, argument):
"""Converts argument to a float; raises ValueError on errors."""
return float(argument)
def Type(self):
return 'float'
# End of FloatParser
def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value must be a float.
If lower_bound or upper_bound are set, then this flag must be
within the given range.
"""
parser = FloatParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values)
#
# INTEGER FLAGS
#
class IntegerParser(NumericParser):
"""Parser of an integer value.
Parsed value may be bounded to a given upper and lower bound.
"""
number_article = "an"
number_name = "integer"
syntactic_help = " ".join((number_article, number_name))
def __init__(self, lower_bound=None, upper_bound=None):
super(IntegerParser, self).__init__()
self.lower_bound = lower_bound
self.upper_bound = upper_bound
sh = self.syntactic_help
if lower_bound is not None and upper_bound is not None:
sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound))
elif lower_bound == 1:
sh = "a positive %s" % self.number_name
elif upper_bound == -1:
sh = "a negative %s" % self.number_name
elif lower_bound == 0:
sh = "a non-negative %s" % self.number_name
elif upper_bound == 0:
sh = "a non-positive %s" % self.number_name
elif upper_bound is not None:
sh = "%s <= %s" % (self.number_name, upper_bound)
elif lower_bound is not None:
sh = "%s >= %s" % (self.number_name, lower_bound)
self.syntactic_help = sh
def Convert(self, argument):
__pychecker__ = 'no-returnvalues'
if type(argument) == str:
base = 10
if len(argument) > 2 and argument[0] == "0" and argument[1] == "x":
base = 16
return int(argument, base)
else:
return int(argument)
def Type(self):
return 'int'
def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value must be an integer.
If lower_bound, or upper_bound are set, then this flag must be
within the given range.
"""
parser = IntegerParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE(parser, name, default, help, flag_values, serializer, **args)
_RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values)
#
# ENUM FLAGS
#
class EnumParser(ArgumentParser):
"""Parser of a string enum value (a string value from a given set).
If enum_values (see below) is not specified, any string is allowed.
"""
def __init__(self, enum_values=None):
super(EnumParser, self).__init__()
self.enum_values = enum_values
def Parse(self, argument):
if self.enum_values and argument not in self.enum_values:
raise ValueError("value should be one of <%s>" %
"|".join(self.enum_values))
return argument
def Type(self):
return 'string enum'
class EnumFlag(Flag):
"""Basic enum flag; its value can be any string from list of enum_values."""
def __init__(self, name, default, help, enum_values=None,
short_name=None, **args):
enum_values = enum_values or []
p = EnumParser(enum_values)
g = ArgumentSerializer()
Flag.__init__(self, p, g, name, default, help, short_name, **args)
if not self.help: self.help = "an enum string"
self.help = "<%s>: %s" % ("|".join(enum_values), self.help)
def _WriteCustomInfoInXMLFormat(self, outfile, indent):
for enum_value in self.parser.enum_values:
_WriteSimpleXMLElement(outfile, 'enum_value', enum_value, indent)
def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS,
**args):
"""Registers a flag whose value can be any string from enum_values."""
DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args),
flag_values)
#
# LIST FLAGS
#
class BaseListParser(ArgumentParser):
"""Base class for a parser of lists of strings.
To extend, inherit from this class; from the subclass __init__, call
BaseListParser.__init__(self, token, name)
where token is a character used to tokenize, and name is a description
of the separator.
"""
def __init__(self, token=None, name=None):
assert name
super(BaseListParser, self).__init__()
self._token = token
self._name = name
self.syntactic_help = "a %s separated list" % self._name
def Parse(self, argument):
if isinstance(argument, list):
return argument
elif argument == '':
return []
else:
return [s.strip() for s in argument.split(self._token)]
def Type(self):
return '%s separated list of strings' % self._name
class ListParser(BaseListParser):
"""Parser for a comma-separated list of strings."""
def __init__(self):
BaseListParser.__init__(self, ',', 'comma')
def WriteCustomInfoInXMLFormat(self, outfile, indent):
BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent)
_WriteSimpleXMLElement(outfile, 'list_separator', repr(','), indent)
class WhitespaceSeparatedListParser(BaseListParser):
"""Parser for a whitespace-separated list of strings."""
def __init__(self):
BaseListParser.__init__(self, None, 'whitespace')
def WriteCustomInfoInXMLFormat(self, outfile, indent):
BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent)
separators = list(string.whitespace)
separators.sort()
for ws_char in string.whitespace:
_WriteSimpleXMLElement(outfile, 'list_separator', repr(ws_char), indent)
def DEFINE_list(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value is a comma-separated list of strings."""
parser = ListParser()
serializer = ListSerializer(',')
DEFINE(parser, name, default, help, flag_values, serializer, **args)
def DEFINE_spaceseplist(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value is a whitespace-separated list of strings.
Any whitespace can be used as a separator.
"""
parser = WhitespaceSeparatedListParser()
serializer = ListSerializer(' ')
DEFINE(parser, name, default, help, flag_values, serializer, **args)
#
# MULTI FLAGS
#
class MultiFlag(Flag):
"""A flag that can appear multiple time on the command-line.
The value of such a flag is a list that contains the individual values
from all the appearances of that flag on the command-line.
See the __doc__ for Flag for most behavior of this class. Only
differences in behavior are described here:
* The default value may be either a single value or a list of values.
A single value is interpreted as the [value] singleton list.
* The value of the flag is always a list, even if the option was
only supplied once, and even if the default value is a single
value
"""
def __init__(self, *args, **kwargs):
Flag.__init__(self, *args, **kwargs)
self.help += ';\n repeat this option to specify a list of values'
def Parse(self, arguments):
"""Parses one or more arguments with the installed parser.
Args:
arguments: a single argument or a list of arguments (typically a
list of default values); a single argument is converted
internally into a list containing one item.
"""
if not isinstance(arguments, list):
# Default value may be a list of values. Most other arguments
# will not be, so convert them into a single-item list to make
# processing simpler below.
arguments = [arguments]
if self.present:
# keep a backup reference to list of previously supplied option values
values = self.value
else:
# "erase" the defaults with an empty list
values = []
for item in arguments:
# have Flag superclass parse argument, overwriting self.value reference
Flag.Parse(self, item) # also increments self.present
values.append(self.value)
# put list of option values back in the 'value' attribute
self.value = values
def Serialize(self):
if not self.serializer:
raise FlagsError("Serializer not present for flag %s" % self.name)
if self.value is None:
return ''
s = ''
multi_value = self.value
for self.value in multi_value:
if s: s += ' '
s += Flag.Serialize(self)
self.value = multi_value
return s
def Type(self):
return 'multi ' + self.parser.Type()
def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS,
**args):
"""Registers a generic MultiFlag that parses its args with a given parser.
Auxiliary function. Normal users should NOT use it directly.
Developers who need to create their own 'Parser' classes for options
which can appear multiple times can call this module function to
register their flags.
"""
DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args),
flag_values)
def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of any strings.
Use the flag on the command line multiple times to place multiple
string values into the list. The 'default' may be a single string
(which will be converted into a single-element list) or a list of
strings.
"""
parser = ArgumentParser()
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of arbitrary integers.
Use the flag on the command line multiple times to place multiple
integer values into the list. The 'default' may be a single integer
(which will be converted into a single-element list) or a list of
integers.
"""
parser = IntegerParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
def DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None,
flag_values=FLAGS, **args):
"""Registers a flag whose value can be a list of arbitrary floats.
Use the flag on the command line multiple times to place multiple
float values into the list. The 'default' may be a single float
(which will be converted into a single-element list) or a list of
floats.
"""
parser = FloatParser(lower_bound, upper_bound)
serializer = ArgumentSerializer()
DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
# Now register the flags that we want to exist in all applications.
# These are all defined with allow_override=1, so user-apps can use
# these flagnames for their own purposes, if they want.
DEFINE_flag(HelpFlag())
DEFINE_flag(HelpshortFlag())
DEFINE_flag(HelpXMLFlag())
# Define special flags here so that help may be generated for them.
# NOTE: Please do NOT use _SPECIAL_FLAGS from outside this module.
_SPECIAL_FLAGS = FlagValues()
DEFINE_string(
'flagfile', "",
"Insert flag definitions from the given file into the command line.",
_SPECIAL_FLAGS)
DEFINE_string(
'undefok', "",
"comma-separated list of flag names that it is okay to specify "
"on the command line even if the program does not define a flag "
"with that name. IMPORTANT: flags in this list that have "
"arguments MUST use the --flag=value format.", _SPECIAL_FLAGS)
| Python |
#!/usr/bin/env python
# Copyright (c) 2010, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Module to enforce different constraints on flags.
A validator represents an invariant, enforced over a one or more flags.
See 'FLAGS VALIDATORS' in gflags.py's docstring for a usage manual.
"""
__author__ = 'olexiy@google.com (Olexiy Oryeshko)'
class Error(Exception):
"""Thrown If validator constraint is not satisfied."""
class Validator(object):
"""Base class for flags validators.
Users should NOT overload these classes, and use gflags.Register...
methods instead.
"""
# Used to assign each validator an unique insertion_index
validators_count = 0
def __init__(self, checker, message):
"""Constructor to create all validators.
Args:
checker: function to verify the constraint.
Input of this method varies, see SimpleValidator and
DictionaryValidator for a detailed description.
message: string, error message to be shown to the user
"""
self.checker = checker
self.message = message
Validator.validators_count += 1
# Used to assert validators in the order they were registered (CL/18694236)
self.insertion_index = Validator.validators_count
def Verify(self, flag_values):
"""Verify that constraint is satisfied.
flags library calls this method to verify Validator's constraint.
Args:
flag_values: gflags.FlagValues, containing all flags
Raises:
Error: if constraint is not satisfied.
"""
param = self._GetInputToCheckerFunction(flag_values)
if not self.checker(param):
raise Error(self.message)
def GetFlagsNames(self):
"""Return the names of the flags checked by this validator.
Returns:
[string], names of the flags
"""
raise NotImplementedError('This method should be overloaded')
def PrintFlagsWithValues(self, flag_values):
raise NotImplementedError('This method should be overloaded')
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues, containing all flags.
Returns:
Return type depends on the specific validator.
"""
raise NotImplementedError('This method should be overloaded')
class SimpleValidator(Validator):
"""Validator behind RegisterValidator() method.
Validates that a single flag passes its checker function. The checker function
takes the flag value and returns True (if value looks fine) or, if flag value
is not valid, either returns False or raises an Exception."""
def __init__(self, flag_name, checker, message):
"""Constructor.
Args:
flag_name: string, name of the flag.
checker: function to verify the validator.
input - value of the corresponding flag (string, boolean, etc).
output - Boolean. Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise Error.
message: string, error message to be shown to the user if validator's
condition is not satisfied
"""
super(SimpleValidator, self).__init__(checker, message)
self.flag_name = flag_name
def GetFlagsNames(self):
return [self.flag_name]
def PrintFlagsWithValues(self, flag_values):
return 'flag --%s=%s' % (self.flag_name, flag_values[self.flag_name].value)
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues
Returns:
value of the corresponding flag.
"""
return flag_values[self.flag_name].value
class DictionaryValidator(Validator):
"""Validator behind RegisterDictionaryValidator method.
Validates that flag values pass their common checker function. The checker
function takes flag values and returns True (if values look fine) or,
if values are not valid, either returns False or raises an Exception.
"""
def __init__(self, flag_names, checker, message):
"""Constructor.
Args:
flag_names: [string], containing names of the flags used by checker.
checker: function to verify the validator.
input - dictionary, with keys() being flag_names, and value for each
key being the value of the corresponding flag (string, boolean, etc).
output - Boolean. Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise Error.
message: string, error message to be shown to the user if validator's
condition is not satisfied
"""
super(DictionaryValidator, self).__init__(checker, message)
self.flag_names = flag_names
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues
Returns:
dictionary, with keys() being self.lag_names, and value for each key
being the value of the corresponding flag (string, boolean, etc).
"""
return dict([key, flag_values[key].value] for key in self.flag_names)
def PrintFlagsWithValues(self, flag_values):
prefix = 'flags '
flags_with_values = []
for key in self.flag_names:
flags_with_values.append('%s=%s' % (key, flag_values[key].value))
return prefix + ', '.join(flags_with_values)
def GetFlagsNames(self):
return self.flag_names
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for Google App Engine
Utilities for making it easier to use OAuth 2.0 on Google App Engine.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import base64
import httplib2
import logging
import pickle
import time
import clientsecrets
from anyjson import simplejson
from client import AccessTokenRefreshError
from client import AssertionCredentials
from client import Credentials
from client import Flow
from client import OAuth2WebServerFlow
from client import Storage
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.api import app_identity
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns'
class InvalidClientSecretsError(Exception):
"""The client_secrets.json file is malformed or missing required fields."""
pass
class AppAssertionCredentials(AssertionCredentials):
"""Credentials object for App Engine Assertion Grants
This object will allow an App Engine application to identify itself to Google
and other OAuth 2.0 servers that can verify assertions. It can be used for
the purpose of accessing data stored under an account assigned to the App
Engine application itself.
This credential does not require a flow to instantiate because it represents
a two legged flow, and therefore has all of the required information to
generate and refresh its own access tokens.
"""
def __init__(self, scope, **kwargs):
"""Constructor for AppAssertionCredentials
Args:
scope: string or list of strings, scope(s) of the credentials being requested.
"""
if type(scope) is list:
scope = ' '.join(scope)
self.scope = scope
super(AppAssertionCredentials, self).__init__(
None,
None,
None)
@classmethod
def from_json(cls, json):
data = simplejson.loads(json)
return AppAssertionCredentials(data['scope'])
def _refresh(self, http_request):
"""Refreshes the access_token.
Since the underlying App Engine app_identity implementation does its own
caching we can skip all the storage hoops and just to a refresh using the
API.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
try:
(token, _) = app_identity.get_access_token(self.scope)
except app_identity.Error, e:
raise AccessTokenRefreshError(str(e))
self.access_token = token
class FlowProperty(db.Property):
"""App Engine datastore Property for Flow.
Utility property that allows easy storage and retreival of an
oauth2client.Flow"""
# Tell what the user type is.
data_type = Flow
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
flow = super(FlowProperty,
self).get_value_for_datastore(model_instance)
return db.Blob(pickle.dumps(flow))
# For reading from datastore.
def make_value_from_datastore(self, value):
if value is None:
return None
return pickle.loads(value)
def validate(self, value):
if value is not None and not isinstance(value, Flow):
raise db.BadValueError('Property %s must be convertible '
'to a FlowThreeLegged instance (%s)' %
(self.name, value))
return super(FlowProperty, self).validate(value)
def empty(self, value):
return not value
class CredentialsProperty(db.Property):
"""App Engine datastore Property for Credentials.
Utility property that allows easy storage and retrieval of
oath2client.Credentials
"""
# Tell what the user type is.
data_type = Credentials
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
logging.info("get: Got type " + str(type(model_instance)))
cred = super(CredentialsProperty,
self).get_value_for_datastore(model_instance)
if cred is None:
cred = ''
else:
cred = cred.to_json()
return db.Blob(cred)
# For reading from datastore.
def make_value_from_datastore(self, value):
logging.info("make: Got type " + str(type(value)))
if value is None:
return None
if len(value) == 0:
return None
try:
credentials = Credentials.new_from_json(value)
except ValueError:
credentials = None
return credentials
def validate(self, value):
value = super(CredentialsProperty, self).validate(value)
logging.info("validate: Got type " + str(type(value)))
if value is not None and not isinstance(value, Credentials):
raise db.BadValueError('Property %s must be convertible '
'to a Credentials instance (%s)' %
(self.name, value))
#if value is not None and not isinstance(value, Credentials):
# return None
return value
class StorageByKeyName(Storage):
"""Store and retrieve a single credential to and from
the App Engine datastore.
This Storage helper presumes the Credentials
have been stored as a CredenialsProperty
on a datastore model class, and that entities
are stored by key_name.
"""
def __init__(self, model, key_name, property_name, cache=None):
"""Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
property_name: string, name of the property that is a CredentialsProperty
cache: memcache, a write-through cache to put in front of the datastore
"""
self._model = model
self._key_name = key_name
self._property_name = property_name
self._cache = cache
def locked_get(self):
"""Retrieve Credential from datastore.
Returns:
oauth2client.Credentials
"""
if self._cache:
json = self._cache.get(self._key_name)
if json:
return Credentials.new_from_json(json)
credential = None
entity = self._model.get_by_key_name(self._key_name)
if entity is not None:
credential = getattr(entity, self._property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self)
if self._cache:
self._cache.set(self._key_name, credential.to_json())
return credential
def locked_put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
entity = self._model.get_or_insert(self._key_name)
setattr(entity, self._property_name, credentials)
entity.put()
if self._cache:
self._cache.set(self._key_name, credentials.to_json())
def locked_delete(self):
"""Delete Credential from datastore."""
if self._cache:
self._cache.delete(self._key_name)
entity = self._model.get_by_key_name(self._key_name)
if entity is not None:
entity.delete()
class CredentialsModel(db.Model):
"""Storage for OAuth 2.0 Credentials
Storage of the model is keyed by the user.user_id().
"""
credentials = CredentialsProperty()
class OAuth2Decorator(object):
"""Utility for making OAuth 2.0 easier.
Instantiate and then use with oauth_required or oauth_aware
as decorators on webapp.RequestHandler methods.
Example:
decorator = OAuth2Decorator(
client_id='837...ent.com',
client_secret='Qh...wwI',
scope='https://www.googleapis.com/auth/plus')
class MainHandler(webapp.RequestHandler):
@decorator.oauth_required
def get(self):
http = decorator.http()
# http is authorized with the user's Credentials and can be used
# in API calls
"""
def __init__(self, client_id, client_secret, scope,
auth_uri='https://accounts.google.com/o/oauth2/auth',
token_uri='https://accounts.google.com/o/oauth2/token',
user_agent=None,
message=None, **kwargs):
"""Constructor for OAuth2Decorator
Args:
client_id: string, client identifier.
client_secret: string client secret.
scope: string or list of strings, scope(s) of the credentials being
requested.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
user_agent: string, User agent of your application, default to None.
message: Message to display if there are problems with the OAuth 2.0
configuration. The message may contain HTML and will be presented on the
web interface for any method that uses the decorator.
**kwargs: dict, Keyword arguments are be passed along as kwargs to the
OAuth2WebServerFlow constructor.
"""
self.flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent,
auth_uri, token_uri, **kwargs)
self.credentials = None
self._request_handler = None
self._message = message
self._in_error = False
def _display_error_message(self, request_handler):
request_handler.response.out.write('<html><body>')
request_handler.response.out.write(self._message)
request_handler.response.out.write('</body></html>')
def oauth_required(self, method):
"""Decorator that starts the OAuth 2.0 dance.
Starts the OAuth dance for the logged in user if they haven't already
granted access for this application.
Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.
"""
def check_oauth(request_handler, *args, **kwargs):
if self._in_error:
self._display_error_message(request_handler)
return
user = users.get_current_user()
# Don't use @login_decorator as this could be used in a POST request.
if not user:
request_handler.redirect(users.create_login_url(
request_handler.request.uri))
return
# Store the request URI in 'state' so we can use it later
self.flow.params['state'] = request_handler.request.url
self._request_handler = request_handler
self.credentials = StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').get()
if not self.has_credentials():
return request_handler.redirect(self.authorize_url())
try:
method(request_handler, *args, **kwargs)
except AccessTokenRefreshError:
return request_handler.redirect(self.authorize_url())
return check_oauth
def oauth_aware(self, method):
"""Decorator that sets up for OAuth 2.0 dance, but doesn't do it.
Does all the setup for the OAuth dance, but doesn't initiate it.
This decorator is useful if you want to create a page that knows
whether or not the user has granted access to this application.
From within a method decorated with @oauth_aware the has_credentials()
and authorize_url() methods can be called.
Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.
"""
def setup_oauth(request_handler, *args, **kwargs):
if self._in_error:
self._display_error_message(request_handler)
return
user = users.get_current_user()
# Don't use @login_decorator as this could be used in a POST request.
if not user:
request_handler.redirect(users.create_login_url(
request_handler.request.uri))
return
self.flow.params['state'] = request_handler.request.url
self._request_handler = request_handler
self.credentials = StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').get()
method(request_handler, *args, **kwargs)
return setup_oauth
def has_credentials(self):
"""True if for the logged in user there are valid access Credentials.
Must only be called from with a webapp.RequestHandler subclassed method
that had been decorated with either @oauth_required or @oauth_aware.
"""
return self.credentials is not None and not self.credentials.invalid
def authorize_url(self):
"""Returns the URL to start the OAuth dance.
Must only be called from with a webapp.RequestHandler subclassed method
that had been decorated with either @oauth_required or @oauth_aware.
"""
callback = self._request_handler.request.relative_url('/oauth2callback')
url = self.flow.step1_get_authorize_url(callback)
user = users.get_current_user()
memcache.set(user.user_id(), pickle.dumps(self.flow),
namespace=OAUTH2CLIENT_NAMESPACE)
return str(url)
def http(self):
"""Returns an authorized http instance.
Must only be called from within an @oauth_required decorated method, or
from within an @oauth_aware decorated method where has_credentials()
returns True.
"""
return self.credentials.authorize(httplib2.Http())
class OAuth2DecoratorFromClientSecrets(OAuth2Decorator):
"""An OAuth2Decorator that builds from a clientsecrets file.
Uses a clientsecrets file as the source for all the information when
constructing an OAuth2Decorator.
Example:
decorator = OAuth2DecoratorFromClientSecrets(
os.path.join(os.path.dirname(__file__), 'client_secrets.json')
scope='https://www.googleapis.com/auth/plus')
class MainHandler(webapp.RequestHandler):
@decorator.oauth_required
def get(self):
http = decorator.http()
# http is authorized with the user's Credentials and can be used
# in API calls
"""
def __init__(self, filename, scope, message=None):
"""Constructor
Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) of the credentials being
requested.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. The message may contain HTML and
will be presented on the web interface for any method that uses the
decorator.
"""
try:
client_type, client_info = clientsecrets.loadfile(filename)
if client_type not in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]:
raise InvalidClientSecretsError('OAuth2Decorator doesn\'t support this OAuth 2.0 flow.')
super(OAuth2DecoratorFromClientSecrets,
self).__init__(
client_info['client_id'],
client_info['client_secret'],
scope,
client_info['auth_uri'],
client_info['token_uri'],
message)
except clientsecrets.InvalidClientSecretsError:
self._in_error = True
if message is not None:
self._message = message
else:
self._message = "Please configure your application for OAuth 2.0"
def oauth2decorator_from_clientsecrets(filename, scope, message=None):
"""Creates an OAuth2Decorator populated from a clientsecrets file.
Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) of the credentials being
requested.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. The message may contain HTML and
will be presented on the web interface for any method that uses the
decorator.
Returns: An OAuth2Decorator
"""
return OAuth2DecoratorFromClientSecrets(filename, scope, message)
class OAuth2Handler(webapp.RequestHandler):
"""Handler for the redirect_uri of the OAuth 2.0 dance."""
@login_required
def get(self):
error = self.request.get('error')
if error:
errormsg = self.request.get('error_description', error)
self.response.out.write(
'The authorization request failed: %s' % errormsg)
else:
user = users.get_current_user()
flow = pickle.loads(memcache.get(user.user_id(),
namespace=OAUTH2CLIENT_NAMESPACE))
# This code should be ammended with application specific error
# handling. The following cases should be considered:
# 1. What if the flow doesn't exist in memcache? Or is corrupt?
# 2. What if the step2_exchange fails?
if flow:
credentials = flow.step2_exchange(self.request.params)
StorageByKeyName(
CredentialsModel, user.user_id(), 'credentials').put(credentials)
self.redirect(str(self.request.get('state')))
else:
# TODO Add error handling here.
pass
application = webapp.WSGIApplication([('/oauth2callback', OAuth2Handler)])
def main():
run_wsgi_app(application)
| Python |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import hashlib
import logging
import time
from OpenSSL import crypto
from anyjson import simplejson
CLOCK_SKEW_SECS = 300 # 5 minutes in seconds
AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds
MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds
class AppIdentityError(Exception):
pass
class Verifier(object):
"""Verifies the signature on a message."""
def __init__(self, pubkey):
"""Constructor.
Args:
pubkey, OpenSSL.crypto.PKey, The public key to verify with.
"""
self._pubkey = pubkey
def verify(self, message, signature):
"""Verifies a message against a signature.
Args:
message: string, The message to verify.
signature: string, The signature on the message.
Returns:
True if message was singed by the private key associated with the public
key that this object was constructed with.
"""
try:
crypto.verify(self._pubkey, signature, message, 'sha256')
return True
except:
return False
@staticmethod
def from_string(key_pem, is_x509_cert):
"""Construct a Verified instance from a string.
Args:
key_pem: string, public key in PEM format.
is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is
expected to be an RSA key in PEM format.
Returns:
Verifier instance.
Raises:
OpenSSL.crypto.Error if the key_pem can't be parsed.
"""
if is_x509_cert:
pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
else:
pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
return Verifier(pubkey)
class Signer(object):
"""Signs messages with a private key."""
def __init__(self, pkey):
"""Constructor.
Args:
pkey, OpenSSL.crypto.PKey, The private key to sign with.
"""
self._key = pkey
def sign(self, message):
"""Signs a message.
Args:
message: string, Message to be signed.
Returns:
string, The signature of the message for the given key.
"""
return crypto.sign(self._key, message, 'sha256')
@staticmethod
def from_string(key, password='notasecret'):
"""Construct a Signer instance from a string.
Args:
key: string, private key in P12 format.
password: string, password for the private key file.
Returns:
Signer instance.
Raises:
OpenSSL.crypto.Error if the key can't be parsed.
"""
pkey = crypto.load_pkcs12(key, password).get_privatekey()
return Signer(pkey)
def _urlsafe_b64encode(raw_bytes):
return base64.urlsafe_b64encode(raw_bytes).rstrip('=')
def _urlsafe_b64decode(b64string):
# Guard against unicode strings, which base64 can't handle.
b64string = b64string.encode('ascii')
padded = b64string + '=' * (4 - len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
def _json_encode(data):
return simplejson.dumps(data, separators = (',', ':'))
def make_signed_jwt(signer, payload):
"""Make a signed JWT.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
Args:
signer: crypt.Signer, Cryptographic signer.
payload: dict, Dictionary of data to convert to JSON and then sign.
Returns:
string, The JWT for the payload.
"""
header = {'typ': 'JWT', 'alg': 'RS256'}
segments = [
_urlsafe_b64encode(_json_encode(header)),
_urlsafe_b64encode(_json_encode(payload)),
]
signing_input = '.'.join(segments)
signature = signer.sign(signing_input)
segments.append(_urlsafe_b64encode(signature))
logging.debug(str(segments))
return '.'.join(segments)
def verify_signed_jwt_with_certs(jwt, certs, audience):
"""Verify a JWT against public certs.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
Args:
jwt: string, A JWT.
certs: dict, Dictionary where values of public keys in PEM format.
audience: string, The audience, 'aud', that this JWT should contain. If
None then the JWT's 'aud' parameter is not verified.
Returns:
dict, The deserialized JSON payload in the JWT.
Raises:
AppIdentityError if any checks are failed.
"""
segments = jwt.split('.')
if (len(segments) != 3):
raise AppIdentityError(
'Wrong number of segments in token: %s' % jwt)
signed = '%s.%s' % (segments[0], segments[1])
signature = _urlsafe_b64decode(segments[2])
# Parse token.
json_body = _urlsafe_b64decode(segments[1])
try:
parsed = simplejson.loads(json_body)
except:
raise AppIdentityError('Can\'t parse token: %s' % json_body)
# Check signature.
verified = False
for (keyname, pem) in certs.items():
verifier = Verifier.from_string(pem, True)
if (verifier.verify(signed, signature)):
verified = True
break
if not verified:
raise AppIdentityError('Invalid token signature: %s' % jwt)
# Check creation timestamp.
iat = parsed.get('iat')
if iat is None:
raise AppIdentityError('No iat field in token: %s' % json_body)
earliest = iat - CLOCK_SKEW_SECS
# Check expiration timestamp.
now = long(time.time())
exp = parsed.get('exp')
if exp is None:
raise AppIdentityError('No exp field in token: %s' % json_body)
if exp >= now + MAX_TOKEN_LIFETIME_SECS:
raise AppIdentityError(
'exp field too far in future: %s' % json_body)
latest = exp + CLOCK_SKEW_SECS
if now < earliest:
raise AppIdentityError('Token used too early, %d < %d: %s' %
(now, earliest, json_body))
if now > latest:
raise AppIdentityError('Token used too late, %d > %d: %s' %
(now, latest, json_body))
# Check audience.
if audience is not None:
aud = parsed.get('aud')
if aud is None:
raise AppIdentityError('No aud field in token: %s' % json_body)
if aud != audience:
raise AppIdentityError('Wrong recipient, %s != %s: %s' %
(aud, audience, json_body))
return parsed
| Python |
# Copyright 2011 Google Inc. All Rights Reserved.
"""Locked file interface that should work on Unix and Windows pythons.
This module first tries to use fcntl locking to ensure serialized access
to a file, then falls back on a lock file if that is unavialable.
Usage:
f = LockedFile('filename', 'r+b', 'rb')
f.open_and_lock()
if f.is_locked():
print 'Acquired filename with r+b mode'
f.file_handle().write('locked data')
else:
print 'Aquired filename with rb mode'
f.unlock_and_close()
"""
__author__ = 'cache@google.com (David T McWherter)'
import errno
import logging
import os
import time
logger = logging.getLogger(__name__)
class AlreadyLockedException(Exception):
"""Trying to lock a file that has already been locked by the LockedFile."""
pass
class _Opener(object):
"""Base class for different locking primitives."""
def __init__(self, filename, mode, fallback_mode):
"""Create an Opener.
Args:
filename: string, The pathname of the file.
mode: string, The preferred mode to access the file with.
fallback_mode: string, The mode to use if locking fails.
"""
self._locked = False
self._filename = filename
self._mode = mode
self._fallback_mode = fallback_mode
self._fh = None
def is_locked(self):
"""Was the file locked."""
return self._locked
def file_handle(self):
"""The file handle to the file. Valid only after opened."""
return self._fh
def filename(self):
"""The filename that is being locked."""
return self._filename
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries.
"""
pass
def unlock_and_close(self):
"""Unlock and close the file."""
pass
class _PosixOpener(_Opener):
"""Lock files using Posix advisory lock files."""
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Tries to create a .lock file next to the file we're trying to open.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries.
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
self._locked = False
try:
self._fh = open(self._filename, self._mode)
except IOError, e:
# If we can't access with _mode, try _fallback_mode and don't lock.
if e.errno == errno.EACCES:
self._fh = open(self._filename, self._fallback_mode)
return
lock_filename = self._posix_lockfile(self._filename)
start_time = time.time()
while True:
try:
self._lock_fd = os.open(lock_filename,
os.O_CREAT|os.O_EXCL|os.O_RDWR)
self._locked = True
break
except OSError, e:
if e.errno != errno.EEXIST:
raise
if (time.time() - start_time) >= timeout:
logger.warn('Could not acquire lock %s in %s seconds' % (
lock_filename, timeout))
# Close the file and open in fallback_mode.
if self._fh:
self._fh.close()
self._fh = open(self._filename, self._fallback_mode)
return
time.sleep(delay)
def unlock_and_close(self):
"""Unlock a file by removing the .lock file, and close the handle."""
if self._locked:
lock_filename = self._posix_lockfile(self._filename)
os.unlink(lock_filename)
os.close(self._lock_fd)
self._locked = False
self._lock_fd = None
if self._fh:
self._fh.close()
def _posix_lockfile(self, filename):
"""The name of the lock file to use for posix locking."""
return '%s.lock' % filename
try:
import fcntl
class _FcntlOpener(_Opener):
"""Open, lock, and unlock a file using fcntl.lockf."""
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
start_time = time.time()
try:
self._fh = open(self._filename, self._mode)
except IOError, e:
# If we can't access with _mode, try _fallback_mode and don't lock.
if e.errno == errno.EACCES:
self._fh = open(self._filename, self._fallback_mode)
return
# We opened in _mode, try to lock the file.
while True:
try:
fcntl.lockf(self._fh.fileno(), fcntl.LOCK_EX)
self._locked = True
return
except IOError, e:
# If not retrying, then just pass on the error.
if timeout == 0:
raise e
if e.errno != errno.EACCES:
raise e
# We could not acquire the lock. Try again.
if (time.time() - start_time) >= timeout:
logger.warn('Could not lock %s in %s seconds' % (
self._filename, timeout))
if self._fh:
self._fh.close()
self._fh = open(self._filename, self._fallback_mode)
return
time.sleep(delay)
def unlock_and_close(self):
"""Close and unlock the file using the fcntl.lockf primitive."""
if self._locked:
fcntl.lockf(self._fh.fileno(), fcntl.LOCK_UN)
self._locked = False
if self._fh:
self._fh.close()
except ImportError:
_FcntlOpener = None
try:
import pywintypes
import win32con
import win32file
class _Win32Opener(_Opener):
"""Open, lock, and unlock a file using windows primitives."""
# Error #33:
# 'The process cannot access the file because another process'
FILE_IN_USE_ERROR = 33
# Error #158:
# 'The segment is already unlocked.'
FILE_ALREADY_UNLOCKED_ERROR = 158
def open_and_lock(self, timeout, delay):
"""Open the file and lock it.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
start_time = time.time()
try:
self._fh = open(self._filename, self._mode)
except IOError, e:
# If we can't access with _mode, try _fallback_mode and don't lock.
if e.errno == errno.EACCES:
self._fh = open(self._filename, self._fallback_mode)
return
# We opened in _mode, try to lock the file.
while True:
try:
hfile = win32file._get_osfhandle(self._fh.fileno())
win32file.LockFileEx(
hfile,
(win32con.LOCKFILE_FAIL_IMMEDIATELY|
win32con.LOCKFILE_EXCLUSIVE_LOCK), 0, -0x10000,
pywintypes.OVERLAPPED())
self._locked = True
return
except pywintypes.error, e:
if timeout == 0:
raise e
# If the error is not that the file is already in use, raise.
if e[0] != _Win32Opener.FILE_IN_USE_ERROR:
raise
# We could not acquire the lock. Try again.
if (time.time() - start_time) >= timeout:
logger.warn('Could not lock %s in %s seconds' % (
self._filename, timeout))
if self._fh:
self._fh.close()
self._fh = open(self._filename, self._fallback_mode)
return
time.sleep(delay)
def unlock_and_close(self):
"""Close and unlock the file using the win32 primitive."""
if self._locked:
try:
hfile = win32file._get_osfhandle(self._fh.fileno())
win32file.UnlockFileEx(hfile, 0, -0x10000, pywintypes.OVERLAPPED())
except pywintypes.error, e:
if e[0] != _Win32Opener.FILE_ALREADY_UNLOCKED_ERROR:
raise
self._locked = False
if self._fh:
self._fh.close()
except ImportError:
_Win32Opener = None
class LockedFile(object):
"""Represent a file that has exclusive access."""
def __init__(self, filename, mode, fallback_mode, use_native_locking=True):
"""Construct a LockedFile.
Args:
filename: string, The path of the file to open.
mode: string, The mode to try to open the file with.
fallback_mode: string, The mode to use if locking fails.
use_native_locking: bool, Whether or not fcntl/win32 locking is used.
"""
opener = None
if not opener and use_native_locking:
if _Win32Opener:
opener = _Win32Opener(filename, mode, fallback_mode)
if _FcntlOpener:
opener = _FcntlOpener(filename, mode, fallback_mode)
if not opener:
opener = _PosixOpener(filename, mode, fallback_mode)
self._opener = opener
def filename(self):
"""Return the filename we were constructed with."""
return self._opener._filename
def file_handle(self):
"""Return the file_handle to the opened file."""
return self._opener.file_handle()
def is_locked(self):
"""Return whether we successfully locked the file."""
return self._opener.is_locked()
def open_and_lock(self, timeout=0, delay=0.05):
"""Open the file, trying to lock it.
Args:
timeout: float, The number of seconds to try to acquire the lock.
delay: float, The number of seconds to wait between retry attempts.
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.
"""
self._opener.open_and_lock(timeout, delay)
def unlock_and_close(self):
"""Unlock and close a file."""
self._opener.unlock_and_close()
| Python |
# Copyright 2011 Google Inc. All Rights Reserved.
"""Multi-credential file store with lock support.
This module implements a JSON credential store where multiple
credentials can be stored in one file. That file supports locking
both in a single process and across processes.
The credential themselves are keyed off of:
* client_id
* user_agent
* scope
The format of the stored data is like so:
{
'file_version': 1,
'data': [
{
'key': {
'clientId': '<client id>',
'userAgent': '<user agent>',
'scope': '<scope>'
},
'credential': {
# JSON serialized Credentials.
}
}
]
}
"""
__author__ = 'jbeda@google.com (Joe Beda)'
import base64
import errno
import logging
import os
import threading
from anyjson import simplejson
from client import Storage as BaseStorage
from client import Credentials
from locked_file import LockedFile
logger = logging.getLogger(__name__)
# A dict from 'filename'->_MultiStore instances
_multistores = {}
_multistores_lock = threading.Lock()
class Error(Exception):
"""Base error for this module."""
pass
class NewerCredentialStoreError(Error):
"""The credential store is a newer version that supported."""
pass
def get_credential_storage(filename, client_id, user_agent, scope,
warn_on_readonly=True):
"""Get a Storage instance for a credential.
Args:
filename: The JSON file storing a set of credentials
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: string or list of strings, Scope(s) being requested
warn_on_readonly: if True, log a warning if the store is readonly
Returns:
An object derived from client.Storage for getting/setting the
credential.
"""
filename = os.path.realpath(os.path.expanduser(filename))
_multistores_lock.acquire()
try:
multistore = _multistores.setdefault(
filename, _MultiStore(filename, warn_on_readonly))
finally:
_multistores_lock.release()
if type(scope) is list:
scope = ' '.join(scope)
return multistore._get_storage(client_id, user_agent, scope)
class _MultiStore(object):
"""A file backed store for multiple credentials."""
def __init__(self, filename, warn_on_readonly=True):
"""Initialize the class.
This will create the file if necessary.
"""
self._file = LockedFile(filename, 'r+b', 'rb')
self._thread_lock = threading.Lock()
self._read_only = False
self._warn_on_readonly = warn_on_readonly
self._create_file_if_needed()
# Cache of deserialized store. This is only valid after the
# _MultiStore is locked or _refresh_data_cache is called. This is
# of the form of:
#
# (client_id, user_agent, scope) -> OAuth2Credential
#
# If this is None, then the store hasn't been read yet.
self._data = None
class _Storage(BaseStorage):
"""A Storage object that knows how to read/write a single credential."""
def __init__(self, multistore, client_id, user_agent, scope):
self._multistore = multistore
self._client_id = client_id
self._user_agent = user_agent
self._scope = scope
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant.
"""
self._multistore._lock()
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
self._multistore._unlock()
def locked_get(self):
"""Retrieve credential.
The Storage lock must be held when this is called.
Returns:
oauth2client.client.Credentials
"""
credential = self._multistore._get_credential(
self._client_id, self._user_agent, self._scope)
if credential:
credential.set_store(self)
return credential
def locked_put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self._multistore._update_credential(credentials, self._scope)
def locked_delete(self):
"""Delete a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self._multistore._delete_credential(self._client_id, self._user_agent,
self._scope)
def _create_file_if_needed(self):
"""Create an empty file if necessary.
This method will not initialize the file. Instead it implements a
simple version of "touch" to ensure the file has been created.
"""
if not os.path.exists(self._file.filename()):
old_umask = os.umask(0177)
try:
open(self._file.filename(), 'a+b').close()
finally:
os.umask(old_umask)
def _lock(self):
"""Lock the entire multistore."""
self._thread_lock.acquire()
self._file.open_and_lock()
if not self._file.is_locked():
self._read_only = True
if self._warn_on_readonly:
logger.warn('The credentials file (%s) is not writable. Opening in '
'read-only mode. Any refreshed credentials will only be '
'valid for this run.' % self._file.filename())
if os.path.getsize(self._file.filename()) == 0:
logger.debug('Initializing empty multistore file')
# The multistore is empty so write out an empty file.
self._data = {}
self._write()
elif not self._read_only or self._data is None:
# Only refresh the data if we are read/write or we haven't
# cached the data yet. If we are readonly, we assume is isn't
# changing out from under us and that we only have to read it
# once. This prevents us from whacking any new access keys that
# we have cached in memory but were unable to write out.
self._refresh_data_cache()
def _unlock(self):
"""Release the lock on the multistore."""
self._file.unlock_and_close()
self._thread_lock.release()
def _locked_json_read(self):
"""Get the raw content of the multistore file.
The multistore must be locked when this is called.
Returns:
The contents of the multistore decoded as JSON.
"""
assert self._thread_lock.locked()
self._file.file_handle().seek(0)
return simplejson.load(self._file.file_handle())
def _locked_json_write(self, data):
"""Write a JSON serializable data structure to the multistore.
The multistore must be locked when this is called.
Args:
data: The data to be serialized and written.
"""
assert self._thread_lock.locked()
if self._read_only:
return
self._file.file_handle().seek(0)
simplejson.dump(data, self._file.file_handle(), sort_keys=True, indent=2)
self._file.file_handle().truncate()
def _refresh_data_cache(self):
"""Refresh the contents of the multistore.
The multistore must be locked when this is called.
Raises:
NewerCredentialStoreError: Raised when a newer client has written the
store.
"""
self._data = {}
try:
raw_data = self._locked_json_read()
except Exception:
logger.warn('Credential data store could not be loaded. '
'Will ignore and overwrite.')
return
version = 0
try:
version = raw_data['file_version']
except Exception:
logger.warn('Missing version for credential data store. It may be '
'corrupt or an old version. Overwriting.')
if version > 1:
raise NewerCredentialStoreError(
'Credential file has file_version of %d. '
'Only file_version of 1 is supported.' % version)
credentials = []
try:
credentials = raw_data['data']
except (TypeError, KeyError):
pass
for cred_entry in credentials:
try:
(key, credential) = self._decode_credential_from_json(cred_entry)
self._data[key] = credential
except:
# If something goes wrong loading a credential, just ignore it
logger.info('Error decoding credential, skipping', exc_info=True)
def _decode_credential_from_json(self, cred_entry):
"""Load a credential from our JSON serialization.
Args:
cred_entry: A dict entry from the data member of our format
Returns:
(key, cred) where the key is the key tuple and the cred is the
OAuth2Credential object.
"""
raw_key = cred_entry['key']
client_id = raw_key['clientId']
user_agent = raw_key['userAgent']
scope = raw_key['scope']
key = (client_id, user_agent, scope)
credential = None
credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential']))
return (key, credential)
def _write(self):
"""Write the cached data back out.
The multistore must be locked.
"""
raw_data = {'file_version': 1}
raw_creds = []
raw_data['data'] = raw_creds
for (cred_key, cred) in self._data.items():
raw_key = {
'clientId': cred_key[0],
'userAgent': cred_key[1],
'scope': cred_key[2]
}
raw_cred = simplejson.loads(cred.to_json())
raw_creds.append({'key': raw_key, 'credential': raw_cred})
self._locked_json_write(raw_data)
def _get_credential(self, client_id, user_agent, scope):
"""Get a credential from the multistore.
The multistore must be locked.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: A string for the scope(s) being requested
Returns:
The credential specified or None if not present
"""
key = (client_id, user_agent, scope)
return self._data.get(key, None)
def _update_credential(self, cred, scope):
"""Update a credential and write the multistore.
This must be called when the multistore is locked.
Args:
cred: The OAuth2Credential to update/set
scope: The scope(s) that this credential covers
"""
key = (cred.client_id, cred.user_agent, scope)
self._data[key] = cred
self._write()
def _delete_credential(self, client_id, user_agent, scope):
"""Delete a credential and write the multistore.
This must be called when the multistore is locked.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: The scope(s) that this credential covers
"""
key = (client_id, user_agent, scope)
try:
del self._data[key]
except KeyError:
pass
self._write()
def _get_storage(self, client_id, user_agent, scope):
"""Get a Storage object to get/set a credential.
This Storage is a 'view' into the multistore.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: A string for the scope(s) being requested
Returns:
A Storage object that can be used to get/set this cred
"""
return self._Storage(self, client_id, user_agent, scope)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility module to import a JSON module
Hides all the messy details of exactly where
we get a simplejson module from.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
try: # pragma: no cover
# Should work for Python2.6 and higher.
import json as simplejson
except ImportError: # pragma: no cover
try:
import simplejson
except ImportError:
# Try to import from django, should work on App Engine
from django.utils import simplejson
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command-line tools for authenticating via OAuth 2.0
Do the OAuth 2.0 Web Server dance for a command line application. Stores the
generated credentials in a common file that is used by other example apps in
the same directory.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
__all__ = ['run']
import BaseHTTPServer
import gflags
import socket
import sys
import webbrowser
from client import FlowExchangeError
from client import OOB_CALLBACK_URN
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('auth_local_webserver', True,
('Run a local web server to handle redirects during '
'OAuth authorization.'))
gflags.DEFINE_string('auth_host_name', 'localhost',
('Host name to use when running a local web server to '
'handle redirects during OAuth authorization.'))
gflags.DEFINE_multi_int('auth_host_port', [8080, 8090],
('Port to use when running a local web server to '
'handle redirects during OAuth authorization.'))
class ClientRedirectServer(BaseHTTPServer.HTTPServer):
"""A server to handle OAuth 2.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into query_params and then stops serving.
"""
query_params = {}
class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""A handler for OAuth 2.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into the servers query_params and then stops serving.
"""
def do_GET(s):
"""Handle a GET request.
Parses the query parameters and prints a message
if the flow has completed. Note that we can't detect
if an error occurred.
"""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
query = s.path.split('?', 1)[-1]
query = dict(parse_qsl(query))
s.server.query_params = query
s.wfile.write("<html><head><title>Authentication Status</title></head>")
s.wfile.write("<body><p>The authentication flow has completed.</p>")
s.wfile.write("</body></html>")
def log_message(self, format, *args):
"""Do not log messages to stdout while running as command line program."""
pass
def run(flow, storage, http=None):
"""Core code for a command-line application.
Args:
flow: Flow, an OAuth 2.0 Flow to step through.
storage: Storage, a Storage to store the credential in.
http: An instance of httplib2.Http.request
or something that acts like it.
Returns:
Credentials, the obtained credential.
"""
if FLAGS.auth_local_webserver:
success = False
port_number = 0
for port in FLAGS.auth_host_port:
port_number = port
try:
httpd = ClientRedirectServer((FLAGS.auth_host_name, port),
ClientRedirectHandler)
except socket.error, e:
pass
else:
success = True
break
FLAGS.auth_local_webserver = success
if not success:
print 'Failed to start a local webserver listening on either port 8080'
print 'or port 9090. Please check your firewall settings and locally'
print 'running programs that may be blocking or using those ports.'
print
print 'Falling back to --noauth_local_webserver and continuing with',
print 'authorization.'
print
if FLAGS.auth_local_webserver:
oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
else:
oauth_callback = OOB_CALLBACK_URN
authorize_url = flow.step1_get_authorize_url(oauth_callback)
if FLAGS.auth_local_webserver:
webbrowser.open(authorize_url, new=1, autoraise=True)
print 'Your browser has been opened to visit:'
print
print ' ' + authorize_url
print
print 'If your browser is on a different machine then exit and re-run this'
print 'application with the command-line parameter '
print
print ' --noauth_local_webserver'
print
else:
print 'Go to the following link in your browser:'
print
print ' ' + authorize_url
print
code = None
if FLAGS.auth_local_webserver:
httpd.handle_request()
if 'error' in httpd.query_params:
sys.exit('Authentication request was rejected.')
if 'code' in httpd.query_params:
code = httpd.query_params['code']
else:
print 'Failed to find "code" in the query parameters of the redirect.'
sys.exit('Try running with --noauth_local_webserver.')
else:
code = raw_input('Enter verification code: ').strip()
try:
credential = flow.step2_exchange(code, http)
except FlowExchangeError, e:
sys.exit('Authentication has failed: %s' % e)
storage.put(credential)
credential.set_store(storage)
print 'Authentication successful.'
return credential
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""An OAuth 2.0 client.
Tools for interacting with OAuth 2.0 protected resources.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import base64
import clientsecrets
import copy
import datetime
import httplib2
import logging
import os
import sys
import time
import urllib
import urlparse
from anyjson import simplejson
HAS_OPENSSL = False
try:
from oauth2client.crypt import Signer
from oauth2client.crypt import make_signed_jwt
from oauth2client.crypt import verify_signed_jwt_with_certs
HAS_OPENSSL = True
except ImportError:
pass
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
logger = logging.getLogger(__name__)
# Expiry is stored in RFC3339 UTC format
EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
# Which certs to use to validate id_tokens received.
ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs'
# Constant to use for the out of band OAuth 2.0 flow.
OOB_CALLBACK_URN = 'urn:ietf:wg:oauth:2.0:oob'
class Error(Exception):
"""Base error for this module."""
pass
class FlowExchangeError(Error):
"""Error trying to exchange an authorization grant for an access token."""
pass
class AccessTokenRefreshError(Error):
"""Error trying to refresh an expired access token."""
pass
class UnknownClientSecretsFlowError(Error):
"""The client secrets file called for an unknown type of OAuth 2.0 flow. """
pass
class AccessTokenCredentialsError(Error):
"""Having only the access_token means no refresh is possible."""
pass
class VerifyJwtTokenError(Error):
"""Could on retrieve certificates for validation."""
pass
def _abstract():
raise NotImplementedError('You need to override this function')
class MemoryCache(object):
"""httplib2 Cache implementation which only caches locally."""
def __init__(self):
self.cache = {}
def get(self, key):
return self.cache.get(key)
def set(self, key, value):
self.cache[key] = value
def delete(self, key):
self.cache.pop(key, None)
class Credentials(object):
"""Base class for all Credentials objects.
Subclasses must define an authorize() method that applies the credentials to
an HTTP transport.
Subclasses must also specify a classmethod named 'from_json' that takes a JSON
string as input and returns an instaniated Credentials object.
"""
NON_SERIALIZED_MEMBERS = ['store']
def authorize(self, http):
"""Take an httplib2.Http instance (or equivalent) and
authorizes it for the set of credentials, usually by
replacing http.request() with a method that adds in
the appropriate headers and then delegates to the original
Http.request() method.
"""
_abstract()
def refresh(self, http):
"""Forces a refresh of the access_token.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
"""
_abstract()
def apply(self, headers):
"""Add the authorization to the headers.
Args:
headers: dict, the headers to add the Authorization header to.
"""
_abstract()
def _to_json(self, strip):
"""Utility function for creating a JSON representation of an instance of Credentials.
Args:
strip: array, An array of names of members to not include in the JSON.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
t = type(self)
d = copy.copy(self.__dict__)
for member in strip:
if member in d:
del d[member]
if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime):
d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT)
# Add in information we will need later to reconsistitue this instance.
d['_class'] = t.__name__
d['_module'] = t.__module__
return simplejson.dumps(d)
def to_json(self):
"""Creating a JSON representation of an instance of Credentials.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)
@classmethod
def new_from_json(cls, s):
"""Utility class method to instantiate a Credentials subclass from a JSON
representation produced by to_json().
Args:
s: string, JSON from to_json().
Returns:
An instance of the subclass of Credentials that was serialized with
to_json().
"""
data = simplejson.loads(s)
# Find and call the right classmethod from_json() to restore the object.
module = data['_module']
try:
m = __import__(module)
except ImportError:
# In case there's an object from the old package structure, update it
module = module.replace('.apiclient', '')
m = __import__(module)
m = __import__(module, fromlist=module.split('.')[:-1])
kls = getattr(m, data['_class'])
from_json = getattr(kls, 'from_json')
return from_json(s)
@classmethod
def from_json(cls, s):
"""Instantiate a Credentials object from a JSON description of it.
The JSON should have been produced by calling .to_json() on the object.
Args:
data: dict, A deserialized JSON object.
Returns:
An instance of a Credentials subclass.
"""
return Credentials()
class Flow(object):
"""Base class for all Flow objects."""
pass
class Storage(object):
"""Base class for all Storage objects.
Store and retrieve a single credential. This class supports locking
such that multiple processes and threads can operate on a single
store.
"""
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant.
"""
pass
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
pass
def locked_get(self):
"""Retrieve credential.
The Storage lock must be held when this is called.
Returns:
oauth2client.client.Credentials
"""
_abstract()
def locked_put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
_abstract()
def locked_delete(self):
"""Delete a credential.
The Storage lock must be held when this is called.
"""
_abstract()
def get(self):
"""Retrieve credential.
The Storage lock must *not* be held when this is called.
Returns:
oauth2client.client.Credentials
"""
self.acquire_lock()
try:
return self.locked_get()
finally:
self.release_lock()
def put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self.acquire_lock()
try:
self.locked_put(credentials)
finally:
self.release_lock()
def delete(self):
"""Delete credential.
Frees any resources associated with storing the credential.
The Storage lock must *not* be held when this is called.
Returns:
None
"""
self.acquire_lock()
try:
return self.locked_delete()
finally:
self.release_lock()
class OAuth2Credentials(Credentials):
"""Credentials object for OAuth 2.0.
Credentials can be applied to an httplib2.Http object using the authorize()
method, which then adds the OAuth 2.0 access token to each request.
OAuth2Credentials objects may be safely pickled and unpickled.
"""
def __init__(self, access_token, client_id, client_secret, refresh_token,
token_expiry, token_uri, user_agent, id_token=None):
"""Create an instance of OAuth2Credentials.
This constructor is not usually called by the user, instead
OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow.
Args:
access_token: string, access token.
client_id: string, client identifier.
client_secret: string, client secret.
refresh_token: string, refresh token.
token_expiry: datetime, when the access_token expires.
token_uri: string, URI of token endpoint.
user_agent: string, The HTTP User-Agent to provide for this application.
id_token: object, The identity of the resource owner.
Notes:
store: callable, A callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has expired and been refreshed.
"""
self.access_token = access_token
self.client_id = client_id
self.client_secret = client_secret
self.refresh_token = refresh_token
self.store = None
self.token_expiry = token_expiry
self.token_uri = token_uri
self.user_agent = user_agent
self.id_token = id_token
# True if the credentials have been revoked or expired and can't be
# refreshed.
self.invalid = False
def authorize(self, http):
"""Authorize an httplib2.Http instance with these credentials.
The modified http.request method will add authentication headers to each
request and will refresh access_tokens when a 401 is received on a
request. In addition the http.request method has a credentials property,
http.request.credentials, which is the Credentials object that authorized
it.
Args:
http: An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth subclass of httplib2.Authenication
because it never gets passed the absolute URI, which is needed for
signing. So instead we have to overload 'request' with a closure
that adds in the Authorization header and then calls the original
version of 'request()'.
"""
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
if not self.access_token:
logger.info('Attempting refresh to obtain initial access_token')
self._refresh(request_orig)
# Modify the request headers to add the appropriate
# Authorization header.
if headers is None:
headers = {}
self.apply(headers)
if self.user_agent is not None:
if 'user-agent' in headers:
headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = self.user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
if resp.status == 401:
logger.info('Refreshing due to a 401')
self._refresh(request_orig)
self.apply(headers)
return request_orig(uri, method, body, headers,
redirections, connection_type)
else:
return (resp, content)
# Replace the request method with our own closure.
http.request = new_request
# Set credentials as a property of the request method.
setattr(http.request, 'credentials', self)
return http
def refresh(self, http):
"""Forces a refresh of the access_token.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
"""
self._refresh(http.request)
def apply(self, headers):
"""Add the authorization to the headers.
Args:
headers: dict, the headers to add the Authorization header to.
"""
headers['Authorization'] = 'Bearer ' + self.access_token
def to_json(self):
return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)
@classmethod
def from_json(cls, s):
"""Instantiate a Credentials object from a JSON description of it. The JSON
should have been produced by calling .to_json() on the object.
Args:
data: dict, A deserialized JSON object.
Returns:
An instance of a Credentials subclass.
"""
data = simplejson.loads(s)
if 'token_expiry' in data and not isinstance(data['token_expiry'],
datetime.datetime):
try:
data['token_expiry'] = datetime.datetime.strptime(
data['token_expiry'], EXPIRY_FORMAT)
except:
data['token_expiry'] = None
retval = OAuth2Credentials(
data['access_token'],
data['client_id'],
data['client_secret'],
data['refresh_token'],
data['token_expiry'],
data['token_uri'],
data['user_agent'],
data.get('id_token', None))
retval.invalid = data['invalid']
return retval
@property
def access_token_expired(self):
"""True if the credential is expired or invalid.
If the token_expiry isn't set, we assume the token doesn't expire.
"""
if self.invalid:
return True
if not self.token_expiry:
return False
now = datetime.datetime.utcnow()
if now >= self.token_expiry:
logger.info('access_token is expired. Now: %s, token_expiry: %s',
now, self.token_expiry)
return True
return False
def set_store(self, store):
"""Set the Storage for the credential.
Args:
store: Storage, an implementation of Stroage object.
This is needed to store the latest access_token if it
has expired and been refreshed. This implementation uses
locking to check for updates before updating the
access_token.
"""
self.store = store
def _updateFromCredential(self, other):
"""Update this Credential from another instance."""
self.__dict__.update(other.__getstate__())
def __getstate__(self):
"""Trim the state down to something that can be pickled."""
d = copy.copy(self.__dict__)
del d['store']
return d
def __setstate__(self, state):
"""Reconstitute the state of the object from being pickled."""
self.__dict__.update(state)
self.store = None
def _generate_refresh_request_body(self):
"""Generate the body that will be used in the refresh request."""
body = urllib.urlencode({
'grant_type': 'refresh_token',
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token,
})
return body
def _generate_refresh_request_headers(self):
"""Generate the headers that will be used in the refresh request."""
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if self.user_agent is not None:
headers['user-agent'] = self.user_agent
return headers
def _refresh(self, http_request):
"""Refreshes the access_token.
This method first checks by reading the Storage object if available.
If a refresh is still needed, it holds the Storage lock until the
refresh is completed.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
if not self.store:
self._do_refresh_request(http_request)
else:
self.store.acquire_lock()
try:
new_cred = self.store.locked_get()
if (new_cred and not new_cred.invalid and
new_cred.access_token != self.access_token):
logger.info('Updated access_token read from Storage')
self._updateFromCredential(new_cred)
else:
self._do_refresh_request(http_request)
finally:
self.store.release_lock()
def _do_refresh_request(self, http_request):
"""Refresh the access_token using the refresh_token.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
body = self._generate_refresh_request_body()
headers = self._generate_refresh_request_headers()
logger.info('Refreshing access_token')
resp, content = http_request(
self.token_uri, method='POST', body=body, headers=headers)
if resp.status == 200:
# TODO(jcgregorio) Raise an error if loads fails?
d = simplejson.loads(content)
self.access_token = d['access_token']
self.refresh_token = d.get('refresh_token', self.refresh_token)
if 'expires_in' in d:
self.token_expiry = datetime.timedelta(
seconds=int(d['expires_in'])) + datetime.datetime.utcnow()
else:
self.token_expiry = None
if self.store:
self.store.locked_put(self)
else:
# An {'error':...} response body means the token is expired or revoked,
# so we flag the credentials as such.
logger.info('Failed to retrieve access token: %s' % content)
error_msg = 'Invalid response %s.' % resp['status']
try:
d = simplejson.loads(content)
if 'error' in d:
error_msg = d['error']
self.invalid = True
if self.store:
self.store.locked_put(self)
except:
pass
raise AccessTokenRefreshError(error_msg)
class AccessTokenCredentials(OAuth2Credentials):
"""Credentials object for OAuth 2.0.
Credentials can be applied to an httplib2.Http object using the
authorize() method, which then signs each request from that object
with the OAuth 2.0 access token. This set of credentials is for the
use case where you have acquired an OAuth 2.0 access_token from
another place such as a JavaScript client or another web
application, and wish to use it from Python. Because only the
access_token is present it can not be refreshed and will in time
expire.
AccessTokenCredentials objects may be safely pickled and unpickled.
Usage:
credentials = AccessTokenCredentials('<an access token>',
'my-user-agent/1.0')
http = httplib2.Http()
http = credentials.authorize(http)
Exceptions:
AccessTokenCredentialsExpired: raised when the access_token expires or is
revoked.
"""
def __init__(self, access_token, user_agent):
"""Create an instance of OAuth2Credentials
This is one of the few types if Credentials that you should contrust,
Credentials objects are usually instantiated by a Flow.
Args:
access_token: string, access token.
user_agent: string, The HTTP User-Agent to provide for this application.
Notes:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
"""
super(AccessTokenCredentials, self).__init__(
access_token,
None,
None,
None,
None,
None,
user_agent)
@classmethod
def from_json(cls, s):
data = simplejson.loads(s)
retval = AccessTokenCredentials(
data['access_token'],
data['user_agent'])
return retval
def _refresh(self, http_request):
raise AccessTokenCredentialsError(
"The access_token is expired or invalid and can't be refreshed.")
class AssertionCredentials(OAuth2Credentials):
"""Abstract Credentials object used for OAuth 2.0 assertion grants.
This credential does not require a flow to instantiate because it
represents a two legged flow, and therefore has all of the required
information to generate and refresh its own access tokens. It must
be subclassed to generate the appropriate assertion string.
AssertionCredentials objects may be safely pickled and unpickled.
"""
def __init__(self, assertion_type, user_agent,
token_uri='https://accounts.google.com/o/oauth2/token',
**unused_kwargs):
"""Constructor for AssertionFlowCredentials.
Args:
assertion_type: string, assertion type that will be declared to the auth
server
user_agent: string, The HTTP User-Agent to provide for this application.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
"""
super(AssertionCredentials, self).__init__(
None,
None,
None,
None,
None,
token_uri,
user_agent)
self.assertion_type = assertion_type
def _generate_refresh_request_body(self):
assertion = self._generate_assertion()
body = urllib.urlencode({
'assertion_type': self.assertion_type,
'assertion': assertion,
'grant_type': 'assertion',
})
return body
def _generate_assertion(self):
"""Generate the assertion string that will be used in the access token
request.
"""
_abstract()
if HAS_OPENSSL:
# PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then
# don't create the SignedJwtAssertionCredentials or the verify_id_token()
# method.
class SignedJwtAssertionCredentials(AssertionCredentials):
"""Credentials object used for OAuth 2.0 Signed JWT assertion grants.
This credential does not require a flow to instantiate because it
represents a two legged flow, and therefore has all of the required
information to generate and refresh its own access tokens.
"""
MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
def __init__(self,
service_account_name,
private_key,
scope,
private_key_password='notasecret',
user_agent=None,
token_uri='https://accounts.google.com/o/oauth2/token',
**kwargs):
"""Constructor for SignedJwtAssertionCredentials.
Args:
service_account_name: string, id for account, usually an email address.
private_key: string, private key in P12 format.
scope: string or list of strings, scope(s) of the credentials being
requested.
private_key_password: string, password for private_key.
user_agent: string, HTTP User-Agent to provide for this application.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
kwargs: kwargs, Additional parameters to add to the JWT token, for
example prn=joe@xample.org."""
super(SignedJwtAssertionCredentials, self).__init__(
'http://oauth.net/grant_type/jwt/1.0/bearer',
user_agent,
token_uri=token_uri,
)
if type(scope) is list:
scope = ' '.join(scope)
self.scope = scope
self.private_key = private_key
self.private_key_password = private_key_password
self.service_account_name = service_account_name
self.kwargs = kwargs
@classmethod
def from_json(cls, s):
data = simplejson.loads(s)
retval = SignedJwtAssertionCredentials(
data['service_account_name'],
data['private_key'],
data['private_key_password'],
data['scope'],
data['user_agent'],
data['token_uri'],
data['kwargs']
)
retval.invalid = data['invalid']
return retval
def _generate_assertion(self):
"""Generate the assertion that will be used in the request."""
now = long(time.time())
payload = {
'aud': self.token_uri,
'scope': self.scope,
'iat': now,
'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS,
'iss': self.service_account_name
}
payload.update(self.kwargs)
logger.debug(str(payload))
return make_signed_jwt(
Signer.from_string(self.private_key, self.private_key_password),
payload)
# Only used in verify_id_token(), which is always calling to the same URI
# for the certs.
_cached_http = httplib2.Http(MemoryCache())
def verify_id_token(id_token, audience, http=None,
cert_uri=ID_TOKEN_VERIFICATON_CERTS):
"""Verifies a signed JWT id_token.
Args:
id_token: string, A Signed JWT.
audience: string, The audience 'aud' that the token should be for.
http: httplib2.Http, instance to use to make the HTTP request. Callers
should supply an instance that has caching enabled.
cert_uri: string, URI of the certificates in JSON format to
verify the JWT against.
Returns:
The deserialized JSON in the JWT.
Raises:
oauth2client.crypt.AppIdentityError if the JWT fails to verify.
"""
if http is None:
http = _cached_http
resp, content = http.request(cert_uri)
if resp.status == 200:
certs = simplejson.loads(content)
return verify_signed_jwt_with_certs(id_token, certs, audience)
else:
raise VerifyJwtTokenError('Status code: %d' % resp.status)
def _urlsafe_b64decode(b64string):
# Guard against unicode strings, which base64 can't handle.
b64string = b64string.encode('ascii')
padded = b64string + '=' * (4 - len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
def _extract_id_token(id_token):
"""Extract the JSON payload from a JWT.
Does the extraction w/o checking the signature.
Args:
id_token: string, OAuth 2.0 id_token.
Returns:
object, The deserialized JSON payload.
"""
segments = id_token.split('.')
if (len(segments) != 3):
raise VerifyJwtTokenError(
'Wrong number of segments in token: %s' % id_token)
return simplejson.loads(_urlsafe_b64decode(segments[1]))
def credentials_from_code(client_id, client_secret, scope, code,
redirect_uri = 'postmessage',
http=None, user_agent=None,
token_uri='https://accounts.google.com/o/oauth2/token'):
"""Exchanges an authorization code for an OAuth2Credentials object.
Args:
client_id: string, client identifier.
client_secret: string, client secret.
scope: string or list of strings, scope(s) to request.
code: string, An authroization code, most likely passed down from
the client
redirect_uri: string, this is generally set to 'postmessage' to match the
redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError if the authorization code cannot be exchanged for an
access token
"""
flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent,
'https://accounts.google.com/o/oauth2/auth',
token_uri)
# We primarily make this call to set up the redirect_uri in the flow object
uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri)
credentials = flow.step2_exchange(code, http)
return credentials
def credentials_from_clientsecrets_and_code(filename, scope, code,
message = None,
redirect_uri = 'postmessage',
http=None):
"""Returns OAuth2Credentials from a clientsecrets file and an auth code.
Will create the right kind of Flow based on the contents of the clientsecrets
file or will raise InvalidClientSecretsError for unknown types of Flows.
Args:
filename: string, File name of clientsecrets.
scope: string or list of strings, scope(s) to request.
code: string, An authroization code, most likely passed down from
the client
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. If message is provided then
sys.exit will be called in the case of an error. If message in not
provided then clientsecrets.InvalidClientSecretsError will be raised.
redirect_uri: string, this is generally set to 'postmessage' to match the
redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError if the authorization code cannot be exchanged for an
access token
UnknownClientSecretsFlowError if the file describes an unknown kind of Flow.
clientsecrets.InvalidClientSecretsError if the clientsecrets file is
invalid.
"""
flow = flow_from_clientsecrets(filename, scope, message)
# We primarily make this call to set up the redirect_uri in the flow object
uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri)
credentials = flow.step2_exchange(code, http)
return credentials
class OAuth2WebServerFlow(Flow):
"""Does the Web Server Flow for OAuth 2.0.
OAuth2Credentials objects may be safely pickled and unpickled.
"""
def __init__(self, client_id, client_secret, scope, user_agent=None,
auth_uri='https://accounts.google.com/o/oauth2/auth',
token_uri='https://accounts.google.com/o/oauth2/token',
**kwargs):
"""Constructor for OAuth2WebServerFlow.
Args:
client_id: string, client identifier.
client_secret: string client secret.
scope: string or list of strings, scope(s) of the credentials being
requested.
user_agent: string, HTTP User-Agent to provide for this application.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
**kwargs: dict, The keyword arguments are all optional and required
parameters for the OAuth calls.
"""
self.client_id = client_id
self.client_secret = client_secret
if type(scope) is list:
scope = ' '.join(scope)
self.scope = scope
self.user_agent = user_agent
self.auth_uri = auth_uri
self.token_uri = token_uri
self.params = {
'access_type': 'offline',
}
self.params.update(kwargs)
self.redirect_uri = None
def step1_get_authorize_url(self, redirect_uri=OOB_CALLBACK_URN):
"""Returns a URI to redirect to the provider.
Args:
redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
a non-web-based application, or a URI that handles the callback from
the authorization server.
If redirect_uri is 'urn:ietf:wg:oauth:2.0:oob' then pass in the
generated verification code to step2_exchange,
otherwise pass in the query parameters received
at the callback uri to step2_exchange.
"""
self.redirect_uri = redirect_uri
query = {
'response_type': 'code',
'client_id': self.client_id,
'redirect_uri': redirect_uri,
'scope': self.scope,
}
query.update(self.params)
parts = list(urlparse.urlparse(self.auth_uri))
query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part
parts[4] = urllib.urlencode(query)
return urlparse.urlunparse(parts)
def step2_exchange(self, code, http=None):
"""Exhanges a code for OAuth2Credentials.
Args:
code: string or dict, either the code as a string, or a dictionary
of the query parameters to the redirect_uri, which contains
the code.
http: httplib2.Http, optional http instance to use to do the fetch
Returns:
An OAuth2Credentials object that can be used to authorize requests.
Raises:
FlowExchangeError if a problem occured exchanging the code for a
refresh_token.
"""
if not (isinstance(code, str) or isinstance(code, unicode)):
if 'code' not in code:
if 'error' in code:
error_msg = code['error']
else:
error_msg = 'No code was supplied in the query parameters.'
raise FlowExchangeError(error_msg)
else:
code = code['code']
body = urllib.urlencode({
'grant_type': 'authorization_code',
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': code,
'redirect_uri': self.redirect_uri,
'scope': self.scope,
})
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if self.user_agent is not None:
headers['user-agent'] = self.user_agent
if http is None:
http = httplib2.Http()
resp, content = http.request(self.token_uri, method='POST', body=body,
headers=headers)
if resp.status == 200:
# TODO(jcgregorio) Raise an error if simplejson.loads fails?
d = simplejson.loads(content)
access_token = d['access_token']
refresh_token = d.get('refresh_token', None)
token_expiry = None
if 'expires_in' in d:
token_expiry = datetime.datetime.utcnow() + datetime.timedelta(
seconds=int(d['expires_in']))
if 'id_token' in d:
d['id_token'] = _extract_id_token(d['id_token'])
logger.info('Successfully retrieved access token: %s' % content)
return OAuth2Credentials(access_token, self.client_id,
self.client_secret, refresh_token, token_expiry,
self.token_uri, self.user_agent,
id_token=d.get('id_token', None))
else:
logger.info('Failed to retrieve access token: %s' % content)
error_msg = 'Invalid response %s.' % resp['status']
try:
d = simplejson.loads(content)
if 'error' in d:
error_msg = d['error']
except:
pass
raise FlowExchangeError(error_msg)
def flow_from_clientsecrets(filename, scope, message=None):
"""Create a Flow from a clientsecrets file.
Will create the right kind of Flow based on the contents of the clientsecrets
file or will raise InvalidClientSecretsError for unknown types of Flows.
Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) to request.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. If message is provided then
sys.exit will be called in the case of an error. If message in not
provided then clientsecrets.InvalidClientSecretsError will be raised.
Returns:
A Flow object.
Raises:
UnknownClientSecretsFlowError if the file describes an unknown kind of Flow.
clientsecrets.InvalidClientSecretsError if the clientsecrets file is
invalid.
"""
try:
client_type, client_info = clientsecrets.loadfile(filename)
if client_type in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]:
return OAuth2WebServerFlow(
client_info['client_id'],
client_info['client_secret'],
scope,
None, # user_agent
client_info['auth_uri'],
client_info['token_uri'])
except clientsecrets.InvalidClientSecretsError:
if message:
sys.exit(message)
else:
raise
else:
raise UnknownClientSecretsFlowError(
'This OAuth 2.0 flow is unsupported: "%s"' * client_type)
| Python |
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for reading OAuth 2.0 client secret files.
A client_secrets.json file contains all the information needed to interact with
an OAuth 2.0 protected service.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from anyjson import simplejson
# Properties that make a client_secrets.json file valid.
TYPE_WEB = 'web'
TYPE_INSTALLED = 'installed'
VALID_CLIENT = {
TYPE_WEB: {
'required': [
'client_id',
'client_secret',
'redirect_uris',
'auth_uri',
'token_uri'],
'string': [
'client_id',
'client_secret'
]
},
TYPE_INSTALLED: {
'required': [
'client_id',
'client_secret',
'redirect_uris',
'auth_uri',
'token_uri'],
'string': [
'client_id',
'client_secret'
]
}
}
class Error(Exception):
"""Base error for this module."""
pass
class InvalidClientSecretsError(Error):
"""Format of ClientSecrets file is invalid."""
pass
def _validate_clientsecrets(obj):
if obj is None or len(obj) != 1:
raise InvalidClientSecretsError('Invalid file format.')
client_type = obj.keys()[0]
if client_type not in VALID_CLIENT.keys():
raise InvalidClientSecretsError('Unknown client type: %s.' % client_type)
client_info = obj[client_type]
for prop_name in VALID_CLIENT[client_type]['required']:
if prop_name not in client_info:
raise InvalidClientSecretsError(
'Missing property "%s" in a client type of "%s".' % (prop_name,
client_type))
for prop_name in VALID_CLIENT[client_type]['string']:
if client_info[prop_name].startswith('[['):
raise InvalidClientSecretsError(
'Property "%s" is not configured.' % prop_name)
return client_type, client_info
def load(fp):
obj = simplejson.load(fp)
return _validate_clientsecrets(obj)
def loads(s):
obj = simplejson.loads(s)
return _validate_clientsecrets(obj)
def loadfile(filename):
try:
fp = file(filename, 'r')
try:
obj = simplejson.load(fp)
finally:
fp.close()
except IOError:
raise InvalidClientSecretsError('File not found: "%s"' % filename)
return _validate_clientsecrets(obj)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth 2.0
credentials.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import os
import stat
import threading
from anyjson import simplejson
from client import Storage as BaseStorage
from client import Credentials
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from a file."""
def __init__(self, filename):
self._filename = filename
self._lock = threading.Lock()
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant."""
self._lock.acquire()
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
self._lock.release()
def locked_get(self):
"""Retrieve Credential from file.
Returns:
oauth2client.client.Credentials
"""
credentials = None
try:
f = open(self._filename, 'rb')
content = f.read()
f.close()
except IOError:
return credentials
try:
credentials = Credentials.new_from_json(content)
credentials.set_store(self)
except ValueError:
pass
return credentials
def _create_file_if_needed(self):
"""Create an empty file if necessary.
This method will not initialize the file. Instead it implements a
simple version of "touch" to ensure the file has been created.
"""
if not os.path.exists(self._filename):
old_umask = os.umask(0177)
try:
open(self._filename, 'a+b').close()
finally:
os.umask(old_umask)
def locked_put(self, credentials):
"""Write Credentials to file.
Args:
credentials: Credentials, the credentials to store.
"""
self._create_file_if_needed()
f = open(self._filename, 'wb')
f.write(credentials.to_json())
f.close()
def locked_delete(self):
"""Delete Credentials file.
Args:
credentials: Credentials, the credentials to store.
"""
os.unlink(self._filename)
| Python |
__version__ = "1.0c2"
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""OAuth 2.0 utilities for Django.
Utilities for using OAuth 2.0 in conjunction with
the Django datastore.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import oauth2client
import base64
import pickle
from django.db import models
from oauth2client.client import Storage as BaseStorage
class CredentialsField(models.Field):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "TextField"
def to_python(self, value):
if value is None:
return None
if isinstance(value, oauth2client.client.Credentials):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value, connection, prepared=False):
if value is None:
return None
return base64.b64encode(pickle.dumps(value))
class FlowField(models.Field):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "TextField"
def to_python(self, value):
if value is None:
return None
if isinstance(value, oauth2client.client.Flow):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value, connection, prepared=False):
if value is None:
return None
return base64.b64encode(pickle.dumps(value))
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from
the datastore.
This Storage helper presumes the Credentials
have been stored as a CredenialsField
on a db model class.
"""
def __init__(self, model_class, key_name, key_value, property_name):
"""Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
key_value: string, key value for the entity that has the credentials
property_name: string, name of the property that is an CredentialsProperty
"""
self.model_class = model_class
self.key_name = key_name
self.key_value = key_value
self.property_name = property_name
def locked_get(self):
"""Retrieve Credential from datastore.
Returns:
oauth2client.Credentials
"""
credential = None
query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query)
if len(entities) > 0:
credential = getattr(entities[0], self.property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self)
return credential
def locked_put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
args = {self.key_name: self.key_value}
entity = self.model_class(**args)
setattr(entity, self.property_name, credentials)
entity.save()
def locked_delete(self):
"""Delete Credentials from the datastore."""
query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query).delete()
| Python |
# Copyright (C) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes to encapsulate a single HTTP request.
The classes implement a command pattern, with every
object supporting an execute() method that does the
actuall HTTP request.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import StringIO
import base64
import copy
import gzip
import httplib2
import mimeparse
import mimetypes
import os
import urllib
import urlparse
import uuid
from email.generator import Generator
from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart
from email.parser import FeedParser
from errors import BatchError
from errors import HttpError
from errors import ResumableUploadError
from errors import UnexpectedBodyError
from errors import UnexpectedMethodError
from model import JsonModel
from oauth2client.anyjson import simplejson
DEFAULT_CHUNK_SIZE = 512*1024
class MediaUploadProgress(object):
"""Status of a resumable upload."""
def __init__(self, resumable_progress, total_size):
"""Constructor.
Args:
resumable_progress: int, bytes sent so far.
total_size: int, total bytes in complete upload, or None if the total
upload size isn't known ahead of time.
"""
self.resumable_progress = resumable_progress
self.total_size = total_size
def progress(self):
"""Percent of upload completed, as a float.
Returns:
the percentage complete as a float, returning 0.0 if the total size of
the upload is unknown.
"""
if self.total_size is not None:
return float(self.resumable_progress) / float(self.total_size)
else:
return 0.0
class MediaDownloadProgress(object):
"""Status of a resumable download."""
def __init__(self, resumable_progress, total_size):
"""Constructor.
Args:
resumable_progress: int, bytes received so far.
total_size: int, total bytes in complete download.
"""
self.resumable_progress = resumable_progress
self.total_size = total_size
def progress(self):
"""Percent of download completed, as a float.
Returns:
the percentage complete as a float, returning 0.0 if the total size of
the download is unknown.
"""
if self.total_size is not None:
return float(self.resumable_progress) / float(self.total_size)
else:
return 0.0
class MediaUpload(object):
"""Describes a media object to upload.
Base class that defines the interface of MediaUpload subclasses.
Note that subclasses of MediaUpload may allow you to control the chunksize
when upload a media object. It is important to keep the size of the chunk as
large as possible to keep the upload efficient. Other factors may influence
the size of the chunk you use, particularly if you are working in an
environment where individual HTTP requests may have a hardcoded time limit,
such as under certain classes of requests under Google App Engine.
"""
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
raise NotImplementedError()
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return 'application/octet-stream'
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return None
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return False
def getbytes(self, begin, end):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
raise NotImplementedError()
def _to_json(self, strip=None):
"""Utility function for creating a JSON representation of a MediaUpload.
Args:
strip: array, An array of names of members to not include in the JSON.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
t = type(self)
d = copy.copy(self.__dict__)
if strip is not None:
for member in strip:
del d[member]
d['_class'] = t.__name__
d['_module'] = t.__module__
return simplejson.dumps(d)
def to_json(self):
"""Create a JSON representation of an instance of MediaUpload.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
return self._to_json()
@classmethod
def new_from_json(cls, s):
"""Utility class method to instantiate a MediaUpload subclass from a JSON
representation produced by to_json().
Args:
s: string, JSON from to_json().
Returns:
An instance of the subclass of MediaUpload that was serialized with
to_json().
"""
data = simplejson.loads(s)
# Find and call the right classmethod from_json() to restore the object.
module = data['_module']
m = __import__(module, fromlist=module.split('.')[:-1])
kls = getattr(m, data['_class'])
from_json = getattr(kls, 'from_json')
return from_json(s)
class MediaFileUpload(MediaUpload):
"""A MediaUpload for a file.
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed uploading images:
media = MediaFileUpload('cow.png', mimetype='image/png',
chunksize=1024*1024, resumable=True)
farm.animals()..insert(
id='cow',
name='cow.png',
media_body=media).execute()
"""
def __init__(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False):
"""Constructor.
Args:
filename: string, Name of the file.
mimetype: string, Mime-type of the file. If None then a mime-type will be
guessed from the file extension.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._filename = filename
self._size = os.path.getsize(filename)
self._fd = None
if mimetype is None:
(mimetype, encoding) = mimetypes.guess_type(filename)
self._mimetype = mimetype
self._chunksize = chunksize
self._resumable = resumable
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return self._size
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorted than length if EOF was reached
first.
"""
if self._fd is None:
self._fd = open(self._filename, 'rb')
self._fd.seek(begin)
return self._fd.read(length)
def to_json(self):
"""Creating a JSON representation of an instance of MediaFileUpload.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
return self._to_json(['_fd'])
@staticmethod
def from_json(s):
d = simplejson.loads(s)
return MediaFileUpload(
d['_filename'], d['_mimetype'], d['_chunksize'], d['_resumable'])
class MediaIoBaseUpload(MediaUpload):
"""A MediaUpload for a io.Base objects.
Note that the Python file object is compatible with io.Base and can be used
with this class also.
fh = io.BytesIO('...Some data to upload...')
media = MediaIoBaseUpload(fh, mimetype='image/png',
chunksize=1024*1024, resumable=True)
farm.animals().insert(
id='cow',
name='cow.png',
media_body=media).execute()
"""
def __init__(self, fh, mimetype, chunksize=DEFAULT_CHUNK_SIZE,
resumable=False):
"""Constructor.
Args:
fh: io.Base or file object, The source of the bytes to upload. MUST be
opened in blocking mode, do not use streams opened in non-blocking mode.
mimetype: string, Mime-type of the file. If None then a mime-type will be
guessed from the file extension.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._fh = fh
self._mimetype = mimetype
self._chunksize = chunksize
self._resumable = resumable
self._size = None
try:
if hasattr(self._fh, 'fileno'):
fileno = self._fh.fileno()
# Pipes and such show up as 0 length files.
size = os.fstat(fileno).st_size
if size:
self._size = os.fstat(fileno).st_size
except IOError:
pass
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return self._size
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorted than length if EOF was reached
first.
"""
self._fh.seek(begin)
return self._fh.read(length)
def to_json(self):
"""This upload type is not serializable."""
raise NotImplementedError('MediaIoBaseUpload is not serializable.')
class MediaInMemoryUpload(MediaUpload):
"""MediaUpload for a chunk of bytes.
Construct a MediaFileUpload and pass as the media_body parameter of the
method.
"""
def __init__(self, body, mimetype='application/octet-stream',
chunksize=DEFAULT_CHUNK_SIZE, resumable=False):
"""Create a new MediaBytesUpload.
Args:
body: string, Bytes of body content.
mimetype: string, Mime-type of the file or default of
'application/octet-stream'.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._body = body
self._mimetype = mimetype
self._resumable = resumable
self._chunksize = chunksize
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return len(self._body)
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
return self._body[begin:begin + length]
def to_json(self):
"""Create a JSON representation of a MediaInMemoryUpload.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
t = type(self)
d = copy.copy(self.__dict__)
del d['_body']
d['_class'] = t.__name__
d['_module'] = t.__module__
d['_b64body'] = base64.b64encode(self._body)
return simplejson.dumps(d)
@staticmethod
def from_json(s):
d = simplejson.loads(s)
return MediaInMemoryUpload(base64.b64decode(d['_b64body']),
d['_mimetype'], d['_chunksize'],
d['_resumable'])
class MediaIoBaseDownload(object):
""""Download media resources.
Note that the Python file object is compatible with io.Base and can be used
with this class also.
Example:
request = farms.animals().get_media(id='cow')
fh = io.FileIO('cow.png', mode='wb')
downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024)
done = False
while done is False:
status, done = downloader.next_chunk()
if status:
print "Download %d%%." % int(status.progress() * 100)
print "Download Complete!"
"""
def __init__(self, fh, request, chunksize=DEFAULT_CHUNK_SIZE):
"""Constructor.
Args:
fh: io.Base or file object, The stream in which to write the downloaded
bytes.
request: apiclient.http.HttpRequest, the media request to perform in
chunks.
chunksize: int, File will be downloaded in chunks of this many bytes.
"""
self.fh_ = fh
self.request_ = request
self.uri_ = request.uri
self.chunksize_ = chunksize
self.progress_ = 0
self.total_size_ = None
self.done_ = False
def next_chunk(self):
"""Get the next chunk of the download.
Returns:
(status, done): (MediaDownloadStatus, boolean)
The value of 'done' will be True when the media has been fully
downloaded.
Raises:
apiclient.errors.HttpError if the response was not a 2xx.
httplib2.Error if a transport error has occured.
"""
headers = {
'range': 'bytes=%d-%d' % (
self.progress_, self.progress_ + self.chunksize_)
}
http = self.request_.http
http.follow_redirects = False
resp, content = http.request(self.uri_, headers=headers)
if resp.status in [301, 302, 303, 307, 308] and 'location' in resp:
self.uri_ = resp['location']
resp, content = http.request(self.uri_, headers=headers)
if resp.status in [200, 206]:
self.progress_ += len(content)
self.fh_.write(content)
if 'content-range' in resp:
content_range = resp['content-range']
length = content_range.rsplit('/', 1)[1]
self.total_size_ = int(length)
if self.progress_ == self.total_size_:
self.done_ = True
return MediaDownloadProgress(self.progress_, self.total_size_), self.done_
else:
raise HttpError(resp, content, self.uri_)
class HttpRequest(object):
"""Encapsulates a single HTTP request."""
def __init__(self, http, postproc, uri,
method='GET',
body=None,
headers=None,
methodId=None,
resumable=None):
"""Constructor for an HttpRequest.
Args:
http: httplib2.Http, the transport object to use to make a request
postproc: callable, called on the HTTP response and content to transform
it into a data object before returning, or raising an exception
on an error.
uri: string, the absolute URI to send the request to
method: string, the HTTP method to use
body: string, the request body of the HTTP request,
headers: dict, the HTTP request headers
methodId: string, a unique identifier for the API method being called.
resumable: MediaUpload, None if this is not a resumbale request.
"""
self.uri = uri
self.method = method
self.body = body
self.headers = headers or {}
self.methodId = methodId
self.http = http
self.postproc = postproc
self.resumable = resumable
self._in_error_state = False
# Pull the multipart boundary out of the content-type header.
major, minor, params = mimeparse.parse_mime_type(
headers.get('content-type', 'application/json'))
# The size of the non-media part of the request.
self.body_size = len(self.body or '')
# The resumable URI to send chunks to.
self.resumable_uri = None
# The bytes that have been uploaded.
self.resumable_progress = 0
def execute(self, http=None):
"""Execute the request.
Args:
http: httplib2.Http, an http object to be used in place of the
one the HttpRequest request object was constructed with.
Returns:
A deserialized object model of the response body as determined
by the postproc.
Raises:
apiclient.errors.HttpError if the response was not a 2xx.
httplib2.Error if a transport error has occured.
"""
if http is None:
http = self.http
if self.resumable:
body = None
while body is None:
_, body = self.next_chunk(http)
return body
else:
if 'content-length' not in self.headers:
self.headers['content-length'] = str(self.body_size)
resp, content = http.request(self.uri, self.method,
body=self.body,
headers=self.headers)
if resp.status >= 300:
raise HttpError(resp, content, self.uri)
return self.postproc(resp, content)
def next_chunk(self, http=None):
"""Execute the next step of a resumable upload.
Can only be used if the method being executed supports media uploads and
the MediaUpload object passed in was flagged as using resumable upload.
Example:
media = MediaFileUpload('cow.png', mimetype='image/png',
chunksize=1000, resumable=True)
request = farm.animals().insert(
id='cow',
name='cow.png',
media_body=media)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print "Upload %d%% complete." % int(status.progress() * 100)
Returns:
(status, body): (ResumableMediaStatus, object)
The body will be None until the resumable media is fully uploaded.
Raises:
apiclient.errors.HttpError if the response was not a 2xx.
httplib2.Error if a transport error has occured.
"""
if http is None:
http = self.http
if self.resumable.size() is None:
size = '*'
else:
size = str(self.resumable.size())
if self.resumable_uri is None:
start_headers = copy.copy(self.headers)
start_headers['X-Upload-Content-Type'] = self.resumable.mimetype()
if size != '*':
start_headers['X-Upload-Content-Length'] = size
start_headers['content-length'] = str(self.body_size)
resp, content = http.request(self.uri, self.method,
body=self.body,
headers=start_headers)
if resp.status == 200 and 'location' in resp:
self.resumable_uri = resp['location']
else:
raise ResumableUploadError("Failed to retrieve starting URI.")
elif self._in_error_state:
# If we are in an error state then query the server for current state of
# the upload by sending an empty PUT and reading the 'range' header in
# the response.
headers = {
'Content-Range': 'bytes */%s' % size,
'content-length': '0'
}
resp, content = http.request(self.resumable_uri, 'PUT',
headers=headers)
status, body = self._process_response(resp, content)
if body:
# The upload was complete.
return (status, body)
data = self.resumable.getbytes(
self.resumable_progress, self.resumable.chunksize())
# A short read implies that we are at EOF, so finish the upload.
if len(data) < self.resumable.chunksize():
size = str(self.resumable_progress + len(data))
headers = {
'Content-Range': 'bytes %d-%d/%s' % (
self.resumable_progress, self.resumable_progress + len(data) - 1,
size)
}
try:
resp, content = http.request(self.resumable_uri, 'PUT',
body=data,
headers=headers)
except:
self._in_error_state = True
raise
return self._process_response(resp, content)
def _process_response(self, resp, content):
"""Process the response from a single chunk upload.
Args:
resp: httplib2.Response, the response object.
content: string, the content of the response.
Returns:
(status, body): (ResumableMediaStatus, object)
The body will be None until the resumable media is fully uploaded.
Raises:
apiclient.errors.HttpError if the response was not a 2xx or a 308.
"""
if resp.status in [200, 201]:
self._in_error_state = False
return None, self.postproc(resp, content)
elif resp.status == 308:
self._in_error_state = False
# A "308 Resume Incomplete" indicates we are not done.
self.resumable_progress = int(resp['range'].split('-')[1]) + 1
if 'location' in resp:
self.resumable_uri = resp['location']
else:
self._in_error_state = True
raise HttpError(resp, content, self.uri)
return (MediaUploadProgress(self.resumable_progress, self.resumable.size()),
None)
def to_json(self):
"""Returns a JSON representation of the HttpRequest."""
d = copy.copy(self.__dict__)
if d['resumable'] is not None:
d['resumable'] = self.resumable.to_json()
del d['http']
del d['postproc']
return simplejson.dumps(d)
@staticmethod
def from_json(s, http, postproc):
"""Returns an HttpRequest populated with info from a JSON object."""
d = simplejson.loads(s)
if d['resumable'] is not None:
d['resumable'] = MediaUpload.new_from_json(d['resumable'])
return HttpRequest(
http,
postproc,
uri=d['uri'],
method=d['method'],
body=d['body'],
headers=d['headers'],
methodId=d['methodId'],
resumable=d['resumable'])
class BatchHttpRequest(object):
"""Batches multiple HttpRequest objects into a single HTTP request.
Example:
from apiclient.http import BatchHttpRequest
def list_animals(request_id, response):
\"\"\"Do something with the animals list response.\"\"\"
pass
def list_farmers(request_id, response):
\"\"\"Do something with the farmers list response.\"\"\"
pass
service = build('farm', 'v2')
batch = BatchHttpRequest()
batch.add(service.animals().list(), list_animals)
batch.add(service.farmers().list(), list_farmers)
batch.execute(http)
"""
def __init__(self, callback=None, batch_uri=None):
"""Constructor for a BatchHttpRequest.
Args:
callback: callable, A callback to be called for each response, of the
form callback(id, response). The first parameter is the request id, and
the second is the deserialized response object.
batch_uri: string, URI to send batch requests to.
"""
if batch_uri is None:
batch_uri = 'https://www.googleapis.com/batch'
self._batch_uri = batch_uri
# Global callback to be called for each individual response in the batch.
self._callback = callback
# A map from id to request.
self._requests = {}
# A map from id to callback.
self._callbacks = {}
# List of request ids, in the order in which they were added.
self._order = []
# The last auto generated id.
self._last_auto_id = 0
# Unique ID on which to base the Content-ID headers.
self._base_id = None
# A map from request id to (headers, content) response pairs
self._responses = {}
# A map of id(Credentials) that have been refreshed.
self._refreshed_credentials = {}
def _refresh_and_apply_credentials(self, request, http):
"""Refresh the credentials and apply to the request.
Args:
request: HttpRequest, the request.
http: httplib2.Http, the global http object for the batch.
"""
# For the credentials to refresh, but only once per refresh_token
# If there is no http per the request then refresh the http passed in
# via execute()
creds = None
if request.http is not None and hasattr(request.http.request,
'credentials'):
creds = request.http.request.credentials
elif http is not None and hasattr(http.request, 'credentials'):
creds = http.request.credentials
if creds is not None:
if id(creds) not in self._refreshed_credentials:
creds.refresh(http)
self._refreshed_credentials[id(creds)] = 1
# Only apply the credentials if we are using the http object passed in,
# otherwise apply() will get called during _serialize_request().
if request.http is None or not hasattr(request.http.request,
'credentials'):
creds.apply(request.headers)
def _id_to_header(self, id_):
"""Convert an id to a Content-ID header value.
Args:
id_: string, identifier of individual request.
Returns:
A Content-ID header with the id_ encoded into it. A UUID is prepended to
the value because Content-ID headers are supposed to be universally
unique.
"""
if self._base_id is None:
self._base_id = uuid.uuid4()
return '<%s+%s>' % (self._base_id, urllib.quote(id_))
def _header_to_id(self, header):
"""Convert a Content-ID header value to an id.
Presumes the Content-ID header conforms to the format that _id_to_header()
returns.
Args:
header: string, Content-ID header value.
Returns:
The extracted id value.
Raises:
BatchError if the header is not in the expected format.
"""
if header[0] != '<' or header[-1] != '>':
raise BatchError("Invalid value for Content-ID: %s" % header)
if '+' not in header:
raise BatchError("Invalid value for Content-ID: %s" % header)
base, id_ = header[1:-1].rsplit('+', 1)
return urllib.unquote(id_)
def _serialize_request(self, request):
"""Convert an HttpRequest object into a string.
Args:
request: HttpRequest, the request to serialize.
Returns:
The request as a string in application/http format.
"""
# Construct status line
parsed = urlparse.urlparse(request.uri)
request_line = urlparse.urlunparse(
(None, None, parsed.path, parsed.params, parsed.query, None)
)
status_line = request.method + ' ' + request_line + ' HTTP/1.1\n'
major, minor = request.headers.get('content-type', 'application/json').split('/')
msg = MIMENonMultipart(major, minor)
headers = request.headers.copy()
if request.http is not None and hasattr(request.http.request,
'credentials'):
request.http.request.credentials.apply(headers)
# MIMENonMultipart adds its own Content-Type header.
if 'content-type' in headers:
del headers['content-type']
for key, value in headers.iteritems():
msg[key] = value
msg['Host'] = parsed.netloc
msg.set_unixfrom(None)
if request.body is not None:
msg.set_payload(request.body)
msg['content-length'] = str(len(request.body))
# Serialize the mime message.
fp = StringIO.StringIO()
# maxheaderlen=0 means don't line wrap headers.
g = Generator(fp, maxheaderlen=0)
g.flatten(msg, unixfrom=False)
body = fp.getvalue()
# Strip off the \n\n that the MIME lib tacks onto the end of the payload.
if request.body is None:
body = body[:-2]
return status_line.encode('utf-8') + body
def _deserialize_response(self, payload):
"""Convert string into httplib2 response and content.
Args:
payload: string, headers and body as a string.
Returns:
A pair (resp, content) like would be returned from httplib2.request.
"""
# Strip off the status line
status_line, payload = payload.split('\n', 1)
protocol, status, reason = status_line.split(' ', 2)
# Parse the rest of the response
parser = FeedParser()
parser.feed(payload)
msg = parser.close()
msg['status'] = status
# Create httplib2.Response from the parsed headers.
resp = httplib2.Response(msg)
resp.reason = reason
resp.version = int(protocol.split('/', 1)[1].replace('.', ''))
content = payload.split('\r\n\r\n', 1)[1]
return resp, content
def _new_id(self):
"""Create a new id.
Auto incrementing number that avoids conflicts with ids already used.
Returns:
string, a new unique id.
"""
self._last_auto_id += 1
while str(self._last_auto_id) in self._requests:
self._last_auto_id += 1
return str(self._last_auto_id)
def add(self, request, callback=None, request_id=None):
"""Add a new request.
Every callback added will be paired with a unique id, the request_id. That
unique id will be passed back to the callback when the response comes back
from the server. The default behavior is to have the library generate it's
own unique id. If the caller passes in a request_id then they must ensure
uniqueness for each request_id, and if they are not an exception is
raised. Callers should either supply all request_ids or nevery supply a
request id, to avoid such an error.
Args:
request: HttpRequest, Request to add to the batch.
callback: callable, A callback to be called for this response, of the
form callback(id, response). The first parameter is the request id, and
the second is the deserialized response object.
request_id: string, A unique id for the request. The id will be passed to
the callback with the response.
Returns:
None
Raises:
BatchError if a media request is added to a batch.
KeyError is the request_id is not unique.
"""
if request_id is None:
request_id = self._new_id()
if request.resumable is not None:
raise BatchError("Media requests cannot be used in a batch request.")
if request_id in self._requests:
raise KeyError("A request with this ID already exists: %s" % request_id)
self._requests[request_id] = request
self._callbacks[request_id] = callback
self._order.append(request_id)
def _execute(self, http, order, requests):
"""Serialize batch request, send to server, process response.
Args:
http: httplib2.Http, an http object to be used to make the request with.
order: list, list of request ids in the order they were added to the
batch.
request: list, list of request objects to send.
Raises:
httplib2.Error if a transport error has occured.
apiclient.errors.BatchError if the response is the wrong format.
"""
message = MIMEMultipart('mixed')
# Message should not write out it's own headers.
setattr(message, '_write_headers', lambda self: None)
# Add all the individual requests.
for request_id in order:
request = requests[request_id]
msg = MIMENonMultipart('application', 'http')
msg['Content-Transfer-Encoding'] = 'binary'
msg['Content-ID'] = self._id_to_header(request_id)
body = self._serialize_request(request)
msg.set_payload(body)
message.attach(msg)
body = message.as_string()
headers = {}
headers['content-type'] = ('multipart/mixed; '
'boundary="%s"') % message.get_boundary()
resp, content = http.request(self._batch_uri, 'POST', body=body,
headers=headers)
if resp.status >= 300:
raise HttpError(resp, content, self._batch_uri)
# Now break out the individual responses and store each one.
boundary, _ = content.split(None, 1)
# Prepend with a content-type header so FeedParser can handle it.
header = 'content-type: %s\r\n\r\n' % resp['content-type']
for_parser = header + content
parser = FeedParser()
parser.feed(for_parser)
mime_response = parser.close()
if not mime_response.is_multipart():
raise BatchError("Response not in multipart/mixed format.", resp,
content)
for part in mime_response.get_payload():
request_id = self._header_to_id(part['Content-ID'])
headers, content = self._deserialize_response(part.get_payload())
self._responses[request_id] = (headers, content)
def execute(self, http=None):
"""Execute all the requests as a single batched HTTP request.
Args:
http: httplib2.Http, an http object to be used in place of the one the
HttpRequest request object was constructed with. If one isn't supplied
then use a http object from the requests in this batch.
Returns:
None
Raises:
httplib2.Error if a transport error has occured.
apiclient.errors.BatchError if the response is the wrong format.
"""
# If http is not supplied use the first valid one given in the requests.
if http is None:
for request_id in self._order:
request = self._requests[request_id]
if request is not None:
http = request.http
break
if http is None:
raise ValueError("Missing a valid http object.")
self._execute(http, self._order, self._requests)
# Loop over all the requests and check for 401s. For each 401 request the
# credentials should be refreshed and then sent again in a separate batch.
redo_requests = {}
redo_order = []
for request_id in self._order:
headers, content = self._responses[request_id]
if headers['status'] == '401':
redo_order.append(request_id)
request = self._requests[request_id]
self._refresh_and_apply_credentials(request, http)
redo_requests[request_id] = request
if redo_requests:
self._execute(http, redo_order, redo_requests)
# Now process all callbacks that are erroring, and raise an exception for
# ones that return a non-2xx response? Or add extra parameter to callback
# that contains an HttpError?
for request_id in self._order:
headers, content = self._responses[request_id]
request = self._requests[request_id]
callback = self._callbacks[request_id]
response = None
exception = None
try:
r = httplib2.Response(headers)
response = request.postproc(r, content)
except HttpError, e:
exception = e
if callback is not None:
callback(request_id, response, exception)
if self._callback is not None:
self._callback(request_id, response, exception)
class HttpRequestMock(object):
"""Mock of HttpRequest.
Do not construct directly, instead use RequestMockBuilder.
"""
def __init__(self, resp, content, postproc):
"""Constructor for HttpRequestMock
Args:
resp: httplib2.Response, the response to emulate coming from the request
content: string, the response body
postproc: callable, the post processing function usually supplied by
the model class. See model.JsonModel.response() as an example.
"""
self.resp = resp
self.content = content
self.postproc = postproc
if resp is None:
self.resp = httplib2.Response({'status': 200, 'reason': 'OK'})
if 'reason' in self.resp:
self.resp.reason = self.resp['reason']
def execute(self, http=None):
"""Execute the request.
Same behavior as HttpRequest.execute(), but the response is
mocked and not really from an HTTP request/response.
"""
return self.postproc(self.resp, self.content)
class RequestMockBuilder(object):
"""A simple mock of HttpRequest
Pass in a dictionary to the constructor that maps request methodIds to
tuples of (httplib2.Response, content, opt_expected_body) that should be
returned when that method is called. None may also be passed in for the
httplib2.Response, in which case a 200 OK response will be generated.
If an opt_expected_body (str or dict) is provided, it will be compared to
the body and UnexpectedBodyError will be raised on inequality.
Example:
response = '{"data": {"id": "tag:google.c...'
requestBuilder = RequestMockBuilder(
{
'plus.activities.get': (None, response),
}
)
apiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder)
Methods that you do not supply a response for will return a
200 OK with an empty string as the response content or raise an excpetion
if check_unexpected is set to True. The methodId is taken from the rpcName
in the discovery document.
For more details see the project wiki.
"""
def __init__(self, responses, check_unexpected=False):
"""Constructor for RequestMockBuilder
The constructed object should be a callable object
that can replace the class HttpResponse.
responses - A dictionary that maps methodIds into tuples
of (httplib2.Response, content). The methodId
comes from the 'rpcName' field in the discovery
document.
check_unexpected - A boolean setting whether or not UnexpectedMethodError
should be raised on unsupplied method.
"""
self.responses = responses
self.check_unexpected = check_unexpected
def __call__(self, http, postproc, uri, method='GET', body=None,
headers=None, methodId=None, resumable=None):
"""Implements the callable interface that discovery.build() expects
of requestBuilder, which is to build an object compatible with
HttpRequest.execute(). See that method for the description of the
parameters and the expected response.
"""
if methodId in self.responses:
response = self.responses[methodId]
resp, content = response[:2]
if len(response) > 2:
# Test the body against the supplied expected_body.
expected_body = response[2]
if bool(expected_body) != bool(body):
# Not expecting a body and provided one
# or expecting a body and not provided one.
raise UnexpectedBodyError(expected_body, body)
if isinstance(expected_body, str):
expected_body = simplejson.loads(expected_body)
body = simplejson.loads(body)
if body != expected_body:
raise UnexpectedBodyError(expected_body, body)
return HttpRequestMock(resp, content, postproc)
elif self.check_unexpected:
raise UnexpectedMethodError(methodId)
else:
model = JsonModel(False)
return HttpRequestMock(None, '{}', model.response)
class HttpMock(object):
"""Mock of httplib2.Http"""
def __init__(self, filename, headers=None):
"""
Args:
filename: string, absolute filename to read response from
headers: dict, header to return with response
"""
if headers is None:
headers = {'status': '200 OK'}
f = file(filename, 'r')
self.data = f.read()
f.close()
self.headers = headers
def request(self, uri,
method='GET',
body=None,
headers=None,
redirections=1,
connection_type=None):
return httplib2.Response(self.headers), self.data
class HttpMockSequence(object):
"""Mock of httplib2.Http
Mocks a sequence of calls to request returning different responses for each
call. Create an instance initialized with the desired response headers
and content and then use as if an httplib2.Http instance.
http = HttpMockSequence([
({'status': '401'}, ''),
({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
({'status': '200'}, 'echo_request_headers'),
])
resp, content = http.request("http://examples.com")
There are special values you can pass in for content to trigger
behavours that are helpful in testing.
'echo_request_headers' means return the request headers in the response body
'echo_request_headers_as_json' means return the request headers in
the response body
'echo_request_body' means return the request body in the response body
'echo_request_uri' means return the request uri in the response body
"""
def __init__(self, iterable):
"""
Args:
iterable: iterable, a sequence of pairs of (headers, body)
"""
self._iterable = iterable
self.follow_redirects = True
def request(self, uri,
method='GET',
body=None,
headers=None,
redirections=1,
connection_type=None):
resp, content = self._iterable.pop(0)
if content == 'echo_request_headers':
content = headers
elif content == 'echo_request_headers_as_json':
content = simplejson.dumps(headers)
elif content == 'echo_request_body':
content = body
elif content == 'echo_request_uri':
content = uri
return httplib2.Response(resp), content
def set_user_agent(http, user_agent):
"""Set the user-agent on every request.
Args:
http - An instance of httplib2.Http
or something that acts like it.
user_agent: string, the value for the user-agent header.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = set_user_agent(h, "my-app-name/6.0")
Most of the time the user-agent will be set doing auth, this is for the rare
cases where you are accessing an unauthenticated endpoint.
"""
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the user-agent."""
if headers is None:
headers = {}
if 'user-agent' in headers:
headers['user-agent'] = user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
return resp, content
http.request = new_request
return http
def tunnel_patch(http):
"""Tunnel PATCH requests over POST.
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = tunnel_patch(h, "my-app-name/6.0")
Useful if you are running on a platform that doesn't support PATCH.
Apply this last if you are using OAuth 1.0, as changing the method
will result in a different signature.
"""
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the user-agent."""
if headers is None:
headers = {}
if method == 'PATCH':
if 'oauth_token' in headers.get('authorization', ''):
logging.warning(
'OAuth 1.0 request made with Credentials after tunnel_patch.')
headers['x-http-method-override'] = "PATCH"
method = 'POST'
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
return resp, content
http.request = new_request
return http
| Python |
# Copyright (C) 2007 Joe Gregorio
#
# Licensed under the MIT License
"""MIME-Type Parser
This module provides basic functions for handling mime-types. It can handle
matching mime-types against a list of media-ranges. See section 14.1 of the
HTTP specification [RFC 2616] for a complete explanation.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
Contents:
- parse_mime_type(): Parses a mime-type into its component parts.
- parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q'
quality parameter.
- quality(): Determines the quality ('q') of a mime-type when
compared against a list of media-ranges.
- quality_parsed(): Just like quality() except the second parameter must be
pre-parsed.
- best_match(): Choose the mime-type with the highest quality ('q')
from a list of candidates.
"""
__version__ = '0.1.3'
__author__ = 'Joe Gregorio'
__email__ = 'joe@bitworking.org'
__license__ = 'MIT License'
__credits__ = ''
def parse_mime_type(mime_type):
"""Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
into:
('application', 'xhtml', {'q', '0.5'})
"""
parts = mime_type.split(';')
params = dict([tuple([s.strip() for s in param.split('=', 1)])\
for param in parts[1:]
])
full_type = parts[0].strip()
# Java URLConnection class sends an Accept header that includes a
# single '*'. Turn it into a legal wildcard.
if full_type == '*':
full_type = '*/*'
(type, subtype) = full_type.split('/')
return (type.strip(), subtype.strip(), params)
def parse_media_range(range):
"""Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
into:
('application', '*', {'q', '0.5'})
In addition this function also guarantees that there is a value for 'q'
in the params dictionary, filling it in with a proper default if
necessary.
"""
(type, subtype, params) = parse_mime_type(range)
if not params.has_key('q') or not params['q'] or \
not float(params['q']) or float(params['q']) > 1\
or float(params['q']) < 0:
params['q'] = '1'
return (type, subtype, params)
def fitness_and_quality_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality parameter of the best
match, or (-1, 0) if no match was found. Just as for quality_parsed(),
'parsed_ranges' must be a list of parsed media ranges.
"""
best_fitness = -1
best_fit_q = 0
(target_type, target_subtype, target_params) =\
parse_media_range(mime_type)
for (type, subtype, params) in parsed_ranges:
type_match = (type == target_type or\
type == '*' or\
target_type == '*')
subtype_match = (subtype == target_subtype or\
subtype == '*' or\
target_subtype == '*')
if type_match and subtype_match:
param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \
target_params.iteritems() if key != 'q' and \
params.has_key(key) and value == params[key]], 0)
fitness = (type == target_type) and 100 or 0
fitness += (subtype == target_subtype) and 10 or 0
fitness += param_matches
if fitness > best_fitness:
best_fitness = fitness
best_fit_q = params['q']
return best_fitness, float(best_fit_q)
def quality_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns the 'q'
quality parameter of the best match, 0 if no match was found. This function
bahaves the same as quality() except that 'parsed_ranges' must be a list of
parsed media ranges.
"""
return fitness_and_quality_parsed(mime_type, parsed_ranges)[1]
def quality(mime_type, ranges):
"""Return the quality ('q') of a mime-type against a list of media-ranges.
Returns the quality 'q' of a mime-type when compared against the
media-ranges in ranges. For example:
>>> quality('text/html','text/*;q=0.3, text/html;q=0.7,
text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
0.7
"""
parsed_ranges = [parse_media_range(r) for r in ranges.split(',')]
return quality_parsed(mime_type, parsed_ranges)
def best_match(supported, header):
"""Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: header. The value of 'supported'
is a list of mime-types. The list of supported mime-types should be sorted
in order of increasing desirability, in case of a situation where there is
a tie.
>>> best_match(['application/xbel+xml', 'text/xml'],
'text/*;q=0.5,*/*; q=0.1')
'text/xml'
"""
split_header = _filter_blank(header.split(','))
parsed_header = [parse_media_range(r) for r in split_header]
weighted_matches = []
pos = 0
for mime_type in supported:
weighted_matches.append((fitness_and_quality_parsed(mime_type,
parsed_header), pos, mime_type))
pos += 1
weighted_matches.sort()
return weighted_matches[-1][0][1] and weighted_matches[-1][2] or ''
def _filter_blank(i):
for s in i:
if s.strip():
yield s
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Schema processing for discovery based APIs
Schemas holds an APIs discovery schemas. It can return those schema as
deserialized JSON objects, or pretty print them as prototype objects that
conform to the schema.
For example, given the schema:
schema = \"\"\"{
"Foo": {
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of the collection."
},
"kind": {
"type": "string",
"description": "Type of the collection ('calendar#acl').",
"default": "calendar#acl"
},
"nextPageToken": {
"type": "string",
"description": "Token used to access the next
page of this result. Omitted if no further results are available."
}
}
}
}\"\"\"
s = Schemas(schema)
print s.prettyPrintByName('Foo')
Produces the following output:
{
"nextPageToken": "A String", # Token used to access the
# next page of this result. Omitted if no further results are available.
"kind": "A String", # Type of the collection ('calendar#acl').
"etag": "A String", # ETag of the collection.
},
The constructor takes a discovery document in which to look up named schema.
"""
# TODO(jcgregorio) support format, enum, minimum, maximum
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import copy
from oauth2client.anyjson import simplejson
class Schemas(object):
"""Schemas for an API."""
def __init__(self, discovery):
"""Constructor.
Args:
discovery: object, Deserialized discovery document from which we pull
out the named schema.
"""
self.schemas = discovery.get('schemas', {})
# Cache of pretty printed schemas.
self.pretty = {}
def _prettyPrintByName(self, name, seen=None, dent=0):
"""Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
if seen is None:
seen = []
if name in seen:
# Do not fall into an infinite loop over recursive definitions.
return '# Object with schema name: %s' % name
seen.append(name)
if name not in self.pretty:
self.pretty[name] = _SchemaToStruct(self.schemas[name],
seen, dent).to_str(self._prettyPrintByName)
seen.pop()
return self.pretty[name]
def prettyPrintByName(self, name):
"""Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
# Return with trailing comma and newline removed.
return self._prettyPrintByName(name, seen=[], dent=1)[:-2]
def _prettyPrintSchema(self, schema, seen=None, dent=0):
"""Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
if seen is None:
seen = []
return _SchemaToStruct(schema, seen, dent).to_str(self._prettyPrintByName)
def prettyPrintSchema(self, schema):
"""Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
# Return with trailing comma and newline removed.
return self._prettyPrintSchema(schema, dent=1)[:-2]
def get(self, name):
"""Get deserialized JSON schema from the schema name.
Args:
name: string, Schema name.
"""
return self.schemas[name]
class _SchemaToStruct(object):
"""Convert schema to a prototype object."""
def __init__(self, schema, seen, dent=0):
"""Constructor.
Args:
schema: object, Parsed JSON schema.
seen: list, List of names of schema already seen while parsing. Used to
handle recursive definitions.
dent: int, Initial indentation depth.
"""
# The result of this parsing kept as list of strings.
self.value = []
# The final value of the parsing.
self.string = None
# The parsed JSON schema.
self.schema = schema
# Indentation level.
self.dent = dent
# Method that when called returns a prototype object for the schema with
# the given name.
self.from_cache = None
# List of names of schema already seen while parsing.
self.seen = seen
def emit(self, text):
"""Add text as a line to the output.
Args:
text: string, Text to output.
"""
self.value.extend([" " * self.dent, text, '\n'])
def emitBegin(self, text):
"""Add text to the output, but with no line terminator.
Args:
text: string, Text to output.
"""
self.value.extend([" " * self.dent, text])
def emitEnd(self, text, comment):
"""Add text and comment to the output with line terminator.
Args:
text: string, Text to output.
comment: string, Python comment.
"""
if comment:
divider = '\n' + ' ' * (self.dent + 2) + '# '
lines = comment.splitlines()
lines = [x.rstrip() for x in lines]
comment = divider.join(lines)
self.value.extend([text, ' # ', comment, '\n'])
else:
self.value.extend([text, '\n'])
def indent(self):
"""Increase indentation level."""
self.dent += 1
def undent(self):
"""Decrease indentation level."""
self.dent -= 1
def _to_str_impl(self, schema):
"""Prototype object based on the schema, in Python code with comments.
Args:
schema: object, Parsed JSON schema file.
Returns:
Prototype object based on the schema, in Python code with comments.
"""
stype = schema.get('type')
if stype == 'object':
self.emitEnd('{', schema.get('description', ''))
self.indent()
for pname, pschema in schema.get('properties', {}).iteritems():
self.emitBegin('"%s": ' % pname)
self._to_str_impl(pschema)
self.undent()
self.emit('},')
elif '$ref' in schema:
schemaName = schema['$ref']
description = schema.get('description', '')
s = self.from_cache(schemaName, self.seen)
parts = s.splitlines()
self.emitEnd(parts[0], description)
for line in parts[1:]:
self.emit(line.rstrip())
elif stype == 'boolean':
value = schema.get('default', 'True or False')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'string':
value = schema.get('default', 'A String')
self.emitEnd('"%s",' % str(value), schema.get('description', ''))
elif stype == 'integer':
value = schema.get('default', '42')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'number':
value = schema.get('default', '3.14')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'null':
self.emitEnd('None,', schema.get('description', ''))
elif stype == 'any':
self.emitEnd('"",', schema.get('description', ''))
elif stype == 'array':
self.emitEnd('[', schema.get('description'))
self.indent()
self.emitBegin('')
self._to_str_impl(schema['items'])
self.undent()
self.emit('],')
else:
self.emit('Unknown type! %s' % stype)
self.emitEnd('', '')
self.string = ''.join(self.value)
return self.string
def to_str(self, from_cache):
"""Prototype object based on the schema, in Python code with comments.
Args:
from_cache: callable(name, seen), Callable that retrieves an object
prototype for a schema with the given name. Seen is a list of schema
names already seen as we recursively descend the schema definition.
Returns:
Prototype object based on the schema, in Python code with comments.
The lines of the code will all be properly indented.
"""
self.from_cache = from_cache
return self._to_str_impl(self.schema)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility module to import a JSON module
Hides all the messy details of exactly where
we get a simplejson module from.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
try: # pragma: no cover
import simplejson
except ImportError: # pragma: no cover
try:
# Try to import from django, should work on App Engine
from django.utils import simplejson
except ImportError:
# Should work for Python2.6 and higher.
import json as simplejson
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import copy
import httplib2
import logging
import oauth2 as oauth
import urllib
import urlparse
from anyjson import simplejson
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
class Error(Exception):
"""Base error for this module."""
pass
class RequestError(Error):
"""Error occurred during request."""
pass
class MissingParameter(Error):
pass
class CredentialsInvalidError(Error):
pass
def _abstract():
raise NotImplementedError('You need to override this function')
def _oauth_uri(name, discovery, params):
"""Look up the OAuth URI from the discovery
document and add query parameters based on
params.
name - The name of the OAuth URI to lookup, one
of 'request', 'access', or 'authorize'.
discovery - Portion of discovery document the describes
the OAuth endpoints.
params - Dictionary that is used to form the query parameters
for the specified URI.
"""
if name not in ['request', 'access', 'authorize']:
raise KeyError(name)
keys = discovery[name]['parameters'].keys()
query = {}
for key in keys:
if key in params:
query[key] = params[key]
return discovery[name]['url'] + '?' + urllib.urlencode(query)
class Credentials(object):
"""Base class for all Credentials objects.
Subclasses must define an authorize() method
that applies the credentials to an HTTP transport.
"""
def authorize(self, http):
"""Take an httplib2.Http instance (or equivalent) and
authorizes it for the set of credentials, usually by
replacing http.request() with a method that adds in
the appropriate headers and then delegates to the original
Http.request() method.
"""
_abstract()
class Flow(object):
"""Base class for all Flow objects."""
pass
class Storage(object):
"""Base class for all Storage objects.
Store and retrieve a single credential.
"""
def get(self):
"""Retrieve credential.
Returns:
apiclient.oauth.Credentials
"""
_abstract()
def put(self, credentials):
"""Write a credential.
Args:
credentials: Credentials, the credentials to store.
"""
_abstract()
class OAuthCredentials(Credentials):
"""Credentials object for OAuth 1.0a
"""
def __init__(self, consumer, token, user_agent):
"""
consumer - An instance of oauth.Consumer.
token - An instance of oauth.Token constructed with
the access token and secret.
user_agent - The HTTP User-Agent to provide for this application.
"""
self.consumer = consumer
self.token = token
self.user_agent = user_agent
self.store = None
# True if the credentials have been revoked
self._invalid = False
@property
def invalid(self):
"""True if the credentials are invalid, such as being revoked."""
return getattr(self, "_invalid", False)
def set_store(self, store):
"""Set the storage for the credential.
Args:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has been revoked.
"""
self.store = store
def __getstate__(self):
"""Trim the state down to something that can be pickled."""
d = copy.copy(self.__dict__)
del d['store']
return d
def __setstate__(self, state):
"""Reconstitute the state of the object from being pickled."""
self.__dict__.update(state)
self.store = None
def authorize(self, http):
"""Authorize an httplib2.Http instance with these Credentials
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth
subclass of httplib2.Authenication because
it never gets passed the absolute URI, which is
needed for signing. So instead we have to overload
'request' with a closure that adds in the
Authorization header and then calls the original version
of 'request()'.
"""
request_orig = http.request
signer = oauth.SignatureMethod_HMAC_SHA1()
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the appropriate
Authorization header."""
response_code = 302
http.follow_redirects = False
while response_code in [301, 302]:
req = oauth.Request.from_consumer_and_token(
self.consumer, self.token, http_method=method, http_url=uri)
req.sign_request(signer, self.consumer, self.token)
if headers is None:
headers = {}
headers.update(req.to_header())
if 'user-agent' in headers:
headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = self.user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
response_code = resp.status
if response_code in [301, 302]:
uri = resp['location']
# Update the stored credential if it becomes invalid.
if response_code == 401:
logging.info('Access token no longer valid: %s' % content)
self._invalid = True
if self.store is not None:
self.store(self)
raise CredentialsInvalidError("Credentials are no longer valid.")
return resp, content
http.request = new_request
return http
class TwoLeggedOAuthCredentials(Credentials):
"""Two Legged Credentials object for OAuth 1.0a.
The Two Legged object is created directly, not from a flow. Once you
authorize and httplib2.Http instance you can change the requestor and that
change will propogate to the authorized httplib2.Http instance. For example:
http = httplib2.Http()
http = credentials.authorize(http)
credentials.requestor = 'foo@example.info'
http.request(...)
credentials.requestor = 'bar@example.info'
http.request(...)
"""
def __init__(self, consumer_key, consumer_secret, user_agent):
"""
Args:
consumer_key: string, An OAuth 1.0 consumer key
consumer_secret: string, An OAuth 1.0 consumer secret
user_agent: string, The HTTP User-Agent to provide for this application.
"""
self.consumer = oauth.Consumer(consumer_key, consumer_secret)
self.user_agent = user_agent
self.store = None
# email address of the user to act on the behalf of.
self._requestor = None
@property
def invalid(self):
"""True if the credentials are invalid, such as being revoked.
Always returns False for Two Legged Credentials.
"""
return False
def getrequestor(self):
return self._requestor
def setrequestor(self, email):
self._requestor = email
requestor = property(getrequestor, setrequestor, None,
'The email address of the user to act on behalf of')
def set_store(self, store):
"""Set the storage for the credential.
Args:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has been revoked.
"""
self.store = store
def __getstate__(self):
"""Trim the state down to something that can be pickled."""
d = copy.copy(self.__dict__)
del d['store']
return d
def __setstate__(self, state):
"""Reconstitute the state of the object from being pickled."""
self.__dict__.update(state)
self.store = None
def authorize(self, http):
"""Authorize an httplib2.Http instance with these Credentials
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth
subclass of httplib2.Authenication because
it never gets passed the absolute URI, which is
needed for signing. So instead we have to overload
'request' with a closure that adds in the
Authorization header and then calls the original version
of 'request()'.
"""
request_orig = http.request
signer = oauth.SignatureMethod_HMAC_SHA1()
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the appropriate
Authorization header."""
response_code = 302
http.follow_redirects = False
while response_code in [301, 302]:
# add in xoauth_requestor_id=self._requestor to the uri
if self._requestor is None:
raise MissingParameter(
'Requestor must be set before using TwoLeggedOAuthCredentials')
parsed = list(urlparse.urlparse(uri))
q = parse_qsl(parsed[4])
q.append(('xoauth_requestor_id', self._requestor))
parsed[4] = urllib.urlencode(q)
uri = urlparse.urlunparse(parsed)
req = oauth.Request.from_consumer_and_token(
self.consumer, None, http_method=method, http_url=uri)
req.sign_request(signer, self.consumer, None)
if headers is None:
headers = {}
headers.update(req.to_header())
if 'user-agent' in headers:
headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = self.user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
response_code = resp.status
if response_code in [301, 302]:
uri = resp['location']
if response_code == 401:
logging.info('Access token no longer valid: %s' % content)
# Do not store the invalid state of the Credentials because
# being 2LO they could be reinstated in the future.
raise CredentialsInvalidError("Credentials are invalid.")
return resp, content
http.request = new_request
return http
class FlowThreeLegged(Flow):
"""Does the Three Legged Dance for OAuth 1.0a.
"""
def __init__(self, discovery, consumer_key, consumer_secret, user_agent,
**kwargs):
"""
discovery - Section of the API discovery document that describes
the OAuth endpoints.
consumer_key - OAuth consumer key
consumer_secret - OAuth consumer secret
user_agent - The HTTP User-Agent that identifies the application.
**kwargs - The keyword arguments are all optional and required
parameters for the OAuth calls.
"""
self.discovery = discovery
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.user_agent = user_agent
self.params = kwargs
self.request_token = {}
required = {}
for uriinfo in discovery.itervalues():
for name, value in uriinfo['parameters'].iteritems():
if value['required'] and not name.startswith('oauth_'):
required[name] = 1
for key in required.iterkeys():
if key not in self.params:
raise MissingParameter('Required parameter %s not supplied' % key)
def step1_get_authorize_url(self, oauth_callback='oob'):
"""Returns a URI to redirect to the provider.
oauth_callback - Either the string 'oob' for a non-web-based application,
or a URI that handles the callback from the authorization
server.
If oauth_callback is 'oob' then pass in the
generated verification code to step2_exchange,
otherwise pass in the query parameters received
at the callback uri to step2_exchange.
"""
consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
client = oauth.Client(consumer)
headers = {
'user-agent': self.user_agent,
'content-type': 'application/x-www-form-urlencoded'
}
body = urllib.urlencode({'oauth_callback': oauth_callback})
uri = _oauth_uri('request', self.discovery, self.params)
resp, content = client.request(uri, 'POST', headers=headers,
body=body)
if resp['status'] != '200':
logging.error('Failed to retrieve temporary authorization: %s', content)
raise RequestError('Invalid response %s.' % resp['status'])
self.request_token = dict(parse_qsl(content))
auth_params = copy.copy(self.params)
auth_params['oauth_token'] = self.request_token['oauth_token']
return _oauth_uri('authorize', self.discovery, auth_params)
def step2_exchange(self, verifier):
"""Exhanges an authorized request token
for OAuthCredentials.
Args:
verifier: string, dict - either the verifier token, or a dictionary
of the query parameters to the callback, which contains
the oauth_verifier.
Returns:
The Credentials object.
"""
if not (isinstance(verifier, str) or isinstance(verifier, unicode)):
verifier = verifier['oauth_verifier']
token = oauth.Token(
self.request_token['oauth_token'],
self.request_token['oauth_token_secret'])
token.set_verifier(verifier)
consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
client = oauth.Client(consumer, token)
headers = {
'user-agent': self.user_agent,
'content-type': 'application/x-www-form-urlencoded'
}
uri = _oauth_uri('access', self.discovery, self.params)
resp, content = client.request(uri, 'POST', headers=headers)
if resp['status'] != '200':
logging.error('Failed to retrieve access token: %s', content)
raise RequestError('Invalid response %s.' % resp['status'])
oauth_params = dict(parse_qsl(content))
token = oauth.Token(
oauth_params['oauth_token'],
oauth_params['oauth_token_secret'])
return OAuthCredentials(consumer, token, self.user_agent)
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Client for discovery based APIs
A client library for Google's discovery based APIs.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
__all__ = [
'build',
'build_from_document'
'fix_method_name',
'key2param'
]
import copy
import httplib2
import logging
import os
import random
import re
import uritemplate
import urllib
import urlparse
import mimeparse
import mimetypes
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
from apiclient.errors import HttpError
from apiclient.errors import InvalidJsonError
from apiclient.errors import MediaUploadSizeError
from apiclient.errors import UnacceptableMimeTypeError
from apiclient.errors import UnknownApiNameOrVersion
from apiclient.errors import UnknownLinkType
from apiclient.http import HttpRequest
from apiclient.http import MediaFileUpload
from apiclient.http import MediaUpload
from apiclient.model import JsonModel
from apiclient.model import MediaModel
from apiclient.model import RawModel
from apiclient.schema import Schemas
from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart
from oauth2client.anyjson import simplejson
logger = logging.getLogger(__name__)
URITEMPLATE = re.compile('{[^}]*}')
VARNAME = re.compile('[a-zA-Z0-9_-]+')
DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/'
'{api}/{apiVersion}/rest')
DEFAULT_METHOD_DOC = 'A description of how to use this function'
# Parameters accepted by the stack, but not visible via discovery.
STACK_QUERY_PARAMETERS = ['trace', 'pp', 'userip', 'strict']
# Python reserved words.
RESERVED_WORDS = ['and', 'assert', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'exec', 'finally', 'for', 'from',
'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or',
'pass', 'print', 'raise', 'return', 'try', 'while' ]
def fix_method_name(name):
"""Fix method names to avoid reserved word conflicts.
Args:
name: string, method name.
Returns:
The name with a '_' prefixed if the name is a reserved word.
"""
if name in RESERVED_WORDS:
return name + '_'
else:
return name
def _add_query_parameter(url, name, value):
"""Adds a query parameter to a url.
Replaces the current value if it already exists in the URL.
Args:
url: string, url to add the query parameter to.
name: string, query parameter name.
value: string, query parameter value.
Returns:
Updated query parameter. Does not update the url if value is None.
"""
if value is None:
return url
else:
parsed = list(urlparse.urlparse(url))
q = dict(parse_qsl(parsed[4]))
q[name] = value
parsed[4] = urllib.urlencode(q)
return urlparse.urlunparse(parsed)
def key2param(key):
"""Converts key names into parameter names.
For example, converting "max-results" -> "max_results"
Args:
key: string, the method key name.
Returns:
A safe method name based on the key name.
"""
result = []
key = list(key)
if not key[0].isalpha():
result.append('x')
for c in key:
if c.isalnum():
result.append(c)
else:
result.append('_')
return ''.join(result)
def build(serviceName,
version,
http=None,
discoveryServiceUrl=DISCOVERY_URI,
developerKey=None,
model=None,
requestBuilder=HttpRequest):
"""Construct a Resource for interacting with an API.
Construct a Resource object for interacting with an API. The serviceName and
version are the names from the Discovery service.
Args:
serviceName: string, name of the service.
version: string, the version of the service.
http: httplib2.Http, An instance of httplib2.Http or something that acts
like it that HTTP requests will be made through.
discoveryServiceUrl: string, a URI Template that points to the location of
the discovery service. It should have two parameters {api} and
{apiVersion} that when filled in produce an absolute URI to the discovery
document for that service.
developerKey: string, key obtained from
https://code.google.com/apis/console.
model: apiclient.Model, converts to and from the wire format.
requestBuilder: apiclient.http.HttpRequest, encapsulator for an HTTP
request.
Returns:
A Resource object with methods for interacting with the service.
"""
params = {
'api': serviceName,
'apiVersion': version
}
if http is None:
http = httplib2.Http()
requested_url = uritemplate.expand(discoveryServiceUrl, params)
# REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment
# variable that contains the network address of the client sending the
# request. If it exists then add that to the request for the discovery
# document to avoid exceeding the quota on discovery requests.
if 'REMOTE_ADDR' in os.environ:
requested_url = _add_query_parameter(requested_url, 'userIp',
os.environ['REMOTE_ADDR'])
logger.info('URL being requested: %s' % requested_url)
resp, content = http.request(requested_url)
if resp.status == 404:
raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName,
version))
if resp.status >= 400:
raise HttpError(resp, content, requested_url)
try:
service = simplejson.loads(content)
except ValueError, e:
logger.error('Failed to parse as JSON: ' + content)
raise InvalidJsonError()
return build_from_document(content, discoveryServiceUrl, http=http,
developerKey=developerKey, model=model, requestBuilder=requestBuilder)
def build_from_document(
service,
base,
future=None,
http=None,
developerKey=None,
model=None,
requestBuilder=HttpRequest):
"""Create a Resource for interacting with an API.
Same as `build()`, but constructs the Resource object from a discovery
document that is it given, as opposed to retrieving one over HTTP.
Args:
service: string, discovery document.
base: string, base URI for all HTTP requests, usually the discovery URI.
future: string, discovery document with future capabilities (deprecated).
http: httplib2.Http, An instance of httplib2.Http or something that acts
like it that HTTP requests will be made through.
developerKey: string, Key for controlling API usage, generated
from the API Console.
model: Model class instance that serializes and de-serializes requests and
responses.
requestBuilder: Takes an http request and packages it up to be executed.
Returns:
A Resource object with methods for interacting with the service.
"""
# future is no longer used.
future = {}
service = simplejson.loads(service)
base = urlparse.urljoin(base, service['basePath'])
schema = Schemas(service)
if model is None:
features = service.get('features', [])
model = JsonModel('dataWrapper' in features)
resource = _createResource(http, base, model, requestBuilder, developerKey,
service, service, schema)
return resource
def _cast(value, schema_type):
"""Convert value to a string based on JSON Schema type.
See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on
JSON Schema.
Args:
value: any, the value to convert
schema_type: string, the type that value should be interpreted as
Returns:
A string representation of 'value' based on the schema_type.
"""
if schema_type == 'string':
if type(value) == type('') or type(value) == type(u''):
return value
else:
return str(value)
elif schema_type == 'integer':
return str(int(value))
elif schema_type == 'number':
return str(float(value))
elif schema_type == 'boolean':
return str(bool(value)).lower()
else:
if type(value) == type('') or type(value) == type(u''):
return value
else:
return str(value)
MULTIPLIERS = {
"KB": 2 ** 10,
"MB": 2 ** 20,
"GB": 2 ** 30,
"TB": 2 ** 40,
}
def _media_size_to_long(maxSize):
"""Convert a string media size, such as 10GB or 3TB into an integer.
Args:
maxSize: string, size as a string, such as 2MB or 7GB.
Returns:
The size as an integer value.
"""
if len(maxSize) < 2:
return 0
units = maxSize[-2:].upper()
multiplier = MULTIPLIERS.get(units, 0)
if multiplier:
return int(maxSize[:-2]) * multiplier
else:
return int(maxSize)
def _createResource(http, baseUrl, model, requestBuilder,
developerKey, resourceDesc, rootDesc, schema):
"""Build a Resource from the API description.
Args:
http: httplib2.Http, Object to make http requests with.
baseUrl: string, base URL for the API. All requests are relative to this
URI.
model: apiclient.Model, converts to and from the wire format.
requestBuilder: class or callable that instantiates an
apiclient.HttpRequest object.
developerKey: string, key obtained from
https://code.google.com/apis/console
resourceDesc: object, section of deserialized discovery document that
describes a resource. Note that the top level discovery document
is considered a resource.
rootDesc: object, the entire deserialized discovery document.
schema: object, mapping of schema names to schema descriptions.
Returns:
An instance of Resource with all the methods attached for interacting with
that resource.
"""
class Resource(object):
"""A class for interacting with a resource."""
def __init__(self):
self._http = http
self._baseUrl = baseUrl
self._model = model
self._developerKey = developerKey
self._requestBuilder = requestBuilder
def createMethod(theclass, methodName, methodDesc, rootDesc):
"""Creates a method for attaching to a Resource.
Args:
theclass: type, the class to attach methods to.
methodName: string, name of the method to use.
methodDesc: object, fragment of deserialized discovery document that
describes the method.
rootDesc: object, the entire deserialized discovery document.
"""
methodName = fix_method_name(methodName)
pathUrl = methodDesc['path']
httpMethod = methodDesc['httpMethod']
methodId = methodDesc['id']
mediaPathUrl = None
accept = []
maxSize = 0
if 'mediaUpload' in methodDesc:
mediaUpload = methodDesc['mediaUpload']
# TODO(jcgregorio) Use URLs from discovery once it is updated.
parsed = list(urlparse.urlparse(baseUrl))
basePath = parsed[2]
mediaPathUrl = '/upload' + basePath + pathUrl
accept = mediaUpload['accept']
maxSize = _media_size_to_long(mediaUpload.get('maxSize', ''))
if 'parameters' not in methodDesc:
methodDesc['parameters'] = {}
# Add in the parameters common to all methods.
for name, desc in rootDesc.get('parameters', {}).iteritems():
methodDesc['parameters'][name] = desc
# Add in undocumented query parameters.
for name in STACK_QUERY_PARAMETERS:
methodDesc['parameters'][name] = {
'type': 'string',
'location': 'query'
}
if httpMethod in ['PUT', 'POST', 'PATCH'] and 'request' in methodDesc:
methodDesc['parameters']['body'] = {
'description': 'The request body.',
'type': 'object',
'required': True,
}
if 'request' in methodDesc:
methodDesc['parameters']['body'].update(methodDesc['request'])
else:
methodDesc['parameters']['body']['type'] = 'object'
if 'mediaUpload' in methodDesc:
methodDesc['parameters']['media_body'] = {
'description': 'The filename of the media request body.',
'type': 'string',
'required': False,
}
if 'body' in methodDesc['parameters']:
methodDesc['parameters']['body']['required'] = False
argmap = {} # Map from method parameter name to query parameter name
required_params = [] # Required parameters
repeated_params = [] # Repeated parameters
pattern_params = {} # Parameters that must match a regex
query_params = [] # Parameters that will be used in the query string
path_params = {} # Parameters that will be used in the base URL
param_type = {} # The type of the parameter
enum_params = {} # Allowable enumeration values for each parameter
if 'parameters' in methodDesc:
for arg, desc in methodDesc['parameters'].iteritems():
param = key2param(arg)
argmap[param] = arg
if desc.get('pattern', ''):
pattern_params[param] = desc['pattern']
if desc.get('enum', ''):
enum_params[param] = desc['enum']
if desc.get('required', False):
required_params.append(param)
if desc.get('repeated', False):
repeated_params.append(param)
if desc.get('location') == 'query':
query_params.append(param)
if desc.get('location') == 'path':
path_params[param] = param
param_type[param] = desc.get('type', 'string')
for match in URITEMPLATE.finditer(pathUrl):
for namematch in VARNAME.finditer(match.group(0)):
name = key2param(namematch.group(0))
path_params[name] = name
if name in query_params:
query_params.remove(name)
def method(self, **kwargs):
# Don't bother with doc string, it will be over-written by createMethod.
for name in kwargs.iterkeys():
if name not in argmap:
raise TypeError('Got an unexpected keyword argument "%s"' % name)
# Remove args that have a value of None.
keys = kwargs.keys()
for name in keys:
if kwargs[name] is None:
del kwargs[name]
for name in required_params:
if name not in kwargs:
raise TypeError('Missing required parameter "%s"' % name)
for name, regex in pattern_params.iteritems():
if name in kwargs:
if isinstance(kwargs[name], basestring):
pvalues = [kwargs[name]]
else:
pvalues = kwargs[name]
for pvalue in pvalues:
if re.match(regex, pvalue) is None:
raise TypeError(
'Parameter "%s" value "%s" does not match the pattern "%s"' %
(name, pvalue, regex))
for name, enums in enum_params.iteritems():
if name in kwargs:
# We need to handle the case of a repeated enum
# name differently, since we want to handle both
# arg='value' and arg=['value1', 'value2']
if (name in repeated_params and
not isinstance(kwargs[name], basestring)):
values = kwargs[name]
else:
values = [kwargs[name]]
for value in values:
if value not in enums:
raise TypeError(
'Parameter "%s" value "%s" is not an allowed value in "%s"' %
(name, value, str(enums)))
actual_query_params = {}
actual_path_params = {}
for key, value in kwargs.iteritems():
to_type = param_type.get(key, 'string')
# For repeated parameters we cast each member of the list.
if key in repeated_params and type(value) == type([]):
cast_value = [_cast(x, to_type) for x in value]
else:
cast_value = _cast(value, to_type)
if key in query_params:
actual_query_params[argmap[key]] = cast_value
if key in path_params:
actual_path_params[argmap[key]] = cast_value
body_value = kwargs.get('body', None)
media_filename = kwargs.get('media_body', None)
if self._developerKey:
actual_query_params['key'] = self._developerKey
model = self._model
# If there is no schema for the response then presume a binary blob.
if methodName.endswith('_media'):
model = MediaModel()
elif 'response' not in methodDesc:
model = RawModel()
headers = {}
headers, params, query, body = model.request(headers,
actual_path_params, actual_query_params, body_value)
expanded_url = uritemplate.expand(pathUrl, params)
url = urlparse.urljoin(self._baseUrl, expanded_url + query)
resumable = None
multipart_boundary = ''
if media_filename:
# Ensure we end up with a valid MediaUpload object.
if isinstance(media_filename, basestring):
(media_mime_type, encoding) = mimetypes.guess_type(media_filename)
if media_mime_type is None:
raise UnknownFileType(media_filename)
if not mimeparse.best_match([media_mime_type], ','.join(accept)):
raise UnacceptableMimeTypeError(media_mime_type)
media_upload = MediaFileUpload(media_filename, media_mime_type)
elif isinstance(media_filename, MediaUpload):
media_upload = media_filename
else:
raise TypeError('media_filename must be str or MediaUpload.')
# Check the maxSize
if maxSize > 0 and media_upload.size() > maxSize:
raise MediaUploadSizeError("Media larger than: %s" % maxSize)
# Use the media path uri for media uploads
expanded_url = uritemplate.expand(mediaPathUrl, params)
url = urlparse.urljoin(self._baseUrl, expanded_url + query)
if media_upload.resumable():
url = _add_query_parameter(url, 'uploadType', 'resumable')
if media_upload.resumable():
# This is all we need to do for resumable, if the body exists it gets
# sent in the first request, otherwise an empty body is sent.
resumable = media_upload
else:
# A non-resumable upload
if body is None:
# This is a simple media upload
headers['content-type'] = media_upload.mimetype()
body = media_upload.getbytes(0, media_upload.size())
url = _add_query_parameter(url, 'uploadType', 'media')
else:
# This is a multipart/related upload.
msgRoot = MIMEMultipart('related')
# msgRoot should not write out it's own headers
setattr(msgRoot, '_write_headers', lambda self: None)
# attach the body as one part
msg = MIMENonMultipart(*headers['content-type'].split('/'))
msg.set_payload(body)
msgRoot.attach(msg)
# attach the media as the second part
msg = MIMENonMultipart(*media_upload.mimetype().split('/'))
msg['Content-Transfer-Encoding'] = 'binary'
payload = media_upload.getbytes(0, media_upload.size())
msg.set_payload(payload)
msgRoot.attach(msg)
body = msgRoot.as_string()
multipart_boundary = msgRoot.get_boundary()
headers['content-type'] = ('multipart/related; '
'boundary="%s"') % multipart_boundary
url = _add_query_parameter(url, 'uploadType', 'multipart')
logger.info('URL being requested: %s' % url)
return self._requestBuilder(self._http,
model.response,
url,
method=httpMethod,
body=body,
headers=headers,
methodId=methodId,
resumable=resumable)
docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n']
if len(argmap) > 0:
docs.append('Args:\n')
# Skip undocumented params and params common to all methods.
skip_parameters = rootDesc.get('parameters', {}).keys()
skip_parameters.append(STACK_QUERY_PARAMETERS)
for arg in argmap.iterkeys():
if arg in skip_parameters:
continue
repeated = ''
if arg in repeated_params:
repeated = ' (repeated)'
required = ''
if arg in required_params:
required = ' (required)'
paramdesc = methodDesc['parameters'][argmap[arg]]
paramdoc = paramdesc.get('description', 'A parameter')
if '$ref' in paramdesc:
docs.append(
(' %s: object, %s%s%s\n The object takes the'
' form of:\n\n%s\n\n') % (arg, paramdoc, required, repeated,
schema.prettyPrintByName(paramdesc['$ref'])))
else:
paramtype = paramdesc.get('type', 'string')
docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required,
repeated))
enum = paramdesc.get('enum', [])
enumDesc = paramdesc.get('enumDescriptions', [])
if enum and enumDesc:
docs.append(' Allowed values\n')
for (name, desc) in zip(enum, enumDesc):
docs.append(' %s - %s\n' % (name, desc))
if 'response' in methodDesc:
if methodName.endswith('_media'):
docs.append('\nReturns:\n The media object as a string.\n\n ')
else:
docs.append('\nReturns:\n An object of the form:\n\n ')
docs.append(schema.prettyPrintSchema(methodDesc['response']))
setattr(method, '__doc__', ''.join(docs))
setattr(theclass, methodName, method)
def createNextMethod(theclass, methodName, methodDesc, rootDesc):
"""Creates any _next methods for attaching to a Resource.
The _next methods allow for easy iteration through list() responses.
Args:
theclass: type, the class to attach methods to.
methodName: string, name of the method to use.
methodDesc: object, fragment of deserialized discovery document that
describes the method.
rootDesc: object, the entire deserialized discovery document.
"""
methodName = fix_method_name(methodName)
methodId = methodDesc['id'] + '.next'
def methodNext(self, previous_request, previous_response):
"""Retrieves the next page of results.
Args:
previous_request: The request for the previous page.
previous_response: The response from the request for the previous page.
Returns:
A request object that you can call 'execute()' on to request the next
page. Returns None if there are no more items in the collection.
"""
# Retrieve nextPageToken from previous_response
# Use as pageToken in previous_request to create new request.
if 'nextPageToken' not in previous_response:
return None
request = copy.copy(previous_request)
pageToken = previous_response['nextPageToken']
parsed = list(urlparse.urlparse(request.uri))
q = parse_qsl(parsed[4])
# Find and remove old 'pageToken' value from URI
newq = [(key, value) for (key, value) in q if key != 'pageToken']
newq.append(('pageToken', pageToken))
parsed[4] = urllib.urlencode(newq)
uri = urlparse.urlunparse(parsed)
request.uri = uri
logger.info('URL being requested: %s' % uri)
return request
setattr(theclass, methodName, methodNext)
# Add basic methods to Resource
if 'methods' in resourceDesc:
for methodName, methodDesc in resourceDesc['methods'].iteritems():
createMethod(Resource, methodName, methodDesc, rootDesc)
# Add in _media methods. The functionality of the attached method will
# change when it sees that the method name ends in _media.
if methodDesc.get('supportsMediaDownload', False):
createMethod(Resource, methodName + '_media', methodDesc, rootDesc)
# Add in nested resources
if 'resources' in resourceDesc:
def createResourceMethod(theclass, methodName, methodDesc, rootDesc):
"""Create a method on the Resource to access a nested Resource.
Args:
theclass: type, the class to attach methods to.
methodName: string, name of the method to use.
methodDesc: object, fragment of deserialized discovery document that
describes the method.
rootDesc: object, the entire deserialized discovery document.
"""
methodName = fix_method_name(methodName)
def methodResource(self):
return _createResource(self._http, self._baseUrl, self._model,
self._requestBuilder, self._developerKey,
methodDesc, rootDesc, schema)
setattr(methodResource, '__doc__', 'A collection resource.')
setattr(methodResource, '__is_resource__', True)
setattr(theclass, methodName, methodResource)
for methodName, methodDesc in resourceDesc['resources'].iteritems():
createResourceMethod(Resource, methodName, methodDesc, rootDesc)
# Add _next() methods
# Look for response bodies in schema that contain nextPageToken, and methods
# that take a pageToken parameter.
if 'methods' in resourceDesc:
for methodName, methodDesc in resourceDesc['methods'].iteritems():
if 'response' in methodDesc:
responseSchema = methodDesc['response']
if '$ref' in responseSchema:
responseSchema = schema.get(responseSchema['$ref'])
hasNextPageToken = 'nextPageToken' in responseSchema.get('properties',
{})
hasPageToken = 'pageToken' in methodDesc.get('parameters', {})
if hasNextPageToken and hasPageToken:
createNextMethod(Resource, methodName + '_next',
resourceDesc['methods'][methodName],
methodName)
return Resource()
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for Google App Engine
Utilities for making it easier to use the
Google API Client for Python on Google App Engine.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import pickle
from google.appengine.ext import db
from apiclient.oauth import OAuthCredentials
from apiclient.oauth import FlowThreeLegged
class FlowThreeLeggedProperty(db.Property):
"""Utility property that allows easy
storage and retreival of an
apiclient.oauth.FlowThreeLegged"""
# Tell what the user type is.
data_type = FlowThreeLegged
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
flow = super(FlowThreeLeggedProperty,
self).get_value_for_datastore(model_instance)
return db.Blob(pickle.dumps(flow))
# For reading from datastore.
def make_value_from_datastore(self, value):
if value is None:
return None
return pickle.loads(value)
def validate(self, value):
if value is not None and not isinstance(value, FlowThreeLegged):
raise BadValueError('Property %s must be convertible '
'to a FlowThreeLegged instance (%s)' %
(self.name, value))
return super(FlowThreeLeggedProperty, self).validate(value)
def empty(self, value):
return not value
class OAuthCredentialsProperty(db.Property):
"""Utility property that allows easy
storage and retrieval of
apiclient.oath.OAuthCredentials
"""
# Tell what the user type is.
data_type = OAuthCredentials
# For writing to datastore.
def get_value_for_datastore(self, model_instance):
cred = super(OAuthCredentialsProperty,
self).get_value_for_datastore(model_instance)
return db.Blob(pickle.dumps(cred))
# For reading from datastore.
def make_value_from_datastore(self, value):
if value is None:
return None
return pickle.loads(value)
def validate(self, value):
if value is not None and not isinstance(value, OAuthCredentials):
raise BadValueError('Property %s must be convertible '
'to an OAuthCredentials instance (%s)' %
(self.name, value))
return super(OAuthCredentialsProperty, self).validate(value)
def empty(self, value):
return not value
class StorageByKeyName(object):
"""Store and retrieve a single credential to and from
the App Engine datastore.
This Storage helper presumes the Credentials
have been stored as a CredenialsProperty
on a datastore model class, and that entities
are stored by key_name.
"""
def __init__(self, model, key_name, property_name):
"""Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
property_name: string, name of the property that is a CredentialsProperty
"""
self.model = model
self.key_name = key_name
self.property_name = property_name
def get(self):
"""Retrieve Credential from datastore.
Returns:
Credentials
"""
entity = self.model.get_or_insert(self.key_name)
credential = getattr(entity, self.property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self.put)
return credential
def put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
entity = self.model.get_or_insert(self.key_name)
setattr(entity, self.property_name, credentials)
entity.put()
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command-line tools for authenticating via OAuth 1.0
Do the OAuth 1.0 Three Legged Dance for
a command line application. Stores the generated
credentials in a common file that is used by
other example apps in the same directory.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
__all__ = ["run"]
import BaseHTTPServer
import gflags
import logging
import socket
import sys
from optparse import OptionParser
from apiclient.oauth import RequestError
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('auth_local_webserver', True,
('Run a local web server to handle redirects during '
'OAuth authorization.'))
gflags.DEFINE_string('auth_host_name', 'localhost',
('Host name to use when running a local web server to '
'handle redirects during OAuth authorization.'))
gflags.DEFINE_multi_int('auth_host_port', [8080, 8090],
('Port to use when running a local web server to '
'handle redirects during OAuth authorization.'))
class ClientRedirectServer(BaseHTTPServer.HTTPServer):
"""A server to handle OAuth 1.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into query_params and then stops serving.
"""
query_params = {}
class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""A handler for OAuth 1.0 redirects back to localhost.
Waits for a single request and parses the query parameters
into the servers query_params and then stops serving.
"""
def do_GET(s):
"""Handle a GET request
Parses the query parameters and prints a message
if the flow has completed. Note that we can't detect
if an error occurred.
"""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
query = s.path.split('?', 1)[-1]
query = dict(parse_qsl(query))
s.server.query_params = query
s.wfile.write("<html><head><title>Authentication Status</title></head>")
s.wfile.write("<body><p>The authentication flow has completed.</p>")
s.wfile.write("</body></html>")
def log_message(self, format, *args):
"""Do not log messages to stdout while running as command line program."""
pass
def run(flow, storage):
"""Core code for a command-line application.
Args:
flow: Flow, an OAuth 1.0 Flow to step through.
storage: Storage, a Storage to store the credential in.
Returns:
Credentials, the obtained credential.
Exceptions:
RequestError: if step2 of the flow fails.
Args:
"""
if FLAGS.auth_local_webserver:
success = False
port_number = 0
for port in FLAGS.auth_host_port:
port_number = port
try:
httpd = BaseHTTPServer.HTTPServer((FLAGS.auth_host_name, port),
ClientRedirectHandler)
except socket.error, e:
pass
else:
success = True
break
FLAGS.auth_local_webserver = success
if FLAGS.auth_local_webserver:
oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number)
else:
oauth_callback = 'oob'
authorize_url = flow.step1_get_authorize_url(oauth_callback)
print 'Go to the following link in your browser:'
print authorize_url
print
if FLAGS.auth_local_webserver:
print 'If your browser is on a different machine then exit and re-run this'
print 'application with the command-line parameter --noauth_local_webserver.'
print
if FLAGS.auth_local_webserver:
httpd.handle_request()
if 'error' in httpd.query_params:
sys.exit('Authentication request was rejected.')
if 'oauth_verifier' in httpd.query_params:
code = httpd.query_params['oauth_verifier']
else:
accepted = 'n'
while accepted.lower() == 'n':
accepted = raw_input('Have you authorized me? (y/n) ')
code = raw_input('What is the verification code? ').strip()
try:
credentials = flow.step2_exchange(code)
except RequestError:
sys.exit('The authentication has failed.')
storage.put(credentials)
credentials.set_store(storage.put)
print "You have successfully authenticated."
return credentials
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth 1.0 credentials.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import pickle
import threading
from apiclient.oauth import Storage as BaseStorage
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from a file."""
def __init__(self, filename):
self._filename = filename
self._lock = threading.Lock()
def get(self):
"""Retrieve Credential from file.
Returns:
apiclient.oauth.Credentials
"""
self._lock.acquire()
try:
f = open(self._filename, 'r')
credentials = pickle.loads(f.read())
f.close()
credentials.set_store(self.put)
except:
credentials = None
self._lock.release()
return credentials
def put(self, credentials):
"""Write a pickled Credentials to file.
Args:
credentials: Credentials, the credentials to store.
"""
self._lock.acquire()
f = open(self._filename, 'w')
f.write(pickle.dumps(credentials))
f.close()
self._lock.release()
| Python |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import apiclient
import base64
import pickle
from django.db import models
class OAuthCredentialsField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self):
return 'VARCHAR'
def to_python(self, value):
if value is None:
return None
if isinstance(value, apiclient.oauth.Credentials):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value):
return base64.b64encode(pickle.dumps(value))
class FlowThreeLeggedField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self):
return 'VARCHAR'
def to_python(self, value):
print "In to_python", value
if value is None:
return None
if isinstance(value, apiclient.oauth.FlowThreeLegged):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value):
return base64.b64encode(pickle.dumps(value))
| Python |
__version__ = "1.0c2"
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model objects for requests and responses.
Each API may support one or more serializations, such
as JSON, Atom, etc. The model classes are responsible
for converting between the wire format and the Python
object representation.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import logging
import urllib
from errors import HttpError
from oauth2client.anyjson import simplejson
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('dump_request_response', False,
'Dump all http server requests and responses. '
)
def _abstract():
raise NotImplementedError('You need to override this function')
class Model(object):
"""Model base class.
All Model classes should implement this interface.
The Model serializes and de-serializes between a wire
format such as JSON and a Python object representation.
"""
def request(self, headers, path_params, query_params, body_value):
"""Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable.
Returns:
A tuple of (headers, path_params, query, body)
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query: string, query part of the request URI
body: string, the body serialized in the desired wire format.
"""
_abstract()
def response(self, resp, content):
"""Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.
"""
_abstract()
class BaseModel(Model):
"""Base model class.
Subclasses should provide implementations for the "serialize" and
"deserialize" methods, as well as values for the following class attributes.
Attributes:
accept: The value to use for the HTTP Accept header.
content_type: The value to use for the HTTP Content-type header.
no_content_response: The value to return when deserializing a 204 "No
Content" response.
alt_param: The value to supply as the "alt" query parameter for requests.
"""
accept = None
content_type = None
no_content_response = None
alt_param = None
def _log_request(self, headers, path_params, query, body):
"""Logs debugging information about the request if requested."""
if FLAGS.dump_request_response:
logging.info('--request-start--')
logging.info('-headers-start-')
for h, v in headers.iteritems():
logging.info('%s: %s', h, v)
logging.info('-headers-end-')
logging.info('-path-parameters-start-')
for h, v in path_params.iteritems():
logging.info('%s: %s', h, v)
logging.info('-path-parameters-end-')
logging.info('body: %s', body)
logging.info('query: %s', query)
logging.info('--request-end--')
def request(self, headers, path_params, query_params, body_value):
"""Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable by simplejson.
Returns:
A tuple of (headers, path_params, query, body)
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query: string, query part of the request URI
body: string, the body serialized as JSON
"""
query = self._build_query(query_params)
headers['accept'] = self.accept
headers['accept-encoding'] = 'gzip, deflate'
if 'user-agent' in headers:
headers['user-agent'] += ' '
else:
headers['user-agent'] = ''
headers['user-agent'] += 'google-api-python-client/1.0'
if body_value is not None:
headers['content-type'] = self.content_type
body_value = self.serialize(body_value)
self._log_request(headers, path_params, query, body_value)
return (headers, path_params, query, body_value)
def _build_query(self, params):
"""Builds a query string.
Args:
params: dict, the query parameters
Returns:
The query parameters properly encoded into an HTTP URI query string.
"""
if self.alt_param is not None:
params.update({'alt': self.alt_param})
astuples = []
for key, value in params.iteritems():
if type(value) == type([]):
for x in value:
x = x.encode('utf-8')
astuples.append((key, x))
else:
if getattr(value, 'encode', False) and callable(value.encode):
value = value.encode('utf-8')
astuples.append((key, value))
return '?' + urllib.urlencode(astuples)
def _log_response(self, resp, content):
"""Logs debugging information about the response if requested."""
if FLAGS.dump_request_response:
logging.info('--response-start--')
for h, v in resp.iteritems():
logging.info('%s: %s', h, v)
if content:
logging.info(content)
logging.info('--response-end--')
def response(self, resp, content):
"""Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.
"""
self._log_response(resp, content)
# Error handling is TBD, for example, do we retry
# for some operation/error combinations?
if resp.status < 300:
if resp.status == 204:
# A 204: No Content response should be treated differently
# to all the other success states
return self.no_content_response
return self.deserialize(content)
else:
logging.debug('Content from bad request was: %s' % content)
raise HttpError(resp, content)
def serialize(self, body_value):
"""Perform the actual Python object serialization.
Args:
body_value: object, the request body as a Python object.
Returns:
string, the body in serialized form.
"""
_abstract()
def deserialize(self, content):
"""Perform the actual deserialization from response string to Python
object.
Args:
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
"""
_abstract()
class JsonModel(BaseModel):
"""Model class for JSON.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request and response bodies.
"""
accept = 'application/json'
content_type = 'application/json'
alt_param = 'json'
def __init__(self, data_wrapper=False):
"""Construct a JsonModel.
Args:
data_wrapper: boolean, wrap requests and responses in a data wrapper
"""
self._data_wrapper = data_wrapper
def serialize(self, body_value):
if (isinstance(body_value, dict) and 'data' not in body_value and
self._data_wrapper):
body_value = {'data': body_value}
return simplejson.dumps(body_value)
def deserialize(self, content):
body = simplejson.loads(content)
if isinstance(body, dict) and 'data' in body:
body = body['data']
return body
@property
def no_content_response(self):
return {}
class RawModel(JsonModel):
"""Model class for requests that don't return JSON.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request, and returns the raw bytes
of the response body.
"""
accept = '*/*'
content_type = 'application/json'
alt_param = None
def deserialize(self, content):
return content
@property
def no_content_response(self):
return ''
class MediaModel(JsonModel):
"""Model class for requests that return Media.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request, and returns the raw bytes
of the response body.
"""
accept = '*/*'
content_type = 'application/json'
alt_param = 'media'
def deserialize(self, content):
return content
@property
def no_content_response(self):
return ''
class ProtocolBufferModel(BaseModel):
"""Model class for protocol buffers.
Serializes and de-serializes the binary protocol buffer sent in the HTTP
request and response bodies.
"""
accept = 'application/x-protobuf'
content_type = 'application/x-protobuf'
alt_param = 'proto'
def __init__(self, protocol_buffer):
"""Constructs a ProtocolBufferModel.
The serialzed protocol buffer returned in an HTTP response will be
de-serialized using the given protocol buffer class.
Args:
protocol_buffer: The protocol buffer class used to de-serialize a
response from the API.
"""
self._protocol_buffer = protocol_buffer
def serialize(self, body_value):
return body_value.SerializeToString()
def deserialize(self, content):
return self._protocol_buffer.FromString(content)
@property
def no_content_response(self):
return self._protocol_buffer()
def makepatch(original, modified):
"""Create a patch object.
Some methods support PATCH, an efficient way to send updates to a resource.
This method allows the easy construction of patch bodies by looking at the
differences between a resource before and after it was modified.
Args:
original: object, the original deserialized resource
modified: object, the modified deserialized resource
Returns:
An object that contains only the changes from original to modified, in a
form suitable to pass to a PATCH method.
Example usage:
item = service.activities().get(postid=postid, userid=userid).execute()
original = copy.deepcopy(item)
item['object']['content'] = 'This is updated.'
service.activities.patch(postid=postid, userid=userid,
body=makepatch(original, item)).execute()
"""
patch = {}
for key, original_value in original.iteritems():
modified_value = modified.get(key, None)
if modified_value is None:
# Use None to signal that the element is deleted
patch[key] = None
elif original_value != modified_value:
if type(original_value) == type({}):
# Recursively descend objects
patch[key] = makepatch(original_value, modified_value)
else:
# In the case of simple types or arrays we just replace
patch[key] = modified_value
else:
# Don't add anything to patch if there's no change
pass
for key in modified:
if key not in original:
patch[key] = modified[key]
return patch
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Errors for the library.
All exceptions defined by the library
should be defined in this file.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from oauth2client.anyjson import simplejson
class Error(Exception):
"""Base error for this module."""
pass
class HttpError(Error):
"""HTTP data was invalid or unexpected."""
def __init__(self, resp, content, uri=None):
self.resp = resp
self.content = content
self.uri = uri
def _get_reason(self):
"""Calculate the reason for the error from the response content."""
if self.resp.get('content-type', '').startswith('application/json'):
try:
data = simplejson.loads(self.content)
reason = data['error']['message']
except (ValueError, KeyError):
reason = self.content
else:
reason = self.resp.reason
return reason
def __repr__(self):
if self.uri:
return '<HttpError %s when requesting %s returned "%s">' % (
self.resp.status, self.uri, self._get_reason())
else:
return '<HttpError %s "%s">' % (self.resp.status, self._get_reason())
__str__ = __repr__
class InvalidJsonError(Error):
"""The JSON returned could not be parsed."""
pass
class UnknownLinkType(Error):
"""Link type unknown or unexpected."""
pass
class UnknownApiNameOrVersion(Error):
"""No API with that name and version exists."""
pass
class UnacceptableMimeTypeError(Error):
"""That is an unacceptable mimetype for this operation."""
pass
class MediaUploadSizeError(Error):
"""Media is larger than the method can accept."""
pass
class ResumableUploadError(Error):
"""Error occured during resumable upload."""
pass
class BatchError(HttpError):
"""Error occured during batch operations."""
def __init__(self, reason, resp=None, content=None):
self.resp = resp
self.content = content
self.reason = reason
def __repr__(self):
return '<BatchError %s "%s">' % (self.resp.status, self.reason)
__str__ = __repr__
class UnexpectedMethodError(Error):
"""Exception raised by RequestMockBuilder on unexpected calls."""
def __init__(self, methodId=None):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedMethodError, self).__init__(
'Received unexpected call %s' % methodId)
class UnexpectedBodyError(Error):
"""Exception raised by RequestMockBuilder on unexpected bodies."""
def __init__(self, expected, provided):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedBodyError, self).__init__(
'Expected: [%s] - Provided: [%s]' % (expected, provided))
| Python |
"""
iri2uri
Converts an IRI to a URI.
"""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = []
__version__ = "1.0.0"
__license__ = "MIT"
__history__ = """
"""
import urlparse
# Convert an IRI to a URI following the rules in RFC 3987
#
# The characters we need to enocde and escape are defined in the spec:
#
# iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD
# ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
# / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
# / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
# / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
# / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
# / %xD0000-DFFFD / %xE1000-EFFFD
escape_range = [
(0xA0, 0xD7FF ),
(0xE000, 0xF8FF ),
(0xF900, 0xFDCF ),
(0xFDF0, 0xFFEF),
(0x10000, 0x1FFFD ),
(0x20000, 0x2FFFD ),
(0x30000, 0x3FFFD),
(0x40000, 0x4FFFD ),
(0x50000, 0x5FFFD ),
(0x60000, 0x6FFFD),
(0x70000, 0x7FFFD ),
(0x80000, 0x8FFFD ),
(0x90000, 0x9FFFD),
(0xA0000, 0xAFFFD ),
(0xB0000, 0xBFFFD ),
(0xC0000, 0xCFFFD),
(0xD0000, 0xDFFFD ),
(0xE1000, 0xEFFFD),
(0xF0000, 0xFFFFD ),
(0x100000, 0x10FFFD)
]
def encode(c):
retval = c
i = ord(c)
for low, high in escape_range:
if i < low:
break
if i >= low and i <= high:
retval = "".join(["%%%2X" % ord(o) for o in c.encode('utf-8')])
break
return retval
def iri2uri(uri):
"""Convert an IRI to a URI. Note that IRIs must be
passed in a unicode strings. That is, do not utf-8 encode
the IRI before passing it into the function."""
if isinstance(uri ,unicode):
(scheme, authority, path, query, fragment) = urlparse.urlsplit(uri)
authority = authority.encode('idna')
# For each character in 'ucschar' or 'iprivate'
# 1. encode as utf-8
# 2. then %-encode each octet of that utf-8
uri = urlparse.urlunsplit((scheme, authority, path, query, fragment))
uri = "".join([encode(c) for c in uri])
return uri
if __name__ == "__main__":
import unittest
class Test(unittest.TestCase):
def test_uris(self):
"""Test that URIs are invariant under the transformation."""
invariant = [
u"ftp://ftp.is.co.za/rfc/rfc1808.txt",
u"http://www.ietf.org/rfc/rfc2396.txt",
u"ldap://[2001:db8::7]/c=GB?objectClass?one",
u"mailto:John.Doe@example.com",
u"news:comp.infosystems.www.servers.unix",
u"tel:+1-816-555-1212",
u"telnet://192.0.2.16:80/",
u"urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ]
for uri in invariant:
self.assertEqual(uri, iri2uri(uri))
def test_iri(self):
""" Test that the right type of escaping is done for each part of the URI."""
self.assertEqual("http://xn--o3h.com/%E2%98%84", iri2uri(u"http://\N{COMET}.com/\N{COMET}"))
self.assertEqual("http://bitworking.org/?fred=%E2%98%84", iri2uri(u"http://bitworking.org/?fred=\N{COMET}"))
self.assertEqual("http://bitworking.org/#%E2%98%84", iri2uri(u"http://bitworking.org/#\N{COMET}"))
self.assertEqual("#%E2%98%84", iri2uri(u"#\N{COMET}"))
self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"))
self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")))
self.assertNotEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode('utf-8')))
unittest.main()
| Python |
from __future__ import generators
"""
httplib2
A caching http interface that supports ETags and gzip
to conserve bandwidth.
Requires Python 2.3 or later
Changelog:
2007-08-18, Rick: Modified so it's able to use a socks proxy if needed.
"""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = ["Thomas Broyer (t.broyer@ltgt.net)",
"James Antill",
"Xavier Verges Farrero",
"Jonathan Feinberg",
"Blair Zajac",
"Sam Ruby",
"Louis Nyffenegger"]
__license__ = "MIT"
__version__ = "0.7.2"
import re
import sys
import email
import email.Utils
import email.Message
import email.FeedParser
import StringIO
import gzip
import zlib
import httplib
import urlparse
import base64
import os
import copy
import calendar
import time
import random
import errno
# remove depracated warning in python2.6
try:
from hashlib import sha1 as _sha, md5 as _md5
except ImportError:
import sha
import md5
_sha = sha.new
_md5 = md5.new
import hmac
from gettext import gettext as _
import socket
try:
from httplib2 import socks
except ImportError:
socks = None
# Build the appropriate socket wrapper for ssl
try:
import ssl # python 2.6
ssl_SSLError = ssl.SSLError
def _ssl_wrap_socket(sock, key_file, cert_file,
disable_validation, ca_certs):
if disable_validation:
cert_reqs = ssl.CERT_NONE
else:
cert_reqs = ssl.CERT_REQUIRED
# We should be specifying SSL version 3 or TLS v1, but the ssl module
# doesn't expose the necessary knobs. So we need to go with the default
# of SSLv23.
return ssl.wrap_socket(sock, keyfile=key_file, certfile=cert_file,
cert_reqs=cert_reqs, ca_certs=ca_certs)
except (AttributeError, ImportError):
ssl_SSLError = None
def _ssl_wrap_socket(sock, key_file, cert_file,
disable_validation, ca_certs):
if not disable_validation:
raise CertificateValidationUnsupported(
"SSL certificate validation is not supported without "
"the ssl module installed. To avoid this error, install "
"the ssl module, or explicity disable validation.")
ssl_sock = socket.ssl(sock, key_file, cert_file)
return httplib.FakeSocket(sock, ssl_sock)
if sys.version_info >= (2,3):
from iri2uri import iri2uri
else:
def iri2uri(uri):
return uri
def has_timeout(timeout): # python 2.6
if hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'):
return (timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT)
return (timeout is not None)
__all__ = ['Http', 'Response', 'ProxyInfo', 'HttpLib2Error',
'RedirectMissingLocation', 'RedirectLimit', 'FailedToDecompressContent',
'UnimplementedDigestAuthOptionError', 'UnimplementedHmacDigestAuthOptionError',
'debuglevel', 'ProxiesUnavailableError']
# The httplib debug level, set to a non-zero value to get debug output
debuglevel = 0
# Python 2.3 support
if sys.version_info < (2,4):
def sorted(seq):
seq.sort()
return seq
# Python 2.3 support
def HTTPResponse__getheaders(self):
"""Return list of (header, value) tuples."""
if self.msg is None:
raise httplib.ResponseNotReady()
return self.msg.items()
if not hasattr(httplib.HTTPResponse, 'getheaders'):
httplib.HTTPResponse.getheaders = HTTPResponse__getheaders
# All exceptions raised here derive from HttpLib2Error
class HttpLib2Error(Exception): pass
# Some exceptions can be caught and optionally
# be turned back into responses.
class HttpLib2ErrorWithResponse(HttpLib2Error):
def __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc)
class RedirectMissingLocation(HttpLib2ErrorWithResponse): pass
class RedirectLimit(HttpLib2ErrorWithResponse): pass
class FailedToDecompressContent(HttpLib2ErrorWithResponse): pass
class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
class MalformedHeader(HttpLib2Error): pass
class RelativeURIError(HttpLib2Error): pass
class ServerNotFoundError(HttpLib2Error): pass
class ProxiesUnavailableError(HttpLib2Error): pass
class CertificateValidationUnsupported(HttpLib2Error): pass
class SSLHandshakeError(HttpLib2Error): pass
class NotSupportedOnThisPlatform(HttpLib2Error): pass
class CertificateHostnameMismatch(SSLHandshakeError):
def __init__(self, desc, host, cert):
HttpLib2Error.__init__(self, desc)
self.host = host
self.cert = cert
# Open Items:
# -----------
# Proxy support
# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
# Pluggable cache storage (supports storing the cache in
# flat files by default. We need a plug-in architecture
# that can support Berkeley DB and Squid)
# == Known Issues ==
# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
# Does not handle Cache-Control: max-stale
# Does not use Age: headers when calculating cache freshness.
# The number of redirections to follow before giving up.
# Note that only GET redirects are automatically followed.
# Will also honor 301 requests by saving that info and never
# requesting that URI again.
DEFAULT_MAX_REDIRECTS = 5
# Default CA certificates file bundled with httplib2.
CA_CERTS = os.path.join(
os.path.dirname(os.path.abspath(__file__ )), "cacerts.txt")
# Which headers are hop-by-hop headers by default
HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade']
def _get_end2end_headers(response):
hopbyhop = list(HOP_BY_HOP)
hopbyhop.extend([x.strip() for x in response.get('connection', '').split(',')])
return [header for header in response.keys() if header not in hopbyhop]
URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
def urlnorm(uri):
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
authority = authority.lower()
scheme = scheme.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
scheme = scheme.lower()
defrag_uri = scheme + "://" + authority + request_uri
return scheme, authority, request_uri, defrag_uri
# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
re_url_scheme = re.compile(r'^\w+://')
re_slash = re.compile(r'[?/:|]+')
def safename(filename):
"""Return a filename suitable for the cache.
Strips dangerous and common characters to create a filename we
can use to store the cache in.
"""
try:
if re_url_scheme.match(filename):
if isinstance(filename,str):
filename = filename.decode('utf-8')
filename = filename.encode('idna')
else:
filename = filename.encode('idna')
except UnicodeError:
pass
if isinstance(filename,unicode):
filename=filename.encode('utf-8')
filemd5 = _md5(filename).hexdigest()
filename = re_url_scheme.sub("", filename)
filename = re_slash.sub(",", filename)
# limit length of filename
if len(filename)>200:
filename=filename[:200]
return ",".join((filename, filemd5))
NORMALIZE_SPACE = re.compile(r'(?:\r\n)?[ \t]+')
def _normalize_headers(headers):
return dict([ (key.lower(), NORMALIZE_SPACE.sub(value, ' ').strip()) for (key, value) in headers.iteritems()])
def _parse_cache_control(headers):
retval = {}
if headers.has_key('cache-control'):
parts = headers['cache-control'].split(',')
parts_with_args = [tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=")]
parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find("=")]
retval = dict(parts_with_args + parts_wo_args)
return retval
# Whether to use a strict mode to parse WWW-Authenticate headers
# Might lead to bad results in case of ill-formed header value,
# so disabled by default, falling back to relaxed parsing.
# Set to true to turn on, usefull for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
# In regex below:
# [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
# "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space
# Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both:
# \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
WWW_AUTH_STRICT = re.compile(r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$")
WWW_AUTH_RELAXED = re.compile(r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$")
UNQUOTE_PAIRS = re.compile(r'\\(.)')
def _parse_www_authenticate(headers, headername='www-authenticate'):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headers.has_key(headername):
try:
authenticate = headers[headername].strip()
www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
while authenticate:
# Break off the scheme at the beginning of the line
if headername == 'authentication-info':
(auth_scheme, the_rest) = ('digest', authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(r'\1', value) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval
def _entry_disposition(response_headers, request_headers):
"""Determine freshness from the Date, Expires and Cache-Control headers.
We don't handle the following:
1. Cache-Control: max-stale
2. Age: headers are not used in the calculations.
Not that this algorithm is simpler than you might think
because we are operating as a private (non-shared) cache.
This lets us ignore 's-maxage'. We can also ignore
'proxy-invalidate' since we aren't a proxy.
We will never return a stale document as
fresh as a design decision, and thus the non-implementation
of 'max-stale'. This also lets us safely ignore 'must-revalidate'
since we operate as if every server has sent 'must-revalidate'.
Since we are private we get to ignore both 'public' and
'private' parameters. We also ignore 'no-transform' since
we don't do any transformations.
The 'no-store' parameter is handled at a higher level.
So the only Cache-Control parameters we look at are:
no-cache
only-if-cached
max-age
min-fresh
"""
retval = "STALE"
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if request_headers.has_key('pragma') and request_headers['pragma'].lower().find('no-cache') != -1:
retval = "TRANSPARENT"
if 'cache-control' not in request_headers:
request_headers['cache-control'] = 'no-cache'
elif cc.has_key('no-cache'):
retval = "TRANSPARENT"
elif cc_response.has_key('no-cache'):
retval = "STALE"
elif cc.has_key('only-if-cached'):
retval = "FRESH"
elif response_headers.has_key('date'):
date = calendar.timegm(email.Utils.parsedate_tz(response_headers['date']))
now = time.time()
current_age = max(0, now - date)
if cc_response.has_key('max-age'):
try:
freshness_lifetime = int(cc_response['max-age'])
except ValueError:
freshness_lifetime = 0
elif response_headers.has_key('expires'):
expires = email.Utils.parsedate_tz(response_headers['expires'])
if None == expires:
freshness_lifetime = 0
else:
freshness_lifetime = max(0, calendar.timegm(expires) - date)
else:
freshness_lifetime = 0
if cc.has_key('max-age'):
try:
freshness_lifetime = int(cc['max-age'])
except ValueError:
freshness_lifetime = 0
if cc.has_key('min-fresh'):
try:
min_fresh = int(cc['min-fresh'])
except ValueError:
min_fresh = 0
current_age += min_fresh
if freshness_lifetime > current_age:
retval = "FRESH"
return retval
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get('content-encoding', None)
if encoding in ['gzip', 'deflate']:
if encoding == 'gzip':
content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read()
if encoding == 'deflate':
content = zlib.decompress(content)
response['content-length'] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response['-content-encoding'] = response['content-encoding']
del response['content-encoding']
except IOError:
content = ""
raise FailedToDecompressContent(_("Content purported to be compressed with %s but failed to decompress.") % response.get('content-encoding'), response, content)
return content
def _updateCache(request_headers, response_headers, content, cache, cachekey):
if cachekey:
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if cc.has_key('no-store') or cc_response.has_key('no-store'):
cache.delete(cachekey)
else:
info = email.Message.Message()
for key, value in response_headers.iteritems():
if key not in ['status','content-encoding','transfer-encoding']:
info[key] = value
# Add annotations to the cache to indicate what headers
# are variant for this request.
vary = response_headers.get('vary', None)
if vary:
vary_headers = vary.lower().replace(' ', '').split(',')
for header in vary_headers:
key = '-varied-%s' % header
try:
info[key] = request_headers[header]
except KeyError:
pass
status = response_headers.status
if status == 304:
status = 200
status_header = 'status: %d\r\n' % status
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = "".join([status_header, header_str, content])
cache.set(cachekey, text)
def _cnonce():
dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest()
return dig[:16]
def _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(_sha("%s%s%s" % (cnonce, iso_now, password)).digest()).strip()
# For credentials we need two things, first
# a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
# Then we also need a list of URIs that have already demanded authentication
# That list is tricky since sub-URIs can take the same auth, or the
# auth scheme may change as you descend the tree.
# So we also need each Auth instance to be able to tell us
# how close to the 'top' it is.
class Authentication(object):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host
self.credentials = credentials
self.http = http
def depth(self, request_uri):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return request_uri[len(self.path):].count("/")
def inscope(self, host, request_uri):
# XXX Should we normalize the request_uri?
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return (host == self.host) and path.startswith(self.path)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header. Over-rise this in sub-classes."""
pass
def response(self, response, content):
"""Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true.
"""
return False
class BasicAuthentication(Authentication):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'Basic ' + base64.b64encode("%s:%s" % self.credentials).strip()
class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
self.challenge = challenge['digest']
qop = self.challenge.get('qop', 'auth')
self.challenge['qop'] = ('auth' in [x.strip() for x in qop.split()]) and 'auth' or None
if self.challenge['qop'] is None:
raise UnimplementedDigestAuthOptionError( _("Unsupported value for qop: %s." % qop))
self.challenge['algorithm'] = self.challenge.get('algorithm', 'MD5').upper()
if self.challenge['algorithm'] != 'MD5':
raise UnimplementedDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
self.A1 = "".join([self.credentials[0], ":", self.challenge['realm'], ":", self.credentials[1]])
self.challenge['nc'] = 1
def request(self, method, request_uri, headers, content, cnonce = None):
"""Modify the request headers"""
H = lambda x: _md5(x).hexdigest()
KD = lambda s, d: H("%s:%s" % (s, d))
A2 = "".join([method, ":", request_uri])
self.challenge['cnonce'] = cnonce or _cnonce()
request_digest = '"%s"' % KD(H(self.A1), "%s:%s:%s:%s:%s" % (self.challenge['nonce'],
'%08x' % self.challenge['nc'],
self.challenge['cnonce'],
self.challenge['qop'], H(A2)
))
headers['authorization'] = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", algorithm=%s, response=%s, qop=%s, nc=%08x, cnonce="%s"' % (
self.credentials[0],
self.challenge['realm'],
self.challenge['nonce'],
request_uri,
self.challenge['algorithm'],
request_digest,
self.challenge['qop'],
self.challenge['nc'],
self.challenge['cnonce'],
)
if self.challenge.get('opaque'):
headers['authorization'] += ', opaque="%s"' % self.challenge['opaque']
self.challenge['nc'] += 1
def response(self, response, content):
if not response.has_key('authentication-info'):
challenge = _parse_www_authenticate(response, 'www-authenticate').get('digest', {})
if 'true' == challenge.get('stale'):
self.challenge['nonce'] = challenge['nonce']
self.challenge['nc'] = 1
return True
else:
updated_challenge = _parse_www_authenticate(response, 'authentication-info').get('digest', {})
if updated_challenge.has_key('nextnonce'):
self.challenge['nonce'] = updated_challenge['nextnonce']
self.challenge['nc'] = 1
return False
class HmacDigestAuthentication(Authentication):
"""Adapted from Robert Sayre's code and DigestAuthentication above."""
__author__ = "Thomas Broyer (t.broyer@ltgt.net)"
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
self.challenge = challenge['hmacdigest']
# TODO: self.challenge['domain']
self.challenge['reason'] = self.challenge.get('reason', 'unauthorized')
if self.challenge['reason'] not in ['unauthorized', 'integrity']:
self.challenge['reason'] = 'unauthorized'
self.challenge['salt'] = self.challenge.get('salt', '')
if not self.challenge.get('snonce'):
raise UnimplementedHmacDigestAuthOptionError( _("The challenge doesn't contain a server nonce, or this one is empty."))
self.challenge['algorithm'] = self.challenge.get('algorithm', 'HMAC-SHA-1')
if self.challenge['algorithm'] not in ['HMAC-SHA-1', 'HMAC-MD5']:
raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
self.challenge['pw-algorithm'] = self.challenge.get('pw-algorithm', 'SHA-1')
if self.challenge['pw-algorithm'] not in ['SHA-1', 'MD5']:
raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge['pw-algorithm']))
if self.challenge['algorithm'] == 'HMAC-MD5':
self.hashmod = _md5
else:
self.hashmod = _sha
if self.challenge['pw-algorithm'] == 'MD5':
self.pwhashmod = _md5
else:
self.pwhashmod = _sha
self.key = "".join([self.credentials[0], ":",
self.pwhashmod.new("".join([self.credentials[1], self.challenge['salt']])).hexdigest().lower(),
":", self.challenge['realm']
])
self.key = self.pwhashmod.new(self.key).hexdigest().lower()
def request(self, method, request_uri, headers, content):
"""Modify the request headers"""
keys = _get_end2end_headers(headers)
keylist = "".join(["%s " % k for k in keys])
headers_val = "".join([headers[k] for k in keys])
created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val)
request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % (
self.credentials[0],
self.challenge['realm'],
self.challenge['snonce'],
cnonce,
request_uri,
created,
request_digest,
keylist,
)
def response(self, response, content):
challenge = _parse_www_authenticate(response, 'www-authenticate').get('hmacdigest', {})
if challenge.get('reason') in ['integrity', 'stale']:
return True
return False
class WsseAuthentication(Authentication):
"""This is thinly tested and should not be relied upon.
At this time there isn't any third party server to test against.
Blogger and TypePad implemented this algorithm at one point
but Blogger has since switched to Basic over HTTPS and
TypePad has implemented it wrong, by never issuing a 401
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'WSSE profile="UsernameToken"'
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers['X-WSSE'] = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"' % (
self.credentials[0],
password_digest,
cnonce,
iso_now)
class GoogleLoginAuthentication(Authentication):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
from urllib import urlencode
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
service = challenge['googlelogin'].get('service', 'xapi')
# Bloggger actually returns the service in the challenge
# For the rest we guess based on the URI
if service == 'xapi' and request_uri.find("calendar") > 0:
service = "cl"
# No point in guessing Base or Spreadsheet
#elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers['user-agent'])
resp, content = self.http.request("https://www.google.com/accounts/ClientLogin", method="POST", body=urlencode(auth), headers={'Content-Type': 'application/x-www-form-urlencoded'})
lines = content.split('\n')
d = dict([tuple(line.split("=", 1)) for line in lines if line])
if resp.status == 403:
self.Auth = ""
else:
self.Auth = d['Auth']
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'GoogleLogin Auth=' + self.Auth
AUTH_SCHEME_CLASSES = {
"basic": BasicAuthentication,
"wsse": WsseAuthentication,
"digest": DigestAuthentication,
"hmacdigest": HmacDigestAuthentication,
"googlelogin": GoogleLoginAuthentication
}
AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
class FileCache(object):
"""Uses a local directory as a store for cached files.
Not really safe to use if multiple threads or processes are going to
be running on the same cache.
"""
def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache):
os.makedirs(self.cache)
def get(self, key):
retval = None
cacheFullPath = os.path.join(self.cache, self.safe(key))
try:
f = file(cacheFullPath, "rb")
retval = f.read()
f.close()
except IOError:
pass
return retval
def set(self, key, value):
cacheFullPath = os.path.join(self.cache, self.safe(key))
f = file(cacheFullPath, "wb")
f.write(value)
f.close()
def delete(self, key):
cacheFullPath = os.path.join(self.cache, self.safe(key))
if os.path.exists(cacheFullPath):
os.remove(cacheFullPath)
class Credentials(object):
def __init__(self):
self.credentials = []
def add(self, name, password, domain=""):
self.credentials.append((domain.lower(), name, password))
def clear(self):
self.credentials = []
def iter(self, domain):
for (cdomain, name, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (name, password)
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
pass
class ProxyInfo(object):
"""Collect information required to use a proxy."""
def __init__(self, proxy_type, proxy_host, proxy_port, proxy_rdns=None, proxy_user=None, proxy_pass=None):
"""The parameter proxy_type must be set to one of socks.PROXY_TYPE_XXX
constants. For example:
p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost', proxy_port=8000)
"""
self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass = proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass
def astuple(self):
return (self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns,
self.proxy_user, self.proxy_pass)
def isgood(self):
return (self.proxy_host != None) and (self.proxy_port != None)
class HTTPConnectionWithTimeout(httplib.HTTPConnection):
"""
HTTPConnection subclass that supports timeouts
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None):
httplib.HTTPConnection.__init__(self, host, port, strict)
self.timeout = timeout
self.proxy_info = proxy_info
def connect(self):
"""Connect to the host and port specified in __init__."""
# Mostly verbatim from httplib.py.
if self.proxy_info and socks is None:
raise ProxiesUnavailableError(
'Proxy support missing but proxy use was requested!')
msg = "getaddrinfo returns an empty list"
for res in socket.getaddrinfo(self.host, self.port, 0,
socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
if self.proxy_info and self.proxy_info.isgood():
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(*self.proxy_info.astuple())
else:
self.sock = socket.socket(af, socktype, proto)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# Different from httplib: support timeouts.
if has_timeout(self.timeout):
self.sock.settimeout(self.timeout)
# End of difference from httplib.
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
self.sock.connect(sa)
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
class HTTPSConnectionWithTimeout(httplib.HTTPSConnection):
"""
This class allows communication via SSL.
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None,
ca_certs=None, disable_ssl_certificate_validation=False):
httplib.HTTPSConnection.__init__(self, host, port=port, key_file=key_file,
cert_file=cert_file, strict=strict)
self.timeout = timeout
self.proxy_info = proxy_info
if ca_certs is None:
ca_certs = CA_CERTS
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = \
disable_ssl_certificate_validation
# The following two methods were adapted from https_wrapper.py, released
# with the Google Appengine SDK at
# http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py
# under the following license:
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
def _GetValidHostsForCert(self, cert):
"""Returns a list of valid host globs for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
Returns:
list: A list of valid host globs.
"""
if 'subjectAltName' in cert:
return [x[1] for x in cert['subjectAltName']
if x[0].lower() == 'dns']
else:
return [x[0][1] for x in cert['subject']
if x[0][0].lower() == 'commonname']
def _ValidateCertificateHostname(self, cert, hostname):
"""Validates that a given hostname is valid for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
hostname: The hostname to test.
Returns:
bool: Whether or not the hostname is valid for this certificate.
"""
hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return False
def connect(self):
"Connect to a host on a given (SSL) port."
msg = "getaddrinfo returns an empty list"
for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(
self.host, self.port, 0, socket.SOCK_STREAM):
try:
if self.proxy_info and self.proxy_info.isgood():
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(*self.proxy_info.astuple())
else:
sock = socket.socket(family, socktype, proto)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if has_timeout(self.timeout):
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
self.sock =_ssl_wrap_socket(
sock, self.key_file, self.cert_file,
self.disable_ssl_certificate_validation, self.ca_certs)
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
if not self.disable_ssl_certificate_validation:
cert = self.sock.getpeercert()
hostname = self.host.split(':', 0)[0]
if not self._ValidateCertificateHostname(cert, hostname):
raise CertificateHostnameMismatch(
'Server presented certificate that does not match '
'host %s: %s' % (hostname, cert), hostname, cert)
except ssl_SSLError, e:
if sock:
sock.close()
if self.sock:
self.sock.close()
self.sock = None
# Unfortunately the ssl module doesn't seem to provide any way
# to get at more detailed error information, in particular
# whether the error is due to certificate validation or
# something else (such as SSL protocol mismatch).
if e.errno == ssl.SSL_ERROR_SSL:
raise SSLHandshakeError(e)
else:
raise
except (socket.timeout, socket.gaierror):
raise
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
SCHEME_TO_CONNECTION = {
'http': HTTPConnectionWithTimeout,
'https': HTTPSConnectionWithTimeout
}
# Use a different connection object for Google App Engine
try:
from google.appengine.api import apiproxy_stub_map
if apiproxy_stub_map.apiproxy.GetStub('urlfetch') is None:
raise ImportError # Bail out; we're not actually running on App Engine.
from google.appengine.api.urlfetch import fetch
from google.appengine.api.urlfetch import InvalidURLError
from google.appengine.api.urlfetch import DownloadError
from google.appengine.api.urlfetch import ResponseTooLargeError
from google.appengine.api.urlfetch import SSLCertificateError
class ResponseDict(dict):
"""Is a dictionary that also has a read() method, so
that it can pass itself off as an httlib.HTTPResponse()."""
def read(self):
pass
class AppEngineHttpConnection(object):
"""Emulates an httplib.HTTPConnection object, but actually uses the Google
App Engine urlfetch library. This allows the timeout to be properly used on
Google App Engine, and avoids using httplib, which on Google App Engine is
just another wrapper around urlfetch.
"""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None, ca_certs=None,
disable_certificate_validation=False):
self.host = host
self.port = port
self.timeout = timeout
if key_file or cert_file or proxy_info or ca_certs:
raise NotSupportedOnThisPlatform()
self.response = None
self.scheme = 'http'
self.validate_certificate = not disable_certificate_validation
self.sock = True
def request(self, method, url, body, headers):
# Calculate the absolute URI, which fetch requires
netloc = self.host
if self.port:
netloc = '%s:%s' % (self.host, self.port)
absolute_uri = '%s://%s%s' % (self.scheme, netloc, url)
try:
response = fetch(absolute_uri, payload=body, method=method,
headers=headers, allow_truncated=False, follow_redirects=False,
deadline=self.timeout,
validate_certificate=self.validate_certificate)
self.response = ResponseDict(response.headers)
self.response['status'] = str(response.status_code)
self.response.status = response.status_code
setattr(self.response, 'read', lambda : response.content)
# Make sure the exceptions raised match the exceptions expected.
except InvalidURLError:
raise socket.gaierror('')
except (DownloadError, ResponseTooLargeError, SSLCertificateError):
raise httplib.HTTPException()
def getresponse(self):
if self.response:
return self.response
else:
raise httplib.HTTPException()
def set_debuglevel(self, level):
pass
def connect(self):
pass
def close(self):
pass
class AppEngineHttpsConnection(AppEngineHttpConnection):
"""Same as AppEngineHttpConnection, but for HTTPS URIs."""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None):
AppEngineHttpConnection.__init__(self, host, port, key_file, cert_file,
strict, timeout, proxy_info)
self.scheme = 'https'
# Update the connection classes to use the Googel App Engine specific ones.
SCHEME_TO_CONNECTION = {
'http': AppEngineHttpConnection,
'https': AppEngineHttpsConnection
}
except ImportError:
pass
class Http(object):
"""An HTTP client that handles:
- all methods
- caching
- ETags
- compression,
- HTTPS
- Basic
- Digest
- WSSE
and more.
"""
def __init__(self, cache=None, timeout=None, proxy_info=None,
ca_certs=None, disable_ssl_certificate_validation=False):
"""
The value of proxy_info is a ProxyInfo instance.
If 'cache' is a string then it is used as a directory name for
a disk cache. Otherwise it must be an object that supports the
same interface as FileCache.
All timeouts are in seconds. If None is passed for timeout
then Python's default timeout for sockets will be used. See
for example the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
ca_certs is the path of a file containing root CA certificates for SSL
server certificate validation. By default, a CA cert file bundled with
httplib2 is used.
If disable_ssl_certificate_validation is true, SSL cert validation will
not be performed.
"""
self.proxy_info = proxy_info
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = \
disable_ssl_certificate_validation
# Map domain name to an httplib connection
self.connections = {}
# The location of the cache, for now a directory
# where cached responses are held.
if cache and isinstance(cache, basestring):
self.cache = FileCache(cache)
else:
self.cache = cache
# Name/password
self.credentials = Credentials()
# Key/cert
self.certificates = KeyCerts()
# authorization objects
self.authorizations = []
# If set to False then no redirects are followed, even safe ones.
self.follow_redirects = True
# Which HTTP methods do we apply optimistic concurrency to, i.e.
# which methods get an "if-match:" etag header added to them.
self.optimistic_concurrency_methods = ["PUT", "PATCH"]
# If 'follow_redirects' is True, and this is set to True then
# all redirecs are followed, including unsafe ones.
self.follow_all_redirects = False
self.ignore_etag = False
self.force_exception_to_status_code = False
self.timeout = timeout
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, 'www-authenticate')
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if challenges.has_key(scheme):
yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self)
def add_credentials(self, name, password, domain=""):
"""Add a name and password that will be used
any time a request requires authentication."""
self.credentials.add(name, password, domain)
def add_certificate(self, key, cert, domain):
"""Add a key and cert that will be used
any time a request requires authentication."""
self.certificates.add(key, cert, domain)
def clear_credentials(self):
"""Remove all the names and passwords
that are used for authentication"""
self.credentials.clear()
self.authorizations = []
def _conn_request(self, conn, request_uri, method, body, headers):
for i in range(2):
try:
if conn.sock is None:
conn.connect()
conn.request(method, request_uri, body, headers)
except socket.timeout:
raise
except socket.gaierror:
conn.close()
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
except ssl_SSLError:
conn.close()
raise
except socket.error, e:
err = 0
if hasattr(e, 'args'):
err = getattr(e, 'args')[0]
else:
err = e.errno
if err == errno.ECONNREFUSED: # Connection refused
raise
except httplib.HTTPException:
# Just because the server closed the connection doesn't apparently mean
# that the server didn't send a response.
if conn.sock is None:
if i == 0:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
if i == 0:
conn.close()
conn.connect()
continue
try:
response = conn.getresponse()
except (socket.error, httplib.HTTPException):
if i == 0:
conn.close()
conn.connect()
continue
else:
raise
else:
content = ""
if method == "HEAD":
response.close()
else:
content = response.read()
response = Response(response)
if method != "HEAD":
content = _decompressContent(response, content)
break
return (response, content)
def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey):
"""Do the actual request using the connection object
and also follow one level of redirects if necessary"""
auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)]
auth = auths and sorted(auths)[0][1] or None
if auth:
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
if auth:
if auth.response(response, body):
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers )
response._stale_digest = 1
if response.status == 401:
for authorization in self._auth_from_challenge(host, request_uri, headers, response, content):
authorization.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers, )
if response.status != 401:
self.authorizations.append(authorization)
authorization.response(response, body)
break
if (self.follow_all_redirects or (method in ["GET", "HEAD"]) or response.status == 303):
if self.follow_redirects and response.status in [300, 301, 302, 303, 307]:
# Pick out the location header and basically start from the beginning
# remembering first to strip the ETag header and decrement our 'depth'
if redirections:
if not response.has_key('location') and response.status != 300:
raise RedirectMissingLocation( _("Redirected but the response is missing a Location: header."), response, content)
# Fix-up relative redirects (which violate an RFC 2616 MUST)
if response.has_key('location'):
location = response['location']
(scheme, authority, path, query, fragment) = parse_uri(location)
if authority == None:
response['location'] = urlparse.urljoin(absolute_uri, location)
if response.status == 301 and method in ["GET", "HEAD"]:
response['-x-permanent-redirect-url'] = response['location']
if not response.has_key('content-location'):
response['content-location'] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
if headers.has_key('if-none-match'):
del headers['if-none-match']
if headers.has_key('if-modified-since'):
del headers['if-modified-since']
if response.has_key('location'):
location = response['location']
old_response = copy.deepcopy(response)
if not old_response.has_key('content-location'):
old_response['content-location'] = absolute_uri
redirect_method = method
if response.status in [302, 303]:
redirect_method = "GET"
body = None
(response, content) = self.request(location, redirect_method, body=body, headers = headers, redirections = redirections - 1)
response.previous = old_response
else:
raise RedirectLimit("Redirected more times than rediection_limit allows.", response, content)
elif response.status in [200, 203] and method in ["GET", "HEAD"]:
# Don't cache 206's since we aren't going to handle byte range requests
if not response.has_key('content-location'):
response['content-location'] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
return (response, content)
def _normalize_headers(self, headers):
return _normalize_headers(headers)
# Need to catch and rebrand some exceptions
# Then need to optionally turn all exceptions into status codes
# including all socket.* and httplib.* exceptions.
def request(self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None):
""" Performs a single HTTP request.
The 'uri' is the URI of the HTTP resource and can begin
with either 'http' or 'https'. The value of 'uri' must be an absolute URI.
The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc.
There is no restriction on the methods allowed.
The 'body' is the entity body to be sent with the request. It is a string
object.
Any extra headers that are to be sent with the request should be provided in the
'headers' dictionary.
The maximum number of redirect to follow before raising an
exception is 'redirections. The default is 5.
The return value is a tuple of (response, content), the first
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
try:
if headers is None:
headers = {}
else:
headers = self._normalize_headers(headers)
if not headers.has_key('user-agent'):
headers['user-agent'] = "Python-httplib2/%s (gzip)" % __version__
uri = iri2uri(uri)
(scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
domain_port = authority.split(":")[0:2]
if len(domain_port) == 2 and domain_port[1] == '443' and scheme == 'http':
scheme = 'https'
authority = domain_port[0]
conn_key = scheme+":"+authority
if conn_key in self.connections:
conn = self.connections[conn_key]
else:
if not connection_type:
connection_type = SCHEME_TO_CONNECTION[scheme]
certs = list(self.certificates.iter(authority))
if issubclass(connection_type, HTTPSConnectionWithTimeout):
if certs:
conn = self.connections[conn_key] = connection_type(
authority, key_file=certs[0][0],
cert_file=certs[0][1], timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=
self.disable_ssl_certificate_validation)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=
self.disable_ssl_certificate_validation)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout,
proxy_info=self.proxy_info)
conn.set_debuglevel(debuglevel)
if 'range' not in headers and 'accept-encoding' not in headers:
headers['accept-encoding'] = 'gzip, deflate'
info = email.Message.Message()
cached_value = None
if self.cache:
cachekey = defrag_uri
cached_value = self.cache.get(cachekey)
if cached_value:
# info = email.message_from_string(cached_value)
#
# Need to replace the line above with the kludge below
# to fix the non-existent bug not fixed in this
# bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html
try:
info, content = cached_value.split('\r\n\r\n', 1)
feedparser = email.FeedParser.FeedParser()
feedparser.feed(info)
info = feedparser.close()
feedparser._parse = None
except IndexError:
self.cache.delete(cachekey)
cachekey = None
cached_value = None
else:
cachekey = None
if method in self.optimistic_concurrency_methods and self.cache and info.has_key('etag') and not self.ignore_etag and 'if-match' not in headers:
# http://www.w3.org/1999/04/Editing/
headers['if-match'] = info['etag']
if method not in ["GET", "HEAD"] and self.cache and cachekey:
# RFC 2616 Section 13.10
self.cache.delete(cachekey)
# Check the vary header in the cache to see if this request
# matches what varies in the cache.
if method in ['GET', 'HEAD'] and 'vary' in info:
vary = info['vary']
vary_headers = vary.lower().replace(' ', '').split(',')
for header in vary_headers:
key = '-varied-%s' % header
value = info[key]
if headers.get(header, None) != value:
cached_value = None
break
if cached_value and method in ["GET", "HEAD"] and self.cache and 'range' not in headers:
if info.has_key('-x-permanent-redirect-url'):
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit("Redirected more times than rediection_limit allows.", {}, "")
(response, new_content) = self.request(info['-x-permanent-redirect-url'], "GET", headers = headers, redirections = redirections - 1)
response.previous = Response(info)
response.previous.fromcache = True
else:
# Determine our course of action:
# Is the cached entry fresh or stale?
# Has the client requested a non-cached response?
#
# There seems to be three possible answers:
# 1. [FRESH] Return the cache entry w/o doing a GET
# 2. [STALE] Do the GET (but add in cache validators if available)
# 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
entry_disposition = _entry_disposition(info, headers)
if entry_disposition == "FRESH":
if not cached_value:
info['status'] = '504'
content = ""
response = Response(info)
if cached_value:
response.fromcache = True
return (response, content)
if entry_disposition == "STALE":
if info.has_key('etag') and not self.ignore_etag and not 'if-none-match' in headers:
headers['if-none-match'] = info['etag']
if info.has_key('last-modified') and not 'last-modified' in headers:
headers['if-modified-since'] = info['last-modified']
elif entry_disposition == "TRANSPARENT":
pass
(response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
if response.status == 304 and method == "GET":
# Rewrite the cache entry with the new end-to-end headers
# Take all headers that are in response
# and overwrite their values in info.
# unless they are hop-by-hop, or are listed in the connection header.
for key in _get_end2end_headers(response):
info[key] = response[key]
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(headers, merged_response, content, self.cache, cachekey)
response = merged_response
response.status = 200
response.fromcache = True
elif response.status == 200:
content = new_content
else:
self.cache.delete(cachekey)
content = new_content
else:
cc = _parse_cache_control(headers)
if cc.has_key('only-if-cached'):
info['status'] = '504'
response = Response(info)
content = ""
else:
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
except Exception, e:
if self.force_exception_to_status_code:
if isinstance(e, HttpLib2ErrorWithResponse):
response = e.response
content = e.content
response.status = 500
response.reason = str(e)
elif isinstance(e, socket.timeout):
content = "Request Timeout"
response = Response( {
"content-type": "text/plain",
"status": "408",
"content-length": len(content)
})
response.reason = "Request Timeout"
else:
content = str(e)
response = Response( {
"content-type": "text/plain",
"status": "400",
"content-length": len(content)
})
response.reason = "Bad Request"
else:
raise
return (response, content)
class Response(dict):
"""An object more like email.Message than httplib.HTTPResponse."""
"""Is this response from our local cache"""
fromcache = False
"""HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1. """
version = 11
"Status code returned by server. "
status = 200
"""Reason phrase returned by server."""
reason = "Ok"
previous = None
def __init__(self, info):
# info is either an email.Message or
# an httplib.HTTPResponse object.
if isinstance(info, httplib.HTTPResponse):
for key, value in info.getheaders():
self[key.lower()] = value
self.status = info.status
self['status'] = str(self.status)
self.reason = info.reason
self.version = info.version
elif isinstance(info, email.Message.Message):
for key, value in info.items():
self[key] = value
self.status = int(self['status'])
else:
for key, value in info.iteritems():
self[key] = value
self.status = int(self.get('status', self.status))
def __getattr__(self, name):
if name == 'dict':
return self
else:
raise AttributeError, name
| Python |
"""SocksiPy - Python SOCKS module.
Version 1.00
Copyright 2006 Dan-Haim. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of Dan Haim nor the names of his contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.
This module provides a standard socket-like interface for Python
for tunneling connections through SOCKS proxies.
"""
"""
Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
for use in PyLoris (http://pyloris.sourceforge.net/)
Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
mainly to merge bug fixes found in Sourceforge
"""
import base64
import socket
import struct
import sys
if getattr(socket, 'socket', None) is None:
raise ImportError('socket.socket missing, proxy support unusable')
PROXY_TYPE_SOCKS4 = 1
PROXY_TYPE_SOCKS5 = 2
PROXY_TYPE_HTTP = 3
PROXY_TYPE_HTTP_NO_TUNNEL = 4
_defaultproxy = None
_orgsocket = socket.socket
class ProxyError(Exception): pass
class GeneralProxyError(ProxyError): pass
class Socks5AuthError(ProxyError): pass
class Socks5Error(ProxyError): pass
class Socks4Error(ProxyError): pass
class HTTPError(ProxyError): pass
_generalerrors = ("success",
"invalid data",
"not connected",
"not available",
"bad proxy type",
"bad input")
_socks5errors = ("succeeded",
"general SOCKS server failure",
"connection not allowed by ruleset",
"Network unreachable",
"Host unreachable",
"Connection refused",
"TTL expired",
"Command not supported",
"Address type not supported",
"Unknown error")
_socks5autherrors = ("succeeded",
"authentication is required",
"all offered authentication methods were rejected",
"unknown username or invalid password",
"unknown error")
_socks4errors = ("request granted",
"request rejected or failed",
"request rejected because SOCKS server cannot connect to identd on the client",
"request rejected because the client program and identd report different user-ids",
"unknown error")
def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
"""setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets a default proxy which all further socksocket objects will use,
unless explicitly changed.
"""
global _defaultproxy
_defaultproxy = (proxytype, addr, port, rdns, username, password)
def wrapmodule(module):
"""wrapmodule(module)
Attempts to replace a module's socket library with a SOCKS socket. Must set
a default proxy using setdefaultproxy(...) first.
This will only work on modules that import socket directly into the namespace;
most of the Python Standard Library falls into this category.
"""
if _defaultproxy != None:
module.socket.socket = socksocket
else:
raise GeneralProxyError((4, "no proxy specified"))
class socksocket(socket.socket):
"""socksocket([family[, type[, proto]]]) -> socket object
Open a SOCKS enabled socket. The parameters are the same as
those of the standard socket init. In order for SOCKS to work,
you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
"""
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
_orgsocket.__init__(self, family, type, proto, _sock)
if _defaultproxy != None:
self.__proxy = _defaultproxy
else:
self.__proxy = (None, None, None, None, None, None)
self.__proxysockname = None
self.__proxypeername = None
self.__httptunnel = True
def __recvall(self, count):
"""__recvall(count) -> data
Receive EXACTLY the number of bytes requested from the socket.
Blocks until the required number of bytes have been received.
"""
data = self.recv(count)
while len(data) < count:
d = self.recv(count-len(data))
if not d: raise GeneralProxyError((0, "connection closed unexpectedly"))
data = data + d
return data
def sendall(self, content, *args):
""" override socket.socket.sendall method to rewrite the header
for non-tunneling proxies if needed
"""
if not self.__httptunnel:
content = self.__rewriteproxy(content)
return super(socksocket, self).sendall(content, *args)
def __rewriteproxy(self, header):
""" rewrite HTTP request headers to support non-tunneling proxies
(i.e. those which do not support the CONNECT method).
This only works for HTTP (not HTTPS) since HTTPS requires tunneling.
"""
host, endpt = None, None
hdrs = header.split("\r\n")
for hdr in hdrs:
if hdr.lower().startswith("host:"):
host = hdr
elif hdr.lower().startswith("get") or hdr.lower().startswith("post"):
endpt = hdr
if host and endpt:
hdrs.remove(host)
hdrs.remove(endpt)
host = host.split(" ")[1]
endpt = endpt.split(" ")
if (self.__proxy[4] != None and self.__proxy[5] != None):
hdrs.insert(0, self.__getauthheader())
hdrs.insert(0, "Host: %s" % host)
hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2]))
return "\r\n".join(hdrs)
def __getauthheader(self):
auth = self.__proxy[4] + ":" + self.__proxy[5]
return "Proxy-Authorization: Basic " + base64.b64encode(auth)
def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
"""setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxytype - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (IP or DNS).
port - The port of the server. Defaults to 1080 for SOCKS
servers and 8080 for HTTP proxy servers.
rdns - Should DNS queries be preformed on the remote side
(rather than the local side). The default is True.
Note: This has no effect with SOCKS4 servers.
username - Username to authenticate with to the server.
The default is no authentication.
password - Password to authenticate with to the server.
Only relevant when username is also provided.
"""
self.__proxy = (proxytype, addr, port, rdns, username, password)
def __negotiatesocks5(self, destaddr, destport):
"""__negotiatesocks5(self,destaddr,destport)
Negotiates a connection through a SOCKS5 server.
"""
# First we'll send the authentication packages we support.
if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
# The username/password details were supplied to the
# setproxy method so we support the USERNAME/PASSWORD
# authentication (in addition to the standard none).
self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02))
else:
# No username/password were entered, therefore we
# only support connections with no authentication.
self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00))
# We'll receive the server's response to determine which
# method was selected
chosenauth = self.__recvall(2)
if chosenauth[0:1] != chr(0x05).encode():
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
# Check the chosen authentication method
if chosenauth[1:2] == chr(0x00).encode():
# No authentication is required
pass
elif chosenauth[1:2] == chr(0x02).encode():
# Okay, we need to perform a basic username/password
# authentication.
self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5])
authstat = self.__recvall(2)
if authstat[0:1] != chr(0x01).encode():
# Bad response
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if authstat[1:2] != chr(0x00).encode():
# Authentication failed
self.close()
raise Socks5AuthError((3, _socks5autherrors[3]))
# Authentication succeeded
else:
# Reaching here is always bad
self.close()
if chosenauth[1] == chr(0xFF).encode():
raise Socks5AuthError((2, _socks5autherrors[2]))
else:
raise GeneralProxyError((1, _generalerrors[1]))
# Now we can request the actual connection
req = struct.pack('BBB', 0x05, 0x01, 0x00)
# If the given destination address is an IP address, we'll
# use the IPv4 address request even if remote resolving was specified.
try:
ipaddr = socket.inet_aton(destaddr)
req = req + chr(0x01).encode() + ipaddr
except socket.error:
# Well it's not an IP number, so it's probably a DNS name.
if self.__proxy[3]:
# Resolve remotely
ipaddr = None
req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr
else:
# Resolve locally
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
req = req + chr(0x01).encode() + ipaddr
req = req + struct.pack(">H", destport)
self.sendall(req)
# Get the response
resp = self.__recvall(4)
if resp[0:1] != chr(0x05).encode():
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
elif resp[1:2] != chr(0x00).encode():
# Connection failed
self.close()
if ord(resp[1:2])<=8:
raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])]))
else:
raise Socks5Error((9, _socks5errors[9]))
# Get the bound address/port
elif resp[3:4] == chr(0x01).encode():
boundaddr = self.__recvall(4)
elif resp[3:4] == chr(0x03).encode():
resp = resp + self.recv(1)
boundaddr = self.__recvall(ord(resp[4:5]))
else:
self.close()
raise GeneralProxyError((1,_generalerrors[1]))
boundport = struct.unpack(">H", self.__recvall(2))[0]
self.__proxysockname = (boundaddr, boundport)
if ipaddr != None:
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
else:
self.__proxypeername = (destaddr, destport)
def getproxysockname(self):
"""getsockname() -> address info
Returns the bound IP address and port number at the proxy.
"""
return self.__proxysockname
def getproxypeername(self):
"""getproxypeername() -> address info
Returns the IP and port number of the proxy.
"""
return _orgsocket.getpeername(self)
def getpeername(self):
"""getpeername() -> address info
Returns the IP address and port number of the destination
machine (note: getproxypeername returns the proxy)
"""
return self.__proxypeername
def __negotiatesocks4(self,destaddr,destport):
"""__negotiatesocks4(self,destaddr,destport)
Negotiates a connection through a SOCKS4 server.
"""
# Check if the destination address provided is an IP address
rmtrslv = False
try:
ipaddr = socket.inet_aton(destaddr)
except socket.error:
# It's a DNS name. Check where it should be resolved.
if self.__proxy[3]:
ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01)
rmtrslv = True
else:
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
# Construct the request packet
req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
# The username parameter is considered userid for SOCKS4
if self.__proxy[4] != None:
req = req + self.__proxy[4]
req = req + chr(0x00).encode()
# DNS name if remote resolving is required
# NOTE: This is actually an extension to the SOCKS4 protocol
# called SOCKS4A and may not be supported in all cases.
if rmtrslv:
req = req + destaddr + chr(0x00).encode()
self.sendall(req)
# Get the response from the server
resp = self.__recvall(8)
if resp[0:1] != chr(0x00).encode():
# Bad data
self.close()
raise GeneralProxyError((1,_generalerrors[1]))
if resp[1:2] != chr(0x5A).encode():
# Server returned an error
self.close()
if ord(resp[1:2]) in (91, 92, 93):
self.close()
raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90]))
else:
raise Socks4Error((94, _socks4errors[4]))
# Get the bound address/port
self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0])
if rmtrslv != None:
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
else:
self.__proxypeername = (destaddr, destport)
def __negotiatehttp(self, destaddr, destport):
"""__negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server.
"""
# If we need to resolve locally, we do this now
if not self.__proxy[3]:
addr = socket.gethostbyname(destaddr)
else:
addr = destaddr
headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"]
headers += ["Host: ", destaddr, "\r\n"]
if (self.__proxy[4] != None and self.__proxy[5] != None):
headers += [self.__getauthheader(), "\r\n"]
headers.append("\r\n")
self.sendall("".join(headers).encode())
# We read the response until we get the string "\r\n\r\n"
resp = self.recv(1)
while resp.find("\r\n\r\n".encode()) == -1:
resp = resp + self.recv(1)
# We just need the first line to check if the connection
# was successful
statusline = resp.splitlines()[0].split(" ".encode(), 2)
if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
try:
statuscode = int(statusline[1])
except ValueError:
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if statuscode != 200:
self.close()
raise HTTPError((statuscode, statusline[2]))
self.__proxysockname = ("0.0.0.0", 0)
self.__proxypeername = (addr, destport)
def connect(self, destpair):
"""connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket's connect).
To select the proxy server use setproxy().
"""
# Do a minimal input check first
if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int):
raise GeneralProxyError((5, _generalerrors[5]))
if self.__proxy[0] == PROXY_TYPE_SOCKS5:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self, (self.__proxy[1], portnum))
self.__negotiatesocks5(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self,(self.__proxy[1], portnum))
self.__negotiatesocks4(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self,(self.__proxy[1], portnum))
self.__negotiatehttp(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self,(self.__proxy[1],portnum))
if destpair[1] == 443:
self.__negotiatehttp(destpair[0],destpair[1])
else:
self.__httptunnel = False
elif self.__proxy[0] == None:
_orgsocket.connect(self, (destpair[0], destpair[1]))
else:
raise GeneralProxyError((4, _generalerrors[4]))
| Python |
import Cookie
import datetime
import time
import email.utils
import calendar
import base64
import hashlib
import hmac
import re
import logging
# Ripped from the Tornado Framework's web.py
# http://github.com/facebook/tornado/commit/39ac6d169a36a54bb1f6b9bf1fdebb5c9da96e09
#
# Tornado is licensed under the Apache Licence, Version 2.0
# (http://www.apache.org/licenses/LICENSE-2.0.html).
#
# Example:
# from vendor.prayls.lilcookies import LilCookies
# cookieutil = LilCookies(self, application_settings['cookie_secret'])
# cookieutil.set_secure_cookie(name = 'mykey', value = 'myvalue', expires_days= 365*100)
# cookieutil.get_secure_cookie(name = 'mykey')
class LilCookies:
@staticmethod
def _utf8(s):
if isinstance(s, unicode):
return s.encode("utf-8")
assert isinstance(s, str)
return s
@staticmethod
def _time_independent_equals(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
@staticmethod
def _signature_from_secret(cookie_secret, *parts):
""" Takes a secret salt value to create a signature for values in the `parts` param."""
hash = hmac.new(cookie_secret, digestmod=hashlib.sha1)
for part in parts: hash.update(part)
return hash.hexdigest()
@staticmethod
def _signed_cookie_value(cookie_secret, name, value):
""" Returns a signed value for use in a cookie.
This is helpful to have in its own method if you need to re-use this function for other needs. """
timestamp = str(int(time.time()))
value = base64.b64encode(value)
signature = LilCookies._signature_from_secret(cookie_secret, name, value, timestamp)
return "|".join([value, timestamp, signature])
@staticmethod
def _verified_cookie_value(cookie_secret, name, signed_value):
"""Returns the un-encrypted value given the signed value if it validates, or None."""
value = signed_value
if not value: return None
parts = value.split("|")
if len(parts) != 3: return None
signature = LilCookies._signature_from_secret(cookie_secret, name, parts[0], parts[1])
if not LilCookies._time_independent_equals(parts[2], signature):
logging.warning("Invalid cookie signature %r", value)
return None
timestamp = int(parts[1])
if timestamp < time.time() - 31 * 86400:
logging.warning("Expired cookie %r", value)
return None
try:
return base64.b64decode(parts[0])
except:
return None
def __init__(self, handler, cookie_secret):
"""You must specify the cookie_secret to use any of the secure methods.
It should be a long, random sequence of bytes to be used as the HMAC
secret for the signature.
"""
if len(cookie_secret) < 45:
raise ValueError("LilCookies cookie_secret should at least be 45 characters long, but got `%s`" % cookie_secret)
self.handler = handler
self.request = handler.request
self.response = handler.response
self.cookie_secret = cookie_secret
def cookies(self):
"""A dictionary of Cookie.Morsel objects."""
if not hasattr(self, "_cookies"):
self._cookies = Cookie.BaseCookie()
if "Cookie" in self.request.headers:
try:
self._cookies.load(self.request.headers["Cookie"])
except:
self.clear_all_cookies()
return self._cookies
def get_cookie(self, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
if name in self.cookies():
return self._cookies[name].value
return default
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
"""
name = LilCookies._utf8(name)
value = LilCookies._utf8(value)
if re.search(r"[\x00-\x20]", name + value):
# Don't let us accidentally inject bad stuff
raise ValueError("Invalid cookie %r: %r" % (name, value))
if not hasattr(self, "_new_cookies"):
self._new_cookies = []
new_cookie = Cookie.BaseCookie()
self._new_cookies.append(new_cookie)
new_cookie[name] = value
if domain:
new_cookie[name]["domain"] = domain
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days)
if expires:
timestamp = calendar.timegm(expires.utctimetuple())
new_cookie[name]["expires"] = email.utils.formatdate(
timestamp, localtime=False, usegmt=True)
if path:
new_cookie[name]["path"] = path
for k, v in kwargs.iteritems():
new_cookie[name][k] = v
# The 2 lines below were not in Tornado. Instead, they output all their cookies to the headers at once before a response flush.
for vals in new_cookie.values():
self.response.headers._headers.append(('Set-Cookie', vals.OutputString(None)))
def clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name."""
expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
self.set_cookie(name, value="", path=path, expires=expires,
domain=domain)
def clear_all_cookies(self):
"""Deletes all the cookies the user sent with this request."""
for name in self.cookies().iterkeys():
self.clear_cookie(name)
def set_secure_cookie(self, name, value, expires_days=30, **kwargs):
"""Signs and timestamps a cookie so it cannot be forged.
To read a cookie set with this method, use get_secure_cookie().
"""
value = LilCookies._signed_cookie_value(self.cookie_secret, name, value)
self.set_cookie(name, value, expires_days=expires_days, **kwargs)
def get_secure_cookie(self, name, value=None):
"""Returns the given signed cookie if it validates, or None."""
if value is None: value = self.get_cookie(name)
return LilCookies._verified_cookie_value(self.cookie_secret, name, value)
def _cookie_signature(self, *parts):
return LilCookies._signature_from_secret(self.cookie_secret)
| Python |
# This is the version of this source code.
manual_verstr = "1.5"
auto_build_num = "211"
verstr = manual_verstr + "." + auto_build_num
try:
from pyutil.version_class import Version as pyutil_Version
__version__ = pyutil_Version(verstr)
except (ImportError, ValueError):
# Maybe there is no pyutil installed.
from distutils.version import LooseVersion as distutils_Version
__version__ = distutils_Version(verstr)
| Python |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import oauth2
import smtplib
import base64
class SMTP(smtplib.SMTP):
"""SMTP wrapper for smtplib.SMTP that implements XOAUTH."""
def authenticate(self, url, consumer, token):
if consumer is not None and not isinstance(consumer, oauth2.Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, oauth2.Token):
raise ValueError("Invalid token.")
self.docmd('AUTH', 'XOAUTH %s' % \
base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
| Python |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import oauth2
import imaplib
class IMAP4_SSL(imaplib.IMAP4_SSL):
"""IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH."""
def authenticate(self, url, consumer, token):
if consumer is not None and not isinstance(consumer, oauth2.Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, oauth2.Token):
raise ValueError("Invalid token.")
imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH',
lambda x: oauth2.build_xoauth_string(url, consumer, token))
| Python |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import base64
import urllib
import time
import random
import urlparse
import hmac
import binascii
import httplib2
try:
from urlparse import parse_qs
parse_qs # placate pyflakes
except ImportError:
# fall back for Python 2.5
from cgi import parse_qs
try:
from hashlib import sha1
sha = sha1
except ImportError:
# hashlib was added in Python 2.5
import sha
import _version
__version__ = _version.__version__
OAUTH_VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
class Error(RuntimeError):
"""Generic exception class."""
def __init__(self, message='OAuth error occurred.'):
self._message = message
@property
def message(self):
"""A hack to get around the deprecation errors in 2.6."""
return self._message
def __str__(self):
return self._message
class MissingSignature(Error):
pass
def build_authenticate_header(realm=''):
"""Optional WWW-Authenticate header (401 error)"""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def build_xoauth_string(url, consumer, token=None):
"""Build an XOAUTH string for use in SMTP/IMPA authentication."""
request = Request.from_consumer_and_token(consumer, token,
"GET", url)
signing_method = SignatureMethod_HMAC_SHA1()
request.sign_request(signing_method, consumer, token)
params = []
for k, v in sorted(request.iteritems()):
if v is not None:
params.append('%s="%s"' % (k, escape(v)))
return "%s %s %s" % ("GET", url, ','.join(params))
def to_unicode(s):
""" Convert to unicode, raise exception with instructive error
message if s is not unicode, ascii, or utf-8. """
if not isinstance(s, unicode):
if not isinstance(s, str):
raise TypeError('You are required to pass either unicode or string here, not: %r (%s)' % (type(s), s))
try:
s = s.decode('utf-8')
except UnicodeDecodeError, le:
raise TypeError('You are required to pass either a unicode object or a utf-8 string here. You passed a Python string object which contained non-utf-8: %r. The UnicodeDecodeError that resulted from attempting to interpret it as utf-8 was: %s' % (s, le,))
return s
def to_utf8(s):
return to_unicode(s).encode('utf-8')
def to_unicode_if_string(s):
if isinstance(s, basestring):
return to_unicode(s)
else:
return s
def to_utf8_if_string(s):
if isinstance(s, basestring):
return to_utf8(s)
else:
return s
def to_unicode_optional_iterator(x):
"""
Raise TypeError if x is a str containing non-utf8 bytes or if x is
an iterable which contains such a str.
"""
if isinstance(x, basestring):
return to_unicode(x)
try:
l = list(x)
except TypeError, e:
assert 'is not iterable' in str(e)
return x
else:
return [ to_unicode(e) for e in l ]
def to_utf8_optional_iterator(x):
"""
Raise TypeError if x is a str or if x is an iterable which
contains a str.
"""
if isinstance(x, basestring):
return to_utf8(x)
try:
l = list(x)
except TypeError, e:
assert 'is not iterable' in str(e)
return x
else:
return [ to_utf8_if_string(e) for e in l ]
def escape(s):
"""Escape a URL including any /."""
return urllib.quote(s.encode('utf-8'), safe='~')
def generate_timestamp():
"""Get seconds since epoch (UTC)."""
return int(time.time())
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
class Consumer(object):
"""A consumer of OAuth-protected services.
The OAuth consumer is a "third-party" service that wants to access
protected resources from an OAuth service provider on behalf of an end
user. It's kind of the OAuth client.
Usually a consumer must be registered with the service provider by the
developer of the consumer software. As part of that process, the service
provider gives the consumer a *key* and a *secret* with which the consumer
software can identify itself to the service. The consumer will include its
key in each request to identify itself, but will use its secret only when
signing requests, to prove that the request is from that particular
registered consumer.
Once registered, the consumer can then use its consumer credentials to ask
the service provider for a request token, kicking off the OAuth
authorization process.
"""
key = None
secret = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def __str__(self):
data = {'oauth_consumer_key': self.key,
'oauth_consumer_secret': self.secret}
return urllib.urlencode(data)
class Token(object):
"""An OAuth credential used to request authorization or a protected
resource.
Tokens in OAuth comprise a *key* and a *secret*. The key is included in
requests to identify the token being used, but the secret is used only in
the signature, to prove that the requester is who the server gave the
token to.
When first negotiating the authorization, the consumer asks for a *request
token* that the live user authorizes with the service provider. The
consumer then exchanges the request token for an *access token* that can
be used to access protected resources.
"""
key = None
secret = None
callback = None
callback_confirmed = None
verifier = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def set_callback(self, callback):
self.callback = callback
self.callback_confirmed = 'true'
def set_verifier(self, verifier=None):
if verifier is not None:
self.verifier = verifier
else:
self.verifier = generate_verifier()
def get_callback_url(self):
if self.callback and self.verifier:
# Append the oauth_verifier.
parts = urlparse.urlparse(self.callback)
scheme, netloc, path, params, query, fragment = parts[:6]
if query:
query = '%s&oauth_verifier=%s' % (query, self.verifier)
else:
query = 'oauth_verifier=%s' % self.verifier
return urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
return self.callback
def to_string(self):
"""Returns this token as a plain string, suitable for storage.
The resulting string includes the token's secret, so you should never
send or store this string where a third party can read it.
"""
data = {
'oauth_token': self.key,
'oauth_token_secret': self.secret,
}
if self.callback_confirmed is not None:
data['oauth_callback_confirmed'] = self.callback_confirmed
return urllib.urlencode(data)
@staticmethod
def from_string(s):
"""Deserializes a token from a string like one returned by
`to_string()`."""
if not len(s):
raise ValueError("Invalid parameter string.")
params = parse_qs(s, keep_blank_values=False)
if not len(params):
raise ValueError("Invalid parameter string.")
try:
key = params['oauth_token'][0]
except Exception:
raise ValueError("'oauth_token' not found in OAuth request.")
try:
secret = params['oauth_token_secret'][0]
except Exception:
raise ValueError("'oauth_token_secret' not found in "
"OAuth request.")
token = Token(key, secret)
try:
token.callback_confirmed = params['oauth_callback_confirmed'][0]
except KeyError:
pass # 1.0, no callback confirmed.
return token
def __str__(self):
return self.to_string()
def setter(attr):
name = attr.__name__
def getter(self):
try:
return self.__dict__[name]
except KeyError:
raise AttributeError(name)
def deleter(self):
del self.__dict__[name]
return property(getter, attr, deleter)
class Request(dict):
"""The parameters and information for an HTTP request, suitable for
authorizing with OAuth credentials.
When a consumer wants to access a service's protected resources, it does
so using a signed HTTP request identifying itself (the consumer) with its
key, and providing an access token authorized by the end user to access
those resources.
"""
version = OAUTH_VERSION
def __init__(self, method=HTTP_METHOD, url=None, parameters=None,
body='', is_form_encoded=False):
if url is not None:
self.url = to_unicode(url)
self.method = method
if parameters is not None:
for k, v in parameters.iteritems():
k = to_unicode(k)
v = to_unicode_optional_iterator(v)
self[k] = v
self.body = body
self.is_form_encoded = is_form_encoded
@setter
def url(self, value):
self.__dict__['url'] = value
if value is not None:
scheme, netloc, path, params, query, fragment = urlparse.urlparse(value)
# Exclude default port numbers.
if scheme == 'http' and netloc[-3:] == ':80':
netloc = netloc[:-3]
elif scheme == 'https' and netloc[-4:] == ':443':
netloc = netloc[:-4]
if scheme not in ('http', 'https'):
raise ValueError("Unsupported URL %s (%s)." % (value, scheme))
# Normalized URL excludes params, query, and fragment.
self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None))
else:
self.normalized_url = None
self.__dict__['url'] = None
@setter
def method(self, value):
self.__dict__['method'] = value.upper()
def _get_timestamp_nonce(self):
return self['oauth_timestamp'], self['oauth_nonce']
def get_nonoauth_parameters(self):
"""Get any non-OAuth parameters."""
return dict([(k, v) for k, v in self.iteritems()
if not k.startswith('oauth_')])
def to_header(self, realm=''):
"""Serialize as a header for an HTTPAuth request."""
oauth_params = ((k, v) for k, v in self.items()
if k.startswith('oauth_'))
stringy_params = ((k, escape(str(v))) for k, v in oauth_params)
header_params = ('%s="%s"' % (k, v) for k, v in stringy_params)
params_header = ', '.join(header_params)
auth_header = 'OAuth realm="%s"' % realm
if params_header:
auth_header = "%s, %s" % (auth_header, params_header)
return {'Authorization': auth_header}
def to_postdata(self):
"""Serialize as post data for a POST request."""
d = {}
for k, v in self.iteritems():
d[k.encode('utf-8')] = to_utf8_optional_iterator(v)
# tell urlencode to deal with sequence values and map them correctly
# to resulting querystring. for example self["k"] = ["v1", "v2"] will
# result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D
return urllib.urlencode(d, True).replace('+', '%20')
def to_url(self):
"""Serialize as a URL for a GET request."""
base_url = urlparse.urlparse(self.url)
try:
query = base_url.query
except AttributeError:
# must be python <2.5
query = base_url[4]
query = parse_qs(query)
for k, v in self.items():
query.setdefault(k, []).append(v)
try:
scheme = base_url.scheme
netloc = base_url.netloc
path = base_url.path
params = base_url.params
fragment = base_url.fragment
except AttributeError:
# must be python <2.5
scheme = base_url[0]
netloc = base_url[1]
path = base_url[2]
params = base_url[3]
fragment = base_url[5]
url = (scheme, netloc, path, params,
urllib.urlencode(query, True), fragment)
return urlparse.urlunparse(url)
def get_parameter(self, parameter):
ret = self.get(parameter)
if ret is None:
raise Error('Parameter not found: %s' % parameter)
return ret
def get_normalized_parameters(self):
"""Return a string that contains the parameters that must be signed."""
items = []
for key, value in self.iteritems():
if key == 'oauth_signature':
continue
# 1.0a/9.1.1 states that kvp must be sorted by key, then by value,
# so we unpack sequence values into multiple items for sorting.
if isinstance(value, basestring):
items.append((to_utf8_if_string(key), to_utf8(value)))
else:
try:
value = list(value)
except TypeError, e:
assert 'is not iterable' in str(e)
items.append((to_utf8_if_string(key), to_utf8_if_string(value)))
else:
items.extend((to_utf8_if_string(key), to_utf8_if_string(item)) for item in value)
# Include any query string parameters from the provided URL
query = urlparse.urlparse(self.url)[4]
url_items = self._split_url_string(query).items()
url_items = [(to_utf8(k), to_utf8(v)) for k, v in url_items if k != 'oauth_signature' ]
items.extend(url_items)
items.sort()
encoded_str = urllib.urlencode(items)
# Encode signature parameters per Oauth Core 1.0 protocol
# spec draft 7, section 3.6
# (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6)
# Spaces must be encoded with "%20" instead of "+"
return encoded_str.replace('+', '%20').replace('%7E', '~')
def sign_request(self, signature_method, consumer, token):
"""Set the signature parameter to the result of sign."""
if not self.is_form_encoded:
# according to
# http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html
# section 4.1.1 "OAuth Consumers MUST NOT include an
# oauth_body_hash parameter on requests with form-encoded
# request bodies."
self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest())
if 'oauth_consumer_key' not in self:
self['oauth_consumer_key'] = consumer.key
if token and 'oauth_token' not in self:
self['oauth_token'] = token.key
self['oauth_signature_method'] = signature_method.name
self['oauth_signature'] = signature_method.sign(self, consumer, token)
@classmethod
def make_timestamp(cls):
"""Get seconds since epoch (UTC)."""
return str(int(time.time()))
@classmethod
def make_nonce(cls):
"""Generate pseudorandom number."""
return str(random.randint(0, 100000000))
@classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None,
query_string=None):
"""Combines multiple parameter sources."""
if parameters is None:
parameters = {}
# Headers
if headers and 'Authorization' in headers:
auth_header = headers['Authorization']
# Check that the authorization header is OAuth.
if auth_header[:6] == 'OAuth ':
auth_header = auth_header[6:]
try:
# Get the parameters from the header.
header_params = cls._split_header(auth_header)
parameters.update(header_params)
except:
raise Error('Unable to parse OAuth parameters from '
'Authorization header.')
# GET or POST query string.
if query_string:
query_params = cls._split_url_string(query_string)
parameters.update(query_params)
# URL parameters.
param_str = urlparse.urlparse(http_url)[4] # query
url_params = cls._split_url_string(param_str)
parameters.update(url_params)
if parameters:
return cls(http_method, http_url, parameters)
return None
@classmethod
def from_consumer_and_token(cls, consumer, token=None,
http_method=HTTP_METHOD, http_url=None, parameters=None,
body='', is_form_encoded=False):
if not parameters:
parameters = {}
defaults = {
'oauth_consumer_key': consumer.key,
'oauth_timestamp': cls.make_timestamp(),
'oauth_nonce': cls.make_nonce(),
'oauth_version': cls.version,
}
defaults.update(parameters)
parameters = defaults
if token:
parameters['oauth_token'] = token.key
if token.verifier:
parameters['oauth_verifier'] = token.verifier
return Request(http_method, http_url, parameters, body=body,
is_form_encoded=is_form_encoded)
@classmethod
def from_token_and_callback(cls, token, callback=None,
http_method=HTTP_METHOD, http_url=None, parameters=None):
if not parameters:
parameters = {}
parameters['oauth_token'] = token.key
if callback:
parameters['oauth_callback'] = callback
return cls(http_method, http_url, parameters)
@staticmethod
def _split_header(header):
"""Turn Authorization: header into parameters."""
params = {}
parts = header.split(',')
for param in parts:
# Ignore realm parameter.
if param.find('realm') > -1:
continue
# Remove whitespace.
param = param.strip()
# Split key-value.
param_parts = param.split('=', 1)
# Remove quotes and unescape the value.
params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
return params
@staticmethod
def _split_url_string(param_str):
"""Turn URL string into parameters."""
parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True)
for k, v in parameters.iteritems():
parameters[k] = urllib.unquote(v[0])
return parameters
class Client(httplib2.Http):
"""OAuthClient is a worker to attempt to execute a request."""
def __init__(self, consumer, token=None, cache=None, timeout=None,
proxy_info=None):
if consumer is not None and not isinstance(consumer, Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, Token):
raise ValueError("Invalid token.")
self.consumer = consumer
self.token = token
self.method = SignatureMethod_HMAC_SHA1()
httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info)
def set_signature_method(self, method):
if not isinstance(method, SignatureMethod):
raise ValueError("Invalid signature method.")
self.method = method
def request(self, uri, method="GET", body='', headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded'
if not isinstance(headers, dict):
headers = {}
if method == "POST":
headers['Content-Type'] = headers.get('Content-Type',
DEFAULT_POST_CONTENT_TYPE)
is_form_encoded = \
headers.get('Content-Type') == 'application/x-www-form-urlencoded'
if is_form_encoded and body:
parameters = parse_qs(body)
else:
parameters = None
req = Request.from_consumer_and_token(self.consumer,
token=self.token, http_method=method, http_url=uri,
parameters=parameters, body=body, is_form_encoded=is_form_encoded)
req.sign_request(self.method, self.consumer, self.token)
schema, rest = urllib.splittype(uri)
if rest.startswith('//'):
hierpart = '//'
else:
hierpart = ''
host, rest = urllib.splithost(rest)
realm = schema + ':' + hierpart + host
if is_form_encoded:
body = req.to_postdata()
elif method == "GET":
uri = req.to_url()
else:
headers.update(req.to_header(realm=realm))
return httplib2.Http.request(self, uri, method=method, body=body,
headers=headers, redirections=redirections,
connection_type=connection_type)
class Server(object):
"""A skeletal implementation of a service provider, providing protected
resources to requests from authorized consumers.
This class implements the logic to check requests for authorization. You
can use it with your web server or web framework to protect certain
resources with OAuth.
"""
timestamp_threshold = 300 # In seconds, five minutes.
version = OAUTH_VERSION
signature_methods = None
def __init__(self, signature_methods=None):
self.signature_methods = signature_methods or {}
def add_signature_method(self, signature_method):
self.signature_methods[signature_method.name] = signature_method
return self.signature_methods
def verify_request(self, request, consumer, token):
"""Verifies an api call and checks all the parameters."""
self._check_version(request)
self._check_signature(request, consumer, token)
parameters = request.get_nonoauth_parameters()
return parameters
def build_authenticate_header(self, realm=''):
"""Optional support for the authenticate header."""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def _check_version(self, request):
"""Verify the correct version of the request for this server."""
version = self._get_version(request)
if version and version != self.version:
raise Error('OAuth version %s not supported.' % str(version))
def _get_version(self, request):
"""Return the version of the request for this server."""
try:
version = request.get_parameter('oauth_version')
except:
version = OAUTH_VERSION
return version
def _get_signature_method(self, request):
"""Figure out the signature with some defaults."""
try:
signature_method = request.get_parameter('oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
# Get the signature method object.
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names))
return signature_method
def _get_verifier(self, request):
return request.get_parameter('oauth_verifier')
def _check_signature(self, request, consumer, token):
timestamp, nonce = request._get_timestamp_nonce()
self._check_timestamp(timestamp)
signature_method = self._get_signature_method(request)
try:
signature = request.get_parameter('oauth_signature')
except:
raise MissingSignature('Missing oauth_signature.')
# Validate the signature.
valid = signature_method.check(request, consumer, token, signature)
if not valid:
key, base = signature_method.signing_base(request, consumer, token)
raise Error('Invalid signature. Expected signature base '
'string: %s' % base)
def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = now - timestamp
if lapsed > self.timestamp_threshold:
raise Error('Expired timestamp: given %d and now %s has a '
'greater difference than threshold %d' % (timestamp, now,
self.timestamp_threshold))
class SignatureMethod(object):
"""A way of signing requests.
The OAuth protocol lets consumers and service providers pick a way to sign
requests. This interface shows the methods expected by the other `oauth`
modules for signing requests. Subclass it and implement its methods to
provide a new way to sign requests.
"""
def signing_base(self, request, consumer, token):
"""Calculates the string that needs to be signed.
This method returns a 2-tuple containing the starting key for the
signing and the message to be signed. The latter may be used in error
messages to help clients debug their software.
"""
raise NotImplementedError
def sign(self, request, consumer, token):
"""Returns the signature for the given request, based on the consumer
and token also provided.
You should use your implementation of `signing_base()` to build the
message to sign. Otherwise it may be less useful for debugging.
"""
raise NotImplementedError
def check(self, request, consumer, token, signature):
"""Returns whether the given signature is the correct signature for
the given consumer and token signing the given request."""
built = self.sign(request, consumer, token)
return built == signature
class SignatureMethod_HMAC_SHA1(SignatureMethod):
name = 'HMAC-SHA1'
def signing_base(self, request, consumer, token):
if not hasattr(request, 'normalized_url') or request.normalized_url is None:
raise ValueError("Base URL for request is not set.")
sig = (
escape(request.method),
escape(request.normalized_url),
escape(request.get_normalized_parameters()),
)
key = '%s&' % escape(consumer.secret)
if token:
key += escape(token.secret)
raw = '&'.join(sig)
return key, raw
def sign(self, request, consumer, token):
"""Builds the base signature string."""
key, raw = self.signing_base(request, consumer, token)
hashed = hmac.new(key, raw, sha)
# Calculate the digest base 64.
return binascii.b2a_base64(hashed.digest())[:-1]
class SignatureMethod_PLAINTEXT(SignatureMethod):
name = 'PLAINTEXT'
def signing_base(self, request, consumer, token):
"""Concatenates the consumer key and secret with the token's
secret."""
sig = '%s&' % escape(consumer.secret)
if token:
sig = sig + escape(token.secret)
return sig, sig
def sign(self, request, consumer, token):
key, raw = self.signing_base(request, consumer, token)
return raw
| Python |
# Early, and incomplete implementation of -04.
#
import re
import urllib
RESERVED = ":/?#[]@!$&'()*+,;="
OPERATOR = "+./;?|!@"
EXPLODE = "*+"
MODIFIER = ":^"
TEMPLATE = re.compile(r"{(?P<operator>[\+\./;\?|!@])?(?P<varlist>[^}]+)}", re.UNICODE)
VAR = re.compile(r"^(?P<varname>[^=\+\*:\^]+)((?P<explode>[\+\*])|(?P<partial>[:\^]-?[0-9]+))?(=(?P<default>.*))?$", re.UNICODE)
def _tostring(varname, value, explode, operator, safe=""):
if type(value) == type([]):
if explode == "+":
return ",".join([varname + "." + urllib.quote(x, safe) for x in value])
else:
return ",".join([urllib.quote(x, safe) for x in value])
if type(value) == type({}):
keys = value.keys()
keys.sort()
if explode == "+":
return ",".join([varname + "." + urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
return urllib.quote(value, safe)
def _tostring_path(varname, value, explode, operator, safe=""):
joiner = operator
if type(value) == type([]):
if explode == "+":
return joiner.join([varname + "." + urllib.quote(x, safe) for x in value])
elif explode == "*":
return joiner.join([urllib.quote(x, safe) for x in value])
else:
return ",".join([urllib.quote(x, safe) for x in value])
elif type(value) == type({}):
keys = value.keys()
keys.sort()
if explode == "+":
return joiner.join([varname + "." + urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys])
elif explode == "*":
return joiner.join([urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys])
else:
return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
if value:
return urllib.quote(value, safe)
else:
return ""
def _tostring_query(varname, value, explode, operator, safe=""):
joiner = operator
varprefix = ""
if operator == "?":
joiner = "&"
varprefix = varname + "="
if type(value) == type([]):
if 0 == len(value):
return ""
if explode == "+":
return joiner.join([varname + "=" + urllib.quote(x, safe) for x in value])
elif explode == "*":
return joiner.join([urllib.quote(x, safe) for x in value])
else:
return varprefix + ",".join([urllib.quote(x, safe) for x in value])
elif type(value) == type({}):
if 0 == len(value):
return ""
keys = value.keys()
keys.sort()
if explode == "+":
return joiner.join([varname + "." + urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys])
elif explode == "*":
return joiner.join([urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys])
else:
return varprefix + ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
if value:
return varname + "=" + urllib.quote(value, safe)
else:
return varname
TOSTRING = {
"" : _tostring,
"+": _tostring,
";": _tostring_query,
"?": _tostring_query,
"/": _tostring_path,
".": _tostring_path,
}
def expand(template, vars):
def _sub(match):
groupdict = match.groupdict()
operator = groupdict.get('operator')
if operator is None:
operator = ''
varlist = groupdict.get('varlist')
safe = "@"
if operator == '+':
safe = RESERVED
varspecs = varlist.split(",")
varnames = []
defaults = {}
for varspec in varspecs:
m = VAR.search(varspec)
groupdict = m.groupdict()
varname = groupdict.get('varname')
explode = groupdict.get('explode')
partial = groupdict.get('partial')
default = groupdict.get('default')
if default:
defaults[varname] = default
varnames.append((varname, explode, partial))
retval = []
joiner = operator
prefix = operator
if operator == "+":
prefix = ""
joiner = ","
if operator == "?":
joiner = "&"
if operator == "":
joiner = ","
for varname, explode, partial in varnames:
if varname in vars:
value = vars[varname]
#if not value and (type(value) == type({}) or type(value) == type([])) and varname in defaults:
if not value and value != "" and varname in defaults:
value = defaults[varname]
elif varname in defaults:
value = defaults[varname]
else:
continue
retval.append(TOSTRING[operator](varname, value, explode, operator, safe=safe))
if "".join(retval):
return prefix + joiner.join(retval)
else:
return ""
return TEMPLATE.sub(_sub, template)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
import PyRSS2Gen
import sys
from datetime import date
from componentsource.classes.ComponentSourceFeedItem import ComponentSourceFeedItem
################################################################################
rss = PyRSS2Gen.RSS2(
title = 'ComponentSource.com - New Releases',
link = 'http://www.componentsource.com/',
description = 'New Releases at ComponentSource.com',
generator = 'http://feedgenerator.appspot.com/',
docs = ''
)
today = date.today()
items = ComponentSourceFeedItem.gql("ORDER BY pubDate DESC LIMIT 50")
for item in items:
rss.items.append(PyRSS2Gen.RSSItem(
title = item.title,
link = item.link,
# description = '<![CDATA[' + item.description + ']]>',
description = item.description,
pubDate = item.pubDate
))
print 'Content-Type: application/rss+xml'
rss.write_xml(sys.stdout, 'utf-8')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
import urllib
import logging
from componentsource.classes.CustomHTMLParser import CustomHTMLParser
################################################################################
def stripPage(page):
beginIndex = page.find('<ul class="search">')
if beginIndex != -1:
endIndex = page.find('</ul>', beginIndex)
if endIndex != -1:
return page[beginIndex : endIndex]
return ''
################################################################################
url = 'http://www.componentsource.com/newreleases/index.html'
logging.info('Scraping URL: ' + url)
page = urllib.urlopen(url).read()
page = stripPage(page)
if len(page) != 0:
htmlParser = CustomHTMLParser()
htmlParser.feed(page)
htmlParser.close()
logging.info('Done!')
| Python |
from google.appengine.ext import db
"""
"""
class ComponentSourceFeedItem(db.Model):
title = db.StringProperty()
link = db.StringProperty()
description = db.TextProperty()
pubDate = db.DateTimeProperty(auto_now_add=True)
| Python |
import logging
import string
import re
from datetime import datetime
from HTMLParser import HTMLParser
from ComponentSourceFeedItem import ComponentSourceFeedItem
"""
"""
class CustomHTMLParser(HTMLParser):
"""
"""
def resetItemData(self):
self.isItemOpened = False
self.itemTitle = ''
self.itemLink = ''
self.itemDescription = ''
"""
"""
def isItemStart(self, tag, attrs):
if tag.lower() == 'li':
return True
return False
"""
"""
def isItemLink(self, tag, attrs):
if self.isItemOpened:
if tag.lower() == 'a':
if self.currentPath == '/ul/li/h3':
return True
return False
"""
"""
def isItemEnd(self, tag):
if tag.lower() == 'li':
if self.isItemOpened:
return True
return False
"""
"""
def isItemTitle(self):
if self.isItemOpened:
if self.currentPath == '/ul/li/h3/a':
return True
return False
"""
"""
def isItemDescription(self):
if self.isItemOpened:
if self.currentPath == '/ul/li/p/span':
return True
return False
"""
"""
def isItemNew(self):
feedItems = ComponentSourceFeedItem.gql("WHERE link = :1", self.itemLink)
if feedItems.count() == 0:
return True
return False
"""
"""
def saveItem(self):
if self.isItemNew() == True:
feedItem = ComponentSourceFeedItem()
feedItem.title = self.itemTitle.strip().decode('utf-8')
feedItem.link = self.itemLink
feedItem.description = self.itemDescription.strip().decode('utf-8')
feedItem.put()
logging.info('Saving item: ' + feedItem.title)
"""
"""
def __init__(self):
HTMLParser.__init__(self)
self.currentPath = ''
self.resetItemData()
logging.info('Parsing page.')
"""
"""
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if self.isItemStart(tag, attrs):
self.isItemOpened = True
if self.isItemLink(tag, attrs):
self.itemLink = 'http://www.componentsource.com' + attrs['href']
self.currentPath += '/' + tag
"""
"""
def handle_entityref(self, entity):
if entity == 'amp':
if self.isItemTitle():
self.itemTitle = self.itemTitle.rstrip() + ' &'
elif self.isItemDescription():
self.itemDescription = self.itemDescription.rstrip() + ' &'
"""
"""
def handle_data(self, data):
if self.isItemTitle():
self.itemTitle += data + ' '
elif self.isItemDescription():
self.itemDescription += data + ' '
"""
"""
def handle_endtag(self, tag):
self.currentPath = string.rsplit(self.currentPath, '/', 1)[0]
if self.isItemEnd(tag):
self.saveItem()
self.resetItemData()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
import urllib
import logging
from componentsource.classes.CustomHTMLParser import CustomHTMLParser
################################################################################
def stripPage(page):
beginIndex = page.find('<ul class="search">')
if beginIndex != -1:
endIndex = page.find('</ul>', beginIndex)
if endIndex != -1:
return page[beginIndex : endIndex]
return ''
################################################################################
url = 'http://www.componentsource.com/newreleases/index.html'
logging.info('Scraping URL: ' + url)
page = urllib.urlopen(url).read()
page = stripPage(page)
if len(page) != 0:
htmlParser = CustomHTMLParser()
htmlParser.feed(page)
htmlParser.close()
logging.info('Done!')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
import PyRSS2Gen
import sys
from datetime import date
from componentsource.classes.ComponentSourceFeedItem import ComponentSourceFeedItem
################################################################################
rss = PyRSS2Gen.RSS2(
title = 'ComponentSource.com - New Releases',
link = 'http://www.componentsource.com/',
description = 'New Releases at ComponentSource.com',
generator = 'http://feedgenerator.appspot.com/',
docs = ''
)
today = date.today()
items = ComponentSourceFeedItem.gql("ORDER BY pubDate DESC LIMIT 50")
for item in items:
rss.items.append(PyRSS2Gen.RSSItem(
title = item.title,
link = item.link,
# description = '<![CDATA[' + item.description + ']]>',
description = item.description,
pubDate = item.pubDate
))
print 'Content-Type: application/rss+xml'
rss.write_xml(sys.stdout, 'utf-8')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
import PyRSS2Gen
import sys
from datetime import date
from filehungry.classes.FileHungryFeedItem import FileHungryFeedItem
################################################################################
rss = PyRSS2Gen.RSS2(
title = 'FileHungry.com - New products',
link = 'http://www.filehungry.com/',
description = 'New products at FileHungry.com',
generator = 'http://feedgenerator.appspot.com/',
docs = ''
)
today = date.today()
items = FileHungryFeedItem.gql("ORDER BY pubDate DESC LIMIT 50")
for item in items:
rss.items.append(PyRSS2Gen.RSSItem(
title = item.title,
link = item.link,
# description = '<![CDATA[' + item.description + ']]>',
description = item.description,
pubDate = item.pubDate
))
print 'Content-Type: application/rss+xml'
rss.write_xml(sys.stdout, 'utf-8')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
import urllib
import logging
from filehungry.classes.CustomHTMLParser import CustomHTMLParser
################################################################################
def stripPage(page):
beginIndex = page.find('<table width="100%" border="0" cellpadding="0" cellspacing="0" id="LatestSoftware">')
if beginIndex != -1:
endIndex = page.find('</table>', beginIndex)
if endIndex != -1:
return page[beginIndex : endIndex]
return ''
################################################################################
url = 'http://www.filehungry.com/english/new'
logging.info('Scraping URL: ' + url)
page = urllib.urlopen(url).read()
page = stripPage(page)
if len(page) != 0:
htmlParser = CustomHTMLParser()
htmlParser.feed(page)
htmlParser.close()
logging.info('Done!')
| Python |
import logging
import string
import re
from datetime import datetime
from HTMLParser import HTMLParser
from FileHungryFeedItem import FileHungryFeedItem
"""
"""
class CustomHTMLParser(HTMLParser):
"""
"""
def resetItemData(self):
self.isItemOpened = False
self.itemTitle = ''
self.itemLink = ''
self.itemDescription = ''
"""
"""
def isItemStart(self, tag, attrs):
if tag.lower() == 'a':
if self.currentPath.find('span') != -1:
if self.currentPath.endswith('/tr/td'):
return True
return False
"""
"""
def isItemLink(self, tag, attrs):
if self.isItemOpened:
if tag.lower() == 'a':
if self.currentPath.find('span') != -1:
if self.currentPath.endswith('/tr/td'):
return True
return False
"""
"""
def isItemEnd(self, tag):
if tag.lower() == 'tr':
if self.isItemOpened:
return True
return False
"""
"""
def isItemTitle(self):
if self.isItemOpened:
if self.currentPath.endswith('/td/a'):
return True
return False
"""
"""
def isItemDescription(self):
if self.isItemOpened:
if self.currentPath.endswith('/tr/td'):
if self.itemDescription.endswith('... ') == False:
return True
return False
"""
"""
def isItemNew(self):
feedItems = FileHungryFeedItem.gql("WHERE link = :1", self.itemLink)
if feedItems.count() == 0:
return True
return False
"""
"""
def saveItem(self):
if self.isItemNew() == True:
feedItem = FileHungryFeedItem()
feedItem.title = self.itemTitle.strip().decode('utf-8')
feedItem.link = self.itemLink
feedItem.description = self.itemDescription.strip().decode('utf-8')
feedItem.put()
logging.info('Saving item: ' + feedItem.title)
"""
"""
def __init__(self):
HTMLParser.__init__(self)
self.currentPath = ''
self.resetItemData()
logging.info('Parsing page.')
"""
"""
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if self.isItemStart(tag, attrs):
self.isItemOpened = True
if self.isItemLink(tag, attrs):
self.itemLink = 'http://www.filehungry.com' + attrs['href']
self.currentPath += '/' + tag
"""
"""
def handle_entityref(self, entity):
if entity == 'amp':
if self.isItemTitle():
self.itemTitle = self.itemTitle.rstrip() + ' &'
elif self.isItemDescription():
self.itemDescription = self.itemDescription.rstrip() + ' &'
"""
"""
def handle_data(self, data):
if self.isItemTitle():
self.itemTitle += data + ' '
elif self.isItemDescription():
self.itemDescription += data + ' '
"""
"""
def handle_endtag(self, tag):
self.currentPath = string.rsplit(self.currentPath, '/', 1)[0]
if self.isItemEnd(tag):
self.saveItem()
self.resetItemData()
| Python |
from google.appengine.ext import db
"""
"""
class FileHungryFeedItem(db.Model):
title = db.StringProperty()
link = db.StringProperty()
description = db.TextProperty()
pubDate = db.DateTimeProperty(auto_now_add=True)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.