Sample preparation at beamline

Final sample preparation

Mount reference samples - HOPG for energy calibration - SBA-15 or something similar for SDD - Blank SiN (should be same thickness and specs used for other samples) for blank measurements - Blank silicon wafer (same specs as TEY samples) for blank measurements

Capture bar image

Before pumping down the high-throughput solid sample bar into the beamline load lock, scan the bar using the imager microscope. - Load the sample bar with the front (flat side) facing up into the image holder and switch on the microscope light. Ensure the shoulders of the bar are fully flush against the holder, and be careful not to bend the bar while loading it. - In Bluesky, run RE(image_bar(front=True, path="/nsls2/data/sst/shared/scratch/spreadsheets_temporary/BarImage_Front.jpg")). The bar will slide along its long axis, and a series of telecentric images along the bar will be captured. If the bar stops sliding before the full image is saved, the imaging can be resumed by clicking the “Start” button on the “RSoXS screen 5” tab in phoebus.

Note the scan ID of the bar image scan, and run the code below to stitch the indiviual raw images into a complete picture of the bar.

Code
```{python}
#| code-fold: true
## Environment setup (for first time only)

ENV_NAME = "nslsii_data_analysis"
REPO_PATH = r"G:\Shared drives\NISTPostdoc\Codebases\xray_loaders"

## Create new environment
print(f"--- Creating environment with conda-forge ---")
%conda create -n {ENV_NAME} -c conda-forge ipykernel jupyterlab zarr openpyxl -y

## If in a terminal, activate the environment
#conda activate {ENV_NAME}

## Register the kernel
## In terminal, run in the activated environment without the %conda run -n {ENV_NAME} 
print(f"--- Registering Jupyter Kernel ---")
%conda run -n {ENV_NAME} python -m ipykernel install --user --name {ENV_NAME} --display-name "{ENV_NAME}"

## Install pyhyperscattering for data access and analysis.
print(f"--- Installing pyhyperscattering ---")
%conda run -n {ENV_NAME} pip install --no-cache-dir pyhyperscattering[bluesky,ui]

print("\n--- Setup Complete! ---")

## Select the kernel that was created above in Jupyter notebook
```
Code
```{python}
#| code-fold: true
#| output: false
#| warning: false
## Access NSLS II data

import PyHyperScattering as phs

loader = phs.load.SST1RSoXSDB(corr_mode="none")
catalog = loader.c
```
Code
```{python}
#| code-fold: true
## Data storage and manipulation
import numpy as np

## Plotting
import matplotlib.pyplot as plt

## Image processing
from PIL import Image

## Originally from rsoxs.alignment.bar_image_processing import stitch_sample
## TODO: rename function to stitch_sample_bar_image?
def stitch_sample(images, step_size, y_off, from_image=None, flip_file=False):
    global sample_image_axes

    if isinstance(from_image, str):
        im_frame = Image.open(from_image)
        result = np.array(im_frame)
        if flip_file:
            result = np.flipud(result)
    else:
        pixel_step = int(step_size * (1760) / 25)
        pixel_overlap = 2464 - pixel_step
        result = images[0][0]
        i = 0
        for imageb in images[1:]:
            image = imageb[0]
            i += 1
            if y_off > 0:
                result = np.concatenate((image[(y_off * i) :, :], result[:-(y_off), pixel_overlap:]), axis=1)
            elif y_off < 0:
                result = np.concatenate((image[: (y_off * i), :], result[-(y_off):, pixel_overlap:]), axis=1)
            else:
                result = np.concatenate((image[:, :], result[:, pixel_overlap:]), axis=1)
        # result = np.flipud(result)

    fig, ax = plt.subplots()
    ax.imshow(result, extent=[-210, 25, -14.5, 14.5])
    sample_image_axes = ax
    #fig.canvas.mpl_connect("button_press_event", plot_click) ## For now, want to keep simple and not do clicking here.
    #fig.canvas.mpl_connect("key_press_event", plot_key_press)
    plt.show()
    return result


## TODO: try clicking on spots in notebook instead of RSoXS control computer

## TODO: try running correct_bar in notebook instead of RSoXS control computer
```
Code
```{python}
#| code-fold: true
SCAN_ID = 106708
FILE_NAME_BAR_IMAGE_EXPORT = r"BarImage_Front2.png"
FILE_PATH_BAR_IMAGE_EXPORT = r"C:\Users\pmk\Downloads"


import os
scan_raw = catalog[int(SCAN_ID)]
images = list(scan_raw["primary"]["data"]["Sample Imager Detector Area Camera_image"].read())
image = stitch_sample(images, 25, -6)
im = Image.fromarray(image)
im.save(os.path.join(FILE_PATH_BAR_IMAGE_EXPORT, FILE_NAME_BAR_IMAGE_EXPORT))
```