aboutsummaryrefslogtreecommitdiff
path: root/examples/lock_eit.py
blob: f61e18902d814ad996bc8fef5b7106caa236dd67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import justpy as jp
import pyvisa
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

import asyncio
import time

from qolab.hardware import BasicInstrument
from qolab.hardware.scope import SDS1104X
from qolab.hardware.rf_generator import AgilentE8257D
from qolab.feedback import PID
from qolab.data import TraceSetSameX, TraceXY, Trace

def initLog():
    errorTrace = Trace("error")
    errorTrace.config['unit']='V'
    timeTrace = Trace("time")
    timeTrace.config['unit']='S'
    errorLog = TraceXY("error")
    errorLog.x = timeTrace
    errorLog.y = errorTrace

    freqTrace = Trace("frequency")
    freqTrace.config['unit']='Hz'
    freqLog = TraceXY("frequency")
    freqLog.x = timeTrace
    freqLog.y = freqTrace

    feedbackTrace = Trace("feedback")
    feedbackTrace.config['unit']='Hz'
    feedbackLog = TraceXY("feedback")
    feedbackLog.x = timeTrace
    feedbackLog.y = feedbackTrace


    log = TraceSetSameX("timelog")
    log.addTrace(errorLog)
    log.addTrace(freqLog)
    log.addTrace(feedbackLog)
    return log

async def feedbackLoop(apparatus, nsteps):
    # while True:
    for i in range(0,nsteps):
        adjustRFandLog(apparatus)
        await asyncio.sleep(0.001)
    apparatus.runStatus = False

def adjustRFandLog(apparatus):
    timenow = time.time()

    scope = apparatus.scope
    rfgen = apparatus.rfgen
    pid   = apparatus.pid
    log   = apparatus.log

    ch1=scope.getTrace(1, decimate=False)
    err = np.mean(ch1.y.values)
    fdbck = pid.feedback(err)

    freq0 = rfgen.getFreqFixed()
    freq = freq0 + fdbck
    rfgen.setFreqFixed(freq)
    # print(f'error = {err}, feedback = {fdbck}, request freq = {freq}')

    log.addPointToTrace(timenow)
    log.addPointToTrace(err, "error")
    log.addPointToTrace(freq0, "frequency")
    log.addPointToTrace(fdbck, "feedback")
        

def updateLogPlot(apparatus):
    log   = apparatus.log
    f = plt.figure()
    # plt.clf()
    log.plot()
    log_chart.set_figure(f)
    plt.close(f)
    # plt.pause(.0001)
    # jp.Matplotlib(a=wp)
    print(f're-plotting')

async def updateLogPlotLoop(apparatus):
    while True:
        updateLogPlot(apparatus)
        if not apparatus.runStatus:
            break
        await asyncio.sleep(1)

def updateLogFile(apparatus):
    log   = apparatus.log
    logFileName = apparatus.logFileName
    if logFileName is not None:
        log.save(logFileName, item_format='.15e')
        print(f'Saving to {logFileName}')

async def updateLogFileLoop(apparatus):
    while True:
        updateLogFile(apparatus)
        if not apparatus.runStatus:
            break
        await asyncio.sleep(10)


freqZero = 6834687190
freqDeltaM2 = 6835387164

async def main():
    apparatus = BasicInstrument()
    apparatus.config['Device type'] = 'QOL VAMPIRE HighPower magnetometer'
    apparatus.config['Device model'] = 'v0.1'
    apparatus.config['FnamePrefix'] = 'locked_magnetometer'
    apparatus.config['SavePath'] = '/mnt/qol_grp_data/data.VAMPIRE.HighPower'


    print("testing")
    rm = pyvisa.ResourceManager()
    instr_scope=rm.open_resource('TCPIP::192.168.0.61::INSTR')
    scope = SDS1104X(instr_scope)
    instr_rfgen=rm.open_resource('TCPIP::192.168.0.114::INSTR')
    rfgen = AgilentE8257D(instr_rfgen)
    print('------ Header start -------------')
    print(str.join('\n', scope.getHeader()))
    print(str.join('\n', rfgen.getHeader()))
    print('------ Header ends  -------------')
    # ch1  = scope.getTrace(1)
    # traces = scope.getAllTraces()
    pid = PID(100,400,0, sign=-1)

    apparatus.scope = scope
    apparatus.rfgen = rfgen
    apparatus.pid   = pid
    apparatus.log   = initLog()
    apparatus.runStatus = False



    SweepSpan = 10000
    apparatus.rfgen.stopFrequencySweep()
    apparatus.rfgen.setFreqFixed(freqDeltaM2+100)


    print('========== Initial lock ===========')
    apparatus.logFileName = None
    apparatus.pid.reset()
    apparatus.runStatus = True
    res = await asyncio.gather( feedbackLoop(apparatus, nsteps=100), updateLogPlotLoop(apparatus), updateLogFileLoop(apparatus) )
    print(apparatus.logFileName)
    updateLogPlot(apparatus)

    print('========= Long term lock ===========')
    apparatus.log   = initLog()
    apparatus.logFileName = None
    apparatus.logFileName = apparatus.getNextDataFile()
    apparatus.pid.reset()
    apparatus.runStatus = True
    res = await asyncio.gather( feedbackLoop(apparatus, nsteps=1000), updateLogPlotLoop(apparatus), updateLogFileLoop(apparatus) )
    print(apparatus.logFileName)
    updateLogPlot(apparatus)

    # apparatus.log.save(apparatus.logFileName, item_format='.15e')
    print(apparatus.logFileName)
    print('========= Done working with hardware ===========')
    return(apparatus)


async def getPage():
    return wp

async def  jp_startup():
    jp.run_task(main())

if __name__ == '__main__': 
    wp = jp.WebPage(delete_flag=False)
    d=jp.Div(text='Magnetometer lock', a=wp)
    f = plt.figure()
    log_chart = jp.Matplotlib(a=wp)
    plt.close(f)
    # mpl.use("TkAgg")
    # apparatus = asyncio.run(main())
    jp.justpy(getPage, startup=jp_startup)