from ipywidgets import interactive, interact, interact_manual
from IPython.display import display
from IPython.display import HTML
import ipywidgets as widgets
import numpy as np
import matplotlib.pyplot as plt
import Scripts.DataManager as dm
class ConfigItemChanger:
def __init__ (self, key, device):
self.key = key
self.value = device.config[key]
self.device = device
self.config = device.config
layout_bt = widgets.Layout(width = '20px')
layout_text = widgets.Layout(width = '180px')
if type(self.value) == bool:
self.cb = widgets.Checkbox(value=self.value,
description=key, layout = layout_text)
self.cb.observe(self.change_bool, names = 'value')
self.widget =self.cb
elif type(self.value) == str:
self.text = widgets.Text(value = self.value, describtion = key)
self.text.on_submit(self.change_str)
self.widget = self.text
elif np.dtype(type(self.value)) == np.dtype('float64'):
self.flt = widgets.Text(value=str(np.round(self.value,4)),description=key, layout = layout_text)
self.step = widgets.FloatText(value=0.1,description='step', layout = layout_text, style = {'description_width': 'initial'})
self.bp = widgets.Button(description='+', layout = layout_bt )
self.bm = widgets.Button(description='-', layout = layout_bt)
self.flt.on_submit(self.change_by_enter_float)
self.bp.on_click(self.change_p_float)
self.bm.on_click(self.change_m_float)
self.widget = widgets.HBox([self.flt, self.step, self.bm, self.bp])
elif np.dtype(type(self.value)) == np.dtype('int64') or np.dtype(type(self.value)) == np.dtype('int32'):
self.flt = widgets.Text(value=str(np.round(self.value,4)),description=key, layout = layout_text)
self.bp = widgets.Button(description='+1', layout = layout_bt)
self.bm = widgets.Button(description='-1', layout = layout_bt)
self.flt.on_submit(self.change_by_enter_int)
self.bp.on_click(self.change_p_int)
self.bm.on_click(self.change_m_int)
self.widget = widgets.HBox([self.flt, self.bm, self.bp])
else:
self.widget = widgets.HTML(key+ ' (type '+str(np.dtype(type(self.value)))+') not changeable')
def change_str(self,text):
self.config[self.key] = self.text.value
self.device.config = self.config
def change_bool(self, new):
self.config[self.key] = new['new']
self.device.config = self.config
def change_by_enter_float(self, text):
self.config[self.key] = float(self.flt.value)
self.device.config = self.config
def change_by_enter_int(self, text):
self.config[self.key] = int(self.flt.value)
self.device.config = self.config
def change_p_float(self, bt):
self.config[self.key] = float(self.flt.value) + self.step.value
self.flt.value = str(np.round(float(self.flt.value) + self.step.value,4))
self.device.config = self.config
def change_p_int(self, bt):
self.config[self.key] = int(self.flt.value) + 1
self.flt.value = str(int(self.flt.value) + 1)
self.device.config = self.config
def change_m_int(self, bt):
self.config[self.key] = int(self.flt.value) - 1
self.flt.value = str(int(self.flt.value) - 1)
self.device.config = self.config
def change_m_float(self, bt):
self.config[self.key] = float(self.flt.value) - self.step.value
self.flt.value = str(np.round(float(self.flt.value) - self.step.value,4))
self.device.config = self.config
class DeviceInterface:
def __init__(self, device_name, device_pool):
self.device_name = device_name
self.device_pool = device_pool
self.device = self.device_pool[device_name]
self.make_widget()
def make_widget(self):
self.subwidgets = [widgets.HTML(' Configuration: ')]
self.subwidgets += [ConfigItemChanger(key, self.device).widget for key in self.device.config.keys()]
box_layout = widgets.Layout(display='flex',
flex_flow='column',
border='solid', width = '420px')
self.config_setter = widgets.VBox(self.subwidgets, layout = box_layout)
self.switch_style = {True: 'success', False: 'danger'}
value_connected = self.device.connected
self.bt_connect = widgets.ToggleButton(value=value_connected,
description='Connect',
disabled=value_connected,
button_style=self.switch_style[value_connected],
tooltip='Description')
self.bt_connect.observe(self.connect_device, names = 'value')
self.conmeas = [self.bt_connect]
if self.device.measureable:
value_make_measurement = self.device.make_measurement
self.bt_make_measurement = widgets.ToggleButton(value=value_make_measurement,
description='Measure',
disabled=False,
button_style=self.switch_style[value_make_measurement],
tooltip='Description')
self.bt_make_measurement.observe(self.measure_device, names = 'value')
self.conmeas += [self.bt_make_measurement]
if self.device.plotable:
value_make_plot = self.device.make_plot
self.bt_make_plot = widgets.ToggleButton(value=value_make_measurement,
description='Plot',
disabled=False,
button_style=self.switch_style[value_make_plot],
tooltip='Description')
self.bt_make_plot.observe(self.plot_device, names = 'value')
self.conmeas += [self.bt_make_plot]
self.spec_func_bts = []
for spec_func in self.device.spec_funcs:
self.spec_func_bts += [widgets.Button(description=spec_func[5:])]
self.spec_func_bts[-1].on_click(self.spec_func_run)
self.widget = widgets.HBox([widgets.VBox(self.conmeas+self.spec_func_bts), self.config_setter])
def spec_func_run(self, bt):
spec_func_name = 'spec_'+bt.description
if self.device.connected:
getattr(self.device.obj, spec_func_name)()
self.refresh()
def connect_device(self, bt = None):
self.device_pool.connect(self.device_name)
self.bt_connect.button_style = 'success'
self.bt_connect.disabled = True
def refresh(self):
self.subwidgets = [widgets.HTML(' Configuration: ')]
self.subwidgets += [ConfigItemChanger(key, self.device).widget for key in self.device.config.keys()]
self.config_setter.children = self.subwidgets
def measure_device(self, bt = None):
self.device.make_measurement = self.bt_make_measurement.value
self.bt_make_measurement.button_style = self.switch_style[self.bt_make_measurement.value]
self.device.make_plot = self.bt_make_plot.value & self.bt_make_measurement.value
self.bt_make_plot.value = self.bt_make_plot.value & self.bt_make_measurement.value
self.bt_make_plot.button_style = self.switch_style[self.bt_make_plot.value & self.bt_make_measurement.value]
self.bt_make_plot.disabled = not self.bt_make_measurement.value
def plot_device(self, bt = None):
self.device.make_plot = self.bt_make_plot.value
self.bt_make_plot.button_style = self.switch_style[self.bt_make_plot.value]
def show(self):
display(self.widget)
class DevicePoolInterface:
def __init__(self, device_pool):
self.device_pool = device_pool
self.make_widget()
def make_widget(self):
self.device_interfaces = {device_name: DeviceInterface(device_name, self.device_pool) for device_name in self.device_pool.device_names}
self.device_interfaces_widgets = np.array([[name, obj.widget] for name, obj in self.device_interfaces.items()])
self.widget = widgets.Accordion(children = list(self.device_interfaces_widgets[:,1]), _titles= dict(enumerate(self.device_interfaces_widgets[:,0])))
def show(self):
display(self.widget)
def refresh(self, device = None):
if device:
self.device_interfaces[device].refresh()
else:
for device_name in self.device_interfaces.keys():
self.device_interfaces[device_name].refresh()
class ConfigLoader:
def __init__(self, config, device_pool, device_pool_interface = None):
self.config = config
self.device_pool = device_pool
self.device_pool_interface = device_pool_interface
self.make_widget()
def make_widget (self):
self.time_html = widgets.HTML('Time: '+self.config['time']+'')
self.load_device_wd = [self.time_html]
if 'devices_connected' in self.config:
self.load_device_wd += [widgets.HTML('devices that where connected:'),
widgets.HTML(''+str(self.config['devices_connected'])+'')]
for device in self.device_pool.device_names:
if device in self.config.keys():
dv_load_bt = widgets.ToggleButton(value=False,
description=device,
disabled=False,
button_style='danger',
tooltip='Description')
dv_load_bt.observe(self.load_device, names = 'value')
dv_config = widgets.HTML( dm.html_dict(self.config[device]))
self.load_device_wd += [dv_load_bt, dv_config]
self.widget = widgets.VBox(self.load_device_wd)
def load_device(self, button):
self.device_pool[button['owner'].description].config = self.config[button['owner'].description]
if type (self.device_pool_interface) != None:
self.device_pool_interface.refresh(button['owner'].description)
button['owner'].button_style = 'success'
button['owner'].disabled = True
class IoInterface:
def __init__(self, io, device_pool, device_pool_interface = None):
self.io = io
self.device_pool = device_pool
self.device_pool_interface = device_pool_interface
self.make_widget()
def make_widget(self):
heading = widgets.HTML('io interface')
self.text_path = widgets.Text(description = 'io folder: ',value = self.io.path)
self.text_path.on_submit(self.change_path)
# save configurations
self.config_saver = [widgets.HTML('save configuration of devices')]
self.text_comment = widgets.Text(description= 'Comment:')
self.check_elog = widgets.Checkbox(value=False,
description='elog')
self.bt_save = widgets.Button(description= 'save')
self.bt_save.on_click(self.save)
self.ht_save = widgets.HTML('')
self.config_saver += [self.text_comment, widgets.HBox([self.bt_save,self.check_elog]), self.ht_save]
box_layout = widgets.Layout(display='flex',
flex_flow='column',
border='solid', width = '340px')
# load configurations
self.config_loader = [widgets.HTML('load configuration of devices')]
self.select_config = widgets.Select(description='comment:', options = self.get_all())
self.config_loader_hb = widgets.HBox([])
self.config_loader += [self.select_config,self.config_loader_hb]
self.select_config.observe(self.select_config_changed, 'value')
self.select_config_changed()
#combine
self.saveload = widgets.Accordion([widgets.VBox(self.config_saver, layout = box_layout),
widgets.VBox(self.config_loader, layout = box_layout)], _titles = {0: 'save configuration of devices' , 1: 'load configuration of devices'})
self.widget = widgets.VBox([heading, self.text_path, self.saveload])
def select_config_changed(self, sel = None):
if type(self.select_config.value) == int:
num = self.select_config.value
config = self.io.load(num)
self.config_loader_hb.children = [ConfigLoader(config,
self.device_pool,
device_pool_interface = self.device_pool_interface).widget]
def change_path(self, text = None):
self.io.path = self.text_path.value
self.select_config.options = self.get_all()
def save(self, bt):
comment = self.text_comment.value
if comment == '':
self.ht_save.value = 'Enter comment to save config!'
return
config = self.device_pool.config
self.io.save(config, comment = comment, elog = self.check_elog.value)
self.text_comment.value = ''
self.ht_save.value = 'Config saved!'
self.select_config.options = self.get_all()
def show(self):
display(self.widget)
def get_all(self):
configs = self.io.search(output = False)
c = {}
for i in range(len(configs)):
c[configs[i]['comment']] = i
return c
class MeasurementManagerInterface:
def __init__(self, measurement_manager):
self.measurement_manager = measurement_manager
self.device_pool = self.measurement_manager.device_pool
self.plot_configurator = PlotConfigurator(self.measurement_manager)
self.scan_configurator = ScanConfigurator(self.measurement_manager)
self.make_widget()
def make_widget(self):
heading = widgets.HTML('
Measurement Manager Interface')
self.switch_style = {True: 'success', False: 'danger'}
self.save_check = widgets.ToggleButton(value=True,
description='save',
button_style='success',
tooltip='Description')
self.save_check.observe(self.button_checked, 'value')
self.clear_hist_bt = widgets.Button(description = 'clear history')
self.clear_hist_bt.on_click(self.clear_hist)
general = widgets.VBox([heading, widgets.HBox([self.save_check, self.clear_hist_bt])])
self.meas_bt = widgets.Button(description = 'measure')
self.meas_bt.on_click(self.measure)
self.loop_inttext = widgets.IntText(value = 1, description = 'loop')
self.rate_text = widgets.FloatText(value = 3, description = 'rate')
self.loop_bt = widgets.Button(description = 'loop')
self.loop_wg = widgets.VBox([widgets.HBox([self.loop_inttext, self.rate_text]), self.loop_bt])
self.loop_bt.on_click(self.loop)
self.bt_scan = widgets.Button(description = 'scan')
self.bt_scan.on_click(self.scan)
self.widget = widgets.VBox([general,
self.meas_bt, self.loop_wg, self.plot_configurator.widget,
self.scan_configurator.widget, self.bt_scan])
def button_checked(self, bt):
bt['owner'].button_style = self.switch_style[bt['new']]
def show(self):
display(self.widget)
def measure(self,bt = None):
self.measurement_manager.measure(save = self.save_check.value,
plot_config = self.plot_configurator.plot_config)
def loop(self,bt = None):
self.measurement_manager.loop(self.loop_inttext.value,self.rate_text.value, save = self.save_check.value,
plot_config = self.plot_configurator.plot_config)
def scan(self, bt = None):
self.measurement_manager.scan(self.scan_configurator.parameters,
n_loop = self.loop_inttext.value,
rate = self.rate_text.value,
save = self.save_check.value,
plot_config = self.plot_configurator.plot_config)
def clear_hist(self, bt = None):
self.measurement_manager.plot_hist = {}
class PlotConfigurator:
def __init__(self, measurement_manager):
self.measurement_manager = measurement_manager
self.device_pool = self.measurement_manager.device_pool
self.plot_config = {}
self.make_widget()
def make_widget(self):
heading = widgets.HTML('
Plot measurement configuration')
self.bt_plot_config_init = widgets.Button(description='Measure to initialize')
self.bt_plot_config_init.on_click(self.initialize)
self.vb_plot_config = widgets.VBox([self.bt_plot_config_init])
self.widget = widgets.VBox([heading,
self.vb_plot_config])
def initialize(self, bt):
#devices
vbs = []
names = {}
wps = []
plot_meas_check = {}
devices_to_measure = self.device_pool.devices_to_measure
device_names = [device.name for device in devices_to_measure]
measurement = self.measurement_manager.measure()
for device_name in device_names:
self.plot_config[device_name] = {}
wgs = []
for parameter, value in sorted(measurement['measure'][device_name].items()):
wgs += [PlotConfigTool(parameter,
value,
self.plot_config[device_name]).widget]
if device_name in [device.name for device in self.device_pool.plotable_devices]:
wgs += [PlotConfigTool('plot_measure',
0,
self.plot_config[device_name]).widget]
vbs += [widgets.VBox(wgs)]
measure_tab = widgets.Tab(children = vbs, _titles= dict(enumerate(device_names)))
self.vb_plot_config.children = [self.bt_plot_config_init, measure_tab]
class PlotConfigTool:
def __init__ (self, variable_name, value, plot_config):
self.variable_name = variable_name
self.value = value
self.plot_config = plot_config
layout_bt = widgets.Layout(width = '20px')
layout_text = widgets.Layout(width = 'auto')
if np.dtype(type(value)) == np.dtype('float64') or np.dtype(type(value)) == np.dtype('int64') or np.dtype(type(value)) == np.dtype('int32'):
self.plot_config[variable_name] = False
self.cb = widgets.Checkbox(description=variable_name, layout = layout_text)
self.cb.observe(self.change_bool, names = 'value')
self.widget = self.cb
else:
self.widget = widgets.HTML(variable_name+' not history plottalbe ('+str(np.dtype(type(value)))+')')
def change_bool(self, new):
self.plot_config[self.variable_name] = new['new']
class ScanConfigurator:
def __init__(self, measurement_manager):
self.measurement_manager = measurement_manager
self.make_widget()
def make_widget(self):
heading = widgets.HTML('Scanning Tool')
self.dimensions_text = widgets.IntSlider(value=1,
min=0,
max=10,
step=1,
description='Number of Parameters:')
self.dimensions_text.observe(self.set_dimension)
self.scanning_tool_box = widgets.HBox([])
self.set_dimension()
self.widget = widgets.VBox([heading, self.dimensions_text, self.scanning_tool_box])
@property
def parameters(self):
return [pc.parameter for pc in self.parameter_choosers]
def set_dimension(self, dum = None):
self.parameter_choosers = [ParameterChooser('Parameter '+str(i+1),self.measurement_manager) for i in range(self.dimensions_text.value)]
self.scanning_tool_box.children = [pc.widget for pc in self.parameter_choosers]
class ParameterChooser:
def __init__(self, title, measurement_manager):
self.title = title
self.measurement_manager = measurement_manager
self.device_pool = measurement_manager.device_pool
self.device_dict = self.device_pool.devices
self.make_widget()
def make_widget(self):
heading = widgets.HTML(''+self.title+'')
self.select_device = widgets.Select(description = 'device: ',options = self.device_dict)
self.select_device.observe(self.on_value_change_device)
self.select_parameter = widgets.Select(description = 'parameter: ', options = {'no device selected': None})
self.select_parameter.observe(self.on_value_change_parameter)
self.current_value = widgets.HTML(' current value: no parameter choosen ')
self.minv = widgets.FloatText(description='minv:',value = 0)
self.maxv = widgets.FloatText(description='maxv:',value = 0)
self.nsteps = widgets.IntText(description='nsteps:', value = 1)
box_layout = widgets.Layout(display='flex',
flex_flow='column',
border='solid', width = '350px')
self.on_value_change_device()
self.widget = widgets.VBox([heading,
widgets.HBox([self.select_device]),
widgets.HBox([self.select_parameter]),
self.current_value,
self.minv,
self.maxv,
self.nsteps], layout = box_layout)
def on_value_change_device(self, dum= None):
device = self.select_device.value
config = self.device_pool.config
scannable = []
for name, variable in config[device.name].items():
if np.dtype(type(variable)) == np.dtype('float64') or np.dtype(type(variable)) == np.dtype(int):
scannable += [name]
self.select_parameter.options = scannable
self.select_parameter.value = scannable[0]
def on_value_change_parameter(self, dum = None):
parameter = self.select_parameter.value
if parameter == None:
return
try:
device = self.select_device.value
config = device.config
current_value = config[device.name][parameter]
self.current_value.value = ' current value: '+str(current_value)+' '
self.minv.value = current_value
self.maxv.value = current_value
except:
print ('Choose parameter!!!')
@property
def parameter(self):
return [self.select_device.value.name, self.select_parameter.value, self.minv.value, self.maxv.value, self.nsteps.value]
# the rest of the gui still has to be changed to newer version (currently not usable)
class variableset:
def __init__(self, name, devices, configset, measure = False):
self.name = name
self.devices = devices
self.configset = configset
self.measure = measure
self.device_dict = {}
for device in self.devices:
self.device_dict[type(device).__name__] = device
self.make_widget()
def make_widget(self):
self.namehtml = widgets.HTML(''+self.name+'')
self.select_device = widgets.Select(description = 'device: ',options = self.device_dict)
self.select_device.observe(self.on_value_change_device, names = 'value')
self.select_parameter = widgets.Select(description = 'parameter: ', options = {'no device selected': None})
if not self.measure:
self.select_parameter.observe(self.on_value_change_parameter, names = 'value')
self.boundmin = widgets.FloatText(description = 'min: ', value = 0.)
self.boundmax = widgets.FloatText(description = 'max: ', value = 0.)
self.uncertainty = widgets.FloatText(description = 'uncertainty: ', value = 1.)
self.widget = widgets.VBox([widgets.HBox([self.namehtml, self.select_device, self.select_parameter]),
widgets.HBox([self.boundmin, self.boundmax, self.uncertainty])])
self.on_value_change_device()
return
self.on_value_change_device()
self.widget = widgets.HBox([self.namehtml, self.select_device, self.select_parameter])
def on_value_change_device(self, dum= None):
device = self.select_device.value
scannable = []
devices2measure = self.configset.find_devices2measure()
if self.measure:
if device in devices2measure:
measurement = dm.measure(devices2measure)
for item in measurement['measure'][type(device).__name__].items():
if np.dtype(type(item[1])) == np.dtype('float64'):
scannable += [item[0]]
else:
config = dm.get_config([device])
for item in config[type(device).__name__].items():
if np.dtype(type(item[1])) == np.dtype('float64'):
scannable += [item[0]]
self.select_parameter.options = scannable
if len(scannable) > 0:
self.select_parameter.value = scannable[0]
else:
self.select_parameter.value = None
def on_value_change_parameter(self, dum= None):
if self.get_parameter() == None:
return
device = self.select_device.value
config = dm.get_config([device])
self.boundmin.value = config[self.get_device_name()][self.get_parameter()]
self.boundmax.value = self.boundmin.value
def get_device_name(self):
return type(self.select_device.value).__name__
def get_device(self):
return self.select_device.value
def get_parameter(self):
return self.select_parameter.value
def bound(self):
if self.measure:
return [None, None]
return [self.boundmin.value, self.boundmax.value]
class optimizer:
def __init__(self, measureset, configset):
self.measureset = measureset
self.configset = configset
self.devices = measureset.devices
self.io = measureset.io
self.variables_change = []
self.variables_formula = []
self.make_widget()
def make_widget(self):
heading = widgets.HTML(' Optimizer ')
text1 = widgets.HTML(' select variables')
self.num_change = widgets.IntSlider(value=0,
min=0,
max=10,
step=1,
description='vars to change:')
self.num_change.observe(self.set_num_change)
self.VBox1 = widgets.VBox()
self.text2 = widgets.HTML(' make optimizer function')
self.num_formula = widgets.IntSlider(value=0,
min=0,
max=10,
step=1,
description='vars to optimize:')
self.num_formula.observe(self.set_num_formula)
self.VBox2 = widgets.VBox()
self.formula_text = widgets.Text(description='Formula: ', value = '0')
self.est_error = widgets.FloatText(description='estim. Error: ',value = '-1')
box_layout = widgets.Layout(display='flex',
flex_flow='column',
border='solid', width = '100%')
self.go_button = widgets.Button(description = 'Optimize!')
self.go_button.on_click(self.optimize)
self.n_steps = widgets.IntText(description = 'Steps: ', value = 30)
self.file_load = widgets.Text(description = 'load results: ', value = 'None')
self.file_save = widgets.Text(description = 'save results: ', value = 'None')
self.widget = widgets.VBox([heading,
text1,
self.num_change,
self.VBox1,
self.text2,
self.num_formula,
self.VBox2,
widgets.HBox([self.formula_text,self.est_error]),
widgets.HBox([self.n_steps, self.file_load, self.file_save]),
self.go_button], layout = box_layout)
def set_num_change(self, dum = None):
self.variables_change = [variableset('par'+str(i), self.devices, self.configset) for i in range(self.num_change.value)]
self.VBox1.children = [vc.widget for vc in self.variables_change]
def set_num_formula(self, dum = None):
self.variables_formula = [variableset('var'+str(i), self.devices, self.configset, measure = True) for i in range(self.num_formula.value)]
self.VBox2.children = [vc.widget for vc in self.variables_formula]
def update_variables(self):
measurements = self.measureset.measure(delete = False)
for vc in self.variables_change:
exec('global '+vc.name+'; '+vc.name+' = '+str(measurements[0]['config'][vc.get_device_name()][vc.get_parameter()]))
#initalize
for vf in self.variables_formula:
exec('global '+vf.name+'; '+vf.name+' = '+str(measurements[0]['measure'][vf.get_device_name()][vf.get_parameter()]))
if len(measurements) > 1:
for i in range(1, len(measurements)):
exec('global '+vf.name+'; '+vf.name+' += '+str(measurements[i]['measure'][vf.get_device_name()][vf.get_parameter()]))
exec('global '+vf.name+'; '+vf.name+' /= len(measurements)')
def optimize(self, dum = None):
# find inital value
pars0 = []
config0 = dm.get_config(self.devices)
for vc in self.variables_change:
pars0 += [config0[vc.get_device_name()][vc.get_parameter()]]
scaling = np.array([vc.uncertainty.value for vc in self.variables_change])
bounds = np.array([vc.bound() for vc in self.variables_change])
pars0 = np.array(pars0)/scaling
if self.est_error.value > 0:
noise = self.est_error.value
else:
noise = 'gaussian'
def to_optimize(pars):
pars = pars * scaling
#config = dm.get_config(self.devices)
print ('Changing:')
for i,vc in enumerate(self.variables_change):
config = dm.get_config([vc.get_device()])
print (vc.get_device_name()+'/'+vc.get_parameter()+' = '+str(pars[i]))
config[vc.get_device_name()][vc.get_parameter()] = pars[i]
dm.set_config([vc.get_device()], config)
self.update_variables()
to_opt = eval(self.formula_text.value)
return to_opt
scaledbounds = np.transpose(np.transpose(bounds)/scaling)
from skopt import gp_minimize
x0 = None
y0 = None
len_x0 = 0
if self.file_load.value != 'None':
from skopt import load
res0 = load(self.io.path+self.file_load.value+'.pkl')
x0 = res0.x_iters
y0 = res0.func_vals
len_x0 = len(x0)
res = gp_minimize(to_optimize, # the function to minimize
scaledbounds, # the bounds on each dimension of x
n_calls=self.n_steps.value, # the number of evaluations of f
n_random_starts=10, # the number of random initialization points
noise = noise,
acq_optimizer='lbfgs',
x0 = x0,
y0 = y0)
if self.file_save.value != 'None':
from skopt import dump
dump(res, self.io.path+self.file_save.value+'.pkl', store_objective=False)
from skopt.plots import plot_convergence
plt.figure()
plot_convergence(res)
if len(bounds) == 1:
from skopt.acquisition import gaussian_ei
x = np.linspace(scaledbounds[0][0], scaledbounds[0][1], 400).reshape(-1, 1)
x_gp = res.space.transform(x.tolist())
num_models = len(res.models)
times = (num_models)//5
if num_models == 0:
print ('no models made')
return
old_x_iters = res.x_iters[:len_x0]
old_func_vals = res.func_vals[:len_x0]
plt.figure(figsize = (8, 14))
# Plot the 5 iterations following the 5 random points
for n in range(5):
plt.subplot(5, 2, 2*n+1)
gp = res.models[- (5- n)*times]
curr_x_iters = res.x_iters[len_x0:len_x0+10+n*times]
curr_func_vals = res.func_vals[len_x0:len_x0+10+n*times]
# Plot GP(x) + contours
y_pred, sigma = gp.predict(x_gp, return_std=True)
plt.plot(x, y_pred, "g--", label=r"$\mu_{GP}(x)$")
plt.fill(np.concatenate([x, x[::-1]]),
np.concatenate([y_pred - 1.9600 * sigma,
(y_pred + 1.9600 * sigma)[::-1]]),
alpha=.2, fc="g", ec="None")
print (sigma)
# Plot sampled points
plt.plot(curr_x_iters, curr_func_vals,
"r.", markersize=8, label="Observations")
plt.plot(old_x_iters, old_func_vals,
'b.', markersize = 2, label = "Observations (loaded data)")
# Adjust plot layout
plt.grid()
if n == 0:
plt.legend(loc="best", prop={'size': 6}, numpoints=1)
if n != 4:
plt.tick_params(axis='x', which='both', bottom='off',
top='off', labelbottom='off')
# Plot EI(x)
plt.subplot(5, 2, 2*n+2)
acq = gaussian_ei(x_gp, gp, y_opt=np.min(curr_func_vals))
plt.plot(x, acq, "b", label="EI(x)")
plt.fill_between(x.ravel(), -2.0, acq.ravel(), alpha=0.3, color='blue')
next_x = res.x_iters[10+n*times]
next_acq = gaussian_ei(res.space.transform([next_x]), gp, y_opt=np.min(curr_func_vals))
plt.plot(next_x, next_acq, "bo", markersize=6, label="Next query point")
# Adjust plot layout
plt.grid()
if n == 0:
plt.legend(loc="best", prop={'size': 6}, numpoints=1)
if n != 4:
plt.tick_params(axis='x', which='both', bottom='off',
top='off', labelbottom='off')
plt.ylim((0,None))
else:
from skopt.plots import plot_evaluations
from skopt.plots import plot_objective
plt.figure()
plot_evaluations(res)
plt.figure()
plot_objective(res)
plt.show()
#if len(par0) > 1:
# import cma
# cma.fmin(to_optimize, pars0, 1.,options = {'bounds': list(np.transpose(bounds)/scaling), 'tolx': 1e-3, 'maxiter': self.n_steps.value, 'verb_plot': self.n_steps.value})
#else:
#from scipy.optimize import differential_evolution
#res = differential_evolution(to_optimize, bounds, strategy='best1bin', maxiter=self.n_steps.value, popsize=7)
# import noisyopt
# res = noisyopt.minimizeSPSA(to_optimize, pars0, bounds=np.transpose(np.transpose(bounds)/scaling), niter=self.n_steps.value,paired = False)
# print (res)
class GUI:
def __init__(self, devices, io):
self.devices = devices
self.io = io
self.parts = []
cs = configset(devices, io)
cio = configio(devices, io, cs)
pc = plot_configurator(cs)
ms = measureset(cs, pc, cio)
self.parts += [cs]
self.parts += [pc]
self.parts += [ms]
self.parts += [cio]
self.parts += [scanning_tool(ms)]
self.parts += [optimizer(ms,cs)]
self.make_widget()
self.show()
def make_widget(self):
heading = widgets.HTML('