Commit 9bd0af38 authored by Christian Schneider's avatar Christian Schneider
Browse files

Adapted to new pyvisa import

parent 18ed2950
......@@ -397,7 +397,7 @@ def plot_NormCircle(module, engine='b', fit=True, **kwargs):
# Plot fit
fig.line(d.real, d.imag,
legend='Circle Fit', color='firebrick')
legend_label='Circle Fit', color='firebrick')
# Return figure
return fig
......@@ -437,7 +437,7 @@ def plot_delay(circuit):
'could be running just parallel')
fig = figure(width=800, height=400, title='Electric Delay fit')
phase = np.unwrap(np.angle(circuit.value_raw)) * 180 / np.pi
fig.circle(circuit.freq, phase, legend='Data')
fig.circle(circuit.freq, phase, legend_label='Data')
# Plot fit range
idx = int(circuit.fit_range*len(circuit.freq))
fig.circle(circuit.freq[:idx], phase[:idx], color='green')
......@@ -445,13 +445,13 @@ def plot_delay(circuit):
# Plot fit
fig.line(circuit.freq,
circuit.delay * circuit.freq * 360,
color='firebrick', line_dash=[5, 5], legend='Linear Fit',
color='firebrick', line_dash=[5, 5], legend_label='Linear Fit',
line_width=2)
show(fig)
else:
fig = figure(width=800, height=400, title='Electric Delay fit')
phase = np.unwrap(np.angle(circuit.value_raw)) * 180 / np.pi
fig.circle(circuit.freq, phase, legend='Data')
fig.circle(circuit.freq, phase, legend_label='Data')
# Plot fit range
idx = int(circuit.fit_range*len(circuit.freq))
fig.circle(circuit.freq[:idx], phase[:idx], color='green')
......@@ -459,7 +459,7 @@ def plot_delay(circuit):
# Plot fit
fig.line(circuit.freq, circuit._delayOffset -
circuit.delay * circuit.freq * 360,
color='firebrick', line_dash=[5, 5], legend='Linear Fit',
color='firebrick', line_dash=[5, 5], legend_label='Linear Fit',
line_width=2)
show(fig)
......@@ -470,7 +470,7 @@ def plot_linear_slope(circuit):
fig = figure(width=800, height=400, title='Linear fit in dB ' +
'magnitude')
fig.circle(circuit.freq, 20 * np.log10(np.abs(circuit.value_raw)),
legend='Data')
legend_label='Data')
# Plot fit range
idx = int(circuit.fit_range*len(circuit.freq))
fig.circle(circuit.freq[:idx], 20 * np.log10(np.abs(
......@@ -480,7 +480,7 @@ def plot_linear_slope(circuit):
# Plot fit
fig.line(circuit.freq, circuit._bg_pars[-1] +
circuit._bg_pars[-2] * circuit.freq, color='firebrick',
line_dash=[5, 5], legend='Lorentzian Fit', line_width=2)
line_dash=[5, 5], legend_label='Lorentzian Fit', line_width=2)
show(fig)
except AttributeError:
print('No background subtraction\n')
......@@ -490,10 +490,10 @@ def plot_lorentzian(circuit):
display(Markdown('## 3. Lorentzian fit\n'))
fig = figure(width=800, height=400, title='Lorentzian fit')
fig.circle(circuit.freq, np.abs(circuit.value),
legend='Data')
legend_label='Data')
fig.line(circuit.freq, lorentzian_abs(circuit.freq,
*circuit._lor_pars[0]),
legend='Lorentzian Fit', color='firebrick', line_dash=[5, 5],
legend_label='Lorentzian Fit', color='firebrick', line_dash=[5, 5],
line_width=2)
show(fig)
errs = np.sqrt(np.diag(circuit._lor_pars[1]))
......@@ -507,7 +507,7 @@ def plot_circle_fit_I(circuit):
display(Markdown('## 4. Circle fit to obtain offrespoint, a and ' +
'alpha\n'))
fig = figure(width=400, height=400, title='Circle Fit I')
fig.circle(circuit.value.real, circuit.value.imag, legend='Data',
fig.circle(circuit.value.real, circuit.value.imag, legend_label='Data',
size=3*circuit._weights)
x_o = circuit.fitresults_full_model.Value.x_offres
y_o = circuit.fitresults_full_model.Value.y_offres
......@@ -516,9 +516,9 @@ def plot_circle_fit_I(circuit):
p = np.linspace(0, 2 * np.pi, 100)
circle = np.complex(xc, yc) + r * np.exp(1j * p)
fig.circle(offrespoint.real, offrespoint.imag, color='firebrick',
size=10, legend='Offrespoint')
size=10, legend_label='Offrespoint')
fig.line(circle.real, circle.imag, color='firebrick', line_width=2,
legend='Circle Fit')
legend_label='Circle Fit')
show(fig)
......@@ -529,10 +529,10 @@ def plot_phase_fit(circuit):
data = (circuit.value - np.complex(xc, yc))
fig = figure(width=800, height=400, title='Lorentzian fit')
fig.circle(circuit.freq, np.unwrap(np.angle(data)),
legend='Data')
legend_label='Data')
fig.line(circuit.freq, tan_phase(circuit.freq,
*circuit._theta_pars[0]),
legend='Tan Fit', color='firebrick', line_dash=[5, 5],
legend_label='Tan Fit', color='firebrick', line_dash=[5, 5],
line_width=2)
show(fig)
errs = np.sqrt(np.diag(circuit._theta_pars[1]))
......@@ -547,16 +547,16 @@ def plot_final_circle(circuit):
fig = figure(width=400, height=400, title='Circle fit (final)' +
'for Ql, absQc and fr')
fig.circle(circuit.circle_norm.real, circuit.circle_norm.imag,
legend='Data', size=3*circuit._weights)
legend_label='Data', size=3*circuit._weights)
if circuit.type == 'Notch':
d = notch_model(circuit.freq, *circuit._cir_fit_pars[0])
fig.line(d.real, d.imag,
legend='Cirlce Fit', color='firebrick',
legend_label='Cirlce Fit', color='firebrick',
line_width=2)
else:
d = reflection_model(circuit.freq, *circuit._cir_fit_pars[0])
fig.circle(d.real, d.imag,
legend='Circle Fit', color='firebrick',
legend_label='Circle Fit', color='firebrick',
)
show(fig)
......
......@@ -20,6 +20,9 @@ import numpy as np
from threading import Timer
from time import sleep
# Password debug
import urllib.parse
# Fridges
fridges = ['Cooler', 'Freezer']
......@@ -41,14 +44,14 @@ cryo_url = ("mysql+mysqlconnector://{username}:" +
"{password}@" +
"{hostname}/{databasename}").format(
username="group",
password='K!rchmair@IQOQI18',
password=urllib.parse.quote_plus('K!rchmair@IQOQI18'),
hostname='192.168.0.137',
databasename='Cryostats')
devices_url = ("mysql+mysqlconnector://{username}:" +
"{password}@" +
"{hostname}/{databasename}").format(
username="group",
password='K!rchmair@IQOQI18',
password=urllib.parse.quote_plus('K!rchmair@IQOQI18'),
hostname='192.168.0.137',
databasename='devices')
......
......@@ -6,7 +6,7 @@ authors: Christian Schneider <c.schneider@uibk.ac.at>
Oscar Gargiulo <oscar.gargiulo@uibk.ac.at>
Date: 19.01.2018
"""
import visa
import pyvisa as visa
import numpy as np
class APMS(object):
......
......@@ -6,7 +6,7 @@ authors: Christian Schneider <c.schneider@uibk.ac.at>
Oscar Gargiulo <oscar.gargiulo@uibk.ac.at>
Date: 19.01.2018
"""
import visa
import pyvisa as visa
import numpy as np
import time
......
......@@ -6,7 +6,7 @@ Created on Mon Nov 07 2016
@author: Michael Schmid, Christian Schneider <c.schneider@uibk.ac.at>
"""
import visa
import pyvisa as visa
version = '2.0.0'
print('BK Precision v' + version)
......
......@@ -4,7 +4,7 @@
Author: Olivia Lanes, Christian Schneider <c.schneider@uibk.ac.at>
"""
# class definition
import visa
import pyvisa as visa
from time import sleep
......
......@@ -15,7 +15,7 @@ v2.0.0 - CHR:
v2.0.1 - OSC:
- migrated to VISA
"""
import visa
import pyvisa as visa
import time
import numpy as np
from tqdm import tqdm_notebook
......
......@@ -9,7 +9,7 @@ v1.2.2 - OSC:
"""
import struct
import visa
import pyvisa as visa
import time
import numpy as np
from tqdm import tqdm_notebook
......
......@@ -19,7 +19,7 @@ v1.0.1 - OSC:
- added the route pulse sync to Trig1 port in pulsed mode
"""
import visa
import pyvisa as visa
import numpy as np
......
......@@ -5,7 +5,7 @@
Driver for Minicircuits RCDAT Digital Step Attenuator
"""
import visa
import pyvisa as visa
VERSION = '1.0.0'
......
......@@ -10,7 +10,7 @@ v2.0.1 - OSC:
import time
import numpy as np
import visa
import pyvisa as visa
import struct
......
......@@ -5,7 +5,7 @@
Driver for the Rohde und Schwarz Digital Step Attenuator
"""
import visa
import pyvisa as visa
VERSION = '1.0.0'
......
......@@ -11,7 +11,7 @@ v1.0.1 - OSC:
import struct
import time
import numpy as np
import visa
import pyvisa as visa
class RSA5115B(object):
......
......@@ -7,7 +7,7 @@ Date: 02.10.2019
"""
import numpy as np
import visa
import pyvisa as visa
VERSION = '1.1.0'
......
......@@ -6,7 +6,7 @@ v3.0.1 - OSC:
- migrated to visa
"""
# class definition
import visa
import pyvisa as visa
import numpy as np
......
......@@ -22,8 +22,8 @@ try:
from Monitor.main import Instruments
print('\nHi {user}. You find your Instrument Monitor at:\n{url}'
.format(user=getpass.getuser(),
url='https://kirchmair.iqoqi.at/lab/dashboard/devices/{' +
'}'.format(getpass.getuser())))
url='https://kirchmair.iqoqi.at/lab/dashboard/devices/{}'
.format(getpass.getuser())))
except:
print('\nHi {user}. No connection to database. You use the library now '
......
__version__ = '4.0.4'
__version__ = '4.1.0'
"""
Last Updates:
......
......@@ -13,8 +13,6 @@ from functools import partial
import os
import calendar
from bokeh.embed import server_document
from bokeh.server.server import Server
from flask import Flask, render_template, request, flash, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
......@@ -25,43 +23,41 @@ from numpy import tile
from itertools import groupby
from numpy import datetime64, timedelta64
# Cryostat plotting
from FridgeWatch.Fridge_SQL_Plot import load_data, plot, load_water_single, load_lab
from FridgeWatch.Fridge_SQL_ACQ import db_cryo as fridge_watch_db
from FridgeWatch.Fridge_SQL_ACQ import OperationTimes, Cryostat, CryoState, read_fridge
# Password debug
import urllib.parse
# Parameters ###################################################################
cryolist = ['Cooler', 'Freezer']
lablist = ['Lab3']
# Flask Config #################################################################
app = Flask(__name__)
devices_url = ("mysql+mysqlconnector://{username}:" +
"{password}@" +
"{hostname}/{databasename}").format(
"{password}@" +
"{hostname}/{databasename}").format(
username="group",
password='K!rchmair@IQOQI18',
password=urllib.parse.quote_plus('K!rchmair@IQOQI18'),
hostname='192.168.0.137',
databasename='devices')
cryo_url = ("mysql+mysqlconnector://{username}:" +
"{password}@" +
"{hostname}/{databasename}").format(
"{password}@" +
"{hostname}/{databasename}").format(
username="group",
password='K!rchmair@IQOQI18',
password=urllib.parse.quote_plus('K!rchmair@IQOQI18'),
hostname='192.168.0.137',
databasename='Cryostats')
app.config['SQLALCHEMY_DATABASE_URI'] = devices_url
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {'connect_args': {'use_pure': True,
'connect_timeout': 1}}
'connect_timeout': 1}}
app.config['SQLALCHEMY_BINDS'] = {
'cryostats': cryo_url,
'devices': devices_url
'devices': devices_url
}
app.root_path = os.path.dirname(os.path.abspath(__file__))
db = SQLAlchemy(app)
# Helper functions #############################################################
def np_to_datetime(date):
"""
......@@ -100,25 +96,31 @@ class Instruments(db.Model):
db.create_all()
# DB Cryostat classes ############################################################
class cryo_values(object):
def __init__(self):
self.pt = pt_values()
class pt_values(object):
"""Values of pulse tube cooler"""
def __init__(self):
self.total = None
self.months = {}
self.years = {}
def grouper(item):
return item.time.year, item.time.strftime("%B")
def grouper_year(item):
return item.time.year
# Devices ######################################################################
@app.route('/')
@app.route('/devices')
......@@ -139,16 +141,15 @@ def index():
elif tp == 'VNA':
d.devtype_mode = tp + "-{}".format(d.parameters['RF Power'])
dev[d.user].append(d)
# Sort by device type
for u in users:
dev[u].sort(key=lambda x:x.devtype)
dev[u].sort(key=lambda x: x.devtype)
# Render template
return render_template('devices_overview.html',
users=users,
devices=dev)
users=users,
devices=dev)
@app.route('/devices/<string:user>/', methods=['GET', 'POST'])
......@@ -239,15 +240,15 @@ def temp_doc(doc, cryo_id, delta_hour=24):
since_time=since_time)
# Create plot
sources, fig = plot(cryo_id, data, key_and_labels[0], key_and_labels[1],
save_html=False)
save_html=False)
# Close connection to database
fridge_watch_db.session.commit()
fridge_watch_db.session.close()
def update():
#print(sources[0].data['x'][-1])
last_time = datetime.datetime.utcfromtimestamp(sources[0].data['x'][-1]/1000)
#last_time = np_to_datetime(sources[0].data['x'][-1])
# print(sources[0].data['x'][-1])
last_time = datetime.datetime.utcfromtimestamp(sources[0].data['x'][-1] / 1000)
# last_time = np_to_datetime(sources[0].data['x'][-1])
fd, key_and_labels = load_data(cryo_id,
since_time=last_time)
fridge_watch_db.session.commit()
......@@ -259,10 +260,11 @@ def temp_doc(doc, cryo_id, delta_hour=24):
y=fd[c],
series_name=tile(name, len(fd[c])),
datetime=datetime_formatted
))
))
doc.add_root(fig)
doc.add_periodic_callback(update, 60*1000)
doc.add_periodic_callback(update, 60 * 1000)
def press_doc(doc, cryo_id, delta_hour=24):
"""Plot recent fridge pressures"""
......@@ -277,14 +279,14 @@ def press_doc(doc, cryo_id, delta_hour=24):
# Create plot
# Keys and labels [2] and [3] are pressures
sources, fig = plot(cryo_id, data, key_and_labels[2], key_and_labels[3],
save_html=False)
save_html=False)
# Close connection to database
fridge_watch_db.session.commit()
fridge_watch_db.session.close()
def update():
last_time = datetime.datetime.utcfromtimestamp(sources[0].data['x'][-1]/1000)
#last_time = np_to_datetime(sources[0].data['x'][-1])
last_time = datetime.datetime.utcfromtimestamp(sources[0].data['x'][-1] / 1000)
# last_time = np_to_datetime(sources[0].data['x'][-1])
fd, key_and_labels = load_data(cryo_id,
since_time=last_time)
fridge_watch_db.session.commit()
......@@ -296,15 +298,14 @@ def press_doc(doc, cryo_id, delta_hour=24):
y=fd[c],
series_name=tile(name, len(fd[c])),
datetime=datetime_formatted
))
))
doc.add_root(fig)
doc.add_periodic_callback(update, 60*1000)
doc.add_periodic_callback(update, 60 * 1000)
@app.route('/cryostat')
def cryostat_dashboard():
# Query fridge parameters (temperatures, pressures, etc...)
cryo_state = {}
for c in cryolist:
......@@ -326,13 +327,13 @@ def water(cryo_id, since_hours=24):
# Load data
since_time = datetime.datetime.now() - datetime.timedelta(hours=since_hours)
data = load_water_single(cryo_id, since_time)
fridge_watch_db.session.close()
fridge_watch_db.session.close()
data_win = []
data_wout = []
for t, w_in, w_out in zip(data['Time'], data['Water In'], data['Water Out']):
data_win.append({'x':int(t.timestamp()*1000), 'y':w_in})
data_wout.append({'x':int(t.timestamp()*1000), 'y':w_out})
data_win.append({'x': int(t.timestamp() * 1000), 'y': w_in})
data_wout.append({'x': int(t.timestamp() * 1000), 'y': w_out})
data['Time'] = [x.strftime('%d.%m %H:%M') for x in data['Time']]
return render_template("cryostat_water_temperatures.html",
......@@ -341,7 +342,8 @@ def water(cryo_id, since_hours=24):
data_wout=data_wout,
cryostats=cryolist,
lab_list=lablist,
cryo_id=cryo_id)
cryo_id=cryo_id)
# Operating hours
@app.route('/cryostat/runtimes/<string:cryo_id>', methods=['GET'])
......@@ -350,8 +352,8 @@ def cryostat_runtimes(cryo_id=cryolist[0]):
runtimes = {}
op_times = {}
# Count operation hours in year/month
times = OperationTimes.query.filter_by(name=cryo_id)\
.order_by(OperationTimes.time.desc())
times = OperationTimes.query.filter_by(name=cryo_id) \
.order_by(OperationTimes.time.desc())
pt_times = times.filter_by(pulsetube=True)
tp_times = times.filter_by(turbopump=True)
fp_times = times.filter_by(forepump=True)
......@@ -367,9 +369,10 @@ def cryostat_runtimes(cryo_id=cryolist[0]):
for ((year, month), items) in groupby(pt_times, grouper):
runtimes['PT_months_count'][year][month] = len(list(items))
# Order by month names
months=list(calendar.month_name)
nd = OrderedDict(sorted(runtimes['PT_months_count'][2019].items(), key=lambda t: months.index(t[0])))
op_times['pt_counts'] = list(nd.values()) # PulseTube
months = list(calendar.month_name)
nd = OrderedDict(
sorted(runtimes['PT_months_count'][2019].items(), key=lambda t: months.index(t[0])))
op_times['pt_counts'] = list(nd.values()) # PulseTube
op_times['pt_months'] = list(nd.keys())
# Turbo Pump
......@@ -381,8 +384,9 @@ def cryostat_runtimes(cryo_id=cryolist[0]):
# Sum for months
for ((year, month), items) in groupby(tp_times, grouper):
runtimes['TP_months_count'][year][month] = len(list(items))
nd = OrderedDict(sorted(runtimes['TP_months_count'][2019].items(), key=lambda t: months.index(t[0])))
op_times['tp_counts'] = list(nd.values()) # Turbo Pump
nd = OrderedDict(
sorted(runtimes['TP_months_count'][2019].items(), key=lambda t: months.index(t[0])))
op_times['tp_counts'] = list(nd.values()) # Turbo Pump
op_times['tp_months'] = list(nd.keys())
# Fore Pump
......@@ -394,8 +398,9 @@ def cryostat_runtimes(cryo_id=cryolist[0]):
# Sum for months
for ((year, month), items) in groupby(fp_times, grouper):
runtimes['FP_months_count'][year][month] = len(list(items))
nd = OrderedDict(sorted(runtimes['FP_months_count'][2019].items(), key=lambda t: months.index(t[0])))
op_times['fp_counts'] = list(nd.values()) # Forepup
nd = OrderedDict(
sorted(runtimes['FP_months_count'][2019].items(), key=lambda t: months.index(t[0])))
op_times['fp_counts'] = list(nd.values()) # Forepup
op_times['fp_months'] = list(nd.keys())
# Compressor
......@@ -407,47 +412,50 @@ def cryostat_runtimes(cryo_id=cryolist[0]):
# Sum for months
for ((year, month), items) in groupby(cp_times, grouper):
runtimes['CP_months_count'][year][month] = len(list(items))
nd = OrderedDict(sorted(runtimes['CP_months_count'][2019].items(), key=lambda t: months.index(t[0])))
op_times['cp_counts'] = list(nd.values()) # Compressor
nd = OrderedDict(
sorted(runtimes['CP_months_count'][2019].items(), key=lambda t: months.index(t[0])))
op_times['cp_counts'] = list(nd.values()) # Compressor
op_times['cp_months'] = list(nd.keys())
# Close db
fridge_watch_db.session.close()
fridge_watch_db.session.close()
return render_template("cryostat_runtimes.html",
op_times=op_times,
cryostats=cryolist,
lab_list=lablist,
cryo_id=cryo_id)
cryo_id=cryo_id)
# Lab
@app.route('/labs/<string:lab_id>', methods=['GET'])
@app.route('/labs/<string:lab_id>:<int:since_hours>', methods=['GET'])
def lab(lab_id, since_hours=24*30):
def lab(lab_id, since_hours=24 * 30):
"""Plot lab logs"""
# Load data
since_time = datetime.datetime.now() - datetime.timedelta(hours=since_hours)
data = load_lab(lab_id, since_time)
fridge_watch_db.session.close()
fridge_watch_db.session.close()
T_pumproom = []
H_pumproom = []
for t, T, H in zip(data['Temperatures']['time'], data['Temperatures']['T_PumpRoom'],
data['Humidities']['H_PumpRoom']):
T_pumproom.append({'x':int(t.timestamp()*1000), 'y':T})
H_pumproom.append({'x':int(t.timestamp()*1000), 'y':H})
data['Humidities']['H_PumpRoom']):
T_pumproom.append({'x': int(t.timestamp() * 1000), 'y': T})
H_pumproom.append({'x': int(t.timestamp() * 1000), 'y': H})
return render_template("lab.html",
temperatures=T_pumproom,
humidities=H_pumproom,
lab_list=lablist,
lab_id=lab_id