Skip to content

Commit 940cc3b

Browse files
committed
scratch
;
1 parent 473e901 commit 940cc3b

File tree

2 files changed

+137
-0
lines changed

2 files changed

+137
-0
lines changed

scratch/jlashner/tickle_sweep.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
2+
def tickle_sweep(S, cfg, freqs):
3+
4+
5+
for f
6+
7+

scratch/jlashner/tracking_check.py

+130
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
import matplotlib
2+
matplotlib.use('Agg')
3+
import matplotlib.pyplot as plt
4+
5+
import argparse
6+
import numpy as np
7+
from sodetlib.det_config import DetConfig
8+
from sodetlib.util import cprint, make_filename, get_tracking_kwargs
9+
from pysmurf.client.util.pub import set_action
10+
11+
12+
@set_action()
13+
def get_tracking_goodness(S, cfg, band, tracking_kwargs=None,
14+
make_channel_plots=False, r_thresh=0.9):
15+
"""
16+
Runs tracking setup and returns how good at tracking each channel is
17+
18+
Args
19+
-----
20+
S : SmurfControl
21+
Pysmurf control object
22+
cfg : DetConfig
23+
Detconfig object
24+
band : int
25+
band number
26+
tracking_kwargs : dict
27+
Dictionary of additional custom args to pass to tracking setup
28+
r_thresh : float
29+
Threshold used to set color on plots
30+
Returns
31+
--------
32+
rs : np.ndarray
33+
Array of size (512) containing values between 0 and 1 which tells
34+
you how good a channel is at tracking. If close to 1, the channel
35+
is tracking well and if close to 0 the channel is tracking poorly
36+
f : np.ndarray
37+
f as returned from tracking setup
38+
df : np.ndarray
39+
df as returned by tracking setup
40+
"""
41+
band_cfg = cfg.dev.bands[band]
42+
tk = get_tracking_kwargs(S, cfg, band, kwargs=tracking_kwargs)
43+
tk['nsamp'] = 2**20 # moreee data
44+
tk['show_plot'] = False # Override
45+
46+
f, df, sync = S.tracking_setup(band, **tk)
47+
si = S.make_sync_flag(sync)
48+
nphi0 = int(round(band_cfg['lms_freq_hz'] / S.get_flux_ramp_freq()/1000))
49+
50+
active_chans = np.zeros_like(f[0], dtype=bool)
51+
active_chans[S.which_on(band)] = True
52+
53+
# Average cycles to get single period estimate
54+
seg_size = (si[1] - si[0]) // nphi0
55+
fstack = np.zeros((seg_size, len(f[0])))
56+
nstacks = (len(si)-1) * nphi0
57+
for i in range(len(si) - 1):
58+
s = si[i]
59+
for j in range(nphi0):
60+
a = s + seg_size * j
61+
fstack += f[a:a + seg_size, :]
62+
fstack /= nstacks
63+
64+
# calculates quality of estimate wrt real data
65+
y_real = f[si[0]:si[-1], :]
66+
# Averaged cycle repeated nstack times
67+
y_est = np.vstack([fstack for _ in range(nstacks)])
68+
sstot = np.sum((y_real - np.mean(y_real, axis=0))**2, axis=0)
69+
ssres = np.sum((y_real - y_est)**2, axis=0)
70+
71+
r = 1 - ssres/sstot
72+
# Probably means it's a bugged debug channels.
73+
r[np.isnan(r) & active_chans] = 1
74+
75+
fname = make_filename(S, 'tracking_goodness.png', plot=True)
76+
fig, ax = plt.subplots()
77+
ax.hist(r[active_chans], bins=30)
78+
ax.axvline(r_thresh, linestyle=':', alpha=0.8)
79+
text_props = {
80+
'transform': ax.transAxes, 'fontsize': 11, 'verticalalignment': 'top',
81+
'bbox': {'facecolor': 'white'}
82+
}
83+
props = {'facecolor': 'white'}
84+
num_good = np.sum(r > r_thresh)
85+
num_active = np.sum(active_chans)
86+
s = f"{num_good}/{num_active} Channels above r={r_thresh}"
87+
ax.text(0.05, 0.95, s, **text_props)
88+
ax.set(xlabel="Tracking Quality", ylabel="Num Channels",
89+
title=f"Band {b} Tracking Quality")
90+
plt.savefig(fname)
91+
S.pub.register_file(fname, 'tracking_goodness', plot=True)
92+
93+
if make_channel_plots:
94+
print("Making channel plots....")
95+
nramps = 2
96+
xs = np.arange(len(f))
97+
m = (si[1] - 20 < xs) & (xs < si[1 + nramps] + 20)
98+
for chan in S.which_on(band):
99+
fig, ax = plt.subplots()
100+
c = 'C1' if r[chan] > 0.85 else 'black'
101+
ax.plot(xs[m], f[m, chan], color=c)
102+
props = {'facecolor': 'white'}
103+
ax.text(0.05, 0.95, f"r={r[chan]:.3f}", transform=ax.transAxes,
104+
fontsize=15, verticalalignment="top", bbox=props)
105+
ax.set_title(f"Band {b} Channel {chan}")
106+
fname = make_filename(S, f"tracking_b{b}_c{chan}.png", plot=True)
107+
fig.savefig(fname)
108+
plt.close(fig)
109+
110+
return r, f, df, sync
111+
112+
113+
if __name__ == '__main__':
114+
cfg = DetConfig()
115+
parser = argparse.ArgumentParser()
116+
parser.add_argument('--bands', '-b', type=int, nargs='+', required=True)
117+
parser.add_argument('--threshold', '-t', type=float, default=0.9)
118+
parser.add_argument('--plots', '-p', action='store_true')
119+
args = cfg.parse_args(parser)
120+
S = cfg.get_smurf_control(dump_configs=True)
121+
122+
for b in args.bands:
123+
rs, f, df, sync = get_tracking_goodness(S, cfg, b,
124+
make_channel_plots=args.plots,
125+
r_thresh=args.threshold)
126+
nchans = len(S.which_on(b))
127+
good_chans = np.where(rs > args.threshold)[0]
128+
cprint(f"{len(good_chans)} / {nchans} have passed on band {b}",
129+
True)
130+
cprint(f"Good chans:\n{good_chans}", True)

0 commit comments

Comments
 (0)