From 130fdfbab13d48916f095d0759f07e6740a161eb Mon Sep 17 00:00:00 2001 From: rtan Date: Mon, 15 Jul 2024 10:53:35 +0200 Subject: [PATCH 01/39] Read Serial-Nr. and checks the limits of the device --- 20240709SerdarModScript.py | 42 +++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index d5cbe09..9f1fce3 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -351,11 +351,10 @@ def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0.01)- except pyvisa.VisaIOError as e: print(f"Error communicating with instrument: {e}") -# TODO: implement the reverse scan and zero when finish functionality # receive values in units of T, rescale in kg to talk with the power supplyy. 1T = 10kG def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, res:float, Settings:str, base_file_name='', path_save="C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test", - singlepowersupply_bool=False, reversescan_bool=False, zerowhenfin_bool=False)->None: + reversescan_bool=False, zerowhenfin_bool=False)->None: """ this function performs a sweep of the B field of the chosen magnet coil. It creates a list o B values from the given min and max values, with the given resolution. For each value, a measurement of the spectrum of the probe in the cryostat is made, using the LightField spectrometer. @@ -375,26 +374,44 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, ValueError: when By limit is exceeded. ValueError: when Bz limit is exceeded. ValueError: when Bx limit is exceeded. + ConnectionError: when no device is connected. """ '''''' if base_file_name =='': base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') - start_time = time.time() + start_time = time.time() # start of the scan function + + # TODO: queries the serial number of the device, and from there, check the if the input limits exceed the recommended limits + instr_info = query_no_echo(instr, '*IDN?') + instr_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim if instr_bsettings[0][0] == 'T': instr_bsettings[1][0] = instr_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T instr_bsettings[2][0] = instr_bsettings[2][0]*0.1 - if singlepowersupply_bool: # checks limits of Bx or By + # if singlepowersupply_bool: # checks limits of Bx or By + # if (min_bval< -BY_MAX) or (max_bval > BY_MAX): + # raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.') + # elif '1' in query_no_echo(instr, 'CHAN?'): # check if its the coils for Bz + # if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX): + # raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.') + # else: # checks limits of Bx + # if (min_bval< -BX_MAX) or (max_bval > BX_MAX): + # raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') + + if '2101014' in instr_info: # single power supply if (min_bval< -BY_MAX) or (max_bval > BY_MAX): raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.') - elif '1' in query_no_echo(instr, 'CHAN?'): # check if its the coils for Bz - if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX): - raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.') - else: # checks limits of Bx - if (min_bval< -BX_MAX) or (max_bval > BX_MAX): - raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') + elif '2301034' in instr_info: # dual power supply + if '1' in query_no_echo(instr, 'CHAN?'): # check if its the coils for Bz + if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX): + raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.') + else: # checks limits of Bx + if (min_bval< -BX_MAX) or (max_bval > BX_MAX): + raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') + else: + raise ConnectionError('Device is not connected!') write_no_echo(instr, f'LLIM {min_bval*10};ULIM {max_bval*10}') # sets the given limits, must convert to kG for the device to read bval_lst = np.arange(min_bval, max_bval + res, res) # creates list of B values to measure at, with given resolution, in T @@ -476,6 +493,8 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, elapsed_time = (end_time - start_time) / 60 print('Scan time: ', elapsed_time, 'minutes') + write_no_echo(instr, f'LLIM {instr_bsettings[1][0]*10};ULIM {instr_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + if zerowhenfin_bool: write_no_echo(instr, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above @@ -560,11 +579,10 @@ experiment_name = f"{set_llim_bval}T_to_{set_ulim_bval}T_{set_res_bval}T_{dateti # perform the B-field measurement for selected axis above # sweep_b_val(powerbox_dualsupply, set_llim_bval, set_ulim_bval, set_res_bval, experiment_settings, experiment_name) sweep_b_val(powerbox_dualsupply, set_llim_bval, set_ulim_bval, set_res_bval, - experiment_settings, experiment_name, singlepowersupply_bool=False, zerowhenfin_bool=True, reversescan_bool=False) + experiment_settings, experiment_name, zerowhenfin_bool=True, reversescan_bool=False) # Internally, axes are numbered 0 to 2 write_no_echo(powerbox_dualsupply, 'LOCAL') # turn off the remote mode # time.sleep(0.5) powerbox_dualsupply.close() - -- 2.39.5 From 1ddd3e96a4f6572beaded9c2bfb0085d7b734d61 Mon Sep 17 00:00:00 2001 From: rtan Date: Mon, 15 Jul 2024 11:41:30 +0200 Subject: [PATCH 02/39] magnet_coil param added. Further mods. to the sweep_b-val func --- 20240709SerdarModScript.py | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index 9f1fce3..4594f2c 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -8,6 +8,7 @@ Lightfield + Positioner # Packages from Ryan import re import pyvisa +import threading # from pyvisa import ResourceManager, constants # B Field Limits (in T) @@ -352,17 +353,20 @@ def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0.01)- print(f"Error communicating with instrument: {e}") # receive values in units of T, rescale in kg to talk with the power supplyy. 1T = 10kG +# NOTE: removed singlepowersupply_bool, reading serial-nr. of the device instead. def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, - res:float, Settings:str, base_file_name='', path_save="C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test", + res:float, magnet_coil:str, Settings:str, base_file_name='', path_save="C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test", reversescan_bool=False, zerowhenfin_bool=False)->None: - """ this function performs a sweep of the B field of the chosen magnet coil. It creates a list o B values from the given min and max values, with the given resolution. For each value, a measurement of the spectrum - of the probe in the cryostat is made, using the LightField spectrometer. + # TODO: update docs in the end + """ this function performs a sweep of the B field of the chosen magnet coil. It creates a list o B values from the given min and max values, + with the given resolution. For each value, a measurement of the spectrum of the probe in the cryostat is made, using the LightField spectrometer. Args: instr (pyvisa.resources.Resource): chosen power supply device to connect to min_bval (float): min B value of the scan (please input in units of Tesla) max_bval (float): max B value of the scan (please input in units of Tesla) res (float): resolution of the list of B values (please input in units of Tesla) + magnet_coil (str): select magnet coil to be used. String should be 'x-axis','y-axis' or 'z-axis'. Settings (str): experiment settings, included in file name. base_file_name (str, optional): base file name. Defaults to ''. path_save (str, optional): file path where the file will be saved. Defaults to "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test". @@ -400,23 +404,26 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, # if (min_bval< -BX_MAX) or (max_bval > BX_MAX): # raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') - if '2101014' in instr_info: # single power supply + if '2101014' in instr_info and (magnet_coil=='y-axis'): # single power supply if (min_bval< -BY_MAX) or (max_bval > BY_MAX): raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.') elif '2301034' in instr_info: # dual power supply - if '1' in query_no_echo(instr, 'CHAN?'): # check if its the coils for Bz + if magnet_coil=='z-axis': # check if its the coils for Bz if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX): raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.') - else: # checks limits of Bx + write_no_echo(instr, 'CHAN 1') + elif magnet_coil=='x-axis': # checks limits of Bx if (min_bval< -BX_MAX) or (max_bval > BX_MAX): raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') + write_no_echo(instr, 'CHAN 2') else: raise ConnectionError('Device is not connected!') write_no_echo(instr, f'LLIM {min_bval*10};ULIM {max_bval*10}') # sets the given limits, must convert to kG for the device to read bval_lst = np.arange(min_bval, max_bval + res, res) # creates list of B values to measure at, with given resolution, in T - init_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # queries the initial B value of the coil, rescale from kG to T + # TODO: unused, see if can remove + # init_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # queries the initial B value of the coil, rescale from kG to T init_lim, subsequent_lim = 'LLIM', 'ULIM' init_sweep, subsequent_sweep = 'DOWN', 'UP' @@ -438,19 +445,13 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, intensity_data = [] # To store data from each scan cwd = os.getcwd() # save original directory - #This gives a directory, in which the script will save the spectrum of each spot as spe - #However, it will open the spectrum, convert it to txt, add it to the intensity_data and delete the spe file #scanning loop for i, bval in enumerate(bval_lst): - # if init_bval == bval: # # if initial bval is equal to the element of the given iteration from the bval_lst, then commence measuring the spectrum # pass # else: - # TODO: improve the conditional block later on... try to shorten the number of conditionals needed/flatten the nested conditionals - # else, travel to the lower or higher limit, depending on how far the init val is to each bound, and commence the measurement from there on - # if not reversescan_bool: if i == 0: # for first iteration, sweep to one of the limits write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG write_no_echo(instr, f'SWEEP {init_sweep}') @@ -533,8 +534,9 @@ powerbox_dualsupply = rm.open_resource('ASRL8::INSTR', write_no_echo(powerbox_dualsupply, 'REMOTE') # turn on the remote mode +# TODO: test functionality of the magnet_coil param later on, should work... as this code below is basically implemented inside the scan func. # select axis for the dual supply, either z-axis(CHAN 1 ^= Supply A) or x-axis(CHAN 2 ^= Supply B) -write_no_echo(powerbox_dualsupply, 'CHAN 1') +# write_no_echo(powerbox_dualsupply, 'CHAN 1') # Setup connection to AMC amc = AMC.Device(IP) @@ -569,16 +571,12 @@ experiment_settings = 'PL_SP_700_LP_700_HeNe_52muW_exp_2s_Start_' #The program adds the range of the scan as well as the resolution and the date and time of the measurement experiment_name = f"{set_llim_bval}T_to_{set_ulim_bval}T_{set_res_bval}T_{datetime.datetime.now().strftime('%Y_%m_%d_%H%M')}" -# # TODO: write the bval scan here -# for idx, bval in enumerate(bval_lst): -# write_no_echo(powerbox_dualsupply, '') - # this moves the probe in xy-direction and measures spectrum there # move_scan_xy(range_x, range_y, resolution, experiment_settings, experiment_name) # perform the B-field measurement for selected axis above # sweep_b_val(powerbox_dualsupply, set_llim_bval, set_ulim_bval, set_res_bval, experiment_settings, experiment_name) -sweep_b_val(powerbox_dualsupply, set_llim_bval, set_ulim_bval, set_res_bval, +sweep_b_val(powerbox_dualsupply, set_llim_bval, set_ulim_bval, set_res_bval, 'z-axis', experiment_settings, experiment_name, zerowhenfin_bool=True, reversescan_bool=False) # Internally, axes are numbered 0 to 2 -- 2.39.5 From c859404a15389b0cfe6b4901f3498b0e3e7f9e01 Mon Sep 17 00:00:00 2001 From: rtan Date: Mon, 15 Jul 2024 16:17:10 +0200 Subject: [PATCH 03/39] added loopscan_bool option, helper function for the scanning loop and implemented the possible loopscan logic conditional in the scanning loop --- 20240709SerdarModScript.py | 75 ++++++++++++++++++++++++++++++++------ 1 file changed, 64 insertions(+), 11 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index 4594f2c..e923049 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -32,6 +32,7 @@ from System import String import numpy as np import matplotlib.pyplot as plt import datetime +from typing import Union #First choose your controller @@ -353,10 +354,11 @@ def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0.01)- print(f"Error communicating with instrument: {e}") # receive values in units of T, rescale in kg to talk with the power supplyy. 1T = 10kG -# NOTE: removed singlepowersupply_bool, reading serial-nr. of the device instead. +# NOTE: removed singlepowersupply_bool, reading serial-nr. of the device instead. +# TODO: add a param to allow the def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, res:float, magnet_coil:str, Settings:str, base_file_name='', path_save="C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test", - reversescan_bool=False, zerowhenfin_bool=False)->None: + reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False)->None: # TODO: update docs in the end """ this function performs a sweep of the B field of the chosen magnet coil. It creates a list o B values from the given min and max values, with the given resolution. For each value, a measurement of the spectrum of the probe in the cryostat is made, using the LightField spectrometer. @@ -380,12 +382,29 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, ValueError: when Bx limit is exceeded. ConnectionError: when no device is connected. """ '''''' + def pyramid_list(lst) -> Union[list, np.ndarray]: + """reverses the list and removes the first element of reversed list. Then, this is appended to + the end of the original list and returned as the 'pyramid' list. + + Args: + lst (list or np.ndarray): + Raises: + TypeError: if the input object isn't a list or np.ndarray + Returns: + Union[list, np.ndarray]: the pyramid list + """ '''''' + if isinstance(lst, list): + return lst + lst[-2::-1] + elif isinstance(lst, np.ndarray): + return np.append(lst, lst[-2::-1]) + else: + raise TypeError('Please input a list!') + if base_file_name =='': base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') start_time = time.time() # start of the scan function - # TODO: queries the serial number of the device, and from there, check the if the input limits exceed the recommended limits instr_info = query_no_echo(instr, '*IDN?') instr_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim @@ -441,18 +460,18 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, init_lim, subsequent_lim = subsequent_lim, init_lim init_sweep, subsequent_sweep = subsequent_sweep, init_sweep + if loopscan_bool: + bval_lst = pyramid_list(bval_lst) + total_points = len(bval_lst) + middle_index_bval_lst = total_points // 2 intensity_data = [] # To store data from each scan cwd = os.getcwd() # save original directory - - #scanning loop - for i, bval in enumerate(bval_lst): - # if init_bval == bval: - # # if initial bval is equal to the element of the given iteration from the bval_lst, then commence measuring the spectrum - # pass - # else: - if i == 0: # for first iteration, sweep to one of the limits + # NOTE: helper function for the scanning loop + def helper_scan_func(idx, bval, instr=instr, init_lim=init_lim, init_sweep=init_sweep, + subsequent_lim=subsequent_lim, subsequent_sweep=subsequent_sweep, sleep=5): + if idx == 0: # for first iteration, sweep to one of the limits write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG write_no_echo(instr, f'SWEEP {init_sweep}') else: @@ -467,6 +486,40 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # update the actual bval print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + + #scanning loop + for i, bval in enumerate(bval_lst): + # if init_bval == bval: + # # if initial bval is equal to the element of the given iteration from the bval_lst, then commence measuring the spectrum + # pass + # else: + + # NOTE: original code without the loop scan + ################################################ + # if i == 0: # for first iteration, sweep to one of the limits + # write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG + # write_no_echo(instr, f'SWEEP {init_sweep}') + # else: + # write_no_echo(instr, f'{subsequent_lim} {bval*10}') # convert back to kG + # write_no_echo(instr, f'SWEEP {subsequent_sweep}') + + # actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # convert kG to T + # print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + + # while abs(actual_bval - bval) > 0.0001: + # time.sleep(5) # little break + # actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 + # # update the actual bval + # print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + ############################################### + if not loopscan_bool: + helper_scan_func(i, bval) + else: + if i <= middle_index_bval_lst: + helper_scan_func(i, bval) + else: + helper_scan_func(i, bval, instr=instr, init_lim=subsequent_lim, init_sweep=subsequent_sweep, + subsequent_lim=init_lim, subsequent_sweep=init_sweep, sleep=5) time.sleep(5) # we acquire with the LF -- 2.39.5 From 87b8908a99188cd2cdb78943208a2600ac5fbf06 Mon Sep 17 00:00:00 2001 From: rtan Date: Tue, 23 Jul 2024 09:10:32 +0200 Subject: [PATCH 04/39] added TODO message, nth more --- 20240709SerdarModScript.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index e923049..292a589 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -567,7 +567,8 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, wl = np.array(loaded_files.wavelength) np.savetxt("Wavelength.txt", wl) - +# TODO: write a function that simultaneously controls the two power supplies. => Threading +# in function head should be func(instr1, instr2, args1, kwargs1, args2, kwargs2) ################################################################# END OF FUNCTION DEFS ########################################################################################### -- 2.39.5 From a566dda4b031af42c9e3f396950c2df49f0917bb Mon Sep 17 00:00:00 2001 From: rtan Date: Tue, 23 Jul 2024 09:45:21 +0200 Subject: [PATCH 05/39] path_save=None default changed --- 20240709SerdarModScript.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index 292a589..4d53971 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -355,9 +355,9 @@ def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0.01)- # receive values in units of T, rescale in kg to talk with the power supplyy. 1T = 10kG # NOTE: removed singlepowersupply_bool, reading serial-nr. of the device instead. -# TODO: add a param to allow the +# old save folder: "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, - res:float, magnet_coil:str, Settings:str, base_file_name='', path_save="C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test", + res:float, magnet_coil:str, Settings:str, base_file_name='', path_save=None, reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False)->None: # TODO: update docs in the end """ this function performs a sweep of the B field of the chosen magnet coil. It creates a list o B values from the given min and max values, @@ -382,6 +382,7 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, ValueError: when Bx limit is exceeded. ConnectionError: when no device is connected. """ '''''' + def pyramid_list(lst) -> Union[list, np.ndarray]: """reverses the list and removes the first element of reversed list. Then, this is appended to the end of the original list and returned as the 'pyramid' list. @@ -400,6 +401,9 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, else: raise TypeError('Please input a list!') + if path_save is None: + path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") + if base_file_name =='': base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') @@ -460,6 +464,7 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, init_lim, subsequent_lim = subsequent_lim, init_lim init_sweep, subsequent_sweep = subsequent_sweep, init_sweep + # creates the pyramid list of B vals if one were to perform a hysteresis measurement if loopscan_bool: bval_lst = pyramid_list(bval_lst) -- 2.39.5 From 0ecbfa12e74c693ad7be795e4357f44c297deb0e Mon Sep 17 00:00:00 2001 From: rtan Date: Wed, 21 Aug 2024 10:58:04 +0200 Subject: [PATCH 06/39] added b_field_rotation --- 20240709SerdarModScript.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index 4d53971..61f70dd 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -7,8 +7,8 @@ Lightfield + Positioner ############################################ # Packages from Ryan import re +from threading import Thread import pyvisa -import threading # from pyvisa import ResourceManager, constants # B Field Limits (in T) @@ -572,8 +572,11 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, wl = np.array(loaded_files.wavelength) np.savetxt("Wavelength.txt", wl) -# TODO: write a function that simultaneously controls the two power supplies. => Threading +# TODO: write a function that simultaneously controls the two power supplies and perform the rotation of the B-field. => Threading # in function head should be func(instr1, instr2, args1, kwargs1, args2, kwargs2) +def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, + Babs:float, startangle:float, endangle:float, angle_stepsize:float, clockwise=True)->None: + pass ################################################################# END OF FUNCTION DEFS ########################################################################################### -- 2.39.5 From 082f99aa0d25d3b3e17d50be61839e2b9212f8a3 Mon Sep 17 00:00:00 2001 From: rtan Date: Wed, 21 Aug 2024 11:00:09 +0200 Subject: [PATCH 07/39] added b_field_rotation --- 20240709SerdarModScript.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index 61f70dd..c9a6624 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -575,7 +575,7 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, # TODO: write a function that simultaneously controls the two power supplies and perform the rotation of the B-field. => Threading # in function head should be func(instr1, instr2, args1, kwargs1, args2, kwargs2) def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, - Babs:float, startangle:float, endangle:float, angle_stepsize:float, clockwise=True)->None: + Babs:float, startangle:float, endangle:float, angle_stepsize:float, clockwise=True, sweepdown=False)->None: pass ################################################################# END OF FUNCTION DEFS ########################################################################################### -- 2.39.5 From 4881f4de3d48af33312333835bce9a5ad07df076 Mon Sep 17 00:00:00 2001 From: rtan Date: Thu, 22 Aug 2024 10:47:10 +0200 Subject: [PATCH 08/39] min_range_list in b rotation added --- 20240709SerdarModScript.py | 79 ++++++++++++++++++++++++++++++++++---- 1 file changed, 71 insertions(+), 8 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index c9a6624..4b8d01b 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -303,7 +303,7 @@ def sep_num_from_units(powerbox_output :str)->list: else: return [powerbox_output,] -def query_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0.01)->str: +def query_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: """helper function for the Attocube APS100 that queries a function to the device, removing the echo. Args: @@ -327,7 +327,7 @@ def query_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0.01)- print(f"Error communicating with instrument: {e}") return None -def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0.01)->str: +def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: """helper function for the Attocube APS100 that writes a function to the device, removing the echo. Args: @@ -572,11 +572,60 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, wl = np.array(loaded_files.wavelength) np.savetxt("Wavelength.txt", wl) + # TODO: write a function that simultaneously controls the two power supplies and perform the rotation of the B-field. => Threading # in function head should be func(instr1, instr2, args1, kwargs1, args2, kwargs2) def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, - Babs:float, startangle:float, endangle:float, angle_stepsize:float, clockwise=True, sweepdown=False)->None: - pass + Babs:float, startangle:float, endangle:float, angle_stepsize:float, path_save:str, base_file_name:str, anticlockwise=True, sweepdown=False)->None: + """_summary_ + + Args: + instr1 (pyvisa.resources.Resource): _description_ + instr2 (pyvisa.resources.Resource): _description_ + Babs (float): absolute B-field value in T + startangle (float): _description_ + endangle (float): _description_ + angle_stepsize (float): _description_ + anticlockwise (bool, optional): _description_. Defaults to True. + sweepdown (bool, optional): _description_. Defaults to False. + """ + if path_save is None: + path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") # TODO: add path_save, base_file_name in the function header + + if base_file_name =='': + base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') + + start_time = time.time() # start of the scan function + + idnstr1 = query_no_echo(instr1, '*IDN?') + + idnstr2 = query_no_echo(instr1, '*IDN?') + + # TODO: find which one is the dual power supply, then, ramp B_x to Babs value + if '2301034' in idnstr1: # serial no. the dual power supply + pass + elif '2101034' in idnstr2: + # swap instruments, instr 1 to be the dual power supply + instr1, instr2 = instr2, instr1 + + # TODO: compare which device has the lower rates, save initial rates lists, then set both devices to the lower rates for each range + # then, set the initial values back + # list of rates (with units) for diff ranges of each device, only up to Range 1 for single power supply as that is already + # the max recommended current. + init_range_lst1 = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'RATE? 0;RATE? 1;RATE? 2').split(';')) + init_range_lst2 = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'RATE? 0;RATE? 1').split(';')) + + min_range_lst = [min(el1[0], el2[0]) for el1,el2 in zip(init_range_lst1, init_range_lst2)] # min rates for each given range + + write_no_echo(instr1, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + + # TODO: check the device rates and ranges in the lab tmrw or friday + + write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit + + # TODO: include the functionalities located in the function above, update function header with the new parameters of path_save, base_file_name + ################################################################# END OF FUNCTION DEFS ########################################################################################### @@ -584,17 +633,29 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # Initialise PYVISA ResourceManager rm = pyvisa.ResourceManager() -# print(rm.list_resources()) # 'ASRL8::INSTR' for dual power supply, 'ASRL9::INSTR' for single power supply +# print(rm.list_resources()) +# 'ASRL8::INSTR' for dual power supply, 'ASRL9::INSTR' for single power supply (online PC) +# 'ASRL10::INSTR' for dual power supply, 'ASRL12::INSTR' for single power supply (offline PC) + # Open the connection with the APS100 dual power supply -powerbox_dualsupply = rm.open_resource('ASRL8::INSTR', - baud_rate=9600, # Example baud rate, adjust as needed +powerbox_dualsupply = rm.open_resource('ASRL10::INSTR', + baud_rate=9600, data_bits=8, parity= pyvisa.constants.Parity.none, stop_bits= pyvisa.constants.StopBits.one, - timeout=5000)# 5000 ms timeout + timeout=100)# 5000 ms timeout + +# Open the connection with the APS100 dual power supply +powerbox_singlesupply = rm.open_resource('ASRL12::INSTR', + baud_rate=9600, + data_bits=8, + parity= pyvisa.constants.Parity.none, + stop_bits= pyvisa.constants.StopBits.one, + timeout=100)# 5000 ms timeout write_no_echo(powerbox_dualsupply, 'REMOTE') # turn on the remote mode +write_no_echo(powerbox_singlesupply, 'REMOTE') # turn on the remote mode # TODO: test functionality of the magnet_coil param later on, should work... as this code below is basically implemented inside the scan func. # select axis for the dual supply, either z-axis(CHAN 1 ^= Supply A) or x-axis(CHAN 2 ^= Supply B) @@ -644,5 +705,7 @@ sweep_b_val(powerbox_dualsupply, set_llim_bval, set_ulim_bval, set_res_bval, 'z- # Internally, axes are numbered 0 to 2 write_no_echo(powerbox_dualsupply, 'LOCAL') # turn off the remote mode +write_no_echo(powerbox_singlesupply, 'LOCAL') # turn off the remote mode # time.sleep(0.5) powerbox_dualsupply.close() +powerbox_singlesupply.close() \ No newline at end of file -- 2.39.5 From 0c21e935edeff9ba4ef70986ee104d7d15941378 Mon Sep 17 00:00:00 2001 From: rtan Date: Fri, 23 Aug 2024 09:49:39 +0200 Subject: [PATCH 09/39] addition of create_discrete_b_field_list, progress on b_field_rotation --- 20240709SerdarModScript.py | 128 ++++++++++++++++++++++++++++++++----- 1 file changed, 113 insertions(+), 15 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index 4b8d01b..9897f88 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -7,6 +7,7 @@ Lightfield + Positioner ############################################ # Packages from Ryan import re +import math from threading import Thread import pyvisa # from pyvisa import ResourceManager, constants @@ -303,6 +304,7 @@ def sep_num_from_units(powerbox_output :str)->list: else: return [powerbox_output,] + def query_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: """helper function for the Attocube APS100 that queries a function to the device, removing the echo. @@ -327,6 +329,7 @@ def query_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->st print(f"Error communicating with instrument: {e}") return None + def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: """helper function for the Attocube APS100 that writes a function to the device, removing the echo. @@ -353,11 +356,12 @@ def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->st except pyvisa.VisaIOError as e: print(f"Error communicating with instrument: {e}") + # receive values in units of T, rescale in kg to talk with the power supplyy. 1T = 10kG # NOTE: removed singlepowersupply_bool, reading serial-nr. of the device instead. # old save folder: "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, - res:float, magnet_coil:str, Settings:str, base_file_name='', path_save=None, + res:float, magnet_coil:str, Settings:str, base_file_name='', path_save='', reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False)->None: # TODO: update docs in the end """ this function performs a sweep of the B field of the chosen magnet coil. It creates a list o B values from the given min and max values, @@ -401,7 +405,7 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, else: raise TypeError('Please input a list!') - if path_save is None: + if path_save =='': path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") if base_file_name =='': @@ -573,34 +577,114 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, np.savetxt("Wavelength.txt", wl) +def create_discrete_b_field_list(radius, start_angle, end_angle, step_size): + # TODO: docs + """_summary_ + + Args: + radius (_type_): _description_ + start_angle (_type_): _description_ + end_angle (_type_): _description_ + step_size (_type_): _description_ + + Returns: + _type_: _description_ + """ """""" + # Initialize lists to hold angles and (x, y) pairs + angles = [] + coordinates = [] + + # Normalize angles to the range [0, 360) + start_angle = start_angle % 360 + end_angle = end_angle % 360 + + # Calculate the clockwise and counterclockwise differences + clockwise_diff = (start_angle - end_angle) % 360 + counterclockwise_diff = (end_angle - start_angle) % 360 + + # Determine the shorter path + if clockwise_diff <= counterclockwise_diff: + # Clockwise is shorter + current_angle = start_angle + while current_angle >= end_angle: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle + if (current_angle ) % 360 == end_angle: + break + + # Decrement the current angle by the step size + current_angle -= step_size + else: + # Counterclockwise is shorter + current_angle = start_angle + while current_angle <= end_angle: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle + if (current_angle ) % 360 == end_angle: + break + + # Increment the current angle by the step size + current_angle += step_size + + return [angles, coordinates] + + # TODO: write a function that simultaneously controls the two power supplies and perform the rotation of the B-field. => Threading # in function head should be func(instr1, instr2, args1, kwargs1, args2, kwargs2) def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, - Babs:float, startangle:float, endangle:float, angle_stepsize:float, path_save:str, base_file_name:str, anticlockwise=True, sweepdown=False)->None: - """_summary_ + Babs:float, startangle:float, endangle:float, angle_stepsize:float, path_save='', base_file_name='', sweepdown=False)->None: + """Rotation of the b-field in discrete steps, spectrum is measured at each discrete step in the rotation. Scan angle is + defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. Args: instr1 (pyvisa.resources.Resource): _description_ instr2 (pyvisa.resources.Resource): _description_ Babs (float): absolute B-field value in T - startangle (float): _description_ - endangle (float): _description_ - angle_stepsize (float): _description_ - anticlockwise (bool, optional): _description_. Defaults to True. - sweepdown (bool, optional): _description_. Defaults to False. + startangle (float): start angle in degrees + endangle (float): end angle in degrees + angle_stepsize (float): angle step size in degrees + sweepdown (bool, optional): after finishing the rotation, both B-field components should be set to 0 T. Defaults to False. """ - if path_save is None: + if path_save =='': path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") # TODO: add path_save, base_file_name in the function header - if base_file_name =='': base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') start_time = time.time() # start of the scan function - idnstr1 = query_no_echo(instr1, '*IDN?') + startangle = startangle % 360 + endangle = endangle % 360 # ensures that the angles are within [0,360) + idnstr1 = query_no_echo(instr1, '*IDN?') idnstr2 = query_no_echo(instr1, '*IDN?') + intensity_data = [] # To store data from each scan + cwd = os.getcwd() # save original directory + # TODO: find which one is the dual power supply, then, ramp B_x to Babs value if '2301034' in idnstr1: # serial no. the dual power supply pass @@ -608,6 +692,20 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # swap instruments, instr 1 to be the dual power supply instr1, instr2 = instr2, instr1 + # initialise the sweep angle list as well as the sweep limits and directions for each instrument + instr1_lim, instr2_lim = 'LLIM', 'ULIM' + instr1_sweep, instr2_sweep = 'DOWN', 'UP' + angles_lst = np.arange(startangle, endangle + angle_stepsize, angle_stepsize) # TODO: check to see if this considers 0° crossover or not + # TODO: this does not consider 0° crossover, try to fix + anticlockwise_bool = True + + if startangle > endangle: + # reverse list of angles, as well as the sweep limits and directions, for clockwise rotation + angles_lst = np.arange(startangle, endangle - angle_stepsize, - angle_stepsize) + instr1_lim, instr2_lim = instr2_lim, instr1_lim + instr1_sweep, instr2_sweep = instr2_sweep, instr1_sweep + anticlockwise_bool = False + # TODO: compare which device has the lower rates, save initial rates lists, then set both devices to the lower rates for each range # then, set the initial values back # list of rates (with units) for diff ranges of each device, only up to Range 1 for single power supply as that is already @@ -617,14 +715,14 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R min_range_lst = [min(el1[0], el2[0]) for el1,el2 in zip(init_range_lst1, init_range_lst2)] # min rates for each given range + # set both devices to the min rates write_no_echo(instr1, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') - # TODO: check the device rates and ranges in the lab tmrw or friday - write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit + print(f'SWEEPING B-X TO {Babs} T NOW') + - # TODO: include the functionalities located in the function above, update function header with the new parameters of path_save, base_file_name ################################################################# END OF FUNCTION DEFS ########################################################################################### -- 2.39.5 From 6efedda662eee2bf8dff388aa40a8d772691df23 Mon Sep 17 00:00:00 2001 From: rtan Date: Fri, 23 Aug 2024 10:04:13 +0200 Subject: [PATCH 10/39] renaming of the function that transform discrete polar coords to discrete cartesian coords --- 20240709SerdarModScript.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index 9897f88..2709b28 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -577,7 +577,7 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, np.savetxt("Wavelength.txt", wl) -def create_discrete_b_field_list(radius, start_angle, end_angle, step_size): +def polar_to_cartesian(radius, start_angle, end_angle, step_size): # TODO: docs """_summary_ -- 2.39.5 From 5c01110ce5baf8edd1eacfb37a8976bd5414ad12 Mon Sep 17 00:00:00 2001 From: rtan Date: Tue, 27 Aug 2024 15:51:24 +0200 Subject: [PATCH 11/39] FIXED:C bug polar_to_cartesian --- 20240709SerdarModScript.py | 149 +++++++++++++++++++++++++++++++------ 1 file changed, 125 insertions(+), 24 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index 2709b28..1c83686 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -576,9 +576,83 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, wl = np.array(loaded_files.wavelength) np.savetxt("Wavelength.txt", wl) +# TODO: old function, DELETE LATER +# def polar_to_cartesian(radius, start_angle, end_angle, step_size): +# """_summary_ -def polar_to_cartesian(radius, start_angle, end_angle, step_size): - # TODO: docs +# Args: +# radius (_type_): _description_ +# start_angle (_type_): _description_ +# end_angle (_type_): _description_ +# step_size (_type_): _description_ + +# Returns: +# _type_: _description_ +# """ """""" +# # Initialize lists to hold angles and (x, y) pairs +# angles = [] +# coordinates = [] + +# # Normalize angles to the range [0, 360) +# start_angle = start_angle % 360 +# end_angle = end_angle % 360 + +# # Calculate the clockwise and counterclockwise differences +# clockwise_diff = (start_angle - end_angle) % 360 +# counterclockwise_diff = (end_angle - start_angle) % 360 + +# # Determine the shorter path +# if clockwise_diff <= counterclockwise_diff: +# # Clockwise is shorter +# current_angle = start_angle +# while current_angle >= end_angle: +# # Append the current angle to the angles list +# angles.append(current_angle % 360) + +# # Convert the current angle to radians +# current_angle_rad = math.radians(current_angle % 360) + +# # Convert polar to Cartesian coordinates +# x = radius * math.cos(current_angle_rad) +# y = radius * math.sin(current_angle_rad) + +# # Append the (x, y) pair to the list +# coordinates.append((x, y)) + +# # Check if we've reached the end_angle +# if (current_angle ) % 360 == end_angle: +# break + +# # Decrement the current angle by the step size +# current_angle -= step_size +# else: +# # Counterclockwise is shorter +# current_angle = start_angle +# while current_angle <= end_angle: +# # Append the current angle to the angles list +# angles.append(current_angle % 360) + +# # Convert the current angle to radians +# current_angle_rad = math.radians(current_angle % 360) + +# # Convert polar to Cartesian coordinates +# x = radius * math.cos(current_angle_rad) +# y = radius * math.sin(current_angle_rad) + +# # Append the (x, y) pair to the list +# coordinates.append((x, y)) + +# # Check if we've reached the end_angle +# if (current_angle ) % 360 == end_angle: +# break + +# # Increment the current angle by the step size +# current_angle += step_size + +# return [angles, coordinates] + +def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True): + # TODO: DOCS """_summary_ Args: @@ -586,6 +660,7 @@ def polar_to_cartesian(radius, start_angle, end_angle, step_size): start_angle (_type_): _description_ end_angle (_type_): _description_ step_size (_type_): _description_ + clockwise (bool, optional): _description_. Defaults to True. Returns: _type_: _description_ @@ -598,15 +673,10 @@ def polar_to_cartesian(radius, start_angle, end_angle, step_size): start_angle = start_angle % 360 end_angle = end_angle % 360 - # Calculate the clockwise and counterclockwise differences - clockwise_diff = (start_angle - end_angle) % 360 - counterclockwise_diff = (end_angle - start_angle) % 360 - - # Determine the shorter path - if clockwise_diff <= counterclockwise_diff: - # Clockwise is shorter + if clockwise: + # Clockwise rotation current_angle = start_angle - while current_angle >= end_angle: + while True: # Append the current angle to the angles list angles.append(current_angle % 360) @@ -620,16 +690,18 @@ def polar_to_cartesian(radius, start_angle, end_angle, step_size): # Append the (x, y) pair to the list coordinates.append((x, y)) - # Check if we've reached the end_angle - if (current_angle ) % 360 == end_angle: + # Check if we've reached the end_angle (handling wrap-around) (current_angle - step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: break # Decrement the current angle by the step size current_angle -= step_size + if current_angle < 0: + current_angle += 360 else: - # Counterclockwise is shorter + # Counterclockwise rotation current_angle = start_angle - while current_angle <= end_angle: + while True: # Append the current angle to the angles list angles.append(current_angle % 360) @@ -643,12 +715,14 @@ def polar_to_cartesian(radius, start_angle, end_angle, step_size): # Append the (x, y) pair to the list coordinates.append((x, y)) - # Check if we've reached the end_angle - if (current_angle ) % 360 == end_angle: + # Check if we've reached the end_angle (handling wrap-around) (current_angle + step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: break # Increment the current angle by the step size current_angle += step_size + if current_angle >= 360: + current_angle -= 360 return [angles, coordinates] @@ -695,19 +769,13 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # initialise the sweep angle list as well as the sweep limits and directions for each instrument instr1_lim, instr2_lim = 'LLIM', 'ULIM' instr1_sweep, instr2_sweep = 'DOWN', 'UP' - angles_lst = np.arange(startangle, endangle + angle_stepsize, angle_stepsize) # TODO: check to see if this considers 0° crossover or not - # TODO: this does not consider 0° crossover, try to fix - anticlockwise_bool = True + angles, cartesian_coords = polar_to_cartesian(Babs, startangle, endangle, angle_stepsize) # create if startangle > endangle: - # reverse list of angles, as well as the sweep limits and directions, for clockwise rotation - angles_lst = np.arange(startangle, endangle - angle_stepsize, - angle_stepsize) + # reverse sweep limits and directions for the clockwise rotation instr1_lim, instr2_lim = instr2_lim, instr1_lim instr1_sweep, instr2_sweep = instr2_sweep, instr1_sweep - anticlockwise_bool = False - # TODO: compare which device has the lower rates, save initial rates lists, then set both devices to the lower rates for each range - # then, set the initial values back # list of rates (with units) for diff ranges of each device, only up to Range 1 for single power supply as that is already # the max recommended current. init_range_lst1 = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'RATE? 0;RATE? 1;RATE? 2').split(';')) @@ -722,8 +790,41 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit print(f'SWEEPING B-X TO {Babs} T NOW') + # wait for Babs to be reached by the Bx field + actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') + while abs(actual_bval - Babs) > 0.0001: + time.sleep(5) # little break + actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 + print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') + # TODO: begin the rotation of the B-field, saving the spectrum for each angle, including the start- and end angles + # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN + # TODO: polar_to_cartesian does not work when the angle is 0°!!!! fix bug + # TODO: write the for loop for the rotation here + for idx, angle in enumerate(angles): + pass + + # # we acquire with the LF + # acquire_name_spe = f'{base_file_name}_{bval}T' + # AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + # # read the .spe file and get the data as loaded_files + # cwd = os.getcwd() # save original directory + # os.chdir(path_save) #change directory + # loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + # os.chdir(cwd) # go back to original directory + + # # Delete the created .spe file from acquiring after getting necessary info + # spe_file_path = os.path.join(path_save, acquire_name_spe + '.spe') + # os.remove(spe_file_path) + + # points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT + # print('Points left in the scan: ', points_left) + + # #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + # intensity_data.append(loaded_files.data[0][0][0]) ################################################################# END OF FUNCTION DEFS ########################################################################################### -- 2.39.5 From 080ce6b1e6bce2f03e6f71e1ecf76a5f11a8eb52 Mon Sep 17 00:00:00 2001 From: rtan Date: Tue, 27 Aug 2024 16:17:45 +0200 Subject: [PATCH 12/39] b_field_rotation: more bug fixes and progress --- 20240709SerdarModScript.py | 99 ++++++-------------------------------- 1 file changed, 15 insertions(+), 84 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index 1c83686..ce8f9e7 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -576,84 +576,11 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, wl = np.array(loaded_files.wavelength) np.savetxt("Wavelength.txt", wl) -# TODO: old function, DELETE LATER -# def polar_to_cartesian(radius, start_angle, end_angle, step_size): -# """_summary_ - -# Args: -# radius (_type_): _description_ -# start_angle (_type_): _description_ -# end_angle (_type_): _description_ -# step_size (_type_): _description_ - -# Returns: -# _type_: _description_ -# """ """""" -# # Initialize lists to hold angles and (x, y) pairs -# angles = [] -# coordinates = [] - -# # Normalize angles to the range [0, 360) -# start_angle = start_angle % 360 -# end_angle = end_angle % 360 - -# # Calculate the clockwise and counterclockwise differences -# clockwise_diff = (start_angle - end_angle) % 360 -# counterclockwise_diff = (end_angle - start_angle) % 360 - -# # Determine the shorter path -# if clockwise_diff <= counterclockwise_diff: -# # Clockwise is shorter -# current_angle = start_angle -# while current_angle >= end_angle: -# # Append the current angle to the angles list -# angles.append(current_angle % 360) - -# # Convert the current angle to radians -# current_angle_rad = math.radians(current_angle % 360) - -# # Convert polar to Cartesian coordinates -# x = radius * math.cos(current_angle_rad) -# y = radius * math.sin(current_angle_rad) - -# # Append the (x, y) pair to the list -# coordinates.append((x, y)) - -# # Check if we've reached the end_angle -# if (current_angle ) % 360 == end_angle: -# break - -# # Decrement the current angle by the step size -# current_angle -= step_size -# else: -# # Counterclockwise is shorter -# current_angle = start_angle -# while current_angle <= end_angle: -# # Append the current angle to the angles list -# angles.append(current_angle % 360) - -# # Convert the current angle to radians -# current_angle_rad = math.radians(current_angle % 360) - -# # Convert polar to Cartesian coordinates -# x = radius * math.cos(current_angle_rad) -# y = radius * math.sin(current_angle_rad) - -# # Append the (x, y) pair to the list -# coordinates.append((x, y)) - -# # Check if we've reached the end_angle -# if (current_angle ) % 360 == end_angle: -# break - -# # Increment the current angle by the step size -# current_angle += step_size - -# return [angles, coordinates] def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True): # TODO: DOCS - """_summary_ + """Creates a list of discrete cartesian coordinates (x,y), given the radius, start- and end angles, the angle step size, and the direction of rotation. + Function then returns a list of two lists: list of angles and list of cartesian coordinates (x,y coordinates in a tuple). Args: radius (_type_): _description_ @@ -730,7 +657,8 @@ def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True # TODO: write a function that simultaneously controls the two power supplies and perform the rotation of the B-field. => Threading # in function head should be func(instr1, instr2, args1, kwargs1, args2, kwargs2) def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, - Babs:float, startangle:float, endangle:float, angle_stepsize:float, path_save='', base_file_name='', sweepdown=False)->None: + Babs:float, startangle:float, endangle:float, angle_stepsize:float, clockwise=True, path_save='', base_file_name='', sweepdown=False)->None: + # TODO: update docs """Rotation of the b-field in discrete steps, spectrum is measured at each discrete step in the rotation. Scan angle is defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. @@ -740,9 +668,14 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R Babs (float): absolute B-field value in T startangle (float): start angle in degrees endangle (float): end angle in degrees - angle_stepsize (float): angle step size in degrees + angle_stepsize (float): angle step size in degrees + clockwise (bool): determines the direction of rotation of the B-field. Defaults to True. sweepdown (bool, optional): after finishing the rotation, both B-field components should be set to 0 T. Defaults to False. """ + + def wait_for_b_val_helper_func(instr,): + pass + if path_save =='': path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") # TODO: add path_save, base_file_name in the function header if base_file_name =='': @@ -763,15 +696,15 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R if '2301034' in idnstr1: # serial no. the dual power supply pass elif '2101034' in idnstr2: - # swap instruments, instr 1 to be the dual power supply + # swap instruments, instr 1 to be the dual power supply (^= x-axis) instr1, instr2 = instr2, instr1 # initialise the sweep angle list as well as the sweep limits and directions for each instrument instr1_lim, instr2_lim = 'LLIM', 'ULIM' instr1_sweep, instr2_sweep = 'DOWN', 'UP' - angles, cartesian_coords = polar_to_cartesian(Babs, startangle, endangle, angle_stepsize) # create + angles, cartesian_coords = polar_to_cartesian(Babs, startangle, endangle, angle_stepsize, clockwise=clockwise) # create lists of angles and discrete Cartesian coordinates - if startangle > endangle: + if clockwise: # NOTE: old conditional was: startangle > endangle see if this works.... # reverse sweep limits and directions for the clockwise rotation instr1_lim, instr2_lim = instr2_lim, instr1_lim instr1_sweep, instr2_sweep = instr2_sweep, instr1_sweep @@ -800,12 +733,10 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # TODO: begin the rotation of the B-field, saving the spectrum for each angle, including the start- and end angles # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN - # TODO: polar_to_cartesian does not work when the angle is 0°!!!! fix bug - - # TODO: write the for loop for the rotation here + # bug fix for polar_to_cartesian (27.08.2024, 15:52 hrs) + # TODO: write the for loop for the rotation here, implement threading => create a helper function to enter into the threads for idx, angle in enumerate(angles): pass - # # we acquire with the LF # acquire_name_spe = f'{base_file_name}_{bval}T' # AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. -- 2.39.5 From 54a2948d0b49f7f839bf0ae379344aa5a9e0e59b Mon Sep 17 00:00:00 2001 From: rtan Date: Wed, 28 Aug 2024 12:53:28 +0200 Subject: [PATCH 13/39] progreess on b_field_rotation; TODO: finish the tail end of the func, copy from b_val_sweep --- 20240709SerdarModScript.py | 112 +++++++++++++++++++++++++++---------- 1 file changed, 84 insertions(+), 28 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index ce8f9e7..935f1e5 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -8,7 +8,7 @@ Lightfield + Positioner # Packages from Ryan import re import math -from threading import Thread +import threading import pyvisa # from pyvisa import ResourceManager, constants @@ -672,9 +672,6 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R clockwise (bool): determines the direction of rotation of the B-field. Defaults to True. sweepdown (bool, optional): after finishing the rotation, both B-field components should be set to 0 T. Defaults to False. """ - - def wait_for_b_val_helper_func(instr,): - pass if path_save =='': path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") # TODO: add path_save, base_file_name in the function header @@ -702,7 +699,9 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # initialise the sweep angle list as well as the sweep limits and directions for each instrument instr1_lim, instr2_lim = 'LLIM', 'ULIM' instr1_sweep, instr2_sweep = 'DOWN', 'UP' - angles, cartesian_coords = polar_to_cartesian(Babs, startangle, endangle, angle_stepsize, clockwise=clockwise) # create lists of angles and discrete Cartesian coordinates + + # create lists of angles and discrete Cartesian coordinates + angles, cartesian_coords = polar_to_cartesian(Babs, startangle, endangle, angle_stepsize, clockwise=clockwise) if clockwise: # NOTE: old conditional was: startangle > endangle see if this works.... # reverse sweep limits and directions for the clockwise rotation @@ -733,29 +732,86 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # TODO: begin the rotation of the B-field, saving the spectrum for each angle, including the start- and end angles # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN - # bug fix for polar_to_cartesian (27.08.2024, 15:52 hrs) - # TODO: write the for loop for the rotation here, implement threading => create a helper function to enter into the threads - for idx, angle in enumerate(angles): - pass - # # we acquire with the LF - # acquire_name_spe = f'{base_file_name}_{bval}T' - # AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. - - # # read the .spe file and get the data as loaded_files - # cwd = os.getcwd() # save original directory - # os.chdir(path_save) #change directory - # loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable - # os.chdir(cwd) # go back to original directory - - # # Delete the created .spe file from acquiring after getting necessary info - # spe_file_path = os.path.join(path_save, acquire_name_spe + '.spe') - # os.remove(spe_file_path) - - # points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT - # print('Points left in the scan: ', points_left) - - # #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) - # intensity_data.append(loaded_files.data[0][0][0]) + # TODO: define the helper functions for threading here, write the commented code inside this function and call the function below + the other + # functionalities in b_val_sweep later on.... + # SEE ThreadTest2.py for the helper functions + # Helper function that listens to a device + def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event): + while not all_targets_met_event.is_set(): # Loop until the event is set + # value = 0 # Simulate receiving a float from the device INSERT QUERY NO ECHO HERE TO ASK FOR DEVICE IMAG + if '2301034' in device_id: + value = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + elif '2101014' in device_id: + value = sep_num_from_units(query_no_echo(instr2, 'IMAG?'))[0]*0.1 # convert kG to T + print(f"Device {device_id} reports value: {value} T") + + with lock: + shared_values[device_id] = value + # Check if both devices have met their targets + if all(shared_values.get(device) is not None and abs(shared_values[device] - target_value[device]) <= 0.0001 + for device in shared_values): # TODO: MODIFY THE IF CONDITIONAL HERE TO THAT IN B VAL SWEEP + print(f"Both devices reached their target values: {shared_values}") + all_targets_met_event.set() # Signal that both targets are met + + # time.sleep(1) # Simulate periodic data checking + + # Main function to manage threads and iterate over target values + def monitor_devices(device_target_values, angles_lst): + for iteration, target in enumerate(device_target_values): + print(f"\nStarting iteration {iteration+1} for target values: {target}") + # Shared dictionary to store values from devices + shared_values = {device: None for device in target.keys()} + # Event to signal when both target values are reached + all_targets_met_event = threading.Event() + + # Lock to synchronize access to shared_values + lock = threading.Lock() + + # Create and start threads for each device + threads = [] + for device_id in target.keys(): + thread = threading.Thread(target=listen_to_device, args=(device_id, target, shared_values, lock, all_targets_met_event)) + threads.append(thread) + thread.start() + + # Wait until both devices meet their target values + all_targets_met_event.wait() + print(f"Both target values for iteration {iteration+1} met. Performing action...") + + # Perform some action after both targets are met + # we acquire with the LF + acquire_name_spe = f'{base_file_name}_{angles_lst[iteration]}°' # NOTE: save each intensity file with the given angle + AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + # read the .spe file and get the data as loaded_files + cwd = os.getcwd() # save original directory + os.chdir(path_save) #change directory + loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + os.chdir(cwd) # go back to original directory + + # Delete the created .spe file from acquiring after getting necessary info + spe_file_path = os.path.join(path_save, acquire_name_spe + '.spe') + os.remove(spe_file_path) + + # points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT + # print('Points left in the scan: ', points_left) + + #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + intensity_data.append(loaded_files.data[0][0][0]) + + # Clean up threads + for thread in threads: + thread.join() + + print(f"Threads for iteration {iteration+1} closed.\n") + + # modify cartesian_coords to suite the required data struct in monitor_devices + cartesian_coords = [{'2301034': t[0], '2101014': t[1]} for t in cartesian_coords] + + monitor_devices(cartesian_coords, angles) + + # TODO: add the end functionalities for saving the intensity data (see b-val_sweep), modify if necessary + # SEE LINES 554 TO 577 in code (version on 28.08.2024, 12.49 hrs) ################################################################# END OF FUNCTION DEFS ########################################################################################### -- 2.39.5 From 4450fd1e769919f232341e8b1f5bcdab03a5fcd6 Mon Sep 17 00:00:00 2001 From: ryantan Date: Fri, 30 Aug 2024 12:04:17 +0200 Subject: [PATCH 14/39] Finished b_field_rotation --- 20240709SerdarModScript.py | 64 +++++++++++++++++++++++++++++--------- 1 file changed, 50 insertions(+), 14 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index 935f1e5..df19bb9 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -415,7 +415,7 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, instr_info = query_no_echo(instr, '*IDN?') - instr_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + instr_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element list of lists containing the set unit, llim and ulim if instr_bsettings[0][0] == 'T': instr_bsettings[1][0] = instr_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T @@ -654,10 +654,8 @@ def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True return [angles, coordinates] -# TODO: write a function that simultaneously controls the two power supplies and perform the rotation of the B-field. => Threading -# in function head should be func(instr1, instr2, args1, kwargs1, args2, kwargs2) def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, - Babs:float, startangle:float, endangle:float, angle_stepsize:float, clockwise=True, path_save='', base_file_name='', sweepdown=False)->None: + Babs:float, startangle:float, endangle:float, angle_stepsize:float, Settings:str, clockwise=True, path_save='', base_file_name='', zerowhenfin_bool=False)->None: # TODO: update docs """Rotation of the b-field in discrete steps, spectrum is measured at each discrete step in the rotation. Scan angle is defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. @@ -670,11 +668,12 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R endangle (float): end angle in degrees angle_stepsize (float): angle step size in degrees clockwise (bool): determines the direction of rotation of the B-field. Defaults to True. - sweepdown (bool, optional): after finishing the rotation, both B-field components should be set to 0 T. Defaults to False. + zerowhenfin_bool (bool, optional): after finishing the rotation, both B-field components should be set to 0 T. Defaults to False. """ + # TODO: possibly rename instr1 and instr2 to the dual and single power supplies respectively?? if path_save =='': - path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") # TODO: add path_save, base_file_name in the function header + path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") if base_file_name =='': base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') @@ -689,12 +688,22 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R intensity_data = [] # To store data from each scan cwd = os.getcwd() # save original directory - # TODO: find which one is the dual power supply, then, ramp B_x to Babs value + # find which one is the dual power supply, then, ramp B_x to Babs value if '2301034' in idnstr1: # serial no. the dual power supply pass elif '2101034' in idnstr2: # swap instruments, instr 1 to be the dual power supply (^= x-axis) instr1, instr2 = instr2, instr1 + + # save initial low and high sweep limits of each device, and set them back after the rotation + instr1_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + instr2_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + if instr1_bsettings[0][0] == 'T': + instr1_bsettings[1][0] = instr1_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr1_bsettings[2][0] = instr1_bsettings[2][0]*0.1 + if instr2_bsettings[0][0] == 'T': + instr2_bsettings[1][0] = instr2_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr2_bsettings[2][0] = instr2_bsettings[2][0]*0.1 # initialise the sweep angle list as well as the sweep limits and directions for each instrument instr1_lim, instr2_lim = 'LLIM', 'ULIM' @@ -730,11 +739,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') - # TODO: begin the rotation of the B-field, saving the spectrum for each angle, including the start- and end angles # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN - # TODO: define the helper functions for threading here, write the commented code inside this function and call the function below + the other - # functionalities in b_val_sweep later on.... - # SEE ThreadTest2.py for the helper functions # Helper function that listens to a device def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event): while not all_targets_met_event.is_set(): # Loop until the event is set @@ -749,7 +754,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R shared_values[device_id] = value # Check if both devices have met their targets if all(shared_values.get(device) is not None and abs(shared_values[device] - target_value[device]) <= 0.0001 - for device in shared_values): # TODO: MODIFY THE IF CONDITIONAL HERE TO THAT IN B VAL SWEEP + for device in shared_values): print(f"Both devices reached their target values: {shared_values}") all_targets_met_event.set() # Signal that both targets are met @@ -804,14 +809,45 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R thread.join() print(f"Threads for iteration {iteration+1} closed.\n") + + #prints total time the mapping lasted + end_time = time.time() + elapsed_time = (end_time - start_time) / 60 + print('Scan time: ', elapsed_time, 'minutes') + + # reset both devices to original sweep limits + write_no_echo(instr1, f'LLIM {instr1_bsettings[1][0]*10};ULIM {instr1_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'LLIM {instr2_bsettings[1][0]*10};ULIM {instr2_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + # reset both devices' initial rates for each range + write_no_echo(instr1, f'RANGE 0 {init_range_lst1[0][0]};RANGE 1 {init_range_lst1[1][0]};RANGE 2 {init_range_lst1[2][0]}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'RANGE 0 {init_range_lst2[0][0]};RANGE 1 {init_range_lst2[1][0]}') # reset the initial limits of the device after the scan + + if zerowhenfin_bool: + write_no_echo(instr1, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above + write_no_echo(instr2, 'SWEEP ZERO') + + #save intensity & WL data as .txt + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas') + # creates new folder for MAP data + new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + os.mkdir(new_folder_name) + # Here the things will be saved in a new folder under user Lukas ! + # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name) + + intensity_data = np.array(intensity_data) + np.savetxt(Settings + f'{angles[0]}°_to_{angles[-1]}°' + experiment_name +'.txt', intensity_data) + # TODO: remove/edit experiment_name in line above, as well in sweep_b_val func, rn takes a global variable below + + wl = np.array(loaded_files.wavelength) + np.savetxt("Wavelength.txt", wl) # modify cartesian_coords to suite the required data struct in monitor_devices cartesian_coords = [{'2301034': t[0], '2101014': t[1]} for t in cartesian_coords] + # call the helper function to carry out the rotation/measurement of spectrum monitor_devices(cartesian_coords, angles) - # TODO: add the end functionalities for saving the intensity data (see b-val_sweep), modify if necessary - # SEE LINES 554 TO 577 in code (version on 28.08.2024, 12.49 hrs) ################################################################# END OF FUNCTION DEFS ########################################################################################### -- 2.39.5 From e2f92a2faf9b5c1fefcabf2c05f888d29a4568af Mon Sep 17 00:00:00 2001 From: rtan Date: Fri, 6 Sep 2024 11:01:14 +0200 Subject: [PATCH 15/39] first steps on planned changes --- 20240709SerdarModScript.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index df19bb9..fba87e9 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -165,6 +165,9 @@ def move_xy(target_x, target_y): # moving in x and y direction closed to desired # intensity_data = [] # To store data from each scan # data_list = [] +# TODO: change the save file path to be entered as in function header for the following functions: +# move_scan_xy, sweep_b_val, b_field_rotation + def move_scan_xy(range_x, range_y, resolution, Settings, baseFileName): """ This function moves the positioners to scan the sample with desired ranges and resolution in 2 dimensions. @@ -219,9 +222,7 @@ def move_scan_xy(range_x, range_y, resolution, Settings, baseFileName): #this if will make the positioner wait a bit longer to really go to the target. if y == False: move_axis(axis_y, y_positions) - y = True - - + y = True #we acquire with the LF acquire_name_spe = f'{baseFileName}_X{x_positions}_Y{y_positions}' -- 2.39.5 From 15d55f2c9c13a071b747bfa3509f2721e2ca7d89 Mon Sep 17 00:00:00 2001 From: rtan Date: Fri, 6 Sep 2024 11:20:28 +0200 Subject: [PATCH 16/39] Changed var name Path_save -> temp_folder_path; bug fixes for b sweep and b rot --- 20240709SerdarModScript.py | 41 ++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/20240709SerdarModScript.py b/20240709SerdarModScript.py index fba87e9..8fc8beb 100644 --- a/20240709SerdarModScript.py +++ b/20240709SerdarModScript.py @@ -165,8 +165,7 @@ def move_xy(target_x, target_y): # moving in x and y direction closed to desired # intensity_data = [] # To store data from each scan # data_list = [] -# TODO: change the save file path to be entered as in function header for the following functions: -# move_scan_xy, sweep_b_val, b_field_rotation + def move_scan_xy(range_x, range_y, resolution, Settings, baseFileName): """ @@ -210,7 +209,7 @@ def move_scan_xy(range_x, range_y, resolution, Settings, baseFileName): #This gives a directory, in which the script will save the spectrum of each spot as spe #However, it will open the spectrum, convert it to txt, add it to the intensity_data and delete the spe file - Path_save = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" #scanning loop for i, x_positions in enumerate(array_x): @@ -230,12 +229,12 @@ def move_scan_xy(range_x, range_y, resolution, Settings, baseFileName): #read the .spe file and get the data as loaded_files cwd = os.getcwd() # save original directory - os.chdir(Path_save) #change directory + os.chdir(temp_folder_path) #change directory loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable os.chdir(cwd) # go back to original directory # Delete the created .spe file from acquiring after getting necessary info - spe_file_path = os.path.join(Path_save, acquire_name_spe + '.spe') + spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') os.remove(spe_file_path) distance = calculate_distance(x_positions, y_positions,amc.move.getPosition(axis_x), amc.move.getPosition(axis_y)) @@ -362,7 +361,7 @@ def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->st # NOTE: removed singlepowersupply_bool, reading serial-nr. of the device instead. # old save folder: "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, - res:float, magnet_coil:str, Settings:str, base_file_name='', path_save='', + res:float, magnet_coil:str, Settings:str, base_file_name='', reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False)->None: # TODO: update docs in the end """ this function performs a sweep of the B field of the chosen magnet coil. It creates a list o B values from the given min and max values, @@ -376,7 +375,6 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, magnet_coil (str): select magnet coil to be used. String should be 'x-axis','y-axis' or 'z-axis'. Settings (str): experiment settings, included in file name. base_file_name (str, optional): base file name. Defaults to ''. - path_save (str, optional): file path where the file will be saved. Defaults to "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test". singlepowersupply_bool (bool, optional): _description_. Defaults to False. reversescan_bool (bool, optional): _description_. Defaults to False. zerowhenfin_bool (bool, optional): _description_. Defaults to False. @@ -405,9 +403,12 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, return np.append(lst, lst[-2::-1]) else: raise TypeError('Please input a list!') - - if path_save =='': - path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") + + # defines the folder, in which the data from the spectrometer is temporarily stored in + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + + # if path_save =='': + # path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") if base_file_name =='': base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') @@ -538,12 +539,12 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, # read the .spe file and get the data as loaded_files cwd = os.getcwd() # save original directory - os.chdir(path_save) #change directory + os.chdir(temp_folder_path) #change directory loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable os.chdir(cwd) # go back to original directory # Delete the created .spe file from acquiring after getting necessary info - spe_file_path = os.path.join(path_save, acquire_name_spe + '.spe') + spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') os.remove(spe_file_path) points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT @@ -656,7 +657,7 @@ def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, - Babs:float, startangle:float, endangle:float, angle_stepsize:float, Settings:str, clockwise=True, path_save='', base_file_name='', zerowhenfin_bool=False)->None: + Babs:float, startangle:float, endangle:float, angle_stepsize:float, Settings:str, clockwise=True, base_file_name='', zerowhenfin_bool=False)->None: # TODO: update docs """Rotation of the b-field in discrete steps, spectrum is measured at each discrete step in the rotation. Scan angle is defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. @@ -673,8 +674,10 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R """ # TODO: possibly rename instr1 and instr2 to the dual and single power supplies respectively?? - if path_save =='': - path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") + + # defines the folder, in which the data from the spectrometer is temporarily stored in + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + if base_file_name =='': base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') @@ -762,7 +765,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # time.sleep(1) # Simulate periodic data checking # Main function to manage threads and iterate over target values - def monitor_devices(device_target_values, angles_lst): + def monitor_devices(device_target_values, angles_lst, intensity_data=intensity_data): for iteration, target in enumerate(device_target_values): print(f"\nStarting iteration {iteration+1} for target values: {target}") # Shared dictionary to store values from devices @@ -791,12 +794,12 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # read the .spe file and get the data as loaded_files cwd = os.getcwd() # save original directory - os.chdir(path_save) #change directory + os.chdir(temp_folder_path) #change directory loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable os.chdir(cwd) # go back to original directory # Delete the created .spe file from acquiring after getting necessary info - spe_file_path = os.path.join(path_save, acquire_name_spe + '.spe') + spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') os.remove(spe_file_path) # points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT @@ -847,7 +850,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R cartesian_coords = [{'2301034': t[0], '2101014': t[1]} for t in cartesian_coords] # call the helper function to carry out the rotation/measurement of spectrum - monitor_devices(cartesian_coords, angles) + monitor_devices(cartesian_coords, angles, intensity_data) ################################################################# END OF FUNCTION DEFS ########################################################################################### -- 2.39.5 From 78b2aa6ba7fdeac3b8457f230af8e8edb07f4286 Mon Sep 17 00:00:00 2001 From: rtan Date: Mon, 28 Oct 2024 11:43:01 +0100 Subject: [PATCH 17/39] offline PC script added to repository --- AttocubePowerboxScript.py | 935 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 935 insertions(+) create mode 100644 AttocubePowerboxScript.py diff --git a/AttocubePowerboxScript.py b/AttocubePowerboxScript.py new file mode 100644 index 0000000..b3715e9 --- /dev/null +++ b/AttocubePowerboxScript.py @@ -0,0 +1,935 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri Dec 22 15:10:10 2023 +Lightfield + Positioner +@author: Serdar, adjusted by Lukas +""" +############################################ +# Packages from Ryan +import re +import math +import threading +import pyvisa +# from pyvisa import ResourceManager, constants + +# B Field Limits (in T) +BX_MAX = 1.7 +BY_MAX = 1.7 +BZ_MAX = 4.0 +############################################ + +import AMC +import csv +import time +import clr +import sys +import os +import spe2py as spe +import spe_loader as sl +import pandas as pd +import time +from System.IO import * +from System import String +import numpy as np +import matplotlib.pyplot as plt +import datetime +from typing import Union + + +#First choose your controller +IP_AMC300 = "192.168.1.1" +IP_AMC100 = "192.168.71.100" + +# IP = "192.168.1.1" +IP = IP_AMC100 + + +# Import os module +import os, glob, string + +# Import System.IO for saving and opening files +from System.IO import * + +from System.Threading import AutoResetEvent + +# Import C compatible List and String +from System import String +from System.Collections.Generic import List + +# Add needed dll references +sys.path.append(os.environ['LIGHTFIELD_ROOT']) +sys.path.append(os.environ['LIGHTFIELD_ROOT']+"\\AddInViews") +sys.path.append(r'C:\Program Files\Princeton Instruments\LightField\AddInViews') #I added them by hand -serdar +sys.path.append(r'C:\Program Files\Princeton Instruments\LightField') #this one also +clr.AddReference('PrincetonInstruments.LightFieldViewV5') +clr.AddReference('PrincetonInstruments.LightField.AutomationV5') +clr.AddReference('PrincetonInstruments.LightFieldAddInSupportServices') +os.environ['LIGHTFIELD_ROOT'] = r'C:\Program Files\Princeton Instruments\LightField' +# PI imports +from PrincetonInstruments.LightField.Automation import Automation +from PrincetonInstruments.LightField.AddIns import ExperimentSettings +from PrincetonInstruments.LightField.AddIns import CameraSettings +#from PrincetonInstruments.LightField.AddIns import DeviceType +from PrincetonInstruments.LightField.AddIns import SpectrometerSettings +from PrincetonInstruments.LightField.AddIns import RegionOfInterest + +######################################################################################################### code begins from here ############################################# + +def set_custom_ROI(): + + # Get device full dimensions + dimensions = experiment.FullSensorRegion() + + regions = [] + + # Add two ROI to regions + regions.append( + RegionOfInterest( + int(dimensions.X), int(dimensions.Y), + int(dimensions.Width), int(dimensions.Height//4), # Use // for integer division + int(dimensions.XBinning), int(dimensions.Height//4))) + + + + # Set both ROI + experiment.SetCustomRegions(regions) + +def experiment_completed(sender, event_args): #callback function which is hooked to event completed, this is the listener + print("... Acquisition Complete!") + acquireCompleted.Set() #set the event. This puts the autoresetevent false.(look at .NET library for furher info) + +def InitializerFilenameParams(): + experiment.SetValue(ExperimentSettings.FileNameGenerationAttachIncrement, False) + experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementNumber, 1.0) + experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementMinimumDigits, 2.0) + experiment.SetValue(ExperimentSettings.FileNameGenerationAttachDate, False) + experiment.SetValue(ExperimentSettings.FileNameGenerationAttachTime, False) + +def AcquireAndLock(name): + print("Acquiring...", end = "") + # name += 'Exp{0:06.2f}ms.CWL{1:07.2f}nm'.format(\ + # experiment.GetValue(CameraSettings.ShutterTimingExposureTime)\ + # ,experiment.GetValue(SpectrometerSettings.GratingCenterWavelength)) + + experiment.SetValue(ExperimentSettings.FileNameGenerationBaseFileName, name) #this creates .spe file with the name + experiment.Acquire() # this is an ashynrchronus func. + acquireCompleted.WaitOne() + +def calculate_distance(x1, y1, x2, y2): + return np.sqrt((x2 - x1)**2 + (y2 - y1)**2) + +def generate_scan_positions(center, range_val, resolution): + positive_range = np.arange(center, center + range_val + resolution, resolution) + return positive_range + +def save_as_csv(filename, position_x, position_y): + file_existance = os.path.isfile(filename) + + with open(filename, 'a', newline = '') as csvfile: + writer = csv.writer(csvfile) + + if not file_existance: + writer.writerow(['x_coordinates','y_coordinates']) + + writer.writerow([position_x, position_y]) + +def move_axis(axis, target): + """ + This function moves an axis to the specified target and stop moving after it is in the really closed + vicinity (+- 25nm) of the target (listener hooked to it). + """ + amc.move.setControlTargetPosition(axis, target) + amc.control.setControlMove(axis, True) + while not (target - 25) < amc.move.getPosition(axis) < (target + 25): + time.sleep(0.1) + time.sleep(0.15) + while not (target - 25) < amc.move.getPosition(axis) < (target + 25): + time.sleep(0.1) + amc.control.setControlMove(axis, False) + +def move_xy(target_x, target_y): # moving in x and y direction closed to desired position + amc.move.setControlTargetPosition(0, target_x) + amc.control.setControlMove(0, True) + amc.move.setControlTargetPosition(1, target_y) + amc.control.setControlMove(1, True) + while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25): + time.sleep(0.1) + time.sleep(0.15) + while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25): + time.sleep(0.1) + + amc.control.setControlOutput(0, False) + amc.control.setControlOutput(1, False) + + +# intensity_data = [] # To store data from each scan +# data_list = [] + +def move_scan_xy(range_x, range_y, resolution, Settings, baseFileName): + """ + This function moves the positioners to scan the sample with desired ranges and resolution in 2 dimensions. + At the end it saves a csv file + + Parameters + ---------- + range_x : integer in nm. max value is 5um + Scan range in x direction. + range_y : integer in nm. max value is 5um + Scan range in y direction. + resolution : integer in nm. + Room temprature max res is 50nm. In cyrostat (4K) it is 10nm (check the Attocube manual) + baseFileName: string. At the end the saved file will be: baseFileName_scan_data.csv and it will be saved to the current directory + + Returns + ------- + None. + + """ + start_time = time.time() + axis_x = 0 #first axis + axis_y = 1 #second axis + center_x = amc.move.getPosition(axis_x) + center_y = amc.move.getPosition(axis_y) + # #check if the intput range is reasonable + # if amc.move.getPosition(axis_x) + range_x >= 5000 or amc.move.getPosition(axis_x)- range_x <= 0 or amc.move.getPosition(axis_y) + range_y >=5000 or amc.move.getPosition(axis_y) - range_y <= 5000 : + # print("scan range is out of range!") + # return + # +- range from current positions for x and y directions + + + array_x = generate_scan_positions(center_x, range_x, resolution) + array_y = generate_scan_positions(center_y, range_y, resolution) + total_points = len(array_x)*len(array_y) + len_y = len(array_y) + intensity_data = [] # To store data from each scan + data_list = [] + cwd = os.getcwd() # save original directory + + #This gives a directory, in which the script will save the spectrum of each spot as spe + #However, it will open the spectrum, convert it to txt, add it to the intensity_data and delete the spe file + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + + #scanning loop + for i, x_positions in enumerate(array_x): + move_axis(axis_x, x_positions) + y = False + for j, y_positions in enumerate(array_y): + move_axis(axis_y, y_positions) + #each time when the positioner comes to the beggining of a new line + #this if will make the positioner wait a bit longer to really go to the target. + if y == False: + move_axis(axis_y, y_positions) + y = True + + #we acquire with the LF + acquire_name_spe = f'{baseFileName}_X{x_positions}_Y{y_positions}' + AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + #read the .spe file and get the data as loaded_files + cwd = os.getcwd() # save original directory + os.chdir(temp_folder_path) #change directory + loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + os.chdir(cwd) # go back to original directory + + # Delete the created .spe file from acquiring after getting necessary info + spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') + os.remove(spe_file_path) + + distance = calculate_distance(x_positions, y_positions,amc.move.getPosition(axis_x), amc.move.getPosition(axis_y)) + + points_left = total_points - (i * len_y + (j+1)) + 1 + print('Points left in the scan: ', points_left) + + #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + intensity_data.append(loaded_files.data[0][0][0]) + + data_list.append({ + 'position_x': x_positions, + 'position_y': y_positions, + 'actual_x': amc.move.getPosition(axis_x), + 'actual_y': amc.move.getPosition(axis_y), + 'distance': distance, + }) + + #moves back to starting position + move_axis(axis_x, center_x) + move_axis(axis_y, center_y) + + #prints total time the mapping lasted + end_time = time.time() + elapsed_time = (end_time - start_time) / 60 + print('Scan time: ', elapsed_time, 'minutes') + + # df = pd.DataFrame(data_list) + + #save intensity & WL data as .txt + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas') + # creates new folder for MAP data + new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + os.mkdir(new_folder_name) + # Here the things will be saved in a new folder under user Lukas ! + # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name) + + intensity_data = np.array(intensity_data) + np.savetxt(Settings + str(center_x) + '_' + str(center_y) + experiment_name +'.txt', intensity_data) + + wl = np.array(loaded_files.wavelength) + np.savetxt("Wavelength.txt", wl) + +################################################################# RYAN'S FUNCTIONS HERE ########################################################################################## + +def sep_num_from_units(powerbox_output :str)->list: + ''' + Receives a string as input and separates the numberic value and unit and returns it as a list. + + Parameters + ---------- + powerbox_output : str + string output from the attocube powerbox, e.g. 1.35325kG + + Returns + ------- + list + list of float value and string (b value and it's units). If string is purely alphabets, then return a single element list + + ''' + match = re.match(r'\s*([+-]?\d*\.?\d+)([A-Za-z]+)', powerbox_output) + if match: + numeric_part = float(match.group(1)) # Convert the numeric part to a float + alphabetic_part = match.group(2) # Get the alphabetic part + return [numeric_part, alphabetic_part] + else: + return [powerbox_output,] + + +def query_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: + """helper function for the Attocube APS100 that queries a function to the device, removing the echo. + + Args: + instr (pyvisa.resources.Resource): + command (str): commands, can be stringed in series with ; between commands + sleeptime (float, optional): delay time between commands. Defaults to 0.01. + + Returns: + str: _description_ + """ '''''' + try: + print(f"Sending command: {command}") + instr.write(command) + time.sleep(sleeptime) + echo_response = instr.read() # Read and discard the echo + # print(f"Echo response: {echo_response}") + actual_response = instr.read() # Read the actual response + print(f"Actual response: {actual_response}") + return actual_response + except pyvisa.VisaIOError as e: + print(f"Error communicating with instrument: {e}") + return None + + +def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: + """helper function for the Attocube APS100 that writes a function to the device, removing the echo. + + Args: + instr (pyvisa.resources.Resource): + command (str): commands, can be stringed in series with ; between commands + sleeptime (float, optional): delay time between commands. Defaults to 0.01. + + Returns: + str: _description_ + """ '''''' + try: + print(f"Sending command: {command}") + instr.write(command) + time.sleep(sleeptime) # Give the device some time to process + try: + while True: + echo_response = instr.read() # Read and discard the echo + # print(f"Echo response: {echo_response}") + except pyvisa.VisaIOError as e: + # Expected timeout after all echoed responses are read + if e.error_code != pyvisa.constants.VI_ERROR_TMO: + raise + except pyvisa.VisaIOError as e: + print(f"Error communicating with instrument: {e}") + + +# receive values in units of T, rescale in kg to talk with the power supplyy. 1T = 10kG +# NOTE: removed singlepowersupply_bool, reading serial-nr. of the device instead. +# old save folder: "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" +def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, + res:float, magnet_coil:str, Settings:str, base_file_name='', + reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False)->None: + # TODO: update docs in the end + """ this function performs a sweep of the B field of the chosen magnet coil. It creates a list o B values from the given min and max values, + with the given resolution. For each value, a measurement of the spectrum of the probe in the cryostat is made, using the LightField spectrometer. + + Args: + instr (pyvisa.resources.Resource): chosen power supply device to connect to + min_bval (float): min B value of the scan (please input in units of Tesla) + max_bval (float): max B value of the scan (please input in units of Tesla) + res (float): resolution of the list of B values (please input in units of Tesla) + magnet_coil (str): select magnet coil to be used. String should be 'x-axis','y-axis' or 'z-axis'. + Settings (str): experiment settings, included in file name. + base_file_name (str, optional): base file name. Defaults to ''. + singlepowersupply_bool (bool, optional): _description_. Defaults to False. + reversescan_bool (bool, optional): _description_. Defaults to False. + zerowhenfin_bool (bool, optional): _description_. Defaults to False. + + Raises: + ValueError: when By limit is exceeded. + ValueError: when Bz limit is exceeded. + ValueError: when Bx limit is exceeded. + ConnectionError: when no device is connected. + """ '''''' + + def pyramid_list(lst) -> Union[list, np.ndarray]: + """reverses the list and removes the first element of reversed list. Then, this is appended to + the end of the original list and returned as the 'pyramid' list. + + Args: + lst (list or np.ndarray): + Raises: + TypeError: if the input object isn't a list or np.ndarray + Returns: + Union[list, np.ndarray]: the pyramid list + """ '''''' + if isinstance(lst, list): + return lst + lst[-2::-1] + elif isinstance(lst, np.ndarray): + return np.append(lst, lst[-2::-1]) + else: + raise TypeError('Please input a list!') + + # defines the folder, in which the data from the spectrometer is temporarily stored in + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + + # if path_save =='': + # path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") + + if base_file_name =='': + base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') + + start_time = time.time() # start of the scan function + + instr_info = query_no_echo(instr, '*IDN?') + + instr_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element list of lists containing the set unit, llim and ulim + + if instr_bsettings[0][0] == 'T': + instr_bsettings[1][0] = instr_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr_bsettings[2][0] = instr_bsettings[2][0]*0.1 + + # if singlepowersupply_bool: # checks limits of Bx or By + # if (min_bval< -BY_MAX) or (max_bval > BY_MAX): + # raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.') + # elif '1' in query_no_echo(instr, 'CHAN?'): # check if its the coils for Bz + # if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX): + # raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.') + # else: # checks limits of Bx + # if (min_bval< -BX_MAX) or (max_bval > BX_MAX): + # raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') + + if '2101014' in instr_info and (magnet_coil=='y-axis'): # single power supply + if (min_bval< -BY_MAX) or (max_bval > BY_MAX): + raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.') + elif '2301034' in instr_info: # dual power supply + if magnet_coil=='z-axis': # check if its the coils for Bz + if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX): + raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.') + write_no_echo(instr, 'CHAN 1') + elif magnet_coil=='x-axis': # checks limits of Bx + if (min_bval< -BX_MAX) or (max_bval > BX_MAX): + raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') + write_no_echo(instr, 'CHAN 2') + else: + raise ConnectionError('Device is not connected!') + + write_no_echo(instr, f'LLIM {min_bval*10};ULIM {max_bval*10}') # sets the given limits, must convert to kG for the device to read + bval_lst = np.arange(min_bval, max_bval + res, res) # creates list of B values to measure at, with given resolution, in T + + # TODO: unused, see if can remove + # init_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # queries the initial B value of the coil, rescale from kG to T + + init_lim, subsequent_lim = 'LLIM', 'ULIM' + init_sweep, subsequent_sweep = 'DOWN', 'UP' + + #################################################### + # TODO: decide whether to start at min b val or max b val, depending on which one is nearer, IMPLEMENT THIS LATER + # nearest_bval = (abs(init_bval - min_bval), abs(init_bval - max_bval)) + # if nearest_bval[0] <= nearest_bval[1]: + # reversescan_bool = True + #################################################### + + # if reverse scan, then flip the values in the b list, and swap the initial limit and sweep conditions + if reversescan_bool: + bval_lst = bval_lst[::-1] + init_lim, subsequent_lim = subsequent_lim, init_lim + init_sweep, subsequent_sweep = subsequent_sweep, init_sweep + + # creates the pyramid list of B vals if one were to perform a hysteresis measurement + if loopscan_bool: + bval_lst = pyramid_list(bval_lst) + + total_points = len(bval_lst) + middle_index_bval_lst = total_points // 2 + intensity_data = [] # To store data from each scan + cwd = os.getcwd() # save original directory + + # NOTE: helper function for the scanning loop + def helper_scan_func(idx, bval, instr=instr, init_lim=init_lim, init_sweep=init_sweep, + subsequent_lim=subsequent_lim, subsequent_sweep=subsequent_sweep, sleep=5): + if idx == 0: # for first iteration, sweep to one of the limits + write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG + write_no_echo(instr, f'SWEEP {init_sweep}') + else: + write_no_echo(instr, f'{subsequent_lim} {bval*10}') # convert back to kG + write_no_echo(instr, f'SWEEP {subsequent_sweep}') + + actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # convert kG to T + print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + + while abs(actual_bval - bval) > 0.0001: + time.sleep(5) # little break + actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 + # update the actual bval + print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + + #scanning loop + for i, bval in enumerate(bval_lst): + # if init_bval == bval: + # # if initial bval is equal to the element of the given iteration from the bval_lst, then commence measuring the spectrum + # pass + # else: + + # NOTE: original code without the loop scan + ################################################ + # if i == 0: # for first iteration, sweep to one of the limits + # write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG + # write_no_echo(instr, f'SWEEP {init_sweep}') + # else: + # write_no_echo(instr, f'{subsequent_lim} {bval*10}') # convert back to kG + # write_no_echo(instr, f'SWEEP {subsequent_sweep}') + + # actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # convert kG to T + # print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + + # while abs(actual_bval - bval) > 0.0001: + # time.sleep(5) # little break + # actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 + # # update the actual bval + # print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + ############################################### + if not loopscan_bool: + helper_scan_func(i, bval) + else: + if i <= middle_index_bval_lst: + helper_scan_func(i, bval) + else: + helper_scan_func(i, bval, instr=instr, init_lim=subsequent_lim, init_sweep=subsequent_sweep, + subsequent_lim=init_lim, subsequent_sweep=init_sweep, sleep=5) + + time.sleep(5) + # we acquire with the LF + acquire_name_spe = f'{base_file_name}_{bval}T' + AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + # read the .spe file and get the data as loaded_files + cwd = os.getcwd() # save original directory + os.chdir(temp_folder_path) #change directory + loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + os.chdir(cwd) # go back to original directory + + # Delete the created .spe file from acquiring after getting necessary info + spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') + os.remove(spe_file_path) + + points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT + print('Points left in the scan: ', points_left) + + #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + intensity_data.append(loaded_files.data[0][0][0]) + + #prints total time the mapping lasted + end_time = time.time() + elapsed_time = (end_time - start_time) / 60 + print('Scan time: ', elapsed_time, 'minutes') + + write_no_echo(instr, f'LLIM {instr_bsettings[1][0]*10};ULIM {instr_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + + if zerowhenfin_bool: + write_no_echo(instr, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above + + #save intensity & WL data as .txt + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas') + # creates new folder for MAP data + new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + os.mkdir(new_folder_name) + # Here the things will be saved in a new folder under user Lukas ! + # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name) + + intensity_data = np.array(intensity_data) + np.savetxt(Settings + str(min_bval) + 'T_to_' + str(max_bval) + 'T' + experiment_name +'.txt', intensity_data) + + wl = np.array(loaded_files.wavelength) + np.savetxt("Wavelength.txt", wl) + + +def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True): + # TODO: DOCS + """Creates a list of discrete cartesian coordinates (x,y), given the radius, start- and end angles, the angle step size, and the direction of rotation. + Function then returns a list of two lists: list of angles and list of cartesian coordinates (x,y coordinates in a tuple). + + Args: + radius (_type_): _description_ + start_angle (_type_): _description_ + end_angle (_type_): _description_ + step_size (_type_): _description_ + clockwise (bool, optional): _description_. Defaults to True. + + Returns: + _type_: _description_ + """ """""" + # Initialize lists to hold angles and (x, y) pairs + angles = [] + coordinates = [] + + # Normalize angles to the range [0, 360) + start_angle = start_angle % 360 + end_angle = end_angle % 360 + + if clockwise: + # Clockwise rotation + current_angle = start_angle + while True: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle (handling wrap-around) (current_angle - step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: + break + + # Decrement the current angle by the step size + current_angle -= step_size + if current_angle < 0: + current_angle += 360 + else: + # Counterclockwise rotation + current_angle = start_angle + while True: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle (handling wrap-around) (current_angle + step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: + break + + # Increment the current angle by the step size + current_angle += step_size + if current_angle >= 360: + current_angle -= 360 + + return [angles, coordinates] + + +def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, + Babs:float, startangle:float, endangle:float, angle_stepsize:float, Settings:str, clockwise=True, base_file_name='', zerowhenfin_bool=False)->None: + # TODO: update docs + """Rotation of the b-field in discrete steps, spectrum is measured at each discrete step in the rotation. Scan angle is + defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. + + Args: + instr1 (pyvisa.resources.Resource): _description_ + instr2 (pyvisa.resources.Resource): _description_ + Babs (float): absolute B-field value in T + startangle (float): start angle in degrees + endangle (float): end angle in degrees + angle_stepsize (float): angle step size in degrees + clockwise (bool): determines the direction of rotation of the B-field. Defaults to True. + zerowhenfin_bool (bool, optional): after finishing the rotation, both B-field components should be set to 0 T. Defaults to False. + """ + + # TODO: possibly rename instr1 and instr2 to the dual and single power supplies respectively?? + + # defines the folder, in which the data from the spectrometer is temporarily stored in + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + + if base_file_name =='': + base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') + + start_time = time.time() # start of the scan function + + startangle = startangle % 360 + endangle = endangle % 360 # ensures that the angles are within [0,360) + + idnstr1 = query_no_echo(instr1, '*IDN?') + idnstr2 = query_no_echo(instr1, '*IDN?') + + intensity_data = [] # To store data from each scan + cwd = os.getcwd() # save original directory + + # find which one is the dual power supply, then, ramp B_x to Babs value + if '2301034' in idnstr1: # serial no. the dual power supply + pass + elif '2101034' in idnstr2: + # swap instruments, instr 1 to be the dual power supply (^= x-axis) + instr1, instr2 = instr2, instr1 + + # save initial low and high sweep limits of each device, and set them back after the rotation + instr1_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + instr2_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + if instr1_bsettings[0][0] == 'T': + instr1_bsettings[1][0] = instr1_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr1_bsettings[2][0] = instr1_bsettings[2][0]*0.1 + if instr2_bsettings[0][0] == 'T': + instr2_bsettings[1][0] = instr2_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr2_bsettings[2][0] = instr2_bsettings[2][0]*0.1 + + # initialise the sweep angle list as well as the sweep limits and directions for each instrument + instr1_lim, instr2_lim = 'LLIM', 'ULIM' + instr1_sweep, instr2_sweep = 'DOWN', 'UP' + + # create lists of angles and discrete Cartesian coordinates + angles, cartesian_coords = polar_to_cartesian(Babs, startangle, endangle, angle_stepsize, clockwise=clockwise) + + if clockwise: # NOTE: old conditional was: startangle > endangle see if this works.... + # reverse sweep limits and directions for the clockwise rotation + instr1_lim, instr2_lim = instr2_lim, instr1_lim + instr1_sweep, instr2_sweep = instr2_sweep, instr1_sweep + + # list of rates (with units) for diff ranges of each device, only up to Range 1 for single power supply as that is already + # the max recommended current. + init_range_lst1 = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'RATE? 0;RATE? 1;RATE? 2').split(';')) + init_range_lst2 = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'RATE? 0;RATE? 1').split(';')) + + min_range_lst = [min(el1[0], el2[0]) for el1,el2 in zip(init_range_lst1, init_range_lst2)] # min rates for each given range + + # set both devices to the min rates + write_no_echo(instr1, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + + write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit + print(f'SWEEPING B-X TO {Babs} T NOW') + + # wait for Babs to be reached by the Bx field + actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') + while abs(actual_bval - Babs) > 0.0001: + time.sleep(5) # little break + actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 + print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') + + # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN + # Helper function that listens to a device + def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event): + while not all_targets_met_event.is_set(): # Loop until the event is set + # value = 0 # Simulate receiving a float from the device INSERT QUERY NO ECHO HERE TO ASK FOR DEVICE IMAG + if '2301034' in device_id: + value = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + elif '2101014' in device_id: + value = sep_num_from_units(query_no_echo(instr2, 'IMAG?'))[0]*0.1 # convert kG to T + print(f"Device {device_id} reports value: {value} T") + + with lock: + shared_values[device_id] = value + # Check if both devices have met their targets + if all(shared_values.get(device) is not None and abs(shared_values[device] - target_value[device]) <= 0.0001 + for device in shared_values): + print(f"Both devices reached their target values: {shared_values}") + all_targets_met_event.set() # Signal that both targets are met + + # time.sleep(1) # Simulate periodic data checking + + # Main function to manage threads and iterate over target values + def monitor_devices(device_target_values, angles_lst, intensity_data=intensity_data): + for iteration, target in enumerate(device_target_values): + print(f"\nStarting iteration {iteration+1} for target values: {target}") + # Shared dictionary to store values from devices + shared_values = {device: None for device in target.keys()} + # Event to signal when both target values are reached + all_targets_met_event = threading.Event() + + # Lock to synchronize access to shared_values + lock = threading.Lock() + + # Create and start threads for each device + threads = [] + for device_id in target.keys(): + thread = threading.Thread(target=listen_to_device, args=(device_id, target, shared_values, lock, all_targets_met_event)) + threads.append(thread) + thread.start() + + # Wait until both devices meet their target values + all_targets_met_event.wait() + print(f"Both target values for iteration {iteration+1} met. Performing action...") + + # Perform some action after both targets are met + # we acquire with the LF + acquire_name_spe = f'{base_file_name}_{angles_lst[iteration]}°' # NOTE: save each intensity file with the given angle + AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + # read the .spe file and get the data as loaded_files + cwd = os.getcwd() # save original directory + os.chdir(temp_folder_path) #change directory + loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + os.chdir(cwd) # go back to original directory + + # Delete the created .spe file from acquiring after getting necessary info + spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') + os.remove(spe_file_path) + + # points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT + # print('Points left in the scan: ', points_left) + + #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + intensity_data.append(loaded_files.data[0][0][0]) + + # Clean up threads + for thread in threads: + thread.join() + + print(f"Threads for iteration {iteration+1} closed.\n") + + #prints total time the mapping lasted + end_time = time.time() + elapsed_time = (end_time - start_time) / 60 + print('Scan time: ', elapsed_time, 'minutes') + + # reset both devices to original sweep limits + write_no_echo(instr1, f'LLIM {instr1_bsettings[1][0]*10};ULIM {instr1_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'LLIM {instr2_bsettings[1][0]*10};ULIM {instr2_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + # reset both devices' initial rates for each range + write_no_echo(instr1, f'RANGE 0 {init_range_lst1[0][0]};RANGE 1 {init_range_lst1[1][0]};RANGE 2 {init_range_lst1[2][0]}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'RANGE 0 {init_range_lst2[0][0]};RANGE 1 {init_range_lst2[1][0]}') # reset the initial limits of the device after the scan + + if zerowhenfin_bool: + write_no_echo(instr1, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above + write_no_echo(instr2, 'SWEEP ZERO') + + #save intensity & WL data as .txt + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas') + # creates new folder for MAP data + new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + os.mkdir(new_folder_name) + # Here the things will be saved in a new folder under user Lukas ! + # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name) + + intensity_data = np.array(intensity_data) + np.savetxt(Settings + f'{angles[0]}°_to_{angles[-1]}°' + experiment_name +'.txt', intensity_data) + # TODO: remove/edit experiment_name in line above, as well in sweep_b_val func, rn takes a global variable below + + wl = np.array(loaded_files.wavelength) + np.savetxt("Wavelength.txt", wl) + + # modify cartesian_coords to suite the required data struct in monitor_devices + cartesian_coords = [{'2301034': t[0], '2101014': t[1]} for t in cartesian_coords] + + # call the helper function to carry out the rotation/measurement of spectrum + monitor_devices(cartesian_coords, angles, intensity_data) + + +################################################################# END OF FUNCTION DEFS ########################################################################################### + +# NOTE: RYAN INTRODUCED SOME FUNCTIONS HERE TO PERFORM THE SCAN + +# Initialise PYVISA ResourceManager +rm = pyvisa.ResourceManager() +# print(rm.list_resources()) +# 'ASRL8::INSTR' for dual power supply, 'ASRL9::INSTR' for single power supply (online PC) +# 'ASRL10::INSTR' for dual power supply, 'ASRL12::INSTR' for single power supply (offline PC) + + +# Open the connection with the APS100 dual power supply +powerbox_dualsupply = rm.open_resource('ASRL10::INSTR', + baud_rate=9600, + data_bits=8, + parity= pyvisa.constants.Parity.none, + stop_bits= pyvisa.constants.StopBits.one, + timeout=100)# 5000 ms timeout + +# Open the connection with the APS100 dual power supply +powerbox_singlesupply = rm.open_resource('ASRL12::INSTR', + baud_rate=9600, + data_bits=8, + parity= pyvisa.constants.Parity.none, + stop_bits= pyvisa.constants.StopBits.one, + timeout=100)# 5000 ms timeout + +write_no_echo(powerbox_dualsupply, 'REMOTE') # turn on the remote mode +write_no_echo(powerbox_singlesupply, 'REMOTE') # turn on the remote mode + +# TODO: test functionality of the magnet_coil param later on, should work... as this code below is basically implemented inside the scan func. +# select axis for the dual supply, either z-axis(CHAN 1 ^= Supply A) or x-axis(CHAN 2 ^= Supply B) +# write_no_echo(powerbox_dualsupply, 'CHAN 1') + +# Setup connection to AMC +amc = AMC.Device(IP) +amc.connect() + +# Internally, axes are numbered 0 to 2 +amc.control.setControlOutput(0, True) +amc.control.setControlOutput(1, True) + + +auto = Automation(True, List[String]()) +experiment = auto.LightFieldApplication.Experiment +acquireCompleted = AutoResetEvent(False) + +experiment.Load("Lukas_experiment_2024_02_06") +experiment.ExperimentCompleted += experiment_completed # we are hooking a listener. +# experiment.SetValue(SpectrometerSettings.GratingSelected, '[750nm,1200][0][0]') +# InitializerFilenameParams() + + +#set scan range and resolution in nanometers +range_x = 20000 +range_y = 20000 +resolution = 1000 +# set B-field scan range and resolution (all in T) +set_llim_bval = -0.01 +set_ulim_bval = 0.01 +set_res_bval = 0.01 + +#Here you can specify the filename of the map e.g. put experiment type, exposure time, used filters, etc.... +experiment_settings = 'PL_SP_700_LP_700_HeNe_52muW_exp_2s_Start_' +#The program adds the range of the scan as well as the resolution and the date and time of the measurement +experiment_name = f"{set_llim_bval}T_to_{set_ulim_bval}T_{set_res_bval}T_{datetime.datetime.now().strftime('%Y_%m_%d_%H%M')}" + +# this moves the probe in xy-direction and measures spectrum there +# move_scan_xy(range_x, range_y, resolution, experiment_settings, experiment_name) + +# perform the B-field measurement for selected axis above +# sweep_b_val(powerbox_dualsupply, set_llim_bval, set_ulim_bval, set_res_bval, experiment_settings, experiment_name) +sweep_b_val(powerbox_dualsupply, set_llim_bval, set_ulim_bval, set_res_bval, 'z-axis', + experiment_settings, experiment_name, zerowhenfin_bool=True, reversescan_bool=False) + +# Internally, axes are numbered 0 to 2 + +write_no_echo(powerbox_dualsupply, 'LOCAL') # turn off the remote mode +write_no_echo(powerbox_singlesupply, 'LOCAL') # turn off the remote mode +# time.sleep(0.5) +powerbox_dualsupply.close() +powerbox_singlesupply.close() \ No newline at end of file -- 2.39.5 From c4d349bfa79f9f8cab8f58909b143ce33f17d703 Mon Sep 17 00:00:00 2001 From: ryantan Date: Mon, 14 Apr 2025 10:29:39 +0200 Subject: [PATCH 18/39] uplaoded updated scripts --- FunctionsTest.py | 33 + Mag_Field_Sweep_2024_10_21.py | 1018 ++++++++++++++++++++ Mapping_Script_Lukas_Version_2024_08_27.py | 355 +++++++ 3 files changed, 1406 insertions(+) create mode 100644 FunctionsTest.py create mode 100644 Mag_Field_Sweep_2024_10_21.py create mode 100644 Mapping_Script_Lukas_Version_2024_08_27.py diff --git a/FunctionsTest.py b/FunctionsTest.py new file mode 100644 index 0000000..22a46af --- /dev/null +++ b/FunctionsTest.py @@ -0,0 +1,33 @@ +import re +import numpy as np + +def sep_num_from_units(powerbox_output :str)->list: + ''' + Receives a string as input and separates the numberic value and unit and returns it as a list. + + Parameters + ---------- + powerbox_output : str + string output from the attocube powerbox, e.g. 1.35325kG + + Returns + ------- + list + list of float value and string (b value and it's units). If string is purely alphabets, then return a single element list + + ''' + match = re.match(r'\s*([+-]?\d*\.?\d+)([A-Za-z]+)', powerbox_output) + if match: + numeric_part = float(match.group(1)) # Convert the numeric part to a float + alphabetic_part = match.group(2) # Get the alphabetic part + return [numeric_part, alphabetic_part] + else: + return [powerbox_output,] + +angles = [1,2,3] + +print(str(angles[0]) +"\n"+ str(angles[-1])) + +rates_lst = list(sep_num_from_units(el) for el in "0.0kG;1.0kG".split(";")) + +print(rates_lst[1][0]) diff --git a/Mag_Field_Sweep_2024_10_21.py b/Mag_Field_Sweep_2024_10_21.py new file mode 100644 index 0000000..108e822 --- /dev/null +++ b/Mag_Field_Sweep_2024_10_21.py @@ -0,0 +1,1018 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri Dec 22 15:10:10 2023 +Lightfield + Positioner +@author: Serdar, adjusted by Lukas +""" +############################################ +# Packages from Ryan +import re +import math +import threading +import pyvisa +# from pyvisa import ResourceManager, constants + +# B Field Limits (in T) +BX_MAX = 1.7 +BY_MAX = 1.7 +BZ_MAX = 4.0 +############################################ + +import AMC +import csv +import time +import clr +import sys +import os +import spe2py as spe +import spe_loader as sl +import pandas as pd +import time +from System.IO import * +from System import String +import numpy as np +import matplotlib.pyplot as plt +import datetime +from typing import Union + + +#First choose your controller +IP_AMC300 = "192.168.71.101" +IP_AMC100 = "192.168.71.100" + +# IP = "192.168.1.1" +IP = IP_AMC100 + + +# Import os module +import os, glob, string + +# Import System.IO for saving and opening files +from System.IO import * + +from System.Threading import AutoResetEvent + +# Import C compatible List and String +from System import String +from System.Collections.Generic import List + +# Add needed dll references +sys.path.append(os.environ['LIGHTFIELD_ROOT']) +sys.path.append(os.environ['LIGHTFIELD_ROOT']+"\\AddInViews") +sys.path.append(r'C:\Program Files\Princeton Instruments\LightField\AddInViews') #I added them by hand -serdar +sys.path.append(r'C:\Program Files\Princeton Instruments\LightField') #this one also +clr.AddReference('PrincetonInstruments.LightFieldViewV5') +clr.AddReference('PrincetonInstruments.LightField.AutomationV5') +clr.AddReference('PrincetonInstruments.LightFieldAddInSupportServices') +os.environ['LIGHTFIELD_ROOT'] = r'C:\Program Files\Princeton Instruments\LightField' +# PI imports +from PrincetonInstruments.LightField.Automation import Automation +from PrincetonInstruments.LightField.AddIns import ExperimentSettings +from PrincetonInstruments.LightField.AddIns import CameraSettings +#from PrincetonInstruments.LightField.AddIns import DeviceType +from PrincetonInstruments.LightField.AddIns import SpectrometerSettings +from PrincetonInstruments.LightField.AddIns import RegionOfInterest + +######################################################################################################### code begins from here ############################################# + +def set_custom_ROI(): + + # Get device full dimensions + dimensions = experiment.FullSensorRegion() + + regions = [] + + # Add two ROI to regions + regions.append( + RegionOfInterest( + int(dimensions.X), int(dimensions.Y), + int(dimensions.Width), int(dimensions.Height//4), # Use // for integer division + int(dimensions.XBinning), int(dimensions.Height//4))) + + + + # Set both ROI + experiment.SetCustomRegions(regions) + +def experiment_completed(sender, event_args): #callback function which is hooked to event completed, this is the listener + print("... Acquisition Complete!") + acquireCompleted.Set() #set the event. This puts the autoresetevent false.(look at .NET library for furher info) + +def InitializerFilenameParams(): + experiment.SetValue(ExperimentSettings.FileNameGenerationAttachIncrement, False) + experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementNumber, 1.0) + experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementMinimumDigits, 2.0) + experiment.SetValue(ExperimentSettings.FileNameGenerationAttachDate, False) + experiment.SetValue(ExperimentSettings.FileNameGenerationAttachTime, False) + +def AcquireAndLock(name): + print("Acquiring...", end = "") + # name += 'Exp{0:06.2f}ms.CWL{1:07.2f}nm'.format(\ + # experiment.GetValue(CameraSettings.ShutterTimingExposureTime)\ + # ,experiment.GetValue(SpectrometerSettings.GratingCenterWavelength)) + + experiment.SetValue(ExperimentSettings.FileNameGenerationBaseFileName, name) #this creates .spe file with the name + experiment.Acquire() # this is an ashynrchronus func. + acquireCompleted.WaitOne() + +def calculate_distance(x1, y1, x2, y2): + return np.sqrt((x2 - x1)**2 + (y2 - y1)**2) + +def generate_scan_positions(center, range_val, resolution): + positive_range = np.arange(center, center + range_val + resolution, resolution) + return positive_range + +def save_as_csv(filename, position_x, position_y): + file_existance = os.path.isfile(filename) + + with open(filename, 'a', newline = '') as csvfile: + writer = csv.writer(csvfile) + + if not file_existance: + writer.writerow(['x_coordinates','y_coordinates']) + + writer.writerow([position_x, position_y]) + +def move_axis(axis, target): + """ + This function moves an axis to the specified target and stop moving after it is in the really closed + vicinity (+- 25nm) of the target (listener hooked to it). + """ + amc.move.setControlTargetPosition(axis, target) + amc.control.setControlMove(axis, True) + while not (target - 25) < amc.move.getPosition(axis) < (target + 25): + time.sleep(0.1) + time.sleep(0.15) + while not (target - 25) < amc.move.getPosition(axis) < (target + 25): + time.sleep(0.1) + amc.control.setControlMove(axis, False) + +def move_xy(target_x, target_y): # moving in x and y direction closed to desired position + amc.move.setControlTargetPosition(0, target_x) + amc.control.setControlMove(0, True) + amc.move.setControlTargetPosition(1, target_y) + amc.control.setControlMove(1, True) + while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25): + time.sleep(0.1) + time.sleep(0.15) + while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25): + time.sleep(0.1) + + amc.control.setControlOutput(0, False) + amc.control.setControlOutput(1, False) + + +# intensity_data = [] # To store data from each scan +# data_list = [] + +def move_scan_xy(range_x, range_y, resolution, Settings, baseFileName): + """ + This function moves the positioners to scan the sample with desired ranges and resolution in 2 dimensions. + At the end it saves a csv file + + Parameters + ---------- + range_x : integer in nm. max value is 5um + Scan range in x direction. + range_y : integer in nm. max value is 5um + Scan range in y direction. + resolution : integer in nm. + Room temprature max res is 50nm. In cyrostat (4K) it is 10nm (check the Attocube manual) + baseFileName: string. At the end the saved file will be: baseFileName_scan_data.csv and it will be saved to the current directory + + Returns + ------- + None. + + """ + start_time = time.time() + axis_x = 0 #first axis + axis_y = 1 #second axis + center_x = amc.move.getPosition(axis_x) + center_y = amc.move.getPosition(axis_y) + # #check if the intput range is reasonable + # if amc.move.getPosition(axis_x) + range_x >= 5000 or amc.move.getPosition(axis_x)- range_x <= 0 or amc.move.getPosition(axis_y) + range_y >=5000 or amc.move.getPosition(axis_y) - range_y <= 5000 : + # print("scan range is out of range!") + # return + # +- range from current positions for x and y directions + + + array_x = generate_scan_positions(center_x, range_x, resolution) + array_y = generate_scan_positions(center_y, range_y, resolution) + total_points = len(array_x)*len(array_y) + len_y = len(array_y) + intensity_data = [] # To store data from each scan + data_list = [] + cwd = os.getcwd() # save original directory + + #This gives a directory, in which the script will save the spectrum of each spot as spe + #However, it will open the spectrum, convert it to txt, add it to the intensity_data and delete the spe file + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + + #scanning loop + for i, x_positions in enumerate(array_x): + move_axis(axis_x, x_positions) + y = False + for j, y_positions in enumerate(array_y): + move_axis(axis_y, y_positions) + #each time when the positioner comes to the beggining of a new line + #this if will make the positioner wait a bit longer to really go to the target. + if y == False: + move_axis(axis_y, y_positions) + y = True + + #we acquire with the LF + acquire_name_spe = f'{baseFileName}_X{x_positions}_Y{y_positions}' + AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + #read the .spe file and get the data as loaded_files + cwd = os.getcwd() # save original directory + os.chdir(temp_folder_path) #change directory + loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + os.chdir(cwd) # go back to original directory + + # Delete the created .spe file from acquiring after getting necessary info + spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') + os.remove(spe_file_path) + + distance = calculate_distance(x_positions, y_positions,amc.move.getPosition(axis_x), amc.move.getPosition(axis_y)) + + points_left = total_points - (i * len_y + (j+1)) + 1 + print('Points left in the scan: ', points_left) + + #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + intensity_data.append(loaded_files.data[0][0][0]) + + data_list.append({ + 'position_x': x_positions, + 'position_y': y_positions, + 'actual_x': amc.move.getPosition(axis_x), + 'actual_y': amc.move.getPosition(axis_y), + 'distance': distance, + }) + + #moves back to starting position + move_axis(axis_x, center_x) + move_axis(axis_y, center_y) + + #prints total time the mapping lasted + end_time = time.time() + elapsed_time = (end_time - start_time) / 60 + print('Scan time: ', elapsed_time, 'minutes') + + # df = pd.DataFrame(data_list) + + #save intensity & WL data as .txt + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas') + # creates new folder for MAP data + new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + os.mkdir(new_folder_name) + # Here the things will be saved in a new folder under user Lukas ! + # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name) + + intensity_data = np.array(intensity_data) + np.savetxt(Settings + str(center_x) + '_' + str(center_y) + experiment_name +'.txt', intensity_data) + + wl = np.array(loaded_files.wavelength) + np.savetxt("Wavelength.txt", wl) + +################################################################# RYAN'S FUNCTIONS HERE ########################################################################################## + +def sep_num_from_units(powerbox_output :str)->list: + ''' + Receives a string as input and separates the numberic value and unit and returns it as a list. + + Parameters + ---------- + powerbox_output : str + string output from the attocube powerbox, e.g. 1.35325kG + + Returns + ------- + list + list of float value and string (b value and it's units). If string is purely alphabets, then return a single element list + + ''' + match = re.match(r'\s*([+-]?\d*\.?\d+)([A-Za-z]+)', powerbox_output) + if match: + numeric_part = float(match.group(1)) # Convert the numeric part to a float + alphabetic_part = match.group(2) # Get the alphabetic part + return [numeric_part, alphabetic_part] + else: + return [powerbox_output,] + + +def query_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: + """helper function for the Attocube APS100 that queries a function to the device, removing the echo. + + Args: + instr (pyvisa.resources.Resource): + command (str): commands, can be stringed in series with ; between commands + sleeptime (float, optional): delay time between commands. Defaults to 0.01. + + Returns: + str: _description_ + """ '''''' + try: + print(f"Sending command: {command}") + instr.write(command) + time.sleep(sleeptime) + echo_response = instr.read() # Read and discard the echo + # print(f"Echo response: {echo_response}") + actual_response = instr.read() # Read the actual response + print(f"Actual response: {actual_response}") + return actual_response + except pyvisa.VisaIOError as e: + print(f"Error communicating with instrument: {e}") + return None + + +def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: + """helper function for the Attocube APS100 that writes a function to the device, removing the echo. + + Args: + instr (pyvisa.resources.Resource): + command (str): commands, can be stringed in series with ; between commands + sleeptime (float, optional): delay time between commands. Defaults to 0.01. + + Returns: + str: _description_ + """ '''''' + try: + print(f"Sending command: {command}") + instr.write(command) + time.sleep(sleeptime) # Give the device some time to process + try: + while True: + echo_response = instr.read() # Read and discard the echo + # print(f"Echo response: {echo_response}") + except pyvisa.VisaIOError as e: + # Expected timeout after all echoed responses are read + if e.error_code != pyvisa.constants.VI_ERROR_TMO: + raise + except pyvisa.VisaIOError as e: + print(f"Error communicating with instrument: {e}") + +def ramp_b_val(instr:pyvisa.resources.Resource, bval:float, magnet_coil:str)->None: + + instr_info = query_no_echo(instr, '*IDN?') + + instr_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element list of lists containing the set unit, llim and ulim + + if instr_bsettings[0][0] == 'T': + instr_bsettings[1][0] = instr_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr_bsettings[2][0] = instr_bsettings[2][0]*0.1 + + + if '2101014' in instr_info and (magnet_coil=='y-axis'): # single power supply + if (bval< -BY_MAX) or (bval > BY_MAX): + raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.') + elif '2301034' in instr_info: # dual power supply + if magnet_coil=='z-axis': # check if its the coils for Bz + if (bval < -BZ_MAX) or (bval > BZ_MAX): + raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.') + write_no_echo(instr, 'CHAN 1') + elif magnet_coil=='x-axis': # checks limits of Bx + if (bval< -BX_MAX) or (bval > BX_MAX): + raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') + write_no_echo(instr, 'CHAN 2') + else: + raise ConnectionError('Device is not connected!') + + + init_lim, subsequent_lim = 'LLIM', 'ULIM' + init_sweep, subsequent_sweep = 'DOWN', 'UP' + + def helper_scan_func(bval, instr=instr, init_lim=init_lim, init_sweep=init_sweep, + subsequent_lim=subsequent_lim, subsequent_sweep=subsequent_sweep, sleep=5): + actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 + if bval > actual_bval: + write_no_echo(instr, f'{subsequent_lim} {bval*10}') # convert back to kG + write_no_echo(instr, f'SWEEP {subsequent_sweep}') + elif bval < actual_bval: + write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG + write_no_echo(instr, f'SWEEP {init_sweep}') + + actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # convert kG to T + print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + + while abs(actual_bval - bval) > 0.0001: + time.sleep(sleep) # little break + actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 + # update the actual bval + print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + + print("Ramping Done!") + + helper_scan_func(bval) + + + +# receive values in units of T, rescale in kg to talk with the power supplyy. 1T = 10kG +# NOTE: removed singlepowersupply_bool, reading serial-nr. of the device instead. +# old save folder: "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" +def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, + res:float, magnet_coil:str, Settings:str, base_file_name='', + reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False)->None: + # TODO: update docs in the end + """ this function performs a sweep of the B field of the chosen magnet coil. It creates a list o B values from the given min and max values, + with the given resolution. For each value, a measurement of the spectrum of the probe in the cryostat is made, using the LightField spectrometer. + + Args: + instr (pyvisa.resources.Resource): chosen power supply device to connect to + min_bval (float): min B value of the scan (please input in units of Tesla) + max_bval (float): max B value of the scan (please input in units of Tesla) + res (float): resolution of the list of B values (please input in units of Tesla) + magnet_coil (str): select magnet coil to be used. String should be 'x-axis','y-axis' or 'z-axis'. + Settings (str): experiment settings, included in file name. + base_file_name (str, optional): base file name. Defaults to ''. + singlepowersupply_bool (bool, optional): _description_. Defaults to False. + reversescan_bool (bool, optional): _description_. Defaults to False. + zerowhenfin_bool (bool, optional): _description_. Defaults to False. + + Raises: + ValueError: when By limit is exceeded. + ValueError: when Bz limit is exceeded. + ValueError: when Bx limit is exceeded. + ConnectionError: when no device is connected. + """ '''''' + + def pyramid_list(lst) -> Union[list, np.ndarray]: + """reverses the list and removes the first element of reversed list. Then, this is appended to + the end of the original list and returned as the 'pyramid' list. + + Args: + lst (list or np.ndarray): + Raises: + TypeError: if the input object isn't a list or np.ndarray + Returns: + Union[list, np.ndarray]: the pyramid list + """ '''''' + if isinstance(lst, list): + return lst + lst[-2::-1] + elif isinstance(lst, np.ndarray): + return np.append(lst, lst[-2::-1]) + else: + raise TypeError('Please input a list!') + + # defines the folder, in which the data from the spectrometer is temporarily stored in + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/B_Field_Dump" + + # if path_save =='': + # path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") + + if base_file_name =='': + base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') + + start_time = time.time() # start of the scan function + + instr_info = query_no_echo(instr, '*IDN?') + + instr_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element list of lists containing the set unit, llim and ulim + + if instr_bsettings[0][0] == 'T': + instr_bsettings[1][0] = instr_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr_bsettings[2][0] = instr_bsettings[2][0]*0.1 + + # if singlepowersupply_bool: # checks limits of Bx or By + # if (min_bval< -BY_MAX) or (max_bval > BY_MAX): + # raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.') + # elif '1' in query_no_echo(instr, 'CHAN?'): # check if its the coils for Bz + # if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX): + # raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.') + # else: # checks limits of Bx + # if (min_bval< -BX_MAX) or (max_bval > BX_MAX): + # raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') + + if '2101014' in instr_info and (magnet_coil=='y-axis'): # single power supply + if (min_bval< -BY_MAX) or (max_bval > BY_MAX): + raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.') + elif '2301034' in instr_info: # dual power supply + if magnet_coil=='z-axis': # check if its the coils for Bz + if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX): + raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.') + write_no_echo(instr, 'CHAN 1') + elif magnet_coil=='x-axis': # checks limits of Bx + if (min_bval< -BX_MAX) or (max_bval > BX_MAX): + raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') + write_no_echo(instr, 'CHAN 2') + else: + raise ConnectionError('Device is not connected!') + + write_no_echo(instr, f'LLIM {min_bval*10};ULIM {max_bval*10}') # sets the given limits, must convert to kG for the device to read + bval_lst = np.arange(min_bval, max_bval + res, res) + # a = np.arange(min_bval, max_bval + res, res) # creates list of B values to measure at, with given resolution, in T + # b = np.arange(max_bval, min_bval - res, res) + # bval_lst = np.concatenate((a,b)) + + # TODO: unused, see if can remove + # init_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # queries the initial B value of the coil, rescale from kG to T + + init_lim, subsequent_lim = 'LLIM', 'ULIM' + init_sweep, subsequent_sweep = 'DOWN', 'UP' + + #################################################### + # TODO: decide whether to start at min b val or max b val, depending on which one is nearer, IMPLEMENT THIS LATER + # nearest_bval = (abs(init_bval - min_bval), abs(init_bval - max_bval)) + # if nearest_bval[0] <= nearest_bval[1]: + # reversescan_bool = True + #################################################### + + # if reverse scan, then flip the values in the b list, and swap the initial limit and sweep conditions + if reversescan_bool: + bval_lst = bval_lst[::-1] + init_lim, subsequent_lim = subsequent_lim, init_lim + init_sweep, subsequent_sweep = subsequent_sweep, init_sweep + + # creates the pyramid list of B vals if one were to perform a hysteresis measurement + if loopscan_bool: + bval_lst = pyramid_list(bval_lst) + + total_points = len(bval_lst) + middle_index_bval_lst = total_points // 2 + intensity_data = [] # To store data from each scan + cwd = os.getcwd() # save original directory + + # NOTE: helper function for the scanning loop + def helper_scan_func(idx, bval, instr=instr, init_lim=init_lim, init_sweep=init_sweep, + subsequent_lim=subsequent_lim, subsequent_sweep=subsequent_sweep, sleep=5): + if idx == 0: # for first iteration, sweep to one of the limits + # time.sleep(10) + actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 + if bval > actual_bval: + write_no_echo(instr, f'{subsequent_lim} {bval*10}') # convert back to kG + write_no_echo(instr, f'SWEEP {subsequent_sweep}') + elif bval < actual_bval: + write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG + write_no_echo(instr, f'SWEEP {init_sweep}') + # write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG + # write_no_echo(instr, f'SWEEP {init_sweep}') + else: + write_no_echo(instr, f'{subsequent_lim} {bval*10}') # convert back to kG + write_no_echo(instr, f'SWEEP {subsequent_sweep}') + + actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # convert kG to T + print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + + while abs(actual_bval - bval) > 0.0001: + time.sleep(sleep) # little break + actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 + # update the actual bval + print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + + #scanning loop + for i, bval in enumerate(bval_lst): + # if init_bval == bval: + # # if initial bval is equal to the element of the given iteration from the bval_lst, then commence measuring the spectrum + # pass + # else: + + # NOTE: original code without the loop scan + ################################################ + # if i == 0: # for first iteration, sweep to one of the limits + # write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG + # write_no_echo(instr, f'SWEEP {init_sweep}') + # else: + # write_no_echo(instr, f'{subsequent_lim} {bval*10}') # convert back to kG + # write_no_echo(instr, f'SWEEP {subsequent_sweep}') + + # actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # convert kG to T + # print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + + # while abs(actual_bval - bval) > 0.0001: + # time.sleep(5) # little break + # actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 + # # update the actual bval + # print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') + ############################################### + if not loopscan_bool: + helper_scan_func(i, bval) + else: + if i <= middle_index_bval_lst: + helper_scan_func(i, bval) + else: + helper_scan_func(i, bval, instr=instr, init_lim=subsequent_lim, init_sweep=subsequent_sweep, + subsequent_lim=init_lim, subsequent_sweep=init_sweep, sleep=5) + + # print(bval_lst) # bval lst is ok + # we acquire with the LF + acquire_name_spe = f'{base_file_name}_{bval}T' + AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + # read the .spe file and get the data as loaded_files + cwd = os.getcwd() # save original directory + os.chdir(temp_folder_path) #change directory + loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + os.chdir(cwd) # go back to original directory + + # Delete the created .spe file from acquiring after getting necessary info + spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') + os.remove(spe_file_path) + + points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT + print('Points left in the scan: ', points_left) + + #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + intensity_data.append(loaded_files.data[0][0][0]) + + #prints total time the mapping lasted + end_time = time.time() + elapsed_time = (end_time - start_time) / 60 + print('Scan time: ', elapsed_time, 'minutes') + + write_no_echo(instr, f'LLIM {instr_bsettings[1][0]*10};ULIM {instr_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + + if zerowhenfin_bool: + write_no_echo(instr, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above + + #save intensity & WL data as .txt + os.chdir('C:/Users/localadmin/Desktop/Users/Priyanka/2025/stacked_2L/Magnetic scan/DR/6th spot/along b_bilayer') + # creates new folder for MAP data + new_folder_name = "DR_Sweep_By_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + os.mkdir(new_folder_name) + # Here the things will be saved in a new folder under user Lukas ! + # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! + os.chdir('C:/Users/localadmin/Desktop/Users/Priyanka/2025/stacked_2L/Magnetic scan/DR/6th spot/along b_bilayer/'+ new_folder_name) + + intensity_data = np.array(intensity_data) + np.savetxt('sweepdata.txt', intensity_data) + with open('experimentsettings.txt', 'w', encoding='utf-8') as f: + f.write(Settings + '_' + str(min_bval) + 'T_to_' + str(max_bval) + 'T_res_' + str(res) + 'T') + + wl = np.array(loaded_files.wavelength) + np.savetxt("Wavelength.txt", wl) + np.savetxt("B_Values.txt", bval_lst) + + +def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True): + # TODO: DOCS + """Creates a list of discrete cartesian coordinates (x,y), given the radius, start- and end angles, the angle step size, and the direction of rotation. + Function then returns a list of two lists: list of angles and list of cartesian coordinates (x,y coordinates in a tuple). + + Args: + radius (_type_): _description_ + start_angle (_type_): _description_ + end_angle (_type_): _description_ + step_size (_type_): _description_ + clockwise (bool, optional): _description_. Defaults to True. + + Returns: + _type_: _description_ + """ """""" + # Initialize lists to hold angles and (x, y) pairs + angles = [] + coordinates = [] + + # Normalize angles to the range [0, 360) + start_angle = start_angle % 360 + end_angle = end_angle % 360 + + if clockwise: + # Clockwise rotation + current_angle = start_angle + while True: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle (handling wrap-around) (current_angle - step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: + break + + # Decrement the current angle by the step size + current_angle -= step_size + if current_angle < 0: + current_angle += 360 + else: + # Counterclockwise rotation + current_angle = start_angle + while True: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle (handling wrap-around) (current_angle + step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: + break + + # Increment the current angle by the step size + current_angle += step_size + if current_angle >= 360: + current_angle -= 360 + + return [angles, coordinates] + + +def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, + Babs:float, startangle:float, endangle:float, angle_stepsize:float, Settings:str, clockwise=True, base_file_name='', zerowhenfin_bool=False)->None: + # TODO: update docs + """Rotation of the b-field in discrete steps, spectrum is measured at each discrete step in the rotation. Scan angle is + defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. + + Args: + instr1 (pyvisa.resources.Resource): _description_ + instr2 (pyvisa.resources.Resource): _description_ + Babs (float): absolute B-field value in T + startangle (float): start angle in degrees + endangle (float): end angle in degrees + angle_stepsize (float): angle step size in degrees + clockwise (bool): determines the direction of rotation of the B-field. Defaults to True. + zerowhenfin_bool (bool, optional): after finishing the rotation, both B-field components should be set to 0 T. Defaults to False. + """ + + # TODO: possibly rename instr1 and instr2 to the dual and single power supplies respectively?? + + # defines the folder, in which the data from the spectrometer is temporarily stored in + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + + if base_file_name =='': + base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') + + start_time = time.time() # start of the scan function + + startangle = startangle % 360 + endangle = endangle % 360 # ensures that the angles are within [0,360) + + idnstr1 = query_no_echo(instr1, '*IDN?') + idnstr2 = query_no_echo(instr1, '*IDN?') + + intensity_data = [] # To store data from each scan + cwd = os.getcwd() # save original directory + + # find which one is the dual power supply, then, ramp B_x to Babs value + if '2301034' in idnstr1: # serial no. the dual power supply + pass + elif '2101034' in idnstr2: + # swap instruments, instr 1 to be the dual power supply (^= x-axis) + instr1, instr2 = instr2, instr1 + + # save initial low and high sweep limits of each device, and set them back after the rotation + instr1_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + instr2_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + if instr1_bsettings[0][0] == 'T': + instr1_bsettings[1][0] = instr1_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr1_bsettings[2][0] = instr1_bsettings[2][0]*0.1 + if instr2_bsettings[0][0] == 'T': + instr2_bsettings[1][0] = instr2_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr2_bsettings[2][0] = instr2_bsettings[2][0]*0.1 + + # initialise the sweep angle list as well as the sweep limits and directions for each instrument + instr1_lim, instr2_lim = 'LLIM', 'ULIM' + instr1_sweep, instr2_sweep = 'DOWN', 'UP' + + # create lists of angles and discrete Cartesian coordinates + angles, cartesian_coords = polar_to_cartesian(Babs, startangle, endangle, angle_stepsize, clockwise=clockwise) + + if clockwise: # NOTE: old conditional was: startangle > endangle see if this works.... + # reverse sweep limits and directions for the clockwise rotation + instr1_lim, instr2_lim = instr2_lim, instr1_lim + instr1_sweep, instr2_sweep = instr2_sweep, instr1_sweep + + # list of rates (with units) for diff ranges of each device, only up to Range 1 for single power supply as that is already + # the max recommended current. + init_range_lst1 = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'RATE? 0;RATE? 1;RATE? 2').split(';')) + init_range_lst2 = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'RATE? 0;RATE? 1').split(';')) + + min_range_lst = [min(el1[0], el2[0]) for el1,el2 in zip(init_range_lst1, init_range_lst2)] # min rates for each given range + + # set both devices to the min rates + write_no_echo(instr1, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + + write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit + print(f'SWEEPING B-X TO {Babs} T NOW') + + # wait for Babs to be reached by the Bx field + actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') + while abs(actual_bval - Babs) > 0.0001: + time.sleep(5) # little break + actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 + print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') + + # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN + # Helper function that listens to a device + def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event): + while not all_targets_met_event.is_set(): # Loop until the event is set + # value = 0 # Simulate receiving a float from the device INSERT QUERY NO ECHO HERE TO ASK FOR DEVICE IMAG + if '2301034' in device_id: + value = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + elif '2101014' in device_id: + value = sep_num_from_units(query_no_echo(instr2, 'IMAG?'))[0]*0.1 # convert kG to T + print(f"Device {device_id} reports value: {value} T") + + with lock: + shared_values[device_id] = value + # Check if both devices have met their targets + if all(shared_values.get(device) is not None and abs(shared_values[device] - target_value[device]) <= 0.0001 + for device in shared_values): + print(f"Both devices reached their target values: {shared_values}") + all_targets_met_event.set() # Signal that both targets are met + + # time.sleep(1) # Simulate periodic data checking + + # Main function to manage threads and iterate over target values + def monitor_devices(device_target_values, angles_lst, intensity_data=intensity_data): + for iteration, target in enumerate(device_target_values): + print(f"\nStarting iteration {iteration+1} for target values: {target}") + # Shared dictionary to store values from devices + shared_values = {device: None for device in target.keys()} + # Event to signal when both target values are reached + all_targets_met_event = threading.Event() + + # Lock to synchronize access to shared_values + lock = threading.Lock() + + # Create and start threads for each device + threads = [] + for device_id in target.keys(): + thread = threading.Thread(target=listen_to_device, args=(device_id, target, shared_values, lock, all_targets_met_event)) + threads.append(thread) + thread.start() + + # Wait until both devices meet their target values + all_targets_met_event.wait() + print(f"Both target values for iteration {iteration+1} met. Performing action...") + + # Perform some action after both targets are met + # we acquire with the LF + acquire_name_spe = f'{base_file_name}_{angles_lst[iteration]}°' # NOTE: save each intensity file with the given angle + AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + # read the .spe file and get the data as loaded_files + cwd = os.getcwd() # save original directory + os.chdir(temp_folder_path) #change directory + loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + os.chdir(cwd) # go back to original directory + + # Delete the created .spe file from acquiring after getting necessary info + spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') + os.remove(spe_file_path) + + # points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT + # print('Points left in the scan: ', points_left) + + #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + intensity_data.append(loaded_files.data[0][0][0]) + + # Clean up threads + for thread in threads: + thread.join() + + print(f"Threads for iteration {iteration+1} closed.\n") + + #prints total time the mapping lasted + end_time = time.time() + elapsed_time = (end_time - start_time) / 60 + print('Scan time: ', elapsed_time, 'minutes') + + # reset both devices to original sweep limits + write_no_echo(instr1, f'LLIM {instr1_bsettings[1][0]*10};ULIM {instr1_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'LLIM {instr2_bsettings[1][0]*10};ULIM {instr2_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + # reset both devices' initial rates for each range + write_no_echo(instr1, f'RANGE 0 {init_range_lst1[0][0]};RANGE 1 {init_range_lst1[1][0]};RANGE 2 {init_range_lst1[2][0]}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'RANGE 0 {init_range_lst2[0][0]};RANGE 1 {init_range_lst2[1][0]}') # reset the initial limits of the device after the scan + + if zerowhenfin_bool: + write_no_echo(instr1, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above + write_no_echo(instr2, 'SWEEP ZERO') + + #save intensity & WL data as .txt + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas') + # creates new folder for MAP data + new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + os.mkdir(new_folder_name) + # Here the things will be saved in a new folder under user Lukas ! + # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name) + + intensity_data = np.array(intensity_data) + np.savetxt(Settings + f'{angles[0]}°_to_{angles[-1]}°' + experiment_name +'.txt', intensity_data) + # TODO: remove/edit experiment_name in line above, as well in sweep_b_val func, rn takes a global variable below + + wl = np.array(loaded_files.wavelength) + np.savetxt("Wavelength.txt", wl) + + # modify cartesian_coords to suite the required data struct in monitor_devices + cartesian_coords = [{'2301034': t[0], '2101014': t[1]} for t in cartesian_coords] + + # call the helper function to carry out the rotation/measurement of spectrum + monitor_devices(cartesian_coords, angles, intensity_data) + + +################################################################# END OF FUNCTION DEFS ########################################################################################### + +# NOTE: RYAN INTRODUCED SOME FUNCTIONS HERE TO PERFORM THE SCAN + +# Initialise PYVISA ResourceManager +rm = pyvisa.ResourceManager() +# print(rm.list_resources()) +# 'ASRL8::INSTR' for dual power supply, 'ASRL9::INSTR' for single power supply (online PC) +# 'ASRL10::INSTR' for dual power supply, 'ASRL12::INSTR' for single power supply (offline PC) + +try: + # # Open the connection with the APS100 dual power supply + # powerbox_dualsupply = rm.open_resource('ASRL10::INSTR', + # baud_rate=9600, + # data_bits=8, + # parity= pyvisa.constants.Parity.none, + # stop_bits= pyvisa.constants.StopBits.one, + # timeout=10000)# 5000 ms timeout + # write_no_echo(powerbox_dualsupply, 'REMOTE') # turn on the remote mode + + # # # select axis for the dual supply, either z-axis(CHAN 1 ^= Supply A) or x-axis(CHAN 2 ^= Supply B) + # write_no_echo(powerbox_dualsupply, 'CHAN 1') + # # # #for dual until here + + # Open the connection with the APS100 single power supply + powerbox_singlesupply = rm.open_resource('ASRL12::INSTR', + baud_rate=9600, + data_bits=8, + parity= pyvisa.constants.Parity.none, + stop_bits= pyvisa.constants.StopBits.one, + timeout=10000)# 5000 ms timeout + write_no_echo(powerbox_singlesupply, 'REMOTE') # turn on the remote mode + #for single until here + # TODO: uncomment AMC connection code later, when moving the probe in cryostat is needed. + # Setup connection to AMC + # amc = AMC.Device(IP) + # amc.connect() + + # # Internally, axes are numbered 0 to 2 + # amc.control.setControlOutput(0, True) + # amc.control.setControlOutput(1, True) + + + auto = Automation(True, List[String]()) + experiment = auto.LightFieldApplication.Experiment + acquireCompleted = AutoResetEvent(False) + + experiment.Load("2025_03_28_Priyanka_CrSBr_DR_Sweep") + experiment.ExperimentCompleted += experiment_completed # we are hooking a listener. + # experiment.SetValue(SpectrometerSettings.GratingSelected, '[750nm,1200][0][0]') + # InitializerFilenameParams() + + + #set scan range and resolution in nanometers + range_x = 20000 + range_y = 20000 + resolution = 1000 + # set B-field scan range and resolution (all in T) + set_llim_bval = -0.3 + set_ulim_bval = 0.3 + set_res_bval = 0.003 + + #Here you can specify the filename of the map e.g. put experiment type, exposure time, used filters, etc.... + # 'PL_SP_700_LP_700_HeNe_52muW_exp_2s_Start_' + # experiment_settings = 'PL_X_1859.2_Y_3918.3_HeNe_10.4muW_H_a-axis_LP_SP_650_exp_180s_600g_cwl_930_det_b-axis_Pol_90_l2_45' + experiment_settings = 'DR_white_6th spot_Power_G600_exp_25s_l1_40_l2_262_det_b_mag_b' + #The program adds the range of the scan as well as the resolution and the date and time of the measurement + # f"{set_llim_bval}T_to_{set_ulim_bval}T_{set_res_bval}T_{datetime.datetime.now().strftime('%Y_%m_%d_%H%M')}" + experiment_name = f"{set_llim_bval}T_to_{set_ulim_bval}T_stepsize_{set_res_bval}T" + + # this moves the probe in xy-direction and measures spectrum there + # move_scan_xy(range_x, range_y, resolution, experiment_settings, experiment_name) + + # ramp_b_val(powerbox_singlesupply, 0, 'y-axis') + # ramp_b_val(powerbox_dualsupply, 0, 'z-axis') + + + # for single/ dual replace and vice versa all the way down + sweep_b_val(powerbox_singlesupply, set_llim_bval, set_ulim_bval, set_res_bval, 'y-axis', + experiment_settings, experiment_name, zerowhenfin_bool=True, reversescan_bool=False, loopscan_bool=True) + # write_no_echo(powerbox_dualsupply, 'LOCAL') # turn off the remote mode + write_no_echo(powerbox_singlesupply, 'LOCAL') # turn off the remote mode + + time.sleep(0.5) + # powerbox_dualsupply.close() + powerbox_singlesupply.close() + +except Exception as e: + print(e) + # Internally, axes are numbered 0 to 2 + + # write_no_echo(powerbox_dualsupply, 'LOCAL') # turn off the remote mode + write_no_echo(powerbox_singlesupply, 'LOCAL') # turn off the remote mode + + time.sleep(0.5) + # powerbox_dualsupply.close() + powerbox_singlesupply.close() \ No newline at end of file diff --git a/Mapping_Script_Lukas_Version_2024_08_27.py b/Mapping_Script_Lukas_Version_2024_08_27.py new file mode 100644 index 0000000..9b3f06a --- /dev/null +++ b/Mapping_Script_Lukas_Version_2024_08_27.py @@ -0,0 +1,355 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri Dec 22 15:10:10 2023 +Lightfield + Positioner +@author: Local Admin +""" +import AMC +import csv +import time +import clr +import sys +import os +import spe2py as spe +import spe_loader as sl +import pandas as pd +import time +from System.IO import * +from System import String +import numpy as np +import matplotlib.pyplot as plt +import datetime + + +#First choose your controller +IP_AMC300 = "192.168.71.101" +IP_AMC100 = "192.168.71.100" + +# IP = "192.168.1.1" +IP = IP_AMC300 + + +# Import os module +import os, glob, string + +# Import System.IO for saving and opening files +from System.IO import * + +from System.Threading import AutoResetEvent + +# Import C compatible List and String +from System import String +from System.Collections.Generic import List + +# Add needed dll references +sys.path.append(os.environ['LIGHTFIELD_ROOT']) +sys.path.append(os.environ['LIGHTFIELD_ROOT']+"\\AddInViews") +sys.path.append(r'C:\Program Files\Princeton Instruments\LightField\AddInViews') #I added them by hand -serdar +sys.path.append(r'C:\Program Files\Princeton Instruments\LightField') #this one also +clr.AddReference('PrincetonInstruments.LightFieldViewV5') +clr.AddReference('PrincetonInstruments.LightField.AutomationV5') +clr.AddReference('PrincetonInstruments.LightFieldAddInSupportServices') +os.environ['LIGHTFIELD_ROOT'] = r'C:\Program Files\Princeton Instruments\LightField' +# PI imports +from PrincetonInstruments.LightField.Automation import Automation +from PrincetonInstruments.LightField.AddIns import ExperimentSettings +from PrincetonInstruments.LightField.AddIns import CameraSettings +#from PrincetonInstruments.LightField.AddIns import DeviceType +from PrincetonInstruments.LightField.AddIns import SpectrometerSettings +from PrincetonInstruments.LightField.AddIns import RegionOfInterest + +######################################################################################################### code begins from here ############################################# + +def set_custom_ROI(): + + # Get device full dimensions + dimensions = experiment.FullSensorRegion() + + regions = [] + + # Add two ROI to regions + regions.append( + RegionOfInterest( + int(dimensions.X), int(dimensions.Y), + int(dimensions.Width), int(dimensions.Height//4), # Use // for integer division + int(dimensions.XBinning), int(dimensions.Height//4))) + + + + # Set both ROI + experiment.SetCustomRegions(regions) + +def experiment_completed(sender, event_args): #callback function which is hooked to event completed, this is the listener + print("... Acquisition Complete!") + acquireCompleted.Set() #set the event. This puts the autoresetevent false.(look at .NET library for furher info) + +def InitializerFilenameParams(): + experiment.SetValue(ExperimentSettings.FileNameGenerationAttachIncrement, False) + experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementNumber, 1.0) + experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementMinimumDigits, 2.0) + experiment.SetValue(ExperimentSettings.FileNameGenerationAttachDate, False) + experiment.SetValue(ExperimentSettings.FileNameGenerationAttachTime, False) + +def AcquireAndLock(name): + print("Acquiring...", end = "") + # name += 'Exp{0:06.2f}ms.CWL{1:07.2f}nm'.format(\ + # experiment.GetValue(CameraSettings.ShutterTimingExposureTime)\ + # ,experiment.GetValue(SpectrometerSettings.GratingCenterWavelength)) + + experiment.SetValue(ExperimentSettings.FileNameGenerationBaseFileName, name) #this creates .spe file with the name + experiment.Acquire() # this is an ashynrchronus func. + acquireCompleted.WaitOne() + +def calculate_distance(x1, y1, x2, y2): + return np.sqrt((x2 - x1)**2 + (y2 - y1)**2) + +def generate_scan_positions(center, range_val, resolution): + positive_range = np.arange(center, center + range_val + resolution, resolution) + return positive_range + +def save_as_csv(filename, position_x, position_y): + file_existance = os.path.isfile(filename) + + with open(filename, 'a', newline = '') as csvfile: + writer = csv.writer(csvfile) + + if not file_existance: + writer.writerow(['x_coordinates','y_coordinates']) + + writer.writerow([position_x, position_y]) + +def move_axis(axis, target): + """ + This function moves an axis to the specified target and stop moving after it is in the really closed + vicinity (+- 25nm) of the target (listener hooked to it). + """ + amc.move.setControlTargetPosition(axis, target) + amc.control.setControlMove(axis, True) + # while not (target - 25) < amc.move.getPosition(axis) < (target + 25): + # time.sleep(0.1) + # time.sleep(0.15) + # while not (target - 25) < amc.move.getPosition(axis) < (target + 25): + # time.sleep(0.1) + # amc.control.setControlMove(axis, False) + +def move_xy(target_x, target_y): # moving in x and y direction closed to desired position + amc.move.setControlTargetPosition(0, target_x) + amc.control.setControlMove(0, True) + amc.move.setControlTargetPosition(1, target_y) + amc.control.setControlMove(1, True) + while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25): + time.sleep(0.1) + time.sleep(0.15) + while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25): + time.sleep(0.1) + + amc.control.setControlOutput(0, False) + amc.control.setControlOutput(1, False) + + +# intensity_data = [] # To store data from each scan +# data_list = [] + +def move_scan_xy(range_x, range_y, resolution, Settings, baseFileName): + """ + This function moves the positioners to scan the sample with desired ranges and resolution in 2 dimensions. + At the end it saves a csv file + + Parameters + ---------- + range_x : integer in nm. max value is 5um + Scan range in x direction. + range_y : integer in nm. max value is 5um + Scan range in y direction. + resolution : integer in nm. + Room temprature max res is 50nm. In cyrostat (4K) it is 10nm (check the Attocube manual) + baseFileName: string. At the end the saved file will be: baseFileName_scan_data.csv and it will be saved to the current directory + + Returns + ------- + None. + + """ + start_time = time.time() + axis_x = 0 #first axis + axis_y = 1 #second axis + center_x = amc.move.getPosition(axis_x) + center_y = amc.move.getPosition(axis_y) + # #check if the intput range is reasonable + # if amc.move.getPosition(axis_x) + range_x >= 5000 or amc.move.getPosition(axis_x)- range_x <= 0 or amc.move.getPosition(axis_y) + range_y >=5000 or amc.move.getPosition(axis_y) - range_y <= 5000 : + # print("scan range is out of range!") + # return + # +- range from current positions for x and y directions + + + array_x = generate_scan_positions(center_x, range_x, resolution) + array_y = generate_scan_positions(center_y, range_y, resolution) + total_points = len(array_x)*len(array_y) + len_y = len(array_y) + intensity_data = [] # To store data from each scan + data_list = [] + cwd = os.getcwd() # save original directory + + #This gives a directory, in which the script will save the spectrum of each spot as spe + #However, it will open the spectrum, convert it to txt, add it to the intensity_data and delete the spe file + Path_save = "C:/Users/localadmin/Desktop/Users/Lukas/Map_dump" + + #scanning loop + for i, x_positions in enumerate(array_x): + move_axis(axis_x, x_positions) + y = False + + for j, y_positions in enumerate(array_y): + move_axis(axis_y, y_positions) + time.sleep(2) + if j == 0: + time.sleep(10) + #each time when the positioner comes to the beggining of a new line + #this if will make the positioner wait a bit longer to really go to the target. + if y == False: + move_axis(axis_y, y_positions) + y = True + + + + #we acquire with the LF + acquire_name_spe = f'{baseFileName}_X{x_positions}_Y{y_positions}' + AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + #read the .spe file and get the data as loaded_files + cwd = os.getcwd() # save original directory + os.chdir(Path_save) #change directory + loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + os.chdir(cwd) # go back to original directory + + # Delete the created .spe file from acquiring after getting necessary info + spe_file_path = os.path.join(Path_save, acquire_name_spe + '.spe') + os.remove(spe_file_path) + + distance = calculate_distance(x_positions, y_positions,amc.move.getPosition(axis_x), amc.move.getPosition(axis_y)) + + points_left = total_points - (i * len_y + (j+1)) + 1 + print('Points left in the scan: ', points_left) + + #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + intensity_data.append(loaded_files.data[0][0][0]) + + data_list.append({ + 'position_x': x_positions, + 'position_y': y_positions, + 'actual_x': amc.move.getPosition(axis_x), + 'actual_y': amc.move.getPosition(axis_y), + 'distance': distance, + }) + + #moves back to starting position + move_axis(axis_x, center_x) + move_axis(axis_y, center_y) + + #prints total time the mapping lasted + end_time = time.time() + elapsed_time = (end_time - start_time) / 60 + print('Scan time: ', elapsed_time, 'minutes') + + # df = pd.DataFrame(data_list) + + #save intensity & WL data as .txt + os.chdir('C:/Users/localadmin/Desktop/Users/Priyanka/2025/stacked_2L/PL_Map_0T/250325') + # creates new folder for MAP data + new_folder_name = "PL_Map_By_0T_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + os.mkdir(new_folder_name) + # Here the things will be saved in a new folder under user Lukas ! + # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! + os.chdir('C:/Users/localadmin/Desktop/Users/Priyanka/2025/stacked_2L/PL_Map_0T/250325/'+ new_folder_name) + + intensity_data = np.array(intensity_data) + np.savetxt(Settings + str(center_x) + '_' + str(center_y) + experiment_name +'.txt', intensity_data) + + wl = np.array(loaded_files.wavelength) + np.savetxt("Wavelength.txt", wl) + + time.sleep(20) + + amc.control.setControlMove(axis_x, False) + amc.control.setControlMove(axis_y, False) + + # wl.to_csv("wl", index = False) + + + + # #Plot the scan data + # plt.figure(figsize=(12, 6)) + # # Plot 1: Target and Actual Positions + # plt.subplot(1, 2, 1) + # plt.scatter(df['position_x'], df['position_y'], c='green', label='Target Positions') + # plt.scatter(df['actual_x'], df['actual_y'], c='red', label='Actual Positions') + # plt.title('Scan Visualization') + # plt.xlabel('X Position') + # plt.ylabel('Y Position') + # plt.legend() + # plt.grid(True) + + # #Plot 2: Distance from Target Position + # mean_distance = df['distance'].mean() + # plt.subplot(1, 2, 2) + # plt.plot(df['distance'], label='Distance from Target Position') + # plt.title(f'Distance from Target Position\nMean Distance: {mean_distance:.2f}') + # plt.xlabel('Scan Point') + # plt.ylabel('Distance') + # plt.subplot(1, 2, 2) + # plt.hist(df['distance'], bins=30, color='skyblue', edgecolor='black', alpha=0.7) + # plt.title(f'Distribution of Distance from Target Position\nMean Distance: {mean_distance:.2f} nm') + # plt.xlabel('Distance') + # plt.ylabel('Frequency') + # plt.legend() + # plt.grid(True) + # plt.text(0.95, 0.95, f'Herz: {(amc.control.getControlFrequency(0)/1000):.2f} Hz', horizontalalignment='right', verticalalignment='top', transform=plt.gca().transAxes) + # plt.text(0.95, 0.90, f'Scan Time: {elapsed_time:.2f} mins', horizontalalignment='right', verticalalignment='top', transform=plt.gca().transAxes) + # plt.text(0.95, 0.05, f"Scan Date: {datetime.datetime.now().strftime('%Y_%m_%d_%H%M')}", horizontalalignment='right', verticalalignment='bottom', transform=plt.gca().transAxes) + # plt.legend() + # plt.grid(True) + # plt.axhline(mean_distance, color='orange', linestyle='--', label=f'Mean Distance: {mean_distance:.2f}') + # plt.tight_layout() + + # plt.savefig(Settings + str(center_x) + '_' + str(center_y) +'_' + experiment_name + '.png') + # plt.show() + # os.chdir(cwd) + +# Setup connection to AMC +amc = AMC.Device(IP) +amc.connect() + +# Internally, axes are numbered 0 to 2 +# amc.control.setControlOutput(0, True) +# amc.control.setControlOutput(1, True) + + +auto = Automation(True, List[String]()) +experiment = auto.LightFieldApplication.Experiment +acquireCompleted = AutoResetEvent(False) + +experiment.Load("2025_02_13_Priyanka_CrSBr") +experiment.ExperimentCompleted += experiment_completed # we are hooking a listener. +# experiment.SetValue(SpectrometerSettings.GratingSelected, '[750nm,1200][0][0]') +# InitializerFilenameParams() + + + +#set scna range and resolution in nanometers + +range_x = 20000 +range_y = 20000 +resolution = 1000 + +#Here you can specify the filename of the map e.g. put experiment type, exposure time, used filters, etc.... +experiment_settings = 'PL_he ne_stacked_2L_G150_P300uW_5s_test_l1_52_l2_260' +# experiment_settings = 'DR_NKT_OD2_rep_0.15_600g_cwl_660_exp_3s_Start_' +# experiment_settings = 'DR_Halogen_Lamp_lin_b-axis_600g_cwl_910_exp_2s_Start_' +#The program adds the range of the scan as well as the resolution and the date and time of the measurement +experiment_name = f"{range_x}nm_{range_y}nm_{resolution}nm_{datetime.datetime.now().strftime('%Y_%m_%d_%H%M')}" + + +move_scan_xy(range_x, range_y, resolution, experiment_settings, experiment_name) + +# Internally, axes are numbered 0 to 2 + -- 2.39.5 From 35f16f7dcdaf5419c59d21be13fa82ebe4279439 Mon Sep 17 00:00:00 2001 From: ryantan Date: Mon, 14 Apr 2025 10:43:08 +0200 Subject: [PATCH 19/39] removed AttocubePowerboxScript.py --- AttocubePowerboxScript.py | 935 -------------------------------------- 1 file changed, 935 deletions(-) delete mode 100644 AttocubePowerboxScript.py diff --git a/AttocubePowerboxScript.py b/AttocubePowerboxScript.py deleted file mode 100644 index b3715e9..0000000 --- a/AttocubePowerboxScript.py +++ /dev/null @@ -1,935 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Created on Fri Dec 22 15:10:10 2023 -Lightfield + Positioner -@author: Serdar, adjusted by Lukas -""" -############################################ -# Packages from Ryan -import re -import math -import threading -import pyvisa -# from pyvisa import ResourceManager, constants - -# B Field Limits (in T) -BX_MAX = 1.7 -BY_MAX = 1.7 -BZ_MAX = 4.0 -############################################ - -import AMC -import csv -import time -import clr -import sys -import os -import spe2py as spe -import spe_loader as sl -import pandas as pd -import time -from System.IO import * -from System import String -import numpy as np -import matplotlib.pyplot as plt -import datetime -from typing import Union - - -#First choose your controller -IP_AMC300 = "192.168.1.1" -IP_AMC100 = "192.168.71.100" - -# IP = "192.168.1.1" -IP = IP_AMC100 - - -# Import os module -import os, glob, string - -# Import System.IO for saving and opening files -from System.IO import * - -from System.Threading import AutoResetEvent - -# Import C compatible List and String -from System import String -from System.Collections.Generic import List - -# Add needed dll references -sys.path.append(os.environ['LIGHTFIELD_ROOT']) -sys.path.append(os.environ['LIGHTFIELD_ROOT']+"\\AddInViews") -sys.path.append(r'C:\Program Files\Princeton Instruments\LightField\AddInViews') #I added them by hand -serdar -sys.path.append(r'C:\Program Files\Princeton Instruments\LightField') #this one also -clr.AddReference('PrincetonInstruments.LightFieldViewV5') -clr.AddReference('PrincetonInstruments.LightField.AutomationV5') -clr.AddReference('PrincetonInstruments.LightFieldAddInSupportServices') -os.environ['LIGHTFIELD_ROOT'] = r'C:\Program Files\Princeton Instruments\LightField' -# PI imports -from PrincetonInstruments.LightField.Automation import Automation -from PrincetonInstruments.LightField.AddIns import ExperimentSettings -from PrincetonInstruments.LightField.AddIns import CameraSettings -#from PrincetonInstruments.LightField.AddIns import DeviceType -from PrincetonInstruments.LightField.AddIns import SpectrometerSettings -from PrincetonInstruments.LightField.AddIns import RegionOfInterest - -######################################################################################################### code begins from here ############################################# - -def set_custom_ROI(): - - # Get device full dimensions - dimensions = experiment.FullSensorRegion() - - regions = [] - - # Add two ROI to regions - regions.append( - RegionOfInterest( - int(dimensions.X), int(dimensions.Y), - int(dimensions.Width), int(dimensions.Height//4), # Use // for integer division - int(dimensions.XBinning), int(dimensions.Height//4))) - - - - # Set both ROI - experiment.SetCustomRegions(regions) - -def experiment_completed(sender, event_args): #callback function which is hooked to event completed, this is the listener - print("... Acquisition Complete!") - acquireCompleted.Set() #set the event. This puts the autoresetevent false.(look at .NET library for furher info) - -def InitializerFilenameParams(): - experiment.SetValue(ExperimentSettings.FileNameGenerationAttachIncrement, False) - experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementNumber, 1.0) - experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementMinimumDigits, 2.0) - experiment.SetValue(ExperimentSettings.FileNameGenerationAttachDate, False) - experiment.SetValue(ExperimentSettings.FileNameGenerationAttachTime, False) - -def AcquireAndLock(name): - print("Acquiring...", end = "") - # name += 'Exp{0:06.2f}ms.CWL{1:07.2f}nm'.format(\ - # experiment.GetValue(CameraSettings.ShutterTimingExposureTime)\ - # ,experiment.GetValue(SpectrometerSettings.GratingCenterWavelength)) - - experiment.SetValue(ExperimentSettings.FileNameGenerationBaseFileName, name) #this creates .spe file with the name - experiment.Acquire() # this is an ashynrchronus func. - acquireCompleted.WaitOne() - -def calculate_distance(x1, y1, x2, y2): - return np.sqrt((x2 - x1)**2 + (y2 - y1)**2) - -def generate_scan_positions(center, range_val, resolution): - positive_range = np.arange(center, center + range_val + resolution, resolution) - return positive_range - -def save_as_csv(filename, position_x, position_y): - file_existance = os.path.isfile(filename) - - with open(filename, 'a', newline = '') as csvfile: - writer = csv.writer(csvfile) - - if not file_existance: - writer.writerow(['x_coordinates','y_coordinates']) - - writer.writerow([position_x, position_y]) - -def move_axis(axis, target): - """ - This function moves an axis to the specified target and stop moving after it is in the really closed - vicinity (+- 25nm) of the target (listener hooked to it). - """ - amc.move.setControlTargetPosition(axis, target) - amc.control.setControlMove(axis, True) - while not (target - 25) < amc.move.getPosition(axis) < (target + 25): - time.sleep(0.1) - time.sleep(0.15) - while not (target - 25) < amc.move.getPosition(axis) < (target + 25): - time.sleep(0.1) - amc.control.setControlMove(axis, False) - -def move_xy(target_x, target_y): # moving in x and y direction closed to desired position - amc.move.setControlTargetPosition(0, target_x) - amc.control.setControlMove(0, True) - amc.move.setControlTargetPosition(1, target_y) - amc.control.setControlMove(1, True) - while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25): - time.sleep(0.1) - time.sleep(0.15) - while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25): - time.sleep(0.1) - - amc.control.setControlOutput(0, False) - amc.control.setControlOutput(1, False) - - -# intensity_data = [] # To store data from each scan -# data_list = [] - -def move_scan_xy(range_x, range_y, resolution, Settings, baseFileName): - """ - This function moves the positioners to scan the sample with desired ranges and resolution in 2 dimensions. - At the end it saves a csv file - - Parameters - ---------- - range_x : integer in nm. max value is 5um - Scan range in x direction. - range_y : integer in nm. max value is 5um - Scan range in y direction. - resolution : integer in nm. - Room temprature max res is 50nm. In cyrostat (4K) it is 10nm (check the Attocube manual) - baseFileName: string. At the end the saved file will be: baseFileName_scan_data.csv and it will be saved to the current directory - - Returns - ------- - None. - - """ - start_time = time.time() - axis_x = 0 #first axis - axis_y = 1 #second axis - center_x = amc.move.getPosition(axis_x) - center_y = amc.move.getPosition(axis_y) - # #check if the intput range is reasonable - # if amc.move.getPosition(axis_x) + range_x >= 5000 or amc.move.getPosition(axis_x)- range_x <= 0 or amc.move.getPosition(axis_y) + range_y >=5000 or amc.move.getPosition(axis_y) - range_y <= 5000 : - # print("scan range is out of range!") - # return - # +- range from current positions for x and y directions - - - array_x = generate_scan_positions(center_x, range_x, resolution) - array_y = generate_scan_positions(center_y, range_y, resolution) - total_points = len(array_x)*len(array_y) - len_y = len(array_y) - intensity_data = [] # To store data from each scan - data_list = [] - cwd = os.getcwd() # save original directory - - #This gives a directory, in which the script will save the spectrum of each spot as spe - #However, it will open the spectrum, convert it to txt, add it to the intensity_data and delete the spe file - temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" - - #scanning loop - for i, x_positions in enumerate(array_x): - move_axis(axis_x, x_positions) - y = False - for j, y_positions in enumerate(array_y): - move_axis(axis_y, y_positions) - #each time when the positioner comes to the beggining of a new line - #this if will make the positioner wait a bit longer to really go to the target. - if y == False: - move_axis(axis_y, y_positions) - y = True - - #we acquire with the LF - acquire_name_spe = f'{baseFileName}_X{x_positions}_Y{y_positions}' - AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. - - #read the .spe file and get the data as loaded_files - cwd = os.getcwd() # save original directory - os.chdir(temp_folder_path) #change directory - loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable - os.chdir(cwd) # go back to original directory - - # Delete the created .spe file from acquiring after getting necessary info - spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') - os.remove(spe_file_path) - - distance = calculate_distance(x_positions, y_positions,amc.move.getPosition(axis_x), amc.move.getPosition(axis_y)) - - points_left = total_points - (i * len_y + (j+1)) + 1 - print('Points left in the scan: ', points_left) - - #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) - intensity_data.append(loaded_files.data[0][0][0]) - - data_list.append({ - 'position_x': x_positions, - 'position_y': y_positions, - 'actual_x': amc.move.getPosition(axis_x), - 'actual_y': amc.move.getPosition(axis_y), - 'distance': distance, - }) - - #moves back to starting position - move_axis(axis_x, center_x) - move_axis(axis_y, center_y) - - #prints total time the mapping lasted - end_time = time.time() - elapsed_time = (end_time - start_time) / 60 - print('Scan time: ', elapsed_time, 'minutes') - - # df = pd.DataFrame(data_list) - - #save intensity & WL data as .txt - os.chdir('C:/Users/localadmin/Desktop/Users/Lukas') - # creates new folder for MAP data - new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" - os.mkdir(new_folder_name) - # Here the things will be saved in a new folder under user Lukas ! - # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! - os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name) - - intensity_data = np.array(intensity_data) - np.savetxt(Settings + str(center_x) + '_' + str(center_y) + experiment_name +'.txt', intensity_data) - - wl = np.array(loaded_files.wavelength) - np.savetxt("Wavelength.txt", wl) - -################################################################# RYAN'S FUNCTIONS HERE ########################################################################################## - -def sep_num_from_units(powerbox_output :str)->list: - ''' - Receives a string as input and separates the numberic value and unit and returns it as a list. - - Parameters - ---------- - powerbox_output : str - string output from the attocube powerbox, e.g. 1.35325kG - - Returns - ------- - list - list of float value and string (b value and it's units). If string is purely alphabets, then return a single element list - - ''' - match = re.match(r'\s*([+-]?\d*\.?\d+)([A-Za-z]+)', powerbox_output) - if match: - numeric_part = float(match.group(1)) # Convert the numeric part to a float - alphabetic_part = match.group(2) # Get the alphabetic part - return [numeric_part, alphabetic_part] - else: - return [powerbox_output,] - - -def query_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: - """helper function for the Attocube APS100 that queries a function to the device, removing the echo. - - Args: - instr (pyvisa.resources.Resource): - command (str): commands, can be stringed in series with ; between commands - sleeptime (float, optional): delay time between commands. Defaults to 0.01. - - Returns: - str: _description_ - """ '''''' - try: - print(f"Sending command: {command}") - instr.write(command) - time.sleep(sleeptime) - echo_response = instr.read() # Read and discard the echo - # print(f"Echo response: {echo_response}") - actual_response = instr.read() # Read the actual response - print(f"Actual response: {actual_response}") - return actual_response - except pyvisa.VisaIOError as e: - print(f"Error communicating with instrument: {e}") - return None - - -def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: - """helper function for the Attocube APS100 that writes a function to the device, removing the echo. - - Args: - instr (pyvisa.resources.Resource): - command (str): commands, can be stringed in series with ; between commands - sleeptime (float, optional): delay time between commands. Defaults to 0.01. - - Returns: - str: _description_ - """ '''''' - try: - print(f"Sending command: {command}") - instr.write(command) - time.sleep(sleeptime) # Give the device some time to process - try: - while True: - echo_response = instr.read() # Read and discard the echo - # print(f"Echo response: {echo_response}") - except pyvisa.VisaIOError as e: - # Expected timeout after all echoed responses are read - if e.error_code != pyvisa.constants.VI_ERROR_TMO: - raise - except pyvisa.VisaIOError as e: - print(f"Error communicating with instrument: {e}") - - -# receive values in units of T, rescale in kg to talk with the power supplyy. 1T = 10kG -# NOTE: removed singlepowersupply_bool, reading serial-nr. of the device instead. -# old save folder: "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" -def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, - res:float, magnet_coil:str, Settings:str, base_file_name='', - reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False)->None: - # TODO: update docs in the end - """ this function performs a sweep of the B field of the chosen magnet coil. It creates a list o B values from the given min and max values, - with the given resolution. For each value, a measurement of the spectrum of the probe in the cryostat is made, using the LightField spectrometer. - - Args: - instr (pyvisa.resources.Resource): chosen power supply device to connect to - min_bval (float): min B value of the scan (please input in units of Tesla) - max_bval (float): max B value of the scan (please input in units of Tesla) - res (float): resolution of the list of B values (please input in units of Tesla) - magnet_coil (str): select magnet coil to be used. String should be 'x-axis','y-axis' or 'z-axis'. - Settings (str): experiment settings, included in file name. - base_file_name (str, optional): base file name. Defaults to ''. - singlepowersupply_bool (bool, optional): _description_. Defaults to False. - reversescan_bool (bool, optional): _description_. Defaults to False. - zerowhenfin_bool (bool, optional): _description_. Defaults to False. - - Raises: - ValueError: when By limit is exceeded. - ValueError: when Bz limit is exceeded. - ValueError: when Bx limit is exceeded. - ConnectionError: when no device is connected. - """ '''''' - - def pyramid_list(lst) -> Union[list, np.ndarray]: - """reverses the list and removes the first element of reversed list. Then, this is appended to - the end of the original list and returned as the 'pyramid' list. - - Args: - lst (list or np.ndarray): - Raises: - TypeError: if the input object isn't a list or np.ndarray - Returns: - Union[list, np.ndarray]: the pyramid list - """ '''''' - if isinstance(lst, list): - return lst + lst[-2::-1] - elif isinstance(lst, np.ndarray): - return np.append(lst, lst[-2::-1]) - else: - raise TypeError('Please input a list!') - - # defines the folder, in which the data from the spectrometer is temporarily stored in - temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" - - # if path_save =='': - # path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_") - - if base_file_name =='': - base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') - - start_time = time.time() # start of the scan function - - instr_info = query_no_echo(instr, '*IDN?') - - instr_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element list of lists containing the set unit, llim and ulim - - if instr_bsettings[0][0] == 'T': - instr_bsettings[1][0] = instr_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T - instr_bsettings[2][0] = instr_bsettings[2][0]*0.1 - - # if singlepowersupply_bool: # checks limits of Bx or By - # if (min_bval< -BY_MAX) or (max_bval > BY_MAX): - # raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.') - # elif '1' in query_no_echo(instr, 'CHAN?'): # check if its the coils for Bz - # if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX): - # raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.') - # else: # checks limits of Bx - # if (min_bval< -BX_MAX) or (max_bval > BX_MAX): - # raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') - - if '2101014' in instr_info and (magnet_coil=='y-axis'): # single power supply - if (min_bval< -BY_MAX) or (max_bval > BY_MAX): - raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.') - elif '2301034' in instr_info: # dual power supply - if magnet_coil=='z-axis': # check if its the coils for Bz - if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX): - raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.') - write_no_echo(instr, 'CHAN 1') - elif magnet_coil=='x-axis': # checks limits of Bx - if (min_bval< -BX_MAX) or (max_bval > BX_MAX): - raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.') - write_no_echo(instr, 'CHAN 2') - else: - raise ConnectionError('Device is not connected!') - - write_no_echo(instr, f'LLIM {min_bval*10};ULIM {max_bval*10}') # sets the given limits, must convert to kG for the device to read - bval_lst = np.arange(min_bval, max_bval + res, res) # creates list of B values to measure at, with given resolution, in T - - # TODO: unused, see if can remove - # init_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # queries the initial B value of the coil, rescale from kG to T - - init_lim, subsequent_lim = 'LLIM', 'ULIM' - init_sweep, subsequent_sweep = 'DOWN', 'UP' - - #################################################### - # TODO: decide whether to start at min b val or max b val, depending on which one is nearer, IMPLEMENT THIS LATER - # nearest_bval = (abs(init_bval - min_bval), abs(init_bval - max_bval)) - # if nearest_bval[0] <= nearest_bval[1]: - # reversescan_bool = True - #################################################### - - # if reverse scan, then flip the values in the b list, and swap the initial limit and sweep conditions - if reversescan_bool: - bval_lst = bval_lst[::-1] - init_lim, subsequent_lim = subsequent_lim, init_lim - init_sweep, subsequent_sweep = subsequent_sweep, init_sweep - - # creates the pyramid list of B vals if one were to perform a hysteresis measurement - if loopscan_bool: - bval_lst = pyramid_list(bval_lst) - - total_points = len(bval_lst) - middle_index_bval_lst = total_points // 2 - intensity_data = [] # To store data from each scan - cwd = os.getcwd() # save original directory - - # NOTE: helper function for the scanning loop - def helper_scan_func(idx, bval, instr=instr, init_lim=init_lim, init_sweep=init_sweep, - subsequent_lim=subsequent_lim, subsequent_sweep=subsequent_sweep, sleep=5): - if idx == 0: # for first iteration, sweep to one of the limits - write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG - write_no_echo(instr, f'SWEEP {init_sweep}') - else: - write_no_echo(instr, f'{subsequent_lim} {bval*10}') # convert back to kG - write_no_echo(instr, f'SWEEP {subsequent_sweep}') - - actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # convert kG to T - print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') - - while abs(actual_bval - bval) > 0.0001: - time.sleep(5) # little break - actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 - # update the actual bval - print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') - - #scanning loop - for i, bval in enumerate(bval_lst): - # if init_bval == bval: - # # if initial bval is equal to the element of the given iteration from the bval_lst, then commence measuring the spectrum - # pass - # else: - - # NOTE: original code without the loop scan - ################################################ - # if i == 0: # for first iteration, sweep to one of the limits - # write_no_echo(instr, f'{init_lim} {bval*10}') # convert back to kG - # write_no_echo(instr, f'SWEEP {init_sweep}') - # else: - # write_no_echo(instr, f'{subsequent_lim} {bval*10}') # convert back to kG - # write_no_echo(instr, f'SWEEP {subsequent_sweep}') - - # actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # convert kG to T - # print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') - - # while abs(actual_bval - bval) > 0.0001: - # time.sleep(5) # little break - # actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 - # # update the actual bval - # print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T') - ############################################### - if not loopscan_bool: - helper_scan_func(i, bval) - else: - if i <= middle_index_bval_lst: - helper_scan_func(i, bval) - else: - helper_scan_func(i, bval, instr=instr, init_lim=subsequent_lim, init_sweep=subsequent_sweep, - subsequent_lim=init_lim, subsequent_sweep=init_sweep, sleep=5) - - time.sleep(5) - # we acquire with the LF - acquire_name_spe = f'{base_file_name}_{bval}T' - AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. - - # read the .spe file and get the data as loaded_files - cwd = os.getcwd() # save original directory - os.chdir(temp_folder_path) #change directory - loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable - os.chdir(cwd) # go back to original directory - - # Delete the created .spe file from acquiring after getting necessary info - spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') - os.remove(spe_file_path) - - points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT - print('Points left in the scan: ', points_left) - - #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) - intensity_data.append(loaded_files.data[0][0][0]) - - #prints total time the mapping lasted - end_time = time.time() - elapsed_time = (end_time - start_time) / 60 - print('Scan time: ', elapsed_time, 'minutes') - - write_no_echo(instr, f'LLIM {instr_bsettings[1][0]*10};ULIM {instr_bsettings[2][0]*10}') # reset the initial limits of the device after the scan - - if zerowhenfin_bool: - write_no_echo(instr, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above - - #save intensity & WL data as .txt - os.chdir('C:/Users/localadmin/Desktop/Users/Lukas') - # creates new folder for MAP data - new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" - os.mkdir(new_folder_name) - # Here the things will be saved in a new folder under user Lukas ! - # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! - os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name) - - intensity_data = np.array(intensity_data) - np.savetxt(Settings + str(min_bval) + 'T_to_' + str(max_bval) + 'T' + experiment_name +'.txt', intensity_data) - - wl = np.array(loaded_files.wavelength) - np.savetxt("Wavelength.txt", wl) - - -def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True): - # TODO: DOCS - """Creates a list of discrete cartesian coordinates (x,y), given the radius, start- and end angles, the angle step size, and the direction of rotation. - Function then returns a list of two lists: list of angles and list of cartesian coordinates (x,y coordinates in a tuple). - - Args: - radius (_type_): _description_ - start_angle (_type_): _description_ - end_angle (_type_): _description_ - step_size (_type_): _description_ - clockwise (bool, optional): _description_. Defaults to True. - - Returns: - _type_: _description_ - """ """""" - # Initialize lists to hold angles and (x, y) pairs - angles = [] - coordinates = [] - - # Normalize angles to the range [0, 360) - start_angle = start_angle % 360 - end_angle = end_angle % 360 - - if clockwise: - # Clockwise rotation - current_angle = start_angle - while True: - # Append the current angle to the angles list - angles.append(current_angle % 360) - - # Convert the current angle to radians - current_angle_rad = math.radians(current_angle % 360) - - # Convert polar to Cartesian coordinates - x = radius * math.cos(current_angle_rad) - y = radius * math.sin(current_angle_rad) - - # Append the (x, y) pair to the list - coordinates.append((x, y)) - - # Check if we've reached the end_angle (handling wrap-around) (current_angle - step_size) % 360 == end_angle or - if current_angle % 360 == end_angle: - break - - # Decrement the current angle by the step size - current_angle -= step_size - if current_angle < 0: - current_angle += 360 - else: - # Counterclockwise rotation - current_angle = start_angle - while True: - # Append the current angle to the angles list - angles.append(current_angle % 360) - - # Convert the current angle to radians - current_angle_rad = math.radians(current_angle % 360) - - # Convert polar to Cartesian coordinates - x = radius * math.cos(current_angle_rad) - y = radius * math.sin(current_angle_rad) - - # Append the (x, y) pair to the list - coordinates.append((x, y)) - - # Check if we've reached the end_angle (handling wrap-around) (current_angle + step_size) % 360 == end_angle or - if current_angle % 360 == end_angle: - break - - # Increment the current angle by the step size - current_angle += step_size - if current_angle >= 360: - current_angle -= 360 - - return [angles, coordinates] - - -def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, - Babs:float, startangle:float, endangle:float, angle_stepsize:float, Settings:str, clockwise=True, base_file_name='', zerowhenfin_bool=False)->None: - # TODO: update docs - """Rotation of the b-field in discrete steps, spectrum is measured at each discrete step in the rotation. Scan angle is - defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. - - Args: - instr1 (pyvisa.resources.Resource): _description_ - instr2 (pyvisa.resources.Resource): _description_ - Babs (float): absolute B-field value in T - startangle (float): start angle in degrees - endangle (float): end angle in degrees - angle_stepsize (float): angle step size in degrees - clockwise (bool): determines the direction of rotation of the B-field. Defaults to True. - zerowhenfin_bool (bool, optional): after finishing the rotation, both B-field components should be set to 0 T. Defaults to False. - """ - - # TODO: possibly rename instr1 and instr2 to the dual and single power supplies respectively?? - - # defines the folder, in which the data from the spectrometer is temporarily stored in - temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" - - if base_file_name =='': - base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') - - start_time = time.time() # start of the scan function - - startangle = startangle % 360 - endangle = endangle % 360 # ensures that the angles are within [0,360) - - idnstr1 = query_no_echo(instr1, '*IDN?') - idnstr2 = query_no_echo(instr1, '*IDN?') - - intensity_data = [] # To store data from each scan - cwd = os.getcwd() # save original directory - - # find which one is the dual power supply, then, ramp B_x to Babs value - if '2301034' in idnstr1: # serial no. the dual power supply - pass - elif '2101034' in idnstr2: - # swap instruments, instr 1 to be the dual power supply (^= x-axis) - instr1, instr2 = instr2, instr1 - - # save initial low and high sweep limits of each device, and set them back after the rotation - instr1_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim - instr2_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim - if instr1_bsettings[0][0] == 'T': - instr1_bsettings[1][0] = instr1_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T - instr1_bsettings[2][0] = instr1_bsettings[2][0]*0.1 - if instr2_bsettings[0][0] == 'T': - instr2_bsettings[1][0] = instr2_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T - instr2_bsettings[2][0] = instr2_bsettings[2][0]*0.1 - - # initialise the sweep angle list as well as the sweep limits and directions for each instrument - instr1_lim, instr2_lim = 'LLIM', 'ULIM' - instr1_sweep, instr2_sweep = 'DOWN', 'UP' - - # create lists of angles and discrete Cartesian coordinates - angles, cartesian_coords = polar_to_cartesian(Babs, startangle, endangle, angle_stepsize, clockwise=clockwise) - - if clockwise: # NOTE: old conditional was: startangle > endangle see if this works.... - # reverse sweep limits and directions for the clockwise rotation - instr1_lim, instr2_lim = instr2_lim, instr1_lim - instr1_sweep, instr2_sweep = instr2_sweep, instr1_sweep - - # list of rates (with units) for diff ranges of each device, only up to Range 1 for single power supply as that is already - # the max recommended current. - init_range_lst1 = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'RATE? 0;RATE? 1;RATE? 2').split(';')) - init_range_lst2 = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'RATE? 0;RATE? 1').split(';')) - - min_range_lst = [min(el1[0], el2[0]) for el1,el2 in zip(init_range_lst1, init_range_lst2)] # min rates for each given range - - # set both devices to the min rates - write_no_echo(instr1, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') - write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') - - write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit - print(f'SWEEPING B-X TO {Babs} T NOW') - - # wait for Babs to be reached by the Bx field - actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T - print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') - while abs(actual_bval - Babs) > 0.0001: - time.sleep(5) # little break - actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 - print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') - - # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN - # Helper function that listens to a device - def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event): - while not all_targets_met_event.is_set(): # Loop until the event is set - # value = 0 # Simulate receiving a float from the device INSERT QUERY NO ECHO HERE TO ASK FOR DEVICE IMAG - if '2301034' in device_id: - value = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T - elif '2101014' in device_id: - value = sep_num_from_units(query_no_echo(instr2, 'IMAG?'))[0]*0.1 # convert kG to T - print(f"Device {device_id} reports value: {value} T") - - with lock: - shared_values[device_id] = value - # Check if both devices have met their targets - if all(shared_values.get(device) is not None and abs(shared_values[device] - target_value[device]) <= 0.0001 - for device in shared_values): - print(f"Both devices reached their target values: {shared_values}") - all_targets_met_event.set() # Signal that both targets are met - - # time.sleep(1) # Simulate periodic data checking - - # Main function to manage threads and iterate over target values - def monitor_devices(device_target_values, angles_lst, intensity_data=intensity_data): - for iteration, target in enumerate(device_target_values): - print(f"\nStarting iteration {iteration+1} for target values: {target}") - # Shared dictionary to store values from devices - shared_values = {device: None for device in target.keys()} - # Event to signal when both target values are reached - all_targets_met_event = threading.Event() - - # Lock to synchronize access to shared_values - lock = threading.Lock() - - # Create and start threads for each device - threads = [] - for device_id in target.keys(): - thread = threading.Thread(target=listen_to_device, args=(device_id, target, shared_values, lock, all_targets_met_event)) - threads.append(thread) - thread.start() - - # Wait until both devices meet their target values - all_targets_met_event.wait() - print(f"Both target values for iteration {iteration+1} met. Performing action...") - - # Perform some action after both targets are met - # we acquire with the LF - acquire_name_spe = f'{base_file_name}_{angles_lst[iteration]}°' # NOTE: save each intensity file with the given angle - AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. - - # read the .spe file and get the data as loaded_files - cwd = os.getcwd() # save original directory - os.chdir(temp_folder_path) #change directory - loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable - os.chdir(cwd) # go back to original directory - - # Delete the created .spe file from acquiring after getting necessary info - spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') - os.remove(spe_file_path) - - # points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT - # print('Points left in the scan: ', points_left) - - #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) - intensity_data.append(loaded_files.data[0][0][0]) - - # Clean up threads - for thread in threads: - thread.join() - - print(f"Threads for iteration {iteration+1} closed.\n") - - #prints total time the mapping lasted - end_time = time.time() - elapsed_time = (end_time - start_time) / 60 - print('Scan time: ', elapsed_time, 'minutes') - - # reset both devices to original sweep limits - write_no_echo(instr1, f'LLIM {instr1_bsettings[1][0]*10};ULIM {instr1_bsettings[2][0]*10}') # reset the initial limits of the device after the scan - write_no_echo(instr2, f'LLIM {instr2_bsettings[1][0]*10};ULIM {instr2_bsettings[2][0]*10}') # reset the initial limits of the device after the scan - # reset both devices' initial rates for each range - write_no_echo(instr1, f'RANGE 0 {init_range_lst1[0][0]};RANGE 1 {init_range_lst1[1][0]};RANGE 2 {init_range_lst1[2][0]}') # reset the initial limits of the device after the scan - write_no_echo(instr2, f'RANGE 0 {init_range_lst2[0][0]};RANGE 1 {init_range_lst2[1][0]}') # reset the initial limits of the device after the scan - - if zerowhenfin_bool: - write_no_echo(instr1, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above - write_no_echo(instr2, 'SWEEP ZERO') - - #save intensity & WL data as .txt - os.chdir('C:/Users/localadmin/Desktop/Users/Lukas') - # creates new folder for MAP data - new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" - os.mkdir(new_folder_name) - # Here the things will be saved in a new folder under user Lukas ! - # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! - os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name) - - intensity_data = np.array(intensity_data) - np.savetxt(Settings + f'{angles[0]}°_to_{angles[-1]}°' + experiment_name +'.txt', intensity_data) - # TODO: remove/edit experiment_name in line above, as well in sweep_b_val func, rn takes a global variable below - - wl = np.array(loaded_files.wavelength) - np.savetxt("Wavelength.txt", wl) - - # modify cartesian_coords to suite the required data struct in monitor_devices - cartesian_coords = [{'2301034': t[0], '2101014': t[1]} for t in cartesian_coords] - - # call the helper function to carry out the rotation/measurement of spectrum - monitor_devices(cartesian_coords, angles, intensity_data) - - -################################################################# END OF FUNCTION DEFS ########################################################################################### - -# NOTE: RYAN INTRODUCED SOME FUNCTIONS HERE TO PERFORM THE SCAN - -# Initialise PYVISA ResourceManager -rm = pyvisa.ResourceManager() -# print(rm.list_resources()) -# 'ASRL8::INSTR' for dual power supply, 'ASRL9::INSTR' for single power supply (online PC) -# 'ASRL10::INSTR' for dual power supply, 'ASRL12::INSTR' for single power supply (offline PC) - - -# Open the connection with the APS100 dual power supply -powerbox_dualsupply = rm.open_resource('ASRL10::INSTR', - baud_rate=9600, - data_bits=8, - parity= pyvisa.constants.Parity.none, - stop_bits= pyvisa.constants.StopBits.one, - timeout=100)# 5000 ms timeout - -# Open the connection with the APS100 dual power supply -powerbox_singlesupply = rm.open_resource('ASRL12::INSTR', - baud_rate=9600, - data_bits=8, - parity= pyvisa.constants.Parity.none, - stop_bits= pyvisa.constants.StopBits.one, - timeout=100)# 5000 ms timeout - -write_no_echo(powerbox_dualsupply, 'REMOTE') # turn on the remote mode -write_no_echo(powerbox_singlesupply, 'REMOTE') # turn on the remote mode - -# TODO: test functionality of the magnet_coil param later on, should work... as this code below is basically implemented inside the scan func. -# select axis for the dual supply, either z-axis(CHAN 1 ^= Supply A) or x-axis(CHAN 2 ^= Supply B) -# write_no_echo(powerbox_dualsupply, 'CHAN 1') - -# Setup connection to AMC -amc = AMC.Device(IP) -amc.connect() - -# Internally, axes are numbered 0 to 2 -amc.control.setControlOutput(0, True) -amc.control.setControlOutput(1, True) - - -auto = Automation(True, List[String]()) -experiment = auto.LightFieldApplication.Experiment -acquireCompleted = AutoResetEvent(False) - -experiment.Load("Lukas_experiment_2024_02_06") -experiment.ExperimentCompleted += experiment_completed # we are hooking a listener. -# experiment.SetValue(SpectrometerSettings.GratingSelected, '[750nm,1200][0][0]') -# InitializerFilenameParams() - - -#set scan range and resolution in nanometers -range_x = 20000 -range_y = 20000 -resolution = 1000 -# set B-field scan range and resolution (all in T) -set_llim_bval = -0.01 -set_ulim_bval = 0.01 -set_res_bval = 0.01 - -#Here you can specify the filename of the map e.g. put experiment type, exposure time, used filters, etc.... -experiment_settings = 'PL_SP_700_LP_700_HeNe_52muW_exp_2s_Start_' -#The program adds the range of the scan as well as the resolution and the date and time of the measurement -experiment_name = f"{set_llim_bval}T_to_{set_ulim_bval}T_{set_res_bval}T_{datetime.datetime.now().strftime('%Y_%m_%d_%H%M')}" - -# this moves the probe in xy-direction and measures spectrum there -# move_scan_xy(range_x, range_y, resolution, experiment_settings, experiment_name) - -# perform the B-field measurement for selected axis above -# sweep_b_val(powerbox_dualsupply, set_llim_bval, set_ulim_bval, set_res_bval, experiment_settings, experiment_name) -sweep_b_val(powerbox_dualsupply, set_llim_bval, set_ulim_bval, set_res_bval, 'z-axis', - experiment_settings, experiment_name, zerowhenfin_bool=True, reversescan_bool=False) - -# Internally, axes are numbered 0 to 2 - -write_no_echo(powerbox_dualsupply, 'LOCAL') # turn off the remote mode -write_no_echo(powerbox_singlesupply, 'LOCAL') # turn off the remote mode -# time.sleep(0.5) -powerbox_dualsupply.close() -powerbox_singlesupply.close() \ No newline at end of file -- 2.39.5 From 9b851c8018e844137206d0b3695fbe2af7dcdee6 Mon Sep 17 00:00:00 2001 From: ryantan Date: Mon, 14 Apr 2025 10:48:05 +0200 Subject: [PATCH 20/39] removed Lukas mapping, did not have b-sweep val --- Mapping_Script_Lukas_Version_2024_08_27.py | 355 --------------------- 1 file changed, 355 deletions(-) delete mode 100644 Mapping_Script_Lukas_Version_2024_08_27.py diff --git a/Mapping_Script_Lukas_Version_2024_08_27.py b/Mapping_Script_Lukas_Version_2024_08_27.py deleted file mode 100644 index 9b3f06a..0000000 --- a/Mapping_Script_Lukas_Version_2024_08_27.py +++ /dev/null @@ -1,355 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Created on Fri Dec 22 15:10:10 2023 -Lightfield + Positioner -@author: Local Admin -""" -import AMC -import csv -import time -import clr -import sys -import os -import spe2py as spe -import spe_loader as sl -import pandas as pd -import time -from System.IO import * -from System import String -import numpy as np -import matplotlib.pyplot as plt -import datetime - - -#First choose your controller -IP_AMC300 = "192.168.71.101" -IP_AMC100 = "192.168.71.100" - -# IP = "192.168.1.1" -IP = IP_AMC300 - - -# Import os module -import os, glob, string - -# Import System.IO for saving and opening files -from System.IO import * - -from System.Threading import AutoResetEvent - -# Import C compatible List and String -from System import String -from System.Collections.Generic import List - -# Add needed dll references -sys.path.append(os.environ['LIGHTFIELD_ROOT']) -sys.path.append(os.environ['LIGHTFIELD_ROOT']+"\\AddInViews") -sys.path.append(r'C:\Program Files\Princeton Instruments\LightField\AddInViews') #I added them by hand -serdar -sys.path.append(r'C:\Program Files\Princeton Instruments\LightField') #this one also -clr.AddReference('PrincetonInstruments.LightFieldViewV5') -clr.AddReference('PrincetonInstruments.LightField.AutomationV5') -clr.AddReference('PrincetonInstruments.LightFieldAddInSupportServices') -os.environ['LIGHTFIELD_ROOT'] = r'C:\Program Files\Princeton Instruments\LightField' -# PI imports -from PrincetonInstruments.LightField.Automation import Automation -from PrincetonInstruments.LightField.AddIns import ExperimentSettings -from PrincetonInstruments.LightField.AddIns import CameraSettings -#from PrincetonInstruments.LightField.AddIns import DeviceType -from PrincetonInstruments.LightField.AddIns import SpectrometerSettings -from PrincetonInstruments.LightField.AddIns import RegionOfInterest - -######################################################################################################### code begins from here ############################################# - -def set_custom_ROI(): - - # Get device full dimensions - dimensions = experiment.FullSensorRegion() - - regions = [] - - # Add two ROI to regions - regions.append( - RegionOfInterest( - int(dimensions.X), int(dimensions.Y), - int(dimensions.Width), int(dimensions.Height//4), # Use // for integer division - int(dimensions.XBinning), int(dimensions.Height//4))) - - - - # Set both ROI - experiment.SetCustomRegions(regions) - -def experiment_completed(sender, event_args): #callback function which is hooked to event completed, this is the listener - print("... Acquisition Complete!") - acquireCompleted.Set() #set the event. This puts the autoresetevent false.(look at .NET library for furher info) - -def InitializerFilenameParams(): - experiment.SetValue(ExperimentSettings.FileNameGenerationAttachIncrement, False) - experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementNumber, 1.0) - experiment.SetValue(ExperimentSettings.FileNameGenerationIncrementMinimumDigits, 2.0) - experiment.SetValue(ExperimentSettings.FileNameGenerationAttachDate, False) - experiment.SetValue(ExperimentSettings.FileNameGenerationAttachTime, False) - -def AcquireAndLock(name): - print("Acquiring...", end = "") - # name += 'Exp{0:06.2f}ms.CWL{1:07.2f}nm'.format(\ - # experiment.GetValue(CameraSettings.ShutterTimingExposureTime)\ - # ,experiment.GetValue(SpectrometerSettings.GratingCenterWavelength)) - - experiment.SetValue(ExperimentSettings.FileNameGenerationBaseFileName, name) #this creates .spe file with the name - experiment.Acquire() # this is an ashynrchronus func. - acquireCompleted.WaitOne() - -def calculate_distance(x1, y1, x2, y2): - return np.sqrt((x2 - x1)**2 + (y2 - y1)**2) - -def generate_scan_positions(center, range_val, resolution): - positive_range = np.arange(center, center + range_val + resolution, resolution) - return positive_range - -def save_as_csv(filename, position_x, position_y): - file_existance = os.path.isfile(filename) - - with open(filename, 'a', newline = '') as csvfile: - writer = csv.writer(csvfile) - - if not file_existance: - writer.writerow(['x_coordinates','y_coordinates']) - - writer.writerow([position_x, position_y]) - -def move_axis(axis, target): - """ - This function moves an axis to the specified target and stop moving after it is in the really closed - vicinity (+- 25nm) of the target (listener hooked to it). - """ - amc.move.setControlTargetPosition(axis, target) - amc.control.setControlMove(axis, True) - # while not (target - 25) < amc.move.getPosition(axis) < (target + 25): - # time.sleep(0.1) - # time.sleep(0.15) - # while not (target - 25) < amc.move.getPosition(axis) < (target + 25): - # time.sleep(0.1) - # amc.control.setControlMove(axis, False) - -def move_xy(target_x, target_y): # moving in x and y direction closed to desired position - amc.move.setControlTargetPosition(0, target_x) - amc.control.setControlMove(0, True) - amc.move.setControlTargetPosition(1, target_y) - amc.control.setControlMove(1, True) - while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25): - time.sleep(0.1) - time.sleep(0.15) - while not (target_x - 25) < amc.move.getPosition(0) < (target_x + 25) and (target_y - 25) < amc.move.getPosition(1) < (target_y + 25): - time.sleep(0.1) - - amc.control.setControlOutput(0, False) - amc.control.setControlOutput(1, False) - - -# intensity_data = [] # To store data from each scan -# data_list = [] - -def move_scan_xy(range_x, range_y, resolution, Settings, baseFileName): - """ - This function moves the positioners to scan the sample with desired ranges and resolution in 2 dimensions. - At the end it saves a csv file - - Parameters - ---------- - range_x : integer in nm. max value is 5um - Scan range in x direction. - range_y : integer in nm. max value is 5um - Scan range in y direction. - resolution : integer in nm. - Room temprature max res is 50nm. In cyrostat (4K) it is 10nm (check the Attocube manual) - baseFileName: string. At the end the saved file will be: baseFileName_scan_data.csv and it will be saved to the current directory - - Returns - ------- - None. - - """ - start_time = time.time() - axis_x = 0 #first axis - axis_y = 1 #second axis - center_x = amc.move.getPosition(axis_x) - center_y = amc.move.getPosition(axis_y) - # #check if the intput range is reasonable - # if amc.move.getPosition(axis_x) + range_x >= 5000 or amc.move.getPosition(axis_x)- range_x <= 0 or amc.move.getPosition(axis_y) + range_y >=5000 or amc.move.getPosition(axis_y) - range_y <= 5000 : - # print("scan range is out of range!") - # return - # +- range from current positions for x and y directions - - - array_x = generate_scan_positions(center_x, range_x, resolution) - array_y = generate_scan_positions(center_y, range_y, resolution) - total_points = len(array_x)*len(array_y) - len_y = len(array_y) - intensity_data = [] # To store data from each scan - data_list = [] - cwd = os.getcwd() # save original directory - - #This gives a directory, in which the script will save the spectrum of each spot as spe - #However, it will open the spectrum, convert it to txt, add it to the intensity_data and delete the spe file - Path_save = "C:/Users/localadmin/Desktop/Users/Lukas/Map_dump" - - #scanning loop - for i, x_positions in enumerate(array_x): - move_axis(axis_x, x_positions) - y = False - - for j, y_positions in enumerate(array_y): - move_axis(axis_y, y_positions) - time.sleep(2) - if j == 0: - time.sleep(10) - #each time when the positioner comes to the beggining of a new line - #this if will make the positioner wait a bit longer to really go to the target. - if y == False: - move_axis(axis_y, y_positions) - y = True - - - - #we acquire with the LF - acquire_name_spe = f'{baseFileName}_X{x_positions}_Y{y_positions}' - AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. - - #read the .spe file and get the data as loaded_files - cwd = os.getcwd() # save original directory - os.chdir(Path_save) #change directory - loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable - os.chdir(cwd) # go back to original directory - - # Delete the created .spe file from acquiring after getting necessary info - spe_file_path = os.path.join(Path_save, acquire_name_spe + '.spe') - os.remove(spe_file_path) - - distance = calculate_distance(x_positions, y_positions,amc.move.getPosition(axis_x), amc.move.getPosition(axis_y)) - - points_left = total_points - (i * len_y + (j+1)) + 1 - print('Points left in the scan: ', points_left) - - #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) - intensity_data.append(loaded_files.data[0][0][0]) - - data_list.append({ - 'position_x': x_positions, - 'position_y': y_positions, - 'actual_x': amc.move.getPosition(axis_x), - 'actual_y': amc.move.getPosition(axis_y), - 'distance': distance, - }) - - #moves back to starting position - move_axis(axis_x, center_x) - move_axis(axis_y, center_y) - - #prints total time the mapping lasted - end_time = time.time() - elapsed_time = (end_time - start_time) / 60 - print('Scan time: ', elapsed_time, 'minutes') - - # df = pd.DataFrame(data_list) - - #save intensity & WL data as .txt - os.chdir('C:/Users/localadmin/Desktop/Users/Priyanka/2025/stacked_2L/PL_Map_0T/250325') - # creates new folder for MAP data - new_folder_name = "PL_Map_By_0T_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" - os.mkdir(new_folder_name) - # Here the things will be saved in a new folder under user Lukas ! - # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! - os.chdir('C:/Users/localadmin/Desktop/Users/Priyanka/2025/stacked_2L/PL_Map_0T/250325/'+ new_folder_name) - - intensity_data = np.array(intensity_data) - np.savetxt(Settings + str(center_x) + '_' + str(center_y) + experiment_name +'.txt', intensity_data) - - wl = np.array(loaded_files.wavelength) - np.savetxt("Wavelength.txt", wl) - - time.sleep(20) - - amc.control.setControlMove(axis_x, False) - amc.control.setControlMove(axis_y, False) - - # wl.to_csv("wl", index = False) - - - - # #Plot the scan data - # plt.figure(figsize=(12, 6)) - # # Plot 1: Target and Actual Positions - # plt.subplot(1, 2, 1) - # plt.scatter(df['position_x'], df['position_y'], c='green', label='Target Positions') - # plt.scatter(df['actual_x'], df['actual_y'], c='red', label='Actual Positions') - # plt.title('Scan Visualization') - # plt.xlabel('X Position') - # plt.ylabel('Y Position') - # plt.legend() - # plt.grid(True) - - # #Plot 2: Distance from Target Position - # mean_distance = df['distance'].mean() - # plt.subplot(1, 2, 2) - # plt.plot(df['distance'], label='Distance from Target Position') - # plt.title(f'Distance from Target Position\nMean Distance: {mean_distance:.2f}') - # plt.xlabel('Scan Point') - # plt.ylabel('Distance') - # plt.subplot(1, 2, 2) - # plt.hist(df['distance'], bins=30, color='skyblue', edgecolor='black', alpha=0.7) - # plt.title(f'Distribution of Distance from Target Position\nMean Distance: {mean_distance:.2f} nm') - # plt.xlabel('Distance') - # plt.ylabel('Frequency') - # plt.legend() - # plt.grid(True) - # plt.text(0.95, 0.95, f'Herz: {(amc.control.getControlFrequency(0)/1000):.2f} Hz', horizontalalignment='right', verticalalignment='top', transform=plt.gca().transAxes) - # plt.text(0.95, 0.90, f'Scan Time: {elapsed_time:.2f} mins', horizontalalignment='right', verticalalignment='top', transform=plt.gca().transAxes) - # plt.text(0.95, 0.05, f"Scan Date: {datetime.datetime.now().strftime('%Y_%m_%d_%H%M')}", horizontalalignment='right', verticalalignment='bottom', transform=plt.gca().transAxes) - # plt.legend() - # plt.grid(True) - # plt.axhline(mean_distance, color='orange', linestyle='--', label=f'Mean Distance: {mean_distance:.2f}') - # plt.tight_layout() - - # plt.savefig(Settings + str(center_x) + '_' + str(center_y) +'_' + experiment_name + '.png') - # plt.show() - # os.chdir(cwd) - -# Setup connection to AMC -amc = AMC.Device(IP) -amc.connect() - -# Internally, axes are numbered 0 to 2 -# amc.control.setControlOutput(0, True) -# amc.control.setControlOutput(1, True) - - -auto = Automation(True, List[String]()) -experiment = auto.LightFieldApplication.Experiment -acquireCompleted = AutoResetEvent(False) - -experiment.Load("2025_02_13_Priyanka_CrSBr") -experiment.ExperimentCompleted += experiment_completed # we are hooking a listener. -# experiment.SetValue(SpectrometerSettings.GratingSelected, '[750nm,1200][0][0]') -# InitializerFilenameParams() - - - -#set scna range and resolution in nanometers - -range_x = 20000 -range_y = 20000 -resolution = 1000 - -#Here you can specify the filename of the map e.g. put experiment type, exposure time, used filters, etc.... -experiment_settings = 'PL_he ne_stacked_2L_G150_P300uW_5s_test_l1_52_l2_260' -# experiment_settings = 'DR_NKT_OD2_rep_0.15_600g_cwl_660_exp_3s_Start_' -# experiment_settings = 'DR_Halogen_Lamp_lin_b-axis_600g_cwl_910_exp_2s_Start_' -#The program adds the range of the scan as well as the resolution and the date and time of the measurement -experiment_name = f"{range_x}nm_{range_y}nm_{resolution}nm_{datetime.datetime.now().strftime('%Y_%m_%d_%H%M')}" - - -move_scan_xy(range_x, range_y, resolution, experiment_settings, experiment_name) - -# Internally, axes are numbered 0 to 2 - -- 2.39.5 From b382e77dd80e3034a1f2309dc7fa871f05c28445 Mon Sep 17 00:00:00 2001 From: ryantan Date: Mon, 14 Apr 2025 10:55:31 +0200 Subject: [PATCH 21/39] added README.md --- Mag_Field_Sweep_2024_10_21.py | 2 +- README.md | 127 ++++++++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+), 1 deletion(-) create mode 100644 README.md diff --git a/Mag_Field_Sweep_2024_10_21.py b/Mag_Field_Sweep_2024_10_21.py index 108e822..f75e83b 100644 --- a/Mag_Field_Sweep_2024_10_21.py +++ b/Mag_Field_Sweep_2024_10_21.py @@ -2,7 +2,7 @@ """ Created on Fri Dec 22 15:10:10 2023 Lightfield + Positioner -@author: Serdar, adjusted by Lukas +@author: Serdar, adjusted by Lukas and Ryan """ ############################################ # Packages from Ryan diff --git a/README.md b/README.md new file mode 100644 index 0000000..600b40f --- /dev/null +++ b/README.md @@ -0,0 +1,127 @@ + +# Magnetic Field Sweep and Spatial Mapping Automation + +**Author:** Serdar (adjusted by Lukas and Ryan) +**Last Updated:** April 2025 +**Filename:** `Mag_Field_Sweep_2024_10_21.py` + +## Overview + +This script automates spectral acquisition in a magneto-optical experiment using: + +- **LightField** for spectrometer control (Princeton Instruments) +- **AMC Positioner** for precise spatial scanning +- **Attocube APS100** power supplies for magnetic field control + +It enables: +- Magnetic field sweeps along selected axes +- Spatial scans across X-Y positions +- B-field vector rotations with spectral capture +- Live spectrum acquisition and intensity mapping + +## Features + +- **2D Spatial Scan:** Raster-scan across a surface using AMC positioners, capturing spectra at each coordinate. +- **Magnetic Field Sweep:** Vary B-fields in controlled steps along x/y/z, measure spectra at each step. +- **Field Rotation:** Circular B-field rotation (in-plane) with angle-defined steps. +- **Automated File Handling:** Acquires `.spe` files, extracts and saves intensity/wavelengths, deletes intermediates. +- **Flexible Configuration:** Resolution, range, exposure, filters, filenames and scan directions are all customizable. + +## Prerequisites + +### Hardware +- AMC100/AMC300 positioner +- Attocube APS100 single/dual-channel magnet power supplies +- Spectrometer compatible with Princeton Instruments LightField + +### Software & Libraries +- **Python 3.8+** +- Packages: `pyvisa`, `numpy`, `matplotlib`, `pandas`, `clr`, `spe2py`, `spe_loader`, `AMC` module +- .NET integration via `pythonnet` +- LightField SDK: Princeton Instruments (with DLLs loaded via `clr`) + +> Note: Ensure `LIGHTFIELD_ROOT` environment variable is set. + +## Setup + +1. **Install dependencies** + ```bash + pip install pyvisa pandas numpy matplotlib pythonnet + ``` + +2. **Ensure required DLLs** are present in: + ``` + C:\Program Files\Princeton Instruments\LightField\ + ``` + +3. **Set up device IPs** + ```python + IP_AMC100 = "192.168.71.100" # or AMC300 + ``` + +4. **Edit scan parameters in main block:** + ```python + range_x = 20000 + range_y = 20000 + resolution = 1000 # nanometers + + set_llim_bval = -0.3 + set_ulim_bval = 0.3 + set_res_bval = 0.003 # Tesla + ``` + +## Main Functions + +### `move_scan_xy(range_x, range_y, resolution, Settings, baseFileName)` +Performs a 2D XY raster scan of the probe. Acquires spectra and saves results. + +### `sweep_b_val(instr, min_bval, max_bval, res, axis, Settings, base_file_name)` +Sweeps magnetic field (in T) along the specified axis, collecting spectra at each field. + +### `ramp_b_val(instr, bval, magnet_coil)` +Smooth ramping of B-field to target value. + +### `b_field_rotation(instr1, instr2, Babs, startangle, endangle, step, Settings)` +Rotates the in-plane magnetic field by vector combination of Bx and By components. + +## File Saving + +- `.txt`: Intensity data and wavelength arrays saved to timestamped folders +- Folder names include experiment metadata +- `.spe` files are deleted after processing to conserve space + +## Usage Example + +To sweep B-field along the **Y-axis**: + +```python +sweep_b_val( + instr=powerbox_singlesupply, + min_bval=-0.3, + max_bval=0.3, + res=0.003, + magnet_coil='y-axis', + Settings='experiment_config', + base_file_name='scan_name', + zerowhenfin_bool=True, + reversescan_bool=False, + loopscan_bool=True +) +``` + +## Notes + +- Always close power supply connections with `.close()` +- Make sure `.spe` files are not locked by LightField before running +- The AMC section is currently commented — uncomment if positioner control is needed +- Ensure `experiment.Load(...)` points to the correct `.lfe` config + +## Troubleshooting + +- **DLL loading issues?** Confirm path via `sys.path.append(...)` and DLL names. +- **Communication errors?** Check serial port resource names via `pyvisa.ResourceManager().list_resources()` +- **No spectra saved?** Ensure LightField is licensed and experiment file is valid. + +## License + +Internal use only – please contact the authors before distribution or reuse. -- 2.39.5 From 69c10571bab84b64fb96e80dd552800e237e3575 Mon Sep 17 00:00:00 2001 From: ryantan Date: Mon, 14 Apr 2025 13:41:09 +0200 Subject: [PATCH 22/39] implemented funct that delivers a list of cartesian coords for the sweep @ a fixed angle --- Mag_Field_Sweep_2024_10_21.py | 12 +++-- Test.py | 89 +++++++++++++++++++++++++++++++++++ ThreadTest.py | 83 ++++++++++++++++++++++++++++++++ 3 files changed, 180 insertions(+), 4 deletions(-) create mode 100644 Test.py create mode 100644 ThreadTest.py diff --git a/Mag_Field_Sweep_2024_10_21.py b/Mag_Field_Sweep_2024_10_21.py index f75e83b..2099103 100644 --- a/Mag_Field_Sweep_2024_10_21.py +++ b/Mag_Field_Sweep_2024_10_21.py @@ -643,9 +643,12 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, wl = np.array(loaded_files.wavelength) np.savetxt("Wavelength.txt", wl) np.savetxt("B_Values.txt", bval_lst) + +def generate_coord_list_fixed_angle(angle, b_abs, b_abs_step_size): + # TODO: write a function that returns a list of coordinates (x,y) for a fixed angle and a given b_val, b_val_step_size + pass - -def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True): +def generate_angle_coord_list(radius, start_angle, end_angle, step_size, clockwise=True): # TODO: DOCS """Creates a list of discrete cartesian coordinates (x,y), given the radius, start- and end angles, the angle step size, and the direction of rotation. Function then returns a list of two lists: list of angles and list of cartesian coordinates (x,y coordinates in a tuple). @@ -742,7 +745,8 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # TODO: possibly rename instr1 and instr2 to the dual and single power supplies respectively?? # defines the folder, in which the data from the spectrometer is temporarily stored in - temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/B_Field_Dump" + # temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" if base_file_name =='': base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') @@ -780,7 +784,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R instr1_sweep, instr2_sweep = 'DOWN', 'UP' # create lists of angles and discrete Cartesian coordinates - angles, cartesian_coords = polar_to_cartesian(Babs, startangle, endangle, angle_stepsize, clockwise=clockwise) + angles, cartesian_coords = generate_angle_coord_list(Babs, startangle, endangle, angle_stepsize, clockwise=clockwise) if clockwise: # NOTE: old conditional was: startangle > endangle see if this works.... # reverse sweep limits and directions for the clockwise rotation diff --git a/Test.py b/Test.py new file mode 100644 index 0000000..a5f4eff --- /dev/null +++ b/Test.py @@ -0,0 +1,89 @@ +import math + +def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True): + # TODO: DOCS + """Creates a list of discrete cartesian coordinates (x,y), given the radius, start- and end angles, the angle step size, and the direction of rotation. + Function then returns a list of two lists: list of angles and list of cartesian coordinates (x,y coordinates in a tuple). + + Args: + radius (_type_): _description_ + start_angle (_type_): _description_ + end_angle (_type_): _description_ + step_size (_type_): _description_ + clockwise (bool, optional): _description_. Defaults to True. + + Returns: + _type_: _description_ + """ """""" + # Initialize lists to hold angles and (x, y) pairs + angles = [] + coordinates = [] + + # Normalize angles to the range [0, 360) + start_angle = start_angle % 360 + end_angle = end_angle % 360 + + if clockwise: + # Clockwise rotation + current_angle = start_angle + while True: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle (handling wrap-around) (current_angle - step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: + break + + # Decrement the current angle by the step size + current_angle -= step_size + if current_angle < 0: + current_angle += 360 + else: + # Counterclockwise rotation + current_angle = start_angle + while True: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle (handling wrap-around) (current_angle + step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: + break + + # Increment the current angle by the step size + current_angle += step_size + if current_angle >= 360: + current_angle -= 360 + + return [angles, coordinates] + +if __name__=="__main__": + # Example usage + radius = 5 + start_angle = 0 + end_angle = 0 + step_size = 10 + + angles, coordinates = polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True) + + print('\n', "Angles:", angles, '\n') + print("Coordinates:", coordinates, '\n',) \ No newline at end of file diff --git a/ThreadTest.py b/ThreadTest.py new file mode 100644 index 0000000..8d7ff7e --- /dev/null +++ b/ThreadTest.py @@ -0,0 +1,83 @@ +import threading +import time +import random + +# Shared values +device_values = [0, 0] +value_lock = threading.Lock() + +# Per-device pause controls +device_events = [threading.Event(), threading.Event()] +device_events[0].set() # Start as running +device_events[1].set() + +# Tolerance threshold +TOLERANCE = 20 + +# Stop flag +stop_event = threading.Event() + +def is_within_tolerance(val_a, val_b): + return abs(val_a - val_b) <= TOLERANCE + +# Device thread +def device_thread(device_id): + other_id = 1 - device_id + while not stop_event.is_set(): + device_events[device_id].wait() # Pause if needed + + # Simulate value from device + new_value = random.randint(0, 100) + + with value_lock: + device_values[device_id] = new_value + my_val = device_values[device_id] + other_val = device_values[other_id] + + print(f"Device {device_id} => {my_val} | Device {other_id} => {other_val}") + + if not is_within_tolerance(my_val, other_val): + print(f"Device {device_id} is out of tolerance! Pausing...") + device_events[device_id].clear() + + time.sleep(0.1) # Faster check interval + +# Watcher thread +def tolerance_watcher(): + while not stop_event.is_set(): + with value_lock: + val0, val1 = device_values + if is_within_tolerance(val0, val1): + for i, event in enumerate(device_events): + if not event.is_set(): + print(f"Resuming Device {i}") + event.set() + + time.sleep(0.05) # Fast response + +# Start threads +threads = [ + threading.Thread(target=device_thread, args=(0,)), + threading.Thread(target=device_thread, args=(1,)), + threading.Thread(target=tolerance_watcher) +] + +for t in threads: + t.start() + +# Run loop (press Ctrl+C to stop) +try: + while True: + time.sleep(0.1) +except KeyboardInterrupt: + print("Stopping...") + +stop_event.set() +for event in device_events: + event.set() + +for t in threads: + t.join() + +print("All threads stopped.") + -- 2.39.5 From 6e1ea0fd8b2ab7c34e0792ee4cf5e1f253c090c3 Mon Sep 17 00:00:00 2001 From: ryantan Date: Mon, 14 Apr 2025 13:43:28 +0200 Subject: [PATCH 23/39] full implementation of generate_coord_list_fixed_angle --- Mag_Field_Sweep_2024_10_21.py | 41 +++++++++++++++++++++++++++++--- Test.py | 44 ++++++++++++++++++++++++++++++++++- 2 files changed, 81 insertions(+), 4 deletions(-) diff --git a/Mag_Field_Sweep_2024_10_21.py b/Mag_Field_Sweep_2024_10_21.py index 2099103..6ab4621 100644 --- a/Mag_Field_Sweep_2024_10_21.py +++ b/Mag_Field_Sweep_2024_10_21.py @@ -644,9 +644,44 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, np.savetxt("Wavelength.txt", wl) np.savetxt("B_Values.txt", bval_lst) -def generate_coord_list_fixed_angle(angle, b_abs, b_abs_step_size): - # TODO: write a function that returns a list of coordinates (x,y) for a fixed angle and a given b_val, b_val_step_size - pass +def generate_coord_list_fixed_angle(angle, b_val, b_val_step_size, reverse=False): + """ + Generates a list of (x, y) Cartesian coordinates along a line defined by a fixed angle, + scanning from -b_val to b_val or from b_val to -b_val depending on the reverse flag. + + Args: + angle (float): The fixed angle (in degrees) from the positive x-axis. + b_val (float): The maximum distance from the origin (both positive and negative). + b_val_step_size (float): The increment in distance for each point. + reverse (bool): If True, scan from b_val to -b_val. If False, scan from -b_val to b_val. + + Returns: + list: A list of tuples representing Cartesian coordinates (x, y). + """ + coordinates = [] + + # Convert angle from degrees to radians + angle_rad = math.radians(angle) + + # Determine the scan direction based on the reverse flag + if reverse: + # Scan from b_val to -b_val + current_b = b_val + while current_b >= -b_val: + x = current_b * math.cos(angle_rad) + y = current_b * math.sin(angle_rad) + coordinates.append((x, y)) + current_b -= b_val_step_size + else: + # Scan from -b_val to b_val + current_b = -b_val + while current_b <= b_val: + x = current_b * math.cos(angle_rad) + y = current_b * math.sin(angle_rad) + coordinates.append((x, y)) + current_b += b_val_step_size + + return coordinates def generate_angle_coord_list(radius, start_angle, end_angle, step_size, clockwise=True): # TODO: DOCS diff --git a/Test.py b/Test.py index a5f4eff..b7ffc1d 100644 --- a/Test.py +++ b/Test.py @@ -76,6 +76,45 @@ def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True return [angles, coordinates] +def generate_coord_list_fixed_angle(angle, b_val, b_val_step_size, reverse=False): + """ + Generates a list of (x, y) Cartesian coordinates along a line defined by a fixed angle, + scanning from -b_val to b_val or from b_val to -b_val depending on the reverse flag. + + Args: + angle (float): The fixed angle (in degrees) from the positive x-axis. + b_val (float): The maximum distance from the origin (both positive and negative). + b_val_step_size (float): The increment in distance for each point. + reverse (bool): If True, scan from b_val to -b_val. If False, scan from -b_val to b_val. + + Returns: + list: A list of tuples representing Cartesian coordinates (x, y). + """ + coordinates = [] + + # Convert angle from degrees to radians + angle_rad = math.radians(angle) + + # Determine the scan direction based on the reverse flag + if reverse: + # Scan from b_val to -b_val + current_b = b_val + while current_b >= -b_val: + x = current_b * math.cos(angle_rad) + y = current_b * math.sin(angle_rad) + coordinates.append((x, y)) + current_b -= b_val_step_size + else: + # Scan from -b_val to b_val + current_b = -b_val + while current_b <= b_val: + x = current_b * math.cos(angle_rad) + y = current_b * math.sin(angle_rad) + coordinates.append((x, y)) + current_b += b_val_step_size + + return coordinates + if __name__=="__main__": # Example usage radius = 5 @@ -86,4 +125,7 @@ if __name__=="__main__": angles, coordinates = polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True) print('\n', "Angles:", angles, '\n') - print("Coordinates:", coordinates, '\n',) \ No newline at end of file + print("Coordinates:", coordinates, '\n',) + + print(generate_coord_list_fixed_angle(10, 5, 1, reverse=False)) + \ No newline at end of file -- 2.39.5 From 45e5fd9107c9342104798eead17acb096d965495 Mon Sep 17 00:00:00 2001 From: ryantan Date: Tue, 15 Apr 2025 11:17:52 +0200 Subject: [PATCH 24/39] fixed general bugs --- Mag_Field_Sweep_2024_10_21.py | 8 ++++---- Test.py | 21 ++++++++++++++++----- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/Mag_Field_Sweep_2024_10_21.py b/Mag_Field_Sweep_2024_10_21.py index 6ab4621..a06a5f3 100644 --- a/Mag_Field_Sweep_2024_10_21.py +++ b/Mag_Field_Sweep_2024_10_21.py @@ -706,7 +706,7 @@ def generate_angle_coord_list(radius, start_angle, end_angle, step_size, clockwi start_angle = start_angle % 360 end_angle = end_angle % 360 - if clockwise: + if not clockwise: # Clockwise rotation current_angle = start_angle while True: @@ -951,11 +951,11 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R wl = np.array(loaded_files.wavelength) np.savetxt("Wavelength.txt", wl) - # modify cartesian_coords to suite the required data struct in monitor_devices - cartesian_coords = [{'2301034': t[0], '2101014': t[1]} for t in cartesian_coords] + # TODO: data struct of device_target_values is not correct + device_target_values = [{'2301034': bval[0], '2101014': bval[1]} for bval in cartesian_coords] # call the helper function to carry out the rotation/measurement of spectrum - monitor_devices(cartesian_coords, angles, intensity_data) + monitor_devices(device_target_values, angles, intensity_data) ################################################################# END OF FUNCTION DEFS ########################################################################################### diff --git a/Test.py b/Test.py index b7ffc1d..2a70cfa 100644 --- a/Test.py +++ b/Test.py @@ -1,6 +1,6 @@ import math -def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True): +def generate_angle_coord_list(radius, start_angle, end_angle, step_size, clockwise=True): # TODO: DOCS """Creates a list of discrete cartesian coordinates (x,y), given the radius, start- and end angles, the angle step size, and the direction of rotation. Function then returns a list of two lists: list of angles and list of cartesian coordinates (x,y coordinates in a tuple). @@ -23,7 +23,7 @@ def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True start_angle = start_angle % 360 end_angle = end_angle % 360 - if clockwise: + if not clockwise: # Clockwise rotation current_angle = start_angle while True: @@ -76,6 +76,7 @@ def polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True return [angles, coordinates] + def generate_coord_list_fixed_angle(angle, b_val, b_val_step_size, reverse=False): """ Generates a list of (x, y) Cartesian coordinates along a line defined by a fixed angle, @@ -119,13 +120,23 @@ if __name__=="__main__": # Example usage radius = 5 start_angle = 0 - end_angle = 0 + end_angle = 180 step_size = 10 - angles, coordinates = polar_to_cartesian(radius, start_angle, end_angle, step_size, clockwise=True) + angles, coordinates = generate_angle_coord_list(radius, start_angle, end_angle, step_size, clockwise=True) print('\n', "Angles:", angles, '\n') print("Coordinates:", coordinates, '\n',) + # device_target_values = [{'2301034': bval[0], '2101014': bval[1]} for bval in coordinates] + xcoord_tuple, ycoord_tuple = zip(*coordinates) + device_target_values = {'2301034': list(xcoord_tuple), '2101014': list(ycoord_tuple)} + print(f"{device_target_values['2301034']=}") + print(f"{device_target_values['2101014']=}") + + for iteration, (device_id,bval_lst) in enumerate(device_target_values.items()): + print(iteration, device_id, bval_lst) + + # print(generate_coord_list_fixed_angle(10, 5, 1, reverse=False)) + - print(generate_coord_list_fixed_angle(10, 5, 1, reverse=False)) \ No newline at end of file -- 2.39.5 From 736a5a8e141cb3f71421408af7626930d9d946f9 Mon Sep 17 00:00:00 2001 From: ryantan Date: Tue, 15 Apr 2025 13:56:54 +0200 Subject: [PATCH 25/39] added write_no_echo in listen helper func --- Mag_Field_Sweep_2024_10_21.py | 29 +++++++++++++++++++---------- Test.py | 8 ++++++++ 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/Mag_Field_Sweep_2024_10_21.py b/Mag_Field_Sweep_2024_10_21.py index a06a5f3..1b75d9f 100644 --- a/Mag_Field_Sweep_2024_10_21.py +++ b/Mag_Field_Sweep_2024_10_21.py @@ -792,7 +792,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R endangle = endangle % 360 # ensures that the angles are within [0,360) idnstr1 = query_no_echo(instr1, '*IDN?') - idnstr2 = query_no_echo(instr1, '*IDN?') + idnstr2 = query_no_echo(instr2, '*IDN?') intensity_data = [] # To store data from each scan cwd = os.getcwd() # save original directory @@ -855,15 +855,26 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # value = 0 # Simulate receiving a float from the device INSERT QUERY NO ECHO HERE TO ASK FOR DEVICE IMAG if '2301034' in device_id: value = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + if value <= target_value[device_id]: + write_no_echo(instr1, f"CHAN 2;ULIM {target_value[device_id]*10};SWEEP UP") + else: + write_no_echo(instr1, "CHAN 2;LLIM {target_value[device_id]*10};SWEEP DOWN") + elif '2101014' in device_id: value = sep_num_from_units(query_no_echo(instr2, 'IMAG?'))[0]*0.1 # convert kG to T + if value <= target_value[device_id]: + write_no_echo(instr2, f"ULIM {target_value[device_id]*10};SWEEP UP") + else: + write_no_echo(instr2, "LLIM {target_value[device_id]*10};SWEEP DOWN") + else: + continue # Skip if device ID is not recognized print(f"Device {device_id} reports value: {value} T") - + with lock: shared_values[device_id] = value # Check if both devices have met their targets - if all(shared_values.get(device) is not None and abs(shared_values[device] - target_value[device]) <= 0.0001 - for device in shared_values): + if all(shared_values.get(device) is not None and abs(value - target_value[device]) <= 0.0001 + for device,value in shared_values.items()): print(f"Both devices reached their target values: {shared_values}") all_targets_met_event.set() # Signal that both targets are met @@ -891,6 +902,10 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # Wait until both devices meet their target values all_targets_met_event.wait() print(f"Both target values for iteration {iteration+1} met. Performing action...") + # Clean up threads + for thread in threads: + thread.join() + print(f"Threads for iteration {iteration+1} closed.\n") # Perform some action after both targets are met # we acquire with the LF @@ -912,12 +927,6 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) intensity_data.append(loaded_files.data[0][0][0]) - - # Clean up threads - for thread in threads: - thread.join() - - print(f"Threads for iteration {iteration+1} closed.\n") #prints total time the mapping lasted end_time = time.time() diff --git a/Test.py b/Test.py index 2a70cfa..33b9349 100644 --- a/Test.py +++ b/Test.py @@ -138,5 +138,13 @@ if __name__=="__main__": # print(generate_coord_list_fixed_angle(10, 5, 1, reverse=False)) + testdict = [{'2301034': bval[0], '2101014': bval[1]} for bval in coordinates] + print(f"{testdict=}") + + for i, target in enumerate(testdict): + print(i, target.keys()) + # for key in target.keys(): + # print(type(key)) + \ No newline at end of file -- 2.39.5 From 67c564188c624d9ce9dbe04809d60b20631cbc82 Mon Sep 17 00:00:00 2001 From: ryantan Date: Tue, 15 Apr 2025 14:07:16 +0200 Subject: [PATCH 26/39] fefe --- Mag_Field_Sweep_2024_10_21.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Mag_Field_Sweep_2024_10_21.py b/Mag_Field_Sweep_2024_10_21.py index 1b75d9f..f492987 100644 --- a/Mag_Field_Sweep_2024_10_21.py +++ b/Mag_Field_Sweep_2024_10_21.py @@ -778,6 +778,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R """ # TODO: possibly rename instr1 and instr2 to the dual and single power supplies respectively?? + # TODO: add logging to the script # defines the folder, in which the data from the spectrometer is temporarily stored in temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/B_Field_Dump" -- 2.39.5 From bcf86c4d70e86319db1b33bfa7b5492f49a62066 Mon Sep 17 00:00:00 2001 From: ryantan Date: Tue, 15 Apr 2025 14:51:09 +0200 Subject: [PATCH 27/39] b_rotation functionality finished TODO: sweep_b_angle and logging in b_rotation --- Mag_Field_Sweep_2024_10_21.py | 8 ++++++++ ThreadTest.py | 5 +++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/Mag_Field_Sweep_2024_10_21.py b/Mag_Field_Sweep_2024_10_21.py index f492987..61b7f00 100644 --- a/Mag_Field_Sweep_2024_10_21.py +++ b/Mag_Field_Sweep_2024_10_21.py @@ -966,6 +966,14 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # call the helper function to carry out the rotation/measurement of spectrum monitor_devices(device_target_values, angles, intensity_data) + +# TODO: implement b_sweep at an arbitrary angle in the Bx-By plane +# copy the functionality of loading the powerboxsupplies from b_rotation and the other sweep functionalities of +# b_sweep_val and implement it in this function +def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, + min_bval:float, max_bval:float, res:float, + Settings:str, clockwise=True, base_file_name='', zerowhenfin_bool=False): + pass ################################################################# END OF FUNCTION DEFS ########################################################################################### diff --git a/ThreadTest.py b/ThreadTest.py index 8d7ff7e..3f0f854 100644 --- a/ThreadTest.py +++ b/ThreadTest.py @@ -37,8 +37,9 @@ def device_thread(device_id): print(f"Device {device_id} => {my_val} | Device {other_id} => {other_val}") if not is_within_tolerance(my_val, other_val): - print(f"Device {device_id} is out of tolerance! Pausing...") - device_events[device_id].clear() + # print(f"Device {device_id} is out of tolerance! Pausing...") + # device_events[device_id].clear() + print("Not within tolerance!") time.sleep(0.1) # Faster check interval -- 2.39.5 From 28263aaefb3cddf1ed95547e7c575ebbeba4cb65 Mon Sep 17 00:00:00 2001 From: ryantan Date: Tue, 15 Apr 2025 15:23:42 +0200 Subject: [PATCH 28/39] upper limit of Babs check in b_field_rotation added --- Mag_Field_Sweep_2024_10_21.py | 59 +++++++++++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 6 deletions(-) diff --git a/Mag_Field_Sweep_2024_10_21.py b/Mag_Field_Sweep_2024_10_21.py index 61b7f00..0ccfa9b 100644 --- a/Mag_Field_Sweep_2024_10_21.py +++ b/Mag_Field_Sweep_2024_10_21.py @@ -764,7 +764,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R Babs:float, startangle:float, endangle:float, angle_stepsize:float, Settings:str, clockwise=True, base_file_name='', zerowhenfin_bool=False)->None: # TODO: update docs """Rotation of the b-field in discrete steps, spectrum is measured at each discrete step in the rotation. Scan angle is - defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. + defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. Args: instr1 (pyvisa.resources.Resource): _description_ @@ -779,6 +779,8 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # TODO: possibly rename instr1 and instr2 to the dual and single power supplies respectively?? # TODO: add logging to the script + # TODO: add check if Babs is within the limits of the power supply, and if not, raise an error + # defines the folder, in which the data from the spectrometer is temporarily stored in temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/B_Field_Dump" @@ -838,8 +840,11 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R write_no_echo(instr1, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') - write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit - print(f'SWEEPING B-X TO {Babs} T NOW') + if Babs <= BX_MAX: + write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit + print(f'SWEEPING B-X TO {Babs} T NOW') + else: + raise ValueError(f'{Babs=}T value exceeds the max limit of the Bx field {BX_MAX}T!') # wait for Babs to be reached by the Bx field actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T @@ -961,7 +966,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R wl = np.array(loaded_files.wavelength) np.savetxt("Wavelength.txt", wl) - # TODO: data struct of device_target_values is not correct + # NOTE: data struct of device_target_values is a list of dictionaries, where each dictionary contains the target values for each device device_target_values = [{'2301034': bval[0], '2101014': bval[1]} for bval in cartesian_coords] # call the helper function to carry out the rotation/measurement of spectrum @@ -972,8 +977,50 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # b_sweep_val and implement it in this function def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, min_bval:float, max_bval:float, res:float, - Settings:str, clockwise=True, base_file_name='', zerowhenfin_bool=False): - pass + Settings:str, clockwise=True, base_file_name='', + reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False): + + # defines the folder, in which the data from the spectrometer is temporarily stored in + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/B_Field_Dump" + # temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + + if base_file_name =='': + base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') + + start_time = time.time() # start of the scan function + + startangle = startangle % 360 + endangle = endangle % 360 # ensures that the angles are within [0,360) + + idnstr1 = query_no_echo(instr1, '*IDN?') + idnstr2 = query_no_echo(instr2, '*IDN?') + + intensity_data = [] # To store data from each scan + cwd = os.getcwd() # save original directory + + # find which one is the dual power supply, then, ramp B_x to Babs value + if '2301034' in idnstr1: # serial no. the dual power supply + pass + elif '2101034' in idnstr2: + # swap instruments, instr 1 to be the dual power supply (^= x-axis) + instr1, instr2 = instr2, instr1 + + # save initial low and high sweep limits of each device, and set them back after the rotation + instr1_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + instr2_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + if instr1_bsettings[0][0] == 'T': + instr1_bsettings[1][0] = instr1_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr1_bsettings[2][0] = instr1_bsettings[2][0]*0.1 + if instr2_bsettings[0][0] == 'T': + instr2_bsettings[1][0] = instr2_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr2_bsettings[2][0] = instr2_bsettings[2][0]*0.1 + + # initialise the sweep angle list as well as the sweep limits and directions for each instrument + instr1_lim, instr2_lim = 'LLIM', 'ULIM' + instr1_sweep, instr2_sweep = 'DOWN', 'UP' + + # TODO: see later parts of b_field_rotation from line 820 onwards, and see if same logic can be applied here + ################################################################# END OF FUNCTION DEFS ########################################################################################### -- 2.39.5 From 9754e25d9cb51da52f1ad26b9865f930e84fb879 Mon Sep 17 00:00:00 2001 From: ryantan Date: Tue, 15 Apr 2025 15:33:28 +0200 Subject: [PATCH 29/39] changed name of the scanscript --- Mag_Field_Sweep_2024_10_21.py => Mag_Field_Sweep_2025_04_15.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Mag_Field_Sweep_2024_10_21.py => Mag_Field_Sweep_2025_04_15.py (100%) diff --git a/Mag_Field_Sweep_2024_10_21.py b/Mag_Field_Sweep_2025_04_15.py similarity index 100% rename from Mag_Field_Sweep_2024_10_21.py rename to Mag_Field_Sweep_2025_04_15.py -- 2.39.5 From dd24a0ace96442912a2b90b8ee46a9fcb7bf6cd7 Mon Sep 17 00:00:00 2001 From: ryantan Date: Wed, 16 Apr 2025 09:57:30 +0200 Subject: [PATCH 30/39] overall changes to generate_coord_list_fixed_angle --- Mag_Field_Sweep_2025_04_15.py | 40 +++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/Mag_Field_Sweep_2025_04_15.py b/Mag_Field_Sweep_2025_04_15.py index 0ccfa9b..bf40316 100644 --- a/Mag_Field_Sweep_2025_04_15.py +++ b/Mag_Field_Sweep_2025_04_15.py @@ -643,8 +643,11 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, wl = np.array(loaded_files.wavelength) np.savetxt("Wavelength.txt", wl) np.savetxt("B_Values.txt", bval_lst) - + +# NOTE: old function of generate_coor_list_fixed_angle +''' def generate_coord_list_fixed_angle(angle, b_val, b_val_step_size, reverse=False): + # TODO: mod function to take different b_min and b_max along given angle. update docs """ Generates a list of (x, y) Cartesian coordinates along a line defined by a fixed angle, scanning from -b_val to b_val or from b_val to -b_val depending on the reverse flag. @@ -682,6 +685,32 @@ def generate_coord_list_fixed_angle(angle, b_val, b_val_step_size, reverse=False current_b += b_val_step_size return coordinates + ''' + +def generate_coord_list_fixed_angle(angle, b_min, b_max, b_val_step_size, reverse=False): + """ + Generates a list of (x, y) Cartesian coordinates along a line defined by a fixed angle, + scanning from b_min to b_max or from b_max to b_min depending on the reverse flag. + """ + coordinates = [] + angle_rad = math.radians(angle) + + if reverse: + current_b = b_max + while current_b >= b_min: + x = current_b * math.cos(angle_rad) + y = current_b * math.sin(angle_rad) + coordinates.append((x, y)) + current_b -= b_val_step_size + else: + current_b = b_min + while current_b <= b_max: + x = current_b * math.cos(angle_rad) + y = current_b * math.sin(angle_rad) + coordinates.append((x, y)) + current_b += b_val_step_size + + return coordinates def generate_angle_coord_list(radius, start_angle, end_angle, step_size, clockwise=True): # TODO: DOCS @@ -840,6 +869,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R write_no_echo(instr1, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + # TODO: see if this is the desired process: to always start from the x-axis ASK LUKAS if Babs <= BX_MAX: write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit print(f'SWEEPING B-X TO {Babs} T NOW') @@ -975,8 +1005,9 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # TODO: implement b_sweep at an arbitrary angle in the Bx-By plane # copy the functionality of loading the powerboxsupplies from b_rotation and the other sweep functionalities of # b_sweep_val and implement it in this function +# CHECK: B_abs <= BX_MAX or BY_MAX def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, - min_bval:float, max_bval:float, res:float, + min_bval:float, max_bval:float, res:float, angle:float, Settings:str, clockwise=True, base_file_name='', reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False): @@ -1020,8 +1051,9 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso instr1_sweep, instr2_sweep = 'DOWN', 'UP' # TODO: see later parts of b_field_rotation from line 820 onwards, and see if same logic can be applied here - - + # acquire coordinates along the fixed axis, threading, sweep both supplies till desired value (with lock) + # then set event, measure, on with the next iteration, just like in b-field-rotation + cartesian_coords = generate_coord_list_fixed_angle(angle, ) ################################################################# END OF FUNCTION DEFS ########################################################################################### -- 2.39.5 From e746a664bdf4f19933490bef3937fa460775d45b Mon Sep 17 00:00:00 2001 From: ryantan Date: Wed, 16 Apr 2025 12:56:44 +0200 Subject: [PATCH 31/39] begun in writing test script for b_rotation function --- Mag_Field_Sweep_2025_04_15.py | 32 ++- b_rotation_test.py | 413 ++++++++++++++++++++++++++++++++++ 2 files changed, 434 insertions(+), 11 deletions(-) create mode 100644 b_rotation_test.py diff --git a/Mag_Field_Sweep_2025_04_15.py b/Mag_Field_Sweep_2025_04_15.py index bf40316..2ddfe69 100644 --- a/Mag_Field_Sweep_2025_04_15.py +++ b/Mag_Field_Sweep_2025_04_15.py @@ -506,8 +506,6 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, # b = np.arange(max_bval, min_bval - res, res) # bval_lst = np.concatenate((a,b)) - # TODO: unused, see if can remove - # init_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1 # queries the initial B value of the coil, rescale from kG to T init_lim, subsequent_lim = 'LLIM', 'ULIM' init_sweep, subsequent_sweep = 'DOWN', 'UP' @@ -610,7 +608,7 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float, spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') os.remove(spe_file_path) - points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT + points_left = total_points - i - 1 print('Points left in the scan: ', points_left) #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) @@ -687,7 +685,7 @@ def generate_coord_list_fixed_angle(angle, b_val, b_val_step_size, reverse=False return coordinates ''' -def generate_coord_list_fixed_angle(angle, b_min, b_max, b_val_step_size, reverse=False): +def generate_coord_list_fixed_angle(angle, b_min, b_max, b_val_step_size, reverse=False)->list[tuple]: """ Generates a list of (x, y) Cartesian coordinates along a line defined by a fixed angle, scanning from b_min to b_max or from b_max to b_min depending on the reverse flag. @@ -790,7 +788,8 @@ def generate_angle_coord_list(radius, start_angle, end_angle, step_size, clockwi def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, - Babs:float, startangle:float, endangle:float, angle_stepsize:float, Settings:str, clockwise=True, base_file_name='', zerowhenfin_bool=False)->None: + Babs:float, startangle:float, endangle:float, angle_stepsize:float, + Settings:str, clockwise=True, base_file_name='', zerowhenfin_bool=False)->None: # TODO: update docs """Rotation of the b-field in discrete steps, spectrum is measured at each discrete step in the rotation. Scan angle is defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. @@ -806,10 +805,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R zerowhenfin_bool (bool, optional): after finishing the rotation, both B-field components should be set to 0 T. Defaults to False. """ - # TODO: possibly rename instr1 and instr2 to the dual and single power supplies respectively?? # TODO: add logging to the script - # TODO: add check if Babs is within the limits of the power supply, and if not, raise an error - # defines the folder, in which the data from the spectrometer is temporarily stored in temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/B_Field_Dump" @@ -858,6 +854,9 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R instr1_lim, instr2_lim = instr2_lim, instr1_lim instr1_sweep, instr2_sweep = instr2_sweep, instr1_sweep + + # TODO: i dont think we need to change the rates just yet, think about this later + ''' # list of rates (with units) for diff ranges of each device, only up to Range 1 for single power supply as that is already # the max recommended current. init_range_lst1 = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'RATE? 0;RATE? 1;RATE? 2').split(';')) @@ -868,6 +867,8 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # set both devices to the min rates write_no_echo(instr1, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + ''' + # TODO: see if this is the desired process: to always start from the x-axis ASK LUKAS if Babs <= BX_MAX: @@ -883,7 +884,10 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R time.sleep(5) # little break actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') + + + # TODO: copy and mod code to see if block logic works, test in lab # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN # Helper function that listens to a device def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event): @@ -958,8 +962,8 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') os.remove(spe_file_path) - # points_left = total_points - i - 1 # TODO: SEE IF THIS IS CORRECT - # print('Points left in the scan: ', points_left) + points_left = len(angles) - iteration - 1 + print('Points left in the scan: ', points_left) #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) intensity_data.append(loaded_files.data[0][0][0]) @@ -972,10 +976,16 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # reset both devices to original sweep limits write_no_echo(instr1, f'LLIM {instr1_bsettings[1][0]*10};ULIM {instr1_bsettings[2][0]*10}') # reset the initial limits of the device after the scan write_no_echo(instr2, f'LLIM {instr2_bsettings[1][0]*10};ULIM {instr2_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + + + # TODO: uncomment later if resetting original rates implemented + ''' # reset both devices' initial rates for each range write_no_echo(instr1, f'RANGE 0 {init_range_lst1[0][0]};RANGE 1 {init_range_lst1[1][0]};RANGE 2 {init_range_lst1[2][0]}') # reset the initial limits of the device after the scan write_no_echo(instr2, f'RANGE 0 {init_range_lst2[0][0]};RANGE 1 {init_range_lst2[1][0]}') # reset the initial limits of the device after the scan - + ''' + + if zerowhenfin_bool: write_no_echo(instr1, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above write_no_echo(instr2, 'SWEEP ZERO') diff --git a/b_rotation_test.py b/b_rotation_test.py new file mode 100644 index 0000000..2c28750 --- /dev/null +++ b/b_rotation_test.py @@ -0,0 +1,413 @@ +############################################ +# Packages from Ryan +import re +import math +import threading +import pyvisa +# from pyvisa import ResourceManager, constants + +# B Field Limits (in T) +BX_MAX = 1.7 +BY_MAX = 1.7 +BZ_MAX = 4.0 +############################################ + +# import AMC +import csv +import time +import clr +import sys +import os +import spe2py as spe +import spe_loader as sl +import pandas as pd +import time +# from System.IO import * +# from System import String +import numpy as np +import matplotlib.pyplot as plt +import datetime +from typing import Union + +def sep_num_from_units(powerbox_output :str)->list: + ''' + Receives a string as input and separates the numberic value and unit and returns it as a list. + + Parameters + ---------- + powerbox_output : str + string output from the attocube powerbox, e.g. 1.35325kG + + Returns + ------- + list + list of float value and string (b value and it's units). If string is purely alphabets, then return a single element list + + ''' + match = re.match(r'\s*([+-]?\d*\.?\d+)([A-Za-z]+)', powerbox_output) + if match: + numeric_part = float(match.group(1)) # Convert the numeric part to a float + alphabetic_part = match.group(2) # Get the alphabetic part + return [numeric_part, alphabetic_part] + else: + return [powerbox_output,] + + +def query_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: + """helper function for the Attocube APS100 that queries a function to the device, removing the echo. + + Args: + instr (pyvisa.resources.Resource): + command (str): commands, can be stringed in series with ; between commands + sleeptime (float, optional): delay time between commands. Defaults to 0.01. + + Returns: + str: _description_ + """ '''''' + try: + print(f"Sending command: {command}") + instr.write(command) + time.sleep(sleeptime) + echo_response = instr.read() # Read and discard the echo + # print(f"Echo response: {echo_response}") + actual_response = instr.read() # Read the actual response + print(f"Actual response: {actual_response}") + return actual_response + except pyvisa.VisaIOError as e: + print(f"Error communicating with instrument: {e}") + return None + + +def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: + """helper function for the Attocube APS100 that writes a function to the device, removing the echo. + + Args: + instr (pyvisa.resources.Resource): + command (str): commands, can be stringed in series with ; between commands + sleeptime (float, optional): delay time between commands. Defaults to 0.01. + + Returns: + str: _description_ + """ '''''' + try: + print(f"Sending command: {command}") + instr.write(command) + time.sleep(sleeptime) # Give the device some time to process + try: + while True: + echo_response = instr.read() # Read and discard the echo + # print(f"Echo response: {echo_response}") + except pyvisa.VisaIOError as e: + # Expected timeout after all echoed responses are read + if e.error_code != pyvisa.constants.VI_ERROR_TMO: + raise + except pyvisa.VisaIOError as e: + print(f"Error communicating with instrument: {e}") + + +def generate_angle_coord_list(radius, start_angle, end_angle, step_size, clockwise=True): + # TODO: DOCS + """Creates a list of discrete cartesian coordinates (x,y), given the radius, start- and end angles, the angle step size, and the direction of rotation. + Function then returns a list of two lists: list of angles and list of cartesian coordinates (x,y coordinates in a tuple). + + Args: + radius (_type_): _description_ + start_angle (_type_): _description_ + end_angle (_type_): _description_ + step_size (_type_): _description_ + clockwise (bool, optional): _description_. Defaults to True. + + Returns: + _type_: _description_ + """ """""" + # Initialize lists to hold angles and (x, y) pairs + angles = [] + coordinates = [] + + # Normalize angles to the range [0, 360) + start_angle = start_angle % 360 + end_angle = end_angle % 360 + + if not clockwise: + # Clockwise rotation + current_angle = start_angle + while True: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle (handling wrap-around) (current_angle - step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: + break + + # Decrement the current angle by the step size + current_angle -= step_size + if current_angle < 0: + current_angle += 360 + else: + # Counterclockwise rotation + current_angle = start_angle + while True: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle (handling wrap-around) (current_angle + step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: + break + + # Increment the current angle by the step size + current_angle += step_size + if current_angle >= 360: + current_angle -= 360 + + return [angles, coordinates] + +def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, + Babs:float, startangle:float, endangle:float, angle_stepsize:float, + Settings:str, clockwise=True, base_file_name='', zerowhenfin_bool=False)->None: + # TODO: update docs + """Rotation of the b-field in discrete steps, spectrum is measured at each discrete step in the rotation. Scan angle is + defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. + + Args: + instr1 (pyvisa.resources.Resource): _description_ + instr2 (pyvisa.resources.Resource): _description_ + Babs (float): absolute B-field value in T + startangle (float): start angle in degrees + endangle (float): end angle in degrees + angle_stepsize (float): angle step size in degrees + clockwise (bool): determines the direction of rotation of the B-field. Defaults to True. + zerowhenfin_bool (bool, optional): after finishing the rotation, both B-field components should be set to 0 T. Defaults to False. + """ + + # TODO: add logging to the script + + # defines the folder, in which the data from the spectrometer is temporarily stored in + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/B_Field_Dump" + # temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + + if base_file_name =='': + base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') + + start_time = time.time() # start of the scan function + + startangle = startangle % 360 + endangle = endangle % 360 # ensures that the angles are within [0,360) + + idnstr1 = query_no_echo(instr1, '*IDN?') + idnstr2 = query_no_echo(instr2, '*IDN?') + + intensity_data = [] # To store data from each scan + cwd = os.getcwd() # save original directory + + # find which one is the dual power supply, then, ramp B_x to Babs value + if '2301034' in idnstr1: # serial no. the dual power supply + pass + elif '2101034' in idnstr2: + # swap instruments, instr 1 to be the dual power supply (^= x-axis) + instr1, instr2 = instr2, instr1 + + # save initial low and high sweep limits of each device, and set them back after the rotation + instr1_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + instr2_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + if instr1_bsettings[0][0] == 'T': + instr1_bsettings[1][0] = instr1_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr1_bsettings[2][0] = instr1_bsettings[2][0]*0.1 + if instr2_bsettings[0][0] == 'T': + instr2_bsettings[1][0] = instr2_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr2_bsettings[2][0] = instr2_bsettings[2][0]*0.1 + + # initialise the sweep angle list as well as the sweep limits and directions for each instrument + instr1_lim, instr2_lim = 'LLIM', 'ULIM' + instr1_sweep, instr2_sweep = 'DOWN', 'UP' + + # create lists of angles and discrete Cartesian coordinates + angles, cartesian_coords = generate_angle_coord_list(Babs, startangle, endangle, angle_stepsize, clockwise=clockwise) + + if clockwise: # NOTE: old conditional was: startangle > endangle see if this works.... + # reverse sweep limits and directions for the clockwise rotation + instr1_lim, instr2_lim = instr2_lim, instr1_lim + instr1_sweep, instr2_sweep = instr2_sweep, instr1_sweep + + + # TODO: i dont think we need to change the rates just yet, think about this later + ''' + # list of rates (with units) for diff ranges of each device, only up to Range 1 for single power supply as that is already + # the max recommended current. + init_range_lst1 = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'RATE? 0;RATE? 1;RATE? 2').split(';')) + init_range_lst2 = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'RATE? 0;RATE? 1').split(';')) + + min_range_lst = [min(el1[0], el2[0]) for el1,el2 in zip(init_range_lst1, init_range_lst2)] # min rates for each given range + + # set both devices to the min rates + write_no_echo(instr1, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + ''' + + + # TODO: see if this is the desired process: to always start from the x-axis ASK LUKAS + if Babs <= BX_MAX: + # write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit + print(f'SWEEPING B-X TO {Babs} T NOW') + else: + raise ValueError(f'{Babs=}T value exceeds the max limit of the Bx field {BX_MAX}T!') + + # wait for Babs to be reached by the Bx field + actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') + while abs(actual_bval - Babs) > 0.0001: + time.sleep(5) # little break + actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 + print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') + + + + # TODO: copy and mod code to see if block logic works, test in lab + # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN + # Helper function that listens to a device + def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event): + while not all_targets_met_event.is_set(): # Loop until the event is set + # value = 0 # Simulate receiving a float from the device INSERT QUERY NO ECHO HERE TO ASK FOR DEVICE IMAG + if '2301034' in device_id: + value = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + if value <= target_value[device_id]: + # write_no_echo(instr1, f"CHAN 2;ULIM {target_value[device_id]*10};SWEEP UP") + print(f'sweeping Bx up to {target_value[device_id]*10}') + else: + # write_no_echo(instr1, "CHAN 2;LLIM {target_value[device_id]*10};SWEEP DOWN") + print(f'sweeping Bx down to {target_value[device_id]*10}') + + elif '2101014' in device_id: + value = sep_num_from_units(query_no_echo(instr2, 'IMAG?'))[0]*0.1 # convert kG to T + if value <= target_value[device_id]: + # write_no_echo(instr2, f"ULIM {target_value[device_id]*10};SWEEP UP") + print(f'sweeping By up to {target_value[device_id]*10}') + else: + # write_no_echo(instr2, "LLIM {target_value[device_id]*10};SWEEP DOWN") + print(f'sweeping By down to {target_value[device_id]*10}') + else: + continue # Skip if device ID is not recognized + print(f"Device {device_id} reports value: {value} T") + + with lock: + shared_values[device_id] = value + # Check if both devices have met their targets + if all(shared_values.get(device) is not None and abs(value - target_value[device]) <= 0.0001 + for device,value in shared_values.items()): + print(f"Both devices reached their target values: {shared_values}") + all_targets_met_event.set() # Signal that both targets are met + + # time.sleep(1) # Simulate periodic data checking + + # Main function to manage threads and iterate over target values + def monitor_devices(device_target_values, angles_lst, intensity_data=intensity_data): + for iteration, target in enumerate(device_target_values): + print(f"\nStarting iteration {iteration+1} for target values: {target}") + # Shared dictionary to store values from devices + shared_values = {device: None for device in target.keys()} + # Event to signal when both target values are reached + all_targets_met_event = threading.Event() + + # Lock to synchronize access to shared_values + lock = threading.Lock() + + # Create and start threads for each device + threads = [] + for device_id in target.keys(): + thread = threading.Thread(target=listen_to_device, args=(device_id, target, shared_values, lock, all_targets_met_event)) + threads.append(thread) + thread.start() + + # Wait until both devices meet their target values + all_targets_met_event.wait() + print(f"Both target values for iteration {iteration+1} met. Performing action...") + # Clean up threads + for thread in threads: + thread.join() + print(f"Threads for iteration {iteration+1} closed.\n") + + # Perform some action after both targets are met + # we acquire with the LF + acquire_name_spe = f'{base_file_name}_{angles_lst[iteration]}°' # NOTE: save each intensity file with the given angle + AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + # read the .spe file and get the data as loaded_files + cwd = os.getcwd() # save original directory + os.chdir(temp_folder_path) #change directory + loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + os.chdir(cwd) # go back to original directory + + # Delete the created .spe file from acquiring after getting necessary info + spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') + os.remove(spe_file_path) + + points_left = len(angles) - iteration - 1 + print('Points left in the scan: ', points_left) + + #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + intensity_data.append(loaded_files.data[0][0][0]) + + #prints total time the mapping lasted + end_time = time.time() + elapsed_time = (end_time - start_time) / 60 + print('Scan time: ', elapsed_time, 'minutes') + + # reset both devices to original sweep limits + write_no_echo(instr1, f'LLIM {instr1_bsettings[1][0]*10};ULIM {instr1_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'LLIM {instr2_bsettings[1][0]*10};ULIM {instr2_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + + + # TODO: uncomment later if resetting original rates implemented + ''' + # reset both devices' initial rates for each range + write_no_echo(instr1, f'RANGE 0 {init_range_lst1[0][0]};RANGE 1 {init_range_lst1[1][0]};RANGE 2 {init_range_lst1[2][0]}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'RANGE 0 {init_range_lst2[0][0]};RANGE 1 {init_range_lst2[1][0]}') # reset the initial limits of the device after the scan + ''' + + + if zerowhenfin_bool: + # write_no_echo(instr1, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above + # write_no_echo(instr2, 'SWEEP ZERO') + print('======================\nSWEEPING BOTH DEVICES TO ZERO NOW\n======================') + + #save intensity & WL data as .txt + os.chdir('C:/Users/localadmin/Desktop/Users/Ryan') + # creates new folder for MAP data + new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + os.mkdir(new_folder_name) + # Here the things will be saved in a new folder under user Lukas ! + # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! + os.chdir('C:/Users/localadmin/Desktop/Users/Ryan/'+ new_folder_name) + + intensity_data = np.array(intensity_data) + np.savetxt(Settings + f'{angles[0]}°_to_{angles[-1]}°' + experiment_name +'.txt', intensity_data) + # TODO: remove/edit experiment_name in line above, as well in sweep_b_val func, rn takes a global variable below + + wl = np.array(loaded_files.wavelength) + np.savetxt("Wavelength.txt", wl) + + # NOTE: data struct of device_target_values is a list of dictionaries, where each dictionary contains the target values for each device + device_target_values = [{'2301034': bval[0], '2101014': bval[1]} for bval in cartesian_coords] + + # call the helper function to carry out the rotation/measurement of spectrum + monitor_devices(device_target_values, angles, intensity_data) + \ No newline at end of file -- 2.39.5 From 2969541799d290702607f16f78accee6e980d79e Mon Sep 17 00:00:00 2001 From: ryantan Date: Wed, 16 Apr 2025 13:07:35 +0200 Subject: [PATCH 32/39] implemented b_rotation_test fully --- b_rotation_test.py | 142 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 124 insertions(+), 18 deletions(-) diff --git a/b_rotation_test.py b/b_rotation_test.py index 2c28750..5721690 100644 --- a/b_rotation_test.py +++ b/b_rotation_test.py @@ -267,7 +267,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # TODO: see if this is the desired process: to always start from the x-axis ASK LUKAS if Babs <= BX_MAX: # write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit - print(f'SWEEPING B-X TO {Babs} T NOW') + print(f'SWITCHED TO BX, SWEEPING B-X TO {Babs} T NOW') else: raise ValueError(f'{Babs=}T value exceeds the max limit of the Bx field {BX_MAX}T!') @@ -336,6 +336,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R thread = threading.Thread(target=listen_to_device, args=(device_id, target, shared_values, lock, all_targets_met_event)) threads.append(thread) thread.start() + print(f"======================\nThread started for device {device_id}\n======================") # Wait until both devices meet their target values all_targets_met_event.wait() @@ -345,26 +346,29 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R thread.join() print(f"Threads for iteration {iteration+1} closed.\n") + + print(f'COLLECTING SPECTRUM FOR ANGLE {angles_lst[iteration]}°\n') # Perform some action after both targets are met # we acquire with the LF - acquire_name_spe = f'{base_file_name}_{angles_lst[iteration]}°' # NOTE: save each intensity file with the given angle - AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + # acquire_name_spe = f'{base_file_name}_{angles_lst[iteration]}°' # NOTE: save each intensity file with the given angle + # AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. # read the .spe file and get the data as loaded_files - cwd = os.getcwd() # save original directory - os.chdir(temp_folder_path) #change directory - loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable - os.chdir(cwd) # go back to original directory + # cwd = os.getcwd() # save original directory + # os.chdir(temp_folder_path) #change directory + # loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + # os.chdir(cwd) # go back to original directory # Delete the created .spe file from acquiring after getting necessary info - spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') - os.remove(spe_file_path) + # spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') + # os.remove(spe_file_path) points_left = len(angles) - iteration - 1 + print('Points left in the scan: ', points_left) #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) - intensity_data.append(loaded_files.data[0][0][0]) + # intensity_data.append(loaded_files.data[0][0][0]) #prints total time the mapping lasted end_time = time.time() @@ -392,22 +396,124 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R #save intensity & WL data as .txt os.chdir('C:/Users/localadmin/Desktop/Users/Ryan') # creates new folder for MAP data - new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" - os.mkdir(new_folder_name) + # new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + # os.mkdir(new_folder_name) # Here the things will be saved in a new folder under user Lukas ! # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! - os.chdir('C:/Users/localadmin/Desktop/Users/Ryan/'+ new_folder_name) + # os.chdir('C:/Users/localadmin/Desktop/Users/Ryan/'+ new_folder_name) - intensity_data = np.array(intensity_data) - np.savetxt(Settings + f'{angles[0]}°_to_{angles[-1]}°' + experiment_name +'.txt', intensity_data) + # intensity_data = np.array(intensity_data) + # np.savetxt(Settings + f'{angles[0]}°_to_{angles[-1]}°' + experiment_name +'.txt', intensity_data) # TODO: remove/edit experiment_name in line above, as well in sweep_b_val func, rn takes a global variable below - wl = np.array(loaded_files.wavelength) - np.savetxt("Wavelength.txt", wl) + # wl = np.array(loaded_files.wavelength) + # np.savetxt("Wavelength.txt", wl) # NOTE: data struct of device_target_values is a list of dictionaries, where each dictionary contains the target values for each device device_target_values = [{'2301034': bval[0], '2101014': bval[1]} for bval in cartesian_coords] # call the helper function to carry out the rotation/measurement of spectrum monitor_devices(device_target_values, angles, intensity_data) - \ No newline at end of file + + +################################################################# END OF FUNCTION DEFS ########################################################################################### + +# NOTE: RYAN INTRODUCED SOME FUNCTIONS HERE TO PERFORM THE SCAN + +# Initialise PYVISA ResourceManager +rm = pyvisa.ResourceManager() +# print(rm.list_resources()) +# 'ASRL8::INSTR' for dual power supply, 'ASRL9::INSTR' for single power supply (online PC) +# 'ASRL10::INSTR' for dual power supply, 'ASRL12::INSTR' for single power supply (offline PC) + +try: + # Open the connection with the APS100 dual power supply + powerbox_dualsupply = rm.open_resource('ASRL10::INSTR', + baud_rate=9600, + data_bits=8, + parity= pyvisa.constants.Parity.none, + stop_bits= pyvisa.constants.StopBits.one, + timeout=10000)# 5000 ms timeout + write_no_echo(powerbox_dualsupply, 'REMOTE') # turn on the remote mode + + # # select axis for the dual supply, either z-axis(CHAN 1 ^= Supply A) or x-axis(CHAN 2 ^= Supply B) + write_no_echo(powerbox_dualsupply, 'CHAN 2') + # # #for dual until here + + # Open the connection with the APS100 single power supply + powerbox_singlesupply = rm.open_resource('ASRL12::INSTR', + baud_rate=9600, + data_bits=8, + parity= pyvisa.constants.Parity.none, + stop_bits= pyvisa.constants.StopBits.one, + timeout=10000)# 5000 ms timeout + write_no_echo(powerbox_singlesupply, 'REMOTE') # turn on the remote mode + #for single until here + # TODO: uncomment AMC connection code later, when moving the probe in cryostat is needed. + # Setup connection to AMC + # amc = AMC.Device(IP) + # amc.connect() + + # # Internally, axes are numbered 0 to 2 + # amc.control.setControlOutput(0, True) + # amc.control.setControlOutput(1, True) + + + # auto = Automation(True, List[String]()) + # experiment = auto.LightFieldApplication.Experiment + # acquireCompleted = AutoResetEvent(False) + + # experiment.Load("2025_03_28_Priyanka_CrSBr_DR_Sweep") + # experiment.ExperimentCompleted += experiment_completed # we are hooking a listener. + # experiment.SetValue(SpectrometerSettings.GratingSelected, '[750nm,1200][0][0]') + # InitializerFilenameParams() + + + #set scan range and resolution in nanometers + range_x = 20000 + range_y = 20000 + resolution = 1000 + # set B-field scan range and resolution (all in T) + set_llim_bval = -0.3 + set_ulim_bval = 0.3 + set_res_bval = 0.003 + + #Here you can specify the filename of the map e.g. put experiment type, exposure time, used filters, etc.... + # 'PL_SP_700_LP_700_HeNe_52muW_exp_2s_Start_' + # experiment_settings = 'PL_X_1859.2_Y_3918.3_HeNe_10.4muW_H_a-axis_LP_SP_650_exp_180s_600g_cwl_930_det_b-axis_Pol_90_l2_45' + experiment_settings = 'DR_white_6th spot_Power_G600_exp_25s_l1_40_l2_262_det_b_mag_b' + #The program adds the range of the scan as well as the resolution and the date and time of the measurement + # f"{set_llim_bval}T_to_{set_ulim_bval}T_{set_res_bval}T_{datetime.datetime.now().strftime('%Y_%m_%d_%H%M')}" + experiment_name = f"{set_llim_bval}T_to_{set_ulim_bval}T_stepsize_{set_res_bval}T" + + # this moves the probe in xy-direction and measures spectrum there + # move_scan_xy(range_x, range_y, resolution, experiment_settings, experiment_name) + + # ramp_b_val(powerbox_singlesupply, 0, 'y-axis') + # ramp_b_val(powerbox_dualsupply, 0, 'z-axis') + + + # for single/ dual replace and vice versa all the way down + # sweep_b_val(powerbox_singlesupply, set_llim_bval, set_ulim_bval, set_res_bval, 'y-axis', + # experiment_settings, experiment_name, zerowhenfin_bool=True, reversescan_bool=False, loopscan_bool=True) + b_field_rotation(powerbox_dualsupply, powerbox_singlesupply, Babs=0.1, startangle=0, endangle=3, + angle_stepsize=1, Settings=experiment_settings, zerowhenfin_bool=True + ) + + write_no_echo(powerbox_dualsupply, 'LOCAL') # turn off the remote mode + write_no_echo(powerbox_singlesupply, 'LOCAL') # turn off the remote mode + + time.sleep(0.5) + # powerbox_dualsupply.close() + powerbox_singlesupply.close() + +except Exception as e: + print(e) + # Internally, axes are numbered 0 to 2 + + write_no_echo(powerbox_dualsupply, 'LOCAL') # turn off the remote mode + write_no_echo(powerbox_singlesupply, 'LOCAL') # turn off the remote mode + + time.sleep(0.5) + powerbox_dualsupply.close() + powerbox_singlesupply.close() \ No newline at end of file -- 2.39.5 From 4e2993486f5e0a5b1438faa7e03c896208bfbd27 Mon Sep 17 00:00:00 2001 From: ryantan Date: Wed, 16 Apr 2025 14:22:19 +0200 Subject: [PATCH 33/39] b_rot function test successful, logic works out --- b_rotation_test_v2.py | 531 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 531 insertions(+) create mode 100644 b_rotation_test_v2.py diff --git a/b_rotation_test_v2.py b/b_rotation_test_v2.py new file mode 100644 index 0000000..adaa863 --- /dev/null +++ b/b_rotation_test_v2.py @@ -0,0 +1,531 @@ +''' +16.04.2025: Initial Test Results for B-field rotation +The logic chain in the function works well, now we need the other function that +scans along an arbitrary axis in plane. +''' +############################################ +# Packages from Ryan +import re +import math +import threading +import pyvisa +# from pyvisa import ResourceManager, constants + +# B Field Limits (in T) +BX_MAX = 1.7 +BY_MAX = 1.7 +BZ_MAX = 4.0 +############################################ + +# import AMC +import csv +import time +import clr +import sys +import os +import spe2py as spe +import spe_loader as sl +import pandas as pd +import time +# from System.IO import * +# from System import String +import numpy as np +import matplotlib.pyplot as plt +import datetime +from typing import Union + +def sep_num_from_units(powerbox_output :str)->list: + ''' + Receives a string as input and separates the numberic value and unit and returns it as a list. + + Parameters + ---------- + powerbox_output : str + string output from the attocube powerbox, e.g. 1.35325kG + + Returns + ------- + list + list of float value and string (b value and it's units). If string is purely alphabets, then return a single element list + + ''' + match = re.match(r'\s*([+-]?\d*\.?\d+)([A-Za-z]+)', powerbox_output) + if match: + numeric_part = float(match.group(1)) # Convert the numeric part to a float + alphabetic_part = match.group(2) # Get the alphabetic part + return [numeric_part, alphabetic_part] + else: + return [powerbox_output,] + + +def query_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: + """helper function for the Attocube APS100 that queries a function to the device, removing the echo. + + Args: + instr (pyvisa.resources.Resource): + command (str): commands, can be stringed in series with ; between commands + sleeptime (float, optional): delay time between commands. Defaults to 0.01. + + Returns: + str: _description_ + """ '''''' + try: + print(f"Sending command: {command}") + instr.write(command) + time.sleep(sleeptime) + echo_response = instr.read() # Read and discard the echo + # print(f"Echo response: {echo_response}") + actual_response = instr.read() # Read the actual response + print(f"Actual response: {actual_response}") + return actual_response + except pyvisa.VisaIOError as e: + print(f"Error communicating with instrument: {e}") + return None + + +def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0)->str: + """helper function for the Attocube APS100 that writes a function to the device, removing the echo. + + Args: + instr (pyvisa.resources.Resource): + command (str): commands, can be stringed in series with ; between commands + sleeptime (float, optional): delay time between commands. Defaults to 0.01. + + Returns: + str: _description_ + """ '''''' + try: + print(f"Sending command: {command}") + instr.write(command) + time.sleep(sleeptime) # Give the device some time to process + try: + while True: + echo_response = instr.read() # Read and discard the echo + # print(f"Echo response: {echo_response}") + except pyvisa.VisaIOError as e: + # Expected timeout after all echoed responses are read + if e.error_code != pyvisa.constants.VI_ERROR_TMO: + raise + except pyvisa.VisaIOError as e: + print(f"Error communicating with instrument: {e}") + + +def generate_angle_coord_list(radius, start_angle, end_angle, step_size, clockwise=True): + # TODO: DOCS + """Creates a list of discrete cartesian coordinates (x,y), given the radius, start- and end angles, the angle step size, and the direction of rotation. + Function then returns a list of two lists: list of angles and list of cartesian coordinates (x,y coordinates in a tuple). + + Args: + radius (_type_): _description_ + start_angle (_type_): _description_ + end_angle (_type_): _description_ + step_size (_type_): _description_ + clockwise (bool, optional): _description_. Defaults to True. + + Returns: + _type_: _description_ + """ """""" + # Initialize lists to hold angles and (x, y) pairs + angles = [] + coordinates = [] + + # Normalize angles to the range [0, 360) + start_angle = start_angle % 360 + end_angle = end_angle % 360 + + if not clockwise: + # Clockwise rotation + current_angle = start_angle + while True: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle (handling wrap-around) (current_angle - step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: + break + + # Decrement the current angle by the step size + current_angle -= step_size + if current_angle < 0: + current_angle += 360 + else: + # Counterclockwise rotation + current_angle = start_angle + while True: + # Append the current angle to the angles list + angles.append(current_angle % 360) + + # Convert the current angle to radians + current_angle_rad = math.radians(current_angle % 360) + + # Convert polar to Cartesian coordinates + x = radius * math.cos(current_angle_rad) + y = radius * math.sin(current_angle_rad) + + # Append the (x, y) pair to the list + coordinates.append((x, y)) + + # Check if we've reached the end_angle (handling wrap-around) (current_angle + step_size) % 360 == end_angle or + if current_angle % 360 == end_angle: + break + + # Increment the current angle by the step size + current_angle += step_size + if current_angle >= 360: + current_angle -= 360 + + return [angles, coordinates] + +def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, + Babs:float, startangle:float, endangle:float, angle_stepsize:float, + Settings:str, clockwise=True, base_file_name='', zerowhenfin_bool=False)->None: + # TODO: update docs + """Rotation of the b-field in discrete steps, spectrum is measured at each discrete step in the rotation. Scan angle is + defined as the angle between the x-axis and the current B-field vector, i.e., in the anticlockwise direction. + + Args: + instr1 (pyvisa.resources.Resource): _description_ + instr2 (pyvisa.resources.Resource): _description_ + Babs (float): absolute B-field value in T + startangle (float): start angle in degrees + endangle (float): end angle in degrees + angle_stepsize (float): angle step size in degrees + clockwise (bool): determines the direction of rotation of the B-field. Defaults to True. + zerowhenfin_bool (bool, optional): after finishing the rotation, both B-field components should be set to 0 T. Defaults to False. + """ + + # TODO: add logging to the script + + # defines the folder, in which the data from the spectrometer is temporarily stored in + temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/B_Field_Dump" + # temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" + + if base_file_name =='': + base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M') + + start_time = time.time() # start of the scan function + + startangle = startangle % 360 + endangle = endangle % 360 # ensures that the angles are within [0,360) + + idnstr1 = query_no_echo(instr1, '*IDN?') + idnstr2 = query_no_echo(instr2, '*IDN?') + + intensity_data = [] # To store data from each scan + cwd = os.getcwd() # save original directory + + # find which one is the dual power supply, then, ramp B_x to Babs value + if '2301034' in idnstr1: # serial no. the dual power supply + pass + elif '2101034' in idnstr2: + # swap instruments, instr 1 to be the dual power supply (^= x-axis) + instr1, instr2 = instr2, instr1 + + # save initial low and high sweep limits of each device, and set them back after the rotation + instr1_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + instr2_bsettings = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'UNITS?;LLIM?;ULIM?').split(';')) # deliver a 3 element tuple of tuples containing the set unit, llim and ulim + if instr1_bsettings[0][0] == 'T': + instr1_bsettings[1][0] = instr1_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr1_bsettings[2][0] = instr1_bsettings[2][0]*0.1 + if instr2_bsettings[0][0] == 'T': + instr2_bsettings[1][0] = instr2_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T + instr2_bsettings[2][0] = instr2_bsettings[2][0]*0.1 + + # initialise the sweep angle list as well as the sweep limits and directions for each instrument + instr1_lim, instr2_lim = 'LLIM', 'ULIM' + instr1_sweep, instr2_sweep = 'DOWN', 'UP' + + # create lists of angles and discrete Cartesian coordinates + angles, cartesian_coords = generate_angle_coord_list(Babs, startangle, endangle, angle_stepsize, clockwise=clockwise) + + if clockwise: # NOTE: old conditional was: startangle > endangle see if this works.... + # reverse sweep limits and directions for the clockwise rotation + instr1_lim, instr2_lim = instr2_lim, instr1_lim + instr1_sweep, instr2_sweep = instr2_sweep, instr1_sweep + + + # TODO: i dont think we need to change the rates just yet, think about this later + ''' + # list of rates (with units) for diff ranges of each device, only up to Range 1 for single power supply as that is already + # the max recommended current. + init_range_lst1 = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'RATE? 0;RATE? 1;RATE? 2').split(';')) + init_range_lst2 = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'RATE? 0;RATE? 1').split(';')) + + min_range_lst = [min(el1[0], el2[0]) for el1,el2 in zip(init_range_lst1, init_range_lst2)] # min rates for each given range + + # set both devices to the min rates + write_no_echo(instr1, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + ''' + + + # TODO: see if this is the desired process: to always start from the x-axis ASK LUKAS + if Babs <= BX_MAX: + # write_no_echo(instr1, f'CHAN 2;ULIM {Babs*10};SWEEP UP') # sets to B_x, the B_x upper limit and sweeps the magnet field to the upper limit + print(f'SWITCHED TO BX, SWEEPING B-X TO {Babs} T NOW') + else: + raise ValueError(f'{Babs=}T value exceeds the max limit of the Bx field {BX_MAX}T!') + + # wait for Babs to be reached by the Bx field + actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') + while abs(actual_bval - Babs) > 0.0001: + time.sleep(5) # little break + actual_bval = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 + print(f'Actual magnet strength (Bx): {actual_bval} T,', f'Target magnet strength: {Babs} T') + actual_bval = Babs # NOTE: ONLY FOR TESTING; REMOVE THIS LINE IN ACTUAL USE + + + # TODO: copy and mod code to see if block logic works, test in lab + # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN + # Helper function that listens to a device + def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event): + while not all_targets_met_event.is_set(): # Loop until the event is set + # value = 0 # Simulate receiving a float from the device INSERT QUERY NO ECHO HERE TO ASK FOR DEVICE IMAG + if '2301034' in device_id: + value = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + if value <= target_value[device_id]: + # write_no_echo(instr1, f"CHAN 2;ULIM {target_value[device_id]*10};SWEEP UP") + print(f'sweeping Bx up to {target_value[device_id]}T') + else: + # write_no_echo(instr1, "CHAN 2;LLIM {target_value[device_id]*10};SWEEP DOWN") + print(f'sweeping Bx down to {target_value[device_id]}T') + value = target_value['2301034'] # NOTE: ONLY FOR TESTING; REMOVE IN REAL USE + time.sleep(6) + + elif '2101014' in device_id: + value = sep_num_from_units(query_no_echo(instr2, 'IMAG?'))[0]*0.1 # convert kG to T + if value <= target_value[device_id]: + # write_no_echo(instr2, f"ULIM {target_value[device_id]*10};SWEEP UP") + print(f'sweeping By up to {target_value[device_id]}T') + else: + # write_no_echo(instr2, "LLIM {target_value[device_id]*10};SWEEP DOWN") + print(f'sweeping By down to {target_value[device_id]}T') + value = target_value['2101014'] # NOTE: ONLY FOR TESTING; REMOVE IN REAL USE + time.sleep(3) + + else: + continue # Skip if device ID is not recognized + print(f"Device {device_id} reports value: {value} T") + + # time.sleep(2) + + with lock: + shared_values[device_id] = value + # Check if both devices have met their targets + if all(shared_values.get(device) is not None and abs(value - target_value[device]) <= 0.0001 + for device,value in shared_values.items()): + print(f"Both devices reached their target values: {shared_values}") + all_targets_met_event.set() # Signal that both targets are met + + # time.sleep(1) # Simulate periodic data checking + + # Main function to manage threads and iterate over target values + def monitor_devices(device_target_values, angles_lst, intensity_data=intensity_data): + for iteration, target in enumerate(device_target_values): + print(f"\nStarting iteration {iteration+1} for target values: {target}") + # Shared dictionary to store values from devices + shared_values = {device: None for device in target.keys()} + # Event to signal when both target values are reached + all_targets_met_event = threading.Event() + + # Lock to synchronize access to shared_values + lock = threading.Lock() + + # Create and start threads for each device + threads = [] + for device_id in target.keys(): + thread = threading.Thread(target=listen_to_device, args=(device_id, target, shared_values, lock, all_targets_met_event)) + threads.append(thread) + thread.start() + print(f"======================\nThread started for device {device_id}\n======================") + + # Wait until both devices meet their target values + all_targets_met_event.wait() + print(f"Both target values for iteration {iteration+1} met. Performing action...") + # Clean up threads + for thread in threads: + thread.join() + print(f"Threads for iteration {iteration+1} closed.\n") + + + print(f'COLLECTING SPECTRUM FOR ANGLE {angles_lst[iteration]}°\n') + # Perform some action after both targets are met + # we acquire with the LF + # acquire_name_spe = f'{base_file_name}_{angles_lst[iteration]}°' # NOTE: save each intensity file with the given angle + # AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + # read the .spe file and get the data as loaded_files + # cwd = os.getcwd() # save original directory + # os.chdir(temp_folder_path) #change directory + # loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + # os.chdir(cwd) # go back to original directory + + # Delete the created .spe file from acquiring after getting necessary info + # spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') + # os.remove(spe_file_path) + + points_left = len(angles) - iteration - 1 + + print('Points left in the scan: ', points_left) + + #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + # intensity_data.append(loaded_files.data[0][0][0]) + + #prints total time the mapping lasted + end_time = time.time() + elapsed_time = (end_time - start_time) / 60 + print('Scan time: ', elapsed_time, 'minutes') + + # reset both devices to original sweep limits + write_no_echo(instr1, f'LLIM {instr1_bsettings[1][0]*10};ULIM {instr1_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'LLIM {instr2_bsettings[1][0]*10};ULIM {instr2_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + + + # TODO: uncomment later if resetting original rates implemented + ''' + # reset both devices' initial rates for each range + write_no_echo(instr1, f'RANGE 0 {init_range_lst1[0][0]};RANGE 1 {init_range_lst1[1][0]};RANGE 2 {init_range_lst1[2][0]}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'RANGE 0 {init_range_lst2[0][0]};RANGE 1 {init_range_lst2[1][0]}') # reset the initial limits of the device after the scan + ''' + + + if zerowhenfin_bool: + # write_no_echo(instr1, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above + # write_no_echo(instr2, 'SWEEP ZERO') + print('======================\nSWEEPING BOTH DEVICES TO ZERO NOW\n======================') + + #save intensity & WL data as .txt + os.chdir('C:/Users/localadmin/Desktop/Users/Ryan') + # creates new folder for MAP data + # new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + # os.mkdir(new_folder_name) + # Here the things will be saved in a new folder under user Lukas ! + # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! + # os.chdir('C:/Users/localadmin/Desktop/Users/Ryan/'+ new_folder_name) + + # intensity_data = np.array(intensity_data) + # np.savetxt(Settings + f'{angles[0]}°_to_{angles[-1]}°' + experiment_name +'.txt', intensity_data) + # TODO: remove/edit experiment_name in line above, as well in sweep_b_val func, rn takes a global variable below + + # wl = np.array(loaded_files.wavelength) + # np.savetxt("Wavelength.txt", wl) + + # NOTE: data struct of device_target_values is a list of dictionaries, where each dictionary contains the target values for each device + device_target_values = [{'2301034': bval[0], '2101014': bval[1]} for bval in cartesian_coords] + + # call the helper function to carry out the rotation/measurement of spectrum + monitor_devices(device_target_values, angles, intensity_data) + + +################################################################# END OF FUNCTION DEFS ########################################################################################### + +# NOTE: RYAN INTRODUCED SOME FUNCTIONS HERE TO PERFORM THE SCAN + +# Initialise PYVISA ResourceManager +rm = pyvisa.ResourceManager() +# print(rm.list_resources()) +# 'ASRL8::INSTR' for dual power supply, 'ASRL9::INSTR' for single power supply (online PC) +# 'ASRL10::INSTR' for dual power supply, 'ASRL12::INSTR' for single power supply (offline PC) + +try: + # Open the connection with the APS100 dual power supply + powerbox_dualsupply = rm.open_resource('ASRL10::INSTR', + baud_rate=9600, + data_bits=8, + parity= pyvisa.constants.Parity.none, + stop_bits= pyvisa.constants.StopBits.one, + timeout=10000)# 5000 ms timeout + write_no_echo(powerbox_dualsupply, 'REMOTE') # turn on the remote mode + + # # select axis for the dual supply, either z-axis(CHAN 1 ^= Supply A) or x-axis(CHAN 2 ^= Supply B) + write_no_echo(powerbox_dualsupply, 'CHAN 2') + # # #for dual until here + + # Open the connection with the APS100 single power supply + powerbox_singlesupply = rm.open_resource('ASRL12::INSTR', + baud_rate=9600, + data_bits=8, + parity= pyvisa.constants.Parity.none, + stop_bits= pyvisa.constants.StopBits.one, + timeout=10000)# 5000 ms timeout + write_no_echo(powerbox_singlesupply, 'REMOTE') # turn on the remote mode + #for single until here + # TODO: uncomment AMC connection code later, when moving the probe in cryostat is needed. + # Setup connection to AMC + # amc = AMC.Device(IP) + # amc.connect() + + # # Internally, axes are numbered 0 to 2 + # amc.control.setControlOutput(0, True) + # amc.control.setControlOutput(1, True) + + + # auto = Automation(True, List[String]()) + # experiment = auto.LightFieldApplication.Experiment + # acquireCompleted = AutoResetEvent(False) + + # experiment.Load("2025_03_28_Priyanka_CrSBr_DR_Sweep") + # experiment.ExperimentCompleted += experiment_completed # we are hooking a listener. + # experiment.SetValue(SpectrometerSettings.GratingSelected, '[750nm,1200][0][0]') + # InitializerFilenameParams() + + + #set scan range and resolution in nanometers + range_x = 20000 + range_y = 20000 + resolution = 1000 + # set B-field scan range and resolution (all in T) + set_llim_bval = -0.3 + set_ulim_bval = 0.3 + set_res_bval = 0.003 + + #Here you can specify the filename of the map e.g. put experiment type, exposure time, used filters, etc.... + # 'PL_SP_700_LP_700_HeNe_52muW_exp_2s_Start_' + # experiment_settings = 'PL_X_1859.2_Y_3918.3_HeNe_10.4muW_H_a-axis_LP_SP_650_exp_180s_600g_cwl_930_det_b-axis_Pol_90_l2_45' + experiment_settings = 'DR_white_6th spot_Power_G600_exp_25s_l1_40_l2_262_det_b_mag_b' + #The program adds the range of the scan as well as the resolution and the date and time of the measurement + # f"{set_llim_bval}T_to_{set_ulim_bval}T_{set_res_bval}T_{datetime.datetime.now().strftime('%Y_%m_%d_%H%M')}" + experiment_name = f"{set_llim_bval}T_to_{set_ulim_bval}T_stepsize_{set_res_bval}T" + + # this moves the probe in xy-direction and measures spectrum there + # move_scan_xy(range_x, range_y, resolution, experiment_settings, experiment_name) + + # ramp_b_val(powerbox_singlesupply, 0, 'y-axis') + # ramp_b_val(powerbox_dualsupply, 0, 'z-axis') + + + # for single/ dual replace and vice versa all the way down + # sweep_b_val(powerbox_singlesupply, set_llim_bval, set_ulim_bval, set_res_bval, 'y-axis', + # experiment_settings, experiment_name, zerowhenfin_bool=True, reversescan_bool=False, loopscan_bool=True) + b_field_rotation(powerbox_dualsupply, powerbox_singlesupply, Babs=0.1, startangle=0, endangle=3, + angle_stepsize=1, Settings=experiment_settings, zerowhenfin_bool=True + ) + + write_no_echo(powerbox_dualsupply, 'LOCAL') # turn off the remote mode + write_no_echo(powerbox_singlesupply, 'LOCAL') # turn off the remote mode + + time.sleep(0.5) + # powerbox_dualsupply.close() + powerbox_singlesupply.close() + +except Exception as e: + print(e) + # Internally, axes are numbered 0 to 2 + + write_no_echo(powerbox_dualsupply, 'LOCAL') # turn off the remote mode + write_no_echo(powerbox_singlesupply, 'LOCAL') # turn off the remote mode + + time.sleep(0.5) + powerbox_dualsupply.close() + powerbox_singlesupply.close() \ No newline at end of file -- 2.39.5 From 14d59a639b96ec199aec6e6bb0d700dbc9464744 Mon Sep 17 00:00:00 2001 From: ryantan Date: Wed, 16 Apr 2025 15:19:20 +0200 Subject: [PATCH 34/39] implemented test package, will use it later on . --- Mag_Field_Sweep_2025_04_15.py | 1 + Test.py | 3 +++ magnet_modules/__init__.py | 1 + .../__pycache__/__init__.cpython-311.pyc | Bin 0 -> 223 bytes .../__pycache__/sweep_functions.cpython-311.pyc | Bin 0 -> 424 bytes magnet_modules/sweep_functions.py | 2 ++ 6 files changed, 7 insertions(+) create mode 100644 magnet_modules/__init__.py create mode 100644 magnet_modules/__pycache__/__init__.cpython-311.pyc create mode 100644 magnet_modules/__pycache__/sweep_functions.cpython-311.pyc create mode 100644 magnet_modules/sweep_functions.py diff --git a/Mag_Field_Sweep_2025_04_15.py b/Mag_Field_Sweep_2025_04_15.py index 2ddfe69..5a09175 100644 --- a/Mag_Field_Sweep_2025_04_15.py +++ b/Mag_Field_Sweep_2025_04_15.py @@ -1063,6 +1063,7 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso # TODO: see later parts of b_field_rotation from line 820 onwards, and see if same logic can be applied here # acquire coordinates along the fixed axis, threading, sweep both supplies till desired value (with lock) # then set event, measure, on with the next iteration, just like in b-field-rotation + cartesian_coords = generate_coord_list_fixed_angle(angle, ) ################################################################# END OF FUNCTION DEFS ########################################################################################### diff --git a/Test.py b/Test.py index 33b9349..89224d2 100644 --- a/Test.py +++ b/Test.py @@ -1,4 +1,7 @@ import math +from magnet_modules import sweep_functions as sf + +# sf.test_func() def generate_angle_coord_list(radius, start_angle, end_angle, step_size, clockwise=True): # TODO: DOCS diff --git a/magnet_modules/__init__.py b/magnet_modules/__init__.py new file mode 100644 index 0000000..991aa1a --- /dev/null +++ b/magnet_modules/__init__.py @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/magnet_modules/__pycache__/__init__.cpython-311.pyc b/magnet_modules/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eccc9f21bcc7f746f435b06d544b35ccb036c572 GIT binary patch literal 223 zcmZ3^%ge<81bf%~PiFzrk3k$5V1zP0vjG{?8B!R688jLFRx%VZ0r{UnlD~?Qtztrp zQ;UjYib@jm3S(UIlS^|`^Gb?if=fzMGD~w~!ZU+YjZBP8V|){fOHzwMGE$2(i({ON zD)Wm=5=)$P-7-^iQhZYri%W}AK{|tzi!uvJVsaDH^HNLVbMsS5b5e_A;^Q;(GE3s) k^$IF~ao9ja?TT1|P5?Qwm>)=dU}j`w{J;PsikN|70CQbGoB#j- literal 0 HcmV?d00001 diff --git a/magnet_modules/__pycache__/sweep_functions.cpython-311.pyc b/magnet_modules/__pycache__/sweep_functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4d198abda9f17238019460c1c366d67a0d5f505 GIT binary patch literal 424 zcmZWku}T9$5Zz5Kngml@2y%j8uFxWA6U0KrE@@5?WFZ{4n`Ghc_MF`##LB{d$R9*R z{Few;0V{tXkS>kRo;e$b-I@1h=FQGNHyU+(<4 zz?>gmNfGgm2y_O*D*X^-YFHc$5@C9=;#nj#(<33$o?XF6mFS~%Jg?cU@)T_1D)uLO z8{H%MbZWEu!MoG^aGJB?Km}`EkLJzbAjvbZfoN4d{e9>Rsz~!uy9gF#O6j6Rskb2i HU9SHD5_xJy literal 0 HcmV?d00001 diff --git a/magnet_modules/sweep_functions.py b/magnet_modules/sweep_functions.py new file mode 100644 index 0000000..f6b9361 --- /dev/null +++ b/magnet_modules/sweep_functions.py @@ -0,0 +1,2 @@ +def test_func(): + print('hello world! from test func') \ No newline at end of file -- 2.39.5 From a0c46cbcd0157df7c79c9cb9b053baa438afbe96 Mon Sep 17 00:00:00 2001 From: ryantan Date: Wed, 16 Apr 2025 15:49:40 +0200 Subject: [PATCH 35/39] copied logic block from b_rot, need to modify helper functions to suit the scan, see sweep_b_val for ideas --- Mag_Field_Sweep_2025_04_15.py | 147 +++++++++++++++++++++++++++++++++- 1 file changed, 146 insertions(+), 1 deletion(-) diff --git a/Mag_Field_Sweep_2025_04_15.py b/Mag_Field_Sweep_2025_04_15.py index 5a09175..1d6e42c 100644 --- a/Mag_Field_Sweep_2025_04_15.py +++ b/Mag_Field_Sweep_2025_04_15.py @@ -1021,6 +1021,10 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso Settings:str, clockwise=True, base_file_name='', reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False): + # check if the given limits exceed the max limits of the device + if (abs(min_bval) > min(BX_MAX, BY_MAX)) or (abs(max_bval) > min(BX_MAX, BY_MAX)): + raise ValueError(f'{min_bval=}T or {max_bval=}T value exceeds the max limit of the Bx or By field!') + # defines the folder, in which the data from the spectrometer is temporarily stored in temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/B_Field_Dump" # temp_folder_path = "C:/Users/localadmin/Desktop/Users/Lukas/2024_02_08_Map_test" @@ -1064,7 +1068,148 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso # acquire coordinates along the fixed axis, threading, sweep both supplies till desired value (with lock) # then set event, measure, on with the next iteration, just like in b-field-rotation - cartesian_coords = generate_coord_list_fixed_angle(angle, ) + cartesian_coords = generate_coord_list_fixed_angle(angle, min_bval, max_bval, res, reverse=reversescan_bool) + + # TODO: i dont think we need to change the rates just yet, think about this later + ''' + # list of rates (with units) for diff ranges of each device, only up to Range 1 for single power supply as that is already + # the max recommended current. + init_range_lst1 = list(sep_num_from_units(el) for el in query_no_echo(instr1, 'RATE? 0;RATE? 1;RATE? 2').split(';')) + init_range_lst2 = list(sep_num_from_units(el) for el in query_no_echo(instr2, 'RATE? 0;RATE? 1').split(';')) + + min_range_lst = [min(el1[0], el2[0]) for el1,el2 in zip(init_range_lst1, init_range_lst2)] # min rates for each given range + + # set both devices to the min rates + write_no_echo(instr1, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') + ''' + + # TODO: mod copied code (from b_field_rotation) forsweep_b_angle + # NEED TO MOD THE LOGIC OF LISTEN-TO-DEVICE TO SWEEP FROM LOWER TO HIGHER ANGLES, SEE SWEEP_B_VAL FUNCTION + + # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN + # Helper function that listens to a device + def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event): + while not all_targets_met_event.is_set(): # Loop until the event is set + # value = 0 # Simulate receiving a float from the device INSERT QUERY NO ECHO HERE TO ASK FOR DEVICE IMAG + if '2301034' in device_id: + value = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T + if value <= target_value[device_id]: + write_no_echo(instr1, f"CHAN 2;ULIM {target_value[device_id]*10};SWEEP UP") + else: + write_no_echo(instr1, "CHAN 2;LLIM {target_value[device_id]*10};SWEEP DOWN") + + elif '2101014' in device_id: + value = sep_num_from_units(query_no_echo(instr2, 'IMAG?'))[0]*0.1 # convert kG to T + if value <= target_value[device_id]: + write_no_echo(instr2, f"ULIM {target_value[device_id]*10};SWEEP UP") + else: + write_no_echo(instr2, "LLIM {target_value[device_id]*10};SWEEP DOWN") + else: + continue # Skip if device ID is not recognized + print(f"Device {device_id} reports value: {value} T") + + with lock: + shared_values[device_id] = value + # Check if both devices have met their targets + if all(shared_values.get(device) is not None and abs(value - target_value[device]) <= 0.0001 + for device,value in shared_values.items()): + print(f"Both devices reached their target values: {shared_values}") + all_targets_met_event.set() # Signal that both targets are met + + # time.sleep(1) # Simulate periodic data checking + + # Main function to manage threads and iterate over target values + def monitor_devices(device_target_values, angle, intensity_data=intensity_data): + for iteration, target in enumerate(device_target_values): + print(f"\nStarting iteration {iteration+1} for target values: {target}") + # Shared dictionary to store values from devices + shared_values = {device: None for device in target.keys()} + # Event to signal when both target values are reached + all_targets_met_event = threading.Event() + + # Lock to synchronize access to shared_values + lock = threading.Lock() + + # Create and start threads for each device + threads = [] + for device_id in target.keys(): + thread = threading.Thread(target=listen_to_device, args=(device_id, target, shared_values, lock, all_targets_met_event)) + threads.append(thread) + thread.start() + + # Wait until both devices meet their target values + all_targets_met_event.wait() + print(f"Both target values for iteration {iteration+1} met. Performing action...") + # Clean up threads + for thread in threads: + thread.join() + print(f"Threads for iteration {iteration+1} closed.\n") + + # Perform some action after both targets are met + # we acquire with the LF + acquire_name_spe = f'{base_file_name}_{angle}°' # NOTE: save each intensity file with the given angle + AcquireAndLock(acquire_name_spe) #this creates a .spe file with the scan name. + + # read the .spe file and get the data as loaded_files + cwd = os.getcwd() # save original directory + os.chdir(temp_folder_path) #change directory + loaded_files = sl.load_from_files([acquire_name_spe + '.spe']) # get the .spe file as a variable + os.chdir(cwd) # go back to original directory + + # Delete the created .spe file from acquiring after getting necessary info + spe_file_path = os.path.join(temp_folder_path, acquire_name_spe + '.spe') + os.remove(spe_file_path) + + points_left = len(angle) - iteration - 1 + print('Points left in the scan: ', points_left) + + #append the intensity data as it is (so after every #of_wl_points, the spectrum of the next point begins) + intensity_data.append(loaded_files.data[0][0][0]) + + #prints total time the mapping lasted + end_time = time.time() + elapsed_time = (end_time - start_time) / 60 + print('Scan time: ', elapsed_time, 'minutes') + + # reset both devices to original sweep limits + write_no_echo(instr1, f'LLIM {instr1_bsettings[1][0]*10};ULIM {instr1_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'LLIM {instr2_bsettings[1][0]*10};ULIM {instr2_bsettings[2][0]*10}') # reset the initial limits of the device after the scan + + + # TODO: uncomment later if resetting original rates implemented + ''' + # reset both devices' initial rates for each range + write_no_echo(instr1, f'RANGE 0 {init_range_lst1[0][0]};RANGE 1 {init_range_lst1[1][0]};RANGE 2 {init_range_lst1[2][0]}') # reset the initial limits of the device after the scan + write_no_echo(instr2, f'RANGE 0 {init_range_lst2[0][0]};RANGE 1 {init_range_lst2[1][0]}') # reset the initial limits of the device after the scan + ''' + + + if zerowhenfin_bool: + write_no_echo(instr1, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above + write_no_echo(instr2, 'SWEEP ZERO') + + #save intensity & WL data as .txt + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas') + # creates new folder for MAP data + new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" + os.mkdir(new_folder_name) + # Here the things will be saved in a new folder under user Lukas ! + # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! + os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name) + + intensity_data = np.array(intensity_data) + np.savetxt(Settings + f'{angle}°' + experiment_name +'.txt', intensity_data) + # TODO: remove/edit experiment_name in line above, as well in sweep_b_val func, rn takes a global variable below + + wl = np.array(loaded_files.wavelength) + np.savetxt("Wavelength.txt", wl) + + # NOTE: data struct of device_target_values is a list of dictionaries, where each dictionary contains the target values for each device + device_target_values = [{'2301034': bval[0], '2101014': bval[1]} for bval in cartesian_coords] + + # call the helper function to carry out the rotation/measurement of spectrum + monitor_devices(device_target_values, angle, intensity_data) ################################################################# END OF FUNCTION DEFS ########################################################################################### -- 2.39.5 From 0e0572502c9126f303286fdee8b55d6337095deb Mon Sep 17 00:00:00 2001 From: ryantan Date: Wed, 23 Apr 2025 11:52:44 +0200 Subject: [PATCH 36/39] modded listen_to_device in sweep_b_angle, should work --- Mag_Field_Sweep_2025_04_15.py | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/Mag_Field_Sweep_2025_04_15.py b/Mag_Field_Sweep_2025_04_15.py index 1d6e42c..fdbcc63 100644 --- a/Mag_Field_Sweep_2025_04_15.py +++ b/Mag_Field_Sweep_2025_04_15.py @@ -898,14 +898,14 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R if value <= target_value[device_id]: write_no_echo(instr1, f"CHAN 2;ULIM {target_value[device_id]*10};SWEEP UP") else: - write_no_echo(instr1, "CHAN 2;LLIM {target_value[device_id]*10};SWEEP DOWN") + write_no_echo(instr1, f"CHAN 2;LLIM {target_value[device_id]*10};SWEEP DOWN") elif '2101014' in device_id: value = sep_num_from_units(query_no_echo(instr2, 'IMAG?'))[0]*0.1 # convert kG to T if value <= target_value[device_id]: write_no_echo(instr2, f"ULIM {target_value[device_id]*10};SWEEP UP") else: - write_no_echo(instr2, "LLIM {target_value[device_id]*10};SWEEP DOWN") + write_no_echo(instr2, f"LLIM {target_value[device_id]*10};SWEEP DOWN") else: continue # Skip if device ID is not recognized print(f"Device {device_id} reports value: {value} T") @@ -1085,7 +1085,8 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso ''' # TODO: mod copied code (from b_field_rotation) forsweep_b_angle - # NEED TO MOD THE LOGIC OF LISTEN-TO-DEVICE TO SWEEP FROM LOWER TO HIGHER ANGLES, SEE SWEEP_B_VAL FUNCTION + # NEED TO MOD THE LOGIC OF listen_to_device FUNCTION LOGIC + # TO SWEEP FROM LOWER TO HIGHER ANGLES, SEE SWEEP_B_VAL FUNCTION # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN # Helper function that listens to a device @@ -1094,17 +1095,25 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso # value = 0 # Simulate receiving a float from the device INSERT QUERY NO ECHO HERE TO ASK FOR DEVICE IMAG if '2301034' in device_id: value = sep_num_from_units(query_no_echo(instr1, 'IMAG?'))[0]*0.1 # convert kG to T - if value <= target_value[device_id]: - write_no_echo(instr1, f"CHAN 2;ULIM {target_value[device_id]*10};SWEEP UP") - else: - write_no_echo(instr1, "CHAN 2;LLIM {target_value[device_id]*10};SWEEP DOWN") + # New code: + sweep_limit = "ULIM" if not reversescan_bool else "LLIM" + write_no_echo(instr1, f"CHAN 2;{sweep_limit} {target_value[device_id]*10};SWEEP {'UP' if sweep_limit == 'ULIM' else 'DOWN'}") + # Old code + # if value <= target_value[device_id]: + # write_no_echo(instr1, f"CHAN 2;ULIM {target_value[device_id]*10};SWEEP UP") + # else: + # write_no_echo(instr1, f"CHAN 2;LLIM {target_value[device_id]*10};SWEEP DOWN") elif '2101014' in device_id: value = sep_num_from_units(query_no_echo(instr2, 'IMAG?'))[0]*0.1 # convert kG to T - if value <= target_value[device_id]: - write_no_echo(instr2, f"ULIM {target_value[device_id]*10};SWEEP UP") - else: - write_no_echo(instr2, "LLIM {target_value[device_id]*10};SWEEP DOWN") + # New code + sweep_limit = "ULIM" if not reversescan_bool else "LLIM" + write_no_echo(instr1, f"{sweep_limit} {target_value[device_id]*10};SWEEP {'UP' if sweep_limit == 'ULIM' else 'DOWN'}") + # Old code + # if value <= target_value[device_id]: + # write_no_echo(instr2, f"ULIM {target_value[device_id]*10};SWEEP UP") + # else: + # write_no_echo(instr2, f"LLIM {target_value[device_id]*10};SWEEP DOWN") else: continue # Skip if device ID is not recognized print(f"Device {device_id} reports value: {value} T") -- 2.39.5 From 510857d3f2d87fe0617ea667f68a590e77510e09 Mon Sep 17 00:00:00 2001 From: ryantan Date: Wed, 23 Apr 2025 12:11:03 +0200 Subject: [PATCH 37/39] added the AMC module --- AMC.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 AMC.py diff --git a/AMC.py b/AMC.py new file mode 100644 index 0000000..97c64b2 --- /dev/null +++ b/AMC.py @@ -0,0 +1,44 @@ +import ACS +from about import About +from access import Access +from amcids import Amcids +from control import Control +from description import Description +from diagnostic import Diagnostic +from functions import Functions +from move import Move +from network import Network +from res import Res +from rotcomp import Rotcomp +from rtin import Rtin +from rtout import Rtout +from status import Status +from system_service import System_service +from update import Update + + +class Device(ACS.Device): + + def __init__ (self, address): + + super().__init__(address) + + self.about = About(self) + self.access = Access(self) + self.amcids = Amcids(self) + self.control = Control(self) + self.description = Description(self) + self.diagnostic = Diagnostic(self) + self.functions = Functions(self) + self.move = Move(self) + self.network = Network(self) + self.res = Res(self) + self.rotcomp = Rotcomp(self) + self.rtin = Rtin(self) + self.rtout = Rtout(self) + self.status = Status(self) + self.system_service = System_service(self) + self.update = Update(self) + +def discover(): + return Device.discover("amc") \ No newline at end of file -- 2.39.5 From f89e543beb06f389a1970e0a894bc12f2f3b10dc Mon Sep 17 00:00:00 2001 From: ryantan Date: Wed, 23 Apr 2025 14:05:04 +0200 Subject: [PATCH 38/39] implemented basic logging helper functions for the rotation and angle sweep functions --- Mag_Field_Sweep_2025_04_15.py | 18 ++++----- Test2.py | 39 +++++++++++++++++++ .../2025-04-23_14-03.txt | 6 +++ 3 files changed, 52 insertions(+), 11 deletions(-) create mode 100644 Test2.py create mode 100644 Test_Map_2025_04_23_14.03/2025-04-23_14-03.txt diff --git a/Mag_Field_Sweep_2025_04_15.py b/Mag_Field_Sweep_2025_04_15.py index fdbcc63..2ce020c 100644 --- a/Mag_Field_Sweep_2025_04_15.py +++ b/Mag_Field_Sweep_2025_04_15.py @@ -1012,14 +1012,12 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R # call the helper function to carry out the rotation/measurement of spectrum monitor_devices(device_target_values, angles, intensity_data) -# TODO: implement b_sweep at an arbitrary angle in the Bx-By plane -# copy the functionality of loading the powerboxsupplies from b_rotation and the other sweep functionalities of -# b_sweep_val and implement it in this function -# CHECK: B_abs <= BX_MAX or BY_MAX + def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource, min_bval:float, max_bval:float, res:float, angle:float, Settings:str, clockwise=True, base_file_name='', - reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False): + reversescan_bool=False, zerowhenfin_bool=False, loopscan_bool=False, + log_folder_path:str=""): # check if the given limits exceed the max limits of the device if (abs(min_bval) > min(BX_MAX, BY_MAX)) or (abs(max_bval) > min(BX_MAX, BY_MAX)): @@ -1060,9 +1058,10 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso instr2_bsettings[1][0] = instr2_bsettings[1][0]*0.1 # rescale kG to T, device accepts values only in kG or A, eventho we set it to T instr2_bsettings[2][0] = instr2_bsettings[2][0]*0.1 - # initialise the sweep angle list as well as the sweep limits and directions for each instrument - instr1_lim, instr2_lim = 'LLIM', 'ULIM' - instr1_sweep, instr2_sweep = 'DOWN', 'UP' + # NOTE: this code block unused, remove later + # # initialise the sweep angle list as well as the sweep limits and directions for each instrument + # instr1_lim, instr2_lim = 'LLIM', 'ULIM' + # instr1_sweep, instr2_sweep = 'DOWN', 'UP' # TODO: see later parts of b_field_rotation from line 820 onwards, and see if same logic can be applied here # acquire coordinates along the fixed axis, threading, sweep both supplies till desired value (with lock) @@ -1084,9 +1083,6 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso write_no_echo(instr2, f'RATE 0 {min_range_lst[0]};RATE 1 {min_range_lst[1]}') ''' - # TODO: mod copied code (from b_field_rotation) forsweep_b_angle - # NEED TO MOD THE LOGIC OF listen_to_device FUNCTION LOGIC - # TO SWEEP FROM LOWER TO HIGHER ANGLES, SEE SWEEP_B_VAL FUNCTION # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN # Helper function that listens to a device diff --git a/Test2.py b/Test2.py new file mode 100644 index 0000000..a761b1e --- /dev/null +++ b/Test2.py @@ -0,0 +1,39 @@ +import os +import datetime + +# List to accumulate measurement data +measurement_data = [] + +def append_measurement(target_b_abs, b_x, b_y, measurement_data=measurement_data): + """Append a single measurement to the global list.""" + measurement = { + "Target B_abs": target_b_abs, + "Datetime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "B_x": b_x, + "B_y": b_y + } + measurement_data.append(measurement) + +def save_measurements_to_file(relative_directory, measurement_data=measurement_data): + """Save accumulated measurements to a file in the specified directory.""" + script_dir = os.path.dirname(os.path.abspath(__file__)) + directory = os.path.join(script_dir, relative_directory) + os.makedirs(directory, exist_ok=True) + + filename = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M") + ".txt" + file_path = os.path.join(directory, filename) + + # Write header and data + with open(file_path, 'w') as f: + f.write("Target B_abs, Datetime, B_x, B_y\n") + for entry in measurement_data: + line = f"{entry['Target B_abs']}, {entry['Datetime']}, {entry['B_x']}, {entry['B_y']}\n" + f.write(line) + +# Example usage +for i in range(5): + append_measurement(target_b_abs=0.5 + i, b_x=1.0 * i, b_y=2.0 * i) + +save_measurements_to_file("Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}") + +# print(datetime.datetime.now()) diff --git a/Test_Map_2025_04_23_14.03/2025-04-23_14-03.txt b/Test_Map_2025_04_23_14.03/2025-04-23_14-03.txt new file mode 100644 index 0000000..24f3318 --- /dev/null +++ b/Test_Map_2025_04_23_14.03/2025-04-23_14-03.txt @@ -0,0 +1,6 @@ +Target B_abs, Datetime, B_x, B_y +0.5, 2025-04-23 14:03:43, 0.0, 0.0 +1.5, 2025-04-23 14:03:43, 1.0, 2.0 +2.5, 2025-04-23 14:03:43, 2.0, 4.0 +3.5, 2025-04-23 14:03:43, 3.0, 6.0 +4.5, 2025-04-23 14:03:43, 4.0, 8.0 -- 2.39.5 From 8a76fac78885e215694a1b5302772f7ca84631f2 Mon Sep 17 00:00:00 2001 From: ryantan Date: Wed, 23 Apr 2025 15:43:46 +0200 Subject: [PATCH 39/39] implemented test logging functions for sweep_b_angle, included in sweep_b_angle. TODO: include in b_rotation --- Mag_Field_Sweep_2025_04_15.py | 51 +++++++++++++-- Test2.py | 29 +++++---- Test3.py | 62 +++++++++++++++++++ .../2025-04-23_14-03.txt | 6 -- 4 files changed, 126 insertions(+), 22 deletions(-) create mode 100644 Test3.py delete mode 100644 Test_Map_2025_04_23_14.03/2025-04-23_14-03.txt diff --git a/Mag_Field_Sweep_2025_04_15.py b/Mag_Field_Sweep_2025_04_15.py index 2ce020c..2789220 100644 --- a/Mag_Field_Sweep_2025_04_15.py +++ b/Mag_Field_Sweep_2025_04_15.py @@ -406,8 +406,39 @@ def ramp_b_val(instr:pyvisa.resources.Resource, bval:float, magnet_coil:str)->No print("Ramping Done!") helper_scan_func(bval) - - + + +# TODO: input logging functions here for the power supply. +def append_measurement(target_b_abs, target_angle, b_x, b_y, measurement_data): + """Append a single measurement to the global list.""" + measurement = { + "Target B_abs (T)": target_b_abs, + "Target Angle (deg)": target_angle, # insert target angle here + "Datetime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "B_x (T)": b_x, + "B_y (T)": b_y, + "Actual B_abs (T)": (b_x**2 + b_y**2)**0.5, + "Actual Angle (deg)": np.degrees(np.arctan2(b_y, b_x)) % 360, + } + measurement_data.append(measurement) + +def save_measurements_to_file(relative_directory, measurement_data, make_dir=False): + """Save accumulated measurements to a file in the specified directory.""" + script_dir = os.path.dirname(os.path.abspath(__file__)) + directory = os.path.join(script_dir, relative_directory) + if make_dir: + os.makedirs(directory, exist_ok=True) + + filename = "scanlog_" + datetime.datetime.now().strftime("%Y-%m-%d_%H-%M") + ".txt" + file_path = os.path.join(directory, filename) + + # Write header and data + with open(file_path, 'w') as f: + f.write("Target B_abs (T);Target Angle (deg);Datetime; B_x (T);B_y (T);Actual B_abs (T);Actual Angle (deg)\n") + for entry in measurement_data: + line = f"{entry['Target B_abs (T)']};{entry['Target Angle (deg)']};{entry['Datetime']};{entry['B_x (T)']};{entry['B_y (T)']};{entry['Actual B_abs (T)']};{entry['Actual Angle (deg)']}\n" + f.write(line) + # receive values in units of T, rescale in kg to talk with the power supplyy. 1T = 10kG # NOTE: removed singlepowersupply_bool, reading serial-nr. of the device instead. @@ -1086,7 +1117,7 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso # NOTE: implement PID control, possibly best option to manage the b field DO THIS LATER ON, WE DO DISCRETE B VALUES RN # Helper function that listens to a device - def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event): + def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event, measurement_data): while not all_targets_met_event.is_set(): # Loop until the event is set # value = 0 # Simulate receiving a float from the device INSERT QUERY NO ECHO HERE TO ASK FOR DEVICE IMAG if '2301034' in device_id: @@ -1116,6 +1147,8 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso with lock: shared_values[device_id] = value + append_measurement((target_value['2301034']**2 + target_value['2101014']**2)**0.5, angle, shared_values['2301034'], shared_values['2101014'], measurement_data) # append the bval to the measurement data + # Check if both devices have met their targets if all(shared_values.get(device) is not None and abs(value - target_value[device]) <= 0.0001 for device,value in shared_values.items()): @@ -1125,7 +1158,11 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso # time.sleep(1) # Simulate periodic data checking # Main function to manage threads and iterate over target values - def monitor_devices(device_target_values, angle, intensity_data=intensity_data): + def monitor_devices(device_target_values, angle, intensity_data=intensity_data): + + # initilise measurement list for b-val tracking + measurement_data = [] + for iteration, target in enumerate(device_target_values): print(f"\nStarting iteration {iteration+1} for target values: {target}") # Shared dictionary to store values from devices @@ -1139,7 +1176,7 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso # Create and start threads for each device threads = [] for device_id in target.keys(): - thread = threading.Thread(target=listen_to_device, args=(device_id, target, shared_values, lock, all_targets_met_event)) + thread = threading.Thread(target=listen_to_device, args=(device_id, target, shared_values, lock, all_targets_met_event, measurement_data)) threads.append(thread) thread.start() @@ -1199,6 +1236,10 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso # creates new folder for MAP data new_folder_name = "Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}" os.mkdir(new_folder_name) + + # NOTE: added log file to folder + save_measurements_to_file(new_folder_name, measurement_data, make_dir=False) + # Here the things will be saved in a new folder under user Lukas ! # IMPORTANT last / has to be there, otherwise data cannot be saved and will be lost!!!!!!!!!!!!!!!! os.chdir('C:/Users/localadmin/Desktop/Users/Lukas/'+ new_folder_name) diff --git a/Test2.py b/Test2.py index a761b1e..a0fb9b9 100644 --- a/Test2.py +++ b/Test2.py @@ -1,39 +1,46 @@ import os +import time import datetime +import numpy as np # List to accumulate measurement data measurement_data = [] -def append_measurement(target_b_abs, b_x, b_y, measurement_data=measurement_data): +def append_measurement(target_b_abs, b_x, b_y, measurement_data): """Append a single measurement to the global list.""" measurement = { - "Target B_abs": target_b_abs, + "Target B_abs (T)": target_b_abs, + "Target Angle (deg)": 90, # insert target angle here "Datetime": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), - "B_x": b_x, - "B_y": b_y + "B_x (T)": b_x, + "B_y (T)": b_y, + "Actual B_abs (T)": (b_x**2 + b_y**2)**0.5, + "Actual Angle (deg)": np.degrees(np.arctan2(b_y, b_x)) % 360, } measurement_data.append(measurement) -def save_measurements_to_file(relative_directory, measurement_data=measurement_data): +def save_measurements_to_file(relative_directory, measurement_data, make_dir=False): """Save accumulated measurements to a file in the specified directory.""" script_dir = os.path.dirname(os.path.abspath(__file__)) directory = os.path.join(script_dir, relative_directory) - os.makedirs(directory, exist_ok=True) + if make_dir: + os.makedirs(directory, exist_ok=True) filename = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M") + ".txt" file_path = os.path.join(directory, filename) # Write header and data with open(file_path, 'w') as f: - f.write("Target B_abs, Datetime, B_x, B_y\n") + f.write("Target B_abs (T);Target Angle (deg);Datetime; B_x (T);B_y (T);Actual B_abs (T);Actual Angle (deg)\n") for entry in measurement_data: - line = f"{entry['Target B_abs']}, {entry['Datetime']}, {entry['B_x']}, {entry['B_y']}\n" + line = f"{entry['Target B_abs (T)']};{entry['Target Angle (deg)']};{entry['Datetime']};{entry['B_x (T)']};{entry['B_y (T)']};{entry['Actual B_abs (T)']};{entry['Actual Angle (deg)']}\n" f.write(line) # Example usage for i in range(5): - append_measurement(target_b_abs=0.5 + i, b_x=1.0 * i, b_y=2.0 * i) - -save_measurements_to_file("Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}") + append_measurement(target_b_abs=0.5 + i, b_x=1.0 * i, b_y=2.0 * i, measurement_data=measurement_data) + time.sleep(1) # Simulate time delay between measurements +save_measurements_to_file("Test_Map_" + f"{datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')}", measurement_data, make_dir=False) +# print(9**0.5) # print(datetime.datetime.now()) diff --git a/Test3.py b/Test3.py new file mode 100644 index 0000000..3b66921 --- /dev/null +++ b/Test3.py @@ -0,0 +1,62 @@ +import os +import threading +from datetime import datetime +import time +import random + +# Shared list and lock +measurement_data = [] +data_lock = threading.Lock() + +def append_measurement(target_b_abs, b_x, b_y): + measurement = { + "Target B_abs": target_b_abs, + "Datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + "B_x": b_x, + "B_y": b_y + } + with data_lock: + measurement_data.append(measurement) + +def save_measurements_to_file(relative_directory): + script_dir = os.path.dirname(os.path.abspath(__file__)) + directory = os.path.join(script_dir, relative_directory) + os.makedirs(directory, exist_ok=True) + + filename = datetime.now().strftime("%Y-%m-%d_%H-%M") + ".txt" + file_path = os.path.join(directory, filename) + + header_keys = ["Target B_abs", "Datetime", "B_x", "B_y"] + + with data_lock: + with open(file_path, 'w') as f: + f.write(", ".join(header_keys) + "\n") + for entry in measurement_data: + line = ", ".join(str(entry[key]) for key in header_keys) + "\n" + f.write(line) + +# Thread function +def simulate_sensor_readings(sensor_id): + for i in range(3): + # Simulate some "sensor" data + target_b_abs = round(random.uniform(0.1, 1.0), 3) + b_x = round(random.uniform(-1.0, 1.0), 3) + b_y = round(random.uniform(-1.0, 1.0), 3) + + print(f"Sensor {sensor_id} appending: {target_b_abs}, {b_x}, {b_y}") + append_measurement(target_b_abs, b_x, b_y) + time.sleep(random.uniform(1,2)) # Simulate delay + +# Launch threads +thread1 = threading.Thread(target=simulate_sensor_readings, args=(1,)) +thread2 = threading.Thread(target=simulate_sensor_readings, args=(2,)) + +thread1.start() +thread2.start() + +thread1.join() +thread2.join() + +# Save all data at the end +save_measurements_to_file("TestDirectory") +print \ No newline at end of file diff --git a/Test_Map_2025_04_23_14.03/2025-04-23_14-03.txt b/Test_Map_2025_04_23_14.03/2025-04-23_14-03.txt deleted file mode 100644 index 24f3318..0000000 --- a/Test_Map_2025_04_23_14.03/2025-04-23_14-03.txt +++ /dev/null @@ -1,6 +0,0 @@ -Target B_abs, Datetime, B_x, B_y -0.5, 2025-04-23 14:03:43, 0.0, 0.0 -1.5, 2025-04-23 14:03:43, 1.0, 2.0 -2.5, 2025-04-23 14:03:43, 2.0, 4.0 -3.5, 2025-04-23 14:03:43, 3.0, 6.0 -4.5, 2025-04-23 14:03:43, 4.0, 8.0 -- 2.39.5