Skip to content

Commit 42b4536

Browse files
committed
Added working dummy enviroment and plotting
1 parent 508f8d8 commit 42b4536

File tree

7 files changed

+257
-14
lines changed

7 files changed

+257
-14
lines changed

Playground/mock_device.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,11 @@ class scale_for_device():
2222
def __init__(self,origin,dir):
2323
self.origin = origin
2424
self.dir = dir
25-
def __call__(self,params):
26-
return (params - self.origin)*self.dir
25+
def __call__(self,params,bc=False):
26+
if bc:
27+
return (params - self.origin[np.newaxis,:])*self.dir[np.newaxis,:]
28+
else:
29+
return (params - self.origin)*self.dir
2730

2831
class Device():
2932
def __init__(self,shapes_list,ndim,origin=None,dir=None):
@@ -38,11 +41,20 @@ def __init__(self,shapes_list,ndim,origin=None,dir=None):
3841
self.shapes_list = shapes_list
3942

4043
def jump(self, params):
41-
self.params = np.array(params).squeeze()
44+
self.params = np.array(params)[np.newaxis,:]
4245
return params
4346

4447
def measure(self):
4548
return float(np.any([shape(self.sd(self.params)) for shape in self.shapes_list]))
4649

4750
def check(self,idx=None):
48-
return self.params if idx is None else self.params[idx]
51+
return self.params.squeeze() if idx is None else self.params.squeeze()[idx]
52+
53+
def arr_measure(self,params):
54+
shape_logical = [shape(params) for shape in self.shapes_list]
55+
56+
shape_logical = np.array(shape_logical)
57+
58+
return np.any(shape_logical,axis=0)
59+
60+

Playground/shapes.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def __init__(self, ndim, a=-1000, b=0):
4040

4141
def __call__(self, x):
4242
x = np.array(x)
43-
inside = np.logical_and(np.all(x > self.lb, axis=-1), np.all(x < self.ub, axis=-1))
43+
inside = np.logical_and(np.all(x > self.lb[np.newaxis,:], axis=-1), np.all(x < self.ub[np.newaxis,:], axis=-1))
4444
return inside
4545

4646
class Leakage(object):
@@ -49,9 +49,9 @@ def __init__(self, ndim, th_leak=-500, idx=0):
4949
self.leak_gate = idx
5050
def __call__(self, x):
5151
x = np.array(x)
52-
leak = x[self.leak_gate] > self.th_leak
52+
leak = x[:,self.leak_gate] > self.th_leak
5353
return leak
54-
54+
#change
5555
class Convexhull(object):
5656
def __init__(self, ndim, points=[-1000,0,[-1000,0],[0,-1000]]):
5757
# points: 2D array (num_points x ndim)

main_utils/model_surf_utils.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
"""
4+
Created on Mon Mar 23 13:17:50 2020
5+
6+
@author: oxml
7+
"""
8+
9+
from . import utils
10+
import matplotlib.pyplot as plt
11+
12+
def show_dummy_device(device,configs,save=True):
13+
conf_g = configs['general']
14+
print("Plotting dummy enviroment")
15+
dev_vol = utils.extract_volume_from_mock_device(conf_g['lb_box'],conf_g['ub_box'],100,device)
16+
ax = utils.plot_volume(dev_vol,conf_g['lb_box'],conf_g['ub_box'],conf_g['ub_box'],100)
17+
18+
if save: utils.rotate_save(ax,configs['save_dir']+'dummy_surf/')
19+
plt.show()
20+
21+
22+
23+
def show_gpr_gpc(gpr,configs,points,condidx,origin,gpc=None,save=True):
24+
conf_g = configs['general']
25+
print("Plotting gpr")
26+
gpr_vol = utils.extract_volume_from_gpr(conf_g['lb_box'],conf_g['ub_box'],100,gpr)
27+
ax = utils.plot_volume(gpr_vol,conf_g['lb_box'],conf_g['ub_box'],origin,100,cmap_func=gpc)
28+
29+
ax = utils.plot_3d_scatter(points,condidx=condidx,ax=ax)
30+
31+
if save: utils.rotate_save(ax,configs['save_dir']+'gpr_surf/')
32+
plt.show()
33+
34+

main_utils/utils.py

Lines changed: 110 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@
99
import time
1010
import numpy as np
1111
import matplotlib.pyplot as plt
12+
from skimage import measure
13+
from pathlib import Path
14+
import imageio
1215

1316

14-
15-
def plot_conditional_idx_improvment(cond_idx,cond_count=2):
17+
def plot_conditional_idx_improvment(cond_idx, config,cond_count=2,save=True):
1618

1719
found = (np.array(cond_idx)>=cond_count).astype(np.float)
1820

@@ -21,10 +23,116 @@ def plot_conditional_idx_improvment(cond_idx,cond_count=2):
2123
count[i] = np.average(found[:i])
2224

2325
plt.plot(count)
26+
plt.xlabel("Iteration")
27+
plt.ylabel("Empirical probability of conditional idx reaching %i"%cond_count)
28+
29+
if save: plt.savefig(config['save_dir']+'improvment.png')
30+
2431
plt.show()
2532

2633

2734

35+
def extract_volume_from_gpr(lb,ub,res,gpr):
36+
37+
38+
axes_linspace = [np.linspace(ub[i],lb[i],res) for i in range(len(lb))]
39+
40+
X = np.array(np.meshgrid(*axes_linspace)).reshape([3,-1])
41+
X = np.swapaxes(X,0,1)
42+
X_r = np.linalg.norm(X,axis=1)[...,np.newaxis]
43+
U = X/X_r
44+
45+
r_est , sig = gpr.predict(U)
46+
Y = X_r<=r_est
47+
48+
Y = Y.reshape([res]*len(axes_linspace))
49+
50+
return Y
51+
52+
53+
def extract_volume_from_mock_device(lb,ub,res,device):
54+
55+
56+
axes_linspace = [np.linspace(ub[i],lb[i],res) for i in range(len(lb))]
57+
58+
X = np.array(np.meshgrid(*axes_linspace)).reshape([len(lb),-1])
59+
X = np.swapaxes(X,0,1)
60+
Y = device.arr_measure(X)
61+
Y = Y.reshape([res]*len(axes_linspace))
62+
63+
return Y
64+
65+
66+
def plot_volume(vols,plot_lb,plot_ub,vol_origin,res,cmap_func=None,cmap='winter',perm=[0,1,2],ax=None):
67+
verts, faces, normals, values = measure.marching_cubes_lewiner(vols,0)
68+
69+
vol_origin = np.array(vol_origin)
70+
vol_origin[[0,1,2]]=vol_origin[[1,0,2]]
71+
verts = (((verts)/res)*-2000)+vol_origin
72+
73+
points_surf = verts[faces[:,0],:]
74+
points_surf[:,[0,1,2]] = points_surf[:,[1,0,2]]
75+
76+
77+
#preds = sampler.gpc.predict_comb_prob(points_surf)
78+
preds = cmap_func(points_surf) if cmap_func is not None else np.array([0.5]*points_surf.shape[0])
79+
cmap = plt.get_cmap(cmap)
80+
c_preds = cmap(preds).squeeze()
81+
if ax is None:
82+
fig = plt.figure(figsize=(10, 10))
83+
ax = fig.add_subplot(111, projection='3d')
84+
85+
ax.view_init(azim=0, elev=15)
86+
87+
88+
#if points is not None: ax.scatter(*points,c=condidx,zorder=1)
89+
90+
surf = ax.plot_trisurf(verts[:, perm[0]], verts[:, perm[1]], faces, verts[:, perm[2]],
91+
lw=0.1,edgecolor="black",alpha=0.5,vmin=0,vmax=1.)
92+
surf.set_facecolor(c_preds.tolist())
93+
94+
ax.set_xlim([plot_ub[0],plot_lb[0]])
95+
ax.set_ylim([plot_ub[1],plot_lb[1]])
96+
ax.set_zlim([plot_ub[2],plot_lb[2]])
97+
98+
ax.set_ylabel("Gate 1 / mV")
99+
ax.set_xlabel("Gate 2 / mV")
100+
ax.set_zlabel("Gate 3 / mV")
101+
return ax
102+
103+
def plot_3d_scatter(points,condidx=None,condidx_max=3,cmap='plasma',ax=None):
104+
points=np.array(points)
105+
points[:,[0,1,2]] = points[:,[1,0,2]]
106+
107+
if ax is None:
108+
fig = plt.figure(figsize=(10, 10))
109+
ax = fig.add_subplot(111, projection='3d')
110+
111+
ax.view_init(azim=0, elev=15)
112+
113+
if condidx is not None:
114+
ax.scatter(*points.T,c=condidx)
115+
else:
116+
ax.scatter(*points.T)
117+
118+
return ax
119+
120+
def rotate_save(ax,path,step=9):
121+
122+
Path(path).mkdir(parents=True,exist_ok=True)
123+
124+
fnames = []
125+
for i in range(0,360,step):
126+
127+
ax.view_init(azim=i, elev=15)
128+
fnames += [path+'/%i.png'%i]
129+
plt.savefig(fnames[-1])
130+
131+
images = []
132+
for fname in fnames:
133+
images.append(imageio.imread(fname))
134+
imageio.mimsave(path+'/movie.gif', images)
135+
28136

29137

30138

mock_device_demo_config.json

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
{
2+
"playground":{
3+
"shapes":{
4+
"Crosstalk_box":{},
5+
"Leakage":{}},
6+
"ndim":3},
7+
8+
"plunger_gates": [1,2],
9+
"save_dir":"dummy_test/",
10+
"plot":true,
11+
12+
"pause":0.2,
13+
14+
"investigation":{
15+
"measurement_seq":["diag_trace","2d_lowres","2d_highres"],
16+
"cond_meas": [false,{ "quantile" : 0.85, "min_thresh" : 0.001 }, false],
17+
"diag_trace":{
18+
"func":"mock_measurement",
19+
"condition":"mock_peak_check",
20+
"a":[0,0],
21+
"b":[-1000,-1000],
22+
"verbose":true},
23+
"2d_lowres":{
24+
"func":"mock_measurement",
25+
"condition":"mock_score_func",
26+
"target":[-500,-250]},
27+
"2d_highres":{
28+
"func":"mock_measurement",
29+
"condition":"check_nothing"}},
30+
31+
"detector": {
32+
"d_r": 20,
33+
"len_after_poff": 300,
34+
"th_high": 0.2,
35+
"th_low": 0.01},
36+
37+
"general": {
38+
"directions": [-1.0, -1.0, -1.0],
39+
"lb_box": [-2000, -2000, -2000],
40+
"bound": [-2000, -2000, -2000],
41+
"num_samples": 50,
42+
"origin": [0,0,0],
43+
"ub_box": [0, 0, 0]},
44+
45+
"gpc": {
46+
"gpc_start": 10,
47+
"gpc_on": true,
48+
"gpc_list": [true,true,false],
49+
"configs": {
50+
"length_prior_mean": 500.0,
51+
"length_prior_var": 100.0,
52+
"var_prior_mean": 50.0,
53+
"var_prior_var": 20.0,
54+
"kernal": "Matern52"}
55+
},
56+
57+
"gpr": {
58+
"restarts": 5,
59+
"factor_std": 2.0,
60+
"gpr_start": 10,
61+
"gpr_on": true,
62+
"length_prior_mean":0.4,
63+
"length_prior_var" : 0.1,
64+
"r_min": 0.0,
65+
"var_prior_mean_divisor": 4.0,
66+
"kernal": "Matern52"},
67+
68+
"pruning": {
69+
"pruning_stop": 30,
70+
"pruning_on": true,
71+
"step_back": 100},
72+
73+
"sampling": {
74+
"max_steps": 100000,
75+
"n_part": 200,
76+
"sigma": 25},
77+
78+
"track": ["origin", "bound", "directions", "samples", "extra_measure", "d_vec","poff_vec", "meas_each_axis", "vols_each_axis", "conditional_idx","vols_pinchoff","detected","r_vals"],
79+
"verbose": ["conditional_idx","vols_pinchoff","detected","r_vals"]
80+
}
81+
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
{
22
"path_to_pygor":"/home/mlserv/Scripts",
3-
"gates":["c10","c3","c4","c5","c6","c7","c9"],
3+
"gates":["c3","c4","c5","c6","c7","c9","c10"],
44
"plunger_gates":["c5","c9"],
55
"bias_chans":["c1"],
66
"bias_vals":[20],
77
"chan_no":0,
8-
"save_dir":"dom_b2_t4_test_20200129/",
8+
"save_dir":"dom_b2_t4_sebtune_23032020/",
99

1010
"investigation":{
1111
"measurement_seq":["diag_trace","2d_lowres","2d_highres"],
@@ -54,7 +54,7 @@
5454
"lb_box": [-2000, -2000, -2000, -2000, -2000,-2000, -2000],
5555
"bound": [-2000, -2000, -2000, -2000, -2000,-2000, -2000],
5656
"num_samples": 500,
57-
"origin": [-100,-500,-100,-100,-100,-100,-100],
57+
"origin": [-500,-100,-100,-100,-100,-100,-100],
5858
"ub_box": [0, 0, 0, 0, 0, 0, 0]},
5959

6060
"gpc": {

tune.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from .Sampler_factory import Paper_sampler
1010
from .Investigation.Investigation_factory import Investigation_stage
1111
from .main_utils.utils import Timer, plot_conditional_idx_improvment
12+
from .main_utils.model_surf_utils import show_gpr_gpc, show_dummy_device
1213
from .Playground.mock_device import build_mock_device_with_json
1314

1415

@@ -53,7 +54,7 @@ def jump(params,plungers=False):
5354
labels = plunger_gates
5455
else:
5556
labels = gates
56-
pygor.setvals(labels,params)
57+
pygor.setvals(labels,params[np.newaxis,:])
5758
return params
5859
def measure():
5960
cvl = pygor.do0d()[chan_no][0]
@@ -81,6 +82,8 @@ def tune_with_playground_from_file(config_file):
8182

8283
device = build_mock_device_with_json(configs['playground'])
8384

85+
if configs.get('plot',False): show_dummy_device(device,configs)
86+
8487
plunger_gates = configs['plunger_gates']
8588

8689

@@ -100,7 +103,12 @@ def jump(params,inv=False):
100103

101104
results,sampler = tune(jump,measure,investigation_stage,configs)
102105

103-
plot_conditional_idx_improvment(results['conditional_idx'])
106+
fields = ['vols_pinchoff','conditional_idx','origin']
107+
108+
if configs.get('plot',False):
109+
show_gpr_gpc(sampler.gpr, configs, *sampler.t.get(*fields), gpc=sampler.gpc.predict_comb_prob)
110+
plot_conditional_idx_improvment(sampler.t['conditional_idx'],configs)
111+
104112
return results,sampler
105113

106114

0 commit comments

Comments
 (0)