ParaMonte Fortran 2.0.0
Parallel Monte Carlo and Machine Learning Library
See the latest version documentation.
pm_sampleCCF::setCCF Interface Reference

Return the cross-correlation function (CCF) \((f\star g)(\tau)\) of the discrete signal \(g\) lagging the signal the discrete signal \(f\) for a range of lags that spans the maximum of the lengths of the two sequences.
More...

Detailed Description

Return the cross-correlation function (CCF) \((f\star g)(\tau)\) of the discrete signal \(g\) lagging the signal the discrete signal \(f\) for a range of lags that spans the maximum of the lengths of the two sequences.

See the documentation of the parent module pm_sampleCCF for algorithmic details and sample correlation matrix definition.

Warning
This low-level generic interface neither right-pads nor normalizes the input sequences in any form.
The input sequences are used as is for computing the CCF.
In general, the following steps should be taken before and after computing the CCF using this routine,
  1. If the original (unpadded) sequences are not already mean-shifted (with zero mean), it is highly recommended to mean-shift the sequences first before computing the CCF.
    This can be readily done by the routines of pm_sampleMean and pm_sampleShift.
  2. While the input mean-shifted sequences can be passed to this generic interface as is, it is highly recommended to right-pad the mean-shifted sequences by zeros to the minimum length of size(f) + size(g) - 1.
  3. The output CCF must from the generic interface must be multiplied by 1 / size(ccf) / sqrt(sum(abs(f)**2) + sum(abs(g)**2)) to properly normalize the output CCF to the range [-1, +1].
    If the input sequences have unit-variances, the normalization factor reduces to 1 / size(ccf).
    While easy, this rescaling can also be readily done via the generic interfaces of pm_sampleScale.
Note
When the input sequences are right-padded to the size size(f) + size(g) - 1, then,
  1. the resulting slice ccf(1 : size(g)) by this generic interface contains the cross-correlation corresponding to lags [(i, i = 0, size(g))].
  2. the resulting slice ccf(size(g) + 1 : size(ccf)) contains the cross-correlation corresponding to lags [(i, i = -size(f) + 1, -1)].
Parameters
[in]factor: The input contiguous vector of shape (:) of type integer of default kind IK, containing the factorization of the length of the input sequence f whose FFT is to be computed.
This input argument along with the input argument coef is the direct output of getFactorFFT.
[in]coef: The input contiguous vector of shape (1:size(data)) of the same type and kind as the input argument f, containing the trigonometric look up table required for FFT of the specified sequences.
This input argument along with factor is the direct output of getFactorFFT.
[in,out]f: The input contiguous vector of arbitrary size (of minimum 2) of,
  1. type complex of kind any supported by the processor (e.g., CK, CK32, CK64, or CK128),
  2. type real of kind any supported by the processor (e.g., RK, RK32, RK64, or RK128),
containing the first sequence in the cross-correlation computation.
On output, the contents of f are destroyed.
If the output inf = .true., then f contains the resulting unnormalized CCF of the input sequences.
[in,out]g: The input contiguous vector of the same type and kind and size as the input argument f, containing the second sequence in the cross-correlation computation.
On output, the contents of g are destroyed.
If the condition inf = .false. holds on output, then g contains the resulting unnormalized CCF of the input sequences.
[out]work: The output contiguous vector of the same type, kind, and size as the input f, used as a workspace.
[out]inf: The output scalar of type logical of default kind LK.
  1. If .true., the resulting ccf is stored in the output argument f upon return from the procedure.
  2. If .false., the resulting ccf is stored in the output argument g upon return from the procedure.


Possible calling interfaces

use pm_sampleCCF, only: setCCF
call setCCF(factor(:), coef(1:nseq), f(1:nseq), g(1:nseq), work(1:nseq), inf)
Return the cross-correlation function (CCF) of the discrete signal lagging the signal the discrete ...
This module contains classes and procedures for computing properties related to the cross correlation...
Warning
The condition 2 < size(f) must hold for the corresponding input arguments.
The condition size(f) == size(g) must hold for the corresponding input arguments.
The condition size(f) == size(coef) must hold for the corresponding input arguments.
The condition size(f) == size(work) must hold for the corresponding input arguments.
These conditions are verified only if the library is built with the preprocessor macro CHECK_ENABLED=1.
The pure procedure(s) documented herein become impure when the ParaMonte library is compiled with preprocessor macro CHECK_ENABLED=1.
By default, these procedures are pure in release build and impure in debug and testing builds.
See also
getACF
setACF
getCCF
setCCF
getCor
setCor
getRho
setRho
getCov
setCov
setECDF
getMean
setMean
getShifted
setShifted
getVar
setVar


