Skip to content
Snippets Groups Projects
Commit 91f23b46 authored by Alexandros Asonitis's avatar Alexandros Asonitis
Browse files

new memristor software version

parent f7348e77
No related branches found
No related tags found
No related merge requests found
"""
This is a python file containing all the important functions for memristor measurement
Available Functions
measurements in the HP4155a
plot results
create data frame
ini file decoder
enabing and disabling widgets for jupyter(lists)
"""
import sys
sys.path.insert(0, '..') #append parent directory
import module
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import filedialog
import tkinter.messagebox
import numpy as np
from IPython.display import display, clear_output
import pandas as pd
from datetime import datetime
import ipywidgets as widgets
import time
import os
#double sweep from start to stop and then from start to stop
def sweep(start,stop,step,comp,integration,device):
device.measurement_mode('SWE')
#changed smu2 is source and 4 is ground
#smu2 is constant and common
device.smu_mode_meas(4,'COMM')
device.smu_function_sweep(4,'CONS')
#smu4 is VAR1 and V
device.smu_mode_meas(2,'V')
device.smu_function_sweep(2,'VAR1')
device.integration_time(integration)
#define double sweep
device.var1_mode('DOUB')
#start stop step and comp
device.start_value_sweep(start)
#time.sleep(5)
device.stop_value_sweep(stop)
#time.sleep(5)
if start < stop and step < 0 :
step = -step
elif start > stop and step > 0 :
step = -step
device.step_sweep(step)
#time.sleep(5)
device.comp('VAR1',comp)
#display variables
device.display_variable('X','V2')
device.display_variable('Y1','I2')
#execute measurement
device.single_measurement()
while device.operation_completed()==False:
time.sleep(2)
device.autoscaling()
#return values
V=device.return_data('V2')
I=device.return_data('I2')
#convert the list to np.array to return the absolute values for the logarithmic scale
V = np.array(V)
I = np.array(I)
#return all values to the function
return V, I
#sampling check
def sampling_check(voltage,device):
device.measurement_mode('SAMP')
device.smu_mode_meas(2,'V')
device.smu_mode_meas(4,'COMM')
#set voltage and compliance
device.constant_smu_sampling(2,voltage)
device.constant_smu_comp(2,'MAX')
device.sampling_mode('LIN')
device.number_of_points(5)
device.integration_time('MED')
device.initial_interval(2e-3)
device.filter_status('OFF')
#remove total sampling time
device.auto_sampling_time('ON')
device.display_variable('X','@TIME')
device.display_variable('Y1','R')
device.single_measurement()
while device.operation_completed() == False:
time.sleep(2)
device.autoscaling()
try:
TIME = device.return_data('@TIME')
R = device.return_data('R')
TIME = np.array(TIME)
R = np.array(R)
R_mean = np.average(R)
return R_mean
except:
return 0
#new (retention)
def retention(voltage,period,duration,device):
device.measurement_mode('SAMP')
device.smu_mode_meas(2,'V')
device.smu_mode_meas(4,'COMM')
#set voltage and compliance
device.constant_smu_sampling(2,voltage)
device.constant_smu_comp(2,'MAX')
device.sampling_mode('LIN')
device.initial_interval(period)
device.total_sampling_time(duration)
if int(duration/period)+1<=10001:
device.number_of_points(int(duration/period)+1)
else:
device.number_of_points('MAX')
device.integration_time('MED')
device.filter_status('OFF')
device.display_variable('X','@TIME')
device.display_variable('Y1','R')
device.single_measurement()
while device.operation_completed() == False:
time.sleep(2)
device.autoscaling()
try:
TIME = device.return_data('@TIME')
R = device.return_data('R')
TIME = np.array(TIME)
R = np.array(R)
return TIME,R
except:
return 0,0
#plot sweep results
def plot_sweep(x,y,title):
#plot results
plt.figure().clear()
fig, (ax1, ax2) = plt.subplots(2,sharex=True,figsize=(8,6)) #the plots share the same x axis
fig.suptitle(title)
ax1.set_title('Linear I')
ax1.set(xlabel='Voltage(V)',ylabel='Current(A)')
ax2.set_title('Logarithmic I')
ax2.set(xlabel='Voltage(V)',ylabel='Current(A)')
ax2.set_yscale('log')
ax1.plot(x,y)
ax2.plot(x,np.absolute(y))
plt.tight_layout()
plt.show()
def plot_retention(x,y):
fig, ax = plt.subplots()
fig.suptitle('Retention')
ax.set(xlabel='time(s)',ylabel='Resistance(Ohm)')
ax.set_yscale('log')
ax.set_xscale('linear')
plt.plot(x,y)
plt.show()
def create_data_frame(x,y):
header = ['V(V)','ABSV(V)',"I(A)",'ABSI(A)',"R(Ohm)"]
data = {header[0]:x,header[1]:np.absolute(x),header[2]:y,header[3]:np.absolute(y),header[4]:np.divide(x,y)}
df = pd.DataFrame(data)
#print(df)
return df
def create_retention_data_frame(x,y):
header = ['Time(s)','R(Ohm)']
data = {header[0]:x,header[1]:y}
df = pd.DataFrame(data)
return df
#write results to file
def write_to_file(file,title,df):
with open(file,'a') as f:
f.write(title)
f.write("\n")
f.write(df.to_string())
f.write("\n\n")
#### new functions ##############
def change_state(widgets_list):
for widget in widgets_list:
widget.disabled = not widget.disabled
def enable_widgets(widgets_list):
for widget in widgets_list:
widget.disabled = False
#a check values function
def check_values(step,set_voltage,reset_voltage):
valid = True
root = tk.Tk()
root.withdraw()
root.lift() #show window above all other applications
root.attributes("-topmost", True)#window stays above all other applications
if step > abs(set_voltage) or step > abs(reset_voltage) or step==0:#invalid parameter setting
valid = False
tkinter.messagebox.showerror(message="Invalid parameter setting!")
#now if the set-reset voltages have the same polarity show a warning
elif set_voltage*reset_voltage>0:
valid = tk.messagebox.askokcancel(message="Set-Reset voltages have the same polarity. Continue?")
else:
pass
root.destroy()
return valid
def information_box(information):
#open dialog and hide the main window
root = tk.Tk()
root.withdraw()
root.lift() #show window above all other applications
root.attributes("-topmost", True)#window stays above all other applications
#display meaagebox
tkinter.messagebox.showinfo(message=information)
root.destroy()
#choose directory to save measurement results
#and check if you have access
def check_writable(folder):
filename = "test.txt"
file = os.path.join(folder,filename)
#protection against removing existing file in python
i=1
while os.path.exists(file):
filename=f"test{i}.txt"
file = os.path.join(folder,filename)
try:
with open(file,'a'):
writable = True
os.remove(file)
except:
writable = False
information_box(f"{folder} is not writable!")
return writable
def choose_folder():
root = tk.Tk()
root.withdraw()
root.lift() #show window above all other applications
root.attributes("-topmost", True)#window stays above all other applications
#choose nonemty folder
folder = tk.filedialog.askdirectory()
while folder == '':
folder = tk.filedialog.askdirectory()
#check if writable in a while loop
writable=check_writable(folder)
while writable == False:
#choose a correct folder
folder = tk.filedialog.askdirectory()
while folder == '':
folder = tk.filedialog.askdirectory()
#check writable if not repeat
writable=check_writable(folder)
root.destroy()
return folder
#create or append to file a new measurement(now locally) we dont need that anymore!!!
def create_remote_file(sample_series,field,DUT,folder):
filename=f"{sample_series.value}_{field.value}_{DUT.value}.txt"
file=os.path.join(folder,filename)#the whole file with location
date = str(datetime.today().replace(microsecond=0))
#check loop (once the return is called the function is over)
while True:
try:#you cannot write in every directory
with open(file,'a') as f:
title = f"Memristor Measurement"+"\n\n"+f"Sample series:{sample_series.value}" +"\n"+f"field:{field.value}"+"\n"+f"DUT:{DUT.value}"+"\n"+f"Date:{date}"+"\n\n"
f.write(title)
return file
except:
information_box(f"You cannot write in the directory: {folder}!")
#again
folder=choose_folder()
file=os.path.join(folder,filename)#the whole file with location
#write the header
def write_header(file,sample_series,field,DUT):
date = str(datetime.today().replace(microsecond=0))
with open(file,'a') as f:
title = f"Memristor Measurement"+"\n\n"+f"Sample series:{sample_series.value}" +"\n"+f"field:{field.value}"+"\n"+f"DUT:{DUT.value}"+"\n"+f"Date:{date}"+"\n\n"
f.write(title)
"""
New function (UPLOAD RESULTS)
IMPORTANT FOR ALL MEASUREMENTS
THE RESULTS ARE MOVED FROM SOURCE FILE TO TARGET FILE EVEN LOCALLY
"""
def upload_results(source_file,target_file,target_file_dir):
while True:
try:
with (open(source_file,'r') as source,open(target_file,'a') as target):
target.write(source.read())
os.remove(source_file)
return source_file,target_file,target_file_dir
except:
information_box(f"{target_file} is no longer accessible. Please change directory")
target_file_dir = choose_folder()
filename = os.path.basename(target_file)
target_file =os.path.join(target_file_dir,filename)
#and then try again
\ No newline at end of file
### this is the new memrstor measurement (set and reset as many times as the user wants and full sweeps with a button)
from help import *
import ipywidgets as widgets
from keyboard import add_hotkey,remove_hotkey
#additional variables
first = True #first measurement
"""
This is not anymore the first time you start a measurement but the first time you write a header
"""
file = None #complete filename with path
#first_sampling = True #indicates first sampling for set and reset buttons because we cannot add two at each button
#we dont need this variable anymore
#create temporary file to store the results localy
temp_file= os.path.join(os.getcwd(),'tempfile.txt')
# the three naming fields
sample_series= widgets.Text(
value= '',
placeholder ='Enter text here:',
description = 'sample series:',
style = {'description_width': 'initial'}
)
field = widgets.Text(
value= '',
placeholder ='Enter text here:',
description = 'Field:',
style = {'description_width': 'initial'},
)
DUT = widgets.Text(
value= '',
placeholder ='Enter text here:',
description = 'DUT:',
style = {'description_width': 'initial'},
)
#start new measurement button(new sample)
new=widgets.Button(description='next sample')
#choose a new folder button
new_folder = widgets.Button(description='change folder')
horizontal = widgets.HBox([sample_series,new])
horizontal3= widgets.HBox([DUT,new_folder])
all_text_boxes = widgets.VBox([horizontal,field,horizontal3])
#first series of parameters
step = widgets.BoundedFloatText(
value=0.01,
min=0,
max=100,
step=0.01,
description='Step(V):',
)
integration_time=widgets.Dropdown(
options=['SHORt', 'MEDium', 'LONG'],
value='MEDium',
description='Integration:',
#style = {'description_width': 'initial'},
)
sampling=widgets.Checkbox(description='sampling check')
#align the widgets horizontaly
line0=widgets.HBox([step,integration_time,sampling])
# THE BUTTONS
#create buttons as it shown in the how_buttons_look
set=widgets.Button(description='SET')
reset=widgets.Button(description='RESET')
full=widgets.Button(description='full sweep')
number = widgets.BoundedIntText(value=1,min=1,max=sys.maxsize,step=1,description='full sweeps:',disabled=False) #number of measuremts for the full sweep
retention_button=widgets.Button(description='retention')
#parameter boxes
Vset=widgets.BoundedFloatText(
value=1,
min=-100,
max=100,
step=0.1,
description='Voltage(V):',
)
#parameter buttons
CC_vset=widgets.BoundedFloatText(
value=1e-3,
min=-0.1,
max=0.1,
step=0.01,
description= 'Comp(A):',
)
#parameter buttons
Vreset=widgets.BoundedFloatText(
value=-1,
min=-100,
max=100,
step=0.1,
description='Voltage(V):',
)
#parameter buttons
CC_vreset=widgets.BoundedFloatText(
value=1e-3,
min=-0.1,
max=0.1,
step=0.01,
description='Comp(A):',
)
Vretention=widgets.BoundedFloatText(
value=1,
min=-100,
max=100,
step=1,
description='Voltage(V):',
)
period=widgets.BoundedFloatText(
value=1,
min=2e-3,
max=65.535,
step=1,
description='Period(s):',
)
duration=widgets.BoundedFloatText(
value=60,
min=60e-6,
max=1e11,
step=1,
description='Duration(s):',
)
#align a button with a checkbox or integer bounded texts horizontaly
line1 = widgets.HBox([set,Vset,CC_vset])
line2 = widgets.HBox([reset,Vreset,CC_vreset])
line3 = widgets.HBox([full,number])
line4 = widgets.HBox([retention_button,Vretention,period,duration])
#pack them into a single vertical box
all = widgets.VBox([line1,line2,line3,line4])
output = widgets.Output()
#help lists for changing state of the buttons
information = [sample_series,field,DUT]
buttons = [set,reset,full,new,new_folder,retention_button]
parameters = [Vset,CC_vset,Vreset,CC_vreset,step,integration_time,number,sampling,Vretention,period,duration]
#connect to the device
device = module.HP4155a('GPIB0::17::INSTR')
device.reset()
#disable all irrelevant units for the measurement
#smu1 and smu3 are disabled
device.smu_disable_sweep(1)
device.smu_disable_sweep(3)
#disable vmus and vsus
device.disable_vsu(1)
device.disable_vsu(2)
device.disable_vmu(1)
device.disable_vmu(2)
# R user function
device.user_function('R','OHM','V2/I2')
#choose folder directory
folder=choose_folder()
#display all at the end
display(all_text_boxes)
print()
display(line0)
print()
#display the buttons
display(all,output)
""" the above is what happens when the programm starts all the rest have to be written into button trigger functions"""
def on_set_button_clicked(b):
global first,folder,file,temp_file
with output:
#disable buttons
change_state(buttons)
change_state(parameters)
#lock the device
device.inst.lock_excl()
clear_output()
#check values
valid = check_values(step.value,Vset.value,Vreset.value)
#during first button press
if first == True and valid == True:
change_state(information)#disable all widgets that are relevant about the information of the sample
filename=f"{sample_series.value}_{field.value}_{DUT.value}.txt"
file = os.path.join(folder,filename)
#write header to temp_file
write_header(temp_file,sample_series,field,DUT)
first = False
if valid == True:
if sampling.value == True: #do sampling set before set process(100mV)
R_mean_before = sampling_check(0.1,device)
R_mean_before = round(R_mean_before,1)#round 1 decimal point
print(f"Average Resistance(Sampling Check):{R_mean_before:e} Ohm")
first_sampling = False
#execute measurement,plot results and save them
V12,I12 = sweep(0,Vset.value,step.value,CC_vset.value,integration_time.value,device)
plot_sweep(V12,I12,'SET')
df = create_data_frame(V12,I12)
print(df)
if sampling.value == True: #do sampling set after set process(10mV)
R_mean_after = sampling_check(0.01,device)
R_mean_after = round(R_mean_after,1)
print(f"Average Resistance(Sampling Check):{R_mean_after:e} Ohm")
first_sampling = False
title = f"SET Memristor:"+"\n\n"+f"Set Voltage={Vset.value}V"+"\n"+f"current compliance={CC_vset.value}A"+"\n"
if sampling.value == True:
title = title + f"R(Ohm) Before/After"+"\n"+f"{R_mean_before} {R_mean_after}"+"\n"
write_to_file(temp_file,title,df)
#upload results
temp_file,file,folder=upload_results(temp_file,file,folder)
#show messagebox
information_box("Measurement finished!")
#unlock device
device.inst.unlock()
change_state(buttons)
change_state(parameters)
def on_reset_button_clicked(b):
global first,folder,file,temp_file
with output:
change_state(buttons)
change_state(parameters)
#lock device
device.inst.lock_excl()
clear_output()
#check values
valid = check_values(step.value,Vset.value,Vreset.value)
#during first button press
if first == True and valid == True:
#disable checkboxes, text fields etc.
change_state(information)
filename=f"{sample_series.value}_{field.value}_{DUT.value}.txt"
file = os.path.join(folder,filename)
#write header to temp_file
write_header(temp_file,sample_series,field,DUT)
first = False #set first to false irrelvant if it is in the if statement or not
if valid == True:
if sampling.value == True: #do sampling set before reset process(10mV)
R_mean_before = sampling_check(0.01,device)
R_mean_before = round(R_mean_before,1)#round 1 decimal point
print(f"Average Resistance(Sampling Check):{R_mean_before:e} Ohm")
first_sampling = False
#execute measurement,plot results and save them
V34,I34 = sweep(0,Vreset.value,step.value,CC_vreset.value,integration_time.value,device)
plot_sweep(V34,I34,'RESET')
df = create_data_frame(V34,I34)
print(df)
if sampling.value == True: #do sampling set after reset process(100mV)
R_mean_after = sampling_check(0.1,device)
R_mean_after = round(R_mean_after,1)
print(f"Average Resistance(Sampling Check):{R_mean_after:e} Ohm")
first_sampling = False
title =f"RESET Memristor:"+"\n\n"+f"Reset Voltage={Vreset.value}V"+"\n"+f"current compliance={CC_vreset.value}A"+"\n"
if sampling.value == True:
title = title + f"R(Ohm) Before/After"+"\n"+f"{R_mean_before} {R_mean_after}"+"\n"
write_to_file(temp_file,title,df)
#upload results
temp_file,file,folder=upload_results(temp_file,file,folder)
#show messagebox
information_box("Measurement finished!")
#unlock device
device.inst.unlock()
change_state(buttons)
change_state(parameters)
def on_full_button_clicked(b):
global first,folder,file,temp_file
with output:
change_state(buttons)
change_state(parameters)
# lock device
device.inst.lock_excl()
clear_output()
#check values
valid = check_values(step.value,Vset.value,Vreset.value)
#during first button press
if first == True and valid == True:
#disable checkboxes, text fields etc.
change_state(information)
filename=f"{sample_series.value}_{field.value}_{DUT.value}.txt"
file = os.path.join(folder,filename)
#write header to temp_file
write_header(temp_file,sample_series,field,DUT)
first = False #set first to false irrelvant if it is in the if statement or not
if valid == True:
with open(temp_file,'a') as f:
f.write(f"{number.value} full sweeps with parameters:")
f.write("\n")
f.write(f"Set Voltage = {Vset.value}V")
f.write("\n")
f.write(f"Current compliance set = {CC_vset.value}A")
f.write("\n")
f.write(f"Reset Voltage = {Vreset.value}V")
f.write("\n")
f.write(f"Current compliance reset = {CC_vreset.value}A")
f.write("\n\n")
plt.figure().clear()
fig, (ax1, ax2) = plt.subplots(2,sharex=True,figsize=(8,6)) #the plots share the same x axis
fig.suptitle('FULL SWEEP')
ax1.set_title('Linear I')
ax1.set(xlabel='Voltage(V)',ylabel='Current(A)')
ax2.set_title('Logarithmic I')
ax2.set(xlabel='Voltage(V)',ylabel='Current(A)')
ax2.set_yscale('log')
stop = False
def break_loop():
nonlocal stop
stop = True
#help list with the resistances
resistances = []
add_hotkey("esc",break_loop)
#execute number of measurements
for i in range(number.value):#here it is easier to implement the sampling checks
if sampling.value == True: #before set(100mv)
R_mean_init = sampling_check(0.1,device)
R_mean_init = round(R_mean_init,1)
resistances.append(R_mean_init)
V12,I12 = sweep(0,Vset.value,step.value,CC_vset.value,integration_time.value,device) #set
#after set/before set
if sampling.value == True: #before set(10mv)
R_mean_set = sampling_check(0.01,device)
R_mean_set = round(R_mean_set,1)
resistances.append(R_mean_set)
V34,I34 = sweep(0,Vreset.value,step.value,CC_vreset.value,integration_time.value,device) #reset
#no reason to do check at the end because the next loop will do that(not anymore) more sampling checks
#after reset
if sampling.value == True:#-0.1V
R_mean_reset = sampling_check(-0.1,device)
R_mean_reset = round(R_mean_reset,1)
resistances.append(R_mean_reset)
#butterfly curve
V=np.concatenate((V12,V34))
I=np.concatenate((I12,I34))
#create data frame and save to file
df = create_data_frame(V,I)
f.write(f"{i+1} Iteration")
f.write("\n")
if sampling.value == True:
f.write(f"R(Ohm) INIT/SET/RESET"+"\n"+f"{R_mean_init} {R_mean_set} {R_mean_reset}"+"\n")
f.write(df.to_string())
f.write("\n\n")
#plot results
ax1.plot(V,I)
ax2.plot(V,np.absolute(I))
fig.tight_layout()
#update plot
clear_output()
display(fig)
#plt.show()
print(df)
#check for loop termination
if stop == True:
information_box("Endurance stopped after esc!")
f.write("endurance stopped!\n\n")
break
else:
information_box("Endurance completed!")
f.write("endurance completed!\n\n")
remove_hotkey('esc')
stop = False
#plot resistances if sampling value == True or len(resistances) !=0
if len(resistances)!=0:
indexes = np.arange(1,len(resistances)+1)
resistances = np.array(resistances)
plt.figure().clear()
fig, ax = plt.subplots()
fig.suptitle('Resistance')
ax.set(xlabel='Index',ylabel='Resistance(Ohm)')
ax.set_yscale('log')
plt.scatter(indexes,resistances)
plt.show()
#print(len(resistances))
#print(indexes)
#upload results
temp_file,file,folder=upload_results(temp_file,file,folder)
#unlock the device
device.inst.unlock()
change_state(buttons)
change_state(parameters)
#move to next sample
def on_new_sample_button_clicked(b):
global first
with output:
#the if is to ensure that is not pressed many times
#just in case the user presses anything
change_state(buttons)
change_state(parameters)
first = True
#change_state(information) not anymore creating changing state but enabling the widgets
enable_widgets(information)
#sample_series.value=''
#field.value=''
DUT.value=''
#enable again
change_state(buttons)
change_state(parameters)
#new_folder clicked
def on_new_folder_button_clicked(b):
global folder,file,first
with output:
change_state(buttons) #just to be sure
change_state(parameters)
folder = choose_folder()#choose new folder
#file = create_file(sample_series,field,DUT,folder) #and create the new file (creates multiple headers!!!)
first = True #that will write header if the directory is the same as the previous one!
change_state(buttons)
change_state(parameters)
def on_retention_button_clicked(b):
global first,folder,file,temp_file
with output:
change_state(buttons)
change_state(parameters)
device.inst.lock_excl()
clear_output()
#during first button press
if first == True:
#disable checkboxes, text fields etc.
change_state(information)
filename=f"{sample_series.value}_{field.value}_{DUT.value}.txt"
file = os.path.join(folder,filename)
#write header to temp_file
write_header(temp_file,sample_series,field,DUT)
first = False #set first to false irrelvant if it is in the if statement or not
#execute measurement
t,R=retention(Vretention.value,period.value,duration.value,device)
plot_retention(t,R)
df=create_retention_data_frame(t,R)
title =f"Retention Memristor:"+"\n\n"+f"Voltage={Vretention.value}V"+"\n"+f"period={period.value}s"+"\n"+f"duration={duration.value}s"+"\n"
write_to_file(temp_file,title,df)
#upload results
temp_file,file,folder=upload_results(temp_file,file,folder)
#show messagebox
information_box("Measurement finished!")
device.inst.unlock()
change_state(buttons)
change_state(parameters)
#link buttons with functions
set.on_click(on_set_button_clicked)
reset.on_click(on_reset_button_clicked)
full.on_click(on_full_button_clicked)
new.on_click(on_new_sample_button_clicked)
new_folder.on_click(on_new_folder_button_clicked)
retention_button.on_click(on_retention_button_clicked)
%% Cell type:code id:df99f5a2-80af-4892-8633-33177239e444 tags:
``` python
%run memristor.py
```
%% Output
%% Cell type:code id:076a9132-edc2-4ae5-8a7f-c8a179473952 tags:
``` python
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment