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 -