Example usage

1program example
2
3 use pm_kind, only: SK, IK, LK, RK
4 use pm_io, only: getErrTableWrite
5 use pm_io, only: display_type
6 use pm_io, only: getFormat
7 use pm_fftpack, only: allocatable
8 use pm_fftpack, only: getFactorFFT
9 use pm_sampleCCF, only: setCCF
10 use pm_sampleCCF, only: stdscale
11 use pm_arrayRange, only: getRange
12 use pm_distUnif, only: getUnifRand
13 use pm_distNorm, only: getNormLogPDF
14 use pm_arrayPad, only: getPaddedr
15 use pm_arrayFill, only: getFilled
16 use pm_sampleShift, only: getShifted
17 use pm_arrayResize, only: setResized
18 use pm_arraySpace, only: getLinSpace
19 use pm_sampleNorm, only: getNormed
20 use pm_sampleMean, only: getMean
21 use pm_sampleVar, only: getVar
22
23 implicit none
24
25 logical(LK) :: inf
26 type(display_type) :: disp
27 character(:), allocatable :: format
28 integer(IK) :: nsam, itry, ntry = 1
29 disp = display_type(file = "main.out.F90")
30
31 call disp%skip()
32 call disp%show("!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
33 call disp%show("!Compute the cross-correlation of two samples.")
34 call disp%show("!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
35 call disp%skip()
36
37 block
38 use pm_kind, only: TKG => RKS ! All other real types are also supported.
39 integer(IK), allocatable :: factor(:), lag(:)
40 real(TKG), allocatable :: f(:), g(:), fcopy(:), gcopy(:), ccf(:), coef(:), range(:)
41 real(TKG), parameter :: ZERO = 0._TKG
42 call disp%skip()
43 call disp%show("nsam = 41")
44 nsam = 41
45 call disp%show("range = getLinSpace(-10., 10., nsam)")
46 range = getLinSpace(-10., 10., nsam)
47 call disp%show("f = sin(range)")
48 f = sin(range)
49 call disp%show("f = getPaddedr(getNormed(f, -getMean(f), 1._TKG / getVar(f)), nsam - 1, ZERO)")
50 f = getPaddedr(getNormed(f, -getMean(f), 1._TKG / getVar(f)), nsam - 1, ZERO)
51 call disp%show("f")
52 call disp%show( f )
53 call disp%show("g = cos(range)")
54 g = cos(range)
55 call disp%show("g = getPaddedr(getNormed(g, -getMean(g), 1._TKG / getVar(g)), nsam - 1, ZERO)")
56 g = getPaddedr(getNormed(g, -getMean(g), 1._TKG / getVar(g)), nsam - 1, ZERO)
57 call disp%show("g")
58 call disp%show( g )
59 call disp%show("fcopy = f; gcopy = g")
60 fcopy = f; gcopy = g
61 call disp%show("call setResized(ccf, size(f, 1, IK))")
62 call setResized(ccf, size(f, 1, IK))
63 call disp%show("factor = getFactorFFT(f, coef, allocatable)")
64 factor = getFactorFFT(f, coef, allocatable)
65 call disp%show("call setCCF(factor, coef, fcopy, gcopy, ccf, inf)")
66 call setCCF(factor, coef, fcopy, gcopy, ccf, inf)
67 call disp%show("ccf = merge(fcopy, gcopy, inf) / size(ccf)")
68 ccf = merge(fcopy, gcopy, inf) / size(ccf)
69 call disp%show("size(ccf)")
70 call disp%show( size(ccf) )
71 call disp%show("ccf")
72 call disp%show( ccf )
73 call disp%show("lag = getRange(-nsam + 1_IK, nsam - 1_IK)")
74 lag = getRange(-nsam + 1_IK, nsam - 1_IK)
75 call disp%show("if (0 /= getErrTableWrite(SK_'setCCF.crd.sin.cos.RK.txt', reshape([range, f(1:nsam), g(1:nsam)], [nsam, 3_IK]), header = SK_'crd,f,g')) error stop 'ccf outputting failed.'")
76 if (0 /= getErrTableWrite(SK_'setCCF.crd.sin.cos.RK.txt', reshape([range, f(1:nsam), g(1:nsam)], [nsam, 3_IK]), header = SK_'crd,f,g')) error stop 'ccf outputting failed.'
77 call disp%show("if (0 /= getErrTableWrite(SK_'setCCF.ccf.sin.cos.RK.txt', reshape([real(lag, TKG), ccf], [size(lag), 2]), header = SK_'lag,ccf')) error stop 'ccf outputting failed.'")
78 if (0 /= getErrTableWrite(SK_'setCCF.ccf.sin.cos.RK.txt', reshape([real(lag, TKG), ccf], [size(lag), 2]), header = SK_'lag,ccf')) error stop 'ccf outputting failed.'
79 call disp%skip()
80 end block
81
82end program example
Generate and return an array of the specified rank and shape of arbitrary intrinsic type and kind wit...
Generate a resized copy of the input array by padding it to the right with the requested paddings and...
Generate minimally-spaced character, integer, real sequences or sequences at fixed intervals of size ...
Allocate or resize (shrink or expand) an input allocatable scalar string or array of rank 1....
Generate count evenly spaced points over the interval [x1, x2] if x1 < x2, or [x2,...
Generate the natural logarithm of probability density function (PDF) of the univariate Normal distrib...
Generate and return a scalar or a contiguous array of rank 1 of length s1 of randomly uniformly distr...
Generate and return the factorization vector factor of the specified input sequence length and the co...
Definition: pm_fftpack.F90:292
Generate and return the iostat code resulting from writing the input table of rank 1 or 2 to the spec...
Definition: pm_io.F90:5940
Generate and return a generic or type/kind-specific IO format with the requested specifications that ...
Definition: pm_io.F90:18485
This is a generic method of the derived type display_type with pass attribute.
Definition: pm_io.F90:11726
This is a generic method of the derived type display_type with pass attribute.
Definition: pm_io.F90:11508
Generate and return the (weighted) mean of an input sample of nsam observations with ndim = 1 or 2 at...
Generate a sample of shape (nsam), or (ndim, nsam) or (nsam, ndim) that is normalized by the specifie...
Generate a sample of shape (nsam), or (ndim, nsam) or (nsam, ndim) that is shifted by the specified i...
Generate and return the variance of the input sample of type complex or real of shape (nsam) or (ndim...
This module contains procedures and generic interfaces for convenient allocation and filling of array...
This module contains procedures and generic interfaces for resizing an input array and padding them w...
Definition: pm_arrayPad.F90:30
This module contains procedures and generic interfaces for generating ranges of discrete character,...
This module contains procedures and generic interfaces for resizing allocatable arrays of various typ...
This module contains procedures and generic interfaces for generating arrays with linear or logarithm...
This module contains classes and procedures for computing various statistical quantities related to t...
This module contains classes and procedures for computing various statistical quantities related to t...
This module contains procedures and generic interfaces for computing the Discrete Fourier Transform o...
Definition: pm_fftpack.F90:205
This module contains classes and procedures for input/output (IO) or generic display operations on st...
Definition: pm_io.F90:252
type(display_type) disp
This is a scalar module variable an object of type display_type for general display.
Definition: pm_io.F90:11393
This module defines the relevant Fortran kind type-parameters frequently used in the ParaMonte librar...
Definition: pm_kind.F90:268
integer, parameter RK
The default real kind in the ParaMonte library: real64 in Fortran, c_double in C-Fortran Interoperati...
Definition: pm_kind.F90:543
integer, parameter LK
The default logical kind in the ParaMonte library: kind(.true.) in Fortran, kind(....
Definition: pm_kind.F90:541
integer, parameter IK
The default integer kind in the ParaMonte library: int32 in Fortran, c_int32_t in C-Fortran Interoper...
Definition: pm_kind.F90:540
integer, parameter SK
The default character kind in the ParaMonte library: kind("a") in Fortran, c_char in C-Fortran Intero...
Definition: pm_kind.F90:539
integer, parameter RKS
The single-precision real kind in Fortran mode. On most platforms, this is an 32-bit real kind.
Definition: pm_kind.F90:567
This module contains classes and procedures for computing the first moment (i.e., the statistical mea...
This module contains classes and procedures for normalizing univariate or multivariate samples by arb...
This module contains classes and procedures for shifting univariate or multivariate samples by arbitr...
This module contains classes and procedures for computing the properties related to the covariance ma...
Generate and return an object of type display_type.
Definition: pm_io.F90:10282

Example Unix compile command via Intel ifort compiler
1#!/usr/bin/env sh
2rm main.exe
3ifort -fpp -standard-semantics -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
4./main.exe

Example Windows Batch compile command via Intel ifort compiler
1del main.exe
2set PATH=..\..\..\lib;%PATH%
3ifort /fpp /standard-semantics /O3 /I:..\..\..\include main.F90 ..\..\..\lib\libparamonte*.lib /exe:main.exe
4main.exe

Example Unix / MinGW compile command via GNU gfortran compiler
1#!/usr/bin/env sh
2rm main.exe
3gfortran -cpp -ffree-line-length-none -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
4./main.exe

Example output
1
2!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3!Compute the cross-correlation of two samples.
4!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5
6
7nsam = 41
8range = getLinSpace(-10., 10., nsam)
9f = sin(range)
10f = getPaddedr(getNormed(f, -getMean(f), 1._TKG / getVar(f)), nsam - 1, ZERO)
11f
12+1.14616740, +0.158331722, -0.868269205, -1.68228757, -2.08442330, -1.97621930, -1.38416803, -0.453224123, +0.588684797, +1.48646319, +2.02030373, +2.05950308, +1.59446442, +0.739045501, -0.297317713, -1.26088738, -1.91574752, -2.10156608, -1.77284777, -1.01007462, +0.551316610E-7, +1.01007473, +1.77284777, +2.10156608, +1.91574752, +1.26088738, +0.297317863, -0.739045382, -1.59446442, -2.05950308, -2.02030373, -1.48646319, -0.588684678, +0.453224242, +1.38416803, +1.97621930, +2.08442330, +1.68228757, +0.868269324, -0.158331588, -1.14616752, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000
13g = cos(range)
14g = getPaddedr(getNormed(g, -getMean(g), 1._TKG / getVar(g)), nsam - 1, ZERO)
15g
16-1.47399807, -1.77797341, -1.61254323, -1.01821089, -0.140489474, +0.805724084, +1.58876371, +2.01691413, +1.98534882, +1.50179660, +0.684647501, -0.266031623, -1.11748147, -1.66123748, -1.76416922, -1.40107536, -0.660853744, +0.275263220, +1.17808151, +1.82656002, +2.06192827, +1.82656002, +1.17808151, +0.275263220, -0.660853744, -1.40107536, -1.76416922, -1.66123748, -1.11748147, -0.266031623, +0.684647501, +1.50179660, +1.98534882, +2.01691413, +1.58876371, +0.805724084, -0.140489474, -1.01821089, -1.61254323, -1.77797341, -1.47399807, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000, +0.00000000
17fcopy = f; gcopy = g
18call setResized(ccf, size(f, 1, IK))
19factor = getFactorFFT(f, coef, allocatable)
20call setCCF(factor, coef, fcopy, gcopy, ccf, inf)
21ccf = merge(fcopy, gcopy, inf) / size(ccf)
22size(ccf)
23+81
24ccf
25+0.616307034E-6, +38.6811829, +66.2860413, +76.7109756, +68.3154831, +44.1006393, +10.7427692, -23.2242260, -49.5879860, -62.4429970, -59.5019302, -42.4451027, -16.2740231, +12.1153097, +35.7402992, +49.2492027, +50.1254883, +39.1103516, +19.7872581, -2.51251292, -22.1620979, -34.6576233, -37.6457672, -31.3270149, -18.1784420, -2.11944509, +12.6191750, +22.6043739, +25.9983597, +22.8599777, +14.9124441, +4.88764429, -4.33513117, -10.5382242, -12.6986217, -11.1170864, -7.14137650, -2.60108185, +0.849937916, +2.27123713, +1.68945014, -1.68944895, -2.27123570, -0.849931896, +2.60108018, +7.14137840, +11.1170835, +12.6986189, +10.5382242, +4.33513403, -4.88764715, -14.9124441, -22.8599834, -25.9983597, -22.6043739, -12.6191711, +2.11945033, +18.1784420, +31.3270187, +37.6457672, +34.6576233, +22.1620941, +2.51250696, -19.7872601, -39.1103516, -50.1254845, -49.2492027, -35.7403030, -12.1153049, +16.2740231, +42.4451027, +59.5019302, +62.4429970, +49.5879822, +23.2242184, -10.7427759, -44.1006470, -68.3154831, -76.7109604, -66.2860413, -38.6811752
26lag = getRange(-nsam + 1_IK, nsam - 1_IK)
27if (0 /= getErrTableWrite(SK_'setCCF.crd.sin.cos.RK.txt', reshape([range, f(1:nsam), g(1:nsam)], [nsam, 3_IK]), header = SK_'crd,f,g')) error stop 'ccf outputting failed.'
28if (0 /= getErrTableWrite(SK_'setCCF.ccf.sin.cos.RK.txt', reshape([real(lag, TKG), ccf], [size(lag), 2]), header = SK_'lag,ccf')) error stop 'ccf outputting failed.'
29
30

Postprocessing of the example output
1#!/usr/bin/env python
2
3import matplotlib.pyplot as plt
4import pandas as pd
5import numpy as np
6import glob
7import sys
8
9linewidth = 2
10fontsize = 17
11
12for kind in ["sin.cos.RK"]:
13
14 file = glob.glob("*crd*"+kind+".txt")[0]
15 df = pd.read_csv(file, delimiter = ",")
16
17 #print(df.values)
18 fig = plt.figure(figsize = (8, 6))
19 ax = plt.subplot(1,1,1)
20 ax.plot ( df.values[:, 0]
21 , df.values[:,1:]
22 , zorder = 1000
23 )
24 plt.minorticks_on()
25 ax.set_xlabel("x", fontsize = 17)
26 ax.set_ylabel("f(x), g(x)", fontsize = 17)
27 ax.tick_params(axis = "x", which = "minor")
28 ax.tick_params(axis = "y", which = "minor")
29 plt.grid(visible = True, which = "both", axis = "both", color = "0.85", linestyle = "-")
30 ax.legend([file.split(".")[-4] + "(x), ", file.split(".")[-3] + "(x)"], fontsize = fontsize)
31 plt.tight_layout()
32 plt.savefig(file.replace(".txt",".png"))
33
34 file = glob.glob("*ccf*"+kind+".txt")[0]
35 df = pd.read_csv(file, delimiter = ",")
36 fig = plt.figure(figsize = (8, 6))
37 ax = plt.subplot(1,1,1)
38 ax.plot ( df.values[:, 0]
39 , df.values[:,1]
40 , zorder = 1000
41 )
42 plt.minorticks_on()
43 ax.set_xlabel("Lag", fontsize = 17)
44 ax.set_ylabel("ccf(f, g)", fontsize = 17)
45 ax.tick_params(axis = "x", which = "minor")
46 ax.tick_params(axis = "y", which = "minor")
47 plt.grid(visible = True, which = "both", axis = "both", color = "0.85", linestyle = "-")
48 plt.tight_layout()
49 plt.savefig(file.replace(".txt",".png"))

Visualization of the example output
Test:
test_pm_sampleCCF
Internal naming convention:
The following illustrates the internal naming convention used for the procedures within this generic interface.
setCCF_FP_FG_CK5()
||| || || |||
||| || || The type and kind parameters of the input sequences.
||| || The input sequences `f` and `g`.
||| The method used: FP => fftpack.
CCF: Cross-Correlation Function.


Final Remarks


If you believe this algorithm or its documentation can be improved, we appreciate your contribution and help to edit this page's documentation and source file on GitHub.
For details on the naming abbreviations, see this page.
For details on the naming conventions, see this page.
This software is distributed under the MIT license with additional terms outlined below.

  1. If you use any parts or concepts from this library to any extent, please acknowledge the usage by citing the relevant publications of the ParaMonte library.
  2. If you regenerate any parts/ideas from this library in a programming environment other than those currently supported by this ParaMonte library (i.e., other than C, C++, Fortran, MATLAB, Python, R), please also ask the end users to cite this original ParaMonte library.

This software is available to the public under a highly permissive license.
Help us justify its continued development and maintenance by acknowledging its benefit to society, distributing it, and contributing to it.

Author:
Fatemeh Bagheri, Monday 02:15 AM, September 27, 2021, Dallas, TX
Amir Shahmoradi, Wednesday 4:13 AM, August 13, 2016, Institute for Computational Engineering and Sciences (ICES), The University of Texas at Austin

Definition at line 1051 of file pm_sampleCCF.F90.


The documentation for this interface was generated from the following file: