Skip to content

Observer Models

Flexpose implements multiple mathematical observer models to evaluate image quality, including Ideal, NPWE, and SNRU observers.

Observer Registry

flexpose.observer

Base Observer & Context

flexpose.observer.base

BaseObserver

Bases: ABC

Source code in flexpose/observer/base.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class BaseObserver(ABC):
    name: str

    @abstractmethod
    def compute_gamma(self, params: AcquisitionParams) -> float:

        """
        Compute the observer performance metric gamma for a single acquisition.

        Parameters
        ----------
        params : AcquisitionParams
            - focus_size_xy: focal spot (x, y) in cm
            - exposure_time_s: integration time in seconds

        Returns
        -------
        float
            A positive scalar gamma. Implementations should raise ValueError
            if required context (e.g., weights, detector curves) is missing
            or if inputs are invalid.
        """

compute_gamma(params) abstractmethod

Compute the observer performance metric gamma for a single acquisition.

Parameters

params : AcquisitionParams - focus_size_xy: focal spot (x, y) in cm - exposure_time_s: integration time in seconds

Returns

float A positive scalar gamma. Implementations should raise ValueError if required context (e.g., weights, detector curves) is missing or if inputs are invalid.

Source code in flexpose/observer/base.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@abstractmethod
def compute_gamma(self, params: AcquisitionParams) -> float:

    """
    Compute the observer performance metric gamma for a single acquisition.

    Parameters
    ----------
    params : AcquisitionParams
        - focus_size_xy: focal spot (x, y) in cm
        - exposure_time_s: integration time in seconds

    Returns
    -------
    float
        A positive scalar gamma. Implementations should raise ValueError
        if required context (e.g., weights, detector curves) is missing
        or if inputs are invalid.
    """

flexpose.observer.context

ImagingContext dataclass

Read-only container for shared imaging primitives used by observers.

Attributes

freq : (F,) ndarray Spatial frequency axis (cycles per unit length). dqe_interp : CubicSpline | None Interpolator over freq for detector DQE (already normalized if provided). mtf_interp : CubicSpline | None Interpolator over freq for detector MTF. sid : float Source-to-image distance. sod : float Source-to-object distance. velocity_xy : (2,) tuple[float, float] Object velocity along x and y. size_xy : (2,) tuple[float, float] Object size along x and y (used by task MTFs). shape : str Object shape: 'cylinder'|'disk'|'rectangular' (same as ContrastObject.shape).

Source code in flexpose/observer/context.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@dataclass(frozen=True)
class ImagingContext:
    """
    Read-only container for shared imaging primitives used by observers.

    Attributes
    ----------
    freq : (F,) ndarray
        Spatial frequency axis (cycles per unit length).
    dqe_interp : CubicSpline | None
        Interpolator over freq for detector DQE (already normalized if provided).
    mtf_interp : CubicSpline | None
        Interpolator over freq for detector MTF.
    sid : float
        Source-to-image distance.
    sod : float
        Source-to-object distance.
    velocity_xy : (2,) tuple[float, float]
        Object velocity along x and y.
    size_xy : (2,) tuple[float, float]
        Object size along x and y (used by task MTFs).
    shape : str
        Object shape: 'cylinder'|'disk'|'rectangular' (same as ContrastObject.shape).
    """
    freq: np.ndarray
    dqe_interp: CubicSpline | None
    mtf_interp: CubicSpline | None
    sid: float
    sod: float
    velocity_xy: tuple[float, float]
    size_xy: tuple[float, float]
    shape: str


    def dqe(self) -> np.ndarray:
        """Detector DQE sampled on self.freq; clipped to non-negative."""
        if self.dqe_interp is None:
            return np.ones(self.freq.size)
        out = self.dqe_interp(self.freq)
        out[out < 0] = 0.0
        return out

    def mtf_detector(self) -> np.ndarray:
        """Detector MTF sampled on self.freq; clipped to non-negative."""
        if self.mtf_interp is None:
            return np.ones(self.freq.size)
        out = self.mtf_interp(self.freq)
        out[out < 0] = 0.0
        return out

    @property
    def magnification(self) -> float:
        """Imaging magnification = SID / SOD."""
        return self.sid / self.sod

