Skip to content

API Reference

sans_fitter.sans_fitter.SANSFitter

A flexible SANS model fitter that works with any SasModels model.

Features: - Loads data from various file formats (CSV, XML, HDF5) - Model-agnostic: works with any model from SasModels library - Supports multiple fitting engines (BUMPS, LMFit) - User-friendly parameter management

Example

fitter = SANSFitter() fitter.load_data('my_sans_data.csv') fitter.set_model('cylinder') fitter.set_param('radius', value=20, min=1, max=100) fitter.set_param('length', value=400, min=10, max=1000) result = fitter.fit(engine='bumps') fitter.plot_results()

Source code in src/sans_fitter/sans_fitter.py
 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
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
class SANSFitter:
    """
    A flexible SANS model fitter that works with any SasModels model.

    Features:
    - Loads data from various file formats (CSV, XML, HDF5)
    - Model-agnostic: works with any model from SasModels library
    - Supports multiple fitting engines (BUMPS, LMFit)
    - User-friendly parameter management

    Example:
        >>> fitter = SANSFitter()
        >>> fitter.load_data('my_sans_data.csv')
        >>> fitter.set_model('cylinder')
        >>> fitter.set_param('radius', value=20, min=1, max=100)
        >>> fitter.set_param('length', value=400, min=10, max=1000)
        >>> result = fitter.fit(engine='bumps')
        >>> fitter.plot_results()
    """

    def __init__(self):
        """Initialize the SANS fitter."""
        self.data = None
        self.kernel = None
        self.model_name = None
        self.params = {}
        self.fit_result = None
        self._fitted_model = None

        # Structure factor support
        self._structure_factor_name = None
        self._radius_effective_mode = 'unconstrained'
        self._form_factor_params = {}  # Store form factor params separately

    def load_data(self, filename: str) -> None:
        """
        Load SANS data from a file.

        Supports CSV, XML, and HDF5 formats through sasdata.

        Args:
            filename: Path to the data file

        Raises:
            FileNotFoundError: If the file doesn't exist
            ValueError: If the data cannot be loaded or is invalid
        """
        loader = Loader()
        try:
            data_list = loader.load(filename)
            if not data_list:
                raise ValueError(f'No data loaded from {filename}')

            self.data = data_list[0]

            # Setup required fields for sasmodels
            self.data.qmin = getattr(self.data, 'qmin', None) or self.data.x.min()
            self.data.qmax = getattr(self.data, 'qmax', None) or self.data.x.max()
            self.data.mask = np.isnan(self.data.y)

            print(f'✓ Loaded data from {filename}')
            print(f'  Q range: {self.data.qmin:.4f} to {self.data.qmax:.4f} Å⁻¹')
            print(f'  Data points: {len(self.data.x)}')

        except Exception as e:
            raise ValueError(f'Failed to load data from {filename}: {str(e)}') from e

    def set_model(self, model_name: str, platform: str = 'cpu') -> None:
        """
        Set the SANS model to use for fitting.

        This resets any active structure factor to ensure a clean state.

        Args:
            model_name: Name of the model from SasModels (e.g., 'cylinder', 'sphere')
            platform: Computation platform ('cpu' or 'opencl')

        Raises:
            ValueError: If the model name is not valid
        """
        try:
            # Reset structure factor when changing form factor
            self._structure_factor_name = None
            self._radius_effective_mode = 'unconstrained'
            self._form_factor_params = {}

            # Force CPU platform to avoid OpenCL issues
            self.kernel = load_model(model_name, dtype='single', platform='dll')
            self.model_name = model_name

            # Initialize parameters with default values from the model
            self.params = {}
            for param in self.kernel.info.parameters.kernel_parameters:
                self.params[param.name] = {
                    'value': param.default,
                    'min': param.limits[0] if param.limits[0] > -np.inf else 0,
                    'max': param.limits[1] if param.limits[1] < np.inf else param.default * 10,
                    'vary': False,  # By default, parameters are fixed
                    'description': param.description,
                }

            # Add implicit scale and background parameters (present in all models)
            # These are not in kernel_parameters but are always available
            if 'scale' not in self.params:
                self.params['scale'] = {
                    'value': 1.0,
                    'min': 0.0,
                    'max': np.inf,
                    'vary': False,
                    'description': 'Scale factor for the model intensity',
                }

            if 'background' not in self.params:
                self.params['background'] = {
                    'value': 0.0,
                    'min': 0.0,
                    'max': np.inf,
                    'vary': False,
                    'description': 'Constant background level',
                }

            print(f"✓ Model '{model_name}' loaded successfully")
            print(f'  Available parameters: {len(self.params)}')

        except Exception as e:
            raise ValueError(f"Failed to load model '{model_name}': {str(e)}") from e

    def get_params(self) -> None:
        """Display current parameter values and settings in a readable format."""
        if not self.params:
            print('No model loaded. Use set_model() first.')
            return

        print(f'\n{"=" * 80}')
        print(f'Model: {self.model_name}')
        if self._structure_factor_name:
            print(f'Structure Factor: {self._structure_factor_name}')
            print(f'Radius Effective Mode: {self._radius_effective_mode}')
        print(f'{"=" * 80}')
        print(f'{"Parameter":<20} {"Value":<12} {"Min":<12} {"Max":<12} {"Vary":<8}')
        print(f'{"-" * 80}')

        for name, info in self.params.items():
            vary_str = '✓' if info['vary'] else '✗'
            # Show linked indicator for radius_effective in link_radius mode
            if name == 'radius_effective' and self._radius_effective_mode == 'link_radius':
                vary_str = '→radius'
            print(
                f'{name:<20} {info["value"]:<12.4g} {info["min"]:<12.4g} '
                f'{info["max"]:<12.4g} {vary_str:<8}'
            )
        print(f'{"=" * 80}\n')

    def set_param(
        self,
        name: str,
        value: Optional[float] = None,
        min: Optional[float] = None,
        max: Optional[float] = None,
        vary: Optional[bool] = None,
    ) -> None:
        """
        Configure a model parameter for fitting.

        Args:
            name: Parameter name
            value: Initial value (optional)
            min: Minimum bound (optional)
            max: Maximum bound (optional)
            vary: Whether to vary during fit (optional)

        Raises:
            KeyError: If parameter name doesn't exist for the current model
        """
        if name not in self.params:
            available = ', '.join(self.params.keys())
            raise KeyError(f"Parameter '{name}' not found. Available: {available}")

        if value is not None:
            self.params[name]['value'] = value
            # Sync radius_effective when radius is updated in link_radius mode
            if (
                name == 'radius'
                and self._radius_effective_mode == 'link_radius'
                and 'radius_effective' in self.params
            ):
                self.params['radius_effective']['value'] = value
        if min is not None:
            self.params[name]['min'] = min
        if max is not None:
            self.params[name]['max'] = max
        if vary is not None:
            self.params[name]['vary'] = vary

    def set_structure_factor(
        self, structure_factor_name: str, radius_effective_mode: str = 'unconstrained'
    ) -> None:
        """
        Apply a structure factor to the current model.

        This creates a product model (form_factor * structure_factor) to account
        for inter-particle interactions in concentrated systems.

        Supported structure factors:
        - 'hardsphere': Hard sphere structure factor (Percus-Yevick closure)
        - 'hayter_msa': Hayter-Penfold rescaled MSA for charged spheres
        - 'squarewell': Square well potential
        - 'stickyhardsphere': Sticky hard sphere (Baxter model)

        Args:
            structure_factor_name: Name of the structure factor (e.g., 'hardsphere')
            radius_effective_mode: How to handle the effective radius.
                - 'unconstrained': 'radius_effective' is a separate fitting parameter.
                - 'link_radius': 'radius_effective' is constrained to the form factor's 'radius'.

        Raises:
            ValueError: If no form factor model is set, or if the structure factor is invalid
        """
        if self.kernel is None or self.model_name is None:
            raise ValueError('No form factor model loaded. Use set_model() first.')

        # Validate structure factor name
        supported_sf = ['hardsphere', 'hayter_msa', 'squarewell', 'stickyhardsphere']
        if structure_factor_name not in supported_sf:
            raise ValueError(
                f"Unsupported structure factor '{structure_factor_name}'. "
                f'Supported: {", ".join(supported_sf)}'
            )

        # Validate radius_effective_mode
        if radius_effective_mode not in ['unconstrained', 'link_radius']:
            raise ValueError(
                f"Invalid radius_effective_mode '{radius_effective_mode}'. "
                "Use 'unconstrained' or 'link_radius'."
            )

        # Store form factor parameters before switching to product model
        if not self._form_factor_params:
            self._form_factor_params = {k: dict(v) for k, v in self.params.items()}

        # Create product model name
        full_model_name = f'{self.model_name}@{structure_factor_name}'

        try:
            # Load the product model
            self.kernel = load_model(full_model_name, dtype='single', platform='dll')
            self._structure_factor_name = structure_factor_name
            self._radius_effective_mode = radius_effective_mode

            # Rebuild parameters from product model
            new_params = {}
            for param in self.kernel.info.parameters.kernel_parameters:
                # Preserve existing values if parameter already exists
                if param.name in self._form_factor_params:
                    new_params[param.name] = dict(self._form_factor_params[param.name])
                else:
                    new_params[param.name] = {
                        'value': param.default,
                        'min': param.limits[0] if param.limits[0] > -np.inf else 0,
                        'max': param.limits[1] if param.limits[1] < np.inf else param.default * 10,
                        'vary': False,
                        'description': param.description,
                    }

            # Ensure scale and background are present
            if 'scale' not in new_params:
                if 'scale' in self._form_factor_params:
                    new_params['scale'] = dict(self._form_factor_params['scale'])
                else:
                    new_params['scale'] = {
                        'value': 1.0,
                        'min': 0.0,
                        'max': np.inf,
                        'vary': False,
                        'description': 'Scale factor for the model intensity',
                    }

            if 'background' not in new_params:
                if 'background' in self._form_factor_params:
                    new_params['background'] = dict(self._form_factor_params['background'])
                else:
                    new_params['background'] = {
                        'value': 0.0,
                        'min': 0.0,
                        'max': np.inf,
                        'vary': False,
                        'description': 'Constant background level',
                    }

            self.params = new_params

            # Handle radius_effective linking
            if radius_effective_mode == 'link_radius':
                if 'radius' in self.params and 'radius_effective' in self.params:
                    # Link radius_effective to radius
                    self.params['radius_effective']['value'] = self.params['radius']['value']
                    self.params['radius_effective']['vary'] = False
                    print("  Note: 'radius_effective' linked to 'radius' value")
                else:
                    warnings.warn(
                        'Cannot link radius_effective to radius: one or both parameters not found. '
                        'Using unconstrained mode.',
                        stacklevel=2,
                    )
                    self._radius_effective_mode = 'unconstrained'

            print(f"✓ Structure factor '{structure_factor_name}' applied to '{self.model_name}'")
            print(f'  Product model: {full_model_name}')
            print(f'  Total parameters: {len(self.params)}')

        except Exception as e:
            raise ValueError(f"Failed to load model '{full_model_name}': {str(e)}") from e

    def remove_structure_factor(self) -> None:
        """
        Remove the current structure factor and revert to the form factor only.

        Raises:
            ValueError: If no structure factor is currently set
        """
        if self._structure_factor_name is None:
            raise ValueError('No structure factor is currently set.')

        # Reload the original form factor model
        try:
            self.kernel = load_model(self.model_name, dtype='single', platform='dll')

            # Restore form factor parameters
            self.params = {k: dict(v) for k, v in self._form_factor_params.items()}

            sf_name = self._structure_factor_name
            self._structure_factor_name = None
            self._radius_effective_mode = 'unconstrained'
            self._form_factor_params = {}

            print(f"✓ Structure factor '{sf_name}' removed")
            print(f'  Reverted to form factor: {self.model_name}')

        except Exception as e:
            raise ValueError(f'Failed to reload form factor model: {str(e)}') from e

    def get_structure_factor(self) -> Optional[str]:
        """
        Get the name of the currently applied structure factor.

        Returns:
            Name of the structure factor, or None if no structure factor is set
        """
        return self._structure_factor_name

    def fit(
        self,
        engine: Literal['bumps', 'lmfit'] = 'bumps',
        method: Optional[str] = None,
        **kwargs: Any,
    ) -> dict[str, Any]:
        """
        Perform the fit using the specified engine.

        Args:
            engine: Fitting engine ('bumps' or 'lmfit')
            method: Optimization method (engine-specific)
                   - BUMPS: 'amoeba', 'lm', 'newton', 'de' (default: 'amoeba')
                   - LMFit: 'leastsq', 'least_squares', 'differential_evolution', etc.
            **kwargs: Additional arguments passed to the fitting engine

        Returns:
            Dictionary with fit results including chi-squared and parameter values

        Raises:
            ValueError: If data or model not loaded, or invalid engine
        """
        if self.data is None:
            raise ValueError('No data loaded. Use load_data() first.')
        if self.kernel is None:
            raise ValueError('No model loaded. Use set_model() first.')

        if engine == 'bumps':
            return self._fit_bumps(method or 'amoeba', **kwargs)
        elif engine == 'lmfit':
            if not LMFIT_AVAILABLE:
                raise ValueError("scipy is not installed. Use 'bumps' engine or install scipy.")
            return self._fit_lmfit(method or 'leastsq', **kwargs)
        else:
            raise ValueError(f"Unknown engine '{engine}'. Use 'bumps' or 'lmfit'.")

    def _fit_bumps(self, method: str = 'amoeba', **kwargs: Any) -> dict[str, Any]:
        """Fit using BUMPS engine."""
        # Prepare parameter dictionary for BumpsModel
        pars = {name: info['value'] for name, info in self.params.items()}

        # Create BUMPS model
        model = BumpsModel(self.kernel, **pars)

        # Set parameter ranges for fitting
        for name, info in self.params.items():
            if info['vary']:
                param_obj = getattr(model, name)
                param_obj.range(info['min'], info['max'])

        # Handle radius_effective linking in link_radius mode
        if (
            self._radius_effective_mode == 'link_radius'
            and hasattr(model, 'radius_effective')
            and hasattr(model, 'radius')
        ):
            # Constrain radius_effective to equal radius
            model.radius_effective = model.radius

        # Create experiment and fit problem
        experiment = Experiment(data=self.data, model=model)
        problem = FitProblem(experiment)

        print(f'\nInitial χ² = {problem.chisq():.4f}')
        print(f'Fitting with BUMPS (method: {method})...')

        # Perform fit
        result = bumps_fit(problem, method=method, **kwargs)

        # Store results
        self.fit_result = {
            'engine': 'bumps',
            'method': method,
            'chisq': problem.chisq(),
            'parameters': {},
            'problem': problem,
            'result': result,
        }

        # Extract fitted parameters
        for k, v, dv in zip(problem.labels(), result.x, result.dx):
            self.fit_result['parameters'][k] = {
                'value': v,
                'stderr': dv,
                'formatted': format_uncertainty(v, dv),
            }
            # Update internal parameter values
            if k in self.params:
                self.params[k]['value'] = v

        self._fitted_model = problem

        # Print results
        print('\n✓ Fit completed!')
        print(f'Final χ² = {self.fit_result["chisq"]:.4f}')
        print('\nFitted parameters:')
        for name, info in self.fit_result['parameters'].items():
            print(f'  {name}: {info["formatted"]}')

        return self.fit_result

    def _fit_lmfit(self, method: str = 'leastsq', **kwargs: Any) -> dict[str, Any]:
        """Fit using scipy.optimize (leastsq/least_squares) engine."""
        # Get initial parameter values and build bounds
        param_names = [name for name, info in self.params.items() if info['vary']]
        x0 = np.array([self.params[name]['value'] for name in param_names])
        bounds_lower = np.array([self.params[name]['min'] for name in param_names])
        bounds_upper = np.array([self.params[name]['max'] for name in param_names])

        # Create direct model calculator (kernel already set to CPU in set_model)
        calculator = DirectModel(self.data, self.kernel)

        # Capture instance attributes for use in residual closure
        radius_effective_mode = self._radius_effective_mode

        # Define residual function
        def residual(x):
            # Build full parameter dictionary
            par_dict = {name: info['value'] for name, info in self.params.items()}
            # Update with fitted parameters
            for i, name in enumerate(param_names):
                par_dict[name] = x[i]

            # Handle radius_effective linking in link_radius mode
            if (
                radius_effective_mode == 'link_radius'
                and 'radius' in par_dict
                and 'radius_effective' in par_dict
            ):
                par_dict['radius_effective'] = par_dict['radius']

            # Calculate model
            I_calc = calculator(**par_dict)
            # Return weighted residuals
            return (self.data.y - I_calc) / self.data.dy

        print(f'\nFitting with scipy.optimize (method: {method})...')

        # Perform fit based on method
        if method == 'leastsq':
            # Levenberg-Marquardt (no bounds support)
            result = leastsq(residual, x0, full_output=True, **kwargs)
            fitted_params = result[0]
            cov_matrix = result[1]
            result[2]

            # Calculate parameter errors from covariance matrix
            if cov_matrix is not None:
                param_errors = np.sqrt(np.diag(cov_matrix))
            else:
                param_errors = np.zeros_like(fitted_params)

            # Calculate chi-squared
            final_residuals = residual(fitted_params)
            chisq = np.sum(final_residuals**2)

        elif method == 'least_squares':
            # Trust Region Reflective (supports bounds)
            bounds = (bounds_lower, bounds_upper)
            result = least_squares(residual, x0, bounds=bounds, **kwargs)
            fitted_params = result.x

            # Estimate parameter errors from Jacobian
            try:
                # Compute covariance from Jacobian
                J = result.jac
                cov_matrix = np.linalg.inv(J.T @ J)
                param_errors = np.sqrt(np.diag(cov_matrix))
            except Exception as e:
                # If Jacobian-based covariance estimation fails, fall back to zeros
                # and emit a warning so users can investigate the cause.
                warnings.warn(f'Failed to compute covariance from Jacobian: {e}', stacklevel=2)
                param_errors = np.zeros_like(fitted_params)

            chisq = np.sum(result.fun**2)

        elif method == 'differential_evolution':
            # Global optimizer (supports bounds)
            bounds_list = list(zip(bounds_lower, bounds_upper))

            def objective(x):
                return np.sum(residual(x) ** 2)

            result = differential_evolution(objective, bounds_list, **kwargs)
            fitted_params = result.x
            param_errors = np.zeros_like(fitted_params)  # DE doesn't provide errors
            chisq = result.fun

        else:
            raise ValueError(
                f"Unknown method '{method}'. Use 'leastsq', 'least_squares', or 'differential_evolution'."
            )

        # Store results
        self.fit_result = {
            'engine': 'lmfit',
            'method': method,
            'chisq': chisq,
            'parameters': {},
            'result': result,
        }

        # Extract fitted parameters
        for i, name in enumerate(param_names):
            self.fit_result['parameters'][name] = {
                'value': fitted_params[i],
                'stderr': param_errors[i],
                'formatted': f'{fitted_params[i]:.6g} ± {param_errors[i]:.6g}'
                if param_errors[i] > 0
                else f'{fitted_params[i]:.6g}',
            }
            # Update internal parameter values
            self.params[name]['value'] = fitted_params[i]

        # Add fixed parameters to results
        for name, info in self.params.items():
            if name not in param_names:
                self.fit_result['parameters'][name] = {
                    'value': info['value'],
                    'stderr': 0.0,
                    'formatted': f'{info["value"]:.6g} (fixed)',
                }

        self._fitted_model = result

        # Print results
        print('\n✓ Fit completed!')
        print(f'Final χ² = {self.fit_result["chisq"]:.4f}')
        print('\nFitted parameters:')
        for name, info in self.fit_result['parameters'].items():
            print(f'  {name}: {info["formatted"]}')

        return self.fit_result

    def plot_results(self, show_residuals: bool = True, log_scale: bool = True) -> None:
        """
        Plot experimental data and fitted model.

        Args:
            show_residuals: If True, show residuals in a separate panel
            log_scale: If True, use log scale for both axes
        """
        if self.data is None:
            raise ValueError('No data to plot. Use load_data() first.')

        if self.fit_result is None:
            print('No fit results available. Plotting data only.')
            plt.figure(figsize=(10, 6))
            plt.errorbar(
                self.data.x, self.data.y, yerr=self.data.dy, fmt='o', label='Data', alpha=0.6
            )
            plt.xlabel('Q (Å⁻¹)')
            plt.ylabel('I(Q)')
            plt.title('SANS Data')
            if log_scale:
                plt.xscale('log')
                plt.yscale('log')
            plt.legend()
            plt.grid(True, alpha=0.3)
            plt.tight_layout()
            plt.show()
            return

        # Calculate fitted curve
        if self.fit_result['engine'] == 'bumps':
            problem = self._fitted_model
            q = self.data.x
            I_fit = problem.fitness.theory()
        else:  # lmfit
            calculator = DirectModel(self.data, self.kernel)
            par_dict = {name: info['value'] for name, info in self.fit_result['parameters'].items()}
            I_fit = calculator(**par_dict)
            q = self.data.x

        residuals = (self.data.y - I_fit) / self.data.dy

        # Create plot
        if show_residuals:
            fig, (ax1, ax2) = plt.subplots(
                2, 1, figsize=(10, 10), gridspec_kw={'height_ratios': [3, 1]}
            )
        else:
            fig, ax1 = plt.subplots(1, 1, figsize=(10, 6))

        # Main plot
        ax1.errorbar(
            self.data.x,
            self.data.y,
            yerr=self.data.dy,
            fmt='o',
            label='Experimental Data',
            alpha=0.6,
            markersize=4,
        )
        ax1.plot(q, I_fit, 'r-', label='Fitted Model', linewidth=2)
        ax1.set_xlabel('Q (Å⁻¹)', fontsize=12)
        ax1.set_ylabel('I(Q)', fontsize=12)
        ax1.set_title(
            f'SANS Fit: {self.model_name} (χ² = {self.fit_result["chisq"]:.4f})', fontsize=14
        )
        ax1.legend()
        ax1.grid(True, alpha=0.3)

        if log_scale:
            ax1.set_xscale('log')
            ax1.set_yscale('log')

        # Residuals plot
        if show_residuals:
            ax2.axhline(0, color='gray', linestyle='--', linewidth=1)
            ax2.plot(self.data.x, residuals, 'o', markersize=4, alpha=0.6)
            ax2.set_xlabel('Q (Å⁻¹)', fontsize=12)
            ax2.set_ylabel('Residuals (σ)', fontsize=12)
            ax2.grid(True, alpha=0.3)
            if log_scale:
                ax2.set_xscale('log')

        plt.tight_layout()
        plt.show()

    def save_results(self, filename: str) -> None:
        """
        Save fit results to a file.

        Args:
            filename: Output file path (CSV format)
        """
        if self.fit_result is None:
            raise ValueError('No fit results to save. Run fit() first.')

        # Prepare data
        with open(filename, 'w') as f:
            f.write('# SANS Fit Results\n')
            f.write(f'# Model: {self.model_name}\n')
            f.write(f'# Engine: {self.fit_result["engine"]}\n')
            f.write(f'# Method: {self.fit_result["method"]}\n')
            f.write(f'# Chi-squared: {self.fit_result["chisq"]:.6f}\n')
            f.write('#\n')
            f.write('# Fitted Parameters:\n')
            for name, info in self.fit_result['parameters'].items():
                f.write(f'# {name}: {info["formatted"]}\n')
            f.write('#\n')
            f.write('Q,I_exp,dI_exp,I_fit,Residuals\n')

            # Get fitted curve
            if self.fit_result['engine'] == 'bumps':
                I_fit = self._fitted_model.fitness.theory()
            else:
                calculator = DirectModel(self.data, self.kernel)
                par_dict = {
                    name: info['value'] for name, info in self.fit_result['parameters'].items()
                }
                I_fit = calculator(**par_dict)

            residuals = (self.data.y - I_fit) / self.data.dy

            for q, i_exp, di_exp, i_fit, res in zip(
                self.data.x, self.data.y, self.data.dy, I_fit, residuals
            ):
                f.write(f'{q:.6e},{i_exp:.6e},{di_exp:.6e},{i_fit:.6e},{res:.6e}\n')

        print(f'✓ Results saved to {filename}')

