This commit is contained in:
2019-01-25 14:00:01 +01:00
parent f25d605c01
commit 38888e02fd
2 changed files with 575 additions and 168 deletions

View File

@@ -9,14 +9,13 @@
tuning functions for ESB-MX
Modes:
1 full recording current step
2 full recording open loop
3 full recording closed loop
4 plot the full bode recording
5 plot the full bode recording with an approximation model
6 plot all raw acquired data files
7 custom chirp test
8 generate observer code (after files generated with matlab)
bit 0=1: record/plot current step
bit 1=2: custom chirp record/plot for IdCmd->ActPos transfer function
bit 1=4: custom chirp record/plot for DesPos->ActPos transfer function
bit 2=8: plot the full bode recording
bit 3=16: plot the full bode recording with an approximation model
bit 4=32: plot all raw acquired data files
bit 5=64: generate observer code (after files generated with matlab)
-> check https://github.com/klauer/ppmac for fast data gathering server which supports
phase gathering -> not yet compiling: /home/zamofing_t/Documents/prj/SwissFEL/PowerBrickInspector/ppmac/fast_gather
@@ -42,14 +41,14 @@ class MXTuning(Tuning):
def __init__(self,comm,gather):
Tuning.__init__(self,comm,gather)
self.homed=False
def init_stage(self,force=True):
def init_stage(self,fn=''):
comm=self.comm
if comm is None: return
gpascii=comm.gpascii
if force==False and gpascii.get_variable('Motor[1].HomeComplete', int) == 1:
if comm is None or self.homed or os.path.isfile(fn):
return
gpascii=comm.gpascii
sys.stdout.write('homing stage');sys.stdout.flush()
gpascii.send_line('enable plc1')
@@ -61,9 +60,10 @@ class MXTuning(Tuning):
break
sys.stdout.write('.');sys.stdout.flush()
time.sleep(.2)
self.homed=True
def bode_model_plot(self, mot,base):
self.bode_full_plot(mot,base)
def bode_model_plot(self, mot):
self.bode_full_plot(mot,self.baseDir)
fig=plt.gcf()
_N=1.#E-3 # normalization factor: -> moves 3 decades to right but has factors around 1
# s -> ms
@@ -115,7 +115,7 @@ class MXTuning(Tuning):
print(mdl)
d={'num':num.coeffs,'num1':num1.coeffs,'num2':num2.coeffs,'numc':numc.coeffs,
'den':den.coeffs,'den1':den1.coeffs,'den2':den2.coeffs,'denc':denc.coeffs}
fn=os.path.join(base,'model%d.mat'%mot)
fn=os.path.join(self.baseDir,'model%d.mat'%mot)
import scipy.io
scipy.io.savemat(fn, mdict=d)
print('save to matlab file:'+fn)
@@ -189,7 +189,7 @@ class MXTuning(Tuning):
print(mdl)
d={'num':num.coeffs,'num1':num1.coeffs,'num2':num2.coeffs,'num3':num3.coeffs,'num4':num4.coeffs,'num5':num5.coeffs,'numc':numc.coeffs,
'den':den.coeffs,'den1':den1.coeffs,'den2':den2.coeffs,'den3':den3.coeffs,'den4':den4.coeffs,'den5':den5.coeffs,'denc':denc.coeffs}
fn=os.path.join(base,'model%d.mat'%mot)
fn=os.path.join(self.baseDir,'model%d.mat'%mot)
import scipy.io
scipy.io.savemat(fn, mdict=d)
print('save to matlab file:'+fn)
@@ -345,6 +345,147 @@ EXPORT_SYMBOL(obsvr_servo_ctrl_{motid});'''.format(motid=motid)
plt.plot(t,data[:,0]-data[:,1])
plt.show()
def run(self,mode):
#plt.ion()
if mode&1: # full recording current step
plt.close('all')
self.homed=False
for mot in (1, 2):
fn=os.path.join(self.baseDir, 'curr_step%d.npz' % mot)
self.init_stage(fn)
self.bode_current(motor=mot, magMove=1000, magPhase=500, dwell=10, file=fn)
plt.show(block=False)
f=np.load(fn)
fn=fn[:-3]+'mat'
import scipy.io
scipy.io.savemat(fn, mdict=f)
print('save to matlab file:'+fn)
if mode&2:
plt.close('all')
self.homed=False
motLst = (1, 2) # (2,)#
#recType:
# IA 0 IqCmd,ActPos (for plant transfer function)
# DA 1 DesPos,ActPos (for regulation transfer function)
# all 2 DesPos,ActPos,IqCmd,IqMeas,IqVolts (for current, plant and regulation transfer function)
#>>>>> IqCmd->ActPos transfer function (plant) using closed loop for low frequencies
for mot in motLst:
fn = os.path.join(self.baseDir, 'chirp_IA_%da.npz' % mot)
self.init_stage(fn)
self.custom_chirp(motor=mot, minFrq=1, maxFrq=15, amp=1000, tSec=15, recType=0,openLoop=False, file=fn)
self.homed=False
#>>>>> IqCmd->ActPos transfer function (plant) using open loop for high frequencies
for ext,amp,minFrq,maxFrq,tSec in (('b', 10, 10, 100*1.5, 30),
('c', 50, 100, 300*1.5, 30),
('d', 50, 300, 1000*1.5, 10),
('e', 100, 1000, 2000, 10)):
self.homed=False
for mot in motLst:
fn = os.path.join(self.baseDir, 'chirp_IA_%d%s.npz' % (mot,ext))
self.init_stage(fn)
self.custom_chirp(motor=mot, minFrq=minFrq, maxFrq=maxFrq, amp=amp, tSec=tSec, recType=0,openLoop=True, file=fn)
if mode&4:
plt.close('all')
self.homed = False
motLst = (1, 2) # (2,)#
#>>>>> desPos->actPos transfer function (regulation) using closed loop
#motor1: 0dB at 20.4 Hz
#motor2: 0dB at 11.3 Hz
#1000um ampl. 15Hz ca. 2A current
#100um ampl. 15Hz ca. 200mA current
#100um at 11.3 Hz needs 100mA ->2A at sqrt(20)*11.3 =50Hz
#20um at 11.3 Hz needs 20mA ->2A at sqrt(100)*11.3 =113Hz
# 5um at 11.3 Hz needs 5mA ->2A at sqrt(2000/)*11.3 =226Hz
# 1um at 11.3 Hz needs 1mA ->2A at sqrt(2000)*11.3 =505Hz
#n times freq, -> n^2 current
for ext,amp,minFrq,maxFrq,tSec in (('a', 100, 1, 30*1.5, 10),
('b', 20, 30, 75*1.5, 15),
('c', 5, 75, 150*1.5, 5),
('d', 1, 150, 750, 5)):
self.homed=False
for mot in motLst:
fn = os.path.join(self.baseDir, 'chirp_DA_%d%s.npz' % (mot,ext))
self.init_stage(fn)
self.custom_chirp(motor=mot, minFrq=minFrq, maxFrq=maxFrq, amp=amp, tSec=tSec, recType=1,openLoop=False, file=fn)
#>>>>> all data for different transfer function
for ext,amp,minFrq,maxFrq,tSec in (('a', 5, 10, 250, 10),):
self.homed=False
for mot in motLst:
fn = os.path.join(self.baseDir, 'chirp_all_%d%s.npz' % (mot,ext))
self.init_stage(fn)
self.custom_chirp(motor=mot, minFrq=minFrq, maxFrq=maxFrq, amp=amp, tSec=tSec, recType=2,openLoop=False, file=fn)
if os.path.isfile(fn):
f = np.load(fn)
data = f['data']
meta = f['meta'].item()
meta['file'] = file
if len(meta['address']) == 4:
for xy in ((0, 1), (0, 3), (2, 3)):
self.bode_plot(data, xy=xy, mode=25, **meta)
if mode&8: #plot the full bode recording
plt.close('all')
self.bode_full_plot(mot=1,base=self.baseDir)
self.bode_full_plot(mot=2,base=self.baseDir)
if mode&16: #plot the full bode recording with an approximation model
plt.close('all')
self.bode_model_plot(mot=1)
self.bode_model_plot(mot=2)
if mode&32: # plot all raw acquired data files
# display bode plots
import glob
for fn in glob.glob(os.path.join(self.baseDir,'*.npz')):
fh = np.load(fn)
meta = fh['meta'].item()
data = fh['data']
self.bode_plot(data, mode=25, **meta)
if mode&64: #generater code
#before this can be done, the observer controller has to be designed with matlab:
#s.a.ESB_MX/matlab/Readme.md
#clear;
#clear global;
#close all;
#[mot1,mot2]=identifyFxFyStage();
#[pb]=simFxFyStage(mot1);
#[ssc]=StateSpaceControlDesign(mot1);
#[pb]=simFxFyStage(mot2);
#[ssc]=StateSpaceControlDesign(mot2);
#after this go to: python/usr_code and call make to build the controller
#to activate the controller checkout: PBTools/pbtools/usr_servo_phase
base=os.path.dirname(__file__)
(hdr1,prog1)=self.usr_servo_gen_code('/tmp/ssc1.mat')
(hdr2,prog2)=self.usr_servo_gen_code('/tmp/ssc2.mat')
fn_ct=os.path.join(base,'usr_code/usrcode_template.c')
fn_ht=os.path.join(base,'usr_code/usrcode_template.h')
fnc=os.path.join(base,'usr_code/usrcode.c')
fnh=os.path.join(base,'usr_code/usrcode.h')
s=open(fn_ht).read()
s=s.replace('<usr_header>',hdr1+'\n\n'+hdr2)
fh=open(fnh,'w')
fh.write(s)
fh.close()
print(fnh+' generated.')
s=open(fn_ct).read()
s=s.replace('<usr_code>',prog1+'\n\n'+prog2)
fh=open(fnc,'w')
fh.write(s)
fh.close()
print(fnc+' generated.')
print('now compile it looking at PBTools/pbtools/usr_servo_phase/usrServoSample')
print('done')
plt.show()
@@ -390,8 +531,7 @@ Examples:'''+''.join(map(lambda s:cmd+s, exampleCmd))+'\n '
parser.add_argument('--host', help='hostname', metavar='HOST', default='SAR-CPPM-EXPMX1')
parser.add_argument('--mode', '-m', type=int, help='modes (see below)', default=1)
parser.add_argument('--dir', help='dir', default=None)
parser.add_argument('--dir', help='dir', default='MXTuning')
args=parser.parse_args()
#plt.ion()
@@ -403,156 +543,9 @@ Examples:'''+''.join(map(lambda s:cmd+s, exampleCmd))+'\n '
comm = PPComm(host=args.host)
gt = Gather(comm)
tune=MXTuning(comm,gt)
base='MXTuning'
if args.dir is not None:
base=args.dir
assert(os.path.exists(base))
#base=os.path.join(base,args.dir)
#if not os.path.exists(base):
# os.mkdir(base)
mode=args.mode
#plt.ion()
if mode==1: # full recording current step
homed=False
for mot in (1, 2):
fn=os.path.join(base, 'curr_step%d.npz' % mot)
if not os.path.isfile(fn) and not homed: tune.init_stage();homed=True
fig=plt.figure(mot)
tune.bode_current(motor=mot, magMove=1000, magPhase=500, dwell=10, file=fn,fig=fig)
plt.show(block=False)
f=np.load(fn)
fn=fn[:-3]+'mat'
import scipy.io
scipy.io.savemat(fn, mdict=f)
print('save to matlab file:'+fn)
elif mode==2: # full recording open loop
for mot in (1, 2):
fsin=os.path.join(base, 'sine_ol_mot%d.npz' % (mot))
fcrp=os.path.join(base, 'chirp_ol_mot%d' % (mot))
if not os.path.isfile(fsin): tune.init_stage();plt.close('all')
tune.bode_sine(openloop=True, file=fsin, motor=mot)
plt.show(block=False)
for ext,amp,minFrq,maxFrq,tSec in (('a', 10, 10, 300,30),
('b', 50,100, 500,30),
('c', 50,300,1500,10),
('d',100,300,2000,10)):
f=fcrp+ext+'.npz'
if not os.path.isfile(f): tune.init_stage();plt.close('all')
tune.bode_chirp(openloop=True, file=f, motor=mot, amp=amp, minFrq=minFrq, maxFrq=maxFrq, tSec=tSec)
plt.show(block=False)
elif mode==3: # full recording closed loop
for mot in (1,2):
#fsin=os.path.join(base, 'sine_cl_mot%d.npz' % (mot))
fcrp=os.path.join(base, 'chirp_cl_mot%d' % (mot))
#if not os.path.isfile(fsin): tune.init_stage();plt.close('all')
#tune.bode_sine(openloop=False, file=fsin, motor=mot)
#the generated program is prog 999 (only during acquisition)
# Gather.MaxLines=174762 -> ca 15 sec. is max.
#with higher frequency and amplitudes often is in DacLimit !
for ext,amp,minFrq,maxFrq,tSec in (('a',100, 1, 200,15),
('b', 20,10, 300,5),
('c', 5,10, 300,5),
('d', 1,10,1000,5),
):
f=fcrp+ext+'.npz'
if not os.path.isfile(f): tune.init_stage();plt.close('all')
tune.bode_chirp(openloop=False, file=f, motor=mot, amp=amp, minFrq=minFrq, maxFrq=maxFrq, tSec=tSec)
plt.show(block=False)
elif mode==4: #plot the full bode recording
tune.bode_full_plot(mot=1,base=base)
tune.bode_full_plot(mot=2,base=base)
elif mode==5: #plot the full bode recording with an approximation model
tune.bode_model_plot(mot=1,base=base)
tune.bode_model_plot(mot=2,base=base)
elif mode == 6: # plot all raw acquired data files
# display bode plots
import glob
for fn in glob.glob(os.path.join(base,'*.npz')):
if os.path.basename(fn).startswith('sine_ol_mot'):
tune.bode_sine(openloop=True, file=fn)
if os.path.basename(fn).startswith('chirp_ol_mot'):
tune.bode_chirp(openloop=True, file=fn)
if os.path.basename(fn).startswith('sine_cl_mot'):
tune.bode_sine(openloop=False, file=fn)
if os.path.basename(fn).startswith('chirp_cl_mot'):
tune.bode_chirp(openloop=False, file=fn)
elif mode==7: #further tests
fn='/tmp/cst_chirp0.npz'
motLst=(1, 2)#(2,)#
init_stage=False
for mot in motLst:
fn=os.path.join(base, 'cst_chirp_s_ol_%d.npz' % mot)
if not init_stage and not os.path.isfile(fn):tune.init_stage();init_stage=True
tune.custom_chirp(motor=mot,minFrq=100,maxFrq=1000,amp=50,tSec=15,mode=0,file=fn)
init_stage=False
for mot in motLst:
fn=os.path.join(base, 'cst_chirp_s_cl1_%d.npz' % mot)
if not init_stage and not os.path.isfile(fn):tune.init_stage();init_stage=True
tune.custom_chirp(motor=mot,minFrq=1,maxFrq=100,amp=20,tSec=15,mode=1,file=fn)
init_stage=False
for mot in motLst:
fn=os.path.join(base, 'cst_chirp_s_cl2a_%d.npz' % mot)
if not init_stage and not os.path.isfile(fn):tune.init_stage();init_stage=True
tune.custom_chirp(motor=mot,minFrq=1,maxFrq=30,amp=100,tSec=30,mode=2,file=fn)
for mot in motLst:
fn=os.path.join(base, 'cst_chirp_s_cl2b_%d.npz' % mot)
if not init_stage and not os.path.isfile(fn):tune.init_stage();init_stage=True
tune.custom_chirp(motor=mot,minFrq=20,maxFrq=150,amp=10,tSec=30,mode=2,file=fn)
init_stage=False
for mot in motLst:
fn=os.path.join(base, 'cst_chirp_s_cl2c_%d.npz' % mot)
if not init_stage and not os.path.isfile(fn):tune.init_stage();init_stage=True
tune.custom_chirp(motor=mot,minFrq=100,maxFrq=300,amp=1,tSec=30,mode=2,file=fn)
elif mode==8: #generater code
#before this can be done, the observer controller has to be designed with matlab:
#s.a.ESB_MX/matlab/Readme.md
#clear;
#clear global;
#close all;
#[mot1,mot2]=identifyFxFyStage();
#[pb]=simFxFyStage(mot1);
#[ssc]=StateSpaceControlDesign(mot1);
#[pb]=simFxFyStage(mot2);
#[ssc]=StateSpaceControlDesign(mot2);
#after this go to: python/usr_code and call make to build the controller
#to activate the controller checkout: PBTools/pbtools/usr_servo_phase
base=os.path.dirname(__file__)
(hdr1,prog1)=tune.usr_servo_gen_code('/tmp/ssc1.mat')
(hdr2,prog2)=tune.usr_servo_gen_code('/tmp/ssc2.mat')
fn_ct=os.path.join(base,'usr_code/usrcode_template.c')
fn_ht=os.path.join(base,'usr_code/usrcode_template.h')
fnc=os.path.join(base,'usr_code/usrcode.c')
fnh=os.path.join(base,'usr_code/usrcode.h')
s=open(fn_ht).read()
s=s.replace('<usr_header>',hdr1+'\n\n'+hdr2)
fh=open(fnh,'w')
fh.write(s)
fh.close()
print(fnh+' generated.')
s=open(fn_ct).read()
s=s.replace('<usr_code>',prog1+'\n\n'+prog2)
fh=open(fnc,'w')
fh.write(s)
fh.close()
print(fnc+' generated.')
print('now compile it looking at PBTools/pbtools/usr_servo_phase/usrServoSample')
elif mode==9: #SCRATCH
motLst=(1, 2)#(2,)#
init_stage=False
for mot in motLst:
fn=os.path.join(base, 'scratch_%d.npz' % mot)
if not init_stage and not os.path.isfile(fn):tune.init_stage();init_stage=True
tune.custom_chirp(motor=mot,minFrq=1,maxFrq=20,amp=200,tSec=15,mode=2,file=fn)
elif mode==10: # record stage x and probe encoder
tune.check_fast_stage()
print('done')
plt.show()
tune.baseDir=args.dir
assert(os.path.exists(tune.baseDir))
tune.run(args.mode)
#------------------ Main Code ----------------------------------
#ssh_test()'/tmp/usrcode.c'
ret=parse_args()

View File

@@ -0,0 +1,414 @@
#!/usr/bin/env python
# *-----------------------------------------------------------------------*
# | |
# | Copyright (c) 2016 by Paul Scherrer Institute (http://www.psi.ch) |
# | |
# | Author Thierry Zamofing (thierry.zamofing@psi.ch) |
# *-----------------------------------------------------------------------*
from __future__ import print_function
import os,sys
import wx
import wx.py
import numpy as np
from MAxyPlot import *
from MAError import *
from MAVelocity import *
#from hdfTree import *
#from hdfGrid import *
#from hdfAttrib import *
#from hdfImage import *
import wxutils as ut
class MADoc():
'''
lenRec=fh['rec']
lenPts=fh['pts']
pts= X,Y array
idx 0 1 2 3 4 5 6
OLD Motor[3].ActPos Motor[2].ActPos Motor[1].ActPos Motor[3].DesPos Motor[2].DesPos Motor[1].DesPos Gate3[1].Chan[1].UserFlag
NEW Motor[1].ActPos Motor[2].ActPos Motor[1].DesPos Motor[2].DesPos Gate3[1].Chan[1].UserFlag
NEW y.ActPos x.ActPos y.DesPos x.DesPos Gate3[1].Chan[1].UserFlag
OLD->NEW
0->none
1->1
2->0
3->none
4->3
5->2
Implemented messages
0: The time slider has changed. usrData=index
1: The position slider has changed. usrData=index
'''
def __init__(self):
self.view=[] #list of object that have view on this document
pass
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
rec=fh['rec']
pts=fh['pts']
self.meta=meta=fh['meta'].item()
print(meta)
try:
ts=meta['timebase']
except KeyError:
ts=self.meta['srv_per']*self.meta['acq_per']*1E-3 #0.2ms
self.ts=ts
lenRec=rec.shape[0]
lenPts=pts.shape[0]
#idxTrigger=np.hstack(([0],rec[:,4]))
#doc.idxTrigger=idxTrigger=np.where(np.diff(idxTrigger)==1)[0]
idxTrigger=rec[:,4]
self.idxTrigger=np.where(np.diff(idxTrigger)==1)[0]+1
idxInPos=[] #first point at idx 0
idx=0
for i in range(lenPts):
l=rec[idx:,(3,2)]-pts[i,:]
l2=l[:,0]**2+l[:,1]**2
try:
ofs=l2.argmin()
except ValueError:
break#print(l2[ofs])
idx+=ofs
idxInPos.append(idx)
#idx+=rng/2
self.idxInPos=np.array(idxInPos)
def Update(self,skipView,msg,usrData):
for v in self.view:
if v==skipView: continue
v.OnUpdate(msg,usrData)
class AboutFrame(wx.Frame):
def __init__(self,parent):
wx.Frame.__init__(self,parent,-1,'About MotionAnalyzer',size=(300,330))
imgDir=ut.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 __init__(self, parent, title,doc):
wx.Frame.__init__(self, parent, title=title, size=wx.Size(650, 230),style = wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP)
self.doc=doc;doc.view.append(self)
imgDir=ut.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)
sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(sizer)
wxTxt = wx.StaticText(self, wx.ID_ANY, "MyLabel", wx.DefaultPosition, wx.DefaultSize, 0 )
sizer.Add(wxTxt, 1, wx.LEFT | wx.TOP | wx.GROW)
wxTimeCtrl=ut.SliderGroup(self, label='DataPoint', range=(0, 1000))
wxTimeCtrl.SetCallback(MAMainFrame.OnSetTime, wxTimeCtrl)
sizer.Add(wxTimeCtrl.sizer, 0, wx.EXPAND | wx.ALIGN_CENTER | wx.ALL, border=5) #wxSplt.SplitVertically(wxTree, wxTxt)
wxPosCtrl=ut.SliderGroup(self, label='IdxInPos', range=(0, 1000))
wxPosCtrl.SetCallback(MAMainFrame.OnSetIdxInPos, wxPosCtrl)
sizer.Add(wxPosCtrl.sizer, 0, wx.EXPAND | wx.ALIGN_CENTER | wx.ALL, border=5) #wxSplt.SplitVertically(wxTree, wxTxt)
wxTrigCtrl=ut.SliderGroup(self, label='IdxTrigger', range=(0, 1000))
wxTrigCtrl.SetCallback(MAMainFrame.OnSetIdxTrigger, wxTrigCtrl)
sizer.Add(wxTrigCtrl.sizer, 0, wx.EXPAND | wx.ALIGN_CENTER | wx.ALL, border=5) #wxSplt.SplitVertically(wxTree, wxTxt)
#wxSplt.SetMinimumPaneSize(320)
#wxLstCtrl=HdfAttrListCtrl(wxSplt)
#wxSplt.SplitVertically(wxTree, wxLstCtrl)
self.BuildMenu()
self.Centre()
self.wxTimeCtrl=wxTimeCtrl
self.wxPosCtrl=wxPosCtrl
self.wxTrigCtrl=wxTrigCtrl
self.wxTxt=wxTxt
#self.wxTree=wxTree
#self.display=wxTxt
def __del__(self):
self.CloseFile()
def OpenFile(self,fn_npz):
doc=self.doc
doc.OpenFile(fn_npz)
s='content of numpy file: '+fn_npz+'\n'
fh=doc.fh
for k,v in fh.iteritems():
s+=' '+k+': '+str(v.dtype)+' '+str(v.shape)+'\n'
self.wxTxt.SetLabel(s)
idxInPos=doc.idxInPos
idxTrigger=doc.idxTrigger
rec=fh['rec']
pts=fh['pts']
lenRec=rec.shape[0]
lenPts=pts.shape[0]
idx=min(idxInPos.shape[0],idxTrigger.shape[0])-1
self.SetStatusText('scaling of DesTimeBase: %f'%(float(idxInPos[idx])/idxTrigger[idx]))
#self.PlotJitter()
self.wxTimeCtrl.slider.SetRange(0,lenRec-1)
self.wxTimeCtrl.slider.SetPageSize(idxInPos[1]-idxInPos[0])
self.wxPosCtrl.slider.SetRange(0,lenPts-1)
self.wxPosCtrl.slider.SetPageSize(10)
self.wxTrigCtrl.slider.SetRange(0,idxTrigger.shape[0]-1)
self.wxTrigCtrl.slider.SetPageSize(10)
def CloseFile(self):
#http://docs.wxwidgets.org/2.8/wx_windowdeletionoverview.html#windowdeletionoverview
#print 'CloseFile'
try:
self.doc.fh.close()
del self.doc.fh
except AttributeError as e:
pass
def PlotJitter(self):
doc=self.doc
fh=doc.fh
idxInPos=doc.idxInPos
idxTrigger=doc.idxTrigger
#display the jitter of inPos->trigger
ts=doc.ts
jitter=idxTrigger[:idxInPos.shape[0]]-idxInPos
import matplotlib.pyplot as plt # used for the colormaps
plt.figure('jitter inPos -> trigger: scaling of DesTimeBase: %f'%(float(idxInPos[-1])/idxTrigger[idxInPos.shape[0]-1]))
plt.plot(jitter*ts)
plt.ylabel('jitter in ms')
plt.ylabel('point idx')
plt.show()
def DispJitter(self,idxInPos,idxTrigger):
doc=self.doc
ts=doc.ts
self.SetStatusText("Jitter: %.2gms scaling: %.6g"%((idxTrigger-idxInPos)*ts,float(idxInPos)/idxTrigger))
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()
self.SetStatusText("This is the status message")
def OnShowXYPath(self, event):
frame=MAxyPlotFrame(self,self.doc)
frame.Show(True)
def OnShowError(self, event):
frame=MAErrorFrame(self,self.doc)
frame.Show(True)
def OnShowVelocity(self, event):
frame=MAVelocityFrame(self,self.doc)
frame.Show(True)
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)
def OnUpdate(self,msg,usrData):
#this is the model-view-control update function
#print self,msg,usrData
pass
@staticmethod
def OnSetTime(usrData, idxRec, msg):
'called when the time slider has been changed'
#print('OnSetTime', usrData, value, msg)
view=usrData.slider.Parent
doc=view.doc
idxInPos=np.argmin(abs(doc.idxInPos-idxRec))
view.wxPosCtrl.SetValue(idxInPos)
idxTrigger=np.argmin(abs(doc.idxTrigger-idxRec))
view.wxTrigCtrl.SetValue(idxTrigger)
view.DispJitter(doc.idxInPos[idxInPos],doc.idxTrigger[idxTrigger])
doc.Update(view,0,idxRec)
@staticmethod
def OnSetIdxInPos(usrData, idxInPos, msg):
'called when the idxInPos slider has been changed'
#print('OnSetPosIdx', usrData, value, msg)
view = usrData.slider.Parent
doc = view.doc
idxRec=doc.idxInPos[idxInPos]
view.wxTimeCtrl.SetValue(idxRec)
idxTrigger=np.argmin(abs(doc.idxTrigger-idxRec))
view.wxTrigCtrl.SetValue(idxTrigger)
view.DispJitter(doc.idxInPos[idxInPos],doc.idxTrigger[idxTrigger])
doc.Update(view, 0, idxRec)
@staticmethod
def OnSetIdxTrigger(usrData, idxTrigger, msg):
'called when the idxTrigger slider has been changed'
#print('OnSetIdxTrigger', usrData, value, msg)
view = usrData.slider.Parent
doc = view.doc
idxRec=doc.idxTrigger[idxTrigger]
view.wxTimeCtrl.SetValue(idxRec)
idxInPos=np.argmin(abs(doc.idxInPos-idxRec))
view.wxPosCtrl.SetValue(idxInPos)
view.DispJitter(doc.idxInPos[idxInPos],doc.idxTrigger[idxTrigger])
doc.Update(view, 0, idxRec)
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()
doc=MADoc()
frame = MAMainFrame(None,'PBMotionAnalyzer',doc)
if args.npzFile:
frame.OpenFile(args.npzFile)
frame.Show(True)
f1 = MAxyPlotFrame(frame, doc)
f1.Show(True)
#f2= MAErrorFrame(frame, doc)
#f2.Show(True)
#f3= MAVelocityFrame(frame, doc)
#f3.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()