GUI.py 39.9 KB
Newer Older
1 2 3 4
from ipywidgets import interactive, interact, interact_manual
from IPython.display import display
from IPython.display import HTML
import ipywidgets as widgets
Nick Sauerwein's avatar
Nick Sauerwein committed
5

6 7
import numpy as np
import matplotlib.pyplot as plt
Nick Sauerwein's avatar
Nick Sauerwein committed
8

9
import Scripts.DataManager as dm
Nick Sauerwein's avatar
Nick Sauerwein committed
10

11 12 13 14 15
class ConfigItemChanger:
    def __init__ (self, key, device):
        self.key = key
        self.value = device.config[key]
        
16
        self.device = device
17 18 19
        
        self.config = device.config

20
        layout_bt = widgets.Layout(width = '20px')
21
        layout_text = widgets.Layout(width = '180px')
22 23 24
        if type(self.value) == bool:
            self.cb =  widgets.Checkbox(value=self.value,
                                        description=key, layout = layout_text)
25 26 27
            self.cb.observe(self.change_bool, names = 'value')
            
            self.widget =self.cb
28 29
        elif type(self.value) == str:
            self.text = widgets.Text(value = self.value, describtion = key)
30 31
            self.text.on_submit(self.change_str)
            self.widget = self.text 
32 33 34 35
        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 )
36 37 38
            self.bm = widgets.Button(description='-', layout = layout_bt)


39 40 41
            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)
42 43

            self.widget = widgets.HBox([self.flt, self.step, self.bm, self.bp])
44 45
        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)
46 47 48 49 50 51 52 53 54 55
            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])
           
56
        else:
57
            self.widget = widgets.HTML(key+ ' (type '+str(np.dtype(type(self.value)))+') not changeable')
58
    def change_str(self,text):
59 60 61
        self.config[self.key] = self.text.value
        self.device.config = self.config

62
    def change_bool(self, new):
63 64
        self.config[self.key] = new['new']
        self.device.config = self.config
65 66
    
    def change_by_enter_float(self, text):
67 68
        self.config[self.key] = float(self.flt.value)
        self.device.config = self.config
69 70

    def change_by_enter_int(self, text):
71 72
        self.config[self.key] = int(self.flt.value)
        self.device.config = self.config
73
    
74
        
75
    def change_p_float(self, bt):
76
        self.config[self.key] = float(self.flt.value) + self.step.value
77
        self.flt.value = str(np.round(float(self.flt.value) + self.step.value,4))
78
        self.device.config = self.config
79
        
80
    def change_p_int(self, bt):
81
        self.config[self.key] = int(self.flt.value) + 1
82
        self.flt.value = str(int(self.flt.value) + 1)
83
        self.device.config = self.config
84 85
        
    def change_m_int(self, bt):
86
        self.config[self.key] = int(self.flt.value) - 1
87
        self.flt.value = str(int(self.flt.value) - 1)
88
        self.device.config = self.config
89 90
        
    def change_m_float(self, bt):
91
        self.config[self.key] = float(self.flt.value) - self.step.value
92
        self.flt.value = str(np.round(float(self.flt.value) - self.step.value,4))
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
        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('<b> Configuration: </b>')]
        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]
            
149 150 151 152 153 154 155
            
        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)
            
        
156 157
        
        
158 159 160 161 162 163 164
        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)()
165
        
166 167
        self.refresh()
        
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 193 194 195 196 197 198 199 200 201 202 203 204
        
    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('<b> Configuration: </b>')]
        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()
205
        
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    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()  
222

223 224 225 226

class ConfigLoader:
    
    def __init__(self, config, device_pool, device_pool_interface = None):
Nick Sauerwein's avatar
Nick Sauerwein committed
227
        
228 229 230 231 232 233
        self.config = config
        
        self.device_pool = device_pool
        
        self.device_pool_interface = device_pool_interface
        self.make_widget()
Nick Sauerwein's avatar
Nick Sauerwein committed
234
        
235
    def make_widget (self):
236
        
237 238 239 240 241 242 243 244 245 246
        self.time_html = widgets.HTML('<b>Time: '+self.config['time']+'</b>')
        self.load_device_wd = [self.time_html]
        
        if 'devices_connected' in self.config:
            self.load_device_wd += [widgets.HTML('<b>devices that where connected:</b>'),
                                    widgets.HTML('<b>'+str(self.config['devices_connected'])+'</b>')]
        
        for device in self.device_pool.device_names: 
            
            if device in self.config.keys():
247

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
                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):
        
276
        self.io = io
277 278
        self.device_pool = device_pool
        self.device_pool_interface = device_pool_interface
279 280
        
        self.make_widget()
281
        
282
    def make_widget(self):
283
        heading = widgets.HTML('<b>io interface</b>')
284
        
285 286
        self.text_path = widgets.Text(description = 'io folder: ',value = self.io.path)
        self.text_path.on_submit(self.change_path)
287
        
288 289 290 291 292
        
        
        # save configurations
        
        self.config_saver = [widgets.HTML('<b>save configuration of devices</b>')]
293 294 295
        self.text_comment = widgets.Text(description= 'Comment:')
        self.check_elog = widgets.Checkbox(value=False,
                                          description='elog')
296
        self.bt_save = widgets.Button(description= 'save')
297
        
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        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('<b>load configuration of devices</b>')]
        
        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]
            
            
336 337
        
        
338 339 340
    def change_path(self, text = None):
        self.io.path = self.text_path.value
        self.select_config.options = self.get_all()
341 342 343
        
    def save(self, bt):
        comment = self.text_comment.value
344
        if comment == '':
345
            self.ht_save.value = '<b>Enter comment to save config!</b>'
346
            return
347
        
348
        config = self.device_pool.config
349 350 351 352
        
        self.io.save(config, comment = comment, elog = self.check_elog.value)
        self.text_comment.value = ''
        self.ht_save.value = '<b>Config saved!</b>'
353 354 355 356 357
        self.select_config.options = self.get_all()
        
    def show(self):
        display(self.widget)        
        
358 359 360
        
    def get_all(self):
        configs = self.io.search(output = False)
361 362 363
        c = {}
        for i in range(len(configs)):
            c[configs[i]['comment']] = i
364
        return c        
365 366

    
367

Nick Sauerwein's avatar
Nick Sauerwein committed
368
    
369
    
370

371
    
372 373 374

        
class MeasurementManagerInterface:
375
    
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    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('<b><br>Measurement Manager Interface</b>')
        
        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
458 459
        
        self.plot_config = {}
460
        
461 462 463 464 465 466 467
        self.make_widget()
        
    def make_widget(self):
        
        heading = widgets.HTML('<b><br>Plot measurement configuration</b>')
        self.bt_plot_config_init = widgets.Button(description='Measure to initialize')
        self.bt_plot_config_init.on_click(self.initialize)
Sauerwein Nick Jacob's avatar
Sauerwein Nick Jacob committed
468
    
469 470 471 472 473 474
        self.vb_plot_config = widgets.VBox([self.bt_plot_config_init])
        
        self.widget = widgets.VBox([heading, 
                            self.vb_plot_config])
        
    def initialize(self, bt):
475 476 477 478 479 480 481
        #devices
        vbs = []
        names = {}
        wps = []
        
        plot_meas_check = {}
        
482 483 484
        devices_to_measure = self.device_pool.devices_to_measure
        
        device_names = [device.name for device in devices_to_measure]
485
        
486
        measurement = self.measurement_manager.measure()
487

488
        for device_name in device_names:
489
            self.plot_config[device_name] = {}
490 491

            wgs = [] 
492 493 494 495
            for parameter, value in sorted(measurement['measure'][device_name].items()):
                wgs += [PlotConfigTool(parameter,
                                       value,
                                       self.plot_config[device_name]).widget]
496
            
497
            if device_name in [device.name for device in self.device_pool.plotable_devices]:
498
                
499
                wgs += [PlotConfigTool('plot_measure',
500
                                         0,
501
                                         self.plot_config[device_name]).widget]
502 503

            vbs += [widgets.VBox(wgs)]
504 505 506
            
        measure_tab = widgets.Tab(children = vbs, _titles= dict(enumerate(device_names)))
        self.vb_plot_config.children = [self.bt_plot_config_init, measure_tab]
507

508
class PlotConfigTool:
509
    
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
    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:
529
    
530
    def __init__(self, measurement_manager):
531
        
532 533
        self.measurement_manager = measurement_manager

534
        
535
        self.make_widget()
536
        
537
    def make_widget(self):
538
        
539
        heading = widgets.HTML('<b>Scanning Tool</b>')
540 541
        
        
542 543 544 545 546 547
        self.dimensions_text = widgets.IntSlider(value=1,
                                                 min=0,
                                                 max=10,
                                                 step=1,
                                                 description='Number of Parameters:')
        self.dimensions_text.observe(self.set_dimension)
548
        
549
        self.scanning_tool_box = widgets.HBox([])
550
        
551 552 553 554 555
        self.set_dimension()
        self.widget = widgets.VBox([heading, self.dimensions_text, self.scanning_tool_box])
    
    @property
    def parameters(self):
556
        
557
        return [pc.parameter for pc in self.parameter_choosers]
558
        
559
    
560
    def set_dimension(self, dum = None):
561
        
562 563 564
        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]
565

566
        
567 568 569
 
        
class ParameterChooser:
570

571
    def __init__(self, title, measurement_manager):
572
        self.title = title
573 574
        self.measurement_manager = measurement_manager
        self.device_pool = measurement_manager.device_pool 
575
        
576
        self.device_dict = self.device_pool.devices
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
        
        self.make_widget()
        
    def make_widget(self):
        heading = widgets.HTML('<b>'+self.title+'</b>')
        
        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('<b> current value: no parameter choosen </b>')
        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
        
615
        config = self.device_pool.config
616
        
root's avatar
root committed
617
        scannable = []
618 619 620
        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]
621 622 623 624 625 626 627 628 629 630 631 632 633
                
        
        
        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
        
root's avatar
root committed
634 635
        try:
            device = self.select_device.value
636
        
637 638 639
            config = device.config
            
            current_value = config[device.name][parameter]
640
        
root's avatar
root committed
641
            self.current_value.value = '<b> current value: '+str(current_value)+' </b>'
642
        
root's avatar
root committed
643 644 645 646
            self.minv.value = current_value
            self.maxv.value = current_value
        except:
            print ('Choose parameter!!!')
647
    
648 649 650
    @property
    def parameter(self):
        return [self.select_device.value.name, self.select_parameter.value, self.minv.value, self.maxv.value, self.nsteps.value]   
651
        
652
       
653 654 655 656
        
        
        
        
657
# the rest of the gui still has to be changed to newer version (currently not usable)
658
class variableset:
659
    
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
    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('<b>'+self.name+'</b>')
        
        self.select_device = widgets.Select(description = 'device: ',options = self.device_dict)
        
Nick Sauerwein's avatar
Nick Sauerwein committed
679
        self.select_device.observe(self.on_value_change_device, names = 'value')
680 681 682
        
        self.select_parameter = widgets.Select(description = 'parameter: ', options = {'no device selected': None})
        
Nick Sauerwein's avatar
Nick Sauerwein committed
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
        
        
        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
                                        
            
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
        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]
Nick Sauerwein's avatar
Nick Sauerwein committed
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
        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
746 747 748 749
            
    def get_device_name(self):
        
        return type(self.select_device.value).__name__
750
    
Nick Sauerwein's avatar
Nick Sauerwein committed
751 752 753 754
    def get_device(self):
        
        return self.select_device.value
    
755 756 757
    def get_parameter(self):
        
        return self.select_parameter.value
Nick Sauerwein's avatar
Nick Sauerwein committed
758 759 760 761 762
    
    def bound(self):
        if self.measure:
            return [None, None]
        return [self.boundmin.value, self.boundmax.value]
763

764 765
        
class optimizer:
Sauerwein Nick Jacob's avatar
Sauerwein Nick Jacob committed
766
    
767 768 769 770 771
    def __init__(self, measureset, configset):
        
        self.measureset = measureset
        self.configset = configset
        self.devices = measureset.devices
Nick Sauerwein's avatar
Nick Sauerwein committed
772
        self.io = measureset.io
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
        
        self.variables_change = []
        self.variables_formula = []
        
        
        self.make_widget()
        
    def make_widget(self):
        
        heading = widgets.HTML('<b> Optimizer </b>')
        
        text1 = widgets.HTML('<b> select variables</b>')
        
        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('<b> make optimizer function</b>')
        
        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')
Nick Sauerwein's avatar
Nick Sauerwein committed
807
        self.est_error = widgets.FloatText(description='estim. Error: ',value = '-1')
808 809 810 811 812 813 814 815
        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)
        
Nick Sauerwein's avatar
Nick Sauerwein committed
816
        self.n_steps = widgets.IntText(description = 'Steps: ', value = 30)