__init__()

Initialize the SANS fitter.

Source code in src/sans_fitter/sans_fitter.py
def __init__(self):
    """Initialize the SANS fitter."""
    self.data = None
    self.kernel = None
    self.model_name = None
    self.params = {}
    self.fit_result = None
    self._fitted_model = None

    # Structure factor support
    self._structure_factor_name = None
    self._radius_effective_mode = 'unconstrained'
    self._form_factor_params = {}  # Store form factor params separately

fit(engine='bumps', method=None, **kwargs)

Perform the fit using the specified engine.

Parameters:

Name Type Description Default
engine Literal['bumps', 'lmfit']

Fitting engine ('bumps' or 'lmfit')

'bumps'
method Optional[str]

Optimization method (engine-specific) - BUMPS: 'amoeba', 'lm', 'newton', 'de' (default: 'amoeba') - LMFit: 'leastsq', 'least_squares', 'differential_evolution', etc.

None
**kwargs Any

Additional arguments passed to the fitting engine

{}

Returns:

Type Description
dict[str, Any]

Dictionary with fit results including chi-squared and parameter values

Raises:

Type Description
ValueError

If data or model not loaded, or invalid engine

Source code in src/sans_fitter/sans_fitter.py
def fit(
    self,
    engine: Literal['bumps', 'lmfit'] = 'bumps',
    method: Optional[str] = None,
    **kwargs: Any,
) -> dict[str, Any]:
    """
    Perform the fit using the specified engine.

    Args:
        engine: Fitting engine ('bumps' or 'lmfit')
        method: Optimization method (engine-specific)
               - BUMPS: 'amoeba', 'lm', 'newton', 'de' (default: 'amoeba')
               - LMFit: 'leastsq', 'least_squares', 'differential_evolution', etc.
        **kwargs: Additional arguments passed to the fitting engine

    Returns:
        Dictionary with fit results including chi-squared and parameter values

    Raises:
        ValueError: If data or model not loaded, or invalid engine
    """
    if self.data is None:
        raise ValueError('No data loaded. Use load_data() first.')
    if self.kernel is None:
        raise ValueError('No model loaded. Use set_model() first.')

    if engine == 'bumps':
        return self._fit_bumps(method or 'amoeba', **kwargs)
    elif engine == 'lmfit':
        if not LMFIT_AVAILABLE:
            raise ValueError("scipy is not installed. Use 'bumps' engine or install scipy.")
        return self._fit_lmfit(method or 'leastsq', **kwargs)
    else:
        raise ValueError(f"Unknown engine '{engine}'. Use 'bumps' or 'lmfit'.")

