コード例 #1
0
def run_measurement(event, 
                    param_set, 
                    param_meas, 
                    spaces, 
                    settle_times, 
                    name, 
                    comment, 
                    meander, 
                    extra_cmd, 
                    extra_cmd_val,
                    wait_first_datapoint,
                    checkstepinterdelay,
                    manualsetpoints):
    # Local reference of THIS thread object
    t = current_thread()
    # Thread is alive by default
    t.alive = True

    # Create measurement object
    meas = Measurement() 
    # Apply name
    meas.name = name

    #Generating setpoints
    if manualsetpoints==False:
        if meander == True:
            setpoints = cartprodmeander(*spaces)
        else:
            setpoints = cartprod(*spaces)
    else:
        setpoints = spaces
    ### Filling station for snapshotting
    fill_station(param_set,param_meas)
    ### Checking and setting safety rates and delays
    if checkstepinterdelay:
        safetyratesdelays(param_set,spaces)    
    
    meas.write_period = 1
       
    #Make array showing changes between setpoints on axes
    changesetpoints = setpoints - np.roll(setpoints, 1, axis=0)

    #Forcing the first setpoint in changesetpoints to 1 to make sure it is always set.
    changesetpoints[0,:] = 1
   
    # Registering set parameters
    param_setstring = ''
    param_setnames = [None]*len(param_set)
    param_setunits = [None]*len(param_set)
    for i,parameter in enumerate(param_set):
        meas.register_parameter(parameter)
        param_setstring += parameter.name + ', '
        param_setnames[i] = parameter.name
        param_setunits[i] = parameter.unit
    
    output = [None]*len(param_meas) 
        # Registering readout parameters
    param_measstring = ''
    param_measnames = [None]*len(param_meas)
    param_measunits = [None]*len(param_meas)
    param_measnames_sub = [None]*len(param_meas)
    paramtype = [None]*len(param_meas)
    for i, parameter in enumerate(param_meas):
        meas.register_parameter(parameter, setpoints=(*param_set,))
        output[i]= [parameter, None]
        param_measstring += parameter.name + ', '
        param_measnames[i] = parameter.name
        if isinstance(parameter, qc.instrument.parameter.ParameterWithSetpoints):
            param_measunits[i] = parameter.unit
            param_measnames_sub[i] = ''
            paramtype[i] = 'ParameterWithSetpoints'
        elif isinstance(parameter, qc.instrument.parameter.MultiParameter):
            param_measunits[i] = parameter.units
            param_measnames_sub[i] = parameter.names
            paramtype[i] = 'MultiParameter'
        elif isinstance(parameter, qc.instrument.parameter.Parameter):
            param_measunits[i] = parameter.unit
            paramtype[i] = 'Parameter'

    # Start measurement routine
    with meas.run() as datasaver:  
        global measid
        measid = datasaver.run_id

        # Getting dimensionality of measurement
        ndims = setpoints.shape[1]
        
        # Add comment to metadata in database
        datasaver.dataset.add_metadata('Comment', comment)
        
        # Main loop for setting values
        for i in range(0,setpoints.shape[0]):
            #Check for nonzero axis to apply new setpoints by looking in changesetpoints arrays
            resultlist = [None]*ndims
            if i==0: #On first datapoint change set_params from slow to fast axis
                dimlist = range(0,ndims)
            else: #On all other datapoints change fast axis first
                dimlist = reversed(range(0,ndims))
            for j in dimlist:
                if not np.isclose(changesetpoints[i,j] , 0, atol=0): # Only set set params that need to be changed
                    if i==0 and not t.alive: # Allows killing of thread in-between initialisiation of set_parameters for first datapoint.
                        event.set() # Trigger closing of run_dbextractor
                        raise KeyboardInterrupt('User interrupted doNd during initialisation of first setpoint.')
                        # Break out of for loop
                        break
                    param_set[j].set(setpoints[i,j])
                    time.sleep(settle_times[j]) # Apply appropriate settle_time
                resultlist[j] = (param_set[j],setpoints[i,j]) # Make a list of result
            if i==0: # Add additional waiting time for first measurement point before readout and start timers
                time.sleep(wait_first_datapoint)
                # Start various timers
                starttime = datetime.datetime.now() + datetime.timedelta(0,-1)
                lastwrittime = starttime
                lastprinttime = starttime             
            for k, parameter in enumerate(param_meas): # Readout all measurement parameters at this setpoint i
                if extra_cmd is not None: # Optional extra command + value that is run before each measurement paremeter is read out.
                    if extra_cmd[k] is not None:
                        if extra_cmd_val[k] is not None:
                            (extra_cmd[k])(extra_cmd_val[k])
                        else:
                            (extra_cmd[k])()
                output[k][1] = parameter.get()
            datasaver.add_result(*resultlist, # Add everything to the database
                                 *output)
            setvals = list(zip(param_setnames,[f"{x:.{6}}" for x in setpoints[i,:]],param_setunits))
            outputparsed = [None]*len(param_meas)
            for k,x in enumerate([row[1] for row in output]):
                if paramtype[k] == 'MultiParameter':
                    valsparsed = [None]*len(x)
                    for l,y in enumerate(x):
                        if isinstance(y, (list,tuple,np.ndarray)):
                            if len(y) > 5:
                                vals = ['{:.6f}'.format(x) for x in y[0:5]]
                                vals.append('.......')
                            else:
                                vals = ['{:.6f}'.format(x) for x in y]
                            newvals = [[vals[i]] for i in range(0,len(vals))]
                            valsparsed[l] = tabulate(newvals,tablefmt='plain') 
                        else:
                            valsparsed[l] = f"{y:.{6}}"
                    outputparsed[k] = tabulate(list(zip(param_measnames_sub[k],valsparsed,param_measunits[k])), tablefmt='plain', colalign=('left','left','left'))
                if paramtype[k] == 'Parameter':
                    outputparsed[k] = tabulate([[f"{x:.{6}}",param_measunits[k]]], tablefmt='plain')
                if paramtype[k] == 'ParameterWithSetpoints':
                    outputparsed[k] = '{Parameter with setpoints, not shown.}'
            measvals = list(zip(param_measnames,outputparsed))

            if not t.alive: # Check if user tried to kill the thread by keyboard interrupt, if so kill it
                event.set() # Trigger closing of run_dbextractor
                qctools.db_extraction.db_extractor(dbloc = qc.dataset.sqlite.database.get_DB_location(),  # Run db_extractor once more
                                   ids=[measid], 
                                   overwrite=True,
                                   newline_slowaxes=True,
                                   no_folders=False,
                                   suppress_output=True,
                                   useopendbconnection = True)
                plot_by_id(measid)
                raise KeyboardInterrupt('User interrupted doNd. All data flushed to database and extracted to *.dat file.')
                # Break out of for loop
                break
            #Time estimation
            printinterval = 0.025 # Increase printinterval to save CPU
            now = datetime.datetime.now()
            finish =['','']
            if (now-lastprinttime).total_seconds() > printinterval or i == len(setpoints)-1: # Calculate and print time estimation
                frac_complete = (i+1)/len(setpoints)
                duration_in_sec = (now-starttime).total_seconds()/frac_complete
                elapsed_in_sec = (now-starttime).total_seconds()
                remaining_in_sec = duration_in_sec-elapsed_in_sec
                perc_complete = np.round(100*frac_complete,2)
                clear_output(wait=True)
                if i == len(setpoints)-1:
                    finish[0] = 'Finished: ' + str((now).strftime('%Y-%m-%d'))
                    finish[1] = str((now).strftime('%H:%M:%S'))

                l1 = tabulate([['----------------------' ,'-------------------------------------------------'],
                               ['Starting runid:', str(measid)], # Time estimation now in properly aligned table format
                               ['Name:', name], 
                               ['Comment:', comment],
                               ['Set parameter(s):', tabulate(setvals, tablefmt='plain', colalign=('left','left','left'))],
                               ['Readout parameter(s):', tabulate(measvals, tablefmt='plain', colalign=('left','left'))],
                               ['______________________' ,'_________________________________________________'],
                               ['Setpoint: ' + str(i+1) + ' of ' + str(len(setpoints)), '%.2f' % perc_complete + ' % complete.'],
                               ['Started: ' + starttime.strftime('%Y-%m-%d'), starttime.strftime('%H:%M:%S')],
                               ['ETA: ' + str((datetime.timedelta(seconds=np.round(duration_in_sec))+starttime).strftime('%Y-%m-%d')), str((datetime.timedelta(seconds=np.round(duration_in_sec))+starttime).strftime('%H:%M:%S'))],
                               [finish[0],finish[1]],
                               ['Total duration:', str(datetime.timedelta(seconds=np.round(duration_in_sec)))],
                               ['Elapsed time:', str(datetime.timedelta(seconds=np.round(elapsed_in_sec)))],
                               ['Remaining time:', str(datetime.timedelta(seconds=np.round(remaining_in_sec)))],
                               ], colalign=('right','left'), tablefmt='plain')
                print(l1)
                lastprinttime = now
        event.set() # Trigger closing of run_dbextractor
