Debian Codegraph @

multipletau/core.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 """
4 A multiple-τ algorithm for Python 2.7 and 3.x.
5
6 Copyright (c) 2014 Paul Müller
7
8 Redistribution and use in source and binary forms, with or without
9 modification, are permitted provided that the following conditions are
10 met:
11
12 1. Redistributions of source code must retain the above copyright
13 notice, this list of conditions and the following disclaimer.
14
15 2. Redistributions in binary form must reproduce the above copyright
16 notice, this list of conditions and the following disclaimer in
17 the documentation and/or other materials provided with the
18 distribution.
19
20 3. Neither the name of multipletau nor the names of its contributors
21 may be used to endorse or promote products derived from this
22 software without specific prior written permission.
23
24 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INFRAE OR
28 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 """
36 from __future__ import division
37
38 import numpy as np
39 import warnings
40
41 __all__ = ["autocorrelate", "correlate", "correlate_numpy"]
42
43
44 #: Defines the cutoff when the absolute mean trace divided by the median
45 #: of the absolute value of the trace is treated as zero.
46 ZERO_CUTOFF = 1e-15
47
48
49 class DtypeWarning(UserWarning):
50 pass
51
52
53 class InvalidMWarning(UserWarning):
54 pass
55
56
57 def autocorrelate(a, m=16, deltat=1, normalize=False, copy=True, dtype=None,
58 compress="average", ret_sum=False):
59 """
60 Autocorrelation of a 1-dimensional sequence on a log2-scale.
61
62 This computes the correlation similar to
63 :py:func:`numpy.correlate` for positive :math:`k` on a base 2
64 logarithmic scale.
65
66 :func:`numpy.correlate(a, a, mode="full")[len(a)-1:]`
67
68 :math:`z_k = \\Sigma_n a_n a_{n+k}`
69
70
71 Parameters
72 ----------
73 a: array-like
74 input sequence
75 m: even integer
76 defines the number of points on one level, must be an
77 even integer
78 deltat: float
79 distance between bins
80 normalize: bool
81 normalize the result to the square of the average input
82 signal and the factor :math:`M-k`.
83 copy: bool
84 copy input array, set to ``False`` to save memory
85 dtype: object to be converted to a data type object
86 The data type of the returned array and of the accumulator
87 for the multiple-tau computation.
88 compress: str
89 strategy for propagating values to the next register
90
91 - `"average"` (default): average two measurements when pushing
92 to the next level of the correlator.
93 - `"first"`: use only the first value when pushing to the next
94 level of the correlator.
95 - `"second"`: use only the second value when pushing to the
96 next level of the correlator.
97
98 Using only the first or the second values during propagation
99 completely removes the systematic error at the cost of
100 increasing the statistical error.
101 See https://doi.org/10.1063/1.3491098 for a discussion on the
102 effect of averaging.
103 ret_sum: bool
104 return the exact sum :math:`z_k = \\Sigma_n a_n a_{n+k}`. In addition
105 :math:`M-k` is returned as an array of length N.
106
107
108 Returns
109 -------
110 autocorrelation: ndarray of shape (N,2)
111 the lag time (1st column) and the autocorrelation (2nd column).
112 count: ndarray of length N
113 only returned if `ret_sum` is True; the value of :math:`M-k`
114 for each row in `autocorrelation`.
115
116
117 Notes
118 -----
119 .. versionchanged:: 0.1.6
120 Compute the correlation for zero lag time.
121
122 The algorithm computes the correlation with the convention of the
123 curve decaying to zero.
124
125 For experiments like e.g. fluorescence correlation spectroscopy,
126 the signal can be normalized to :math:`M-k`
127 by invoking ``normalize=True``.
128
129 For normalizing according to the behavior
130 of :py:func:`numpy.correlate`, use ``normalize=False``.
131
132 For complex arrays, this method falls back to the method
133 :func:`correlate`.
134
135
136 Examples
137 --------
138 >>> from multipletau import autocorrelate
139 >>> autocorrelate(range(42), m=2, dtype=np.float64)
140 array([[ 0.00000000e+00, 2.38210000e+04],
141 [ 1.00000000e+00, 2.29600000e+04],
142 [ 2.00000000e+00, 2.21000000e+04],
143 [ 4.00000000e+00, 2.03775000e+04],
144 [ 8.00000000e+00, 1.50612000e+04]])
145 """
146 if not isinstance(normalize, bool):
147 raise ValueError("`normalize` must be boolean!")
148 if not isinstance(copy, bool):
149 raise ValueError("`copy` must be boolean!")
150 if not isinstance(ret_sum, bool):
151 raise ValueError("`ret_sum` must be boolean!")
152 if normalize and ret_sum:
153 raise ValueError("'normalize' and 'ret_sum' must not both be True!")
154 compress_values = ["average", "first", "second"]
155 if compress not in compress_values:
156 raise ValueError("Invalid value for `compress`! Possible values "
157 "are '{}'.".format(','.join(compress_values)))
158
159 if dtype is None:
160 dtype = np.dtype(a[0].__class__)
161 else:
162 dtype = np.dtype(dtype)
163
164 # Complex data
165 if dtype.kind == "c":
166 # run cross-correlation
167 return correlate(a=a,
168 v=a,
169 m=m,
170 deltat=deltat,
171 normalize=normalize,
172 copy=copy,
173 dtype=dtype)
174 elif dtype.kind != "f":
175 warnings.warn("Input dtype is not float; casting to np.float64!",
176 DtypeWarning)
177 dtype = np.dtype(np.float64)
178
179 # If copy is false and dtype is the same as the input array,
180 # then this line does not have an effect:
181 trace = np.array(a, dtype=dtype, copy=copy)
182
183 # Check parameters
184 if m // 2 != m / 2:
185 mold = m
186 m = np.int_((m // 2 + 1) * 2)
187 warnings.warn("Invalid value of m={}. Using m={} instead"
188 .format(mold, m), InvalidMWarning)
189 else:
190 m = np.int_(m)
191
192 N = N0 = trace.shape[0]
193
194 # Find out the length of the correlation function.
195 # The integer k defines how many times we can average over
196 # two neighboring array elements in order to obtain an array of
197 # length just larger than m.
198 k = np.int_(np.floor(np.log2(N / m)))
199
200 # In the base2 multiple-tau scheme, the length of the correlation
201 # array is (only taking into account values that are computed from
202 # traces that are just larger than m):
203 lenG = m + k * (m // 2) + 1
204
205 G = np.zeros((lenG, 2), dtype=dtype)
206
207 normstat = np.zeros(lenG, dtype=dtype)
208 normnump = np.zeros(lenG, dtype=dtype)
209
210 traceavg = np.average(trace)
211
212 # We use the fluctuation of the signal around the mean
213 if normalize:
214 trace -= traceavg
215 if np.abs(traceavg) / np.median(np.abs(trace)) < ZERO_CUTOFF:
216 raise ValueError("Cannot normalize: Average of `a` is zero!")
217
218 # Otherwise the following for-loop will fail:
219 if N < 2 * m:
220 raise ValueError("`len(a)` must be >= `2m`!")
221
222 # Calculate autocorrelation function for first m+1 bins
223 # Discrete convolution of m elements
224 for n in range(0, m + 1):
225 G[n, 0] = deltat * n
226 # This is the computationally intensive step
227 G[n, 1] = np.sum(trace[:N - n] * trace[n:])
228 normstat[n] = N - n
229 normnump[n] = N
230 # Now that we calculated the first m elements of G, let us
231 # go on with the next m/2 elements.
232 # Check if len(trace) is even:
233 if N % 2 == 1:
234 N -= 1
235 # compress every second element
236 if compress == compress_values[0]:
237 trace = (trace[:N:2] + trace[1:N:2]) / 2
238 elif compress == compress_values[1]:
239 trace = trace[:N:2]
240 elif compress == compress_values[2]:
241 trace = trace[1:N:2]
242 N //= 2
243 # Start iteration for each m/2 values
244 for step in range(1, k + 1):
245 # Get the next m/2 values via correlation of the trace
246 for n in range(1, m // 2 + 1):
247 npmd2 = n + m // 2
248 idx = m + n + (step - 1) * m // 2
249 if len(trace[:N - npmd2]) == 0:
250 # This is a shortcut that stops the iteration once the
251 # length of the trace is too small to compute a corre-
252 # lation. The actual length of the correlation function
253 # does not only depend on k - We also must be able to
254 # perform the sum with respect to k for all elements.
255 # For small N, the sum over zero elements would be
256 # computed here.
257 #
258 # One could make this for-loop go up to maxval, where
259 # maxval1 = int(m/2)
260 # maxval2 = int(N-m/2-1)
261 # maxval = min(maxval1, maxval2)
262 # However, we then would also need to find out which
263 # element in G is the last element...
264 G = G[:idx - 1]
265 normstat = normstat[:idx - 1]
266 normnump = normnump[:idx - 1]
267 # Note that this break only breaks out of the current
268 # for loop. However, we are already in the last loop
269 # of the step-for-loop. That is because we calculated
270 # k in advance.
271 break
272 else:
273 G[idx, 0] = deltat * npmd2 * 2**step
274 # This is the computationally intensive step
275 G[idx, 1] = np.sum(trace[:N - npmd2] *
276 trace[npmd2:])
277 normstat[idx] = N - npmd2
278 normnump[idx] = N
279 # Check if len(trace) is even:
280 if N % 2 == 1:
281 N -= 1
282 # compress every second element
283 if compress == compress_values[0]:
284 trace = (trace[:N:2] + trace[1:N:2]) / 2
285 elif compress == compress_values[1]:
286 trace = trace[:N:2]
287 elif compress == compress_values[2]:
288 trace = trace[1:N:2]
289
290 N //= 2
291
292 if normalize:
293 G[:, 1] /= traceavg**2 * normstat
294 elif not ret_sum:
295 G[:, 1] *= N0 / normnump
296
297 if ret_sum:
298 return G, normstat
299 else:
300 return G
301
302
303 def correlate(a, v, m=16, deltat=1, normalize=False, copy=True, dtype=None,
304 compress="average", ret_sum=False):
305 """
306 Cross-correlation of two 1-dimensional sequences
307 on a log2-scale.
308
309 This computes the cross-correlation similar to
310 :py:func:`numpy.correlate` for positive :math:`k` on a base 2
311 logarithmic scale.
312
313 :func:`numpy.correlate(a, v, mode="full")[len(a)-1:]`
314
315 :math:`z_k = \\Sigma_n a_n v_{n+k}`
316
317 Note that only the correlation in the positive direction is
318 computed. To obtain the correlation for negative lag times
319 swap the input variables ``a`` and ``v``.
320
321 Parameters
322 ----------
323 a, v: array-like
324 input sequences with equal length
325 m: even integer
326 defines the number of points on one level, must be an
327 even integer
328 deltat: float
329 distance between bins
330 normalize: bool
331 normalize the result to the square of the average input
332 signal and the factor :math:`M-k`.
333 copy: bool
334 copy input array, set to ``False`` to save memory
335 dtype: object to be converted to a data type object
336 The data type of the returned array and of the accumulator
337 for the multiple-tau computation.
338 compress: str
339 strategy for propagating values to the next register
340
341 - `"average"` (default): average two measurements when pushing
342 to the next level of the correlator.
343 - `"first"`: use only the first value when pushing to the next
344 level of the correlator.
345 - `"second"`: use only the second value when pushing to the
346 next level of the correlator.
347
348 Using only the first or the second values during propagation
349 completely removes the systematic error at the cost of
350 increasing the statistical error.
351 See https://doi.org/10.1063/1.3491098 for a discussion on the
352 effect of averaging.
353 ret_sum: bool
354 return the exact sum :math:`z_k = \\Sigma_n a_n v_{n+k}`. In addition
355 :math:`M-k` is returned as an array of length N.
356
357
358 Returns
359 -------
360 cross_correlation: ndarray of shape (N,2)
361 the lag time (1st column), the cross-correlation (2nd column).
362 count: ndarray of length N
363 only returned if `ret_sum` is True; the value of :math:`M-k`
364 for each row in `autocorrelation`.
365
366
367 Notes
368 -----
369 .. versionchanged:: 0.1.6
370 Compute the correlation for zero lag time and correctly
371 normalize the correlation for a complex input sequence `v`.
372
373 The algorithm computes the correlation with the convention of the
374 curve decaying to zero.
375
376 For experiments like e.g. fluorescence correlation spectroscopy,
377 the signal can be normalized to :math:`M-k`
378 by invoking ``normalize=True``.
379
380 For normalizing according to the behavior of
381 :py:func:`numpy.correlate`, use ``normalize=False``.
382
383
384 Examples
385 --------
386 >>> from multipletau import correlate
387 >>> correlate(range(42), range(1,43), m=2, dtype=np.float64)
388 array([[ 0.00000000e+00, 2.46820000e+04],
389 [ 1.00000000e+00, 2.38210000e+04],
390 [ 2.00000000e+00, 2.29600000e+04],
391 [ 4.00000000e+00, 2.12325000e+04],
392 [ 8.00000000e+00, 1.58508000e+04]])
393
394 """
395 if not isinstance(normalize, bool):
396 raise ValueError("`normalize` must be boolean!")
397 if not isinstance(copy, bool):
398 raise ValueError("`copy` must be boolean!")
399 if not isinstance(ret_sum, bool):
400 raise ValueError("`ret_sum` must be boolean!")
401 if normalize and ret_sum:
402 raise ValueError("'normalize' and 'ret_sum' must not both be True!")
403 compress_values = ["average", "first", "second"]
404 if compress not in compress_values:
405 raise ValueError("Invalid value for `compress`! Possible values "
406 "are '{}'.".format(','.join(compress_values)))
407
408 # See `autocorrelation` for better documented code.
409 traceavg1 = np.average(v)
410 traceavg2 = np.average(a)
411 if normalize:
412 if np.abs(traceavg1) / np.median(np.abs(v)) < ZERO_CUTOFF:
413 raise ValueError("Cannot normalize: Average of `v` is zero!")
414 if np.abs(traceavg2) / np.median(np.abs(a)) < ZERO_CUTOFF:
415 raise ValueError("Cannot normalize: Average of `a` is zero!")
416
417 if dtype is None:
418 dtype = np.dtype(v[0].__class__)
419 dtype2 = np.dtype(a[0].__class__)
420 if dtype != dtype2:
421 if dtype.kind == "c" or dtype2.kind == "c":
422 # The user might try to combine complex64 and float128.
423 warnings.warn(
424 "Input dtypes not equal; casting to np.complex128!",
425 InvalidMWarning)
426 dtype = np.dtype(np.complex128)
427 else:
428 warnings.warn("Input dtypes not equal; casting to np.float64!",
429 InvalidMWarning)
430 dtype = np.dtype(np.float64)
431 else:
432 dtype = np.dtype(dtype)
433
434 if dtype.kind not in ["c", "f"]:
435 warnings.warn("Input dtype is not float; casting to np.float64!",
436 InvalidMWarning)
437 dtype = np.dtype(np.float64)
438
439 trace1 = np.array(v, dtype=dtype, copy=copy)
440
441 # Prevent traces from overwriting each other
442 if a is v:
443 # Force copying trace 2
444 copy = True
445
446 trace2 = np.array(a, dtype=dtype, copy=copy)
447
448 if trace1.size != trace2.size:
449 raise ValueError("`a` and `v` must have same length!")
450
451 # Complex data
452 if dtype.kind == "c":
453 np.conjugate(trace1, out=trace1)
454
455 # Check parameters
456 if m // 2 != m / 2:
457 mold = m
458 m = np.int_(m // 2 + 1) * 2
459 warnings.warn("Invalid value of m={}. Using m={} instead"
460 .format(mold, m), InvalidMWarning)
461 else:
462 m = np.int_(m)
463
464 N = N0 = trace1.shape[0]
465 # Find out the length of the correlation function.
466 # The integer k defines how many times we can average over
467 # two neighboring array elements in order to obtain an array of
468 # length just larger than m.
469 k = np.int_(np.floor(np.log2(N / m)))
470
471 # In the base2 multiple-tau scheme, the length of the correlation
472 # array is (only taking into account values that are computed from
473 # traces that are just larger than m):
474 lenG = m + k * m // 2 + 1
475
476 G = np.zeros((lenG, 2), dtype=dtype)
477 normstat = np.zeros(lenG, dtype=dtype)
478 normnump = np.zeros(lenG, dtype=dtype)
479
480 # We use the fluctuation of the signal around the mean
481 if normalize:
482 trace1 -= np.conj(traceavg1)
483 trace2 -= traceavg2
484
485 # Otherwise the following for-loop will fail:
486 if N < 2 * m:
487 raise ValueError("`len(a)` must be >= `2m`!")
488
489 # Calculate autocorrelation function for first m+1 bins
490 for n in range(0, m + 1):
491 G[n, 0] = deltat * n
492 G[n, 1] = np.sum(trace1[:N - n] * trace2[n:])
493 normstat[n] = N - n
494 normnump[n] = N
495 # Check if len(trace) is even:
496 if N % 2 == 1:
497 N -= 1
498 # compress every second element
499 if compress == compress_values[0]:
500 trace1 = (trace1[:N:2] + trace1[1:N:2]) / 2
501 trace2 = (trace2[:N:2] + trace2[1:N:2]) / 2
502 elif compress == compress_values[1]:
503 trace1 = trace1[:N:2]
504 trace2 = trace2[:N:2]
505 elif compress == compress_values[2]:
506 trace1 = trace1[1:N:2]
507 trace2 = trace2[1:N:2]
508 N //= 2
509
510 for step in range(1, k + 1):
511 # Get the next m/2 values of the trace
512 for n in range(1, m // 2 + 1):
513 npmd2 = (n + m // 2)
514 idx = m + n + (step - 1) * m // 2
515 if len(trace1[:N - npmd2]) == 0:
516 # Abort
517 G = G[:idx - 1]
518 normstat = normstat[:idx - 1]
519 normnump = normnump[:idx - 1]
520 break
521 else:
522 G[idx, 0] = deltat * npmd2 * 2**step
523 G[idx, 1] = np.sum(
524 trace1[:N - npmd2] * trace2[npmd2:])
525 normstat[idx] = N - npmd2
526 normnump[idx] = N
527
528 # Check if len(trace) is even:
529 if N % 2 == 1:
530 N -= 1
531 # compress every second element
532 if compress == compress_values[0]:
533 trace1 = (trace1[:N:2] + trace1[1:N:2]) / 2
534 trace2 = (trace2[:N:2] + trace2[1:N:2]) / 2
535 elif compress == compress_values[1]:
536 trace1 = trace1[:N:2]
537 trace2 = trace2[:N:2]
538 elif compress == compress_values[2]:
539 trace1 = trace1[1:N:2]
540 trace2 = trace2[1:N:2]
541 N //= 2
542
543 if normalize:
544 G[:, 1] /= traceavg1 * traceavg2 * normstat
545 elif not ret_sum:
546 G[:, 1] *= N0 / normnump
547
548 if ret_sum:
549 return G, normstat
550 else:
551 return G
552
553
554 def correlate_numpy(a, v, deltat=1, normalize=False,
555 dtype=None, copy=True):
556 """
557 Convenience function that wraps around :py:func:`numpy.correlate` and
558 returns the correlation in the same format as :func:`correlate` does.
559
560
561 Parameters
562 ----------
563 a, v: array-like
564 input sequences
565 deltat: float
566 distance between bins
567 normalize: bool
568 normalize the result to the square of the average input signal
569 and the factor :math:`M-k`. The resulting curve follows
570 the convention of decaying to zero for large lag times.
571 copy: bool
572 copy input array, set to ``False`` to save memory
573 dtype: object to be converted to a data type object
574 The data type of the returned array.
575
576
577 Returns
578 -------
579 cross_correlation: ndarray of shape (N,2)
580 the lag time (column 1) and the cross-correlation (column 2).
581
582
583 Notes
584 -----
585 .. versionchanged:: 0.1.6
586 Removed false normalization when `normalize==False`.
587 """
588 ab = np.array(a, dtype=dtype, copy=copy)
589 vb = np.array(v, dtype=dtype, copy=copy)
590
591 if ab.size != vb.size:
592 raise ValueError("`a` and `v` must have same length!")
593
594 avg = np.average(ab)
595 vvg = np.average(vb)
596
597 if normalize:
598 ab -= avg
599 vb -= vvg
600 if np.abs(avg) / np.median(np.abs(ab)) < ZERO_CUTOFF:
601 raise ValueError("Cannot normalize: Average of `a` is zero!")
602 if np.abs(vvg) / np.median(np.abs(vb)) < ZERO_CUTOFF:
603 raise ValueError("Cannot normalize: Average of `v` is zero!")
604
605 Gd = np.correlate(ab, vb, mode="full")[len(ab) - 1:]
606
607 if normalize:
608 N = len(Gd)
609 m = N - np.arange(N)
610 Gd /= m * avg * vvg
611
612 G = np.zeros((len(Gd), 2), dtype=dtype)
613 G[:, 1] = Gd
614 G[:, 0] = np.arange(len(Gd)) * deltat
615 return G