get_params()

Display current parameter values and settings in a readable format.

Source code in src/sans_fitter/sans_fitter.py
def get_params(self) -> None:
    """Display current parameter values and settings in a readable format."""
    if not self.params:
        print('No model loaded. Use set_model() first.')
        return

    print(f'\n{"=" * 80}')
    print(f'Model: {self.model_name}')
    if self._structure_factor_name:
        print(f'Structure Factor: {self._structure_factor_name}')
        print(f'Radius Effective Mode: {self._radius_effective_mode}')
    print(f'{"=" * 80}')
    print(f'{"Parameter":<20} {"Value":<12} {"Min":<12} {"Max":<12} {"Vary":<8}')
    print(f'{"-" * 80}')

    for name, info in self.params.items():
        vary_str = '✓' if info['vary'] else '✗'
        # Show linked indicator for radius_effective in link_radius mode
        if name == 'radius_effective' and self._radius_effective_mode == 'link_radius':
            vary_str = '→radius'
        print(
            f'{name:<20} {info["value"]:<12.4g} {info["min"]:<12.4g} '
            f'{info["max"]:<12.4g} {vary_str:<8}'
        )
    print(f'{"=" * 80}\n')

get_structure_factor()

Get the name of the currently applied structure factor.

Returns:

Type Description
Optional[str]