magnification property

Imaging magnification = SID / SOD.

dqe()

Detector DQE sampled on self.freq; clipped to non-negative.

Source code in flexpose/observer/context.py
40
41
42
43
44
45
46
def dqe(self) -> np.ndarray:
    """Detector DQE sampled on self.freq; clipped to non-negative."""
    if self.dqe_interp is None:
        return np.ones(self.freq.size)
    out = self.dqe_interp(self.freq)
    out[out < 0] = 0.0
    return out

mtf_detector()

Detector MTF sampled on self.freq; clipped to non-negative.

Source code in flexpose/observer/context.py
48
49
50
51
52
53
54
def mtf_detector(self) -> np.ndarray:
    """Detector MTF sampled on self.freq; clipped to non-negative."""
    if self.mtf_interp is None:
        return np.ones(self.freq.size)
    out = self.mtf_interp(self.freq)
    out[out < 0] = 0.0
    return out

build_context(config)

Construct ImagingContext from ConfigData. - Frequency grid uses min(object.size_xy) to define Nyquist and spans [1e-5, 2*Nyquist]. - DQE is normalized by its first tabulated value.

Source code in flexpose/observer/context.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def build_context(config: ConfigData) -> ImagingContext:
    """
    Construct ImagingContext from ConfigData.
    - Frequency grid uses min(object.size_xy) to define Nyquist and spans [1e-5, 2*Nyquist].
    - DQE is normalized by its first tabulated value.
    """

    size_min = min(config.object_data.size_xy)
    nyquist = 1.0 / (2.0 * size_min)
    freq = np.linspace(1e-5, 2.0 * nyquist, 100)


    dqe_tab = config.detector_data.dqe.values 
    if dqe_tab is not None:
        dqe_f, dqe_v = dqe_tab[:, 0], dqe_tab[:, 1]
        dqe_v = dqe_v / dqe_v[0]                  
        dqe_interp = CubicSpline(dqe_f, dqe_v)
    else:
        dqe_interp = None


    if config.detector_data.mtf.values is not None:
        mtf_tab = config.detector_data.mtf.values  
        mtf_f, mtf_v = mtf_tab[:, 0], mtf_tab[:, 1]
        mtf_interp = CubicSpline(mtf_f, mtf_v)
    else:
        mtf_interp = None


    ctx = ImagingContext(
        freq=freq,
        dqe_interp=dqe_interp,
        mtf_interp=mtf_interp,
        sid=config.detector_data.sid,
        sod=config.object_data.sod,
        velocity_xy=tuple(config.object_data.velocity_xy),
        size_xy=tuple(config.object_data.size_xy),
        shape=config.object_data.shape,
    )
    return ctx

Implementations

flexpose.observer.ideal

flexpose.observer.npwe

flexpose.observer.snru

Modulation Transfer Functions (MTF)

flexpose.observer.system_mtf

flexpose.observer.task_mtf

Task Weights

flexpose.observer.weights

Weights dataclass

Weights for observer performance metric, defined per dimension and sampled on the same frequency axis as the MTFs.