コード例 #2
0
def run_zerodim(event, param_meas, name, comment, wait_first_datapoint):
    # Local reference of THIS thread object
    t = current_thread()
    # Thread is alive by default
    t.alive = True

    # Create measurement object
    meas = Measurement() 
    # Apply name
    meas.name = name

    ### Filling station for snapshotting
    fill_station_zerodim(param_meas)
    
    meas.write_period = 0.5
    output = [] 
    # Registering readout parameters
    param_measstring = ''
    for parameter in param_meas:
        meas.register_parameter(parameter)
        output.append([parameter, None])   
        param_measstring += parameter.name + ', '
    
    # Start measurement routine
    with meas.run() as datasaver:  
        global measid
        measid = datasaver.run_id

        # Start various timers
        starttime = datetime.datetime.now()
        l1 = tabulate([['----------------------' ,'-------------------------------------------------'],
                       ['Running 0-dimensional measurement,', 'time estimation not available.'], # Time estimation now in properly aligned table format
                       ['Starting runid:', str(measid)], # Time estimation now in properly aligned table format
                       ['Name:', name], 
                       ['Comment:', comment],
                       ['Starting runid:', str(measid)],
                       ['Readout parameter(s):', str(param_measstring)],
                       ['______________________' ,'_________________________________________________'],
                       ['Started: ' + starttime.strftime('%Y-%m-%d'), starttime.strftime('%H:%M:%S')],
                       ], colalign=('right','left'), tablefmt='plain')
        print(l1)

        # Getting dimensions and array dimensions and lengths
        # Main loop for setting values
        #Check for nonzero axis to apply new setpoints by looking in changesetpoints arrays
        time.sleep(wait_first_datapoint)
        resultlist = [None]*1
        for k, parameter in enumerate(param_meas): # Readout all measurement parameters at this setpoint i
                output[k][1] = parameter.get()                
        datasaver.add_result(*output)
        datasaver.dataset.add_metadata('Comment', comment) # Add comment to metadata in database
        now = datetime.datetime.now()
        elapsed_in_sec = (now-starttime).total_seconds()
        clear_output(wait=True)
        l1 = tabulate([['---------------------------------' ,'-------------------------------------------'],
                       ['Running 0-dimensional measurement,', 'time estimation not available.'], # Time estimation now in properly aligned table format
                       ['Starting runid:', str(measid)], # Time estimation now in properly aligned table format
                       ['Name:', name], 
                       ['Comment:', comment],
                       ['Starting runid:', str(measid)],
                       ['Readout parameter(s):', str(param_measstring)],
                       ['_________________________________' ,'___________________________________________'],
                       ['Started: ' + starttime.strftime('%Y-%m-%d'), starttime.strftime('%H:%M:%S')],
                       ['Finished: ' + str((now).strftime('%Y-%m-%d')),str((now).strftime('%H:%M:%S'))],
                       ['Total duration:', str(datetime.timedelta(seconds=np.round(elapsed_in_sec)))],
                       ], colalign=('right','left'), tablefmt='plain')
        print(l1)
        event.set() # Trigger closing of run_dbextractor