Name of the structure factor, or None if no structure factor is set

Source code in src/sans_fitter/sans_fitter.py
def get_structure_factor(self) -> Optional[str]:
    """
    Get the name of the currently applied structure factor.

    Returns:
        Name of the structure factor, or None if no structure factor is set
    """
    return self._structure_factor_name

load_data(filename)

Load SANS data from a file.

Supports CSV, XML, and HDF5 formats through sasdata.

Parameters:

Name Type Description Default
filename str

Path to the data file

required

Raises:

Type Description
FileNotFoundError

If the file doesn't exist

ValueError

If the data cannot be loaded or is invalid

Source code in src/sans_fitter/sans_fitter.py
def load_data(self, filename: str) -> None:
    """
    Load SANS data from a file.

    Supports CSV, XML, and HDF5 formats through sasdata.

    Args:
        filename: Path to the data file

    Raises:
        FileNotFoundError: If the file doesn't exist
        ValueError: If the data cannot be loaded or is invalid
    """
    loader = Loader()
    try:
        data_list = loader.load(filename)
        if not data_list:
            raise ValueError(f'No data loaded from {filename}')

        self.data = data_list[0]

        # Setup required fields for sasmodels
        self.data.qmin = getattr(self.data, 'qmin', None) or self.data.x.min()
        self.data.qmax = getattr(self.data, 'qmax', None) or self.data.x.max()
        self.data.mask = np.isnan(self.data.y)

        print(f'✓ Loaded data from {filename}')
        print(f'  Q range: {self.data.qmin:.4f} to {self.data.qmax:.4f} Å⁻¹')
        print(f'  Data points: {len(self.data.x)}')

    except Exception as e:
        raise ValueError(f'Failed to load data from {filename}: {str(e)}') from e

