add preliminary PBMotionAnalyzer.py

This commit is contained in:
2016-12-22 10:13:32 +01:00
parent b98456b6ad
commit 6e31c7e705
6 changed files with 235 additions and 181 deletions

View File

@@ -1,180 +0,0 @@
#!/usr/bin/env python
# *-----------------------------------------------------------------------*
# | |
# | Copyright (c) 2015 by Paul Scherrer Institute (http://www.psi.ch) |
# | |
# | Author Thierry Zamofing (thierry.zamofing@psi.ch) |
# *-----------------------------------------------------------------------*
'''
gathers data on powerpmac and plot
#mode bits:
0 1 configure acquisition -> needs -c
1 2 start acquisition ->Gather.Enable=2
2 4 stop acquisition ->Gather.Enable=0
3 8 wait acquisition stopped ->while(1){if(Gather.Enable==0) break}
4 16 upload acquisition
5 32 plot acquisition -> needs -a (or -c)
mode 1+2+8+16+32 | user sets a stop
mode 1+2 | motion, wait some time| #mode 4+16+32
mode 1+8+16+32 | start acqu, do motion stop acqu.
verbose bits:
1 basic info
2 wait progress
4 upload progress
#config file example:
{
"channels": [
"Motor[1].ActPos",
"Motor[9].ActPos",
"Motor[10].ActPos",
"Motor[11].ActPos",
"PowerBrick[0].GpioData[0]"
],
"axes": [
[0, "b", "ActPos 1"],
[1, "g", "ActPos_9"],
[2, "r", "ActPos_10"],
[3, "m", "ActPos_11"],
[4, ["bits", 15, 3], "GPIO"]],
"gather": {
"MaxSamples":1000,
"Period":10
}
}
Acquired time is:MaxSamples*Period*.2
'''
#gatherPlot
#channels -c '[Sys.ServoCount,Motor[1].ActPos,Motor[9].ActPos,Motor[10].ActPos,Motor[11].ActPos,PowerBrick[0].GpioData[0]]'
#axis -a '(((0,1),'b','ActPos 1'), ((0,2),'g','ActPos 9'), ((0,3),'r','ActPos 10'), ((0,4),'m','ActPos 11'), ((0,5),('bits',14,18),'GPIO'))
#('bits',14,18) means decode bits 14-18
#
#check: Gather.Enable Gather.Index
#on PPMAC do something like:
#Gather.Items=6
#Gather.MaxSamples=10000
#Gather.Period=10
#Gather.Addr[0]=Sys.ServoCount.a
#Gather.Addr[1]=Motor[1].ActPos.a
#Gather.Addr[2]=Motor[9].ActPos.a
#Gather.Addr[3]=Motor[10].ActPos.a
#Gather.Addr[4]=Motor[11].ActPos.a
#Gather.Addr[5]=PowerBrick[0].GpioData[0].a
#
#Gather.Enable=2
## move the motor[1]
#Gather.Enable=0
#
#1;&1;#1->1000X
#k;j=0;P1=1000
#b3r
# to run that script without password, make first an ssh connection e.g. ssh root@PPMACZT84
#
import os, sys, json
import numpy as np
import matplotlib as mpl
import subprocess as sprc
class GatherPlot:
def __init__(self):
pass
def plot1(self):
import matplotlib.pyplot as plt
fnLoc='/tmp/gather.txt'
data = np.genfromtxt(fnLoc, delimiter=' ')
x=np.arange(data.shape[0])*2. #-> msec
pass #-> needs -a (or -c)
fig=plt.figure()
ax0 = fig.add_subplot(1,1,1)
ax0.set_xlabel('msec')
ax=[ax0,]
axArgs=[(0,'r','A'),(1,'g','B'),(2,'b','C')]
for i in range(len(axArgs)-1):
ax.append(ax0.twinx())
fig.subplots_adjust(right=0.75)
n=(len(ax)-2);dx=.2/n
for i in range(n):
ax[2+i].spines['right'].set_position(('axes', 1+dx*(1+i)))
ax[2+i].set_frame_on(True)
ax[2+i].patch.set_visible(False)
for i in range(len(axArgs)):
idx,param,lbl=axArgs[i]
col=param
ax[i].set_ylabel(lbl, color=col)
ax[i].plot(x, data[:,idx], color=col)
ax[i].tick_params(axis='y', colors=col)
plt.show()
def plot(self):
import matplotlib.pyplot as plt
fnLoc='/tmp/gather.txt'
data = np.genfromtxt(fnLoc, delimiter=' ')
fig=plt.figure()
ax0 = fig.add_subplot(1,1,1)
ax0.set_xlabel('msec')
ax=[ax0,]
#fig.subplots_adjust(right=0.75)
col='b'
#idx=1
#ax[0].set_ylabel(ch[idx], color=col)
x=data[:,1]
y=data[:,2]
hl=ax[0].plot(x, y, color=col)
ax[0].tick_params(axis='y', colors=col)
cid = fig.canvas.mpl_connect('scroll_event', self.onclick)
fig.obj=self
self.data=data
#self.ch=ch
self.idx=1
self.ax=ax
self.col=col
self.hl=hl
plt.show()
@staticmethod
def onclick(event):
#print 'button=%s, x=%d, y=%d, xdata=%f, ydata=%f'%(
# event.button, event.x, event.y, event.xdata, event.ydata)
obj=event.canvas.figure.obj
if event.button=='up':
if obj.idx<len(obj.ch)-1:
obj.idx+=1
else:
if obj.idx>0:
obj.idx-=1
obj.ax[0].set_ylabel(obj.ch[obj.idx], color=obj.col)
d=obj.data[:,obj.idx]
if obj.args.diff:
d=np.diff(d)
obj.hl[0].set_ydata(d)
#obj.ax[0].plot(x, obj.data[:,obj.idx]obj.data[:,obj.idx]obj.data[:,obj.idx], color=obj.col)
min=bottom=d.min()
max=d.max()
delta=(max-min)/10.
obj.ax[0].set_ylim(bottom=min-delta,top=max+delta,emit=True,auto=True)
event.canvas.figure.show()
if __name__=='__main__':
gp=GatherPlot()
gp.plot()