817
        
Nick Sauerwein's avatar
Nick Sauerwein committed
818 819
        self.file_load = widgets.Text(description = 'load results: ', value = 'None')
        self.file_save = widgets.Text(description = 'save results: ', value = 'None')
820 821 822 823 824 825 826
        self.widget = widgets.VBox([heading, 
                                    text1, 
                                    self.num_change, 
                                    self.VBox1,
                                    self.text2, 
                                    self.num_formula,
                                    self.VBox2,
Nick Sauerwein's avatar
Nick Sauerwein committed
827
                                    widgets.HBox([self.formula_text,self.est_error]),
Nick Sauerwein's avatar
Nick Sauerwein committed
828
                                    widgets.HBox([self.n_steps, self.file_load, self.file_save]),
829 830 831 832 833 834 835 836 837 838 839 840 841
                                    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]    
Sauerwein Nick Jacob's avatar
Sauerwein Nick Jacob committed
842
    
843
    def update_variables(self):
Nick Sauerwein's avatar
Nick Sauerwein committed
844
        measurements = self.measureset.measure(delete = False) 
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
        
        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)')
            
            
Nick Sauerwein's avatar
Nick Sauerwein committed
861
    
862 863 864 865 866 867 868 869 870 871 872 873 874
    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()]]
        
        
            
Nick Sauerwein's avatar
Nick Sauerwein committed
875 876 877 878 879 880 881 882 883
        
        
        
        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
        
Nick Sauerwein's avatar
Nick Sauerwein committed
884 885 886 887 888 889
        if self.est_error.value > 0:
            noise = self.est_error.value
            
        else:
            noise = 'gaussian'
        
Nick Sauerwein's avatar
Nick Sauerwein committed
890 891
        def to_optimize(pars):
            pars = pars * scaling
Nick Sauerwein's avatar
Nick Sauerwein committed
892
            #config = dm.get_config(self.devices)
Nick Sauerwein's avatar
Nick Sauerwein committed
893
            print ('Changing:')
894
            for i,vc in enumerate(self.variables_change):
Nick Sauerwein's avatar
Nick Sauerwein committed
895
                config = dm.get_config([vc.get_device()])
Nick Sauerwein's avatar
Nick Sauerwein committed
896
                print (vc.get_device_name()+'/'+vc.get_parameter()+' = '+str(pars[i]))
897
                config[vc.get_device_name()][vc.get_parameter()] = pars[i]
Nick Sauerwein's avatar
Nick Sauerwein committed
898
                dm.set_config([vc.get_device()], config)
899 900 901 902 903 904 905 906
            
            
            
            self.update_variables()
            to_opt = eval(self.formula_text.value)
            
            return to_opt
        
Nick Sauerwein's avatar
Nick Sauerwein committed
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
        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
Nick Sauerwein's avatar
Nick Sauerwein committed
926
                          noise = noise,
Nick Sauerwein's avatar
Nick Sauerwein committed
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
                          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
943
            
944

Nick Sauerwein's avatar
Nick Sauerwein committed
945 946
            x = np.linspace(scaledbounds[0][0], scaledbounds[0][1], 400).reshape(-1, 1)
            x_gp = res.space.transform(x.tolist())
947
            
Nick Sauerwein's avatar
Nick Sauerwein committed
948
            num_models = len(res.models)
949
            
Nick Sauerwein's avatar
Nick Sauerwein committed
950 951 952 953
            times = (num_models)//5
            if num_models == 0:
                print ('no models made')
                return
954
            
Nick Sauerwein's avatar
Nick Sauerwein committed
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
            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")
Nick Sauerwein's avatar
Nick Sauerwein committed
974 975
                
                print (sigma)
Nick Sauerwein's avatar
Nick Sauerwein committed
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026

                # 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()
            

1027 1028 1029
            
            
            
Nick Sauerwein's avatar
Nick Sauerwein committed
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
        #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)
1046
            
Nick Sauerwein's avatar
Nick Sauerwein committed
1047
        #    print (res)    
1048
        
1049 1050
    

1051
class GUI:
1052
    
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
    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('<h1>LWFA GUI</h1>')
        
        self.widget = widgets.VBox([heading]+
                                   [part.widget for part in self.parts])
        
        
    def show(self):
        display(self.widget)

1085
    
Nick Sauerwein's avatar
Nick Sauerwein committed
1086