plot_results(show_residuals=True, log_scale=True)

Plot experimental data and fitted model.

Parameters:

Name Type Description Default
show_residuals bool

If True, show residuals in a separate panel

True
log_scale bool

If True, use log scale for both axes

True
Source code in src/sans_fitter/sans_fitter.py
def plot_results(self, show_residuals: bool = True, log_scale: bool = True) -> None:
    """
    Plot experimental data and fitted model.

    Args:
        show_residuals: If True, show residuals in a separate panel
        log_scale: If True, use log scale for both axes
    """
    if self.data is None:
        raise ValueError('No data to plot. Use load_data() first.')

    if self.fit_result is None:
        print('No fit results available. Plotting data only.')
        plt.figure(figsize=(10, 6))
        plt.errorbar(
            self.data.x, self.data.y, yerr=self.data.dy, fmt='o', label='Data', alpha=0.6
        )
        plt.xlabel('Q (Å⁻¹)')
        plt.ylabel('I(Q)')
        plt.title('SANS Data')
        if log_scale:
            plt.xscale('log')
            plt.yscale('log')
        plt.legend()
        plt.grid(True, alpha=0.3)
        plt.tight_layout()
        plt.show()
        return

    # Calculate fitted curve
    if self.fit_result['engine'] == 'bumps':
        problem = self._fitted_model
        q = self.data.x
        I_fit = problem.fitness.theory()
    else:  # lmfit
        calculator = DirectModel(self.data, self.kernel)
        par_dict = {name: info['value'] for name, info in self.fit_result['parameters'].items()}
        I_fit = calculator(**par_dict)
        q = self.data.x

    residuals = (self.data.y - I_fit) / self.data.dy

    # Create plot
    if show_residuals:
        fig, (ax1, ax2) = plt.subplots(
            2, 1, figsize=(10, 10), gridspec_kw={'height_ratios': [3, 1]}
        )
    else:
        fig, ax1 = plt.subplots(1, 1, figsize=(10, 6))

    # Main plot
    ax1.errorbar(
        self.data.x,
        self.data.y,
        yerr=self.data.dy,
        fmt='o',
        label='Experimental Data',
        alpha=0.6,
        markersize=4,
    )
    ax1.plot(q, I_fit, 'r-', label='Fitted Model', linewidth=2)
    ax1.set_xlabel('Q (Å⁻¹)', fontsize=12)
    ax1.set_ylabel('I(Q)', fontsize=12)
    ax1.set_title(
        f'SANS Fit: {self.model_name} (χ² = {self.fit_result["chisq"]:.4f})', fontsize=14
    )
    ax1.legend()
    ax1.grid(True, alpha=0.3)

    if log_scale:
        ax1.set_xscale('log')
        ax1.set_yscale('log')

    # Residuals plot
    if show_residuals:
        ax2.axhline(0, color='gray', linestyle='--', linewidth=1)
        ax2.plot(self.data.x, residuals, 'o', markersize=4, alpha=0.6)
        ax2.set_xlabel('Q (Å⁻¹)', fontsize=12)
        ax2.set_ylabel('Residuals (σ)', fontsize=12)
        ax2.grid(True, alpha=0.3)
        if log_scale:
            ax2.set_xscale('log')

    plt.tight_layout()
    plt.show()

