implemented logging functionality in b_field_rotation

This commit is contained in:
ryantan 2025-04-24 10:30:42 +02:00
parent a08cf28117
commit 717cd5c687
2 changed files with 66 additions and 9 deletions

View File

@ -878,7 +878,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 = generate_angle_coord_list(Babs, startangle, endangle, angle_stepsize, clockwise=clockwise)
angles_lst, 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
@ -921,7 +921,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R
# 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):
def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event, target_angle, measurement_data)->None:
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:
@ -943,6 +943,9 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R
with lock:
shared_values[device_id] = value
# ADDED APPEND_MEASUREMENT
append_measurement(Babs, target_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()):
@ -952,9 +955,16 @@ 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, intensity_data=intensity_data):
def monitor_devices(device_target_values, angles_lst, intensity_data=intensity_data)->None:
# 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}")
target_angle = angles_lst[iteration] # get the angle for the current iteration
# 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
@ -966,7 +976,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R
# 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, target_angle, measurement_data))
threads.append(thread)
thread.start()
@ -993,7 +1003,7 @@ 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 = len(angles) - iteration - 1
points_left = len(angles_lst) - 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)
@ -1026,12 +1036,16 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R
# 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)
intensity_data = np.array(intensity_data)
np.savetxt(Settings + f'{angles[0]}°_to_{angles[-1]}°' + experiment_name +'.txt', intensity_data)
np.savetxt(Settings + f'{angles_lst[0]}°_to_{angles_lst[-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)
@ -1041,7 +1055,7 @@ def b_field_rotation(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.R
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)
monitor_devices(device_target_values, angles_lst, intensity_data)
def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Resource,
@ -1117,7 +1131,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, measurement_data):
def listen_to_device(device_id, target_value, shared_values, lock, all_targets_met_event, measurement_data)->None:
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:
@ -1147,6 +1161,7 @@ def sweep_b_angle(instr1:pyvisa.resources.Resource, instr2:pyvisa.resources.Reso
with lock:
shared_values[device_id] = value
# ADDED APPEND_MEASUREMENT
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
@ -1158,7 +1173,7 @@ 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)->None:
# initilise measurement list for b-val tracking
measurement_data = []

42
Test_PyQt.py Normal file
View File

@ -0,0 +1,42 @@
import sys
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QVBoxLayout, QWidget
# Worker Thread
class Worker(QThread):
progress = pyqtSignal(int) # Signal to send data to the main thread
def run(self):
for i in range(100):
self.sleep(1) # simulate long task
self.progress.emit(i) # emit progress update
# Main Window
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("QThread Example")
self.setGeometry(100, 100, 300, 150)
self.label = QLabel("Press Start", self)
self.button = QPushButton("Start Long Task", self)
self.button.clicked.connect(self.start_task)
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setLayout(layout)
def start_task(self):
self.worker = Worker()
self.worker.progress.connect(self.update_label)
self.worker.start()
def update_label(self, value):
self.label.setText(f"Count: {value}")
# Run the app
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())