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 ###########################################################################################