Compare commits
14 Commits
main
...
Serial-Nr,
Author | SHA1 | Date | |
---|---|---|---|
|
4450fd1e76 | ||
54a2948d0b | |||
080ce6b1e6 | |||
5c01110ce5 | |||
6efedda662 | |||
0c21e935ed | |||
4881f4de3d | |||
082f99aa0d | |||
0ecbfa12e7 | |||
a566dda4b0 | |||
87b8908a99 | |||
c859404a15 | |||
1ddd3e96a4 | |||
130fdfbab1 |
@ -7,6 +7,8 @@ Lightfield + Positioner
|
|||||||
############################################
|
############################################
|
||||||
# Packages from Ryan
|
# Packages from Ryan
|
||||||
import re
|
import re
|
||||||
|
import math
|
||||||
|
import threading
|
||||||
import pyvisa
|
import pyvisa
|
||||||
# from pyvisa import ResourceManager, constants
|
# from pyvisa import ResourceManager, constants
|
||||||
|
|
||||||
@ -31,6 +33,7 @@ from System import String
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
import datetime
|
import datetime
|
||||||
|
from typing import Union
|
||||||
|
|
||||||
|
|
||||||
#First choose your controller
|
#First choose your controller
|
||||||
@ -301,7 +304,8 @@ def sep_num_from_units(powerbox_output :str)->list:
|
|||||||
else:
|
else:
|
||||||
return [powerbox_output,]
|
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.
|
"""helper function for the Attocube APS100 that queries a function to the device, removing the echo.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@ -325,7 +329,8 @@ def query_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0.01)-
|
|||||||
print(f"Error communicating with instrument: {e}")
|
print(f"Error communicating with instrument: {e}")
|
||||||
return None
|
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.
|
"""helper function for the Attocube APS100 that writes a function to the device, removing the echo.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@ -351,19 +356,23 @@ def write_no_echo(instr:pyvisa.resources.Resource, command:str, sleeptime=0.01)-
|
|||||||
except pyvisa.VisaIOError as e:
|
except pyvisa.VisaIOError as e:
|
||||||
print(f"Error communicating with instrument: {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
|
# 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,
|
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='',
|
||||||
singlepowersupply_bool=False, reversescan_bool=False, zerowhenfin_bool=False)->None:
|
reversescan_bool=False, zerowhenfin_bool=False, loopscan_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
|
# TODO: update docs in the end
|
||||||
of the probe in the cryostat is made, using the LightField spectrometer.
|
""" 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:
|
Args:
|
||||||
instr (pyvisa.resources.Resource): chosen power supply device to connect to
|
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)
|
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)
|
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)
|
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.
|
Settings (str): experiment settings, included in file name.
|
||||||
base_file_name (str, optional): base file name. Defaults to ''.
|
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".
|
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".
|
||||||
@ -375,31 +384,73 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float,
|
|||||||
ValueError: when By limit is exceeded.
|
ValueError: when By limit is exceeded.
|
||||||
ValueError: when Bz limit is exceeded.
|
ValueError: when Bz limit is exceeded.
|
||||||
ValueError: when Bx 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!')
|
||||||
|
|
||||||
|
if path_save =='':
|
||||||
|
path_save = datetime.datetime.now().strftime("%Y_%m_%d_%H%M_hrs_")
|
||||||
|
|
||||||
if base_file_name =='':
|
if base_file_name =='':
|
||||||
base_file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H.%M')
|
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
|
||||||
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_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':
|
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[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
|
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 and (magnet_coil=='y-axis'): # single power supply
|
||||||
if (min_bval< -BY_MAX) or (max_bval > BY_MAX):
|
if (min_bval< -BY_MAX) or (max_bval > BY_MAX):
|
||||||
raise ValueError('Input limits exceed that of the magnet By! Please input smaller limits.')
|
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
|
elif '2301034' in instr_info: # dual power supply
|
||||||
if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX):
|
if magnet_coil=='z-axis': # check if its the coils for Bz
|
||||||
raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.')
|
if (min_bval < -BZ_MAX) or (max_bval > BZ_MAX):
|
||||||
else: # checks limits of Bx
|
raise ValueError('Input limits exceed that of the magnet (Bz)! Please input smaller limits.')
|
||||||
if (min_bval< -BX_MAX) or (max_bval > BX_MAX):
|
write_no_echo(instr, 'CHAN 1')
|
||||||
raise ValueError('Input limits exceed that of the magnet Bx! Please input smaller limits.')
|
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
|
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
|
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_lim, subsequent_lim = 'LLIM', 'ULIM'
|
||||||
init_sweep, subsequent_sweep = 'DOWN', 'UP'
|
init_sweep, subsequent_sweep = 'DOWN', 'UP'
|
||||||
@ -417,24 +468,19 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float,
|
|||||||
init_lim, subsequent_lim = subsequent_lim, init_lim
|
init_lim, subsequent_lim = subsequent_lim, init_lim
|
||||||
init_sweep, subsequent_sweep = subsequent_sweep, init_sweep
|
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)
|
total_points = len(bval_lst)
|
||||||
|
middle_index_bval_lst = total_points // 2
|
||||||
intensity_data = [] # To store data from each scan
|
intensity_data = [] # To store data from each scan
|
||||||
cwd = os.getcwd() # save original directory
|
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:
|
# NOTE: helper function for the scanning loop
|
||||||
# # if initial bval is equal to the element of the given iteration from the bval_lst, then commence measuring the spectrum
|
def helper_scan_func(idx, bval, instr=instr, init_lim=init_lim, init_sweep=init_sweep,
|
||||||
# pass
|
subsequent_lim=subsequent_lim, subsequent_sweep=subsequent_sweep, sleep=5):
|
||||||
# else:
|
if idx == 0: # for first iteration, sweep to one of the limits
|
||||||
|
|
||||||
# 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'{init_lim} {bval*10}') # convert back to kG
|
||||||
write_no_echo(instr, f'SWEEP {init_sweep}')
|
write_no_echo(instr, f'SWEEP {init_sweep}')
|
||||||
else:
|
else:
|
||||||
@ -449,6 +495,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
|
actual_bval = sep_num_from_units(query_no_echo(instr, 'IMAG?'))[0]*0.1
|
||||||
# update the actual bval
|
# update the actual bval
|
||||||
print(f'Actual magnet strength: {actual_bval} T,', f'Target magnet strength: {bval} T')
|
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)
|
time.sleep(5)
|
||||||
# we acquire with the LF
|
# we acquire with the LF
|
||||||
@ -476,6 +556,8 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float,
|
|||||||
elapsed_time = (end_time - start_time) / 60
|
elapsed_time = (end_time - start_time) / 60
|
||||||
print('Scan time: ', elapsed_time, 'minutes')
|
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:
|
if zerowhenfin_bool:
|
||||||
write_no_echo(instr, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above
|
write_no_echo(instr, 'SWEEP ZERO') # if switched on, discharges the magnet after performing the measurement loop above
|
||||||
|
|
||||||
@ -495,6 +577,277 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float,
|
|||||||
np.savetxt("Wavelength.txt", wl)
|
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, 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.
|
||||||
|
|
||||||
|
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??
|
||||||
|
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
|
||||||
|
|
||||||
|
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):
|
||||||
|
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")
|
||||||
|
|
||||||
|
#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)
|
||||||
|
|
||||||
|
|
||||||
################################################################# END OF FUNCTION DEFS ###########################################################################################
|
################################################################# END OF FUNCTION DEFS ###########################################################################################
|
||||||
|
|
||||||
@ -502,20 +855,33 @@ def sweep_b_val(instr:pyvisa.resources.Resource, min_bval:float, max_bval:float,
|
|||||||
|
|
||||||
# Initialise PYVISA ResourceManager
|
# Initialise PYVISA ResourceManager
|
||||||
rm = 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
|
# Open the connection with the APS100 dual power supply
|
||||||
powerbox_dualsupply = rm.open_resource('ASRL8::INSTR',
|
powerbox_dualsupply = rm.open_resource('ASRL10::INSTR',
|
||||||
baud_rate=9600, # Example baud rate, adjust as needed
|
baud_rate=9600,
|
||||||
data_bits=8,
|
data_bits=8,
|
||||||
parity= pyvisa.constants.Parity.none,
|
parity= pyvisa.constants.Parity.none,
|
||||||
stop_bits= pyvisa.constants.StopBits.one,
|
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_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)
|
# 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
|
# Setup connection to AMC
|
||||||
amc = AMC.Device(IP)
|
amc = AMC.Device(IP)
|
||||||
@ -550,21 +916,18 @@ 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
|
#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')}"
|
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
|
# this moves the probe in xy-direction and measures spectrum there
|
||||||
# move_scan_xy(range_x, range_y, resolution, experiment_settings, experiment_name)
|
# move_scan_xy(range_x, range_y, resolution, experiment_settings, experiment_name)
|
||||||
|
|
||||||
# perform the B-field measurement for selected axis above
|
# 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)
|
||||||
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, 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
|
# Internally, axes are numbered 0 to 2
|
||||||
|
|
||||||
write_no_echo(powerbox_dualsupply, 'LOCAL') # turn off the remote mode
|
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)
|
# time.sleep(0.5)
|
||||||
powerbox_dualsupply.close()
|
powerbox_dualsupply.close()
|
||||||
|
powerbox_singlesupply.close()
|
Loading…
Reference in New Issue
Block a user