diff --git a/tutorial/plotting_shotcuts_branch/plotting_shortcuts_sst1_carbon_prsoxs.ipynb b/tutorial/plotting_shotcuts_branch/plotting_shortcuts_sst1_carbon_prsoxs.ipynb new file mode 100644 index 00000000..30a84db5 --- /dev/null +++ b/tutorial/plotting_shotcuts_branch/plotting_shortcuts_sst1_carbon_prsoxs.ipynb @@ -0,0 +1,2641 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "0", + "metadata": {}, + "source": [ + "# Plotting pre-processed SST1 RSoXS data\n", + "Use pyhyper's new RSoXS plotting shortctus" + ] + }, + { + "cell_type": "markdown", + "id": "1", + "metadata": { + "tags": [] + }, + "source": [ + "## Imports" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "## Imports\n", + "import PyHyperScattering as phs\n", + "import pathlib\n", + "import sys\n", + "import io\n", + "import ast\n", + "import json\n", + "import datetime\n", + "import dask.array as da\n", + "import numpy as np\n", + "import pandas as pd\n", + "import xarray as xr\n", + "import matplotlib.pyplot as plt\n", + "from matplotlib.colors import LogNorm\n", + "from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)\n", + "from tqdm.auto import tqdm\n", + "import subprocess\n", + "import gc\n", + "\n", + "print(f'Using PyHyperScattering Version: {phs.__version__}')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5ebcfdba-3989-4fcb-8e66-c241a321827e", + "metadata": {}, + "outputs": [], + "source": [ + "%load_ext autoreload" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0fa625ad-1430-4286-ac94-a02a0e5d218e", + "metadata": {}, + "outputs": [], + "source": [ + "%autoreload" + ] + }, + { + "cell_type": "markdown", + "id": "96adcc47-a83c-4c87-a74b-f87496d0f753", + "metadata": {}, + "source": [ + "## Define paths" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "16617d00-65e5-4015-82c4-45fb3d8ae910", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "basePath = pathlib.Path.cwd()" + ] + }, + { + "cell_type": "markdown", + "id": "8", + "metadata": { + "jp-MarkdownHeadingCollapsed": true, + "tags": [] + }, + "source": [ + "## Load cartesian data " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "[f.name for f in basePath.glob('*zarr')]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "11", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "DS = xr.open_zarr(basePath.joinpath('cartesian_data_PM6_CF.zarr'))\n", + "\n", + "# Compute any dask coordiantes\n", + "for coord_name, coord_data in DS.coords.items():\n", + " if isinstance(coord_data.data, da.Array):\n", + " DS.coords[coord_name] = coord_data.compute()\n", + " \n", + "DS" + ] + }, + { + "cell_type": "markdown", + "id": "5fe3d743-571f-41e0-b2e6-ec92ef1fdaca", + "metadata": {}, + "source": [ + "### Detector images" + ] + }, + { + "cell_type": "markdown", + "id": "d8d4d1d7-8458-401d-9415-dd5a6749532b", + "metadata": {}, + "source": [ + "#### Facet plot at several selected energies" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "66cd537c-e218-480d-845c-9f0367add046", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "2779843d-0741-45c8-9cf8-fd11a08e89e6", + "metadata": {}, + "source": [ + "#### Single image at selected energy" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "156cada4-ad4a-4059-b15a-97d837419550", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "3e86b7cd-b724-4c54-ad63-82d3f5d093af", + "metadata": {}, + "source": [ + "#### Generate mp4 movie of detector image at all energies" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1219ad6a-fe5b-4d2a-888b-8c0d0ca4d0d3", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "440cf8e0-9a01-49fc-a739-c72212012602", + "metadata": {}, + "source": [ + "## Load polar data" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fbc68672-0ebe-42f5-b8a4-5ac19740741a", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "[f.name for f in basePath.glob('*zarr')]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e98775cc-7447-40f6-8c90-a6c58ba9e4cd", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "DS = xr.open_zarr(basePath.joinpath('polar_data_PM6_CF.zarr'))\n", + "\n", + "# Compute any dask coordiantes\n", + "for coord_name, coord_data in DS.coords.items():\n", + " if isinstance(coord_data.data, da.Array):\n", + " DS.coords[coord_name] = coord_data.compute()\n", + " \n", + "DS" + ] + }, + { + "cell_type": "markdown", + "id": "15995e5c-cd62-415b-abb9-ce23d4aafae3", + "metadata": {}, + "source": [ + "### Integrated scattered intensity (ISI) plots" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a44694d0-c26e-4fb2-ad65-7e2e5eba10af", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Select a dataarray (potentially from larger dataset)\n", + "pol = 0\n", + "data_variable = 'raw_intensity'\n", + "DA = DS[data_variable].sel(polarization=pol)\n", + "\n", + "# Set parameters for ISI function\n", + "chi_width = 90 # width of chi wedge for para / perp slices\n", + "q_slice = slice(0.01, 0.09) # q range (as slice object)\n", + "e_slice = slice(280, 295) # energy range (as slice object)\n", + "sample_name = str(DA.sample_name.values) # set custom sample name, ideally from DataArray \n", + "\n", + "# Call ISI function, return ISI figure & axes object\n", + "fig, ax = DA.pt.plot_ISI(pol, chi_width, q_slice, e_slice, sample_name)\n", + "\n", + "# Save if desired\n", + "save = False\n", + "filename = f'{sample_name}_chi-{chi_width}_q-{q_slice.start}-{q_slice.stop}_energy-{e_slice.start}-{e_slice.stop}_.png'\n", + "if save:\n", + " savePath = basePath.joinpath('ISI_plots')\n", + " savePath.mkdir(exist_ok=True)\n", + " fig.savefig(savePath.joinpath(f'{sample_name}.png'))\n", + "\n", + "# Plot\n", + "plt.show()\n", + "plt.close('all')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a49c3352-6b63-4e8a-9e86-77d08da13642", + "metadata": {}, + "outputs": [], + "source": [ + "# quick plotting to find q limits\n", + "\n", + "# %matplotlib widget\n", + "# plt.close('all')\n", + "# sel_DA = DA.sel(energy=285)\n", + "# cmin, cmax = sel_DA.quantile([0.01, 0.99]).compute()\n", + "# sel_DA.plot(norm=LogNorm(cmin,cmax), cmap=plt.cm.turbo)\n", + "# plt.show()\n", + "\n", + "%matplotlib widget\n", + "plt.close('all')\n", + "sel_DA = perp_DA.sel(energy=285, method='nearest').interpolate_na(dim='q')\n", + "cmin, cmax = sel_DA.quantile([0.01,0.99]).compute()\n", + "sel_DA.plot(norm=LogNorm(cmin,cmax))\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "40ed92b4-5597-4965-a016-a6ca3dc52f51", + "metadata": {}, + "source": [ + "### Intensity heatmaps" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "85a67a8b-9394-4d84-be6e-acb80653edbb", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "671d7fdb-2cc3-41ca-8d5f-b285efab2dc0", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "79e5f90f-f3d8-449b-8970-32ea3f567456", + "metadata": {}, + "source": [ + "### Intensity vs Q linecuts" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "193a2ee0-b215-45d4-b717-f3e02ecc8b6f", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3b1db826-e723-4895-b70e-cfe4354ccd34", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c13ef87c-ef20-40a5-8a68-52dd53c67217", + "metadata": {}, + "source": [ + "### Anisotropy heatmaps" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "62185924-2ae2-46a3-adfe-64c3a7644afa", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e307c9fd-25b7-4128-aa4d-4d015e3ec9cb", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "cbb2d354-62ba-4001-9459-02b129de73d5", + "metadata": {}, + "source": [ + "### Anisotropy vs Q linecuts" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f1bfa476-e7db-4889-b186-e85f0ed607d0", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ff0c8eb5-9e50-4dd7-8121-e6f3573853ae", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "cf0362da-43a5-4802-9418-2d2efcc3f5e3", + "metadata": {}, + "source": [ + "## Previous, less organized code below:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# misc helper function\n", + "def make_para_perp_DAs(DS, sample_name, intensity_type, pol, qlims, chi_width):\n", + " # select dataarray to plot\n", + " DA = DS.sel(sample_name=sample_name)[f'{intensity_type}_intensity']\n", + " sliced_DA = DA.sel(polarization=pol, q=slice(qlims[0],qlims[1]))\n", + "\n", + " # calculate ISI dataarrays\n", + " if pol==0:\n", + " para_DA = sliced_DA.rsoxs.slice_chi(180, chi_width=(chi_width/2))\n", + " perp_DA = sliced_DA.rsoxs.slice_chi(90, chi_width=(chi_width/2))\n", + " elif pol==45:\n", + " para_DA = sliced_DA.rsoxs.slice_chi(-135, chi_width=(chi_width/2))\n", + " perp_DA = sliced_DA.rsoxs.slice_chi(135, chi_width=(chi_width/2)) \n", + " elif pol==90:\n", + " perp_DA = sliced_DA.rsoxs.slice_chi(180, chi_width=(chi_width/2))\n", + " para_DA = sliced_DA.rsoxs.slice_chi(90, chi_width=(chi_width/2)) \n", + " \n", + " return para_DA, perp_DA" + ] + }, + { + "cell_type": "markdown", + "id": "fdfc2b59-417c-4ab3-927b-efb926b581e6", + "metadata": { + "tags": [] + }, + "source": [ + "## Intensity Plots" + ] + }, + { + "cell_type": "markdown", + "id": "bb3a0085-5e8c-4354-a5e9-20bcb9d1f063", + "metadata": { + "jp-MarkdownHeadingCollapsed": true, + "tags": [] + }, + "source": [ + "### 1. Detector movies" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "94886aac-3f8a-48b3-9dcc-a34362d024f4", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "%matplotlib inline" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a50812e6-8c8a-4fc6-bb36-cf2f42731c2f", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "plt.close('all')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "14241c70-ef04-4d36-92ba-d7241a3d48be", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "already_made_movies = set([f.name[:-17] for f in plotsPath.joinpath('rsoxs_carbon_detector_movies_v1').glob('*pol90*')])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1f256176-831b-4e59-8162-8f83f5177517", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "selected_samples = list(set(DS.sample_name.values).difference(already_made_movies))\n", + "selected_samples" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "42", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Parameters\n", + "edge = 'carbon'\n", + "# DS = rsoxs_datasets[f'cartesian_{edge}']\n", + "# DS = rsoxs_datasets[f'cartesian_{edge}_reverse']\n", + "intensity_type = 'raw'\n", + "pol = 0\n", + "energy = 285.2\n", + "\n", + "# selected_samples = ['PM6_CB', 'PM6_p5CN-CB', 'PM6_1CN-CB', 'PM6_5CN-CB', \n", + "# 'PM6_CF', 'PM6_p5CN-CF', 'PM6_1CN-CF', 'PM6_5CN-CF', \n", + "# 'PM6_4CF-1CB', 'PM6_2CF-3CB', 'PM6_p5CN-2CF-3CB'] \n", + "# selected_samples = ['PM6_5CN-CB']\n", + "\n", + "# for sample_name in DS.sample_name.values:\n", + "for sample_name in selected_samples:\n", + " DA = DS.sel(sample_name=sample_name)[f'{intensity_type}_intensity']\n", + " DA = DA.where(DA>0, 10)\n", + " # Make & customize plot\n", + " sliced_DA = DA.sel(polarization=pol).sel(energy=energy, method='nearest').swap_dims({'pix_x':'qx','pix_y':'qy'})\n", + "\n", + " cmin = float(sliced_DA.sel(qx=slice(0.01,0.05),qy=slice(0.01,0.05)).compute().quantile(0.03))\n", + " cmax = float(sliced_DA.sel(qx=slice(0.01,0.05),qy=slice(0.01,0.05)).compute().quantile(0.999))\n", + " \n", + " # cmin = cmin if cmin > 1e8 else 1e8\n", + "\n", + " ax = sliced_DA.plot.imshow(figsize=(5.5,4.5), cmap=cmap, norm=LogNorm(cmin,cmax))\n", + " ax.figure.suptitle(f'Photon Energy = {np.round(energy, 1)} eV', fontsize=14, y=0.96)\n", + " ax.figure.set_tight_layout(True) \n", + " ax.axes.set(aspect='equal', title=f'{sample_name}, Polarization = {pol}°', xlabel='q$_x$ [$Å^{-1}$]', ylabel='q$_y$ [$Å^{-1}$]')\n", + " ax.colorbar.set_label('Raw Intensity [arb. units]', rotation=270, labelpad=12)\n", + "\n", + " plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "44", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Select Dataset\n", + "# edge = 'carbon'\n", + "# DS = rsoxs_datasets[f'cartesian_{edge}_reverse']\n", + "# DS = rsoxs_datasets[f'cartesian_{edge}_tilted']\n", + "\n", + "# bcx = DS['raw_intensity'].beamcenter_x\n", + "# bcy = DS['raw_intensity'].beamcenter_y\n", + "\n", + "# Select Plotting Parameters\n", + "# pol = 90\n", + "# pix_size = 500\n", + "# pix_x_slice = slice(bcx-(pix_size/2), bcx+(pix_size/2))\n", + "# pix_y_slice = slice(bcy-(pix_size/2), bcy+(pix_size/2))\n", + "intensity_type = 'raw'\n", + "\n", + "# Select DataArray\n", + "# sample_name = 'PM6-Y6_3000_dSiN'\n", + "# selected_samples = ['PM6_5CN-CB']\n", + "for pol in [0, 90]:\n", + " # for sample_name in tqdm(DS.sample_name.values, desc=f'Polarization {pol}°'):\n", + " for sample_name in tqdm(selected_samples, desc=f'Polarization {pol}°'):\n", + " DA = DS.sel(sample_name=sample_name)[f'{intensity_type}_intensity']\n", + "\n", + " savePath = plotsPath.joinpath('rsoxs_carbon_detector_movies_v1')\n", + " savePath.mkdir(exist_ok=True)\n", + " output_path = savePath.joinpath(f'{sample_name}_{intensity_type}_pol{pol}deg.mp4')\n", + "\n", + " # FFmpeg command. This is set up to accept data from the pipe and use it as input, with PNG format.\n", + " # It will then output an H.264 encoded MP4 video.\n", + " cmd = [\n", + " 'ffmpeg',\n", + " '-y', # Overwrite output file if it exists\n", + " '-f', 'image2pipe',\n", + " '-vcodec', 'png',\n", + " '-r', '16', # Frame rate\n", + " '-i', '-', # The input comes from a pipe\n", + " '-vcodec', 'libx264',\n", + " '-pix_fmt', 'yuv420p',\n", + " '-crf', '22', # Set the quality (lower is better, 17 is often considered visually lossless)\n", + " str(output_path)\n", + " ]\n", + "\n", + " # Start the subprocess\n", + " proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n", + "\n", + " # Loop through the energy dimension and send frames to FFmpeg\n", + " for i, energy in enumerate(tqdm(DA.energy.values, desc=f'Making the {sample_name} movie')):\n", + " # Make & customize plot\n", + " sliced_DA = DA.sel(polarization=pol).sel(energy=energy, method='nearest').swap_dims({'pix_x':'qx','pix_y':'qy'})\n", + " \n", + "# cmin = float(sliced_DA.sel(qx=slice(0.01,0.05),qy=slice(0.01,0.05)).compute().quantile(0.05))\n", + "# cmax = float(sliced_DA.sel(qx=slice(0.01,0.05),qy=slice(0.01,0.05)).compute().quantile(0.999))\n", + "\n", + "# cmin = cmin if cmin > 1e8 else 1e8\n", + " \n", + " ax = sliced_DA.plot.imshow(figsize=(5.5,4.5), cmap=cmap, norm=LogNorm(cmin,cmax))\n", + " ax.figure.suptitle(f'Photon Energy = {np.round(energy, 1)} eV', fontsize=14, y=0.96)\n", + " ax.figure.set_tight_layout(True) \n", + " ax.axes.set(aspect='equal', title=f'{sample_name}, Polarization = {pol}°', xlabel='q$_x$ [$Å^{-1}$]', ylabel='q$_y$ [$Å^{-1}$]')\n", + " ax.colorbar.set_label('Raw Intensity [arb. units]', rotation=270, labelpad=12)\n", + "\n", + " # Save first frame (or specific energy value)\n", + " if energy == 285.2:\n", + " ax.figure.savefig(savePath.joinpath(f'{sample_name}_{intensity_type}_pol{pol}deg.png'), dpi=120)\n", + "\n", + " buf = io.BytesIO()\n", + " ax.figure.savefig(buf, format='png')\n", + " buf.seek(0)\n", + "\n", + " # Write the PNG buffer data to the process\n", + " proc.stdin.write(buf.getvalue())\n", + " plt.close('all')\n", + "\n", + " # Finish the subprocess\n", + " out, err = proc.communicate()\n", + " if proc.returncode != 0:\n", + " print(f\"Error: {err}\")\n", + " \n", + " gc.collect() # try to clear up some memory...\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2efd81dc-060a-4f17-941e-d885379fc85e", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "plotsPath" + ] + }, + { + "cell_type": "markdown", + "id": "45", + "metadata": { + "tags": [] + }, + "source": [ + "### 2. ISI Plots" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "46", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Select polar dataset, to ISI plots, polarizations 0 & 90 averaged\n", + "edge = 'carbon'\n", + "DS = rsoxs_datasets[f'polar_{edge}_reverse'].copy()\n", + "# DS = rsoxs_datasets[f'polar_{edge}_tilted'].copy()\n", + "\n", + "# DS = DS.rename_vars({'raw_intensity':'corr_intensity'})\n", + "\n", + "chi_width = 90\n", + "q_slice = slice(0.009,0.08)\n", + "e_slice = slice(282, 295)\n", + "\n", + "# make selection\n", + "intensity_type = 'corr'\n", + "\n", + "# for sample_name in tqdm(filtered_selected_samples):\n", + "for sample_name in tqdm(DS.sample_name.values[:]):\n", + " pol_paras = []\n", + " pol_perps = []\n", + " for pol in [0, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, (q_slice.start,q_slice.stop), chi_width) \n", + " pol_paras.append(para_DA)\n", + " pol_perps.append(perp_DA)\n", + "\n", + "\n", + " pol_paras[0] = pol_paras[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_paras[1] = pol_paras[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + " pol_perps[1] = pol_perps[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " pol_paras[0] = pol_paras[0].interp({'chi': pol_paras[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].interp({'chi': pol_perps[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " para_DA = (pol_paras[0] + pol_paras[1])/2\n", + " perp_DA = (pol_perps[0] + pol_perps[1])/2\n", + "\n", + " para_DA = para_DA.assign_coords({'polarization':'avg'})\n", + " perp_DA = perp_DA.assign_coords({'polarization':'avg'})\n", + "\n", + " para_DA = para_DA.interpolate_na(dim='q')\n", + " perp_DA = perp_DA.interpolate_na(dim='q')\n", + "\n", + " pol = str(para_DA.polarization.values) \n", + " \n", + "# # Fl correction?\n", + "# scale_factor = float(para_DA.sel(energy=slice(285,305), q=slice(2e-2,6e-2)).mean('chi').mean('energy').integrate('q'))\n", + "# manual_scale_factor = manual_scale_factors_v4[sample_name]\n", + "# trmsn90_corr = (manual_scale_factor * scale_factor * trmsn90_bkgs_DA.sel(sample_name=sample_name))\n", + " \n", + "# para_DA = para_DA - trmsn90_corr\n", + "# perp_DA = perp_DA - trmsn90_corr\n", + "\n", + " # slice ISI data\n", + " para_ISI = para_DA.interpolate_na(dim='q').sel(q=q_slice).mean('chi').mean('q')\n", + " perp_ISI = perp_DA.interpolate_na(dim='q').sel(q=q_slice).mean('chi').mean('q')\n", + "\n", + " # plot\n", + " fig, ax = plt.subplots(figsize=(6,4), dpi=120)\n", + " ax.xaxis.set_minor_locator(MultipleLocator(1))\n", + "\n", + " para_ISI.sel(energy=e_slice).plot.line(ax=ax, label='$\\parallel$', yscale='log')\n", + " perp_ISI.sel(energy=e_slice).plot.line(ax=ax, label='$\\perp$', yscale='log')\n", + " fig.suptitle(f'ISI: {sample_name}', fontsize=14, x=0.55)\n", + " ax.set(title=f'Pol = {pol}°, chi width = {chi_width}°, Q = ({q_slice.start}, {q_slice.stop}) ' + 'Å$^{-1}$', \n", + " xlabel='X-ray energy [eV]', ylabel='Intensity [arb. units]')\n", + " ax.legend(loc='upper right', fontsize=14)\n", + " ax.grid(axis='x', which='both')\n", + " plt.subplots_adjust(top=0.86, bottom=0.2, left=0.2)\n", + " \n", + " # savePath = plotsPath.joinpath('rsoxs_carbon_reverse/ISIs_v1')\n", + " # savePath.mkdir(exist_ok=True)\n", + " # fig.savefig(savePath.joinpath( \n", + " # f'{sample_name}_{intensity_type}_chi{chi_width}deg_q{q_slice.start}-{q_slice.stop}_pol{pol}deg.png'), dpi=120)\n", + "\n", + " # plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cbff014e-bd96-497c-a0d7-54bba0fcf826", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "plotsPath" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "47", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Select polar dataset, to ISI plots, individual polarizations\n", + "edge = 'carbon'\n", + "# DS = rsoxs_datasets[f'polar_{edge}'].copy()\n", + "DS = rsoxs_datasets[f'polar_{edge}_tilted'].copy()\n", + "\n", + "# DS = DS.rename_vars({'raw_intensity':'corr_intensity'})\n", + "\n", + "chi_width = 90\n", + "q_slice = slice(0.009,0.08)\n", + "e_slice = slice(282, 295)\n", + "\n", + "# make selection\n", + "intensity_type = 'corr'\n", + "\n", + "# for sample_name in tqdm(filtered_selected_samples):\n", + "for sample_name in tqdm(DS.sample_name.values[:]):\n", + " for pol in [0, 45, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, (q_slice.start,q_slice.stop), chi_width) \n", + "\n", + " # slice ISI data\n", + " para_ISI = para_DA.interpolate_na(dim='q').sel(q=q_slice).mean('chi').mean('q')\n", + " perp_ISI = perp_DA.interpolate_na(dim='q').sel(q=q_slice).mean('chi').mean('q')\n", + "\n", + " # plot\n", + " fig, ax = plt.subplots(figsize=(6,4), dpi=120)\n", + " ax.xaxis.set_minor_locator(MultipleLocator(1))\n", + "\n", + " para_ISI.sel(energy=e_slice).plot.line(ax=ax, label='$\\parallel$', yscale='log')\n", + " perp_ISI.sel(energy=e_slice).plot.line(ax=ax, label='$\\perp$', yscale='log')\n", + " fig.suptitle(f'ISI: {sample_name}', fontsize=14, x=0.55)\n", + " ax.set(title=f'Pol = {pol}°, chi width = {chi_width}°, Q = ({q_slice.start}, {q_slice.stop}) ' + 'Å$^{-1}$', \n", + " xlabel='X-ray energy [eV]', ylabel='Intensity [arb. units]')\n", + " ax.legend(loc='upper right', fontsize=14)\n", + " ax.grid(axis='x', which='both')\n", + " plt.subplots_adjust(top=0.86, bottom=0.2, left=0.2)\n", + "\n", + " savePath = plotsPath.joinpath('rsoxs_carbon_tilted/ISIs_v1')\n", + " savePath.mkdir(exist_ok=True)\n", + " fig.savefig(savePath.joinpath( \n", + " f'{sample_name}_{intensity_type}_chi{chi_width}deg_q{q_slice.start}-{q_slice.stop}_pol{pol}deg.png'), dpi=120)\n", + "\n", + " # plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "48", + "metadata": {}, + "outputs": [], + "source": [ + "selected_samples = ['Y6_3000_dSiN', 'PM6_3000_dSiN', 'PM6-Y6_3000_dSiN', 'PM7-Y6_3000_dSiN', 'Y7_3000_dSiN', 'PM7_3000_dSiN', 'PM7-Y7_3000_dSiN']\n", + "# selected_samples = ['Y6_3000_dSiN', 'PM6_3000_dSiN', 'PM6-Y6_3000_dSiN', 'PM7-Y6_3000_dSiN', 'Y7_3000_dSiN', 'PM7_3000_dSiN', 'PM7-Y7_3000_dSiN']" + ] + }, + { + "cell_type": "markdown", + "id": "49", + "metadata": { + "tags": [] + }, + "source": [ + "### 3. 2D Linecut Maps" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "50", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Select polar dataset, to I cuts, averaged 0 & 90 deg polarization\n", + "edge = 'carbon'\n", + "# DS = rsoxs_datasets[f'polar_{edge}'].copy()\n", + "# DS = rsoxs_datasets[f'polar_{edge}_tilted'].copy()\n", + "DS = rsoxs_datasets[f'polar_{edge}_reverse'].copy()\n", + "\n", + "chi_width = 90\n", + "q_slice = slice(0.009, 0.08)\n", + "e_slice = slice(282, 292)\n", + "\n", + "# make selection\n", + "# sample_name = 'PM6-Y6_3000_dSiN'\n", + "intensity_type = 'corr'\n", + "pol = 0\n", + "\n", + "# for sample_name in tqdm(filtered_selected_samples):\n", + "for sample_name in tqdm(DS.sample_name.values[:]):\n", + " # for pol in [0]:\n", + " # para_DA, perp_DA = make_para_perp_DAs(rsoxs_datasets, sample_name, edge, intensity_type, pol, qlims, chi_width) \n", + " \n", + " pol_paras = []\n", + " pol_perps = []\n", + " for pol in [0, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, (q_slice.start,q_slice.stop), chi_width) \n", + " pol_paras.append(para_DA)\n", + " pol_perps.append(perp_DA)\n", + "\n", + "\n", + " pol_paras[0] = pol_paras[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_paras[1] = pol_paras[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + " pol_perps[1] = pol_perps[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " pol_paras[0] = pol_paras[0].interp({'chi': pol_paras[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].interp({'chi': pol_perps[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " para_DA = (pol_paras[0] + pol_paras[1])/2\n", + " perp_DA = (pol_perps[0] + pol_perps[1])/2\n", + "\n", + " para_DA = para_DA.assign_coords({'polarization':'avg'})\n", + " perp_DA = perp_DA.assign_coords({'polarization':'avg'})\n", + "\n", + " para_DA = para_DA.interpolate_na(dim='q')\n", + " perp_DA = perp_DA.interpolate_na(dim='q')\n", + "\n", + " pol = str(para_DA.polarization.values) \n", + " \n", + "# # Fl correction?\n", + "# scale_factor = float(para_DA.sel(energy=slice(285,305), q=slice(2e-2,6e-2)).mean('chi').mean('energy').integrate('q'))\n", + "# manual_scale_factor = manual_scale_factors_v4[sample_name]\n", + "# trmsn90_corr = (manual_scale_factor * scale_factor * trmsn90_bkgs_DA.sel(sample_name=sample_name))\n", + " \n", + "# para_DA = para_DA - trmsn90_corr\n", + "# perp_DA = perp_DA - trmsn90_corr\n", + " \n", + " # Plot\n", + " fig, axs = plt.subplots(1, 2, figsize=(11,5))\n", + " # cmin = 1e8\n", + " # cmax = 1e11\n", + "\n", + " para_slice = para_DA.mean('chi').sel(q=q_slice, energy=e_slice) # .plot(ax=axs[0], cmap=cmap, norm=LogNorm(cmin, cmax), add_colorbar=False)\n", + " perp_slice = perp_DA.mean('chi').sel(q=q_slice, energy=e_slice) # .plot(ax=axs[1], cmap=cmap, norm=LogNorm(cmin, cmax), add_colorbar=False)\n", + "\n", + " cmin = perp_slice.compute().quantile(0.01)\n", + " cmax = para_slice.compute().quantile(0.995)\n", + "\n", + " para_slice.plot(ax=axs[0], cmap=cmap, norm=LogNorm(cmin, cmax), add_colorbar=False)\n", + " perp_slice.plot(ax=axs[1], cmap=cmap, norm=LogNorm(cmin, cmax), add_colorbar=False)\n", + "\n", + " # Add colorbar\n", + " sm = plt.cm.ScalarMappable(cmap=cmap, norm=LogNorm(cmin, cmax)) # Create a ScalarMappable object with the colormap and normalization & add the colorbar to the figure\n", + " cax = axs[1].inset_axes([1.03, 0, 0.05, 1])\n", + " cbar = fig.colorbar(sm, cax=cax, orientation='vertical')\n", + " cbar.set_label(label='Double-Norm-Corrected Intensity [arb. units]', labelpad=12, rotation=270)\n", + "\n", + " fig.suptitle(f'Linecut Maps: {sample_name}, Polarization = {pol}°, Chi Width = {chi_width}°', fontsize=14)\n", + " # fig.suptitle(f'Linecut Maps: {sample_name} Bare SiN Subtracted, Polarization = {pol}°, Chi Width = {chi_width}°', fontsize=14)\n", + " # fig.suptitle(f'Linecut Maps: {sample_name} Bare SiN & Fluorescence Subtracted, Polarization = {pol}°, Chi Width = {chi_width}°', fontsize=14)\n", + "\n", + " fig.set(tight_layout=True)\n", + "\n", + " axs[0].set(xscale='log', title='Parallel to $E_p$', ylabel='Photon energy [eV]', xlabel='q [$Å^{-1}$]')\n", + " axs[1].set(xscale='log', title='Perpendicular to $E_p$ ', ylabel=None, xlabel='q [$Å^{-1}$]')\n", + "\n", + " savePath = plotsPath.joinpath('rsoxs_carbon_reverse/I_maps_v1')\n", + " savePath.mkdir(exist_ok=True)\n", + " fig.savefig(savePath.joinpath( \n", + " f'{sample_name}_{e_slice.start}-{e_slice.stop}_{intensity_type}_chiWidth-{chi_width}deg_pol{pol}deg.png'), dpi=120)\n", + "\n", + " # plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "51", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Select polar dataset, to I cuts, individual polarizations\n", + "edge = 'carbon'\n", + "# DS = rsoxs_datasets[f'polar_{edge}'].copy()\n", + "DS = rsoxs_datasets[f'polar_{edge}_tilted'].copy()\n", + "\n", + "chi_width = 90\n", + "q_slice = slice(0.009, 0.08)\n", + "e_slice = slice(282, 292)\n", + "\n", + "# make selection\n", + "# sample_name = 'PM6-Y6_3000_dSiN'\n", + "intensity_type = 'corr'\n", + "pol = 0\n", + "\n", + "# for sample_name in tqdm(filtered_selected_samples):\n", + "for sample_name in tqdm(DS.sample_name.values[:]):\n", + " for pol in [0, 45, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, (q_slice.start,q_slice.stop), chi_width) \n", + "\n", + " # Plot\n", + " fig, axs = plt.subplots(1, 2, figsize=(11,5))\n", + "\n", + " para_slice = para_DA.mean('chi').sel(q=q_slice, energy=e_slice) # .plot(ax=axs[0], cmap=cmap, norm=LogNorm(cmin, cmax), add_colorbar=False)\n", + " perp_slice = perp_DA.mean('chi').sel(q=q_slice, energy=e_slice) # .plot(ax=axs[1], cmap=cmap, norm=LogNorm(cmin, cmax), add_colorbar=False)\n", + "\n", + " cmin = perp_slice.compute().quantile(0.01)\n", + " cmax = para_slice.compute().quantile(0.995)\n", + "\n", + " para_slice.plot(ax=axs[0], cmap=cmap, norm=LogNorm(cmin, cmax), add_colorbar=False)\n", + " perp_slice.plot(ax=axs[1], cmap=cmap, norm=LogNorm(cmin, cmax), add_colorbar=False)\n", + "\n", + " # Add colorbar\n", + " sm = plt.cm.ScalarMappable(cmap=cmap, norm=LogNorm(cmin, cmax)) # Create a ScalarMappable object with the colormap and normalization & add the colorbar to the figure\n", + " cax = axs[1].inset_axes([1.03, 0, 0.05, 1])\n", + " cbar = fig.colorbar(sm, cax=cax, orientation='vertical')\n", + " cbar.set_label(label='Double-Norm-Corrected Intensity [arb. units]', labelpad=12, rotation=270)\n", + "\n", + " fig.suptitle(f'Linecut Maps: {sample_name}, Polarization = {pol}°, Chi Width = {chi_width}°', fontsize=14)\n", + " # fig.suptitle(f'Linecut Maps: {sample_name} Bare SiN Subtracted, Polarization = {pol}°, Chi Width = {chi_width}°', fontsize=14)\n", + " # fig.suptitle(f'Linecut Maps: {sample_name} Bare SiN & Fluorescence Subtracted, Polarization = {pol}°, Chi Width = {chi_width}°', fontsize=14)\n", + "\n", + " fig.set(tight_layout=True)\n", + "\n", + " axs[0].set(xscale='log', title='Parallel to $E_p$', ylabel='Photon energy [eV]', xlabel='q [$Å^{-1}$]')\n", + " axs[1].set(xscale='log', title='Perpendicular to $E_p$ ', ylabel=None, xlabel='q [$Å^{-1}$]')\n", + "\n", + " savePath = plotsPath.joinpath('rsoxs_carbon_tilted/I_maps_v1')\n", + " savePath.mkdir(exist_ok=True)\n", + " fig.savefig(savePath.joinpath( \n", + " f'{sample_name}_{e_slice.start}-{e_slice.stop}_{intensity_type}_chiWidth-{chi_width}deg_pol{pol}deg.png'), dpi=120)\n", + "\n", + " # plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "52", + "metadata": {}, + "outputs": [], + "source": [ + "# a = para_EvsQ_avg.hvplot.line(groupby=\"energy\", loglog=True)\n", + "# a * perp_EvsQ_avg.hvplot.line(groupby=\"energy\")" + ] + }, + { + "cell_type": "markdown", + "id": "53", + "metadata": { + "tags": [] + }, + "source": [ + "### 4. Meaned 1D intensity lineplots, selected energies" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "54", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# trmsn90_bkgs_DA = xr.concat(trmsn90_bkgs, dim='sample_name')\n", + "# trmsn90_bkgs_DA" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "55", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# for sample_name in trmsn90_bkgs_DA.sample_name.values:\n", + "# trmsn90_bkgs_DA.sel(sample_name=sample_name).plot()\n", + "# plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "56", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# fl_bkgs_DA = xr.concat(fl_bkgs, dim='sample_name')\n", + "# fl_bkgs_DA" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "57", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# trmsn90_corr.plot()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "58", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# manual_scale_factors_v4 = {\n", + "# 'PM6_CB_3000': 8.4,\n", + "# 'PM6_CBCN': 11,\n", + "# 'PM6_CF_3000': 6,\n", + "# 'PM6_CFCN': 10.5,\n", + "# 'PM6-Y6_CB': 6.3,\n", + "# 'PM6-Y6_CBCN': 4.5,\n", + "# 'PM6-Y6_CF': 6,\n", + "# 'PM6-Y6_CFCN': 11.5,\n", + "# 'PM6-Y6BO_CB': 7.5,\n", + "# 'PM6-Y6BO_CF': 5,\n", + "# 'PM6-Y6BO_CFCN': 12.8,\n", + "# 'PM6-Y7_CB': 6.5,\n", + "# 'PM6-Y7_CBCN': 8.5,\n", + "# 'PM6-Y7_CF': 4.5,\n", + "# 'PM6-Y7_CFCN': 12.8,\n", + "# 'PM6-Y7BO_CB': 5,\n", + "# 'PM6-Y7BO_CBCN': 8.2,\n", + "# 'PM6-Y7BO_CF': 5,\n", + "# 'PM6-Y7BO_CFCN': 10,\n", + "# 'Y6_CB_2000_1': 5,\n", + "# 'Y6_CB_2000': 6,\n", + "# 'Y6_CB_2500': 6,\n", + "# 'Y6_CB_3000': 6,\n", + "# 'Y6_CF_2000': 18,\n", + "# 'Y6_CF_2500': 20,\n", + "# }\n", + "\n", + "# len(manual_scale_factors_v4)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "59", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# make selection, averaged polarizations\n", + "edge = 'carbon'\n", + "# DS = rsoxs_datasets[f'polar_{edge}']\n", + "DS = rsoxs_datasets[f'polar_{edge}_reverse']\n", + "\n", + "intensity_type = 'corr'\n", + "qlims = (0.009, 0.08)\n", + "chi_width = 90\n", + "\n", + "# for sample_name in tqdm(filtered_selected_samples):\n", + "for sample_name in tqdm(DS.sample_name.values[:]):\n", + " pol_paras = []\n", + " pol_perps = []\n", + " for pol in [0, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, qlims, chi_width) \n", + " pol_paras.append(para_DA)\n", + " pol_perps.append(perp_DA)\n", + "\n", + "\n", + " pol_paras[0] = pol_paras[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_paras[1] = pol_paras[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + " pol_perps[1] = pol_perps[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " pol_paras[0] = pol_paras[0].interp({'chi': pol_paras[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].interp({'chi': pol_perps[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " para_DA = (pol_paras[0] + pol_paras[1])/2\n", + " perp_DA = (pol_perps[0] + pol_perps[1])/2\n", + "\n", + " para_DA = para_DA.assign_coords({'polarization':'avg'})\n", + " perp_DA = perp_DA.assign_coords({'polarization':'avg'})\n", + "\n", + " para_DA = para_DA.interpolate_na(dim='q')\n", + " perp_DA = perp_DA.interpolate_na(dim='q')\n", + "\n", + " pol = str(para_DA.polarization.values) \n", + " \n", + "# # Fl correction?\n", + "# scale_factor = float(para_DA.sel(energy=slice(285,305), q=slice(2e-2,6e-2)).mean('chi').mean('energy').integrate('q'))\n", + "# manual_scale_factor = manual_scale_factors_v4[sample_name]\n", + "# trmsn90_corr = (manual_scale_factor * scale_factor * trmsn90_bkgs_DA.sel(sample_name=sample_name))\n", + " \n", + "# para_DA = para_DA - trmsn90_corr\n", + "# perp_DA = perp_DA - trmsn90_corr\n", + " \n", + " # Plot\n", + " energies = para_DA.energy.sel(energy=[260, 275, 283, 284, 284.4, 284.8, 285.2, 285.6, 286.2, 287, 300, 338.75], method='nearest').data\n", + "\n", + " cmap = plt.cm.turbo.copy()\n", + " colors = cmap(np.linspace(0, 1, len(energies)))\n", + "\n", + " fig, axs = plt.subplots(ncols=2,figsize=(8,5), tight_layout=True)\n", + "\n", + " qmin = qlims[0]\n", + " qmax = qlims[1]\n", + "\n", + " for j, energy in enumerate(energies):\n", + " (para_DA.sel(q=slice(qmin, qmax), energy=energy).mean('chi')\n", + " .plot.line(ax=axs[0], color=colors[j], yscale='log', xscale='log', label=energy))\n", + " (perp_DA.sel(q=slice(qmin, qmax), energy=energy).mean('chi')\n", + " .plot.line(ax=axs[1], color=colors[j], yscale='log', xscale='log', label=energy))\n", + "\n", + " fig.suptitle(f'IvsQ, {pol}° pol, 90° chi width: {sample_name}', x=0.47)\n", + " # fig.suptitle(f'IvsQ ($Fl$ Corr (C={manual_scale_factor})), {pol}° pol, 90° chi width: {sample_name}', x=0.47)\n", + "\n", + " axs[0].set(title=f'Parallel to E$_p$', ylabel='Intensity [arb. units]', xlabel='Q [$Å^{-1}$]')\n", + " axs[0].set_ylim(bottom=1e8)\n", + " axs[1].set(title=f'Perpendicular to E$_p$', ylabel='Intensity [arb. units]', xlabel='Q [$Å^{-1}$]')\n", + " axs[1].set_ylim(bottom=1e8)\n", + " axs[1].legend(title='Energy [eV]', loc=(1.05,0.1))\n", + "\n", + " savePath = plotsPath.joinpath('rsoxs_carbon_reverse/I_cuts_v1')\n", + " savePath.mkdir(exist_ok=True)\n", + " fig.savefig(savePath.joinpath(\n", + " f'{sample_name}_chiWidth-{chi_width}deg_q{qmin}-{qmax}_pol{pol}deg.png'), dpi=120)\n", + "\n", + " # plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "60", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# make selection, individual polarizations\n", + "edge = 'carbon'\n", + "# Drsoxs_datasets rsoxs_datasets[f'polar_{edge}']\n", + "DS = rsoxs_datasets[f'polar_{edge}_tilted']\n", + "\n", + "intensity_type = 'corr'\n", + "qlims = (0.009, 0.08)\n", + "chi_width = 90\n", + "\n", + "# for sample_name in tqdm(filtered_selected_samples):\n", + "for sample_name in tqdm(DS.sample_name.values[:]):\n", + " for pol in [0, 45, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, qlims, chi_width) \n", + "\n", + " # Plot\n", + " energies = para_DA.energy.sel(energy=[260, 275, 283, 284, 284.4, 284.8, 285.2, 285.6, 286.2, 287, 300, 338.75], method='nearest').data\n", + "\n", + " cmap = plt.cm.turbo.copy()\n", + " colors = cmap(np.linspace(0, 1, len(energies)))\n", + "\n", + " fig, axs = plt.subplots(ncols=2,figsize=(8,5), tight_layout=True)\n", + "\n", + " qmin = qlims[0]\n", + " qmax = qlims[1]\n", + "\n", + " for j, energy in enumerate(energies):\n", + " (para_DA.sel(q=slice(qmin, qmax), energy=energy).mean('chi')\n", + " .plot.line(ax=axs[0], color=colors[j], yscale='log', xscale='log', label=energy))\n", + " (perp_DA.sel(q=slice(qmin, qmax), energy=energy).mean('chi')\n", + " .plot.line(ax=axs[1], color=colors[j], yscale='log', xscale='log', label=energy))\n", + "\n", + " fig.suptitle(f'IvsQ, {pol}° pol, 90° chi width: {sample_name}', x=0.47)\n", + " # fig.suptitle(f'IvsQ ($Fl$ Corr (C={manual_scale_factor})), {pol}° pol, 90° chi width: {sample_name}', x=0.47)\n", + "\n", + " axs[0].set(title=f'Parallel to E$_p$', ylabel='Intensity [arb. units]', xlabel='Q [$Å^{-1}$]')\n", + " axs[0].set_ylim(bottom=1e8)\n", + " axs[1].set(title=f'Perpendicular to E$_p$', ylabel='Intensity [arb. units]', xlabel='Q [$Å^{-1}$]')\n", + " axs[1].set_ylim(bottom=1e8)\n", + " axs[1].legend(title='Energy [eV]', loc=(1.05,0.1))\n", + "\n", + " savePath = plotsPath.joinpath('rsoxs_carbon_tilted/I_cuts_v1')\n", + " savePath.mkdir(exist_ok=True)\n", + " fig.savefig(savePath.joinpath(\n", + " f'{sample_name}_chiWidth-{chi_width}deg_q{qmin}-{qmax}_pol{pol}deg.png'), dpi=120)\n", + "\n", + " # plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "markdown", + "id": "61", + "metadata": { + "tags": [] + }, + "source": [ + "## Anisotropy Ratio Plots" + ] + }, + { + "cell_type": "markdown", + "id": "62", + "metadata": { + "tags": [] + }, + "source": [ + "### 1. 2D AR Maps" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f7bcd029-5fbe-4586-ba21-6454fc59d4bc", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "DS" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5ed14127-4117-406a-a5cb-fcc2279e5524", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# make selection, averaged polarizations\n", + "edge = 'carbon'\n", + "# # DS = rsoxs_datasets[f'polar_{edge}']\n", + "# DS = rsoxs_datasets[f'polar_{edge}_reverse']\n", + "\n", + "intensity_type = 'raw'\n", + "chi_width = 90\n", + "q_slice = slice(0.009, 0.08)\n", + "e_slice = slice(282, 292)\n", + "\n", + "for sample_name in DS.sample_name.values[:]: \n", + " pol_paras = []\n", + " pol_perps = []\n", + " for pol in [0, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, (q_slice.start,q_slice.stop), chi_width) \n", + " pol_paras.append(para_DA)\n", + " pol_perps.append(perp_DA)\n", + "\n", + "\n", + " pol_paras[0] = pol_paras[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_paras[1] = pol_paras[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + " pol_perps[1] = pol_perps[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " pol_paras[0] = pol_paras[0].interp({'chi': pol_paras[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].interp({'chi': pol_perps[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " para_DA = (pol_paras[0] + pol_paras[1])/2\n", + " perp_DA = (pol_perps[0] + pol_perps[1])/2\n", + "\n", + " para_DA = para_DA.assign_coords({'polarization':'avg'})\n", + " perp_DA = perp_DA.assign_coords({'polarization':'avg'})\n", + "\n", + " para_DA = para_DA.interpolate_na(dim='q')\n", + " perp_DA = perp_DA.interpolate_na(dim='q')\n", + "\n", + " pol = str(para_DA.polarization.values) \n", + "\n", + " # Select AR data\n", + " ar_DA = (para_DA.mean('chi') - perp_DA.mean('chi')) / (para_DA.mean('chi') + perp_DA.mean('chi'))\n", + "\n", + " # Plot\n", + " vlim = 0.4\n", + " ax = ar_DA.sel(energy=e_slice).plot.pcolormesh(figsize=(8,5), norm=plt.Normalize(-vlim, vlim))\n", + " # ax = ar_DA.sel(energy=slice(energy_min,energy_max)).plot(figsize=(8,5))\n", + "\n", + " ax.figure.suptitle('Anisotropy Ratio (AR) Map', fontsize=14, x=0.43)\n", + " ax.axes.set(title=f'{sample_name}, Polarization = {pol}°, Chi Width = {chi_width}°', ylabel='Photon Energy [eV]', xlabel='q [$Å^{-1}$]', xscale='log')\n", + " ax.colorbar.set_label('AR [arb. units]', rotation=270, labelpad=12)\n", + "\n", + " # savePath = plotsPath.joinpath('rsoxs_carbon_reverse/ar_maps_v1')\n", + " # savePath.mkdir(exist_ok=True)\n", + " # ax.figure.savefig(savePath.joinpath( \n", + " # f'vset_{sample_name}_{intensity_type}_chiWidth-{chi_width}deg_q-{q_slice.start}-{q_slice.stop}_energy{e_slice.start}-{e_slice.stop}_pol{pol}deg.png'), \n", + " # dpi=120)\n", + "\n", + " plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c0acae0e-969f-4900-a154-57b0c2a96015", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "%matplotlib inline" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "63", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# make selection, averaged polarizations\n", + "edge = 'carbon'\n", + "# # DS = rsoxs_datasets[f'polar_{edge}']\n", + "# DS = rsoxs_datasets[f'polar_{edge}_reverse']\n", + "\n", + "intensity_type = 'raw'\n", + "chi_width = 90\n", + "q_slice = slice(0.009, 0.08)\n", + "e_slice = slice(282, 292)\n", + "\n", + "for sample_name in DS.sample_name.values[:]: \n", + " pol_paras = []\n", + " pol_perps = []\n", + " for pol in [0, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, (q_slice.start,q_slice.stop), chi_width) \n", + " pol_paras.append(para_DA)\n", + " pol_perps.append(perp_DA)\n", + "\n", + "\n", + " pol_paras[0] = pol_paras[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_paras[1] = pol_paras[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + " pol_perps[1] = pol_perps[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " pol_paras[0] = pol_paras[0].interp({'chi': pol_paras[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].interp({'chi': pol_perps[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " para_DA = (pol_paras[0] + pol_paras[1])/2\n", + " perp_DA = (pol_perps[0] + pol_perps[1])/2\n", + "\n", + " para_DA = para_DA.assign_coords({'polarization':'avg'})\n", + " perp_DA = perp_DA.assign_coords({'polarization':'avg'})\n", + "\n", + " para_DA = para_DA.interpolate_na(dim='q')\n", + " perp_DA = perp_DA.interpolate_na(dim='q')\n", + "\n", + " pol = str(para_DA.polarization.values) \n", + "\n", + " # Select AR data\n", + " ar_DA = (para_DA.mean('chi') - perp_DA.mean('chi')) #/ (para_DA.mean('chi') + perp_DA.mean('chi'))\n", + "\n", + " # Plot\n", + " # vlim = 0.4\n", + " cmap = plt.cm.turbo\n", + " cmap.set_bad('black')\n", + " cmax = ar_DA.sel(energy=e_slice).compute().quantile(0.999)\n", + " ax = ar_DA.sel(energy=e_slice).plot.pcolormesh(figsize=(8,5), norm=LogNorm(1e0, cmax), cmap=cmap)\n", + " # ax = ar_DA.sel(energy=slice(energy_min,energy_max)).plot(figsize=(8,5))\n", + "\n", + " ax.figure.suptitle('$\\parallel$ - $\\perp$ Intensity Absolute Difference', fontsize=14, x=0.43)\n", + " ax.axes.set(title=f'{sample_name}, Polarization = {pol}°, Chi Width = {chi_width}°', ylabel='Photon Energy [eV]', xlabel='q [$Å^{-1}$]', xscale='log')\n", + " ax.colorbar.set_label('AR [arb. units]', rotation=270, labelpad=12)\n", + "\n", + " savePath = plotsPath.joinpath('rsoxs_carbon_para-perp_maps_v1')\n", + " savePath.mkdir(exist_ok=True)\n", + " ax.figure.savefig(savePath.joinpath( \n", + " f'{sample_name}_{intensity_type}_chiWidth-{chi_width}deg_q-{q_slice.start}-{q_slice.stop}_energy{e_slice.start}-{e_slice.stop}_pol{pol}deg.png'), \n", + " dpi=120)\n", + "\n", + " # plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "473b9a23-ff8d-4b36-96b9-13d0ab55a8cb", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "cmin" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a3d74f1c-981b-4e17-9931-a71cdb6e1ed0", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "cmax" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "64", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# make selection, individual polarizations\n", + "edge = 'carbon'\n", + "# DS = rsoxs_datasets[f'polar_{edge}']\n", + "DS = rsoxs_datasets[f'polar_{edge}_tilted']\n", + "\n", + "intensity_type = 'corr'\n", + "chi_width = 90\n", + "q_slice = slice(0.009, 0.08)\n", + "e_slice = slice(282, 292)\n", + "\n", + "for sample_name in tqdm(DS.sample_name.values[:]): \n", + " for pol in [0, 45, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, (q_slice.start,q_slice.stop), chi_width) \n", + "\n", + "\n", + " # Select AR data\n", + " ar_DA = (para_DA.mean('chi') - perp_DA.mean('chi')) / (para_DA.mean('chi') + perp_DA.mean('chi'))\n", + "\n", + " # Plot\n", + " vlim = 0.5\n", + " ax = ar_DA.sel(energy=e_slice).plot.pcolormesh(figsize=(8,5), norm=plt.Normalize(-vlim, vlim))\n", + " # ax = ar_DA.sel(energy=slice(energy_min,energy_max)).plot(figsize=(8,5))\n", + "\n", + " ax.figure.suptitle('Anisotropy Ratio (AR) Map', fontsize=14, x=0.43)\n", + " ax.axes.set(title=f'{sample_name}, Polarization = {pol}°, Chi Width = {chi_width}°', ylabel='Photon Energy [eV]', xlabel='q [$Å^{-1}$]', xscale='log')\n", + " ax.colorbar.set_label('AR [arb. units]', rotation=270, labelpad=12)\n", + "\n", + " savePath = plotsPath.joinpath('rsoxs_carbon_tilted/ar_maps_v1')\n", + " savePath.mkdir(exist_ok=True)\n", + " ax.figure.savefig(savePath.joinpath( \n", + " f'vset_{sample_name}_{intensity_type}_chiWidth-{chi_width}deg_q-{q_slice.start}-{q_slice.stop}_energy{e_slice.start}-{e_slice.stop}_pol{pol}deg.png'), \n", + " dpi=120)\n", + "\n", + " # plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "markdown", + "id": "65", + "metadata": { + "tags": [] + }, + "source": [ + "### 2. 1D meaned AR linecuts" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "64cf5091-6162-4b59-a696-4b10cabea92e", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "DS" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "66", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# make selection\n", + "edge = 'carbon'\n", + "# DS = rsoxs_datasets[f'polar_{edge}']\n", + "# DS = rsoxs_datasets[f'polar_{edge}_reverse']\n", + "\n", + "intensity_type = 'raw'\n", + "chi_width = 90\n", + "q_slice = slice(0.008, None)\n", + "e_slice = slice(282, 292)\n", + "\n", + "selected_samples = ['PM6_CB', 'PM6_p5CN-CB', 'PM6_1CN-CB', 'PM6_5CN-CB', \n", + " 'PM6_CF', 'PM6_p5CN-CF', 'PM6_1CN-CF', 'PM6_5CN-CF', \n", + " 'PM6_4CF-1CB', 'PM6_2CF-3CB', 'PM6_p5CN-2CF-3CB'] \n", + "\n", + "for sample_name in DS.sample_name.values[:]:\n", + "# for sample_name in tqdm(selected_samples):\n", + " pol_paras = []\n", + " pol_perps = []\n", + " for pol in [0, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, (q_slice.start,q_slice.stop), chi_width) \n", + " pol_paras.append(para_DA)\n", + " pol_perps.append(perp_DA)\n", + "\n", + "\n", + " pol_paras[0] = pol_paras[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_paras[1] = pol_paras[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + " pol_perps[1] = pol_perps[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " pol_paras[0] = pol_paras[0].interp({'chi': pol_paras[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].interp({'chi': pol_perps[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " para_DA = (pol_paras[0] + pol_paras[1])/2\n", + " perp_DA = (pol_perps[0] + pol_perps[1])/2\n", + "\n", + " para_DA = para_DA.assign_coords({'polarization':'avg'})\n", + " perp_DA = perp_DA.assign_coords({'polarization':'avg'})\n", + "\n", + " para_DA = para_DA.interpolate_na(dim='q')\n", + " perp_DA = perp_DA.interpolate_na(dim='q')\n", + "\n", + " pol = str(para_DA.polarization.values) \n", + "\n", + " # Select AR data\n", + " ar_DA = (para_DA.mean('chi') - perp_DA.mean('chi')) / (para_DA.mean('chi') + perp_DA.mean('chi'))\n", + "\n", + " # Plot \n", + " energies = para_DA.energy.sel(energy=[260, 275, 283, 284, 284.4, 284.8, 285.2, 285.6, 286.2, 287, 300, 338.75], method='nearest').data\n", + " cmap = plt.cm.turbo.copy()\n", + " colors = cmap(np.linspace(0, 1, len(energies))) \n", + "\n", + " # # Create a ScalarMappable object with the colormap and normalization & add the colorbar to the figure\n", + " # sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=energies[0], vmax=energies[-1]))\n", + " # cax = ax.inset_axes([1.03, 0, 0.03, 1])\n", + " # cbar = fig.colorbar(sm, cax=cax, orientation='vertical')\n", + " # cbar.set_label(label=f'Time [seconds]', labelpad=14)\n", + " # cbar.set_ticks(np.round(np.linspace(energies[0], energies[-1], len(energies)), 2))\n", + "\n", + " fig, ax = plt.subplots(tight_layout=True, figsize=(6,4), dpi=120)\n", + "\n", + " for j, energy in enumerate(energies):\n", + " (ar_DA.sel(energy=energy).plot.line(ax=ax, color=colors[j], label=energy, xscale='log'))\n", + "\n", + " fig.suptitle(f'Anisotropy Ratio Linecuts: {sample_name}', x=0.46, y=0.95)\n", + "\n", + " ax.set(title=f'Chi width = {chi_width}°, Pol = {pol}°', ylim=(-0.5, 0.5), ylabel='AR [arb. units]', xlabel='Q [$Å^{-1}$]')\n", + " ax.legend(title='Energy [eV]', loc=(1.03,0.02))\n", + "\n", + " # savePath = plotsPath.joinpath('rsoxs_carbon_reverse/ar_cuts_v1')\n", + " # savePath.mkdir(exist_ok=True)\n", + " # fig.savefig(savePath.joinpath( \n", + " # f'{sample_name}_{intensity_type}_chiWidth-{chi_width}deg_q-{q_slice.start}-{q_slice.stop}_pol{pol}deg.png'), dpi=120)\n", + "\n", + " plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "67", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# make selection, individual polarizations\n", + "edge = 'carbon'\n", + "# DS = rsoxs_datasets[f'polar_{edge}']\n", + "DS = rsoxs_datasets[f'polar_{edge}_tilted']\n", + "\n", + "intensity_type = 'corr'\n", + "chi_width = 90\n", + "q_slice = slice(0.009, 0.08)\n", + "e_slice = slice(282, 292)\n", + "\n", + "for sample_name in tqdm(DS.sample_name.values[:]):\n", + " for pol in [0, 45, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, (q_slice.start,q_slice.stop), chi_width) \n", + "\n", + " # Select AR data\n", + " ar_DA = (para_DA.mean('chi') - perp_DA.mean('chi')) / (para_DA.mean('chi') + perp_DA.mean('chi'))\n", + "\n", + " # Plot \n", + " energies = para_DA.energy.sel(energy=[260, 275, 283, 284, 284.4, 284.8, 285.2, 285.6, 286.2, 287, 300, 338.75], method='nearest').data\n", + " cmap = plt.cm.turbo.copy()\n", + " colors = cmap(np.linspace(0, 1, len(energies))) \n", + "\n", + " # # Create a ScalarMappable object with the colormap and normalization & add the colorbar to the figure\n", + " # sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=energies[0], vmax=energies[-1]))\n", + " # cax = ax.inset_axes([1.03, 0, 0.03, 1])\n", + " # cbar = fig.colorbar(sm, cax=cax, orientation='vertical')\n", + " # cbar.set_label(label=f'Time [seconds]', labelpad=14)\n", + " # cbar.set_ticks(np.round(np.linspace(energies[0], energies[-1], len(energies)), 2))\n", + "\n", + " fig, ax = plt.subplots(tight_layout=True, figsize=(6,4), dpi=120)\n", + "\n", + " for j, energy in enumerate(energies):\n", + " (ar_DA.sel(energy=energy).plot.line(ax=ax, color=colors[j], label=energy, xscale='log'))\n", + "\n", + " fig.suptitle(f'Anisotropy Ratio Linecuts: {sample_name}', x=0.46, y=0.95)\n", + "\n", + " # ax.set(title=f'Chi width = {chi_width}°, Pol = {pol}°', ylim=(-0.5, 0.5), ylabel='AR [arb. units]', xlabel='Q [$Å^{-1}$]')\n", + " ax.set(title=f'Chi width = {chi_width}°, Pol = {pol}°', ylabel='AR [arb. units]', xlabel='Q [$Å^{-1}$]')\n", + "\n", + " ax.legend(title='Energy [eV]', loc=(1.03,0.02))\n", + "\n", + " # savePath = plotsPath.joinpath('rsoxs_carbon_tilted/ar_cuts_v1')\n", + " # savePath.mkdir(exist_ok=True)\n", + " # fig.savefig(savePath.joinpath( \n", + " # f'{sample_name}_{intensity_type}_chiWidth-{chi_width}deg_q-{q_slice.start}-{q_slice.stop}_pol{pol}deg.png'), dpi=120)\n", + "\n", + " # plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "markdown", + "id": "0e9b442a-445c-44bb-a33a-32fc22d96ebc", + "metadata": { + "tags": [] + }, + "source": [ + "### Para - perp log scale intensity" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "86f843a0-31a6-4a7c-8f17-2cf913023ecc", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "%matplotlib inline" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "31d4f831-1c2a-4caf-b0bf-ba15d10fdd75", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "plotsPath" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "db1d2486-0162-4a03-aff0-622b98785baa", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "porod_slice" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1846f720-250d-4fff-b5ba-f9a04f6e7647", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "DS" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "66236e9a-3631-44b4-8a1b-6d4d00fca16b", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "DS" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8b3afd1e-fcd9-4c27-b71c-c4a37858810a", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "%matplotlib inline" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "33ad047b-fae3-41d2-80f4-8ae6bc42fd6b", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# make selection\n", + "edge = 'carbon'\n", + "# DS = rsoxs_datasets[f'polar_{edge}']\n", + "# DS = rsoxs_datasets[f'polar_{edge}_tilted']\n", + "\n", + "intensity_type = 'raw'\n", + "chi_width = 90\n", + "q_slice = slice(0.01, None)\n", + "e_slice = slice(282, 292)\n", + "porod_slices = []\n", + "# porod_slices = [slice(0.0107, 0.0138), # Calculate 1 degree polynomial (straigh line) through these regions\n", + "# slice(0.0107, 0.0240),\n", + "# slice(0.0250, 0.0500),\n", + "# slice(0.0500, 0.0800)]\n", + "\n", + "# selected_samples = ['PM6_CB', 'PM6_p5CN-CB', 'PM6_1CN-CB', 'PM6_5CN-CB', \n", + "# 'PM6_CF', 'PM6_p5CN-CF', 'PM6_1CN-CF', 'PM6_5CN-CF', \n", + "# 'PM6_4CF-1CB', 'PM6_2CF-3CB', 'PM6_p5CN-2CF-3CB'] \n", + "# selected_samples = ['PM6_5CN-CB', 'PM6_CF']\n", + "\n", + "# plt.close('all')\n", + "\n", + "all_slopes = {}\n", + "for sample_name in DS.sample_name.values[:]:\n", + "# for sample_name in tqdm(selected_samples):\n", + " pol_paras = []\n", + " pol_perps = []\n", + " slopes = {}\n", + " for pol in [0, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, (q_slice.start,q_slice.stop), chi_width) \n", + " pol_paras.append(para_DA)\n", + " pol_perps.append(perp_DA)\n", + "\n", + "\n", + " pol_paras[0] = pol_paras[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_paras[1] = pol_paras[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + " pol_perps[1] = pol_perps[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " pol_paras[0] = pol_paras[0].interp({'chi': pol_paras[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].interp({'chi': pol_perps[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " para_DA = (pol_paras[0] + pol_paras[1])/2\n", + " perp_DA = (pol_perps[0] + pol_perps[1])/2\n", + "\n", + " para_DA = para_DA.assign_coords({'polarization':'avg'})\n", + " perp_DA = perp_DA.assign_coords({'polarization':'avg'})\n", + "\n", + " para_DA = para_DA.interpolate_na(dim='q')\n", + " perp_DA = perp_DA.interpolate_na(dim='q')\n", + "\n", + " pol = str(para_DA.polarization.values) \n", + "\n", + " # Select AR data\n", + " # ar_DA = (para_DA.mean('chi') - perp_DA.mean('chi')) # / (para_DA.mean('chi') + perp_DA.mean('chi'))\n", + " ar_DA = np.abs(para_DA.mean('chi') - perp_DA.mean('chi')) # / (para_DA.mean('chi') + perp_DA.mean('chi'))\n", + "\n", + " # Plot \n", + " energies = para_DA.energy.sel(energy=[270, 283, 284.4, 284.8, 284.9, 285, 285.1, 285.2, 285.3, 285.4, 286.2, 338.75], method='nearest').data\n", + " cmap = plt.cm.turbo.copy()\n", + " colors = cmap(np.linspace(0, 1, len(energies))) \n", + "\n", + " # # Create a ScalarMappable object with the colormap and normalization & add the colorbar to the figure\n", + " # sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=energies[0], vmax=energies[-1]))\n", + " # cax = ax.inset_axes([1.03, 0, 0.03, 1])\n", + " # cbar = fig.colorbar(sm, cax=cax, orientation='vertical')\n", + " # cbar.set_label(label=f'Time [seconds]', labelpad=14)\n", + " # cbar.set_ticks(np.round(np.linspace(energies[0], energies[-1], len(energies)), 2))\n", + "\n", + " fig, ax = plt.subplots(tight_layout=True, figsize=(6,4), dpi=120)\n", + "\n", + " for j, energy in enumerate(tqdm(energies, desc='Plotting & fitting slopes per energy')):\n", + " sel_DA = ar_DA.sel(energy=energy)\n", + " sel_DA.plot.line(ax=ax, color=colors[j], label=energy, xscale='log', yscale='log',\n", + " linestyle='None', marker='.', markersize=3)\n", + " \n", + " porod_slopes = {}\n", + " for porod_slice in porod_slices:\n", + " m, b = np.polyfit(np.log(sel_DA.sel(q=porod_slice).q.data), np.log(sel_DA.sel(q=porod_slice).data.compute()), deg=1)\n", + " # display(porod_slice, m) \n", + " porod_slopes[f'{porod_slice.start}-{porod_slice.stop}'] = np.round(m, 2)\n", + " \n", + " slopes[energy] = porod_slopes\n", + " \n", + " all_slopes[sample_name] = slopes\n", + " fig.suptitle(f'$\\parallel$ - $\\perp$ Intensity Absolute Difference: {sample_name}', x=0.46, y=0.95)\n", + "\n", + " ax.set(title=f'Chi width = {chi_width}°, Pol = {pol}°', ylim=(1e0, None), ylabel='Intensity [arb. units]', xlabel='Q [$Å^{-1}$]')\n", + " # ax.set(title=f'Chi width = {chi_width}°, Pol = {pol}°', ylim=(None, None), ylabel='AR [arb. units]', xlabel='Q [$Å^{-1}$]')\n", + " ax.axes.grid(visible=True, which='both', axis='x')\n", + " legend = ax.legend(title='Energy [eV]', loc=(1.03,0.02))\n", + " for handle in legend.legend_handles:\n", + " handle.set_markersize(15)\n", + " \n", + " savePath = plotsPath.joinpath('rsoxs_carbon_para-perp_cuts_v1')\n", + " savePath.mkdir(exist_ok=True)\n", + " fig.savefig(savePath.joinpath( \n", + " f'{sample_name}_{intensity_type}_chiWidth-{chi_width}deg_q-{q_slice.start}-{q_slice.stop}_pol{pol}deg.png'), dpi=120)\n", + "\n", + " plt.show()\n", + " plt.close('all')\n", + " \n", + "# # Save all_slopes.json in same save folder\n", + "# json_data = json.dumps(all_slopes)\n", + "# with open(str(savePath.joinpath('all_slopes.json')), 'w') as f:\n", + "# f.write(json_data)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f5d9e41c-30ce-4cb4-8925-77eb5458794b", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "plotsPath" + ] + }, + { + "cell_type": "markdown", + "id": "5d5f6bb9-902c-41b8-ad22-fcc43ff6fbbf", + "metadata": { + "tags": [] + }, + "source": [ + "### Load solution SAXS PM6 data text files" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "70d77d1e-9af4-4ebd-b9cc-bfacb358c4db", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "from scipy.ndimage import gaussian_filter1d" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0636b9fd-ca0b-4415-bec3-7c4b248742cc", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Check files\n", + "saxsPath = pathlib.Path('/nsls2/data/sst/proposals/2024-2/pass-313412/processed_data/solution_saxs_txts')\n", + "# saxsPath = pathlib.Path('/nsls2/data/sst/proposals/2023-3/pass-313412/processed_data/prsoxs_plots/carbon/PM6_solution_saxs_txts')\n", + "# saxsPath = outPath.joinpath('prsoxs_plots/carbon/PM6_solution_saxs_txts')\n", + "display([f.name for f in sorted(saxsPath.glob('*'))[:8]])\n", + "display([f.name for f in sorted(saxsPath.glob('*'))[8:]])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0172aab0-eafb-4c46-ab09-6f5a02934f41", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "saxs_arrs = {}\n", + "\n", + "for f in sorted(saxsPath.glob('*')):\n", + " # print('_'.join(f.name.split('_')[:2]))\n", + " var_name = '_'.join(f.name.split('_')[:2])\n", + " saxs_arrs[var_name] = np.loadtxt(f)\n", + "\n", + "saxs_arrs.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "afa1cb23-a5b6-4c0f-a1d6-5ed7daeef01c", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Load data into dict of numpy arrays\n", + "saxs_arrs = {}\n", + "\n", + "for f in sorted(saxsPath.glob('*')):\n", + " # print('_'.join(f.name.split('_')[:2]))\n", + " var_name = '_'.join(f.name.split('_')[:2])\n", + " saxs_arrs[var_name] = np.loadtxt(f)\n", + "\n", + "# saxs_arrs.keys()\n", + "\n", + "# Smooth saxs with gaussian filter:\n", + "sigma = 3 # In pixels\n", + "for var_name, arr in saxs_arrs.items():\n", + " saxs_arrs[var_name][:,1] = gaussian_filter1d(arr[:,1], sigma)\n", + " \n", + "# Put numpy arrays into DataArrays\n", + "# saxs_DAs = []\n", + "saxs_DS = xr.Dataset(attrs={'name':'PM6_Solution_SAXS'})\n", + "for var_name, arr in saxs_arrs.items():\n", + " saxs_DA = xr.DataArray(data=arr[:,1], dims=['q'], coords={'q':arr[:,0], 'err':('q', arr[:,2])})\n", + " saxs_DS[var_name] = saxs_DA\n", + "\n", + "saxs_DS" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e19cd7ba-a46e-4940-b8a5-eee9a0ddd124", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# # Ensure q values are equal between datasets, else interpolation needed\n", + "# print(np.array_equal(pm6_cb[:,0], pm6_cf[:,0]))\n", + "# print(np.array_equal(pm6_cf[:,0], pm6_cn[:,0]))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0e32d76a-bfa6-45ec-bcac-8407a67aefee", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# qmin = 0.008\n", + "qmin = None\n", + "# qmax = float(full_DS.q.max())\n", + "qmax = None\n", + "\n", + "plt.close('all')\n", + "fig, ax = plt.subplots()\n", + "for sample in ['PM6_CB', 'PM6_CF', 'PM6_CN', 'PM6_TO']:\n", + "# for sample in saxs_DS.data_vars:\n", + " saxs_DS[sample].sel(q=slice(qmin,qmax)).plot.line(ax=ax, xscale='log',yscale='log', label=sample)\n", + "\n", + "ax.set_ybound(lower=1e-5)\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8524ee46-60e3-4f04-8834-799bd31e58eb", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# qmin = 0.008\n", + "qmin = None\n", + "# qmax = float(full_DS.q.max())\n", + "qmax = None\n", + "\n", + "plt.close('all')\n", + "fig, ax = plt.subplots()\n", + "# for sample in ['PM6_CB', 'PM6_CF', 'PM6_CN', 'PM6_TO']:\n", + "for sample in ['PM7_CB', 'PM7_CF', 'PM7_CN', 'PM7_TO']:\n", + "# for sample in saxs_DS.data_vars:\n", + " saxs_DS[sample].sel(q=slice(qmin,qmax)).plot.line(ax=ax, xscale='log',yscale='log', label=sample)\n", + "\n", + "ax.set_ybound(lower=1e-5)\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "872a7441-d6fa-4bbb-9b07-343c9ecc38ce", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "%matplotlib widget" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "13675f77-1532-4ba9-8d23-96ab75f6da69", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# qmin = 0.008\n", + "qmin = None\n", + "# qmax = float(full_DS.q.max())\n", + "qmax = None\n", + "\n", + "plt.close('all')\n", + "fig, ax = plt.subplots()\n", + "for sample in ['Y6_CN', 'Y7_CB', 'Y7_CN']:\n", + "# for sample in ['Y7_CB', 'Y7_CN']:\n", + " saxs_DS[sample].sel(q=slice(qmin,qmax)).plot.line(ax=ax, xscale='log',yscale='log', label=sample)\n", + "\n", + "ax.set_ybound(lower=1e-5)\n", + "ax.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "5efe12b9-9fe0-46a6-8016-17e1c3a5b487", + "metadata": { + "tags": [] + }, + "source": [ + "### Plot para-perp P-RSoXS + solution SAXS overlays" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9fcc3eca-810a-4e78-aaf1-b56a5a3446f8", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "%matplotlib widget" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cb5ee819-0c2f-4762-9f28-dab000c96fe4", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a3618e55-f0af-40fd-8248-a2cd5bff3d3a", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "sn = {\n", + " 'PM6_CF': 'PM6, CF',\n", + " 'PM6_5CN-CF': 'PM6, CF 5%CN',\n", + " 'PM6_5CN-CB': 'PM6, CB 5%CN'\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e8b407ed-ec6d-46de-8886-7c81e2159acb", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "DS" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ff87390e-3357-470b-912e-a93173001caf", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "%matplotlib widget" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ecd14ae1-3e5b-4d03-84d7-87e5b2a9e2f7", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "DS.sample_name.values" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4ab82cd2-17b1-4bfe-9c10-522853cf3bf6", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# make selection\n", + "edge = 'carbon'\n", + "# DS = rsoxs_datasets[f'polar_{edge}']\n", + "\n", + "intensity_type = 'raw'\n", + "soln_mat = 'PM7'\n", + "chi_width = 90\n", + "q_slice = slice(0.01, None)\n", + "# e_slice = slice(282, 292)\n", + "energy = 285.2\n", + "# energy = 284.8\n", + "# energies = [260, 283, 284.4, 284.8, 285.2, 286.2, 338.75]\n", + "# shift_qval = 0.0104 # value by which to look to shift data, divide rsoxs by this value\n", + "shift_qval = 0.02 # value by which to look to shift data, divide rsoxs by this value\n", + "# shift_qval = 0.05\n", + "\n", + "# selected_samples = ['PM6_CB', 'PM6_p5CN-CB', 'PM6_1CN-CB', 'PM6_5CN-CB', \n", + "# 'PM6_CF', 'PM6_p5CN-CF', 'PM6_1CN-CF', 'PM6_5CN-CF', \n", + "# 'PM6_4CF-1CB', 'PM6_2CF-3CB', 'PM6_p5CN-2CF-3CB'] \n", + "# selected_samples = ['PM6_CF', 'PM6_5CN-CB']\n", + "# selected_samples = ['PM6_5CN-CF']\n", + "# selected_samples = ['PM6_CB', 'PM6_p5CN-CB', 'PM6_1CN-CB', 'PM6_5CN-CB']\n", + "\n", + "# selected_samples = ['PM6_CF', 'PM6_p5CN-CF', 'PM6_1CN-CF', 'PM6_5CN-CF']\n", + "# selected_samples = [f'{soln_mat}_CF', f'{soln_mat}_p5CN-CF', f'{soln_mat}_1CN-CF', f'{soln_mat}_5CN-CF']\n", + "# selected_samples = [f'{soln_mat}_p5CN-CB', f'{soln_mat}_1CN-CB', f'{soln_mat}_5CN-CB']\n", + "selected_samples = [f'{soln_mat}_CF', f'{soln_mat}_5CN-CB', f'{soln_mat}_TO']\n", + "\n", + "# selected_samples = ['PM6_4CF-1CB', 'PM6_2CF-3CB', 'PM6_p5CN-2CF-3CB']\n", + "\n", + "# selected_samples = ['Y6_CF', 'Y6_p5CN-CF', \n", + "# 'Y6_4CF-1CB', 'Y6_2CF-3CB', 'Y6_p5CN-2CF-3CB', \n", + "# 'Y6_CB', 'Y6_p5CN-CB',\n", + "# 'Y6BO_CF', 'Y6BO_p5CN-CF', 'Y6BO_CB', 'Y6BO_p5CN-CB']\n", + "# selected_samples = ['Y6_4CF-1CB', 'Y6_2CF-3CB', 'Y6_p5CN-2CF-3CB']\n", + "# selected_samples = ['Y6_CB', 'Y6_p5CN-CB']\n", + "\n", + "# saxs_samples = ['PM6_CF', 'PM6_CB', 'PM6_CN']\n", + "# saxs_samples = [f'{soln_mat}_CF', f'{soln_mat}_CB', f'{soln_mat}_CN', f'{soln_mat}_TO']\n", + "saxs_samples = [f'{soln_mat}_CF', f'{soln_mat}_CN', f'{soln_mat}_TO']\n", + "\n", + "# saxs_samples = ['PM6_CF', 'PM6_CN']\n", + "# saxs_samples = ['Y6_CN', 'Y7_CN', 'Y7_CB']\n", + "saxs_sample_to_align = f'{soln_mat}_CN'\n", + "selected_qval = float(saxs_DS[saxs_sample_to_align].sel(q=shift_qval, method='nearest'))\n", + "\n", + "# Shift all saxs to line up with selected sample qval\n", + "factor1 = selected_qval / float(saxs_DS[f'{soln_mat}_CB'].sel(q=shift_qval, method='nearest'))\n", + "factor2 = selected_qval / float(saxs_DS[f'{soln_mat}_CF'].sel(q=shift_qval, method='nearest'))\n", + "factor3 = selected_qval / float(saxs_DS[f'{soln_mat}_TO'].sel(q=shift_qval, method='nearest'))\n", + "pm6_cb_shifted = saxs_DS[f'{soln_mat}_CB'] * factor1\n", + "pm6_cf_shifted = saxs_DS[f'{soln_mat}_CF'] * factor2\n", + "pm6_to_shifted = saxs_DS[f'{soln_mat}_TO'] * factor3\n", + "\n", + "# factor1 = selected_qval / float(saxs_DS['Y7_CN'].sel(q=shift_qval, method='nearest'))\n", + "# factor2 = selected_qval / float(saxs_DS['Y7_CB'].sel(q=shift_qval, method='nearest'))\n", + "# y7_cn_shifted = saxs_DS['Y7_CN'] * factor1\n", + "# y7_cb_shifted = saxs_DS['Y7_CB'] * factor2\n", + "\n", + "# saxs_colors = plt.cm.RdPu(np.linspace(0.4,1,len(saxs_samples)))\n", + "saxs_colors = plt.cm.Blues(np.linspace(0.5,1,len(saxs_samples)))\n", + "plt.close('all')\n", + "\n", + "# for selected_samples in (['Y6_CF', 'Y6_p5CN-CF'],\n", + "# ['Y6_4CF-1CB', 'Y6_2CF-3CB', 'Y6_p5CN-2CF-3CB'], \n", + "# ['Y6_CB', 'Y6_p5CN-CB']):\n", + "# for selected_samples in (['PM6_CB', 'PM6_p5CN-CB', 'PM6_1CN-CB', 'PM6_5CN-CB'],\n", + "# ['PM6_CF', 'PM6_p5CN-CF', 'PM6_1CN-CF', 'PM6_5CN-CF'],\n", + "# ['PM6_4CF-1CB', 'PM6_2CF-3CB', 'PM6_p5CN-2CF-3CB']):\n", + "rsoxs_colors = plt.cm.Blues(np.linspace(0.3,0.8,len(selected_samples)))\n", + "fig, ax = plt.subplots(tight_layout=True, figsize=(4.8,4.3), dpi=130)\n", + "for i, sample_name in enumerate(tqdm(selected_samples)):\n", + " pol_paras = []\n", + " pol_perps = []\n", + " for pol in [0, 90]:\n", + " para_DA, perp_DA = make_para_perp_DAs(DS, sample_name, intensity_type, pol, (q_slice.start,q_slice.stop), chi_width) \n", + " pol_paras.append(para_DA)\n", + " pol_perps.append(perp_DA)\n", + "\n", + "\n", + " pol_paras[0] = pol_paras[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_paras[1] = pol_paras[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_paras[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[0].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + " pol_perps[1] = pol_perps[1].assign_coords({'chi': np.linspace(0, chi_width, len(pol_perps[1].chi.values))}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " pol_paras[0] = pol_paras[0].interp({'chi': pol_paras[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_paras[1].chi.values))})\n", + " pol_perps[0] = pol_perps[0].interp({'chi': pol_perps[1].chi.values}) # .assign_coords({'chi': np.linspace(0, 90,len(pol_perps[1].chi.values))})\n", + "\n", + " para_DA = (pol_paras[0] + pol_paras[1])/2\n", + " perp_DA = (pol_perps[0] + pol_perps[1])/2\n", + "\n", + " para_DA = para_DA.assign_coords({'polarization':'avg'})\n", + " perp_DA = perp_DA.assign_coords({'polarization':'avg'})\n", + "\n", + " para_DA = para_DA.interpolate_na(dim='q')\n", + " perp_DA = perp_DA.interpolate_na(dim='q')\n", + "\n", + " pol = str(para_DA.polarization.values) \n", + "\n", + " # Select AR data\n", + " ar_DA = (para_DA.mean('chi') - perp_DA.mean('chi')) # / (para_DA.mean('chi') + perp_DA.mean('chi'))\n", + " DA = ar_DA.sel(energy=energy, method='nearest')\n", + "\n", + " # Shift RSoXS to line up with SAXS\n", + " rsoxs_qval = float(DA.sel(q=shift_qval, method='nearest'))\n", + " rsoxs_shift_factor = selected_qval / rsoxs_qval\n", + " DA = DA * rsoxs_shift_factor\n", + "\n", + " # Plot rsoxs diff profile:\n", + " DA.plot.line(ax=ax, color=rsoxs_colors[i], label=f'Film RSoXS: {sample_name}', \n", + " linestyle='None', marker='.', markersize=3)\n", + " \n", + "pm6_cf_shifted.plot.line(ax=ax, color=saxs_colors[0], label=f'Solution SAXS: {soln_mat} in CF') \n", + "# pm6_cb_shifted.plot.line(ax=ax, color=saxs_colors[2], label=f'Solution SAXS: {soln_mat} in CB')\n", + "# y7_cn_shifted.plot.line(ax=ax, color=saxs_colors[1], label='Solution: Y7 in CN') \n", + "# y7_cb_shifted.plot.line(ax=ax, color=saxs_colors[0], label='Solution: Y7 in CB') \n", + "saxs_DS[saxs_sample_to_align].plot.line(ax=ax, color=saxs_colors[1], label=f'Solution SAXS: {soln_mat} in CN') \n", + "pm6_to_shifted.plot.line(ax=ax, color=saxs_colors[2], label=f'Solution SAXS: {soln_mat} in TO')\n", + "\n", + "\n", + "ax.set(xscale='log', yscale='log', ylabel='Intensity [arb. units]', xlabel='Q [$Å^{-1}$]')\n", + "ax.set(title=f'{soln_mat} film P-RSoXS and solution SAXS overlays \\n RSoXS profile: $I_\\parallel(Q, E) - I_\\perp(Q, E)$, $E={energy}$ eV', ylim=(None, None), xlim=(None, 0.4))\n", + "ax.grid(visible=True, which='both', axis='x')\n", + "# ax.legend(title='Sample', loc=(1.02,0.2))\n", + "AA_str = '$Å^{-1}$'\n", + "legend = ax.legend(title=f'Data plotted:')\n", + "for handle in legend.legend_handles:\n", + " handle.set_markersize(18)\n", + "\n", + "plt.show()\n", + "# plt.close('all')" + ] + }, + { + "cell_type": "markdown", + "id": "70", + "metadata": { + "jp-MarkdownHeadingCollapsed": true, + "tags": [] + }, + "source": [ + "## Loop for saving many plots" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "71", + "metadata": {}, + "outputs": [], + "source": [ + "rsoxs_datasets['polar_oxygen']" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "72", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# make selection\n", + "edge = 'oxygen'\n", + "intensity_type = 'corr'\n", + "qlims = (0.01, 0.08)\n", + "chi_width = 30\n", + "energy_min = 525\n", + "energy_max = 545\n", + "cmin = 5e8\n", + "cmax = 5e10\n", + "\n", + "for sample_name in tqdm(rsoxs_datasets[f'polar_{edge}'].sample_name.data):\n", + " for pol in [0, 90]:\n", + " ### Select para & perp DataArrays\n", + " para_DA, perp_DA = make_para_perp_DAs(rsoxs_datasets, sample_name, edge, intensity_type, pol, qlims, chi_width) \n", + " \n", + " ### ISI:\n", + " # Slice ISI data\n", + " para_ISI = para_DA.interpolate_na(dim='q').mean('chi').sum('q')\n", + " perp_ISI = perp_DA.interpolate_na(dim='q').mean('chi').sum('q')\n", + " \n", + " # Plot\n", + " fig, ax = plt.subplots()\n", + " para_ISI.sel(energy=slice(energy_min,energy_max)).plot.line(ax=ax, label='para', yscale='log')\n", + " perp_ISI.sel(energy=slice(energy_min,energy_max)).plot.line(ax=ax, label='perp', yscale='log')\n", + " # para_ISI.plot.line(ax=ax, label='para', yscale='log')\n", + " # perp_ISI.plot.line(ax=ax, label='perp', yscale='log') \n", + " fig.suptitle('Integrated Scattering Intensity (ISI)', fontsize=14)\n", + " ax.set(title=f'{sample_name}, Polarization = {pol}°, Chi Width = {chi_width}°', xlabel='Photon Energy [eV]', ylabel='Double-Norm-Corrected Intensity [arb. units]')\n", + " ax.legend()\n", + " fig.savefig(plotsPath.joinpath('isi_oxygen_v1', f'{sample_name}_{edge}_{intensity_type}_chiWidth-{chi_width}deg_pol{pol}deg.png'), dpi=120)\n", + " # plt.show()\n", + " plt.close('all')\n", + " \n", + " ### Linecut Maps:\n", + " fig, axs = plt.subplots(1, 2, figsize=(11,5))\n", + "\n", + " para_DA.mean('chi').sel(energy=slice(energy_min,energy_max)).plot(ax=axs[0], cmap=cmap, norm=LogNorm(cmin, cmax), add_colorbar=False)\n", + " perp_DA.mean('chi').sel(energy=slice(energy_min,energy_max)).plot(ax=axs[1], cmap=cmap, norm=LogNorm(cmin, cmax), add_colorbar=False)\n", + "\n", + " sm = plt.cm.ScalarMappable(cmap=cmap, norm=LogNorm(cmin, cmax)) # Create a ScalarMappable object with the colormap and normalization & add the colorbar to the figure\n", + " cax = axs[1].inset_axes([1.03, 0, 0.05, 1])\n", + " cbar = fig.colorbar(sm, cax=cax, orientation='vertical')\n", + " cbar.set_label(label='Intensity [arb. units]', labelpad=12)\n", + " fig.suptitle(f'Linecut Maps: {sample_name}, Polarization = {pol}°, Chi Width = {chi_width}°', fontsize=14)\n", + " fig.set(tight_layout=True)\n", + " axs[0].set(title='Parallel to $E_p$', ylabel='Photon energy [eV]', xlabel='q [$Å^{-1}$]')\n", + " axs[1].set(title='Perpendicular to $E_p$ ', ylabel=None, xlabel='q [$Å^{-1}$]')\n", + " fig.savefig(plotsPath.joinpath('linecut_maps_oxygen_v1', f'{sample_name}_{edge}_{intensity_type}_chiWidth-{chi_width}deg_pol{pol}deg.png'), dpi=120)\n", + " # plt.show()\n", + " plt.close('all')\n", + "\n", + " ### AR Maps:\n", + " # Select AR data\n", + " ar_DA = (para_DA.mean('chi') - perp_DA.mean('chi')) / (para_DA.mean('chi') + perp_DA.mean('chi'))\n", + "\n", + " if para_DA.sample_name=='BareSiN':\n", + " bareSiN_ar_DA = ar_DA.copy()\n", + " \n", + " # # Subtract AR from SiN:\n", + " # ar_DA = ar_DA - bareSiN_ar_DA\n", + "\n", + " # Plot\n", + " ax = ar_DA.sel(energy=slice(energy_min,energy_max)).plot(figsize=(8,5), norm=plt.Normalize(-0.6, 0.6))\n", + " ax.figure.suptitle('Anisotropy Ratio (AR) Map', fontsize=14, x=0.43)\n", + " ax.axes.set(title=f'{sample_name}, Polarization = {pol}°, Chi Width = {chi_width}°', ylabel='Photon Energy [eV]', xlabel='q [$Å^{-1}$]')\n", + " ax.colorbar.set_label('AR [arb. units]', rotation=270, labelpad=12)\n", + " ax.figure.savefig(plotsPath.joinpath('ar_maps_oxygen_v1', f'{sample_name}_{edge}_{intensity_type}_chiWidth-{chi_width}deg_pol{pol}deg.png'), dpi=120)\n", + " # plt.show()\n", + " plt.close('all')" + ] + }, + { + "cell_type": "markdown", + "id": "73", + "metadata": { + "jp-MarkdownHeadingCollapsed": true, + "tags": [] + }, + "source": [ + "## Incorporating simulation output\n", + "old and incomplete" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "74", + "metadata": {}, + "outputs": [], + "source": [ + "import h5py" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "75", + "metadata": {}, + "outputs": [], + "source": [ + "whos PosixPath" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "76", + "metadata": {}, + "outputs": [], + "source": [ + "simsPath = rootPath.joinpath('imgs_analysis/sim_runs')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "77", + "metadata": {}, + "outputs": [], + "source": [ + "[f.name for f in simPath.iterdir()]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "78", + "metadata": {}, + "outputs": [], + "source": [ + "simPath = simsPath.joinpath('D1.0_a1.0_eps1.0_250pix_375size_0.5m_600steps_1')\n", + "h5path = simPath.joinpath('HDF5')\n", + "h5list = sorted(h5path.glob('E*h5'))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "79", + "metadata": {}, + "outputs": [], + "source": [ + "def print_key(f, key):\n", + " try:\n", + " keys2 = f[key].keys()\n", + " for key2 in keys2:\n", + " new_key = key + '/' + key2\n", + " print_key(f, new_key)\n", + " except AttributeError:\n", + " print(key)\n", + "\n", + "with h5py.File(h5list[0],'r') as f:\n", + " for key in f.keys():\n", + " print_key(f, key)" + ] + }, + { + "cell_type": "markdown", + "id": "80", + "metadata": {}, + "source": [ + "#### The scattering pattern is contained within 'K0/projection.' If you simulated multiple incident angles there would be additional 'K#' keys. KIDList contains the vector values for each of the incident angles (propagation direction)." + ] + }, + { + "cell_type": "markdown", + "id": "81", + "metadata": {}, + "source": [ + "#### Instantiate the PyHyperScattering loader and integrator" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "82", + "metadata": {}, + "outputs": [], + "source": [ + "load = phs.load.cyrsoxsLoader(use_chunked_loading=True)\n", + "integ = phs.integrate.WPIntegrator(force_np_backend=True) # avoiding gpu backend for this tutorial" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "83", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "raw = load.loadDirectory(simPath)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84", + "metadata": {}, + "outputs": [], + "source": [ + "raw" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "85", + "metadata": {}, + "outputs": [], + "source": [ + "remeshed = integ.integrateImageStack(raw)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "86", + "metadata": {}, + "outputs": [], + "source": [ + "remeshed" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "87", + "metadata": {}, + "outputs": [], + "source": [ + "remeshed.sel(energy=285.1).plot()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "88", + "metadata": {}, + "outputs": [], + "source": [ + "# c = cm.jet(np.linspace(0,1,len(remeshed)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "89", + "metadata": {}, + "outputs": [], + "source": [ + "fig, ax = plt.subplots(1,3,figsize=(10,3),dpi=140,constrained_layout=True)\n", + "raw.sel(energy=275).plot(norm=LogNorm(1e-7,1),cmap='terrain',ax=ax[0],add_colorbar=False)\n", + "raw.sel(energy=285).plot(norm=LogNorm(1e-7,1),cmap='terrain',ax=ax[1],add_colorbar=False)\n", + "raw.sel(energy=295).plot(norm=LogNorm(1e-7,1),cmap='terrain',ax=ax[2])\n", + "\n", + "[{axes.set_xlim(-0.1,0.1),axes.set_ylim(-0.1,0.1)} for axes in ax]\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "90", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "loaded_rsoxs.build_tiff_stack??" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "91", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}