Skip to content

API Reference

SANSFitter

The main class for SANS data fitting.

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
 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
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
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.fit_result = None
        self._fitted_model = None

        # Parameter management delegated to ParameterManager
        self._param_manager = ParameterManager()

    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:
            # Force CPU platform to avoid OpenCL issues
            self.kernel = load_model(model_name, dtype='single', platform='dll')

            # Initialize parameters via ParameterManager
            self._param_manager.initialize_from_kernel(self.kernel, model_name)

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

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

    # =========================================================================
    # Property accessors for backward compatibility
    # =========================================================================

    @property
    def model_name(self) -> Optional[str]:
        """Get the current model name."""
        return self._param_manager.model_name

    @model_name.setter
    def model_name(self, value: Optional[str]) -> None:
        """Set the model name (used internally)."""
        self._param_manager.model_name = value

    @property
    def params(self) -> dict[str, dict[str, Any]]:
        """Get the parameter dictionary."""
        return self._param_manager.params

    @params.setter
    def params(self, value: dict[str, dict[str, Any]]) -> None:
        """Set the parameter dictionary (used internally)."""
        self._param_manager.params = value

    @property
    def _structure_factor_name(self) -> Optional[str]:
        """Get the structure factor name."""
        return self._param_manager.get_structure_factor()

    @property
    def _radius_effective_mode(self) -> str:
        """Get the radius effective mode."""
        return self._param_manager.get_radius_effective_mode()

    def get_params(self) -> None:
        """Display current parameter values and settings in a readable format."""
        self._param_manager.display_params()

    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
        """
        self._param_manager.set_param(name, value=value, min=min, max=max, 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)}'
            )

        # 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')

            # Delegate parameter management to ParameterManager
            self._param_manager.update_for_product_model(
                self.kernel, structure_factor_name, radius_effective_mode
            )

            if radius_effective_mode == 'link_radius':
                print("  Note: 'radius_effective' linked to 'radius' value")

            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')

            # Delegate to ParameterManager - this restores params and PD state
            sf_name = self._param_manager.remove_structure_factor()

            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

    # =========================================================================
    # Polydispersity Methods
    # =========================================================================

    def supports_polydispersity(self) -> bool:
        """
        Check if current model has polydisperse parameters.

        Returns:
            True if model supports polydispersity, False otherwise
        """
        return self._param_manager.has_polydisperse_parameters()

    def get_polydisperse_parameters(self) -> list[str]:
        """
        Get list of polydisperse parameter names.

        Returns:
            List of parameter names that support polydispersity
        """
        return self._param_manager.get_polydisperse_parameters()

    def set_pd_param(
        self,
        param_name: str,
        pd_width: Optional[float] = None,
        pd_n: Optional[int] = None,
        pd_nsigma: Optional[float] = None,
        pd_type: Optional[str] = None,
        vary: Optional[bool] = None,
    ) -> None:
        """
        Configure polydispersity for a parameter.

        Args:
            param_name: Name of the base parameter (e.g., 'radius')
            pd_width: Polydispersity width (relative, 0.0 = monodisperse)
            pd_n: Number of Gaussian quadrature points (default: 35)
            pd_nsigma: Number of sigmas to include (default: 3.0)
            pd_type: Distribution type ('gaussian', 'rectangle', 'lognormal', 'schulz', 'boltzmann')
            vary: Whether to vary the pd_width during fitting

        Raises:
            KeyError: If param_name is not a polydisperse parameter
            ValueError: If pd_type is not a valid distribution type
        """
        self._param_manager.set_pd_param(
            param_name,
            pd_width=pd_width,
            pd_n=pd_n,
            pd_nsigma=pd_nsigma,
            pd_type=pd_type,
            vary=vary,
        )

    def get_pd_param(self, param_name: str) -> dict[str, Any]:
        """
        Get polydispersity configuration for a parameter.

        Args:
            param_name: Name of the base parameter (e.g., 'radius')

        Returns:
            Dictionary with pd, pd_n, pd_nsigma, pd_type, vary, and active values.
            'active' indicates whether polydispersity is active for this parameter (pd > 0).

        Raises:
            KeyError: If param_name is not a polydisperse parameter
        """
        return self._param_manager.get_pd_param(param_name)

    def enable_polydispersity(self, enabled: bool = True) -> None:
        """
        Enable or disable polydispersity globally.

        When disabled, polydispersity parameters are excluded from fitting
        but their values are preserved for when PD is re-enabled.

        Args:
            enabled: Whether to enable polydispersity (default: True)
        """
        self._param_manager.toggle_pd_visibility(enabled)

    def is_polydispersity_enabled(self) -> bool:
        """
        Check if polydispersity is enabled.

        Returns:
            True if polydispersity is globally enabled, False otherwise
        """
        return self._param_manager.is_pd_enabled()

    def get_pd_params(self) -> None:
        """Display polydispersity parameter values and settings."""
        self._param_manager.display_pd_params()

    def get_varying_pd_params(self) -> list[str]:
        """
        Get list of polydispersity parameters that are set to vary.

        Returns:
            List of parameter names (e.g., ['radius_pd']) that will vary during fitting
        """
        # ParameterManager returns base param names, we need to add _pd suffix
        varying_base = self._param_manager.get_varying_pd_params()
        return [f'{param_name}_pd' for param_name in varying_base]

    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()}

        # Add polydispersity parameters if PD is enabled
        if self._param_manager.is_pd_enabled():
            for param_name in self._param_manager.get_polydisperse_parameters():
                pd_config = self._param_manager.get_pd_param(param_name)
                include_pd = pd_config['pd'] > 0 or pd_config.get('vary', False)
                if include_pd:
                    pars[f'{param_name}_pd'] = pd_config['pd']
                    pars[f'{param_name}_pd_n'] = pd_config['pd_n']
                    pars[f'{param_name}_pd_nsigma'] = pd_config['pd_nsigma']
                    pars[f'{param_name}_pd_type'] = pd_config['pd_type']

        # 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'])

        # Set polydispersity parameter ranges if PD is enabled and vary=True
        if self._param_manager.is_pd_enabled():
            for param_name in self._param_manager.get_polydisperse_parameters():
                pd_config = self._param_manager.get_pd_param(param_name)
                include_pd = pd_config['pd'] > 0 or pd_config.get('vary', False)
                if include_pd and pd_config.get('vary', False):
                    # Allow pd_width to vary between 0 and 1 (0-100%)
                    pd_param = getattr(model, f'{param_name}_pd')
                    pd_param.range(0, 1)

        # 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
            elif k.endswith('_pd'):
                # Update polydispersity parameter via ParameterManager
                base_param = k[:-3]  # Remove '_pd' suffix
                if base_param in self._param_manager.get_polydisperse_parameters():
                    self._param_manager.set_pd_param(base_param, pd_width=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 for regular parameters
        param_names = [name for name, info in self.params.items() if info['vary']]
        x0_list = [self.params[name]['value'] for name in param_names]
        bounds_lower_list = [self.params[name]['min'] for name in param_names]
        bounds_upper_list = [self.params[name]['max'] for name in param_names]

        # Add polydispersity parameters if PD is enabled and vary=True
        pd_param_names = []
        if self._param_manager.is_pd_enabled():
            for base_param in self._param_manager.get_polydisperse_parameters():
                pd_config = self._param_manager.get_pd_param(base_param)
                include_pd = pd_config['pd'] > 0 or pd_config.get('vary', False)
                if include_pd and pd_config.get('vary', False):
                    pd_name = f'{base_param}_pd'
                    pd_param_names.append(pd_name)
                    param_names.append(pd_name)
                    x0_list.append(pd_config['pd'])
                    bounds_lower_list.append(0.0)
                    bounds_upper_list.append(1.0)

        x0 = np.array(x0_list)
        bounds_lower = np.array(bounds_lower_list)
        bounds_upper = np.array(bounds_upper_list)

        # 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
        param_manager = self._param_manager

        # 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):
                if name in par_dict:
                    par_dict[name] = x[i]
                elif name.endswith('_pd'):
                    # This is a PD parameter
                    par_dict[name] = x[i]

            # Add polydispersity parameters if PD is enabled
            if param_manager.is_pd_enabled():
                for base_param in param_manager.get_polydisperse_parameters():
                    pd_config = param_manager.get_pd_param(base_param)
                    include_pd = pd_config['pd'] > 0 or pd_config.get('vary', False)
                    if include_pd:
                        # pd value may have been updated above if varying
                        if f'{base_param}_pd' not in par_dict:
                            par_dict[f'{base_param}_pd'] = pd_config['pd']
                        par_dict[f'{base_param}_pd_n'] = pd_config['pd_n']
                        par_dict[f'{base_param}_pd_nsigma'] = pd_config['pd_nsigma']
                        par_dict[f'{base_param}_pd_type'] = pd_config['pd_type']

            # 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] contains infodict, not needed for basic fitting

            # 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
            if name in self.params:
                self.params[name]['value'] = fitted_params[i]
            elif name.endswith('_pd'):
                # Update polydispersity parameter via ParameterManager
                base_param = name[:-3]  # Remove '_pd' suffix
                if base_param in self._param_manager.get_polydisperse_parameters():
                    self._param_manager.set_pd_param(base_param, pd_width=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) -> go.Figure:
        """
        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

        Returns:
            Plotly Figure object
        """
        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.')
            fig = go.Figure()
            fig.add_trace(
                go.Scatter(
                    x=self.data.x,
                    y=self.data.y,
                    error_y={'type': 'data', 'array': self.data.dy, 'visible': True},
                    mode='markers',
                    name='Data',
                    opacity=0.6,
                )
            )
            fig.update_layout(
                title='SANS Data',
                xaxis_title='Q (Å⁻¹)',
                yaxis_title='I(Q)',
                xaxis_type='log' if log_scale else 'linear',
                yaxis_type='log' if log_scale else 'linear',
                template='plotly_white',
            )
            fig.show()
            return fig

        # 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 = make_subplots(
                rows=2,
                cols=1,
                row_heights=[0.75, 0.25],
                shared_xaxes=True,
                vertical_spacing=0.05,
            )
        else:
            fig = go.Figure()

        # Main plot - experimental data with error bars
        data_trace = go.Scatter(
            x=self.data.x,
            y=self.data.y,
            error_y={'type': 'data', 'array': self.data.dy, 'visible': True},
            mode='markers',
            name='Experimental Data',
            opacity=0.6,
            marker={'size': 6},
        )

        # Fitted model line
        fit_trace = go.Scatter(
            x=q,
            y=I_fit,
            mode='lines',
            name='Fitted Model',
            line={'color': 'red', 'width': 2},
        )

        if show_residuals:
            fig.add_trace(data_trace, row=1, col=1)
            fig.add_trace(fit_trace, row=1, col=1)

            # Residuals plot
            fig.add_trace(
                go.Scatter(
                    x=self.data.x,
                    y=residuals,
                    mode='markers',
                    name='Residuals',
                    marker={'size': 6},
                    opacity=0.6,
                    showlegend=False,
                ),
                row=2,
                col=1,
            )

            # Add zero line for residuals
            fig.add_hline(y=0, line_dash='dash', line_color='gray', row=2, col=1)

            # Update axes
            fig.update_xaxes(
                title_text='Q (Å⁻¹)',
                type='log' if log_scale else 'linear',
                row=2,
                col=1,
            )
            fig.update_yaxes(
                title_text='I(Q)',
                type='log' if log_scale else 'linear',
                row=1,
                col=1,
            )
            fig.update_yaxes(title_text='Residuals (σ)', row=2, col=1)
            fig.update_xaxes(type='log' if log_scale else 'linear', row=1, col=1)
        else:
            fig.add_trace(data_trace)
            fig.add_trace(fit_trace)
            fig.update_xaxes(
                title_text='Q (Å⁻¹)',
                type='log' if log_scale else 'linear',
            )
            fig.update_yaxes(
                title_text='I(Q)',
                type='log' if log_scale else 'linear',
            )

        fig.update_layout(
            title=f'SANS Fit: {self.model_name} (χ² = {self.fit_result["chisq"]:.4f})',
            template='plotly_white',
            height=800 if show_residuals else 500,
            width=900,
        )

        fig.show()
        return fig

    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}')

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

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:
        # Force CPU platform to avoid OpenCL issues
        self.kernel = load_model(model_name, dtype='single', platform='dll')

        # Initialize parameters via ParameterManager
        self._param_manager.initialize_from_kernel(self.kernel, model_name)

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

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

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)}'
        )

    # 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')

        # Delegate parameter management to ParameterManager
        self._param_manager.update_for_product_model(
            self.kernel, structure_factor_name, radius_effective_mode
        )

        if radius_effective_mode == 'link_radius':
            print("  Note: 'radius_effective' linked to 'radius' value")

        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

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."""
    self._param_manager.display_params()

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
    """
    self._param_manager.set_param(name, value=value, min=min, max=max, vary=vary)

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'.")

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

Returns:

Type Description
Figure

Plotly Figure object

Source code in src/sans_fitter/sans_fitter.py
def plot_results(self, show_residuals: bool = True, log_scale: bool = True) -> go.Figure:
    """
    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

    Returns:
        Plotly Figure object
    """
    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.')
        fig = go.Figure()
        fig.add_trace(
            go.Scatter(
                x=self.data.x,
                y=self.data.y,
                error_y={'type': 'data', 'array': self.data.dy, 'visible': True},
                mode='markers',
                name='Data',
                opacity=0.6,
            )
        )
        fig.update_layout(
            title='SANS Data',
            xaxis_title='Q (Å⁻¹)',
            yaxis_title='I(Q)',
            xaxis_type='log' if log_scale else 'linear',
            yaxis_type='log' if log_scale else 'linear',
            template='plotly_white',
        )
        fig.show()
        return fig

    # 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 = make_subplots(
            rows=2,
            cols=1,
            row_heights=[0.75, 0.25],
            shared_xaxes=True,
            vertical_spacing=0.05,
        )
    else:
        fig = go.Figure()

    # Main plot - experimental data with error bars
    data_trace = go.Scatter(
        x=self.data.x,
        y=self.data.y,
        error_y={'type': 'data', 'array': self.data.dy, 'visible': True},
        mode='markers',
        name='Experimental Data',
        opacity=0.6,
        marker={'size': 6},
    )

    # Fitted model line
    fit_trace = go.Scatter(
        x=q,
        y=I_fit,
        mode='lines',
        name='Fitted Model',
        line={'color': 'red', 'width': 2},
    )

    if show_residuals:
        fig.add_trace(data_trace, row=1, col=1)
        fig.add_trace(fit_trace, row=1, col=1)

        # Residuals plot
        fig.add_trace(
            go.Scatter(
                x=self.data.x,
                y=residuals,
                mode='markers',
                name='Residuals',
                marker={'size': 6},
                opacity=0.6,
                showlegend=False,
            ),
            row=2,
            col=1,
        )

        # Add zero line for residuals
        fig.add_hline(y=0, line_dash='dash', line_color='gray', row=2, col=1)

        # Update axes
        fig.update_xaxes(
            title_text='Q (Å⁻¹)',
            type='log' if log_scale else 'linear',
            row=2,
            col=1,
        )
        fig.update_yaxes(
            title_text='I(Q)',
            type='log' if log_scale else 'linear',
            row=1,
            col=1,
        )
        fig.update_yaxes(title_text='Residuals (σ)', row=2, col=1)
        fig.update_xaxes(type='log' if log_scale else 'linear', row=1, col=1)
    else:
        fig.add_trace(data_trace)
        fig.add_trace(fit_trace)
        fig.update_xaxes(
            title_text='Q (Å⁻¹)',
            type='log' if log_scale else 'linear',
        )
        fig.update_yaxes(
            title_text='I(Q)',
            type='log' if log_scale else 'linear',
        )

    fig.update_layout(
        title=f'SANS Fit: {self.model_name} (χ² = {self.fit_result["chisq"]:.4f})',
        template='plotly_white',
        height=800 if show_residuals else 500,
        width=900,
    )

    fig.show()
    return fig

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}')

supports_polydispersity()

Check if current model has polydisperse parameters.

Returns:

Type Description
bool

True if model supports polydispersity, False otherwise

Source code in src/sans_fitter/sans_fitter.py
def supports_polydispersity(self) -> bool:
    """
    Check if current model has polydisperse parameters.

    Returns:
        True if model supports polydispersity, False otherwise
    """
    return self._param_manager.has_polydisperse_parameters()

get_polydisperse_parameters()

Get list of polydisperse parameter names.

Returns:

Type Description
list[str]

List of parameter names that support polydispersity

Source code in src/sans_fitter/sans_fitter.py
def get_polydisperse_parameters(self) -> list[str]:
    """
    Get list of polydisperse parameter names.

    Returns:
        List of parameter names that support polydispersity
    """
    return self._param_manager.get_polydisperse_parameters()

set_pd_param(param_name, pd_width=None, pd_n=None, pd_nsigma=None, pd_type=None, vary=None)

Configure polydispersity for a parameter.

Parameters:

Name Type Description Default
param_name str

Name of the base parameter (e.g., 'radius')

required
pd_width Optional[float]

Polydispersity width (relative, 0.0 = monodisperse)

None
pd_n Optional[int]

Number of Gaussian quadrature points (default: 35)

None
pd_nsigma Optional[float]

Number of sigmas to include (default: 3.0)

None
pd_type Optional[str]

Distribution type ('gaussian', 'rectangle', 'lognormal', 'schulz', 'boltzmann')

None
vary Optional[bool]

Whether to vary the pd_width during fitting

None

Raises:

Type Description
KeyError

If param_name is not a polydisperse parameter

ValueError

If pd_type is not a valid distribution type

Source code in src/sans_fitter/sans_fitter.py
def set_pd_param(
    self,
    param_name: str,
    pd_width: Optional[float] = None,
    pd_n: Optional[int] = None,
    pd_nsigma: Optional[float] = None,
    pd_type: Optional[str] = None,
    vary: Optional[bool] = None,
) -> None:
    """
    Configure polydispersity for a parameter.

    Args:
        param_name: Name of the base parameter (e.g., 'radius')
        pd_width: Polydispersity width (relative, 0.0 = monodisperse)
        pd_n: Number of Gaussian quadrature points (default: 35)
        pd_nsigma: Number of sigmas to include (default: 3.0)
        pd_type: Distribution type ('gaussian', 'rectangle', 'lognormal', 'schulz', 'boltzmann')
        vary: Whether to vary the pd_width during fitting

    Raises:
        KeyError: If param_name is not a polydisperse parameter
        ValueError: If pd_type is not a valid distribution type
    """
    self._param_manager.set_pd_param(
        param_name,
        pd_width=pd_width,
        pd_n=pd_n,
        pd_nsigma=pd_nsigma,
        pd_type=pd_type,
        vary=vary,
    )

get_pd_param(param_name)

Get polydispersity configuration for a parameter.

Parameters:

Name Type Description Default
param_name str

Name of the base parameter (e.g., 'radius')

required

Returns:

Type Description
dict[str, Any]

Dictionary with pd, pd_n, pd_nsigma, pd_type, vary, and active values.

dict[str, Any]

'active' indicates whether polydispersity is active for this parameter (pd > 0).

Raises:

Type Description
KeyError

If param_name is not a polydisperse parameter

Source code in src/sans_fitter/sans_fitter.py
def get_pd_param(self, param_name: str) -> dict[str, Any]:
    """
    Get polydispersity configuration for a parameter.

    Args:
        param_name: Name of the base parameter (e.g., 'radius')

    Returns:
        Dictionary with pd, pd_n, pd_nsigma, pd_type, vary, and active values.
        'active' indicates whether polydispersity is active for this parameter (pd > 0).

    Raises:
        KeyError: If param_name is not a polydisperse parameter
    """
    return self._param_manager.get_pd_param(param_name)

enable_polydispersity(enabled=True)

Enable or disable polydispersity globally.

When disabled, polydispersity parameters are excluded from fitting but their values are preserved for when PD is re-enabled.

Parameters:

Name Type Description Default
enabled bool

Whether to enable polydispersity (default: True)

True
Source code in src/sans_fitter/sans_fitter.py
def enable_polydispersity(self, enabled: bool = True) -> None:
    """
    Enable or disable polydispersity globally.

    When disabled, polydispersity parameters are excluded from fitting
    but their values are preserved for when PD is re-enabled.

    Args:
        enabled: Whether to enable polydispersity (default: True)
    """
    self._param_manager.toggle_pd_visibility(enabled)

is_polydispersity_enabled()

Check if polydispersity is enabled.

Returns:

Type Description
bool

True if polydispersity is globally enabled, False otherwise

Source code in src/sans_fitter/sans_fitter.py
def is_polydispersity_enabled(self) -> bool:
    """
    Check if polydispersity is enabled.

    Returns:
        True if polydispersity is globally enabled, False otherwise
    """
    return self._param_manager.is_pd_enabled()

get_pd_params()

Display polydispersity parameter values and settings.

Source code in src/sans_fitter/sans_fitter.py
def get_pd_params(self) -> None:
    """Display polydispersity parameter values and settings."""
    self._param_manager.display_pd_params()

get_varying_pd_params()

Get list of polydispersity parameters that are set to vary.

Returns:

Type Description
list[str]

List of parameter names (e.g., ['radius_pd']) that will vary during fitting

Source code in src/sans_fitter/sans_fitter.py
def get_varying_pd_params(self) -> list[str]:
    """
    Get list of polydispersity parameters that are set to vary.

    Returns:
        List of parameter names (e.g., ['radius_pd']) that will vary during fitting
    """
    # ParameterManager returns base param names, we need to add _pd suffix
    varying_base = self._param_manager.get_varying_pd_params()
    return [f'{param_name}_pd' for param_name in varying_base]

ParameterManager

Internal class for managing model parameters and polydispersity settings.

sans_fitter.parameter_manager.ParameterManager

Manages model parameters for SANS fitting.

Handles parameter initialization, validation, bounds management, special logic for structure factor parameter linking, and polydispersity support.

Attributes:

Name Type Description
params dict[str, dict[str, Any]]

Dictionary of parameter configurations

model_name Optional[str]

Name of the current model

structure_factor_name Optional[str]

Name of applied structure factor (if any)

radius_effective_mode Optional[str]

Mode for handling radius_effective ('unconstrained' or 'link_radius')

polydisperse_params dict[str, dict[str, Any]]

Dictionary of polydispersity parameters

pd_enabled dict[str, dict[str, Any]]

Whether polydispersity is globally enabled

Source code in src/sans_fitter/parameter_manager.py
 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
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
class ParameterManager:
    """
    Manages model parameters for SANS fitting.

    Handles parameter initialization, validation, bounds management,
    special logic for structure factor parameter linking, and polydispersity support.

    Attributes:
        params: Dictionary of parameter configurations
        model_name: Name of the current model
        structure_factor_name: Name of applied structure factor (if any)
        radius_effective_mode: Mode for handling radius_effective ('unconstrained' or 'link_radius')
        polydisperse_params: Dictionary of polydispersity parameters
        pd_enabled: Whether polydispersity is globally enabled
    """

    def __init__(self):
        """Initialize the parameter manager."""
        self.params: dict[str, dict[str, Any]] = {}
        self.model_name: Optional[str] = None
        self._structure_factor_name: Optional[str] = None
        self._radius_effective_mode: str = 'unconstrained'
        self._form_factor_params: dict[str, dict[str, Any]] = {}

        # Polydispersity support
        self._polydisperse_param_names: list[str] = []  # List of params that support PD
        self.polydisperse_params: dict[str, dict[str, Any]] = {}  # PD parameter values
        self._pd_enabled: bool = False  # Global PD visibility toggle

        # Backup storage for polydispersity state (used with structure factors)
        self._backed_up_pd_state: Optional[dict[str, Any]] = None

    def initialize_from_kernel(self, kernel: Any, model_name: str) -> None:
        """
        Initialize parameters from a SasModels kernel.

        Args:
            kernel: SasModels kernel object
            model_name: Name of the model

        Raises:
            ValueError: If kernel is invalid
        """
        if kernel is None:
            raise ValueError('Kernel cannot be None')

        # Clear all state first to ensure clean initialization
        self.clear()

        self.model_name = model_name

        # Extract parameters from kernel
        for param in 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,
            }

            # Track polydisperse parameters
            if getattr(param, 'polydisperse', False):
                self._polydisperse_param_names.append(param.name)

        # Add implicit scale and background parameters (present in all models)
        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',
            }

        # Initialize polydispersity parameters
        self._initialize_polydispersity_params()

    def get_param_dict(self) -> dict[str, dict[str, Any]]:
        """
        Get the full parameter dictionary.

        Returns:
            Dictionary of parameter configurations
        """
        return self.params

    def get_param_values(self) -> dict[str, float]:
        """
        Get dictionary of parameter names to current values.

        Returns:
            Dictionary mapping parameter names to their current values
        """
        return {name: info['value'] for name, info in self.params.items()}

    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.

        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
        """
        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 validate_param(self, name: str) -> bool:
        """
        Check if a parameter name exists.

        Args:
            name: Parameter name to validate

        Returns:
            True if parameter exists, False otherwise
        """
        return name in self.params

    def display_params(self) -> None:
        """Display current parameter values and settings in a readable format."""
        if not self.params:
            print('No parameters available.')
            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 backup_params(self) -> None:
        """Backup current parameters (used before applying structure factor)."""
        self._form_factor_params = {k: dict(v) for k, v in self.params.items()}

    def restore_params(self) -> None:
        """Restore backed up parameters (used when removing structure factor)."""
        if self._form_factor_params:
            self.params = {k: dict(v) for k, v in self._form_factor_params.items()}
            self._form_factor_params = {}

    def has_backed_up_params(self) -> bool:
        """
        Check if there are backed up parameters.

        Returns:
            True if parameters have been backed up, False otherwise
        """
        return bool(self._form_factor_params)

    def get_backed_up_params(self) -> dict[str, dict[str, Any]]:
        """
        Get the backed up form factor parameters.

        Returns:
            Dictionary of backed up parameters
        """
        return self._form_factor_params

    def update_for_product_model(
        self, kernel: Any, structure_factor_name: str, radius_effective_mode: str = 'unconstrained'
    ) -> None:
        """
        Update parameters for a product model (form factor @ structure factor).

        Args:
            kernel: New product model kernel
            structure_factor_name: Name of the structure factor
            radius_effective_mode: How to handle radius_effective
                - 'unconstrained': radius_effective is a separate parameter
                - 'link_radius': radius_effective is linked to radius

        Raises:
            ValueError: If radius_effective_mode is invalid
        """
        if radius_effective_mode not in ['unconstrained', 'link_radius']:
            raise ValueError(
                f"Invalid radius_effective_mode '{radius_effective_mode}'. "
                "Use 'unconstrained' or 'link_radius'."
            )

        # Backup form factor parameters if not already done
        if not self._form_factor_params:
            self.backup_params()

        # Backup polydispersity state if not already done
        if not self._backed_up_pd_state:
            self.backup_pd_state()

        self._structure_factor_name = structure_factor_name
        self._radius_effective_mode = radius_effective_mode

        # Rebuild parameters from product model
        new_params = {}
        for param in 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
            else:
                import warnings

                warnings.warn(
                    'Cannot link radius_effective to radius: one or both parameters not found. '
                    'Using unconstrained mode.',
                    stacklevel=3,
                )
                self._radius_effective_mode = 'unconstrained'

    def remove_structure_factor(self) -> str:
        """
        Remove structure factor and restore form factor parameters.

        Returns:
            Name of the removed structure factor

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

        sf_name = self._structure_factor_name
        self.restore_params()
        self.restore_pd_state()
        self._structure_factor_name = None
        self._radius_effective_mode = 'unconstrained'

        return sf_name

    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 get_radius_effective_mode(self) -> str:
        """
        Get the current radius_effective mode.

        Returns:
            Current radius_effective mode ('unconstrained' or 'link_radius')
        """
        return self._radius_effective_mode

    def update_param_value(self, name: str, value: float) -> None:
        """
        Update a parameter's value.

        Args:
            name: Parameter name
            value: New value

        Raises:
            KeyError: If parameter doesn't exist
        """
        if name not in self.params:
            raise KeyError(f"Parameter '{name}' not found")
        self.params[name]['value'] = value

    def get_varying_params(self) -> list[str]:
        """
        Get list of parameter names that are set to vary.

        Returns:
            List of parameter names with vary=True
        """
        return [name for name, info in self.params.items() if info['vary']]

    # =========================================================================
    # Polydispersity Methods
    # =========================================================================

    def _initialize_polydispersity_params(self) -> None:
        """Initialize polydispersity parameters for all polydisperse parameters."""
        self.polydisperse_params = {}

        for param_name in self._polydisperse_param_names:
            self.polydisperse_params[param_name] = {
                'pd': PD_DEFAULTS['pd'],
                'pd_n': PD_DEFAULTS['pd_n'],
                'pd_nsigma': PD_DEFAULTS['pd_nsigma'],
                'pd_type': PD_DEFAULTS['pd_type'],
                'vary': PD_DEFAULTS['vary'],
            }

    def get_polydisperse_parameters(self) -> list[str]:
        """
        Return list of parameter names that support polydispersity.

        Returns:
            List of parameter names that can have polydispersity applied
        """
        return list(self._polydisperse_param_names)

    def has_polydisperse_parameters(self) -> bool:
        """
        Check if the current model has any polydisperse parameters.

        Returns:
            True if model has polydisperse parameters, False otherwise
        """
        return len(self._polydisperse_param_names) > 0

    def set_pd_param(
        self,
        base_param: str,
        pd_width: Optional[float] = None,
        pd_n: Optional[int] = None,
        pd_nsigma: Optional[float] = None,
        pd_type: Optional[str] = None,
        vary: Optional[bool] = None,
    ) -> None:
        """
        Configure polydispersity for a specific parameter.

        Args:
            base_param: Name of the base parameter (e.g., 'radius')
            pd_width: Polydispersity width (relative, 0.0 = monodisperse)
            pd_n: Number of Gaussian quadrature points (default: 35)
            pd_nsigma: Number of sigmas to include (default: 3.0)
            pd_type: Distribution type ('gaussian', 'rectangle', 'lognormal', 'schulz', 'boltzmann')
            vary: Whether to vary the pd_width during fitting

        Raises:
            KeyError: If base_param is not a polydisperse parameter
            ValueError: If pd_type is not a valid distribution type
        """
        if base_param not in self._polydisperse_param_names:
            available = ', '.join(self._polydisperse_param_names)
            raise KeyError(
                f"Parameter '{base_param}' does not support polydispersity. "
                f'Available polydisperse parameters: {available}'
            )

        if pd_type is not None and pd_type not in PD_DISTRIBUTION_TYPES:
            raise ValueError(
                f"Invalid pd_type '{pd_type}'. Valid types: {', '.join(PD_DISTRIBUTION_TYPES)}"
            )

        if pd_width is not None:
            self.polydisperse_params[base_param]['pd'] = pd_width
        if pd_n is not None:
            self.polydisperse_params[base_param]['pd_n'] = pd_n
        if pd_nsigma is not None:
            self.polydisperse_params[base_param]['pd_nsigma'] = pd_nsigma
        if pd_type is not None:
            self.polydisperse_params[base_param]['pd_type'] = pd_type
        if vary is not None:
            self.polydisperse_params[base_param]['vary'] = vary

    def get_pd_param(self, base_param: str) -> dict[str, Any]:
        """
        Get polydispersity configuration for a specific parameter.

        Args:
            base_param: Name of the base parameter (e.g., 'radius')

        Returns:
            Dictionary with pd, pd_n, pd_nsigma, pd_type, vary, and active values.
            'active' indicates whether polydispersity is active for this parameter (pd > 0).

        Raises:
            KeyError: If base_param is not a polydisperse parameter
        """
        if base_param not in self._polydisperse_param_names:
            available = ', '.join(self._polydisperse_param_names)
            raise KeyError(
                f"Parameter '{base_param}' does not support polydispersity. "
                f'Available polydisperse parameters: {available}'
            )

        pd_config = self.polydisperse_params[base_param].copy()
        pd_config['active'] = pd_config['pd'] > 0
        return pd_config

    def toggle_pd_visibility(self, enabled: bool) -> None:
        """
        Enable/disable polydispersity globally.

        When disabled, polydispersity parameters are excluded from fitting
        but their values are preserved for when PD is re-enabled.

        Args:
            enabled: Whether polydispersity should be enabled
        """
        self._pd_enabled = enabled

    def is_pd_enabled(self) -> bool:
        """
        Check if polydispersity is globally enabled.

        Returns:
            True if polydispersity is enabled, False otherwise
        """
        return self._pd_enabled

    def get_pd_params_for_fitting(self) -> dict[str, Any]:
        """
        Return polydispersity parameters to include in fitting.

        Only returns PD parameters when pd_enabled is True.
        Returns parameters in the format expected by SasModels:
        - {param}_pd: polydispersity width
        - {param}_pd_n: number of quadrature points
        - {param}_pd_nsigma: number of sigmas
        - {param}_pd_type: distribution type

        Returns:
            Dictionary of PD parameters ready for fitting
        """
        if not self._pd_enabled:
            return {}

        pd_params = {}
        for param_name in self._polydisperse_param_names:
            pd_config = self.polydisperse_params[param_name]
            pd_params[f'{param_name}_pd'] = pd_config['pd']
            pd_params[f'{param_name}_pd_n'] = pd_config['pd_n']
            pd_params[f'{param_name}_pd_nsigma'] = pd_config['pd_nsigma']
            pd_params[f'{param_name}_pd_type'] = pd_config['pd_type']

        return pd_params

    def get_varying_pd_params(self) -> list[str]:
        """
        Get list of polydispersity parameter names set to vary.

        Only returns parameters when pd_enabled is True.

        Returns:
            List of base parameter names whose PD width should vary
        """
        if not self._pd_enabled:
            return []

        return [
            param_name
            for param_name, pd_config in self.polydisperse_params.items()
            if pd_config.get('vary', False)
        ]

    def display_pd_params(self) -> None:
        """Display polydispersity parameter values and settings."""
        if not self._polydisperse_param_names:
            print('No polydisperse parameters available for this model.')
            return

        status = 'ENABLED' if self._pd_enabled else 'DISABLED'
        print(f'\n{"=" * 90}')
        print(f'Polydispersity Status: {status}')
        print(f'{"=" * 90}')
        print(
            f'{"Parameter":<15} {"Width":<10} {"N Points":<10} {"N Sigma":<10} {"Type":<12} {"Vary":<8}'
        )
        print(f'{"-" * 90}')

        for param_name in self._polydisperse_param_names:
            pd_config = self.polydisperse_params[param_name]
            vary_str = '✓' if pd_config.get('vary', False) else '✗'
            print(
                f'{param_name:<15} {pd_config["pd"]:<10.4g} {pd_config["pd_n"]:<10} '
                f'{pd_config["pd_nsigma"]:<10.4g} {pd_config["pd_type"]:<12} {vary_str:<8}'
            )
        print(f'{"=" * 90}\n')

    def backup_pd_state(self) -> None:
        """Backup current polydispersity state (used before applying structure factor)."""
        self._backed_up_pd_state = {
            'polydisperse_param_names': list(self._polydisperse_param_names),
            'polydisperse_params': {k: dict(v) for k, v in self.polydisperse_params.items()},
            'pd_enabled': self._pd_enabled,
        }

    def restore_pd_state(self) -> None:
        """Restore backed up polydispersity state (used when removing structure factor)."""
        if self._backed_up_pd_state:
            self._polydisperse_param_names = self._backed_up_pd_state['polydisperse_param_names']
            self.polydisperse_params = {
                k: dict(v) for k, v in self._backed_up_pd_state['polydisperse_params'].items()
            }
            self._pd_enabled = self._backed_up_pd_state['pd_enabled']
            self._backed_up_pd_state = None

    def has_backed_up_pd_state(self) -> bool:
        """
        Check if there is backed up polydispersity state.

        Returns:
            True if polydispersity state has been backed up, False otherwise
        """
        return self._backed_up_pd_state is not None

    def clear(self) -> None:
        """Clear all parameters and reset state."""
        self.params = {}
        self.model_name = None
        self._structure_factor_name = None
        self._radius_effective_mode = 'unconstrained'
        self._form_factor_params = {}

        # Reset polydispersity state
        self._polydisperse_param_names = []
        self.polydisperse_params = {}
        self._pd_enabled = False
        self._backed_up_pd_state = None

get_polydisperse_parameters()

Return list of parameter names that support polydispersity.

Returns:

Type Description
list[str]

List of parameter names that can have polydispersity applied

Source code in src/sans_fitter/parameter_manager.py
def get_polydisperse_parameters(self) -> list[str]:
    """
    Return list of parameter names that support polydispersity.

    Returns:
        List of parameter names that can have polydispersity applied
    """
    return list(self._polydisperse_param_names)

has_polydisperse_parameters()

Check if the current model has any polydisperse parameters.

Returns:

Type Description
bool

True if model has polydisperse parameters, False otherwise

Source code in src/sans_fitter/parameter_manager.py
def has_polydisperse_parameters(self) -> bool:
    """
    Check if the current model has any polydisperse parameters.

    Returns:
        True if model has polydisperse parameters, False otherwise
    """
    return len(self._polydisperse_param_names) > 0

set_pd_param(base_param, pd_width=None, pd_n=None, pd_nsigma=None, pd_type=None, vary=None)

Configure polydispersity for a specific parameter.

Parameters:

Name Type Description Default
base_param str

Name of the base parameter (e.g., 'radius')

required
pd_width Optional[float]

Polydispersity width (relative, 0.0 = monodisperse)

None
pd_n Optional[int]

Number of Gaussian quadrature points (default: 35)

None
pd_nsigma Optional[float]

Number of sigmas to include (default: 3.0)

None
pd_type Optional[str]

Distribution type ('gaussian', 'rectangle', 'lognormal', 'schulz', 'boltzmann')

None
vary Optional[bool]

Whether to vary the pd_width during fitting

None

Raises:

Type Description
KeyError

If base_param is not a polydisperse parameter

ValueError

If pd_type is not a valid distribution type

Source code in src/sans_fitter/parameter_manager.py
def set_pd_param(
    self,
    base_param: str,
    pd_width: Optional[float] = None,
    pd_n: Optional[int] = None,
    pd_nsigma: Optional[float] = None,
    pd_type: Optional[str] = None,
    vary: Optional[bool] = None,
) -> None:
    """
    Configure polydispersity for a specific parameter.

    Args:
        base_param: Name of the base parameter (e.g., 'radius')
        pd_width: Polydispersity width (relative, 0.0 = monodisperse)
        pd_n: Number of Gaussian quadrature points (default: 35)
        pd_nsigma: Number of sigmas to include (default: 3.0)
        pd_type: Distribution type ('gaussian', 'rectangle', 'lognormal', 'schulz', 'boltzmann')
        vary: Whether to vary the pd_width during fitting

    Raises:
        KeyError: If base_param is not a polydisperse parameter
        ValueError: If pd_type is not a valid distribution type
    """
    if base_param not in self._polydisperse_param_names:
        available = ', '.join(self._polydisperse_param_names)
        raise KeyError(
            f"Parameter '{base_param}' does not support polydispersity. "
            f'Available polydisperse parameters: {available}'
        )

    if pd_type is not None and pd_type not in PD_DISTRIBUTION_TYPES:
        raise ValueError(
            f"Invalid pd_type '{pd_type}'. Valid types: {', '.join(PD_DISTRIBUTION_TYPES)}"
        )

    if pd_width is not None:
        self.polydisperse_params[base_param]['pd'] = pd_width
    if pd_n is not None:
        self.polydisperse_params[base_param]['pd_n'] = pd_n
    if pd_nsigma is not None:
        self.polydisperse_params[base_param]['pd_nsigma'] = pd_nsigma
    if pd_type is not None:
        self.polydisperse_params[base_param]['pd_type'] = pd_type
    if vary is not None:
        self.polydisperse_params[base_param]['vary'] = vary

get_pd_param(base_param)

Get polydispersity configuration for a specific parameter.

Parameters:

Name Type Description Default
base_param str

Name of the base parameter (e.g., 'radius')

required

Returns:

Type Description
dict[str, Any]

Dictionary with pd, pd_n, pd_nsigma, pd_type, vary, and active values.

dict[str, Any]

'active' indicates whether polydispersity is active for this parameter (pd > 0).

Raises:

Type Description
KeyError

If base_param is not a polydisperse parameter

Source code in src/sans_fitter/parameter_manager.py
def get_pd_param(self, base_param: str) -> dict[str, Any]:
    """
    Get polydispersity configuration for a specific parameter.

    Args:
        base_param: Name of the base parameter (e.g., 'radius')

    Returns:
        Dictionary with pd, pd_n, pd_nsigma, pd_type, vary, and active values.
        'active' indicates whether polydispersity is active for this parameter (pd > 0).

    Raises:
        KeyError: If base_param is not a polydisperse parameter
    """
    if base_param not in self._polydisperse_param_names:
        available = ', '.join(self._polydisperse_param_names)
        raise KeyError(
            f"Parameter '{base_param}' does not support polydispersity. "
            f'Available polydisperse parameters: {available}'
        )

    pd_config = self.polydisperse_params[base_param].copy()
    pd_config['active'] = pd_config['pd'] > 0
    return pd_config

toggle_pd_visibility(enabled)

Enable/disable polydispersity globally.

When disabled, polydispersity parameters are excluded from fitting but their values are preserved for when PD is re-enabled.

Parameters:

Name Type Description Default
enabled bool

Whether polydispersity should be enabled

required
Source code in src/sans_fitter/parameter_manager.py
def toggle_pd_visibility(self, enabled: bool) -> None:
    """
    Enable/disable polydispersity globally.

    When disabled, polydispersity parameters are excluded from fitting
    but their values are preserved for when PD is re-enabled.

    Args:
        enabled: Whether polydispersity should be enabled
    """
    self._pd_enabled = enabled

is_pd_enabled()

Check if polydispersity is globally enabled.

Returns:

Type Description
bool

True if polydispersity is enabled, False otherwise

Source code in src/sans_fitter/parameter_manager.py
def is_pd_enabled(self) -> bool:
    """
    Check if polydispersity is globally enabled.

    Returns:
        True if polydispersity is enabled, False otherwise
    """
    return self._pd_enabled

get_pd_params_for_fitting()

Return polydispersity parameters to include in fitting.

Only returns PD parameters when pd_enabled is True. Returns parameters in the format expected by SasModels: - {param}_pd: polydispersity width - {param}_pd_n: number of quadrature points - {param}_pd_nsigma: number of sigmas - {param}_pd_type: distribution type

Returns:

Type Description
dict[str, Any]

Dictionary of PD parameters ready for fitting

Source code in src/sans_fitter/parameter_manager.py
def get_pd_params_for_fitting(self) -> dict[str, Any]:
    """
    Return polydispersity parameters to include in fitting.

    Only returns PD parameters when pd_enabled is True.
    Returns parameters in the format expected by SasModels:
    - {param}_pd: polydispersity width
    - {param}_pd_n: number of quadrature points
    - {param}_pd_nsigma: number of sigmas
    - {param}_pd_type: distribution type

    Returns:
        Dictionary of PD parameters ready for fitting
    """
    if not self._pd_enabled:
        return {}

    pd_params = {}
    for param_name in self._polydisperse_param_names:
        pd_config = self.polydisperse_params[param_name]
        pd_params[f'{param_name}_pd'] = pd_config['pd']
        pd_params[f'{param_name}_pd_n'] = pd_config['pd_n']
        pd_params[f'{param_name}_pd_nsigma'] = pd_config['pd_nsigma']
        pd_params[f'{param_name}_pd_type'] = pd_config['pd_type']

    return pd_params

display_pd_params()

Display polydispersity parameter values and settings.

Source code in src/sans_fitter/parameter_manager.py
def display_pd_params(self) -> None:
    """Display polydispersity parameter values and settings."""
    if not self._polydisperse_param_names:
        print('No polydisperse parameters available for this model.')
        return

    status = 'ENABLED' if self._pd_enabled else 'DISABLED'
    print(f'\n{"=" * 90}')
    print(f'Polydispersity Status: {status}')
    print(f'{"=" * 90}')
    print(
        f'{"Parameter":<15} {"Width":<10} {"N Points":<10} {"N Sigma":<10} {"Type":<12} {"Vary":<8}'
    )
    print(f'{"-" * 90}')

    for param_name in self._polydisperse_param_names:
        pd_config = self.polydisperse_params[param_name]
        vary_str = '✓' if pd_config.get('vary', False) else '✗'
        print(
            f'{param_name:<15} {pd_config["pd"]:<10.4g} {pd_config["pd_n"]:<10} '
            f'{pd_config["pd_nsigma"]:<10.4g} {pd_config["pd_type"]:<12} {vary_str:<8}'
        )
    print(f'{"=" * 90}\n')

Polydispersity Constants

The following constants are available in sans_fitter.parameter_manager:

PD_DISTRIBUTION_TYPES

PD_DISTRIBUTION_TYPES = ['gaussian', 'rectangle', 'lognormal', 'schulz', 'boltzmann']

Supported polydispersity distribution types:

Type Description
gaussian Gaussian/normal distribution (default)
rectangle Uniform/rectangular distribution
lognormal Log-normal distribution
schulz Schulz distribution (common for polymers)
boltzmann Boltzmann distribution

Default Values

Constant Default Value Description
DEFAULT_PD_WIDTH 0.0 Default polydispersity width (monodisperse)
DEFAULT_PD_N 35 Default number of quadrature points
DEFAULT_PD_NSIGMA 3.0 Default number of sigmas to include
DEFAULT_PD_TYPE 'gaussian' Default distribution type