Skip to content

158 magnetism in refl1d #159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 28 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
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
531 changes: 531 additions & 0 deletions docs/src/tutorials/magnetism.ipynb

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/src/tutorials/resolution_functions.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
"print(f'numpy: {np.__version__}')\n",
"print(f'scipp: {sc.__version__}')\n",
"print(f'easyreflectometry: {easyreflectometry.__version__}')\n",
"print(f'Refl1D: {refnx.__version__}')"
"print(f'refnx: {refnx.__version__}')"
]
},
{
Expand Down
13 changes: 13 additions & 0 deletions src/easyreflectometry/calculators/calculator_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,16 @@ def sld_profile(self, model_id: str) -> tuple[np.ndarray, np.ndarray]:

def set_resolution_function(self, resolution_function: Callable[[np.array], np.array]) -> None:
return self._wrapper.set_resolution_function(resolution_function)

@property
def magnetism(self):
return self._wrapper.magnetism

@magnetism.setter
def magnetism(self, magnetism: bool):
"""
Set the magnetism flag for the calculator

:param magnetism: True if the calculator should include magnetism
"""
self._wrapper.magnetism = magnetism
36 changes: 23 additions & 13 deletions src/easyreflectometry/calculators/refl1d/wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
from typing import Tuple

import numpy as np
from easyreflectometry.experiment.resolution_functions import is_percentage_fhwm_resolution_function
from refl1d import model
from refl1d import names

from easyreflectometry.experiment.resolution_functions import is_percentage_fhwm_resolution_function

from ..wrapper_base import WrapperBase

RESOLUTION_PADDING = 3.5
OVERSAMPLING_FACTOR = 21
MAGNETISM = False
ALL_POLARIZATIONS = False


Expand All @@ -30,8 +30,8 @@ def create_layer(self, name: str):

:param name: The name of the layer
"""
if MAGNETISM: # A test with hardcoded magnetism in all layers
magnetism = names.Magnetism(rhoM=0.2, thetaM=270)
if self._magnetism:
magnetism = names.Magnetism(rhoM=0.0, thetaM=0.0)
else:
magnetism = None
self.storage['layer'][name] = model.Slab(name=str(name), magnetism=magnetism)
Expand All @@ -47,17 +47,27 @@ def create_item(self, name: str):
)
del self.storage['item'][name].stack[0]

def get_item_value(self, name: str, key: str) -> float:
def update_layer(self, name: str, **kwargs):
"""Update a layer in a given item.

:param name: The layer name.
:param kwargs:
"""
A function to get a given item value
kwargs_no_magnetism = {k: v for k, v in kwargs.items() if k != 'magnetism_rhoM' and k != 'magnetism_thetaM'}
super().update_layer(name, **kwargs_no_magnetism)
if any(item.startswith('magnetism') for item in kwargs.keys()):
magnetism = names.Magnetism(rhoM=kwargs['magnetism_rhoM'], thetaM=kwargs['magnetism_thetaM'])
self.storage['layer'][name].magnetism = magnetism

:param name: The item name
def get_layer_value(self, name: str, key: str) -> float:
"""A function to get a given layer value

:param name: The layer name
:param key: The given value keys
:return: The desired value
"""
item = self.storage['item'][name]
item = getattr(item, key)
return getattr(item, 'value')
if key in ['magnetism_rhoM', 'magnetism_thetaM']:
return getattr(self.storage['layer'][name].magnetism, key.split('_')[-1])
return super().get_layer_value(name, key)

def create_model(self, name: str):
"""
Expand Down Expand Up @@ -151,7 +161,7 @@ def calculate(self, q_array: np.ndarray, model_name: str) -> np.ndarray:
# Get percentage of Q and change from sigma to FWHM
dq_array = dq_array * q_array / 100 / (2 * np.sqrt(2 * np.log(2)))

if not MAGNETISM:
if not self._magnetism:
probe = _get_probe(
q_array=q_array,
dq_array=dq_array,
Expand Down Expand Up @@ -236,7 +246,7 @@ def _get_polarized_probe(
storage: dict,
oversampling_factor: int = 1,
all_polarizations: bool = False,
) -> names.QProbe:
) -> names.PolarizedQProbe:
four_probes = []
for i in range(4):
if i == 0 or all_polarizations:
Expand Down
7 changes: 7 additions & 0 deletions src/easyreflectometry/calculators/refnx/wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,13 @@ def sld_profile(self, model_name: str) -> Tuple[np.ndarray, np.ndarray]:
"""
return _remove_unecessary_stacks(self.storage['model'][model_name].structure).sld_profile()

def set_magnetism(self, magnetism: bool) -> None:
"""Set the magnetism flag.

:param magnetism: The magnetism flag
"""
raise NotImplementedError('Magnetism is not supported by refnx')


def _remove_unecessary_stacks(current_structure: reflect.Structure) -> reflect.Structure:
"""
Expand Down
13 changes: 13 additions & 0 deletions src/easyreflectometry/calculators/wrapper_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
class WrapperBase:
def __init__(self):
"""Constructor."""
self._magnetism = False
self.storage = {
'material': {},
'layer': {},
Expand Down Expand Up @@ -212,3 +213,15 @@ def set_resolution_function(self, resolution_function: Callable[[np.array], np.a
:param resolution_function: The resolution function
"""
self._resolution_function = resolution_function

@property
def magnetism(self) -> None:
return self._magnetism

@magnetism.setter
def magnetism(self, magnetism: bool) -> None:
"""Set the magnetism flag.

:param magnetism: The magnetism flag
"""
self._magnetism = magnetism
47 changes: 46 additions & 1 deletion tests/calculators/refl1d/test_refl1d_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
import unittest

import numpy as np
from easyreflectometry.calculators.refl1d.calculator import Refl1d
from numpy.testing import assert_almost_equal
from numpy.testing import assert_equal

from easyreflectometry.calculators.refl1d.calculator import Refl1d


class TestRefl1d(unittest.TestCase):
def test_init(self):
Expand Down Expand Up @@ -108,6 +109,50 @@ def test_calculate2(self):
]
assert_almost_equal(p.fit_func(q, 'MyModel'), expected)

def test_calculate_magnetic(self):
p = Refl1d()
p.set_magnetism(True)
p._wrapper.create_material('Material1')
p._wrapper.update_material('Material1', rho=0.000, irho=0.000)
p._wrapper.create_material('Material2')
p._wrapper.update_material('Material2', rho=2.000, irho=0.000)
p._wrapper.create_material('Material3')
p._wrapper.update_material('Material3', rho=4.000, irho=0.000)
p._wrapper.create_model('MyModel')
p._wrapper.update_model('MyModel', bkg=1e-7)
p._wrapper.create_layer('Layer1')
p._wrapper.assign_material_to_layer('Material1', 'Layer1')
p._wrapper.create_layer('Layer2')
p._wrapper.assign_material_to_layer('Material2', 'Layer2')
p._wrapper.update_layer('Layer2', thickness=10, interface=1.0)
p._wrapper.create_layer('Layer3')
p._wrapper.assign_material_to_layer('Material3', 'Layer3')
p._wrapper.update_layer('Layer3', interface=1.0)
p._wrapper.create_item('Item1')
p._wrapper.add_layer_to_item('Layer1', 'Item1')
p._wrapper.create_item('Item2')
p._wrapper.add_layer_to_item('Layer2', 'Item2')
p._wrapper.add_layer_to_item('Layer1', 'Item2')
p._wrapper.create_item('Item3')
p._wrapper.add_layer_to_item('Layer3', 'Item3')
p._wrapper.add_item('Item1', 'MyModel')
p._wrapper.add_item('Item2', 'MyModel')
p._wrapper.add_item('Item3', 'MyModel')
q = np.linspace(0.001, 0.3, 10)
expected = [
9.99491251e-01,
1.08413641e-02,
1.46824402e-04,
2.11783999e-05,
5.24616472e-06,
1.61422945e-06,
5.66961121e-07,
2.34269519e-07,
1.30026616e-07,
1.05139655e-07,
]
assert_almost_equal(p.fit_func(q, 'MyModel'), expected)

def test_sld_profile(self):
p = Refl1d()
p._wrapper.create_material('Material1')
Expand Down
27 changes: 25 additions & 2 deletions tests/calculators/refl1d/test_refl1d_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,27 @@
from unittest.mock import patch

import numpy as np
from numpy.testing import assert_almost_equal
from numpy.testing import assert_equal

from easyreflectometry.calculators.refl1d.wrapper import Refl1dWrapper
from easyreflectometry.calculators.refl1d.wrapper import _build_sample
from easyreflectometry.calculators.refl1d.wrapper import _get_oversampling_q
from easyreflectometry.calculators.refl1d.wrapper import _get_polarized_probe
from easyreflectometry.calculators.refl1d.wrapper import _get_probe
from numpy.testing import assert_almost_equal
from numpy.testing import assert_equal


class TestRefl1d(unittest.TestCase):
def test_init(self):
p = Refl1dWrapper()
assert_equal(list(p.storage.keys()), ['material', 'layer', 'item', 'model'])
assert_equal(issubclass(p.storage['material'].__class__, dict), True)
assert p._magnetism is False

def test_set_magnetism(self):
p = Refl1dWrapper()
p.set_magnetism(True)
assert p._magnetism is True

def test_reset_storage(self):
p = Refl1dWrapper()
Expand Down Expand Up @@ -70,13 +77,29 @@ def test_update_layer(self):
assert_almost_equal(p.storage['layer']['Si'].thickness.value, 10)
assert_almost_equal(p.storage['layer']['Si'].interface.value, 5)

def test_update_magnetic_layer(self):
p = Refl1dWrapper()
p.set_magnetism(True)
p.create_layer('Si')
p.update_layer('Si', magnetism_rhoM=5, magnetism_thetaM=10)
assert_almost_equal(p.storage['layer']['Si'].magnetism.thetaM.value, 10)
assert_almost_equal(p.storage['layer']['Si'].magnetism.rhoM.value, 5)

def test_get_layer_value(self):
p = Refl1dWrapper()
p.create_layer('Si')
p.update_layer('Si', thickness=10, interface=5)
assert_almost_equal(p.get_layer_value('Si', 'thickness'), 10)
assert_almost_equal(p.get_layer_value('Si', 'interface'), 5)

def test_magnetic_get_layer_value(self):
p = Refl1dWrapper()
p.set_magnetism(True)
p.create_layer('Si')
p.update_layer('Si', magnetism_rhoM=5, magnetism_thetaM=10)
assert_almost_equal(p.get_layer_value('Si', 'magnetism_thetaM'), 10)
assert_almost_equal(p.get_layer_value('Si', 'magnetism_rhoM'), 5)

def test_create_item(self):
p = Refl1dWrapper()
p.create_item('SiNi')
Expand Down
13 changes: 10 additions & 3 deletions tests/calculators/refnx/test_refnx_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,28 @@
import unittest

import numpy as np
from easyreflectometry.calculators.refnx.wrapper import RefnxWrapper
from easyreflectometry.experiment import linear_spline_resolution_function
from easyreflectometry.experiment import percentage_fhwm_resolution_function
import pytest
from numpy.testing import assert_allclose
from numpy.testing import assert_almost_equal
from numpy.testing import assert_equal
from refnx import reflect

from easyreflectometry.calculators.refnx.wrapper import RefnxWrapper
from easyreflectometry.experiment import linear_spline_resolution_function
from easyreflectometry.experiment import percentage_fhwm_resolution_function


class TestRefnx(unittest.TestCase):
def test_init(self):
p = RefnxWrapper()
assert_equal(list(p.storage.keys()), ['material', 'layer', 'item', 'model'])
assert_equal(issubclass(p.storage['material'].__class__, dict), True)

def test_set_magnetism(self):
p = RefnxWrapper()
with pytest.raises(NotImplementedError):
p.set_magnetism(True)

def test_reset_storage(self):
p = RefnxWrapper()
p.storage['material']['a'] = 1
Expand Down