Skip to content

Commit 89ad00c

Browse files
authored
Merge pull request #373 from fooof-tools/algoex
[DOC] - Add custom algorithm example
2 parents bd75cdc + 8257002 commit 89ad00c

File tree

17 files changed

+588
-119
lines changed

17 files changed

+588
-119
lines changed
Lines changed: 315 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,315 @@
1+
"""
2+
Custom Algorithms
3+
=================
4+
5+
This example covers defining and using custom fit algorithms.
6+
"""
7+
8+
from specparam import SpectralModel
9+
10+
# Import function to simulate a power spectrum
11+
from specparam.sim import sim_power_spectrum
12+
13+
# Import elements to define custom fit algorithms
14+
from specparam.algorithms.settings import SettingsDefinition
15+
from specparam.algorithms.algorithm import Algorithm
16+
17+
###################################################################################################
18+
# Defining Custom Fit Algorithms
19+
# ------------------------------
20+
#
21+
# The specparam module includes a standard fitting algorithm that is used to for fitting the
22+
# selected fit modes to the data. However, you do not have to use this particular algorithm,
23+
# you can tweak how it works, and/or define your own custom algorithm and plug this in to
24+
# the model object.
25+
#
26+
# In this tutorial, we will explore how you can also define your own custom fit algorithms.
27+
#
28+
# To do so, we will start by simulating an example power spectrum to use for this example.
29+
#
30+
31+
###################################################################################################
32+
33+
# Define simulation parameters
34+
ap_params = [0, 1]
35+
gauss_params = [10, 0.5, 2]
36+
nlv = 0.025
37+
38+
# Simulate an example power spectrum
39+
freqs, powers = sim_power_spectrum(\
40+
[3, 50], {'fixed' : ap_params}, {'gaussian' : gauss_params}, nlv)
41+
42+
###################################################################################################
43+
# Example: Custom Algorithm Object
44+
# --------------------------------
45+
#
46+
# In our first example, we will introduce how to create a custom fit algorithm.
47+
#
48+
# For simplicity, we will start with a 'dummy' algorithm - one that functions code wise, but
49+
# doesn't actually implement a detailed fitting algorithm, so that we can start with the
50+
# organization of the code, and build up from there.
51+
#
52+
53+
###################################################################################################
54+
# Algorithm Settings
55+
# ~~~~~~~~~~~~~~~~~~
56+
#
57+
# A fitting algorithm typically has some settings that you want to define and describe so that
58+
# the user can check their description and provide values for the settings.
59+
#
60+
# For fitting algorithms, these setting descriptions are managed by the
61+
# :class:`~specparam.algorithms.settings.SettingsDefinition` object.
62+
#
63+
# For our dummy algorithm, we will initialize a settings definition object, with a
64+
# placeholder label and description.
65+
#
66+
67+
###################################################################################################
68+
69+
# Create a settings definition for our dummy algorithm
70+
DUMMY_ALGO_SETTINGS = SettingsDefinition({'fit_setting' : 'Setting description'})
71+
72+
###################################################################################################
73+
# Algorithm Object
74+
# ~~~~~~~~~~~~~~~~
75+
#
76+
# Now we can define our custom fitting algorithm. To do so, we will create a custom object
77+
# that inherits from the specparam :class:`~specparam.algorithms.algorithm.Algorithm` object.
78+
#
79+
# Implementing a custom fit object requires following several standards for specparam
80+
# to be able to use it:
81+
#
82+
# - the class should inherit from the specparam Algorithm object
83+
# - the object needs to accept `modes`, `data`, `results`, and `debug` input arguments
84+
# - at initialization, the object should initialize the Algorithm object ('super()'),
85+
# including providing a name and description, passing in the algorithm settings
86+
# object (from above), and passing in the 'modes', 'data', 'results', and 'debug' inputs
87+
# - the object needs to define a `_fit` function that serves as the main fit function
88+
#
89+
# In the following code, we initialize a custom object following the above to create a fit
90+
# algorithm object. Note that as a dummy algorithm, the 'fit' aspect doesn't actually
91+
# implement a step-by-step fitting procedure, but simply instantiates a pre-specified
92+
# model (to mimic the outputs of a fit algorithm).
93+
#
94+
95+
###################################################################################################
96+
97+
import numpy as np
98+
99+
class DummyAlgorithm(Algorithm):
100+
"""Dummy object to mimic a fit algorithm."""
101+
102+
def __init__(self, modes=None, data=None, results=None, debug=False):
103+
"""Initialize DummyAlgorithm instance."""
104+
105+
# Initialize base algorithm object with algorithm metadata
106+
super().__init__(
107+
name='dummy_fit_algo',
108+
description='Dummy fit algorithm.',
109+
public_settings=DUMMY_ALGO_SETTINGS,
110+
modes=modes, data=data, results=results, debug=debug)
111+
112+
def _fit(self):
113+
"""Define the full fitting algorithm."""
114+
115+
self.results.params.aperiodic.add_params('fit', np.array([0, 1]))
116+
self.results.params.periodic.add_params('fit', np.array([10, 0.5, 2], ndmin=2))
117+
self.results._regenerate_model(self.data.freqs)
118+
119+
###################################################################################################
120+
# Expected outcomes of algorithm fitting
121+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
122+
#
123+
# In order for a custom fitting algorithm to work properly when embedded within a model object,
124+
# there are some expectations for what the fitting process should do.
125+
#
126+
# The following elements are expected to computed through the fitting procedure:
127+
#
128+
# - Parameter results should be added for each parameter
129+
# - `model.results.params.{component}.add_params(...)`
130+
#
131+
# - The model should be computed and added to the object
132+
# - `model.results.model.modeled_spectrum` should be populated, as well as model
133+
# components (`model.results.model._ap_fit` & `model.results.model._peak_fit`)
134+
#
135+
# If the above you do the above, the model object can be used as normal, and you can do
136+
# (fit / print_results / plot / report / as well as save and load results).
137+
#
138+
# There are also some additional procedures / outputs that a custom fit process may do:
139+
#
140+
# - Update fit parameters to also have converted versions
141+
#
142+
143+
###################################################################################################
144+
#
145+
# Now that our custom fit algorithm is defined, we can use it by passing it into a model object.
146+
#
147+
# Note that in this example, we will use :class:`~specparam.SpectralModel` for our example, but
148+
# you can also take the same approach to define custom fit algorithms with other model objects.
149+
#
150+
151+
###################################################################################################
152+
153+
# Initialize a model object, passing in our custom dummy algorithm
154+
fm = SpectralModel(algorithm=DummyAlgorithm)
155+
156+
# Check the defined fit algorithm
157+
fm.algorithm.print()
158+
159+
###################################################################################################
160+
161+
# Fit and report model, using our custom algorithm
162+
fm.report(freqs, powers)
163+
164+
###################################################################################################
165+
#
166+
# In this case, with our dummy algorithm, we cheated a bit - the model was pre-specified to
167+
# initialize a model that happened to match the simulated data, and no real fitting took place.
168+
#
169+
# The point of this example is to show the outline of how a custom fit algorithm can be developed,
170+
# since the `_fit` method can implement any arbitrarily defined procedure to fit a model,
171+
#
172+
173+
###################################################################################################
174+
# Example with Custom Fitting
175+
# ---------------------------
176+
#
177+
# Having sketched out the basic outline with the dummy algorithm above, lets now define a custom
178+
# fit algorithm that actually does some fitting.
179+
#
180+
# For simplicity, this algorithm will be a simple fit that starts with an aperiodic fit, and
181+
# then fits a single peak to the flattened (aperiodic removed) spectrum. To do so, it will
182+
# take in an algorithm setting that defines a guess center-frequency for this peak.
183+
#
184+
185+
###################################################################################################
186+
187+
# Define the algorithm settings for our custom fit
188+
CUSTOM_ALGO_SETTINGS = SettingsDefinition(\
189+
{'guess_cf' : 'Initial guess center frequency for peak.'})
190+
191+
###################################################################################################
192+
#
193+
# Now we need to define our fit approach! To do so, we will mimic the approach we used above
194+
# to define a custom algorithm object, this time making the `_fit` method implement an actual
195+
# fitting procedure. Note that while the `_fit` function should be the main method that runs
196+
# the fitting process, it can also call additional methods. In this implementation, we define
197+
# additional fit methods to fit each component.
198+
#
199+
# To fit the data components, we will use the `curve_fit` function from scipy.
200+
#
201+
202+
###################################################################################################
203+
204+
from scipy.optimize import curve_fit
205+
206+
class CustomAlgorithm(Algorithm):
207+
"""Custom fitting algorithm."""
208+
209+
def __init__(self, guess_cf, modes=None, data=None, results=None, debug=False):
210+
"""Initialize DummyAlgorithm instance."""
211+
212+
# Initialize base algorithm object with algorithm metadata
213+
super().__init__(
214+
name='custom_fit_algo',
215+
description='Example custom algorithm.',
216+
public_settings=CUSTOM_ALGO_SETTINGS,
217+
modes=modes, data=data, results=results, debug=debug)
218+
219+
## Public settings
220+
self.settings.guess_cf = guess_cf
221+
222+
def _fit(self):
223+
"""Define the full fitting algorithm."""
224+
225+
# Fit each individual component
226+
self._fit_aperiodic()
227+
self._fit_peak()
228+
229+
# Create full model from the individual components
230+
self.results.model.modeled_spectrum = \
231+
self.results.model._peak_fit + self.results.model._ap_fit
232+
233+
def _fit_aperiodic(self):
234+
"""Fit aperiodic - direct fit to full spectrum."""
235+
236+
# Fit aperiodic component directly to data & collect parameter results
237+
ap_params, _ = curve_fit(\
238+
self.modes.aperiodic.func, self.data.freqs, self.data.power_spectrum,
239+
p0=np.array([0] * self.modes.aperiodic.n_params))
240+
self.results.params.aperiodic.add_params('fit', ap_params)
241+
242+
# Construct & collect aperiodic component
243+
self.results.model._ap_fit = self.modes.aperiodic.func(freqs, *ap_params)
244+
245+
def _fit_peak(self):
246+
"""Fit peak - single peak, with initial guess CF, to flattened spectrum."""
247+
248+
# Fit peak
249+
self.results.model._spectrum_flat = self.data.power_spectrum - self.results.model._ap_fit
250+
pe_params, _ = curve_fit(\
251+
self.modes.periodic.func, self.data.freqs, self.results.model._spectrum_flat,
252+
p0=np.array([self.settings.guess_cf] + [1] * (self.modes.periodic.n_params - 1)))
253+
self.results.params.periodic.add_params('fit', np.atleast_2d(pe_params))
254+
255+
# Construct periodic component
256+
self.results.model._peak_fit = self.modes.periodic.func(freqs, *pe_params)
257+
258+
###################################################################################################
259+
260+
# Initialize a model object, passing in a custom fit algorithm and settings for this algorithm
261+
fm = SpectralModel(algorithm=CustomAlgorithm, guess_cf=10)
262+
263+
# Check the defined fit algorithm
264+
fm.algorithm.print()
265+
266+
###################################################################################################
267+
268+
# Fit model with custom algorithm and report results
269+
fm.report(freqs, powers)
270+
271+
###################################################################################################
272+
#
273+
# In the above we fit a model with our custom fit algorithm, and can see the results.
274+
#
275+
276+
###################################################################################################
277+
# Notes on Defining Custom Algorithms
278+
# -----------------------------------
279+
#
280+
# In these examples, we have made quite simple algorithms. This may be a desired use case -
281+
# creating bespoke fit approaches for specific kinds of data.
282+
#
283+
# In cases where generalizability is more desired, the fit algorithm is likely going to need to
284+
# be significantly more detailed to address
285+
#
286+
# To see, for example, the details of the original / default fit algorithm, check the
287+
# definition of the `spectral_fit` algorithm in the codebase, which is also defined in the same
288+
# way as here.
289+
#
290+
# Additional notes to consider when creating custom algorithms:
291+
#
292+
# - In the above, we didn't consider different fit modes, and used the defaults. Depending on
293+
# your use case, the fit algorithm may or not want to make assumptions about the fit modes.
294+
# To make it generalize, the algorithm needs to be written in a way that is flexible for
295+
# applying different fit functions that may have different numbers of parameters
296+
# - As well as the public settings we defined here, you may want to additional specify
297+
# a set of private settings (additional settings that are defined for the algorithm, which
298+
# are not expected to be changed in most use cases, but which can be accessed)
299+
#
300+
301+
###################################################################################################
302+
# Algorithms that use curve_fit
303+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
304+
#
305+
# A common approach for fitting functions to data is to use the scipy `curve_fit`
306+
# function to estimate parameters to fit a specified function to some data, as we did in
307+
# an above example.
308+
#
309+
# When doing so, you may also want to manage and allow inputs for settings that to the
310+
# curve_fit function to manage the fitting process. As a shortcut for this case, you can use the
311+
# :class:`~specparam.algorithms.algorithm.AlgorithmCF` object which pre-initializes a set
312+
# of curve_fit settings.
313+
#
314+
# In addition, when using `curve_fit` you are likely going to want to
315+
#

0 commit comments

Comments
 (0)