qmri.thermometry¶
thermometry ¶
MR thermometry models.
This module provides functions for:
- Proton Resonance Frequency (PRF) thermometry
- Multi-echo dual-resonance thermometry (ethylene glycol phantoms)
R_SQUARED_THRESHOLD
module-attribute
¶
R_SQUARED_THRESHOLD: float = 0.9
Default threshold for acceptable fit quality (R² > 0.9).
RANDOM_SEED
module-attribute
¶
RANDOM_SEED: int = 840275920
Fixed seed for reproducibility of bootstrap sampling.
DfInitMethod
module-attribute
¶
DfInitMethod = Literal["multistart", "fixed", "lombscargle"]
Strategy for choosing the frequency-difference starting value of the fit.
"multistart"(default): fit from both the fixed default and the data-driven Lomb-Scargle estimate, and keep the highest-R² result. Most robust against frequency aliasing."fixed": a single fit from the fixed default starting value (:data:_DEFAULT_DF_GUESS). Cheapest; can alias on cold phantoms."lombscargle": a single fit seeded from the Lomb-Scargle estimate, falling back to the fixed default when no estimate can be made.
RegionAnalysisMethod
module-attribute
¶
RegionAnalysisMethod = Literal[
"regionwise", "voxelwise", "regionwise_bootstrap"
]
Analysis methods for image-based (segmentation-driven) thermometry fitting.
MultiEchoResult
dataclass
¶
MultiEchoResult(
temperature: float,
temperature_uncertainty: float,
df: float,
r_squared: float,
fitted_params: NDArray[floating],
n_bootstrap: int | None = None,
)
Result of multi-echo dual-resonance thermometry fitting.
Attributes:
| Name | Type | Description |
|---|---|---|
temperature |
float
|
Estimated temperature in degrees Celsius. |
temperature_uncertainty |
float
|
Uncertainty in temperature (°C). For single fits, from covariance matrix. For bootstrap fits, from standard deviation of bootstrap samples. |
df |
float
|
Fitted frequency difference in Hz. |
r_squared |
float
|
Coefficient of determination (R²) of the fit. For bootstrap, this is the mean R² across samples. |
fitted_params |
NDArray[floating]
|
Fitted parameters [A1, A2, R2*1, R2*2, df, dphi_deg]. For bootstrap, these are the mean parameters. |
n_bootstrap |
int | None
|
Number of bootstrap samples (None for single fit). |
RegionThermometryResult
dataclass
¶
RegionThermometryResult(
region_id: int,
region_size: int,
temperature: float,
temperature_uncertainty: float,
coverage_factor: float,
temperature_values: NDArray[floating],
temperature_uncertainty_values: NDArray[floating],
r_squared: NDArray[floating],
fitted_params: NDArray[floating],
mean_fitted_params: NDArray[floating],
signal_values: NDArray[floating],
)
Per-region results from segmentation-driven multi-echo thermometry.
A "region" is the set of voxels sharing a single non-zero integer label in the segmentation image. The interpretation of the per-fit arrays depends on the analysis method:
regionwise: a single fit of the region-mean signal (arrays length 1).voxelwise: one fit per voxel (arrays lengthregion_size).regionwise_bootstrap: one fit per bootstrap sample (arrays lengthn_bootstrap).
Attributes:
| Name | Type | Description |
|---|---|---|
region_id |
int
|
The integer label of the region in the segmentation. |
region_size |
int
|
Number of voxels in the region. |
temperature |
float
|
Representative region temperature in °C. For |
temperature_uncertainty |
float
|
Standard uncertainty (coverage factor
|
coverage_factor |
float
|
Coverage factor k for |
temperature_values |
NDArray[floating]
|
Temperature estimate from each individual fit (°C). |
temperature_uncertainty_values |
NDArray[floating]
|
Per-fit standard uncertainty in °C, derived from the fitted Δf covariance. |
r_squared |
NDArray[floating]
|
Coefficient of determination R² for each individual fit. |
fitted_params |
NDArray[floating]
|
Fitted parameters per fit, shape |
mean_fitted_params |
NDArray[floating]
|
Mean of |
signal_values |
NDArray[floating]
|
Signal values fed to each fit, shape |
to_dict ¶
Return a JSON-serialisable dictionary of the region results.
Source code in packages/qmri/src/qmri/thermometry/multiecho.py
PRFResult
dataclass
¶
calculate_df_from_temperature ¶
calculate_df_from_temperature(
temperature_celsius: float | NDArray[floating],
magnetic_field_tesla: float,
) -> float | NDArray[floating]
Calculate frequency difference from temperature for ethylene glycol.
Uses the empirical relationship:
This relationship is specific to ethylene glycol and should not be used for other substances without recalibration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
temperature_celsius
|
float | NDArray[floating]
|
Temperature in degrees Celsius. |
required |
magnetic_field_tesla
|
float
|
Magnetic field strength in Tesla. |
required |
Returns:
| Type | Description |
|---|---|
float | NDArray[floating]
|
Frequency difference in Hz. |
Example
Source code in packages/qmri/src/qmri/thermometry/multiecho.py
calculate_temperature_from_df ¶
calculate_temperature_from_df(
df: float | NDArray[floating],
magnetic_field_tesla: float,
) -> float | NDArray[floating]
Calculate temperature from frequency difference for ethylene glycol.
Uses the empirical relationship:
This relationship is specific to ethylene glycol and should not be used for other substances without recalibration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
float | NDArray[floating]
|
Frequency difference in Hz. |
required |
magnetic_field_tesla
|
float
|
Magnetic field strength in Tesla. |
required |
Returns:
| Type | Description |
|---|---|
float | NDArray[floating]
|
Temperature in degrees Celsius. |
Example
Source code in packages/qmri/src/qmri/thermometry/multiecho.py
calculate_temperature_uncertainty ¶
Calculate temperature uncertainty from frequency difference uncertainty.
Uses uncertainty propagation:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_uncertainty
|
float
|
Uncertainty in frequency difference (Hz). |
required |
magnetic_field_tesla
|
float
|
Magnetic field strength in Tesla. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Uncertainty in temperature (°C). |
Example
Source code in packages/qmri/src/qmri/thermometry/multiecho.py
fit_multiecho_thermometry ¶
fit_multiecho_thermometry(
signal: NDArray[floating],
echo_times: NDArray[floating],
magnetic_field_tesla: float,
method: Literal["single", "bootstrap"] = "single",
n_bootstrap: int = 100,
r_squared_threshold: float = R_SQUARED_THRESHOLD,
df_init: DfInitMethod = "multistart",
) -> MultiEchoResult
Fit multi-echo signal to dual-resonance model for thermometry.
This function fits the dual-resonance signal model to multi-echo magnitude data and converts the fitted frequency difference to temperature using the ethylene glycol calibration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
NDArray[floating]
|
Multi-echo magnitude signal array. Shape should be (n_echoes,). |
required |
echo_times
|
NDArray[floating]
|
Array of echo times in seconds. |
required |
magnetic_field_tesla
|
float
|
Magnetic field strength in Tesla. |
required |
method
|
Literal['single', 'bootstrap']
|
Fitting method. Options: - "single": Single least-squares fit (default). - "bootstrap": Bootstrap resampling for uncertainty estimation. |
'single'
|
n_bootstrap
|
int
|
Number of bootstrap samples (default 100). Only used when method="bootstrap". |
100
|
r_squared_threshold
|
float
|
Minimum R² for accepting a fit (default 0.9). For bootstrap, samples below threshold are excluded. |
R_SQUARED_THRESHOLD
|
df_init
|
DfInitMethod
|
Frequency starting-value strategy — |
'multistart'
|
Returns:
| Type | Description |
|---|---|
MultiEchoResult
|
MultiEchoResult containing temperature, uncertainty, and fit parameters. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If signal and echo_times have different lengths. |
Example
import numpy as np
from qmri.thermometry.multiecho import (
thermometry_signal_model,
calculate_df_from_temperature,
fit_multiecho_thermometry,
)
# Generate synthetic data at 25°C
magnetic_field = 3.0
echo_times = np.linspace(0.001, 0.024, 24)
df_true = calculate_df_from_temperature(25.0, magnetic_field)
signal = thermometry_signal_model(
echo_times, 1.0, 0.5, 50.0, 100.0, df_true, 45.0
)
# Fit the model
result = fit_multiecho_thermometry(
signal, echo_times, magnetic_field, method="single"
)
temp = result.temperature
uncert = result.temperature_uncertainty
print(f"Temperature: {temp:.1f} ± {uncert:.2f} °C")
print(f"R²: {result.r_squared:.4f}")
# With bootstrap uncertainty
result_bs = fit_multiecho_thermometry(
signal, echo_times, magnetic_field,
method="bootstrap", n_bootstrap=50
)
print(f"Bootstrap uncertainty: {result_bs.temperature_uncertainty:.2f} °C")
Note
The temperature-frequency calibration is specific to ethylene glycol. For other substances, the fitted frequency difference (df) can still be used, but the temperature conversion will not be valid.
Source code in packages/qmri/src/qmri/thermometry/multiecho.py
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 | |
fit_multiecho_thermometry_image ¶
fit_multiecho_thermometry_image(
signal: NDArray[floating],
segmentation: NDArray[floating],
echo_times: NDArray[floating],
magnetic_field_tesla: float,
method: RegionAnalysisMethod = "regionwise",
n_bootstrap: int = 100,
r_squared_threshold: float = R_SQUARED_THRESHOLD,
df_init: DfInitMethod = "multistart",
) -> tuple[
NDArray[floating], list[RegionThermometryResult]
]
Fit multi-echo thermometry over a segmented image volume.
The segmentation defines discrete regions by integer label; label 0 is
treated as background and ignored. Each non-zero region is fitted with the
dual-resonance model and the fitted frequency difference is converted to
temperature with the ethylene-glycol calibration.
The arrays must be co-located in world space: signal is the 4D
magnitude volume (nx, ny, nz, n_echoes) and segmentation is the 3D
label map (nx, ny, nz). echo_times must have length n_echoes and
be in seconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
NDArray[floating]
|
Multi-echo magnitude data, shape |
required |
segmentation
|
NDArray[floating]
|
Integer label map, shape |
required |
echo_times
|
NDArray[floating]
|
Echo times in seconds, shape |
required |
magnetic_field_tesla
|
float
|
Magnetic field strength \(B_0\) in Tesla. |
required |
method
|
RegionAnalysisMethod
|
Analysis method:
|
'regionwise'
|
n_bootstrap
|
int
|
Number of bootstrap samples ( |
100
|
r_squared_threshold
|
float
|
Minimum R² for a fit to contribute to
|
R_SQUARED_THRESHOLD
|
df_init
|
DfInitMethod
|
Frequency starting-value strategy — |
'multistart'
|
Returns:
| Type | Description |
|---|---|
NDArray[floating]
|
A tuple |
list[RegionThermometryResult]
|
array of temperatures in °C co-located with the segmentation, and |
tuple[NDArray[floating], list[RegionThermometryResult]]
|
|
tuple[NDArray[floating], list[RegionThermometryResult]]
|
non-empty region (in ascending label order). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the array dimensions or echo-time length are inconsistent,
or if |
Source code in packages/qmri/src/qmri/thermometry/multiecho.py
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 | |
lsq_fit_thermometry_signal_model ¶
lsq_fit_thermometry_signal_model(
echo_times: NDArray[floating],
signal_values: NDArray[floating],
initial_guess: list[float],
) -> tuple[NDArray[floating], NDArray[floating], float]
Perform least squares fit of the dual-resonance signal model.
Fits the signal data to the thermometry signal model using scipy.optimize.curve_fit with bounded parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
echo_times
|
NDArray[floating]
|
Array of echo times in seconds. |
required |
signal_values
|
NDArray[floating]
|
Array of signal values at each echo time. |
required |
initial_guess
|
list[float]
|
Initial parameter estimates [amplitude_1, amplitude_2, r2star_1, r2star_2, df, dphi_deg]. |
required |
Returns:
| Type | Description |
|---|---|
tuple[NDArray[floating], NDArray[floating], float]
|
Tuple containing: - popt: Optimal parameters [A1, A2, R2*1, R2*2, df, dphi]. - pcov: Covariance matrix of the parameters. - r_squared: Coefficient of determination (R²) of the fit. |
If the fit fails to converge, returns arrays of NaN values.
Example
import numpy as np
from qmri.thermometry.multiecho import (
thermometry_signal_model,
lsq_fit_thermometry_signal_model,
)
# Generate synthetic data
echo_times = np.linspace(0.001, 0.024, 24)
true_params = [1.0, 0.5, 50.0, 100.0, 200.0, 45.0]
signal = thermometry_signal_model(echo_times, *true_params)
# Fit the model
initial_guess = [0.8, 0.4, 40.0, 80.0, 180.0, 30.0]
popt, pcov, r2 = lsq_fit_thermometry_signal_model(
echo_times, signal, initial_guess
)
print(f"R²: {r2:.4f}")
Source code in packages/qmri/src/qmri/thermometry/multiecho.py
thermometry_signal_model ¶
thermometry_signal_model(
t: NDArray[floating],
amplitude_1: float,
amplitude_2: float,
r2star_1: float,
r2star_2: float,
df: float | NDArray[floating],
dphi_deg: float,
) -> NDArray[floating]
Calculate the dual-resonance signal at time t.
Implements the signal model equation:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
NDArray[floating]
|
Echo times in seconds. |
required |
amplitude_1
|
float
|
Amplitude of the first signal component. |
required |
amplitude_2
|
float
|
Amplitude of the second signal component. |
required |
r2star_1
|
float
|
R2* relaxation rate of the first component (1/s). |
required |
r2star_2
|
float
|
R2* relaxation rate of the second component (1/s). |
required |
df
|
float | NDArray[floating]
|
Frequency difference between the two components (Hz). |
required |
dphi_deg
|
float
|
Phase difference between the components (degrees). |
required |
Returns:
| Type | Description |
|---|---|
NDArray[floating]
|
Signal magnitude at each echo time. |
Example
Source code in packages/qmri/src/qmri/thermometry/multiecho.py
calculate_temperature ¶
calculate_temperature(
phase_difference: NDArray[floating] | float,
echo_time: NDArray[floating] | float,
magnetic_field: float,
baseline_temperature: NDArray[floating] | float = 37.0,
prf_coefficient: float = PRF_THERMAL_COEFFICIENT,
) -> PRFResult
Calculate temperature change from phase difference.
Implements the inverse PRF equation:
where the phase difference is \(\phi_{heated} - \phi_{baseline}\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase_difference
|
NDArray[floating] | float
|
Phase difference between heated and baseline images in radians. Calculated as phase_heated - phase_baseline. |
required |
echo_time
|
NDArray[floating] | float
|
Echo time (TE) in seconds. |
required |
magnetic_field
|
float
|
Main magnetic field strength (B0) in Tesla. |
required |
baseline_temperature
|
NDArray[floating] | float
|
Baseline temperature in degrees Celsius (default 37.0). This is the reference temperature at which the baseline phase image was acquired. The absolute temperature is calculated as baseline_temperature + temperature_change. |
37.0
|
prf_coefficient
|
float
|
PRF thermal coefficient in per degree Celsius (default -0.01e-6). The standard value for water is approximately -0.01 ppm/°C. |
PRF_THERMAL_COEFFICIENT
|
Returns:
| Type | Description |
|---|---|
PRFResult
|
Result containing temperature change and phase difference. |
Example
import numpy as np
from qmri.thermometry import prf
# Calculate temperature from measured phase difference
result = prf.calculate_temperature(
phase_difference=-0.16, # radians (negative = heating)
echo_time=0.020, # 20 ms
magnetic_field=3.0,
)
print(f"Temperature change: {result.temperature_change:.1f} °C")
Important considerations for PRF thermometry:
-
Phase wrapping: Phase values are typically wrapped to [-pi, pi]. For large temperature changes, phase unwrapping may be required.
-
Reference tissue: PRF thermometry provides relative temperature changes. A reference tissue (e.g., subcutaneous fat) with known temperature can be used for drift correction.
-
Fat signal: Fat does not exhibit PRF shift with temperature. Fat suppression or water-fat separation is often used.
-
Motion: Motion between baseline and heated acquisitions causes artefacts. Multi-baseline or referenceless methods can help.
-
Field drift: B0 drift over time causes apparent temperature changes. Drift correction using reference regions is recommended.
See Also
signal_phase_shift: Calculate phase shift from temperature change.
Source code in packages/qmri/src/qmri/thermometry/prf.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
signal_phase_shift ¶
signal_phase_shift(
temperature_change: NDArray[floating] | float,
echo_time: NDArray[floating] | float,
magnetic_field: float,
prf_coefficient: float = PRF_THERMAL_COEFFICIENT,
) -> NDArray[floating]
Calculate temperature-induced phase shift.
Implements the PRF phase shift equation:
Note that the negative sign arises from the negative PRF thermal coefficient, which means increasing temperature causes a negative phase shift (frequency decrease).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
temperature_change
|
NDArray[floating] | float
|
Temperature change in degrees Celsius. |
required |
echo_time
|
NDArray[floating] | float
|
Echo time (TE) in seconds. |
required |
magnetic_field
|
float
|
Main magnetic field strength (B0) in Tesla. |
required |
prf_coefficient
|
float
|
PRF thermal coefficient in per degree Celsius (default -0.01e-6). The standard value for water is approximately -0.01 ppm/°C. |
PRF_THERMAL_COEFFICIENT
|
Returns:
| Type | Description |
|---|---|
NDArray[floating]
|
Phase shift in radians. |
Example
The phase shift is proportional to:
- Temperature change (linear)
- Echo time (longer TE gives larger phase shift but lower SNR)
- Field strength (higher field gives larger phase shift)
Typical phase shifts at 3T with TE=20ms are approximately 5-10 degrees per degree Celsius temperature change.