Source code in flexpose/observer/weights.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@dataclass(frozen=True)
class Weights:
    """
    Weights for observer performance metric, defined per dimension and sampled on 
    the same frequency axis as the MTFs.
    """
    values: np.ndarray          
    freq: np.ndarray            
    mode: Mode
    source_path: Optional[Path] = None
    normalized: bool = False    

    def __post_init__(self):
        if self.values.ndim != 2:
            raise ValueError("weights.values must be a 2D array (D, F)")
        D, F = self.values.shape
        if self.freq.ndim != 1 or self.freq.size != F:
            raise ValueError("freq must be 1D and match weights length")
        if not np.isfinite(self.values).all() or (self.values < 0).any():
            raise ValueError("weights must be finite and non-negative")
        self.values.setflags(write=False)


    @property
    def dims(self) -> int:
        return self.values.shape[0]

    def for_dim(self, dim: int) -> np.ndarray:
        return self.values[dim]

    def as_matrix(self) -> np.ndarray:
        return self.values

    def with_area_normalized(self) -> "Weights":
        """Return a copy where each dim integrates to 1.0 over freq (trapezoidal)."""
        vals = self.values.copy()
        vals.setflags(write=True)
        for d in range(self.dims):
            area = np.trapezoid(vals[d], self.freq)
            if area > 0:
                vals[d] /= area
        vals.setflags(write=False)
        return Weights(values=vals, freq=self.freq, mode=self.mode,
                       source_path=self.source_path, normalized=True)


    @classmethod
    def init_flat(cls, freq: np.ndarray, size_xy: tuple[float, float]) -> "Weights":
        D = len(size_xy)
        values = np.ones((D, freq.size))
        return cls(values=values, freq=freq, mode='flat', source_path=None, normalized=False)

    @classmethod
    def init_band(cls, freq: np.ndarray, size_xy: tuple[float, float]) -> "Weights":
        """
        Auto = Gaussian "band" around 1/(2*d) with sigma = 0.05*loc
        Normalized to integrate to 1 per dim, but not necessarily bounded by 1 at each freq.
        """
        D = len(size_xy)
        values = np.zeros((D, freq.size))
        for idx, d in enumerate(size_xy):
            loc = 1.0 / (2.0 * d)
            scale = 0.05 * loc
            w = stats.norm.pdf(freq, loc, scale)
            s = np.sum(w)
            if s > 0:
                w = w / s
            values[idx] = w
        return cls(values=values, freq=freq, mode='band', source_path=None, normalized=True)

    @classmethod
    def init_from_table(cls, freq: np.ndarray, size_xy: tuple[float, float], path: Path) -> "Weights":
        """
        TSV with columns:
          freq [cycles/cm], weight_x, weight_y
        Or just (freq, w) to apply same weights to both dims.
        """
        df = pd.read_csv(path, sep='\t')
        xy_equal = (df.values.shape[1] == 2)  # (freq, w) applies to both; else (freq, wx, wy)
        D = len(size_xy)
        values = np.ones((D, freq.size))
        f_tab = df.iloc[:, 0].values
        for idx in range(D):
            w_tab = df.iloc[:, 1].values if xy_equal else df.iloc[:, idx + 1].values
            values[idx] = CubicSpline(f_tab, w_tab, extrapolate=False)(freq)
            values[idx][~np.isfinite(values[idx])] = 0.0 
        return cls(values=values, freq=freq, mode='table', source_path=path, normalized=False)

    @classmethod
    def from_spec(cls,
                  freq: np.ndarray,
                  size_xy: tuple[float, float],
                  spec: Union[str, Path, None]) -> "Weights":
        """
        Build weights from a single spec:
          - None or ''  => flat weights (ones)
          - 'auto'      => Gaussian around 1/(2d) with sigma=0.05*loc (per current code)
          - Path/str    => TSV table (freq, [wx, wy] or single column applied to both); cubic-spline onto freq
        """
        if spec in (None, ''):
            return cls.init_flat(freq, size_xy)

        if isinstance(spec, str) and spec.lower() == 'band':
            return cls.init_band(freq, size_xy)

        # Otherwise: treat as path
        path = Path(spec)
        return cls.init_from_table(freq, size_xy, path)

from_spec(freq, size_xy, spec) classmethod

Build weights from a single spec
  • None or '' => flat weights (ones)
  • 'auto' => Gaussian around 1/(2d) with sigma=0.05*loc (per current code)
  • Path/str => TSV table (freq, [wx, wy] or single column applied to both); cubic-spline onto freq