remove_structure_factor()

Remove the current structure factor and revert to the form factor only.

Raises:

Type Description
ValueError

If no structure factor is currently set

Source code in src/sans_fitter/sans_fitter.py
def remove_structure_factor(self) -> None:
    """
    Remove the current structure factor and revert to the form factor only.

    Raises:
        ValueError: If no structure factor is currently set
    """
    if self._structure_factor_name is None:
        raise ValueError('No structure factor is currently set.')

    # Reload the original form factor model
    try:
        self.kernel = load_model(self.model_name, dtype='single', platform='dll')

        # Restore form factor parameters
        self.params = {k: dict(v) for k, v in self._form_factor_params.items()}

        sf_name = self._structure_factor_name
        self._structure_factor_name = None
        self._radius_effective_mode = 'unconstrained'
        self._form_factor_params = {}

        print(f"✓ Structure factor '{sf_name}' removed")
        print(f'  Reverted to form factor: {self.model_name}')

    except Exception as e:
        raise ValueError(f'Failed to reload form factor model: {str(e)}') from e

save_results(filename)

Save fit results to a file.

Parameters:

Name Type Description Default
filename str

Output file path (CSV format)

required
Source code in src/sans_fitter/sans_fitter.py
def save_results(self, filename: str) -> None:
    """
    Save fit results to a file.

    Args:
        filename: Output file path (CSV format)
    """
    if self.fit_result is None:
        raise ValueError('No fit results to save. Run fit() first.')

    # Prepare data
    with open(filename, 'w') as f:
        f.write('# SANS Fit Results\n')
        f.write(f'# Model: {self.model_name}\n')
        f.write(f'# Engine: {self.fit_result["engine"]}\n')
        f.write(f'# Method: {self.fit_result["method"]}\n')
        f.write(f'# Chi-squared: {self.fit_result["chisq"]:.6f}\n')
        f.write('#\n')
        f.write('# Fitted Parameters:\n')
        for name, info in self.fit_result['parameters'].items():
            f.write(f'# {name}: {info["formatted"]}\n')
        f.write('#\n')
        f.write('Q,I_exp,dI_exp,I_fit,Residuals\n')

        # Get fitted curve
        if self.fit_result['engine'] == 'bumps':
            I_fit = self._fitted_model.fitness.theory()
        else:
            calculator = DirectModel(self.data, self.kernel)
            par_dict = {
                name: info['value'] for name, info in self.fit_result['parameters'].items()
            }
            I_fit = calculator(**par_dict)

        residuals = (self.data.y - I_fit) / self.data.dy

        for q, i_exp, di_exp, i_fit, res in zip(
            self.data.x, self.data.y, self.data.dy, I_fit, residuals
        ):
            f.write(f'{q:.6e},{i_exp:.6e},{di_exp:.6e},{i_fit:.6e},{res:.6e}\n')

    print(f'✓ Results saved to {filename}')

