towards matlab
This commit is contained in:
@@ -76,6 +76,11 @@ class MXTuning(Tuning):
|
||||
num1=np.poly1d([mag1])
|
||||
den1 = np.poly1d([T1**2,2*T1*d1,1])
|
||||
|
||||
#reiner integrator: 30Hz=0dB -> k=30*2*pi=180
|
||||
#num1=np.poly1d([120*120])
|
||||
#den1 = np.poly1d([1,0,0])
|
||||
|
||||
|
||||
#first resonance frequency
|
||||
f2=np.array([197,199])
|
||||
d2=np.array([.02,.02])#daempfung
|
||||
@@ -101,9 +106,9 @@ class MXTuning(Tuning):
|
||||
num=num1*num2*numc#*num3
|
||||
den=den1*den2*denc#*den3
|
||||
mdl= signal.lti(num, den) #num denum
|
||||
print num
|
||||
print den
|
||||
print mdl
|
||||
print(num)
|
||||
print(den)
|
||||
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)
|
||||
@@ -175,9 +180,9 @@ class MXTuning(Tuning):
|
||||
num=num1*num2*num3*num4*num5*numc
|
||||
den=den1*den2*den3*den4*den5*denc
|
||||
mdl= signal.lti(num, den) #num denum
|
||||
print num
|
||||
print den
|
||||
print mdl
|
||||
print(num)
|
||||
print(den)
|
||||
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)
|
||||
@@ -196,6 +201,100 @@ class MXTuning(Tuning):
|
||||
# tp print see also: print(np.poly1d([1,2,3], variable='s')), print(np.poly1d([1,2,3], r=True, variable='s'))
|
||||
|
||||
|
||||
def custom_chirp(self):
|
||||
motor = 1
|
||||
amp, minFrq, maxFrq, tSec = (10, 10, 300, 30)
|
||||
file='/tmp/gather.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)
|
||||
prog = '''
|
||||
&0 //cout works only in coord 0
|
||||
open prog 999
|
||||
L11=0
|
||||
L10=0
|
||||
L12=0
|
||||
L13=0
|
||||
L14=0
|
||||
Gather.Enable=2
|
||||
while(L10<300005)
|
||||
{
|
||||
L12=10*sin(31.415926535897931*(pow(1.058324104020218,(L10*0.000199996614513))-1)/log(1.058324104020218))
|
||||
cout%d:(L12)
|
||||
L10=L10+1
|
||||
}
|
||||
Gather.Enable=0
|
||||
close
|
||||
b999r
|
||||
'''%motor
|
||||
gpascii = self.comm.gpascii
|
||||
gt = self.gather
|
||||
print(gpascii.servo_period)
|
||||
gt.set_phasemode(False)
|
||||
address=("Motor[1].IqCmd", "Motor[1].ActPos",)
|
||||
gt.set_address(*address)
|
||||
#Gather.Enable=1
|
||||
gt.set_property(MaxSamples=300000, Period=1)
|
||||
|
||||
# gt.enable(2)
|
||||
gpascii.send_line(prog)
|
||||
gpascii.sync()
|
||||
|
||||
gt.wait_stopped()
|
||||
self.data=data=gt.upload()
|
||||
meta={'motor':motor,'date':time.asctime(),'minFrq':minFrq,'maxFrq':maxFrq,'tSec':tSec,'amp':amp,'address':address}
|
||||
np.savez_compressed(file, data=data, meta=meta)
|
||||
meta['file'] = file
|
||||
self.bode_chirp_plot(data, meta,True)
|
||||
pass
|
||||
|
||||
|
||||
def bode_sine(self,openloop=True,motor=1,minFrq=1,maxFrq=20,numFrq=15,amp=10,file='/tmp/gather.npz'):
|
||||
'''calculates phase and amplitude at different frequencies and
|
||||
saves:#loads and plots the bode diagram'''
|
||||
if False:# os.path.isfile(file):
|
||||
f=np.load(file)
|
||||
bode=f['bode']
|
||||
meta=f['meta'].item()
|
||||
meta['file']=file
|
||||
else:
|
||||
gpascii=self.comm.gpascii
|
||||
#motor 1 maximum: 13750
|
||||
#amp= percentage of maximum amplitude
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot(1, 1, 1)
|
||||
frqLst=np.logspace(np.log10(minFrq),np.log10(maxFrq),numFrq)
|
||||
n=len(frqLst)
|
||||
#frqLst=(10,15,20,25,30)
|
||||
bode=np.ndarray((n,3))
|
||||
bode[:, 0]=frqLst
|
||||
#for i in range(n):
|
||||
for i in range(n-1,-1,-1):
|
||||
frq=frqLst[i]
|
||||
t=1
|
||||
rep=max(1,frq*t)
|
||||
if openloop:
|
||||
data=self.do_command('openloopsine',motor,amp,frq,rep,0)
|
||||
else:
|
||||
data=self.do_command('sinusoidal',motor,amp,frq,rep,0)
|
||||
data=data[:,(1,2)]
|
||||
gpascii.send_line('#1j=0')
|
||||
time.sleep(1)
|
||||
ax.clear()
|
||||
avg=data.mean(0)
|
||||
print(avg)
|
||||
ax.plot(data[:, 0]-avg[0] , 'b-', label='input')
|
||||
ax.plot(data[:, 1]-avg[1], 'g-', label='output')
|
||||
#plt.pause(.05)
|
||||
bode[i,1:]=self.phase_amp(frq, rep)
|
||||
print('frq %g ampl %g phase %g'%tuple(bode[i,:]))
|
||||
plt.show(block=False);plt.pause(.05)
|
||||
|
||||
meta={'motor':motor,'date':time.asctime()}
|
||||
np.savez_compressed(file, bode=bode, meta=meta)
|
||||
meta['file']=file
|
||||
self.bode_sine_plot(bode, meta)
|
||||
|
||||
|
||||
def bode(mdl):
|
||||
w,mag,phase = signal.bode(mdl,1000)
|
||||
f=w/(2*np.pi)
|
||||
@@ -214,6 +313,16 @@ def bode(mdl):
|
||||
|
||||
if __name__=='__main__':
|
||||
from argparse import ArgumentParser,RawDescriptionHelpFormatter
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
logger = logging.getLogger('pbtools.misc.pp_comm')
|
||||
logger.setLevel(logging.DEBUG)
|
||||
logging.basicConfig(format=('%(asctime)s %(name)-12s '
|
||||
'%(levelname)-8s %(message)s'),
|
||||
datefmt='%m-%d %H:%M',
|
||||
)
|
||||
|
||||
|
||||
def parse_args():
|
||||
'main command line interpreter function'
|
||||
#usage: gpasciiCommunicator.py --host=PPMACZT84 myPowerBRICK.cfg
|
||||
@@ -315,7 +424,13 @@ Examples:'''+''.join(map(lambda s:cmd+s, exampleCmd))+'\n '
|
||||
tune.bode_sine(openloop=False, file=fn)
|
||||
if os.path.basename(fn).startswith('chirp_cl_mot'):
|
||||
tune.bode_chirp(openloop=False, file=fn)
|
||||
print 'done'
|
||||
print('done')
|
||||
elif mode==7: #further tests
|
||||
tune.init_stage();
|
||||
plt.close('all')
|
||||
tune.bode_sine()
|
||||
tune.custom_chirp()
|
||||
|
||||
plt.show()
|
||||
#------------------ Main Code ----------------------------------
|
||||
#ssh_test()
|
||||
|
||||
@@ -151,19 +151,19 @@ class HelicalScan:
|
||||
param = self.param
|
||||
cx, cz, w, fy, = (0.2,0.3,0.1,0.4)
|
||||
#cx, cz, w, fy, = (10.,20,3.,40)
|
||||
print 'input : cx:%.6g cz:%.6g w:%.6g fy:%.6g' % (cx,cz,w/d2r*1000.,fy)
|
||||
print('input : cx:%.6g cz:%.6g w:%.6g fy:%.6g' % (cx,cz,w/d2r*1000.,fy))
|
||||
(dx,dz,w,y) = self.fwd_transform(cx,cz,w,fy)
|
||||
print 'fwd_trf: dx:%.6g dz:%.6g w:%.6g fy:%.6g' % (dx,dz,w/d2r*1000.,y)
|
||||
print('fwd_trf: dx:%.6g dz:%.6g w:%.6g fy:%.6g' % (dx,dz,w/d2r*1000.,y))
|
||||
(cx,cz,w,fy) = self.inv_transform(dx,dz,w,y)
|
||||
print 'inv_trf: cx:%.6g cz:%.6g w:%.6g fy:%.6g' % (cx,cz,w/d2r*1000.,fy)
|
||||
print('inv_trf: cx:%.6g cz:%.6g w:%.6g fy:%.6g' % (cx,cz,w/d2r*1000.,fy))
|
||||
|
||||
dx, dz, w, y, = (0.2,0.3,0.1,0.4)
|
||||
#dx, dz, w, y, = (10.,20,3.,40)
|
||||
print 'input : dx:%.6g dz:%.6g w:%.6g fy:%.6g' % (dx,dz,w/d2r*1000.,y)
|
||||
print('input : dx:%.6g dz:%.6g w:%.6g fy:%.6g' % (dx,dz,w/d2r*1000.,y))
|
||||
(cx,cz,w,fy) = self.inv_transform(dx,dz,w,y)
|
||||
print 'inv_trf: cx:%.6g cz:%.6g w:%.6g fy:%.6g' % (cx,cz,w/d2r*1000.,fy)
|
||||
print('inv_trf: cx:%.6g cz:%.6g w:%.6g fy:%.6g' % (cx,cz,w/d2r*1000.,fy))
|
||||
(dx,dz,w,y) = self.fwd_transform(cx,cz,w,fy)
|
||||
print 'fwd_trf: dx:%.6g dz:%.6g w:%.6g fy:%.6g' % (dx,dz,w/d2r*1000.,y)
|
||||
print('fwd_trf: dx:%.6g dz:%.6g w:%.6g fy:%.6g' % (dx,dz,w/d2r*1000.,y))
|
||||
|
||||
|
||||
|
||||
@@ -306,7 +306,7 @@ class HelicalScan:
|
||||
p[i,0]=x_i+r_i*np.sin(phi_i) # x= x_i+r_i*cos(phi_i+w)+cx
|
||||
p[i,1]=y_i # y= y_i
|
||||
p[i,2]=z_i+r_i*np.cos(phi_i) # z= z_i+r_i*sin(phi_i*w)
|
||||
print p
|
||||
print(p)
|
||||
ofs=(p[1]+p[0])/2. # = center of the cristal
|
||||
|
||||
m=Trf.trans(*ofs); self.hOrig=self.pltOrig(m)
|
||||
@@ -327,7 +327,7 @@ class HelicalScan:
|
||||
p[i, 0] = x_i + r_i * np.cos(phi_i) # x= x_i+r_i*cos(phi_i+w)+cx
|
||||
p[i, 1] = y_i # y= y_i
|
||||
p[i, 2] = z_i + r_i * np.sin(phi_i) # z= z_i+r_i*sin(phi_i*w)
|
||||
print p
|
||||
print(p)
|
||||
ofs = (p[1] + p[0]) / 2. # = center of the cristal
|
||||
|
||||
m = Trf.trans(cx,fy,cz)
|
||||
@@ -375,7 +375,7 @@ class HelicalScan:
|
||||
p[i,1]=y_i # y= y_i
|
||||
p[i,2]=z_i+r_i*np.cos(phi_i) # z= z_i+r_i*sin(phi_i*w)
|
||||
ofs=(p[1]+p[0])/2. # = center of the cristal
|
||||
print 'p, ofs',p,ofs
|
||||
print('p, ofs',p,ofs)
|
||||
|
||||
m=Trf.trans(0,0,0); self.hOrig=self.pltOrig(m)
|
||||
hCrist,pt=self.pltCrist(cx=-ofs[0],fy=-ofs[1],cz=-ofs[2])
|
||||
@@ -458,7 +458,7 @@ class HelicalScan:
|
||||
for k,v in fh.iteritems():
|
||||
s+=' '+k+': '+str(v.dtype)+' '+str(v.shape)+'\n'
|
||||
setattr(self,k,v)
|
||||
print s
|
||||
print(s)
|
||||
|
||||
def fwd_transform(self,cx,cz,w,fy):
|
||||
#cx,cy: coarse stage
|
||||
@@ -530,7 +530,7 @@ class HelicalScan:
|
||||
param[i, 1] = y
|
||||
param[i, 2:] = HelicalScan.meas_rot_ctr(x) # (bias,ampl,phase)
|
||||
(bias, ampl, phase) = param[i][2:]
|
||||
print param
|
||||
print(param)
|
||||
|
||||
|
||||
def calcParam(self,x=((-241.,96.,-53.),(-162.,-293.,246.)),
|
||||
@@ -569,15 +569,15 @@ class HelicalScan:
|
||||
x_ = ampl * np.cos(w + phase) + bias
|
||||
print(x_)
|
||||
(dx,dz,w,y_) = (0,0,0,y[0])
|
||||
print 'input : dx:%.6g dz:%.6g w:%.6g fy:%.6g' % (dx,dz,w/d2r*1000.,y_)
|
||||
print('input : dx:%.6g dz:%.6g w:%.6g fy:%.6g' % (dx,dz,w/d2r*1000.,y_))
|
||||
(cx,cz,w,fy) = self.inv_transform(dx,dz,w,y_)
|
||||
print 'inv_trf: cx:%.6g cz:%.6g w:%.6g fy:%.6g' % (cx,cz,w/d2r*1000.,fy)
|
||||
print('inv_trf: cx:%.6g cz:%.6g w:%.6g fy:%.6g' % (cx,cz,w/d2r*1000.,fy))
|
||||
(dx, dz, w, y_) = (0,0,0,y[1])
|
||||
print 'input : dx:%.6g dz:%.6g w:%.6g fy:%.6g' % (dx, dz, w / d2r * 1000., y_)
|
||||
print('input : dx:%.6g dz:%.6g w:%.6g fy:%.6g' % (dx, dz, w / d2r * 1000., y_))
|
||||
(cx, cz, w, fy) = self.inv_transform(dx, dz, w, y_)
|
||||
print 'inv_trf: cx:%.6g cz:%.6g w:%.6g fy:%.6g' % (cx, cz, w / d2r * 1000., fy)
|
||||
print('inv_trf: cx:%.6g cz:%.6g w:%.6g fy:%.6g' % (cx, cz, w / d2r * 1000., fy))
|
||||
|
||||
print param
|
||||
print(param)
|
||||
|
||||
|
||||
def pltOrig(self,m,h=None):
|
||||
|
||||
@@ -56,7 +56,6 @@ import matplotlib as mpl
|
||||
import matplotlib.pyplot as plt
|
||||
import subprocess as sprc
|
||||
import telnetlib
|
||||
from utilities import *
|
||||
|
||||
class ShapePath:
|
||||
def __init__(self,args):
|
||||
|
||||
91
python/utilities.py
Executable file
91
python/utilities.py
Executable file
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python
|
||||
#*-----------------------------------------------------------------------*
|
||||
#| |
|
||||
#| Copyright (c) 2016 by Paul Scherrer Institute (http://www.psi.ch) |
|
||||
#| |
|
||||
#| Author Thierry Zamofing (thierry.zamofing@psi.ch) |
|
||||
#*-----------------------------------------------------------------------*
|
||||
'''
|
||||
utilities classes
|
||||
'''
|
||||
import json
|
||||
import numpy as np
|
||||
import time,os
|
||||
|
||||
|
||||
class dotdict(dict):
|
||||
"""dot.notation access to dictionary attributes"""
|
||||
def __init__(self,arg=None,**kwargs):
|
||||
if arg!=None:
|
||||
self.__fill__(arg)
|
||||
self.__fill__(kwargs)
|
||||
|
||||
def __fill__(self,kw):
|
||||
for k,v in kw.iteritems():
|
||||
if type(v)==dict:
|
||||
self[k]=dotdict(v)
|
||||
else:
|
||||
self[k]=v
|
||||
if type(v)==list:
|
||||
for i,w in enumerate(v):
|
||||
if type(w)==dict:
|
||||
v[i]=dotdict(w)
|
||||
pass
|
||||
|
||||
def __dir__(self):
|
||||
l=dir(object)
|
||||
#l.extend(self.keys())
|
||||
l.extend(map(str,self.keys()))
|
||||
return l
|
||||
|
||||
def __getattr__(self, attr):
|
||||
#return self.get(attr)
|
||||
try:
|
||||
return self[attr]
|
||||
except KeyError as e:
|
||||
raise AttributeError("%r instance has no attribute %r" % (self.__class__, attr))
|
||||
|
||||
def __repr__(self):
|
||||
return '<' + dict.__repr__(self)[1:-1] + '>'
|
||||
|
||||
def PrettyPrint(self,indent=0):
|
||||
for k,v in self.iteritems():
|
||||
if type(v)==dotdict:
|
||||
print(' '*indent,str(k)+':')
|
||||
v.PrettyPrint(indent+2)
|
||||
else:
|
||||
print(' '*indent+str(k)+'\t'+str(v))
|
||||
|
||||
__setattr__= dict.__setitem__
|
||||
__delattr__= dict.__delitem__
|
||||
#__getattr__= dict.__getattr__
|
||||
|
||||
|
||||
def ConvUtf8(s):
|
||||
'convert unicoded json object to ASCII encoded'
|
||||
#http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python
|
||||
if isinstance(s, dict):
|
||||
return {ConvUtf8(key): ConvUtf8(value) for key, value in s.items()}
|
||||
elif isinstance(s, list):
|
||||
return [ConvUtf8(element) for element in s]
|
||||
elif isinstance(s, str):
|
||||
return s.encode('utf-8')
|
||||
else:
|
||||
return s
|
||||
|
||||
class GpasciiCommunicator():
|
||||
'''Communicates with the Delta Tau gpascii programm
|
||||
'''
|
||||
gpascii_ack="\x06\r\n"
|
||||
gpascii_inp='Input\r\n'
|
||||
|
||||
def connect(self, host, username='root', password='deltatau',prompt='ppmac# '):
|
||||
p=telnetlib.Telnet(host)
|
||||
print(p.read_until('login: '))
|
||||
p.write(username+'\n')
|
||||
print(p.read_until('Password: '))
|
||||
p.write(password+'\n')
|
||||
print(p.read_until(prompt)) # command prompt
|
||||
p.write('gpascii -2\n') # execute gpascii command
|
||||
print(p.read_until(self.gpascii_inp))
|
||||
return p
|
||||
Reference in New Issue
Block a user