Source code in flexpose/observer/weights.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@classmethod
def from_spec(cls,
              freq: np.ndarray,
              size_xy: tuple[float, float],
              spec: Union[str, Path, None]) -> "Weights":
    """
    Build weights from a single spec:
      - None or ''  => flat weights (ones)
      - 'auto'      => Gaussian around 1/(2d) with sigma=0.05*loc (per current code)
      - Path/str    => TSV table (freq, [wx, wy] or single column applied to both); cubic-spline onto freq
    """
    if spec in (None, ''):
        return cls.init_flat(freq, size_xy)

    if isinstance(spec, str) and spec.lower() == 'band':
        return cls.init_band(freq, size_xy)

    # Otherwise: treat as path
    path = Path(spec)
    return cls.init_from_table(freq, size_xy, path)

init_band(freq, size_xy) classmethod

Auto = Gaussian "band" around 1/(2d) with sigma = 0.05loc Normalized to integrate to 1 per dim, but not necessarily bounded by 1 at each freq.

Source code in flexpose/observer/weights.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
@classmethod
def init_band(cls, freq: np.ndarray, size_xy: tuple[float, float]) -> "Weights":
    """
    Auto = Gaussian "band" around 1/(2*d) with sigma = 0.05*loc
    Normalized to integrate to 1 per dim, but not necessarily bounded by 1 at each freq.
    """
    D = len(size_xy)
    values = np.zeros((D, freq.size))
    for idx, d in enumerate(size_xy):
        loc = 1.0 / (2.0 * d)
        scale = 0.05 * loc
        w = stats.norm.pdf(freq, loc, scale)
        s = np.sum(w)
        if s > 0:
            w = w / s
        values[idx] = w
    return cls(values=values, freq=freq, mode='band', source_path=None, normalized=True)

init_from_table(freq, size_xy, path) classmethod

TSV with columns

freq [cycles/cm], weight_x, weight_y

Or just (freq, w) to apply same weights to both dims.

Source code in flexpose/observer/weights.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@classmethod
def init_from_table(cls, freq: np.ndarray, size_xy: tuple[float, float], path: Path) -> "Weights":
    """
    TSV with columns:
      freq [cycles/cm], weight_x, weight_y
    Or just (freq, w) to apply same weights to both dims.
    """
    df = pd.read_csv(path, sep='\t')
    xy_equal = (df.values.shape[1] == 2)  # (freq, w) applies to both; else (freq, wx, wy)
    D = len(size_xy)
    values = np.ones((D, freq.size))
    f_tab = df.iloc[:, 0].values
    for idx in range(D):
        w_tab = df.iloc[:, 1].values if xy_equal else df.iloc[:, idx + 1].values
        values[idx] = CubicSpline(f_tab, w_tab, extrapolate=False)(freq)
        values[idx][~np.isfinite(values[idx])] = 0.0 
    return cls(values=values, freq=freq, mode='table', source_path=path, normalized=False)

with_area_normalized()

Return a copy where each dim integrates to 1.0 over freq (trapezoidal).

Source code in flexpose/observer/weights.py
45
46
47
48
49
50
51
52
53
54
55
def with_area_normalized(self) -> "Weights":
    """Return a copy where each dim integrates to 1.0 over freq (trapezoidal)."""
    vals = self.values.copy()
    vals.setflags(write=True)
    for d in range(self.dims):
        area = np.trapezoid(vals[d], self.freq)
        if area > 0:
            vals[d] /= area
    vals.setflags(write=False)
    return Weights(values=vals, freq=self.freq, mode=self.mode,
                   source_path=self.source_path, normalized=True)

Diagnostics

flexpose.observer.diagnostics

save_observer_diagnostics(obs, params, out_path, *, logger=None, options=None)

Save a PNG summarizing the components used by the observer on each axis

Plots per axis
  • Task MTF
  • System MTF (focus x motion)
  • (Optional) System x Detector MTF
  • (Optional) Detector MTF and DQE (on a secondary axis)
  • Task Weight (scaled to [0, 1] for plotting if selected)

Returns:

Type Description
Path

The saved path.