set_model(model_name, platform='cpu')

Set the SANS model to use for fitting.

This resets any active structure factor to ensure a clean state.

Parameters:

Name Type Description Default
model_name str

Name of the model from SasModels (e.g., 'cylinder', 'sphere')

required
platform str

Computation platform ('cpu' or 'opencl')

'cpu'

Raises:

Type Description
ValueError

If the model name is not valid

Source code in src/sans_fitter/sans_fitter.py
def set_model(self, model_name: str, platform: str = 'cpu') -> None:
    """
    Set the SANS model to use for fitting.

    This resets any active structure factor to ensure a clean state.

    Args:
        model_name: Name of the model from SasModels (e.g., 'cylinder', 'sphere')
        platform: Computation platform ('cpu' or 'opencl')

    Raises:
        ValueError: If the model name is not valid
    """
    try:
        # Reset structure factor when changing form factor
        self._structure_factor_name = None
        self._radius_effective_mode = 'unconstrained'
        self._form_factor_params = {}

        # Force CPU platform to avoid OpenCL issues
        self.kernel = load_model(model_name, dtype='single', platform='dll')
        self.model_name = model_name

        # Initialize parameters with default values from the model
        self.params = {}
        for param in self.kernel.info.parameters.kernel_parameters:
            self.params[param.name] = {
                'value': param.default,
                'min': param.limits[0] if param.limits[0] > -np.inf else 0,
                'max': param.limits[1] if param.limits[1] < np.inf else param.default * 10,
                'vary': False,  # By default, parameters are fixed
                'description': param.description,
            }

        # Add implicit scale and background parameters (present in all models)
        # These are not in kernel_parameters but are always available
        if 'scale' not in self.params:
            self.params['scale'] = {
                'value': 1.0,
                'min': 0.0,
                'max': np.inf,
                'vary': False,
                'description': 'Scale factor for the model intensity',
            }

        if 'background' not in self.params:
            self.params['background'] = {
                'value': 0.0,
                'min': 0.0,
                'max': np.inf,
                'vary': False,
                'description': 'Constant background level',
            }

        print(f"✓ Model '{model_name}' loaded successfully")
        print(f'  Available parameters: {len(self.params)}')

    except Exception as e:
        raise ValueError(f"Failed to load model '{model_name}': {str(e)}") from e

set_param(name, value=None, min=None, max=None, vary=None)

Configure a model parameter for fitting.

Parameters:

Name Type Description Default
name str

Parameter name

required
value Optional[float]

Initial value (optional)

None
min Optional[float]

Minimum bound (optional)

None
max Optional[float]

Maximum bound (optional)

None
vary Optional[bool]

Whether to vary during fit (optional)

None

Raises:

Type Description
KeyError

If parameter name doesn't exist for the current model

Source code in src/sans_fitter/sans_fitter.py
def set_param(
    self,
    name: str,
    value: Optional[float] = None,
    min: Optional[float] = None,
    max: Optional[float] = None,
    vary: Optional[bool] = None,
) -> None:
    """
    Configure a model parameter for fitting.

    Args:
        name: Parameter name
        value: Initial value (optional)
        min: Minimum bound (optional)
        max: Maximum bound (optional)
        vary: Whether to vary during fit (optional)

    Raises:
        KeyError: If parameter name doesn't exist for the current model
    """
    if name not in self.params:
        available = ', '.join(self.params.keys())
        raise KeyError(f"Parameter '{name}' not found. Available: {available}")

    if value is not None:
        self.params[name]['value'] = value
        # Sync radius_effective when radius is updated in link_radius mode
        if (
            name == 'radius'
            and self._radius_effective_mode == 'link_radius'
            and 'radius_effective' in self.params
        ):
            self.params['radius_effective']['value'] = value
    if min is not None:
        self.params[name]['min'] = min
    if max is not None:
        self.params[name]['max'] = max
    if vary is not None:
        self.params[name]['vary'] = vary

