Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 4 additions & 52 deletions examples/component_collection.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -23,54 +23,6 @@
"%matplotlib widget"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f2d27900",
"metadata": {},
"outputs": [],
"source": [
"from scipy.integrate import simpson\n",
"\n",
"model = ComponentCollection(display_name=\"TestComponentCollection\")\n",
"component1 = Gaussian(\n",
" display_name=\"TestGaussian1\",\n",
" area=1.0,\n",
" center=0.0,\n",
" width=1.0,\n",
" unit=\"meV\",\n",
" unique_name=\"TestGaussian1\",\n",
")\n",
"component2 = Lorentzian(\n",
" display_name=\"TestLorentzian1\",\n",
" area=2.0,\n",
" center=1.0,\n",
" width=0.5,\n",
" unit=\"meV\",\n",
" unique_name=\"TestLorentzian1\",\n",
")\n",
"model.add_component(component1)\n",
"model.add_component(component2)\n",
"\n",
"model.normalize_area()\n",
"# EXPECT\n",
"x = np.linspace(-10000, 10000, 1000000) # Lorentzians have long tails\n",
"result = model.evaluate(x)\n",
"numerical_area = simpson(result, x)\n",
"\n",
"print(numerical_area)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fe3b8780",
"metadata": {},
"outputs": [],
"source": [
"model.components[1].area"
]
},
{
"cell_type": "code",
"execution_count": null,
Expand All @@ -87,10 +39,10 @@
"polynomial = Polynomial(display_name='Polynomial',coefficients=[0.1, 0, 0.5]) # y=0.1+0.5*x^2\n",
"\n",
"# Adding components to the component collection\n",
"component_collection.add_component(gaussian)\n",
"component_collection.add_component(dho)\n",
"component_collection.add_component(lorentzian)\n",
"component_collection.add_component(polynomial)\n",
"component_collection.append_component(gaussian)\n",
"component_collection.append_component(dho)\n",
"component_collection.append_component(lorentzian)\n",
"component_collection.append_component(polynomial)\n",
"\n",
"x=np.linspace(-2, 2, 100)\n",
"\n",
Expand Down
45 changes: 1 addition & 44 deletions examples/diffusion_model.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@
"# Q is in Angstrom^-1 and energy in meV.\n",
"\n",
"Q=np.linspace(0.5,2,7)\n",
"# energy=np.linspace(-2, 2, 501)\n",
"energy=sc.linspace(start=-2,stop=2,num=501,unit=\"meV\",dim='energy')\n",
"energy=np.linspace(-2, 2, 501)\n",
"scale=1.0\n",
"diffusion_coefficient = 2.4e-9 # m^2/s\n",
"diffusion_unit= \"m**2/s\"\n",
Expand All @@ -53,48 +52,6 @@
"plt.title('Brownian Translational Diffusion Model') "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dce619d8",
"metadata": {},
"outputs": [],
"source": [
"energy=np.linspace(-2, 2, 501)\n",
"energy=sc.linspace(start=-2,stop=2,num=501,unit=\"meV\",dim='energy')\n",
"energy"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "555cb19a",
"metadata": {},
"outputs": [],
"source": [
"component_collections[0].get_all_parameters()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7247d79d",
"metadata": {},
"outputs": [],
"source": [
"component_collections[0].get_all_parameters()[2].dependency_expression"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "04e99b93",
"metadata": {},
"outputs": [],
"source": [
"diffusion_model.diffusion_coefficient=5.0e-9"
]
},
{
"cell_type": "code",
"execution_count": null,
Expand Down
147 changes: 147 additions & 0 deletions examples/sample_model.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "8bda4c84",
"metadata": {},
"outputs": [],
"source": [
"from easydynamics.sample_model.sample_model import SampleModel\n",
"from easydynamics.sample_model.resolution_model import ResolutionModel\n",
"from easydynamics.sample_model.background_model import BackgroundModel\n",
"import numpy as np\n",
"\n",
"from easydynamics.sample_model import BrownianTranslationalDiffusion, Gaussian, DampedHarmonicOscillator, ComponentCollection, DeltaFunction, Polynomial\n",
"\n",
"import matplotlib.pyplot as plt\n",
"\n",
"%matplotlib widget\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d610e54f",
"metadata": {},
"outputs": [],
"source": [
"# Create a diffusion_model and components for the SampleModel\n",
"Q=np.linspace(0.5,2,7)\n",
"energy=np.linspace(-2, 2, 501)\n",
"\n",
"scale=1.0\n",
"diffusion_coefficient = 2.4e-9 # m^2/s\n",
"diffusion_unit= \"m**2/s\"\n",
"diffusion_model=BrownianTranslationalDiffusion(display_name=\"DiffusionModel\", scale=scale, diffusion_coefficient= diffusion_coefficient, diffusion_unit=diffusion_unit)\n",
"\n",
"\n",
"# Creating components\n",
"component_collection=ComponentCollection()\n",
"gaussian=Gaussian(display_name='Gaussian',width=0.2,area=1, center=1.5)\n",
"dho = DampedHarmonicOscillator(display_name='DHO',center=1.0,width=0.3,area=2.0)\n",
"\n",
"# Adding components to the component collection\n",
"component_collection.append_component(gaussian)\n",
"component_collection.append_component(dho)\n",
"\n",
"sample_model=SampleModel(\n",
" diffusion_models=diffusion_model,\n",
" components=component_collection,\n",
" Q=Q,\n",
" unit=\"meV\",\n",
" display_name=\"MySampleModel\",\n",
" temperature=10,\n",
")\n",
"\n",
"# Generate a component_collection with the template components for each Q\n",
"sample_model.generate_component_collections() # This will be done implicitly later, but for now users will need to call it explicitly after making changes\n",
"\n",
"# Calculate the model intensity at the specified Q and energy values\n",
"# y_list will be a list of intensity arrays, one for each Q value\n",
"sample_intensity = sample_model.evaluate(energy)\n",
"\n",
"plt.figure()\n",
"for i, Q_value in enumerate(Q):\n",
" plt.plot(\n",
" energy,sample_intensity[i],\n",
" label=f\"Q={Q_value:.2f} Å⁻¹\"\n",
" )\n",
"plt.xlabel(\"Energy (meV)\")\n",
"plt.ylabel(\"Intensity (a.u.)\")\n",
"plt.title(\"Sample Model Evaluation at 10 K\")\n",
"plt.legend()\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "44c6bdad",
"metadata": {},
"outputs": [],
"source": [
"# Create a BackgroundModel and show other ways to set Q and components\n",
"\n",
"background_model = BackgroundModel()\n",
"background_model.Q = Q\n",
"\n",
"background_model.components = Polynomial(coefficients=[1, 0.1, 0.01])\n",
"background_model.generate_component_collections()\n",
"background = background_model.evaluate(energy)\n",
"\n",
"# Also create a ResolutionModel. It doesn't do anything here, but shows how to set it up.\n",
"resolution_model = ResolutionModel()\n",
"resolution_model.Q = Q\n",
"resolution_model.append_component(Gaussian(width=0.05))\n",
"resolution_model.generate_component_collections()\n",
"resolution = resolution_model.evaluate(energy)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "40be03c6",
"metadata": {},
"outputs": [],
"source": [
"# Plot the three models together\n",
"for i, Q_value in enumerate(Q):\n",
" plt.figure()\n",
" plt.plot(energy,sample_intensity[i], label=\"Sample model\")\n",
" plt.plot(energy,background[i], label=\"Background model\")\n",
" plt.plot(energy,resolution[i], label=\"Resolution model\")\n",
" plt.legend()\n",
" plt.xlabel(\"Energy (meV)\")\n",
" plt.ylabel(\"Intensity (a.u.)\")\n",
" plt.title(f\"Sample Model Evaluation at 10 K and Q ={Q_value:.2f} Å⁻¹\")\n",
" plt.legend()\n",
" plt.show()\n",
"\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "easydynamics_newbase",
"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.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
41 changes: 41 additions & 0 deletions src/easydynamics/sample_model/background_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import scipp as sc

from easydynamics.sample_model.model_base import ModelBase
from easydynamics.utils.utils import Q_type

from .component_collection import ComponentCollection
from .components.model_component import ModelComponent


class BackgroundModel(ModelBase):
"""BackgroundModel represents a model of the background in an experiment at various Q.
Parameters
----------
display_name : str
Display name of the model.
unique_name : str | None
Unique name of the model. If None, a unique name will be generated.
unit : str | sc.Unit | None
Unit of the model. If None, unitless.
components : ModelComponent | ComponentCollection | None
Template components of the model. If None, no components are added. These components are copied into ComponentCollections for each Q value.
Q : Q_type | None
Q values for the model. If None, Q is not set.
"""

def __init__(
self,
display_name: str = "MyBackgroundModel",
unique_name: str | None = None,
unit: str | sc.Unit = "meV",
components: ComponentCollection | ModelComponent | None = None,
Q: Q_type | None = None,
):
super().__init__(
display_name=display_name,
unique_name=unique_name,
unit=unit,
components=components,
Q=Q,
)
36 changes: 23 additions & 13 deletions src/easydynamics/sample_model/component_collection.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from __future__ import annotations

import warnings
from typing import List

import numpy as np
import scipp as sc

# from easyscience.job.theoreticalmodel import TheoreticalModelBase
from easyscience.base_classes.model_base import ModelBase
from easyscience.variable import DescriptorBase, Parameter

Expand Down Expand Up @@ -64,19 +64,29 @@ def __init__(
"components must be a list of ModelComponent instances."
)
for comp in components:
self.add_component(comp)

def add_component(self, component: ModelComponent) -> None:
if not isinstance(component, ModelComponent):
raise TypeError("Component must be an instance of ModelComponent.")
self.append_component(comp)

def append_component(
self, component: ModelComponent | "ComponentCollection"
) -> None:
match component:
case ModelComponent():
components = (component,)
case ComponentCollection(components=components):
pass
case _:
raise TypeError(
"Component must be a ModelComponent or ComponentCollection."
)

if component in self._components:
raise ValueError(
f"Component '{component.unique_name}' is already in the collection."
f"Here is a list of the components in the collection: {self.list_component_names()} "
)
for comp in components:
if comp in self._components:
raise ValueError(
f"Component '{comp.unique_name}' is already in the collection. "
f"Existing components: {self.list_component_names()}"
)

self._components.append(component)
self._components.append(comp)

def remove_component(self, unique_name: str) -> None:
if not isinstance(unique_name, str):
Expand Down
Loading