232
python/PBMotionAnalyzer.py Normal file
View File

@@ -0,0 +1,232 @@
import os,sys
import wx
import wx.py
import numpy as np
#from hdfTree import *
#from hdfGrid import *
#from hdfAttrib import *
#from hdfImage import *
import utilities as ut
class Path():
@staticmethod
def GetImage():
path=__file__
try:symPath=os.readlink(path) #follow symbolic link
except (AttributeError,OSError) as e:pass
else:
path=symPath
path=os.path.abspath(path)
path=os.path.dirname(path)
return os.path.join(path,'images')
class AboutFrame(wx.Frame):
def __init__(self,parent):
wx.Frame.__init__(self,parent,-1,'About MotionAnalyzer',size=(300,330))
imgDir=Path.GetImage()
icon = wx.Icon(os.path.join(imgDir,'PBMA.ico'), wx.BITMAP_TYPE_ICO)
self.SetIcon(icon)
self.Centre()
panel=wx.Panel(self,-1)
#import pkg_resources
#v=pkg_resources.get_distribution("h5pyViewer")
v='my version info'
s='Version:'+str(v)+'\n(c) www.psi.ch\n Author: Thierry Zamofing\n thierry.zamofing@psi.ch'
st0=wx.StaticText(panel,-1,s,(30,10))
bmp = wx.StaticBitmap(panel,-1,wx.Bitmap(os.path.join(imgDir,'PBMA.png'), wx.BITMAP_TYPE_ANY ), (30,st0.Position[1]+st0.Size[1]+10))
for k,v in os.environ.iteritems():
print k,'=',v
class MAMainFrame(wx.Frame):
def OpenFile(self,fn_npz):
try:
self.fh=fh=np.load(fn_npz)
except IOError as e:
sys.stderr.write('Unable to open File: '+fn_npz+'\n')
else:
pass
s='content of numpy file: '+fn_npz+'\n'
for k,v in fh.iteritems():
s+=' '+k+': '+str(v.dtype)+' '+str(v.shape)+'\n'
self.wxTxt.SetLabel(s)
#self.wxTree.ShowHirarchy(self.fid)
def CloseFile(self):
#http://docs.wxwidgets.org/2.8/wx_windowdeletionoverview.html#windowdeletionoverview
#print 'CloseFile'
try:
self.fh.close()
del self.fh
except AttributeError as e:
pass
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=wx.Size(650, 350))
imgDir=Path.GetImage()
icon = wx.Icon(os.path.join(imgDir,'PBMA.ico'), wx.BITMAP_TYPE_ICO)
self.SetIcon(icon)
#wxSplt = wx.SplitterWindow(self, -1)
#wxTree = HdfTreeCtrl(wxSplt, 1, wx.DefaultPosition, (-1,-1), wx.TR_HAS_BUTTONS)
#wxTree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, id=1)
#wxTree.Bind(wx.EVT_TREE_ITEM_MENU, self.OnMenu, id=1)
#wx.EVT_TREE_ITEM_MENU(id, func)
#wxTxt = wx.StaticText(wxSplt, -1, '',(10,10) )#, style=wx.ALIGN_CENTRE)
self.wxTxt = wx.StaticText(self, wx.ID_ANY, "MyLabel", wx.DefaultPosition, wx.DefaultSize, 0 )
#wxSplt.SplitVertically(wxTree, wxTxt)
#wxSplt.SetMinimumPaneSize(320)
#wxLstCtrl=HdfAttrListCtrl(wxSplt)
#wxSplt.SplitVertically(wxTree, wxLstCtrl)
self.BuildMenu()
self.Centre()
#self.wxTree=wxTree
#self.display=wxTxt
def __del__(self):
self.CloseFile()
def OnOpen(self, event):
dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), '','numpy files (*.npz;*.npy)|*.npz;*.npy|all (*.*)|*.*', wx.OPEN|wx.FD_CHANGE_DIR)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
#mypath = os.path.basename(path)
#self.SetStatusText("You selected: %s" % mypath)
self.CloseFile()
self.OpenFile(path)
#print 'OnOpen',path
dlg.Destroy()
def OnCloseWindow(self, event):
#print 'OnCloseWindow'
self.Destroy()
def OnAbout(self,event):
frame=AboutFrame(self)
frame.Show()
def BuildMenu(self):
#http://wiki.wxpython.org/AnotherTutorial#wx.MenuBar
mnBar = wx.MenuBar()
#-------- File Menu --------
mn = wx.Menu()
mnItem=mn.Append(wx.ID_OPEN, '&Open', 'Open a new document');self.Bind(wx.EVT_MENU, self.OnOpen, mnItem)
#mnSub = wx.Menu()
#mnItem=mnSub.Append(wx.ID_ANY, 'SubMenuEntry', 'My SubMenuEntry')
#mn.AppendMenu(wx.ID_ANY, 'SubMenu', mnSub)
mn.AppendSeparator()
mnItem=mn.Append(wx.ID_EXIT, '&Quit', 'Quit the Application');self.Bind(wx.EVT_MENU, self.OnCloseWindow, mnItem)
mnBar.Append(mn, '&File')
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
#-------- Edit Menu --------
mn = wx.Menu()
mnItem = mn.Append(wx.ID_ANY, 'Show &XY-Path', 'Show XY-path motion path');self.Bind(wx.EVT_MENU, self.OnShowXYPath, mnItem)
mnItem = mn.Append(wx.ID_ANY, 'Show &Error', 'Show error of motion path');self.Bind(wx.EVT_MENU, self.OnShowError, mnItem)
mnItem = mn.Append(wx.ID_ANY, 'Show &Velocity', 'Show velocity of motion path');self.Bind(wx.EVT_MENU, self.OnShowVelocity, mnItem)
mnItem = mn.Append(wx.ID_ANY, '&Python Shell', 'Opens an interactive python shell"');self.Bind(wx.EVT_MENU, self.OnShell, mnItem)
mnBar.Append(mn, '&Window')
#-------- Help Menu --------
mn = wx.Menu()
#mnItem=mn.Append(wx.ID_HELP,'Help','Application Help')
mnItem=mn.Append(wx.ID_ABOUT,'About','Application About');self.Bind(wx.EVT_MENU, self.OnAbout, mnItem)
mnBar.Append(mn, '&Help')
#mn.AppendSeparator()
#mnItem = wx.MenuItem(mn, 105, '&Quit\tCtrl+Q', 'Quit the Application')
#mnItem.SetBitmap(wx.Image('stock_exit-16.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap())
#mn.AppendItem(mnItem)
self.SetMenuBar(mnBar)
self.CreateStatusBar()
def OnShowXYPath(self, event):
pass
def OnShowError(self, event):
pass
def OnShowVelocity(self, event):
pass
def OnShell(self, event):
frame = wx.Frame(self, -1, "wxPyShell",size=wx.Size(800, 500))
imgDir=Path.GetImage()
icon = wx.Icon(os.path.join(imgDir,'PBMA.ico'), wx.BITMAP_TYPE_ICO)
frame.SetIcon(icon)
frame.Centre()
fh=app.GetTopWindow().fh
wnd=app.GetTopWindow()
loc={'app' :app,
'fh' :fh,
'pts' :fh['pts'],
'rec' :fh['rec']
}
introText='''Shell to the HDF5 objects
app: application object
fh: numpy file
pts: desired motion points
rec: recorded data
#Examples:
pts
rec
#using user defined modules
#import userSample as us;reload(us);us.test1(hid)
'''
shell=wx.py.shell.Shell(frame, introText=introText,locals=loc)
frame.Show(True)
#if loc is None, all variables are visible. the context is global
#shell.push('wnd=app.GetTopWindow()')
#for cmd in [
# 'wnd=app.GetTopWindow();wxTree=wnd.wxTree',
# 'wxNode=wnd.wxTree.GetSelection()',
# 'print wnd.fid',
# 'lbl=wxTree.GetItemText(wxNode)',
# 'hid=wxTree.GetPyData(wxNode)']:
# shell.run(cmd, prompt=False)
if __name__ == '__main__':
def GetArgs():
import sys,argparse #since python 2.7
exampleCmd='/tmp/shapepath.npz'
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description=__doc__,
epilog='Example:\n'+os.path.basename(sys.argv[0])+' '+exampleCmd+'\n ')
parser.add_argument('npzFile', nargs='?', help='the npz file with motion path data to show',default='/tmp/shapepath.npz')
args = parser.parse_args()
return args
class MyApp(wx.App):
def OnInit(self):
args=GetArgs()
frame = MAMainFrame(None, 'PBMotionAnalyzer')
if args.npzFile:
frame.OpenFile(args.npzFile)
frame.Show(True)
self.SetTopWindow(frame)
return True
#------------------ Main Code ----------------------------------
#redirect stdout/stderr:
#http://www.blog.pythonlibrary.org/2009/01/01/wxpython-redirecting-stdout-stderr/
#https://groups.google.com/forum/#!topic/wxpython-users/S9uSKIYdYoo
#https://17677433047266577941.googlegroups.com/attach/e4d343dc6a751906/REDIRECT.PY?part=2&view=1&vt=ANaJVrFeyCjCMydKnkyfFbYJM7ip07mE-ozUIBxJ5A1QuK1GhycJYJsPTxpAaNk5L2LpXvGhzRPInxDt8_WUcUyK2Ois28Dq8LNebfYoWG9Yxr-tujf5Jk4
#http://www.wxpython.org/docs/api/wx.PyOnDemandOutputWindow-class.html
rd=not sys.stdout.isatty()#have a redirect window, if there is no console
#rd=True #force to open a redirect window
rd=False #avoid a redirect window
app = MyApp(redirect=rd)
app.MainLoop()

BIN
python/images/PBMA.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

BIN
python/images/PBMA.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@@ -200,9 +200,11 @@ class ShapePath:
self.ax=ax
self.hl=hl
def plot_gather(self,fnLoc='/tmp/gather.txt'):
def plot_gather(self,fnLoc='/tmp/gather.txt',fnOut='/tmp/shapepath.npz'):
pts=self.points
rec = np.genfromtxt(fnLoc, delimiter=' ')
if fnOut:
np.savez_compressed(fnOut, rec=rec, pts=pts)
fig=plt.figure()
ax = fig.add_subplot(1,1,1)
#hl=ax[0].plot(x, y, color=col)