set_structure_factor(structure_factor_name, radius_effective_mode='unconstrained')

Apply a structure factor to the current model.

This creates a product model (form_factor * structure_factor) to account for inter-particle interactions in concentrated systems.

Supported structure factors: - 'hardsphere': Hard sphere structure factor (Percus-Yevick closure) - 'hayter_msa': Hayter-Penfold rescaled MSA for charged spheres - 'squarewell': Square well potential - 'stickyhardsphere': Sticky hard sphere (Baxter model)

Parameters:

Name Type Description Default
structure_factor_name str

Name of the structure factor (e.g., 'hardsphere')

required
radius_effective_mode str

How to handle the effective radius. - 'unconstrained': 'radius_effective' is a separate fitting parameter. - 'link_radius': 'radius_effective' is constrained to the form factor's 'radius'.

'unconstrained'

Raises:

Type Description
ValueError

If no form factor model is set, or if the structure factor is invalid

Source code in src/sans_fitter/sans_fitter.py
def set_structure_factor(
    self, structure_factor_name: str, radius_effective_mode: str = 'unconstrained'
) -> None:
    """
    Apply a structure factor to the current model.

    This creates a product model (form_factor * structure_factor) to account
    for inter-particle interactions in concentrated systems.

    Supported structure factors:
    - 'hardsphere': Hard sphere structure factor (Percus-Yevick closure)
    - 'hayter_msa': Hayter-Penfold rescaled MSA for charged spheres
    - 'squarewell': Square well potential
    - 'stickyhardsphere': Sticky hard sphere (Baxter model)

    Args:
        structure_factor_name: Name of the structure factor (e.g., 'hardsphere')
        radius_effective_mode: How to handle the effective radius.
            - 'unconstrained': 'radius_effective' is a separate fitting parameter.
            - 'link_radius': 'radius_effective' is constrained to the form factor's 'radius'.

    Raises:
        ValueError: If no form factor model is set, or if the structure factor is invalid
    """
    if self.kernel is None or self.model_name is None:
        raise ValueError('No form factor model loaded. Use set_model() first.')

    # Validate structure factor name
    supported_sf = ['hardsphere', 'hayter_msa', 'squarewell', 'stickyhardsphere']
    if structure_factor_name not in supported_sf:
        raise ValueError(
            f"Unsupported structure factor '{structure_factor_name}'. "
            f'Supported: {", ".join(supported_sf)}'
        )

    # Validate radius_effective_mode
    if radius_effective_mode not in ['unconstrained', 'link_radius']:
        raise ValueError(
            f"Invalid radius_effective_mode '{radius_effective_mode}'. "
            "Use 'unconstrained' or 'link_radius'."
        )

    # Store form factor parameters before switching to product model
    if not self._form_factor_params:
        self._form_factor_params = {k: dict(v) for k, v in self.params.items()}

    # Create product model name
    full_model_name = f'{self.model_name}@{structure_factor_name}'

    try:
        # Load the product model
        self.kernel = load_model(full_model_name, dtype='single', platform='dll')
        self._structure_factor_name = structure_factor_name
        self._radius_effective_mode = radius_effective_mode

        # Rebuild parameters from product model
        new_params = {}
        for param in self.kernel.info.parameters.kernel_parameters:
            # Preserve existing values if parameter already exists
            if param.name in self._form_factor_params:
                new_params[param.name] = dict(self._form_factor_params[param.name])
            else:
                new_params[param.name] = {
                    'value': param.default,
                    'min': param.limits[0] if param.limits[0] > -np.inf else 0,
                    'max': param.limits[1] if param.limits[1] < np.inf else param.default * 10,
                    'vary': False,
                    'description': param.description,
                }

        # Ensure scale and background are present
        if 'scale' not in new_params:
            if 'scale' in self._form_factor_params:
                new_params['scale'] = dict(self._form_factor_params['scale'])
            else:
                new_params['scale'] = {
                    'value': 1.0,
                    'min': 0.0,
                    'max': np.inf,
                    'vary': False,
                    'description': 'Scale factor for the model intensity',
                }

        if 'background' not in new_params:
            if 'background' in self._form_factor_params:
                new_params['background'] = dict(self._form_factor_params['background'])
            else:
                new_params['background'] = {
                    'value': 0.0,
                    'min': 0.0,
                    'max': np.inf,
                    'vary': False,
                    'description': 'Constant background level',
                }

        self.params = new_params

        # Handle radius_effective linking
        if radius_effective_mode == 'link_radius':
            if 'radius' in self.params and 'radius_effective' in self.params:
                # Link radius_effective to radius
                self.params['radius_effective']['value'] = self.params['radius']['value']
                self.params['radius_effective']['vary'] = False
                print("  Note: 'radius_effective' linked to 'radius' value")
            else:
                warnings.warn(
                    'Cannot link radius_effective to radius: one or both parameters not found. '
                    'Using unconstrained mode.',
                    stacklevel=2,
                )
                self._radius_effective_mode = 'unconstrained'

        print(f"✓ Structure factor '{structure_factor_name}' applied to '{self.model_name}'")
        print(f'  Product model: {full_model_name}')
        print(f'  Total parameters: {len(self.params)}')

    except Exception as e:
        raise ValueError(f"Failed to load model '{full_model_name}': {str(e)}") from e