Source code in flexpose/observer/diagnostics.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def save_observer_diagnostics(
    obs: BaseObserver,
    params: AcquisitionParams,
    out_path: Path,
    *,
    logger: Logger | None = None,
    options: DiagnosticOptions | None = None,
) -> Path:
    """
    Save a PNG summarizing the components used by the observer on each axis

    Plots per axis:
      - Task MTF
      - System MTF (focus x motion)
      - (Optional) System x Detector MTF
      - (Optional) Detector MTF and DQE (on a secondary axis)
      - Task Weight (scaled to [0, 1] for plotting if selected)

    Returns:
      The saved path.
    """
    if options is None:
        options = DiagnosticOptions()

    ctx = getattr(obs, "ctx", None)
    weights = getattr(obs, "weights", None)
    if ctx is None or weights is None:
        raise ValueError("Observer is missing ctx and/or weights; cannot build diagnostics.")

    f = ctx.freq
    mag = ctx.magnification
    det_mtf = ctx.mtf_detector() if options.include_detector_curves else None
    dqe = ctx.dqe() if options.include_detector_curves else None


    D = len(ctx.size_xy)
    fig, axes = plt.subplots(
        nrows=1, ncols=D, figsize=(6.0 * D, 4.2), sharey=True, constrained_layout=True
    )
    if D == 1:
        axes = [axes]

    for dim in range(D):
        ax = axes[dim]
        size = ctx.size_xy[dim]
        w = weights.for_dim(dim)

        if ctx.shape in ("cylinder", "disk"):
            mtf_task = task_cylinder(f, radius=0.5 * size, magnification=mag)
        elif ctx.shape == "rectangular":
            mtf_task = task_rectangular(f, length=size, magnification=mag)
        else:
            mtf_task = task_default(f)

        sys_mtf = (
            mtf_focus(f, ctx.sid, ctx.sod, params.focus_size_xy, dim)
            * mtf_motion(f, ctx.velocity_xy, params.exposure_time_s, dim)
        )

        sys_x_det = sys_mtf * det_mtf if (det_mtf is not None and options.include_system_times_detector) else None

        ax.plot(f, mtf_task, label="Task MTF", lw=2.0)
        ax.plot(f, sys_mtf, label="System MTF (focus x motion)", lw=2.0)
        if sys_x_det is not None:
            ax.plot(f, sys_x_det, label="System x Detector MTF", lw=2.0, ls="--")

        if options.normalize_weight_for_plot:
            w_plot = (w - w.min()) / (w.max() - w.min() + 1e-15)
            ax.plot(f, w_plot, label="Task Weight (scaled)", lw=1.8, alpha=0.85)
        else:
            ax.plot(f, w, label="Task Weight", lw=1.8, alpha=0.85)

        ax.set_xlabel("Spatial frequency (cycles / unit)")
        if dim == 0:
            ax.set_ylabel("Amplitude / (scaled) weight")
        ax.set_title(f"Axis {dim}  |  size={size:g}")
        ax.grid(True, alpha=0.25)

        if options.include_detector_curves and det_mtf is not None and dqe is not None:
            ax2 = ax.twinx()
            ax2.plot(f, det_mtf, color="tab:purple", lw=1.5, alpha=0.9, label="Detector MTF")
            ax2.plot(f, dqe, color="tab:green", lw=1.5, alpha=0.9, ls="--", label="DQE")
            ax2.set_ylabel("Detector MTF / DQE")
            # Build a combined legend (primary + secondary)
            lines1, labels1 = ax.get_legend_handles_labels()
            lines2, labels2 = ax2.get_legend_handles_labels()
            ax2.legend(lines1 + lines2, labels1 + labels2, loc="upper right")
        else:
            ax.legend(loc="upper right")

    suptitle = options.title or f"Observer: {getattr(obs, 'name', type(obs).__name__)}"
    fig.suptitle(suptitle)

    out_path = Path(out_path)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    fig.savefig(out_path, dpi=options.dpi)
    plt.close(fig)

    if logger is not None:
        logger.info("Saved observer debug to %s")
    return out_path