### Setup: Import Libraries and Initialize miepython Source: https://github.com/scottprahl/miepython/blob/main/docs/05_fog.ipynb This snippet initializes the environment for Mie scattering calculations. It imports necessary libraries like numpy, matplotlib, and scipy, and sets up the miepython library, including conditional installation for jupyterlite environments and disabling JIT compilation. ```python %config InlineBackend.figure_format = 'retina' import os import sys import numpy as np import matplotlib.pyplot as plt from scipy import stats # needed for lognormal distribution if sys.platform == "emscripten": import piplite await piplite.install("miepython", deps=False) os.environ["MIEPYTHON_USE_JIT"] = "0" # jupyterlite cannot use numba import miepython as mie ``` -------------------------------- ### Import Miepython and Setup for JupyterLite Source: https://github.com/scottprahl/miepython/blob/main/docs/10_basic_tests.ipynb This snippet sets up the environment for running Miepython tests, including installing the library via piplite for jupyterlite and configuring matplotlib. It also imports necessary libraries like numpy, unittest, and os. ```python %config InlineBackend.figure_format = 'retina' import os import sys import unittest import numpy as np import matplotlib.pyplot as plt if sys.platform == "emscripten": import piplite await piplite.install("miepython", deps=False) os.environ["MIEPYTHON_USE_JIT"] = "0" # jupyterlite cannot use numba import miepython as mie ``` -------------------------------- ### Setup Mie Resonance Analysis Environment with miepython Source: https://github.com/scottprahl/miepython/blob/main/docs/13_resonance.ipynb Initializes the Python environment for Mie resonance calculations. Installs the 'miepython' library if running in a JupyterLite environment and configures matplotlib for high-resolution figures. It also sets an environment variable to disable JIT compilation in environments where it's not supported. ```python %config InlineBackend.figure_format = 'retina' import os import sys import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize_scalar if sys.platform == "emscripten": import piplite await piplite.install("miepython", deps=False) os.environ["MIEPYTHON_USE_JIT"] = "0" # jupyterlite cannot use numba import miepython as mie ``` -------------------------------- ### Import Mie Scattering Libraries and Setup Source: https://github.com/scottprahl/miepython/blob/main/docs/07_algorithm.ipynb Imports necessary libraries for Mie scattering calculations and plotting, including miepython and SciPy's spherical Bessel functions. It also includes platform-specific setup for emscripten environments, disabling JIT compilation. ```python %config InlineBackend.figure_format = 'retina' import os import sys import numpy as np import matplotlib.pyplot as plt from scipy.special import spherical_jn, spherical_yn if sys.platform == "emscripten": import piplite await piplite.install("miepython", deps=False) os.environ["MIEPYTHON_USE_JIT"] = "0" # jupyterlite cannot use numba import miepython as mie from miepython.util import cs ``` -------------------------------- ### Import miepython and Set Up Environment Source: https://github.com/scottprahl/miepython/blob/main/docs/02_efficiencies.ipynb This code snippet initializes the necessary libraries for Mie scattering calculations, including `miepython`, `numpy`, and `matplotlib`. It also includes conditional setup for `jupyterlite` environments, disabling Numba JIT compilation if necessary. ```python %config InlineBackend.figure_format = 'retina' import os import sys import imageio.v3 as iio import numpy as np import matplotlib.pyplot as plt import importlib.resources if sys.platform == "emscripten": import piplite await piplite.install("miepython", deps=False) os.environ["MIEPYTHON_USE_JIT"] = "0" # jupyterlite cannot use numba import miepython as mie ``` -------------------------------- ### Import miepython and necessary libraries Source: https://github.com/scottprahl/miepython/blob/main/docs/01_basics.ipynb This snippet imports the miepython library along with other essential libraries like numpy and matplotlib for numerical operations and plotting. It also includes conditional installation for emscripten environments. ```python %config InlineBackend.figure_format = 'retina' import os import sys import numpy as np import matplotlib.pyplot as plt import importlib.resources if sys.platform == "emscripten": import piplite await piplite.install("miepython", deps=False) os.environ["MIEPYTHON_USE_JIT"] = "0" # jupyterlite cannot use numba import miepython as mie ``` -------------------------------- ### Install miepython using pip or conda Source: https://github.com/scottprahl/miepython/blob/main/README.rst This snippet shows how to install the miepython library using either the pip package manager or the conda package manager. Pip is commonly used for Python packages, while conda is popular in scientific computing environments. ```bash pip install miepython ``` ```bash conda install -c conda-forge miepython ``` -------------------------------- ### Import Libraries and Setup for Mie Scattering Simulation Source: https://github.com/scottprahl/miepython/blob/main/docs/06_random_deviates.ipynb Imports necessary libraries like numpy, matplotlib, and miepython. It also includes conditional setup for emscripten environments, disabling JIT compilation if needed. This code prepares the environment for running Mie scattering simulations. ```python %config InlineBackend.figure_format = 'retina' import os import sys import numpy as np import matplotlib.pyplot as plt if sys.platform == "emscripten": import piplite await piplite.install("miepython", deps=False) os.environ["MIEPYTHON_USE_JIT"] = "0" # jupyterlite cannot use numba import miepython as mie import miepython.monte_carlo as mc_mie ``` -------------------------------- ### Initial Setup for MIE Scattering Plot (Python) Source: https://github.com/scottprahl/miepython/blob/main/docs/12_multipoles.ipynb Sets up the initial Matplotlib figure and axes for plotting MIE scattering intensities. It configures polar plots with specific subplot and grid spacing, and sets a super title with relevant physical parameters. Dependencies include matplotlib.pyplot as plt and numpy as np, and a mie module. ```python import matplotlib.pyplot as plt import numpy as np import mie # Set up the plot fig, axes = plt.subplots(5, 2, figsize=(5, 14), subplot_kw={"polar": True}, gridspec_kw={"hspace": 0.3}) fig.suptitle( "d=%.1fµm, $n_{sphere}$=%.3f, $n_{env}=$%.3f, λ=%.3fµm" % (d, n_sph, n_env, lambda0), fontsize=12, ) titles = [ (r"$\\perp$ — Dipole", r"$\\parallel$ — Dipole"), (r"$\\perp$ — Quadrupole", r"$\\parallel$ — Quadrupole"), (r"$\\perp$ — Octopole", r"$\\parallel$ — Octopole"), (r"$\\perp$ — Hexadecapole", r"$\\parallel$ — Hexadecapole"), (r"$\\perp$ — All terms", r"$\\parallel$ — All terms"), ] title = [ "Dipole", "Quadrupole", "Octopole", "Hexadecapole", "Sum of All Multipoles", ] term = np.array([1, 2, 3, 4, 0]) for i, (title1, title2) in enumerate(titles): row = i par, per = mie.intensities(n_sph, d, lambda0, mu, n_env=n_env, n_pole=term[row]) maxx = np.max(par) # Left column (perpendicular) axes[row, 0].set_rlabel_position(135) # This will position the labels at 45 degrees axes[row, 0].plot(theta, per / maxx, color="blue") axes[row, 0].plot([0], [0], "ok", markersize=2) axes[row, 0].set_ylabel("") axes[row, 0].set_xticklabels([]) axes[row, 0].set_rmax(1) axes[row, 0].set_yticks([0.5, 1.0]) axes[row, 0].set_yticklabels(["", ""]) axes[row, 0].text(np.pi / 2, 1.1, "%s (max=%.2g/sr)" % (title[row], maxx)) axes[row, 0].text(np.pi / 2.2, 0.8, r"$\\parallel$", fontsize=12, ha="center", va="center") # Right column (parallel) maxx = np.max(per) axes[row, 1].set_rlabel_position(135) # This will position the labels at 45 degrees axes[row, 1].plot(theta, par / maxx, color="blue") axes[row, 1].plot([0], [0], "ok", markersize=2) axes[row, 1].set_ylabel("") axes[row, 1].set_xticklabels([]) axes[row, 1].set_rmax(1) axes[row, 1].set_yticks([0.5, 1.0]) axes[row, 1].set_yticklabels(["", ""]) axes[row, 1].text(np.pi / 2.2, 0.8, r"$\\perp$", fontsize=16, ha="center", va="center") plt.show() ``` -------------------------------- ### Import and Setup miepython Source: https://github.com/scottprahl/miepython/blob/main/docs/12_multipoles.ipynb Imports necessary libraries including numpy, matplotlib, and miepython. It includes conditional import for piplite for emscripten environments and sets an environment variable to disable JIT compilation for compatibility. ```python %config InlineBackend.figure_format = 'retina' import os import sys import numpy as np import matplotlib.pyplot as plt if sys.platform == "emscripten": import piplite await piplite.install("miepython", deps=False) os.environ["MIEPYTHON_USE_JIT"] = "0" # jupyterlite cannot use numba import miepython as mie from miepython.vsh import mie_pi, mie_tau from miepython.util import cs as comp_str ``` -------------------------------- ### Get MIE Python Library Version Source: https://github.com/scottprahl/miepython/blob/main/docs/13_resonance.ipynb Prints the version of the MIE Python library currently installed. This is a simple utility function to check the library's version. ```python print(mie.__version__) ``` -------------------------------- ### Setup and Import for miepython Validation Source: https://github.com/scottprahl/miepython/blob/main/docs/09_backscattering.ipynb This code snippet sets up the environment for running miepython validation tests. It configures inline plotting, imports necessary libraries like numpy and matplotlib, and handles potential installation of 'miepython' for emscripten environments (like jupyterlite). It also disables Numba JIT for compatibility with jupyterlite. ```python %config InlineBackend.figure_format = 'retina' import os import sys import numpy as np import matplotlib.pyplot as plt if sys.platform == "emscripten": import piplite await piplite.install("miepython", deps=False) os.environ["MIEPYTHON_USE_JIT"] = "0" # jupyterlite cannot use numba import miepython as mie ``` -------------------------------- ### JIT Compilation Performance Boost with MiePython Source: https://context7.com/scottprahl/miepython/llms.txt Demonstrates how to enable Numba JIT compilation in MiePython for significant performance improvements in large-scale calculations. This involves setting an environment variable before importing MiePython and then benchmarking the calculation speed. It requires os, time, NumPy, and MiePython. ```python import os import time import numpy as np # Must set environment variable BEFORE importing miepython os.environ["MIEPYTHON_USE_JIT"] = "1" import miepython as mie # Benchmark parameters n_particles = 100000 m = 1.5 - 0.1j x_min, x_max = 0.1, 10.0 # Generate random particle sizes np.random.seed(42) x_array = np.random.uniform(x_min, x_max, n_particles) # Warm-up JIT compilation _ = mie.efficiencies_mx(m, x_array[0]) # Benchmark calculation start = time.time() qext, qsca, qback, g = mie.efficiencies_mx(m, x_array) elapsed = time.time() - start print(f"Calculated scattering for {n_particles:,} particles") print(f"Time elapsed: {elapsed:.3f} seconds") print(f"Throughput: {n_particles/elapsed:.0f} particles/second") print(f"\nStatistics:") print(f" Mean extinction efficiency: {np.mean(qext):.4f} ± {np.std(qext):.4f}") print(f" Mean scattering efficiency: {np.mean(qsca):.4f} ± {np.std(qsca):.4f}") print(f" Mean asymmetry parameter: {np.mean(g):.4f} ± {np.std(g):.4f}") ``` -------------------------------- ### Compare Rayleigh and Mie Scattering Efficiencies Source: https://github.com/scottprahl/miepython/blob/main/docs/04_rayleigh.ipynb Calculates and prints the extinction efficiency (Qext), scattering efficiency (Qsca), backscattering efficiency (Qback), and asymmetry parameter (g) for both Mie and Rayleigh scattering models. This provides a quantitative comparison of the overall scattering characteristics. ```python m = 1.5 x = 0.1 qext, qsca, qback, g = mie.efficiencies_mx(m, x) rext, rsca, rback, rg = ray.efficiencies_mx(m, x) print("Qext Qsca Qback g") print("%.5e %.5e %.5e %.5f Mie" % (qext, qsca, qback, g)) print("%.5e %.5e %.5e %.5f Rayleigh" % (rext, rsca, rback, rg)) ``` -------------------------------- ### Running Unit Tests in Python Source: https://github.com/scottprahl/miepython/blob/main/docs/10_basic_tests.ipynb This code snippet shows how to initiate the execution of unit tests using Python's built-in `unittest` module. The `argv` and `exit` parameters are configured to allow running tests within an environment like a Jupyter notebook without exiting the kernel. ```python unittest.main(argv=[""], verbosity=2, exit=False) ``` -------------------------------- ### Compare Bohren & Huffman Unpolarized Intensity with miepython Source: https://github.com/scottprahl/miepython/blob/main/docs/03a_normalization.ipynb This Python code snippet compares the unpolarized intensity calculated by miepython against the results from Bohren & Huffman's method for a specific test case (BHMie Test Case 14). It defines a complex refractive index (m) and size parameter (x), calculates efficiencies and unpolarized intensity using miepython, and then computes and prints the comparison, noting potential discrepancies and the robustness of Wiscombe's code. ```python """ BHMie Test Case 14, Refractive index = 1.5000-1.0000j, Size parameter = 1.0000 Angle Cosine S1 S2 0.00 1.0000 -8.38663e-01 -8.64763e-01 -8.38663e-01 -8.64763e-01 0.52 0.8660 -8.19225e-01 -8.61719e-01 -7.21779e-01 -7.27856e-01 1.05 0.5000 -7.68157e-01 -8.53697e-01 -4.19454e-01 -3.72965e-01 1.57 0.0000 -7.03034e-01 -8.43425e-01 -4.44461e-02 6.94424e-02 """ x = 1.0 m = 1.5 - 1j mu = np.cos(np.linspace(0, 90, 4) * np.pi / 180) qext, qsca, qback, g = mie.efficiencies_mx(m, x) unpolar = mie.i_unpolarized(m, x, mu, norm="bohren") s1_bh = np.empty(4, dtype=complex) s1_bh[0] = -8.38663e-01 - 8.64763e-01 * 1j s1_bh[1] = -8.19225e-01 - 8.61719e-01 * 1j s1_bh[2] = -7.68157e-01 - 8.53697e-01 * 1j s1_bh[3] = -7.03034e-01 - 8.43425e-01 * 1j s2_bh = np.empty(4, dtype=complex) s2_bh[0] = -8.38663e-01 - 8.64763e-01 * 1j s2_bh[1] = -7.21779e-01 - 7.27856e-01 * 1j s2_bh[2] = -4.19454e-01 - 3.72965e-01 * 1j s2_bh[3] = -4.44461e-02 + 6.94424e-02 * 1j # BHMie seems to normalize their intensities to 4 * pi * x**2 * Qsca unpolar_bh = (abs(s1_bh) ** 2 + abs(s2_bh) ** 2) / 2 ratio = unpolar_bh / unpolar print("BHMie Test Case 14: m=1.5000-1.0000j, Size parameter = 1.0000") print() print(" %9.1f°%9.1f°%9.1f°%9.1f°" % (0, 30, 60, 90)) print("BHMIE %9.5f %9.5f %9.5f %9.5f" % (unpolar_bh[0], unpolar_bh[1], unpolar_bh[2], unpolar_bh[3])) print("miepython %9.5f %9.5f %9.5f %9.5f" % (unpolar[0], unpolar[1], unpolar[2], unpolar[3])) print("ratio %9.5f %9.5f %9.5f %9.5f" % (ratio[0], ratio[1], ratio[2], ratio[3])) print() print("Note that this test is identical to MIEV0 Test Case 14 above.") print() print("Wiscombe's code is much more robust than Bohren's so I attribute errors all to Bohren") ``` -------------------------------- ### Compare Mie Scattering Results (Python) Source: https://github.com/scottprahl/miepython/blob/main/docs/03a_normalization.ipynb Compares the output of mie.mie_S1_S2 with normalization set to 'wiscombe' against the PyMieScatt library for Mie scattering calculations. This function takes size parameter, refractive index, and wavelength as input and returns scattering amplitudes S1 and S2. ```python import PyMieScatt import miepython as mie print(PyMieScatt.MieS1S2(1.5,0.02,0.75)) print(mie.mie_S1_S2(1.5,0.02,0.75,norm='wiscombe')) ``` -------------------------------- ### Calculate Scattering Phase Function and Efficiencies Source: https://github.com/scottprahl/miepython/blob/main/docs/02_efficiencies.ipynb This example calculates the scattering phase function and compares scattering and back-scattering cross-sections for a dielectric sphere. It utilizes `miepython.S1_S2` for scattering amplitudes and `mie.efficiencies_mx` for overall efficiencies, demonstrating the relationship between phase function and cross-sections. ```python lambda0 = 1 # microns a = lambda0 / 10 # also microns k = 2 * np.pi / lambda0 # per micron m = 1.5 x = a * k geometric_cross_section = np.pi * a**2 theta = np.linspace(-180, 180, 180) mu = np.cos(theta / 180 * np.pi) s1, s2 = mie.S1_S2(m, x, mu) phase = (abs(s1[0]) ** 2 + abs(s2[0]) ** 2) / 2 print(" unpolarized =", phase) print(" |s1[-180]|**2 =", abs(s1[0] ** 2)) print(" |s2[-180]|**2 =", abs(s2[0] ** 2)) print(" |s1[ 180]|**2 =", abs(s1[179] ** 2)) print(" |s2[ 180]|**2 =", abs(s2[179] ** 2)) print() qext, qsca, qback, g = mie.efficiencies_mx(m, x) Cback = qback * geometric_cross_section Csca = qsca * geometric_cross_section print(" Csca =", Csca) print(" Cback =", Cback) print("4*pi*Csca*p(180) =", 4 * np.pi * Csca * phase) ``` -------------------------------- ### Mie Theory: Efficiencies for Small Spheres (mie.small_sphere) Source: https://github.com/scottprahl/miepython/blob/main/docs/07_algorithm.ipynb This snippet calculates extinction (Qext), scattering (Qsca), absorption (Qabs), backscattering (Qback), and asymmetry factor (g) for a small sphere using 'mie.small_sphere'. It compares results with 'mie.efficiencies_mx' for a slightly different size parameter. Requires numpy. ```python import mie import numpy as np m = 1.5 - 0.1j x = 0.0665 print("abs(m*x)=", abs(m * x)) qext, qsca, qback, g = mie.small_sphere(m, x) print("Qext = % .7f" % qext) print("Qsca = % .7f" % qsca) print("Qabs = % .7f" % (qext - qsca)) print("Qback= % .7f" % qback) print("g = % .7f" % g) print() # print a blank line print("The following should be nearly the same as those above:") print() # print a blank line x = 0.067 print("abs(m*x)=", abs(m * x)) qext, qsca, qback, g = mie.efficiencies_mx(m, x) print("Qext = % .7f" % qext) print("Qsca = % .7f" % qsca) print("Qabs = % .7f" % (qext - qsca)) print("Qback= % .7f" % qback) print("g = % .7f" % g) ``` -------------------------------- ### Calculate S1 and S2 scattering amplitudes Source: https://github.com/scottprahl/miepython/blob/main/docs/01_basics.ipynb Demonstrates the usage of the `mie.S1_S2` function to calculate the scattering amplitudes S1 and S2. It shows two examples with a complex refractive index and size parameter, one using a numpy array for the size parameter and another using a single integer. ```python mie.S1_S2(1.507 - 0.002j, 0.7086, np.array([-1.0], dtype=float)) ``` ```python mie.S1_S2(1.507 - 0.002j, 0.7086, -1) ``` -------------------------------- ### Plotting Mie Backscattering Efficiencies vs. Size Parameter Source: https://github.com/scottprahl/miepython/blob/main/docs/13_resonance.ipynb Generates plots of backscattering efficiency (Qback) versus size parameter (x) for different refractive indices. It uses matplotlib for plotting and assumes the 'mie' and 'numpy' libraries are imported. The function mie.efficiencies_mx is used to calculate Qback for various materials and size parameters. The plots are annotated and displayed using plt.show(). ```python plt.figure(figsize=(6, 6)) m = 3.41 - 1.94j x = np.linspace(0.1, 3.5, 300) qext, qsca, qback, g = mie.efficiencies_mx(m, x) plt.plot(x, qback, "b") plt.text(2.5, 0, "m=3.41-1.94j", ha="left", color="blue") m = 1000j x = np.linspace(0.1, 3, 100) qext, qsca, qback, g = mie.efficiencies_mx(m, x) plt.text(1.2, 3.2, "m=1000j", ha="left", color="red") plt.plot(x, qback, "r") plt.xlabel("x") plt.ylabel(r"$Q_{back}$") plt.title("van de Hulst Figure 61") plt.show() ``` -------------------------------- ### Initialize and Populate NumPy Arrays for Optical Properties (Python) Source: https://github.com/scottprahl/miepython/blob/main/docs/13_resonance.ipynb This snippet demonstrates the initialization of three NumPy arrays: `ag_lambda`, `ag_n`, and `ag_k`. These arrays are populated with a series of floating-point numbers, likely representing wavelength, real part of the refractive index, and imaginary part of the refractive index, respectively. The data is structured as a 2D array, where each row corresponds to a specific data point and columns represent different properties. This is a common pattern for loading experimental or simulated data for further analysis in scientific computing. ```python ag_lambda, ag_n, ag_k = np.array( [ [0.245202, 1.168773, 1.331022], [0.246793, 1.176486, 1.342173], [0.248384, 1.184909, 1.352390], [0.249976, 1.195191, 1.360441], [0.251567, 1.208012, 1.365649], [0.253159, 1.222298, 1.369346], [0.254751, 1.236561, 1.373296], [0.256342, 1.250863, 1.377493], [0.257934, 1.266081, 1.380957], [0.259526, 1.280422, 1.385425], [0.261118, 1.295747, 1.388624], [0.262710, 1.314122, 1.388161], [0.264302, 1.332088, 1.387543], [0.265894, 1.349186, 1.387035], [0.267486, 1.365779, 1.386098], [0.269078, 1.381617, 1.384834], [0.270671, 1.397479, 1.382323], [0.272263, 1.414073, 1.377756], [0.273856, 1.430565, 1.371857], [0.275448, 1.446650, 1.364803], [0.277041, 1.462390, 1.356414], [0.278633, 1.477705, 1.346650], [0.280226, 1.493032, 1.335003], [0.281819, 1.507621, 1.322091], [0.283412, 1.521520, 1.308001], [0.285004, 1.534962, 1.292706], [0.286597, 1.548117, 1.276244], [0.288190, 1.561090, 1.258708], [0.289783, 1.573846, 1.240198], [0.291377, 1.585484, 1.221170], [0.292970, 1.597032, 1.200512], [0.294563, 1.609048, 1.177539], [0.296156, 1.622041, 1.151580], [0.297750, 1.638017, 1.119556], [0.299343, 1.652347, 1.081758], [0.300936, 1.664638, 1.035518], [0.302530, 1.674244, 0.981291], [0.304124, 1.676124, 0.924319], [0.305717, 1.670761, 0.862526], [0.307311, 1.656782, 0.794018], [0.308905, 1.632069, 0.729033], [0.310498, 1.601690, 0.666868], [0.312092, 1.564974, 0.603757], [0.313686, 1.521603, 0.541588], [0.315280, 1.473780, 0.478805], [0.316874, 1.416480, 0.407797], [0.318468, 1.328991, 0.327906], [0.320062, 1.204332, 0.254230], [0.321656, 1.058416, 0.205534], [0.323250, 0.908725, 0.186685], [0.324844, 0.769420, 0.194293], [0.326439, 0.640105, 0.225011], [0.328033, 0.508378, 0.278807], [0.329627, 0.381485, 0.366136], [0.331222, 0.287389, 0.479734], [0.332816, 0.230957, 0.590405], [0.334411, 0.197050, 0.685981], [0.336005, 0.174356, 0.770536], [0.337600, 0.157490, 0.850140], [0.339194, 0.144728, 0.924251], [0.340789, 0.136119, 0.984005], [0.342384, 0.129949, 1.034139], [0.343978, 0.124166, 1.087744], [0.345573, 0.119236, 1.140053], [0.347168, 0.115660, 1.184273], [0.348763, 0.112847, 1.224136], [0.350358, 0.110334, 1.263474], [0.351952, 0.108068, 1.302222], [0.353547, 0.106046, 1.339786], [0.355142, 0.104260, 1.375640], [0.356737, 0.102673, 1.409608], [0.358332, 0.101240, 1.441979], [0.359928, 0.099932, 1.473051], [0.361523, 0.098726, 1.503093], [0.363118, 0.097604, 1.532351], [0.364713, 0.096552, 1.561050], [0.366308, 0.095557, 1.589396], [0.367903, 0.094617, 1.617465], [0.369499, 0.093738, 1.645204], [0.371094, 0.092924, 1.672551], [0.372689, 0.092181, 1.699454], [0.374285, 0.091512, 1.725859], [0.375880, 0.090922, 1.751718], [0.377476, 0.090413, 1.776983], [0.379071, 0.089990, 1.801611], [0.380667, 0.089654, 1.825569], [0.382262, 0.089405, 1.848890], [0.383858, 0.089242, 1.871626], [0.385453, 0.089159, 1.893827], [0.387049, 0.089149, 1.915539], [0.388644, 0.089206, 1.936805], [0.390240, 0.089324, 1.957667], [0.391836, 0.089498, 1.978165], [0.393431, 0.089722, 1.998337], [0.395027, 0.089992, 2.018219], [0.396623, 0.090303, 2.037845], [0.398219, 0.090652, 2.057249], [0.399814, 0.091033, 2.076463], [0.401410, 0.091443, 2.095516], [0.403006, 0.091879, 2.114440], [0.404602, 0.092337, 2.133262], [0.406198, 0.092814, 2.152009], [0.407793, 0.093306, 2.170709], [0.409389, 0.093810, 2.189387], [0.410985, 0.094324, 2.208056], [0.412581, 0.094848, 2.226702], [0.414177, 0.095378, 2.245305], [0.415773, 0.095916, 2.263849], [0.417369, 0.096460, 2.282315], [0.418965, 0.097008, 2.300687], [0.420561, 0.097560, 2.318949], [0.422157, 0.098116, 2.337084], [0.423753, 0.098674, 2.355078], [0.425349, 0.099233, 2.372916], [0.426945, 0.099793, 2.390584], [0.428541, 0.100354, 2.408066], [0.430137, 0.100913, 2.425350], [0.431733, 0.101470, 2.442428], [0.433329, 0.102027, 2.459308], [0.434925, 0.102581, 2.475997], [0.436521, 0.103134, 2.492505], [0.438117, 0.103684, 2.508840] ] ) ``` -------------------------------- ### Import Libraries and Setup for Rayleigh Scattering Analysis Source: https://github.com/scottprahl/miepython/blob/main/docs/04_rayleigh.ipynb This snippet imports necessary libraries like numpy and matplotlib for numerical computations and plotting. It also includes conditional imports for emscripten environments, disabling JIT compilation for compatibility. The `miepython` library, specifically its `rayleigh` module, is imported for scattering calculations. ```python %config InlineBackend.figure_format = 'retina' import os import sys import numpy as np import matplotlib.pyplot as plt import importlib.resources if sys.platform == "emscripten": import piplite await piplite.install("miepython", deps=False) os.environ["MIEPYTHON_USE_JIT"] = "0" # jupyterlite cannot use numba import miepython as mie from miepython import rayleigh as ray ``` -------------------------------- ### Configure MiePython for JIT Compilation Source: https://github.com/scottprahl/miepython/blob/main/docs/11_performance.ipynb Sets environment variables to enable JIT compilation and specify the Numba cache directory for the miepython library. This configuration is crucial for performance optimizations. ```python import os import tempfile import numpy as np os.environ["MIEPYTHON_USE_JIT"] = "1" # Set to "0" to disable JIT os.environ["NUMBA_CACHE_DIR"] = tempfile.gettempdir() import miepython as mie ``` -------------------------------- ### Mie Scattering Intensity for Complex Refractive Index Source: https://github.com/scottprahl/miepython/blob/main/docs/03_angular_scattering.ipynb Calculates and plots the unpolarized scattering intensity for a sphere with a complex refractive index. This example also demonstrates the calculation of extinction efficiency (qext), scattering efficiency (qsca), backscattering efficiency (qback), and asymmetry parameter (g) using mie.efficiencies_mx, and integrates the intensity to find the total scattered light. ```python m = 1.5 - 1.5j x = 1 mu = np.linspace(-1, 1, 501) intensity = mie.i_unpolarized(m, x, mu) qext, qsca, qback, g = mie.efficiencies_mx(m, x) a = qsca / qext # integrate over all angles dmu = mu[1] - mu[0] total = 2 * np.pi * dmu * np.sum(intensity) plt.plot(mu, intensity) plt.xlabel(r"$cos(\theta)$") plt.ylabel("Unpolarized Scattering Intensity [1/sr]") plt.title("m=%.3f%+.3fj, x=%.2f, a=%.3f, total=%.3f" % (m.real, m.imag, x, a, total)) plt.show() ``` -------------------------------- ### Bohren & Huffman Water Droplet Scattering Plot Source: https://github.com/scottprahl/miepython/blob/main/docs/03_angular_scattering.ipynb Calculates and plots the intensity of perpendicularly polarized (iper) and parallelly polarized (ipar) light scattered by a small water droplet, along with the resulting polarization. This example uses a specific scaling factor to match Figure 4.9 from Bohren and Huffman's 'Absorption and Scattering of Light by Small Particles'. It requires numpy for numerical operations and matplotlib for plotting. ```python import numpy as np import matplotlib.pyplot as plt import miepython as mie x = 3 m = 1.33 - 1e-8j theta = np.linspace(0, 180, 181) mu = np.cos(theta * np.pi / 180) scaling_factor = 16 * np.pi iper = scaling_factor * mie.i_per(m, x, mu) ipar = scaling_factor * mie.i_par(m, x, mu) P = (iper - ipar) / (iper + ipar) plt.subplots(2, 1, figsize=(8, 8)) plt.subplot(2, 1, 1) plt.semilogy(theta, ipar, label="$i_{par}$") plt.semilogy(theta, iper, label="$i_{per}$") plt.xlim(0, 180) plt.xticks(range(0, 181, 30)) plt.ylabel("i$_{par}$ and i$_{per}$") plt.legend() plt.title("Figure 4.9 from Bohren & Huffman") plt.subplot(2, 1, 2) plt.plot(theta, P) plt.ylim(-1, 1) plt.xticks(range(0, 181, 30)) plt.xlim(0, 180) plt.ylabel("Polarization") plt.plot([0, 180], [0, 0], ":k") plt.xlabel("Angle (Degrees)") plt.show() ``` -------------------------------- ### Plotting Mie Extinction Efficiencies vs. Size Parameter Source: https://github.com/scottprahl/miepython/blob/main/docs/13_resonance.ipynb Generates plots of extinction efficiency (Qext) versus size parameter (x) for different refractive indices. It uses matplotlib for plotting and assumes the 'mie' and 'numpy' libraries are imported. The function mie.efficiencies_mx is used to calculate Qext for various materials (represented by complex refractive indices 'm') and size parameters 'x'. The plots are annotated with the refractive indices and displayed using plt.show(). ```python plt.figure(figsize=(6, 6)) m = 8.9 - 0.69j x = np.linspace(0.1, 0.7, 300) qext, qsca, qback, g = mie.efficiencies_mx(m, x) plt.plot(x, qext, "r") plt.text(0.4, 2.5, "m=8.90-0.69j", ha="left", color="red") m = 8.18 - 1.96j x = np.linspace(0.1, 1.0, 300) qext, qsca, qback, g = mie.efficiencies_mx(m, x) plt.plot(x, qext, "b") plt.text(1.0, 2.5, "m=8.18-1.96j", ha="left", color="blue") m = 1000j x = np.linspace(0.1, 1.5, 100) qext, qsca, qback, g = mie.efficiencies_mx(m, x) plt.text(0.9, 1.4, "m=1000j", ha="left", color="black") plt.plot(x, qext, "k") plt.xlabel("x") plt.ylabel(r"$Q_{ext}$") plt.title("van de Hulst Figure 60") plt.show() ``` -------------------------------- ### Initializing Mie Scattering Parameters Source: https://github.com/scottprahl/miepython/blob/main/docs/12_multipoles.ipynb This Python code snippet initializes the parameters required for Mie scattering calculations. It defines the refractive indices of the sphere and environment, the sphere diameter, the reference wavelength, and sets up an array of scattering angles in both degrees and radians, along with their cosines. ```python import numpy as np n_sph = 1.5 n_env = 1.333 d = 1 lambda0 = 0.805 thetad = np.linspace(0, 360, 181) theta = np.radians(thetad) mu = np.cos(theta) ``` -------------------------------- ### Mie Efficiencies for Spheres with Lower Refractive Index (Python) Source: https://github.com/scottprahl/miepython/blob/main/docs/09_backscattering.ipynb Calculates and prints Mie scattering efficiencies (Qback) for spheres with a real refractive index less than the environment (m.real = 0.75). It demonstrates the calculation for different size parameters (x) and compares the Mie result with a reference calculation. The output shows the size parameter, refractive index components, calculated Qback, reference Qback, and their ratio. ```python print(" mie Wiscombe") print(" X m.real m.imag Qback Qback ratio") m = complex(0.75, 0.0) x = 0.099 ref = (1.81756e-08 * 1.81756e-08 + 1.64810e-04 * 1.64810e-04) / x / x * 4 qext, qsca, qback, g = mie.efficiencies_mx(m, x) print("%9.3f % 8.4f % 8.4f % 8e % 8e %8.5f" % (x, m.real, m.imag, qback, ref, qback / ref)) x = 0.101 ref = (2.04875e-08 * 2.04875e-08 + 1.74965e-04 * 1.74965e-04) / x / x * 4 qext, qsca, qback, g = mie.efficiencies_mx(m, x) print("%9.3f % 8.4f % 8.4f % 8e % 8e %8.5f" % (x, m.real, m.imag, qback, ref, qback / ref)) x = 10.0 ref = (1.07857e00 * 1.07857e00 + 3.60881e-02 * 3.60881e-02) / x / x * 4 qext, qsca, qback, g = mie.efficiencies_mx(m, x) print("%9.3f % 8.4f % 8.4f % 8e % 8e %8.5f" % (x, m.real, m.imag, qback, ref, qback / ref)) x = 1000.0 ref = (1.70578e01 * 1.70578e01 + 4.84251e02 * 4.84251e02) / x / x * 4 qext, qsca, qback, g = mie.efficiencies_mx(m, x) print("%9.3f % 8.4f % 8.4f % 8e % 8e %8.5f" % (x, m.real, m.imag, qback, ref, qback / ref)) print() ```