Full Code of chlubba/catch22 for AI

main d39af485c9fe cached
142 files
385.6 KB
135.8k tokens
143 symbols
1 requests
Download .txt
Showing preview only (420K chars total). Download the full file or copy to clipboard to get everything.
Repository: chlubba/catch22
Branch: main
Commit: d39af485c9fe
Files: 142
Total size: 385.6 KB

Directory structure:
gitextract_0hyl0dq4/

├── .github/
│   └── workflows/
│       └── github-repo-stats.yml
├── .gitignore
├── C/
│   ├── .gitignore
│   ├── CO_AutoCorr.c
│   ├── CO_AutoCorr.h
│   ├── DN_HistogramMode_10.c
│   ├── DN_HistogramMode_10.h
│   ├── DN_HistogramMode_5.c
│   ├── DN_HistogramMode_5.h
│   ├── DN_Mean.c
│   ├── DN_Mean.h
│   ├── DN_OutlierInclude.c
│   ├── DN_OutlierInclude.h
│   ├── DN_Spread_Std.c
│   ├── DN_Spread_Std.h
│   ├── FC_LocalSimple.c
│   ├── FC_LocalSimple.h
│   ├── IN_AutoMutualInfoStats.c
│   ├── IN_AutoMutualInfoStats.h
│   ├── MD_hrv.c
│   ├── MD_hrv.h
│   ├── PD_PeriodicityWang.c
│   ├── PD_PeriodicityWang.h
│   ├── SB_BinaryStats.c
│   ├── SB_BinaryStats.h
│   ├── SB_CoarseGrain.c
│   ├── SB_CoarseGrain.h
│   ├── SB_MotifThree.c
│   ├── SB_MotifThree.h
│   ├── SB_TransitionMatrix.c
│   ├── SB_TransitionMatrix.h
│   ├── SC_FluctAnal.c
│   ├── SC_FluctAnal.h
│   ├── SP_Summaries.c
│   ├── SP_Summaries.h
│   ├── butterworth.c
│   ├── butterworth.h
│   ├── fft.c
│   ├── fft.h
│   ├── helper_functions.c
│   ├── helper_functions.h
│   ├── histcounts.c
│   ├── histcounts.h
│   ├── main.c
│   ├── main.h
│   ├── runAllTS.sh
│   ├── splinefit.c
│   ├── splinefit.h
│   ├── stats.c
│   └── stats.h
├── LICENSE
├── Matlab/
│   ├── BasisOperations/
│   │   ├── BF_Binarize.m
│   │   ├── CO_AutoCorr.m
│   │   ├── CO_FirstZero.m
│   │   ├── CO_trev.m
│   │   ├── DN_HistogramMode.m
│   │   ├── DN_OutlierInclude_001_mdrmd.m
│   │   ├── NK_hist2.m
│   │   ├── SB_CoarseGrain_quantile.m
│   │   ├── SB_TransitionMatrix.m
│   │   ├── SC_FluctAnal_q2_taustep50_k1_logi_prop_r1.m
│   │   ├── SP_Summaries_welch_rect.m
│   │   ├── buffer_.m
│   │   ├── decimate_.m
│   │   ├── downsample_.m
│   │   ├── filtfilt_.m
│   │   ├── histcounts_.m
│   │   ├── myButter.m
│   │   ├── poly_.m
│   │   ├── splinefit.m
│   │   ├── test_zp2ss.m
│   │   ├── testfilt.m
│   │   └── welchy.m
│   ├── CO_Embed2_Dist_tau_d_expfit_meandiff.m
│   ├── CO_FirstMin_ac.m
│   ├── CO_HistogramAMI_even_2_5.m
│   ├── CO_f1ecac.m
│   ├── CO_trev_1_num.m
│   ├── DN_HistogramMode_10.m
│   ├── DN_HistogramMode_5.m
│   ├── DN_Mean.m
│   ├── DN_OutlierInclude_n_001_mdrmd.m
│   ├── DN_OutlierInclude_p_001_mdrmd.m
│   ├── DN_Spread_Std.m
│   ├── FC_LocalSimple_mean1_tauresrat.m
│   ├── FC_LocalSimple_mean3_stderr.m
│   ├── IN_AutoMutualInfoStats_40_gaussian_fmmi.m
│   ├── MD_hrv_classic_pnn40.m
│   ├── PD_PeriodicityWang_th0_01.m
│   ├── SB_BinaryStats_diff_longstretch0.m
│   ├── SB_BinaryStats_mean_longstretch1.m
│   ├── SB_MotifThree_quantile_hh.m
│   ├── SB_TransitionMatrix_3ac_sumdiagcov.m
│   ├── SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1.m
│   ├── SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1.m
│   ├── SP_Summaries_welch_rect_area_5_1.m
│   └── SP_Summaries_welch_rect_centroid.m
├── README.md
├── catch22.m
├── featureList.txt
├── testData/
│   ├── runtests.sh
│   ├── test.txt
│   ├── test2.txt
│   ├── test2_output.txt
│   ├── testInf.txt
│   ├── testInfMinus.txt
│   ├── testNaN.txt
│   ├── testShort.txt
│   ├── testShort_output.txt
│   ├── testSinusoid.txt
│   ├── testSinusoid_output.txt
│   └── test_output.txt
└── wrap_Matlab/
    ├── GetAllFeatureNames.m
    ├── M_wrapper.c
    ├── M_wrapper.h
    ├── catch22_CO_Embed2_Dist_tau_d_expfit_meandiff.c
    ├── catch22_CO_FirstMin_ac.c
    ├── catch22_CO_HistogramAMI_even_2_5.c
    ├── catch22_CO_f1ecac.c
    ├── catch22_CO_trev_1_num.c
    ├── catch22_DN_HistogramMode_10.c
    ├── catch22_DN_HistogramMode_5.c
    ├── catch22_DN_Mean.c
    ├── catch22_DN_OutlierInclude_n_001_mdrmd.c
    ├── catch22_DN_OutlierInclude_p_001_mdrmd.c
    ├── catch22_DN_Spread_Std.c
    ├── catch22_FC_LocalSimple_mean1_tauresrat.c
    ├── catch22_FC_LocalSimple_mean3_stderr.c
    ├── catch22_IN_AutoMutualInfoStats_40_gaussian_fmmi.c
    ├── catch22_MD_hrv_classic_pnn40.c
    ├── catch22_PD_PeriodicityWang_th0_01.c
    ├── catch22_SB_BinaryStats_diff_longstretch0.c
    ├── catch22_SB_BinaryStats_mean_longstretch1.c
    ├── catch22_SB_MotifThree_quantile_hh.c
    ├── catch22_SB_TransitionMatrix_3ac_sumdiagcov.c
    ├── catch22_SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1.c
    ├── catch22_SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1.c
    ├── catch22_SP_Summaries_welch_rect_area_5_1.c
    ├── catch22_SP_Summaries_welch_rect_centroid.c
    ├── catch22_all.m
    ├── mexAll.m
    └── testing.m

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/workflows/github-repo-stats.yml
================================================
name: github-repo-stats

on:
  schedule:
    # Run this once per day, towards the end of the day for keeping the most
    # recent data point most meaningful (hours are interpreted in UTC).
    - cron: "0 23 * * *"
  workflow_dispatch: # Allow for running this manually.

jobs:
  j1:
    name: github-repo-stats
    runs-on: ubuntu-latest
    steps:
      - name: run-ghrs
        # Use latest release.
        uses: jgehrcke/github-repo-stats@RELEASE
        with:
          ghtoken: ${{ secrets.ghrs_github_api_token }}




================================================
FILE: .gitignore
================================================
*.prj
*.mexmaci64
*.mexmaca64
*.mat
*.m~
.DS_Store
*.vscode
*.code-workspace
*/run_features


================================================
FILE: C/.gitignore
================================================
codegen
*.prj
*.mexmaci64
*.o
C_polished
generated
header
timeSeries*
featureOutputs

================================================
FILE: C/CO_AutoCorr.c
================================================
#if __cplusplus
#   include <complex>
typedef std::complex< double > cplx;
#else
#   include <complex.h>
#if defined(__GNUC__) || defined(__GNUG__)
typedef double complex cplx;
#elif defined(_MSC_VER)
typedef _Dcomplex cplx;
#endif
#endif

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "stats.h"
#include "fft.h"
#include "histcounts.h"

#include "helper_functions.h"

#ifndef CMPLX
#define CMPLX(x, y) ((cplx)((double)(x) + _Imaginary_I * (double)(y)))
#endif
#define pow2(x) (1 << x)

int nextpow2(int n)
{
    n--;
    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    n++;
    return n;
}

/*
static void apply_conj(cplx a[], int size, int normalize)
{   
    switch(normalize) {
        case(1):
            for (int i = 0; i < size; i++) {
                a[i] = conj(a[i]) / size;
            }
            break;
        default:
            for (int i = 0; i < size; i++) {
                a[i] = conj(a[i]);
            }
            break;
    }
}
 */

void dot_multiply(cplx a[], cplx b[], int size)
{
    for (int i = 0; i < size; i++) {
        a[i] = _Cmulcc(a[i], conj(b[i]));
    }
}

double * CO_AutoCorr(const double y[], const int size, const int tau[], const int tau_size)
{
    double m, nFFT;
    m = mean(y, size);
    nFFT = nextpow2(size) << 1;

    cplx * F = malloc(nFFT * sizeof *F);
    cplx * tw = malloc(nFFT * sizeof *tw);
    for (int i = 0; i < size; i++) {
        
        #if defined(__GNUC__) || defined(__GNUG__)
                F[i] = CMPLX(y[i] - m, 0.0);
        #elif defined(_MSC_VER)
                cplx tmp = { y[i] - m, 0.0 };
                F[i] = tmp;
        #endif
        
    }
    for (int i = size; i < nFFT; i++) {
        #if defined(__GNUC__) || defined(__GNUG__)
                F[i] = CMPLX(0.0, 0.0);
        #elif defined(_MSC_VER)
                cplx tmp = { 0.0, 0.0 };
                F[i] = tmp; // CMPLX(0.0, 0.0);
        #endif
        
    }
    // size = nFFT;

    twiddles(tw, nFFT);
    fft(F, nFFT, tw);
    dot_multiply(F, F, nFFT);
    fft(F, nFFT, tw);
    cplx divisor = F[0];
    for (int i = 0; i < nFFT; i++) {
        //F[i] = F[i] / divisor;
        F[i] = _Cdivcc(F[i], divisor);
    }
    
    double * out = malloc(tau_size * sizeof(out));
    for (int i = 0; i < tau_size; i++) {
        out[i] = creal(F[tau[i]]);
    }
    free(F);
    free(tw);
    return out;
}

double * co_autocorrs(const double y[], const int size)
{
    double m, nFFT;
    m = mean(y, size);
    nFFT = nextpow2(size) << 1;
    
    cplx * F = malloc(nFFT * 2 * sizeof *F);
    cplx * tw = malloc(nFFT * 2 * sizeof *tw);
    for (int i = 0; i < size; i++) {
        
        #if defined(__GNUC__) || defined(__GNUG__)
                F[i] = CMPLX(y[i] - m, 0.0);
        #elif defined(_MSC_VER)
                cplx tmp = { y[i] - m, 0.0 };
                F[i] = tmp;
        #endif
    }
    for (int i = size; i < nFFT; i++) {
        
        #if defined(__GNUC__) || defined(__GNUG__)
            F[i] = CMPLX(0.0, 0.0);
        #elif defined(_MSC_VER)
            cplx tmp = { 0.0, 0.0 };
            F[i] = tmp;
        #endif
    }
    //size = nFFT;
    
    twiddles(tw, nFFT);
    fft(F, nFFT, tw);
    dot_multiply(F, F, nFFT);
    fft(F, nFFT, tw);
    cplx divisor = F[0];
    for (int i = 0; i < nFFT; i++) {
        F[i] = _Cdivcc(F[i], divisor); // F[i] / divisor;
    }
    
    double * out = malloc(nFFT * 2 * sizeof(out));
    for (int i = 0; i < nFFT; i++) {
        out[i] = creal(F[i]);
    }
    free(F);
    free(tw);
    return out;
}

int co_firstzero(const double y[], const int size, const int maxtau)
{
    
    //double * autocorrs = malloc(size * sizeof * autocorrs);
    //autocorrs = co_autocorrs(y, size);
    
    double * autocorrs = co_autocorrs(y, size);
    
    int zerocrossind = 0;
    while(autocorrs[zerocrossind] > 0 && zerocrossind < maxtau)
    {
        zerocrossind += 1;
    }
    
    free(autocorrs);
    return zerocrossind;
    
}

double CO_f1ecac(const double y[], const int size)
{
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return 0;
        }
    }
    
    // compute autocorrelations
    double * autocorrs = co_autocorrs(y, size);

    // threshold to cross
    double thresh = 1.0/exp(1);
    
    double out = (double)size;
    for(int i = 0; i < size-2; i++){
        // printf("i=%d autocorrs_i=%1.3f\n", i, autocorrs[i]);
        if ( autocorrs[i+1] < thresh ){
            double m = autocorrs[i+1] - autocorrs[i];
            double dy = thresh - autocorrs[i];
            double dx = dy/m;
            out = ((double)i) + dx;
            // printf("thresh=%1.3f AC(i)=%1.3f AC(i-1)=%1.3f m=%1.3f dy=%1.3f dx=%1.3f out=%1.3f\n", thresh, autocorrs[i], autocorrs[i-1], m, dy, dx, out);
            free(autocorrs);
            return out;
        }
    }
    
    free(autocorrs);
    
    return out;
    
}

double CO_Embed2_Basic_tau_incircle(const double y[], const int size, const double radius, const int tau)
{
    int tauIntern = 0;
    
    if(tau < 0)
    {
        tauIntern = co_firstzero(y, size, size);
    }
    else{
        tauIntern = tau;
    }
    
    double insidecount = 0;
    for(int i = 0; i < size-tauIntern; i++)
    {
        if(y[i]*y[i] + y[i+tauIntern]*y[i+tauIntern] < radius)
        {
            insidecount += 1;
        }
    }
    
    return insidecount/(size-tauIntern);
}

double CO_Embed2_Dist_tau_d_expfit_meandiff(const double y[], const int size)
{
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    int tau = co_firstzero(y, size, size);
    
    //printf("co_firstzero ran\n");
    
    if (tau > (double)size/10){
        tau = floor((double)size/10);
    }
    //printf("tau = %i\n", tau);
    
    double * d = malloc((size-tau) * sizeof(double));
    for(int i = 0; i < size-tau-1; i++)
    {
        
        d[i] = sqrt((y[i+1]-y[i])*(y[i+1]-y[i]) + (y[i+tau]-y[i+tau+1])*(y[i+tau]-y[i+tau+1]));
        
        //printf("d[%i]: %1.3f\n", i, d[i]);
        if (isnan(d[i])){
            free(d);
            return NAN;
        }
        
        /*
        if(i<100)
            printf("%i, y[i]=%1.3f, y[i+1]=%1.3f, y[i+tau]=%1.3f, y[i+tau+1]=%1.3f, d[i]: %1.3f\n", i, y[i], y[i+1], y[i+tau], y[i+tau+1], d[i]);
         */
    }
    
    //printf("embedding finished\n");
    
    // mean for exponential fit
    double l = mean(d, size-tau-1);
    
    // count histogram bin contents
    /*
     int * histCounts;
    double * binEdges;
    int nBins = histcounts(d, size-tau-1, -1, &histCounts, &binEdges);
     */
    
    int nBins = num_bins_auto(d, size-tau-1);
    if (nBins == 0){
        return 0;
    }
    int * histCounts = malloc(nBins * sizeof(double));
    double * binEdges = malloc((nBins + 1) * sizeof(double));
    histcounts_preallocated(d, size-tau-1, nBins, histCounts, binEdges);
    
    //printf("histcount ran\n");
    
    // normalise to probability
    double * histCountsNorm = malloc(nBins * sizeof(double));
    for(int i = 0; i < nBins; i++){
        //printf("histCounts %i: %i\n", i, histCounts[i]);
        histCountsNorm[i] = (double)histCounts[i]/(double)(size-tau-1);
        //printf("histCounts norm %i: %1.3f\n", i, histCountsNorm[i]);
    }
    
    /*
    for(int i = 0; i < nBins; i++){
        printf("histCounts[%i] = %i\n", i, histCounts[i]);
    }
    for(int i = 0; i < nBins; i++){
        printf("histCountsNorm[%i] = %1.3f\n", i, histCountsNorm[i]);
    }
    for(int i = 0; i < nBins+1; i++){
        printf("binEdges[%i] = %1.3f\n", i, binEdges[i]);
    }
    */
     
    
    //printf("histcounts normed\n");
    
    double * d_expfit_diff = malloc(nBins * sizeof(double));
    for(int i = 0; i < nBins; i++){
        double expf = exp(-(binEdges[i] + binEdges[i+1])*0.5/l)/l;
        if (expf < 0){
            expf = 0;
        }
        d_expfit_diff[i] = fabs(histCountsNorm[i]-expf);
        //printf("d_expfit_diff %i: %1.3f\n", i, d_expfit_diff[i]);
    }
    
    double out = mean(d_expfit_diff, nBins);
    
    //printf("out = %1.6f\n", out);
    //printf("reached free statements\n");
    
    // arrays created dynamically in function histcounts
    free(d);
    free(d_expfit_diff);
    free(binEdges);
    free(histCountsNorm);
    free(histCounts);
    
    return out;
    
}

int CO_FirstMin_ac(const double y[], const int size)
{
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return 0;
        }
    }
    
    double * autocorrs = co_autocorrs(y, size);
    
    int minInd = size;
    for(int i = 1; i < size-1; i++)
    {
        if(autocorrs[i] < autocorrs[i-1] && autocorrs[i] < autocorrs[i+1])
        {
            minInd = i;
            break;
        }
    }
    
    free(autocorrs);
    
    return minInd;
    
}

double CO_trev_1_num(const double y[], const int size)
{
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    int tau = 1;
    
    double * diffTemp = malloc((size-1) * sizeof * diffTemp);
    
    for(int i = 0; i < size-tau; i++)
    {
        diffTemp[i] = pow(y[i+1] - y[i],3);
    }
    
    double out;
    
    out = mean(diffTemp, size-tau);
    
    free(diffTemp);
    
    return out;
}

#define tau 2
#define numBins 5

double CO_HistogramAMI_even_2_5(const double y[], const int size)
{
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    //const int tau = 2;
    //const int numBins = 5;
    
    double * y1 = malloc((size-tau) * sizeof(double));
    double * y2 = malloc((size-tau) * sizeof(double));
    
    for(int i = 0; i < size-tau; i++){
        y1[i] = y[i];
        y2[i] = y[i+tau];
    }
    
    // set bin edges
    const double maxValue = max_(y, size);
    const double minValue = min_(y, size);
    
    double binStep = (maxValue - minValue + 0.2)/5;
    //double binEdges[numBins+1] = {0};
	double binEdges[5+1] = {0};
    for(int i = 0; i < numBins+1; i++){
        binEdges[i] = minValue + binStep*i - 0.1;
        // printf("binEdges[%i] = %1.3f\n", i, binEdges[i]);
    }
    
    
    // count histogram bin contents
    int * bins1;
    bins1 = histbinassign(y1, size-tau, binEdges, numBins+1);
    
    int * bins2;
    bins2 = histbinassign(y2, size-tau, binEdges, numBins+1);
    
    /*
    // debug
    for(int i = 0; i < size-tau; i++){
        printf("bins1[%i] = %i, bins2[%i] = %i\n", i, bins1[i], i, bins2[i]);
    }
    */
    
    // joint
    double * bins12 = malloc((size-tau) * sizeof(double));
    //double binEdges12[(numBins + 1) * (numBins + 1)] = {0};
	double binEdges12[(5 + 1) * (5 + 1)] = {0};    

    for(int i = 0; i < size-tau; i++){
        bins12[i] = (bins1[i]-1)*(numBins+1) + bins2[i];
        // printf("bins12[%i] = %1.3f\n", i, bins12[i]);
    }
    
    for(int i = 0; i < (numBins+1)*(numBins+1); i++){
        binEdges12[i] = i+1;
        // printf("binEdges12[%i] = %1.3f\n", i, binEdges12[i]);
    }
    
    // fancy solution for joint histogram here
    int * jointHistLinear;
    jointHistLinear = histcount_edges(bins12, size-tau, binEdges12, (numBins + 1) * (numBins + 1));
    
    /*
    // debug
    for(int i = 0; i < (numBins+1)*(numBins+1); i++){
        printf("jointHistLinear[%i] = %i\n", i, jointHistLinear[i]);
    }
    */
    
    // transfer to 2D histogram (no last bin, as in original implementation)
    double pij[numBins][numBins];
    int sumBins = 0;
    for(int i = 0; i < numBins; i++){
        for(int j = 0; j < numBins; j++){
            pij[j][i] = jointHistLinear[i*(numBins+1)+j];
            
            // printf("pij[%i][%i]=%1.3f\n", i, j, pij[i][j]);
            
            sumBins += pij[j][i];
        }
    }
    
    // normalise
    for(int i = 0; i < numBins; i++){
        for(int j = 0; j < numBins; j++){
            pij[j][i] /= sumBins;
        }
    }

    // marginals
    //double pi[numBins] = {0};
	double pi[5] = {0};
    //double pj[numBins] = {0};
	double pj[5] = {0};
    for(int i = 0; i < numBins; i++){
        for(int j = 0; j < numBins; j++){
            pi[i] += pij[i][j];
            pj[j] += pij[i][j];
            // printf("pij[%i][%i]=%1.3f, pi[%i]=%1.3f, pj[%i]=%1.3f\n", i, j, pij[i][j], i, pi[i], j, pj[j]);
        }
    }
    
    /*
    // debug
    for(int i = 0; i < numBins; i++){
        printf("pi[%i]=%1.3f, pj[%i]=%1.3f\n", i, pi[i], i, pj[i]);
    }
    */
    
    // mutual information
    double ami = 0;
    for(int i = 0; i < numBins; i++){
        for(int j = 0; j < numBins; j++){
            if(pij[i][j] > 0){
                //printf("pij[%i][%i]=%1.3f, pi[%i]=%1.3f, pj[%i]=%1.3f, logarg=, %1.3f, log(...)=%1.3f\n",
                //       i, j, pij[i][j], i, pi[i], j, pj[j], pij[i][j]/(pi[i]*pj[j]), log(pij[i][j]/(pi[i]*pj[j])));
                ami += pij[i][j] * log(pij[i][j]/(pj[j]*pi[i]));
            }
        }
    }
    
    free(bins1);
    free(bins2);
    free(jointHistLinear);
    
    free(y1);
    free(y2);
    free(bins12);
    
    return ami;
}















================================================
FILE: C/CO_AutoCorr.h
================================================
#ifndef CO_AUTOCORR_H
#define CO_AUTOCORR_H

#if __cplusplus
#   include <complex>
typedef std::complex< double > cplx;
#else
#   include <complex.h>
#if defined(__GNUC__) || defined(__GNUG__)
typedef double complex cplx;
#elif defined(_MSC_VER)
typedef _Dcomplex cplx;
#endif
#endif

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "stats.h"
#include "fft.h"

extern int nextpow2(int n);
extern void dot_multiply(cplx a[], cplx b[], int size);
extern double * CO_AutoCorr(const double y[], const int size, const int tau[], const int tau_size);
extern double * co_autocorrs(const double y[], const int size);
extern int co_firstzero(const double y[], const int size, const int maxtau);
extern double CO_Embed2_Basic_tau_incircle(const double y[], const int size, const double radius, const int tau);
extern double CO_Embed2_Dist_tau_d_expfit_meandiff(const double y[], const int size);
extern int CO_FirstMin_ac(const double y[], const int size);
extern double CO_trev_1_num(const double y[], const int size);
extern double CO_f1ecac(const double y[], const int size);
extern double CO_HistogramAMI_even_2_5(const double y[], const int size);

#endif


================================================
FILE: C/DN_HistogramMode_10.c
================================================
#include <math.h>
#include <string.h>
#include <time.h>
#include <float.h>

#include "stats.h"
#include "histcounts.h"

double DN_HistogramMode_10(const double y[], const int size)
{
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    const int nBins = 10;
    
    int * histCounts;
    double * binEdges;
    
    histcounts(y, size, nBins, &histCounts, &binEdges);
    
    double maxCount = 0;
    int numMaxs = 1;
    double out = 0;;
    for(int i = 0; i < nBins; i++)
    {
        // printf("binInd=%i, binCount=%i, binEdge=%1.3f \n", i, histCounts[i], binEdges[i]);
        
        if (histCounts[i] > maxCount)
        {
            maxCount = histCounts[i];
            numMaxs = 1;
            out = (binEdges[i] + binEdges[i+1])*0.5;
        }
        else if (histCounts[i] == maxCount){
            
            numMaxs += 1;
            out += (binEdges[i] + binEdges[i+1])*0.5;
        }
    }
    out = out/numMaxs;
    
    // arrays created dynamically in function histcounts
    free(histCounts);
    free(binEdges);
    
    return out;
}

/*
 double DN_HistogramMode_10(double y[], int size)
 {
 
 double min = DBL_MAX, max=-DBL_MAX;
 for(int i = 0; i < size; i++)
 {
 if (y[i] < min)
 {
 min = y[i];
 }
 if (y[i] > max)
 {
 max = y[i];
 }
 }
 
 double binStep = (max - min)/10;
 
 // fprintf(stdout, "min=%f, max=%f, binStep=%f \n", min, max, binStep);
 
 int histCounts[10] = {0};
 for(int i = 0; i < size; i++)
 {
 int binsLeft = 10;
 int lowerInd = 0, upperInd = 10;
 while(binsLeft > 1)
 {
 int limitInd = (upperInd - lowerInd)/2 + lowerInd;
 double limit = limitInd * binStep + min;
 
 if (y[i] < limit)
 {
 upperInd = limitInd;
 }
 else
 {
 lowerInd = limitInd;
 }
 binsLeft = upperInd - lowerInd;
 }
 histCounts[lowerInd] += 1;
 }
 
 double maxCount = 0;
 int maxCountInd = 0;
 for(int i = 0; i < 10; i++)
 {
 // fprintf(stdout, "binInd=%i, binCount=%i \n", i, histCounts[i]);
 
 if (histCounts[i] > maxCount)
 {
 maxCountInd = i;
 maxCount = histCounts[i];
 }
 }
 return binStep*(maxCountInd+0.5) + min;
 }
 */


================================================
FILE: C/DN_HistogramMode_10.h
================================================
#ifndef DN_HISTOGRAMMODE_10
#define DN_HISTOGRAMMODE_10
#include <math.h>
#include <string.h>
#include "stats.h"

extern double DN_HistogramMode_10(const double y[], const int size);

#endif


================================================
FILE: C/DN_HistogramMode_5.c
================================================
#include <math.h>
#include <string.h>
#include <time.h>
#include <float.h>
#include "stats.h"
#include "histcounts.h"

double DN_HistogramMode_5(const double y[], const int size)
{
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    const int nBins = 5;
    
    int * histCounts;
    double * binEdges;
    
    histcounts(y, size, nBins, &histCounts, &binEdges);
    
    /*
    for(int i = 0; i < nBins; i++){
        printf("histCounts[%i] = %i\n", i, histCounts[i]);
    }
    for(int i = 0; i < nBins+1; i++){
        printf("binEdges[%i] = %1.3f\n", i, binEdges[i]);
    }
     */
    
    double maxCount = 0;
    int numMaxs = 1;
    double out = 0;;
    for(int i = 0; i < nBins; i++)
    {
        // printf("binInd=%i, binCount=%i, binEdge=%1.3f \n", i, histCounts[i], binEdges[i]);
        
        if (histCounts[i] > maxCount)
        {
            maxCount = histCounts[i];
            numMaxs = 1;
            out = (binEdges[i] + binEdges[i+1])*0.5;
        }
        else if (histCounts[i] == maxCount){
            
            numMaxs += 1;
            out += (binEdges[i] + binEdges[i+1])*0.5;
        }
    }
    out = out/numMaxs;
    
    // arrays created dynamically in function histcounts
    free(histCounts);
    free(binEdges);
    
    return out;
}

/*
double DN_HistogramMode_5(double y[], int size)
{
    
    double min = DBL_MAX, max=-DBL_MAX;
    for(int i = 0; i < size; i++)
    {
        if (y[i] < min)
        {
            min = y[i];
        }
        if (y[i] > max)
        {
            max = y[i];
        }
    }
    
    double binStep = (max - min)/5;
    
    // fprintf(stdout, "min=%f, max=%f, binStep=%f \n", min, max, binStep);
    
    int histCounts[5] = {0};
    for(int i = 0; i < size; i++)
    {
        int binsLeft = 5;
        int lowerInd = 0, upperInd = 10;
        while(binsLeft > 1)
        {
            int limitInd = (upperInd - lowerInd)/2 + lowerInd;
            double limit = limitInd * binStep + min;
            
            if (y[i] < limit)
            {
                upperInd = limitInd;
            }
            else
            {
                lowerInd = limitInd;
            }
            binsLeft = upperInd - lowerInd;
        }
        histCounts[lowerInd] += 1;
    }
    
    double maxCount = 0;
    int maxCountInd = 0;
    for(int i = 0; i < 5; i++)
    {
        // fprintf(stdout, "binInd=%i, binCount=%i \n", i, histCounts[i]);
        
        if (histCounts[i] > maxCount)
        {
            maxCountInd = i;
            maxCount = histCounts[i];
        }
    }
    return binStep*(maxCountInd+0.5) + min;
}
 
 */


================================================
FILE: C/DN_HistogramMode_5.h
================================================
#ifndef DN_HISTOGRAMMODE_5
#define DN_HISTOGRAMMODE_5
#include <math.h>
#include <string.h>
#include "stats.h"

extern double DN_HistogramMode_5(const double y[], const int size);

#endif


================================================
FILE: C/DN_Mean.c
================================================
#include <stdio.h>

double DN_Mean(const double a[], const int size)
{
    double m = 0.0;
    for (int i = 0; i < size; i++) {
        m += a[i];
    }
    m /= size;
    return m;
}


================================================
FILE: C/DN_Mean.h
================================================
//
//  Created by Trent Henderson 27 September 2021
//

#ifndef DN_MEAN
#define DN_MEAN

#include <stdio.h>

extern double DN_Mean(const double a[], const int size);

#endif /* DN_MEAN */

================================================
FILE: C/DN_OutlierInclude.c
================================================
#include <math.h>
#include <string.h>
#include <time.h>
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include "stats.h"

double DN_OutlierInclude_np_001_mdrmd(const double y[], const int size, const int sign)
{
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    double inc = 0.01;
    int tot = 0;
    double * yWork = malloc(size * sizeof(double));
    
    // apply sign and check constant time series
    int constantFlag = 1;
    for(int i = 0; i < size; i++)
    {
        if(y[i] != y[0])
        {
            constantFlag = 0;
        }
        
        // apply sign, save in new variable
        yWork[i] = sign*y[i];
        
        // count pos/ negs
        if(yWork[i] >= 0){
            tot += 1;
        }
        
    }
    if(constantFlag){
        free(yWork);
        return 0; // if constant, return 0
    }
    
    // find maximum (or minimum, depending on sign)
    double maxVal = max_(yWork, size);
    
    // maximum value too small? return 0
    if(maxVal < inc){
        free(yWork);
        return 0;
    }
    
    int nThresh = maxVal/inc + 1;
    
    // save the indices where y > threshold
    double * r = malloc(size * sizeof * r);
    
    // save the median over indices with absolute value > threshold
    double * msDti1 = malloc(nThresh * sizeof(double));
    double * msDti3 = malloc(nThresh * sizeof(double));
    double * msDti4 = malloc(nThresh * sizeof(double));
    
    for(int j = 0; j < nThresh; j++)
    {
        //printf("j=%i, thr=%1.3f\n", j, j*inc);
        
        int highSize = 0;
        
        for(int i = 0; i < size; i++)
        {
            if(yWork[i] >= j*inc)
            {
                r[highSize] = i+1;
                //printf("r[%i]=%1.f \n", highSize, r[highSize]);
                highSize += 1;
            }
        }
        
        // intervals between high-values
        double * Dt_exc = malloc(highSize * sizeof(double));
        
        for(int i = 0; i < highSize-1; i++)
        {
            //printf("i=%i, r[i+1]=%1.f, r[i]=%1.f \n", i, r[i+1], r[i]);
            Dt_exc[i] = r[i+1] - r[i];
        }

        /*
        // median
        double medianOut;
        medianOut = median(r, highSize);
        */
         
        msDti1[j] = mean(Dt_exc, highSize-1);
        msDti3[j] = (highSize-1)*100.0/tot;
        msDti4[j] = median(r, highSize) / ((double)size/2) - 1;
        
        //printf("msDti1[%i] = %1.3f, msDti13[%i] = %1.3f, msDti4[%i] = %1.3f\n",
        //       j, msDti1[j], j, msDti3[j], j, msDti4[j]);
        
        free(Dt_exc);
        
    }
    
    int trimthr = 2;
    int mj = 0;
    int fbi = nThresh-1;
    for(int i = 0; i < nThresh; i ++)
    {
        if (msDti3[i] > trimthr)
        {
            mj = i;
        }
        if (isnan(msDti1[nThresh-1-i]))
        {
            fbi = nThresh-1-i;
        }
    }
    
    double outputScalar;
    int trimLimit = mj < fbi ? mj : fbi;
    outputScalar = median(msDti4, trimLimit+1);
    
    free(r);
    free(yWork);
    free(msDti1);
    free(msDti3);
    free(msDti4);
    
    return outputScalar;
}

double DN_OutlierInclude_p_001_mdrmd(const double y[], const int size)
{
    return DN_OutlierInclude_np_001_mdrmd(y, size, 1.0);
}

double DN_OutlierInclude_n_001_mdrmd(const double y[], const int size)
{
    return DN_OutlierInclude_np_001_mdrmd(y, size, -1.0);
}

double DN_OutlierInclude_abs_001(const double y[], const int size)
{
    double inc = 0.01;
    double maxAbs = 0;
    double * yAbs = malloc(size * sizeof * yAbs);
    
    for(int i = 0; i < size; i++)
    {
        // yAbs[i] = (y[i] > 0) ? y[i] : -y[i];
        yAbs[i] = (y[i] > 0) ? y[i] : -y[i];
        
        if(yAbs[i] > maxAbs)
        {
            maxAbs = yAbs[i];
        }
    }
    
    int nThresh = maxAbs/inc + 1;
    
    printf("nThresh = %i\n", nThresh);
    
    // save the indices where y > threshold
    double * highInds = malloc(size * sizeof * highInds);
    
    // save the median over indices with absolute value > threshold
    double * msDti3 = malloc(nThresh * sizeof * msDti3);
    double * msDti4 = malloc(nThresh * sizeof * msDti4);

    for(int j = 0; j < nThresh; j++)
    {
        int highSize = 0;
        
        for(int i = 0; i < size; i++)
        {
            if(yAbs[i] >= j*inc)
            {
                // fprintf(stdout, "%i, ", i);
                
                highInds[highSize] = i;
                highSize += 1;
            }
        }
        
        // median
        double medianOut;
        medianOut = median(highInds, highSize);
        
        msDti3[j] = (highSize-1)*100.0/size;
        msDti4[j] = medianOut / (size/2) - 1;
        
    }
    
    int trimthr = 2;
    int mj = 0;
    for(int i = 0; i < nThresh; i ++)
    {
        if (msDti3[i] > trimthr)
        {
            mj = i;
        }
    }
    
    double outputScalar;
    outputScalar = median(msDti4, mj);

    free(highInds);
    free(yAbs);
    free(msDti4);
    
    return outputScalar;
}


================================================
FILE: C/DN_OutlierInclude.h
================================================
#ifndef DN_OUTLIERINCLUDE_ABS_001
#define DN_OUTLIERINCLUDE_ABS_001
#include <math.h>
#include <string.h>
#include <time.h>
#include <float.h>
#include "stats.h"

extern double DN_OutlierInclude_abs_001(const double y[], const int size);
extern double DN_OutlierInclude_np_001_mdrmd(const double y[], const int size, const int sign);
extern double DN_OutlierInclude_p_001_mdrmd(const double y[], const int size);
extern double DN_OutlierInclude_n_001_mdrmd(const double y[], const int size);

#endif


================================================
FILE: C/DN_Spread_Std.c
================================================
#include <stdio.h>
#include "stats.h"

double DN_Spread_Std(const double a[], const int size)
{
    double m = mean(a, size);
    double sd = 0.0;
    for (int i = 0; i < size; i++) {
        sd += pow(a[i] - m, 2);
    }
    sd = sqrt(sd / (size - 1));
    return sd;
}


================================================
FILE: C/DN_Spread_Std.h
================================================
//
//  Created by Trent Henderson 27 September 2021
//

#ifndef DN_SPREADSTD
#define DN_SPREADSTD

#include <stdio.h>

extern double DN_Spread_Std(const double a[], const int size);

#endif /* DN_SPREADSTD */

================================================
FILE: C/FC_LocalSimple.c
================================================
#include <math.h>
#include <string.h>
#include "stats.h"
#include "CO_AutoCorr.h"

static void abs_diff(const double a[], const int size, double b[])
{
    for (int i = 1; i < size; i++) {
        b[i - 1] = fabs(a[i] - a[i - 1]);
    }
}

double fc_local_simple(const double y[], const int size, const int train_length)
{
    double * y1 = malloc((size - 1) * sizeof *y1);
    abs_diff(y, size, y1);
    double m = mean(y1, size - 1);
    free(y1);
    return m;
}

double FC_LocalSimple_mean_tauresrat(const double y[], const int size, const int train_length)
{
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    double * res = malloc((size - train_length) * sizeof *res);
    
    for (int i = 0; i < size - train_length; i++)
    {
        double yest = 0;
        for (int j = 0; j < train_length; j++)
        {
            yest += y[i+j];
            
        }
        yest /= train_length;
        
        res[i] = y[i+train_length] - yest;
    }
    
    double resAC1stZ = co_firstzero(res, size - train_length, size - train_length);
    double yAC1stZ = co_firstzero(y, size, size);
    double output = resAC1stZ/yAC1stZ;
    
    free(res);
    return output;
    
}

double FC_LocalSimple_mean_stderr(const double y[], const int size, const int train_length)
{
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    double * res = malloc((size - train_length) * sizeof *res);
    
    for (int i = 0; i < size - train_length; i++)
    {
        double yest = 0;
        for (int j = 0; j < train_length; j++)
        {
            yest += y[i+j];
            
        }
        yest /= train_length;
        
        res[i] = y[i+train_length] - yest;
    }
    
    double output = stddev(res, size - train_length);
    
    free(res);
    return output;
    
}

double FC_LocalSimple_mean3_stderr(const double y[], const int size)
{
    return FC_LocalSimple_mean_stderr(y, size, 3);
}

double FC_LocalSimple_mean1_tauresrat(const double y[], const int size){
    return FC_LocalSimple_mean_tauresrat(y, size, 1);
}

double FC_LocalSimple_mean_taures(const double y[], const int size, const int train_length)
{
    double * res = malloc((size - train_length) * sizeof *res);
    
    // first z-score
    // no, assume ts is z-scored!!
    //zscore_norm(y, size);
    
    for (int i = 0; i < size - train_length; i++)
    {
        double yest = 0;
        for (int j = 0; j < train_length; j++)
        {
            yest += y[i+j];
            
        }
        yest /= train_length;
        
        res[i] = y[i+train_length] - yest;
    }
    
    int output = co_firstzero(res, size - train_length, size - train_length);
    
    free(res);
    return output;
    
}

double FC_LocalSimple_lfit_taures(const double y[], const int size)
{
    // set tau from first AC zero crossing
    int train_length = co_firstzero(y, size, size);
    
    double * xReg = malloc(train_length * sizeof * xReg);
    // double * yReg = malloc(train_length * sizeof * yReg);
    for(int i = 1; i < train_length+1; i++)
    {
        xReg[i-1] = i;
    }
    
    double * res = malloc((size - train_length) * sizeof *res);
    
    double m = 0.0, b = 0.0;
    
    for (int i = 0; i < size - train_length; i++)
    {
        linreg(train_length, xReg, y+i, &m, &b);
        
        // fprintf(stdout, "i=%i, m=%f, b=%f\n", i, m, b);
        
        res[i] = y[i+train_length] - (m * (train_length+1) + b);
    }
    
    int output = co_firstzero(res, size - train_length, size - train_length);
    
    free(res);
    free(xReg);
    // free(yReg);
    
    return output;
    
}




================================================
FILE: C/FC_LocalSimple.h
================================================
#ifndef FC_LOCALSIMPLE_H
#define FC_LOCALSIMPLE_H
#include <math.h>
#include <string.h>
#include "stats.h"
#include "CO_AutoCorr.h"

extern double fc_local_simple(const double y[], const int size, const int train_length);
extern double FC_LocalSimple_mean_taures(const double y[], const int size, const int train_length);
extern double FC_LocalSimple_lfit_taures(const double y[], const int size);
extern double FC_LocalSimple_mean_tauresrat(const double y[], const int size, const int train_length);
extern double FC_LocalSimple_mean1_tauresrat(const double y[], const int size);
extern double FC_LocalSimple_mean_stderr(const double y[], const int size, const int train_length);
extern double FC_LocalSimple_mean3_stderr(const double y[], const int size);

#endif


================================================
FILE: C/IN_AutoMutualInfoStats.c
================================================
//
//  IN_AutoMutualInfoStats.c
//  C_polished
//
//  Created by Carl Henning Lubba on 22/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//
#include <math.h>

#include "IN_AutoMutualInfoStats.h"
#include "CO_AutoCorr.h"
#include "stats.h"

double IN_AutoMutualInfoStats_40_gaussian_fmmi(const double y[], const int size)
{
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    // maximum time delay
    int tau = 40;
    
    // don't go above half the signal length
    if(tau > ceil((double)size/2)){
        tau = ceil((double)size/2);
    }
    
    // compute autocorrelations and compute automutual information
    double * ami = malloc(size * sizeof(double));
    for(int i = 0; i < tau; i++){
        double ac = autocorr_lag(y,size, i+1);
        ami[i] = -0.5 * log(1 - ac*ac);
        // printf("ami[%i]=%1.7f\n", i, ami[i]);
    }
    
    // find first minimum of automutual information
    double fmmi = tau;
    for(int i = 1; i < tau-1; i++){
        if(ami[i] < ami[i-1] & ami[i] < ami[i+1]){
            fmmi = i;
            // printf("found minimum at %i\n", i);
            break;
        }
    }
    
    free(ami);
    
    return fmmi;
}


================================================
FILE: C/IN_AutoMutualInfoStats.h
================================================
//
//  IN_AutoMutualInfoStats.h
//  C_polished
//
//  Created by Carl Henning Lubba on 22/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//

#ifndef IN_AutoMutualInfoStats_h
#define IN_AutoMutualInfoStats_h

#include <stdio.h>

extern double IN_AutoMutualInfoStats_40_gaussian_fmmi(const double y[], const int size);

#endif /* IN_AutoMutualInfoStats_h */


================================================
FILE: C/MD_hrv.c
================================================
//
//  MD_hrv.c
//  C_polished
//
//  Created by Carl Henning Lubba on 22/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//

#include "MD_hrv.h"
#include "stats.h"

double MD_hrv_classic_pnn40(const double y[], const int size){
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    const int pNNx = 40;
    
    // compute diff
    double * Dy = malloc((size-1) * sizeof(double));
    diff(y, size, Dy);
    
    double pnn40 = 0;
    for(int i = 0; i < size-1; i++){
        if(fabs(Dy[i])*1000 > pNNx){
            pnn40 += 1;
        }
    }
    
    free(Dy);
    
    return pnn40/(size-1);
}



================================================
FILE: C/MD_hrv.h
================================================
//
//  MD_hrv.h
//  C_polished
//
//  Created by Carl Henning Lubba on 22/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//

#ifndef MD_hrv_h
#define MD_hrv_h

#include <stdio.h>

extern double MD_hrv_classic_pnn40(const double y[], const int size);

#endif /* MD_hrv_h */


================================================
FILE: C/PD_PeriodicityWang.c
================================================
//
//  PD_PeriodicityWang.c
//  C_polished
//
//  Created by Carl Henning Lubba on 28/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//

#include <stdlib.h>
#include <math.h>

#include "PD_PeriodicityWang.h"
#include "splinefit.h"
#include "stats.h"

int PD_PeriodicityWang_th0_01(const double * y, const int size){
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return 0;
        }
    }
    
    const double th = 0.01;
    
    double * ySpline = malloc(size * sizeof(double));
    
    // fit a spline with 3 nodes to the data
    splinefit(y, size, ySpline);
    
    //printf("spline fit complete.\n");
    
    // subtract spline from data to remove trend
    double * ySub = malloc(size * sizeof(double));
    for(int i = 0; i < size; i++){
        ySub[i] = y[i] - ySpline[i];
        //printf("ySub[%i] = %1.5f\n", i, ySub[i]);
    }
    
    // compute autocorrelations up to 1/3 of the length of the time series
    int acmax = (int)ceil((double)size/3);
    
    double * acf = malloc(acmax*sizeof(double));
    for(int tau = 1; tau <= acmax; tau++){
        // correlation/ covariance the same, don't care for scaling (cov would be more efficient)
        acf[tau-1] = autocov_lag(ySub, size, tau);
        //printf("acf[%i] = %1.9f\n", tau-1, acf[tau-1]);
    }
    
    //printf("ACF computed.\n");
    
    // find troughts and peaks
    double * troughs = malloc(acmax * sizeof(double));
    double * peaks = malloc(acmax * sizeof(double));
    int nTroughs = 0;
    int nPeaks = 0;
    double slopeIn = 0;
    double slopeOut = 0;
    for(int i = 1; i < acmax-1; i ++){
        slopeIn = acf[i] - acf[i-1];
        slopeOut = acf[i+1] - acf[i];
        
        if(slopeIn < 0 & slopeOut > 0)
        {
            // printf("trough at %i\n", i);
            troughs[nTroughs] = i;
            nTroughs += 1;
        }
        else if(slopeIn > 0 & slopeOut < 0)
        {
            // printf("peak at %i\n", i);
            peaks[nPeaks] = i;
            nPeaks += 1;
        }
    }
    
    //printf("%i troughs and %i peaks found.\n", nTroughs, nPeaks);
    
    
    // search through all peaks for one that meets the conditions:
    // (a) a trough before it
    // (b) difference between peak and trough is at least 0.01
    // (c) peak corresponds to positive correlation
    int iPeak = 0;
    double thePeak = 0;
    int iTrough = 0;
    double theTrough = 0;
    
    int out = 0;
    
    for(int i = 0; i < nPeaks; i++){
        iPeak = peaks[i];
        thePeak = acf[iPeak];
        
        //printf("i=%i/%i, iPeak=%i, thePeak=%1.3f\n", i, nPeaks-1, iPeak, thePeak);
        
        // find trough before this peak
        int j = -1;
        while(troughs[j+1] < iPeak && j+1 < nTroughs){
            // printf("j=%i/%i, iTrough=%i, theTrough=%1.3f\n", j+1, nTroughs-1, (int)troughs[j+1], acf[(int)troughs[j+1]]);
            j++;
        }
        if(j == -1)
            continue;
        
        iTrough = troughs[j];
        theTrough = acf[iTrough];
        
        // (a) should be implicit
        
        // (b) different between peak and trough it as least 0.01
        if(thePeak - theTrough < th)
            continue;
        
        // (c) peak corresponds to positive correlation
        if(thePeak < 0)
            continue;
        
        // use this frequency that first fulfils all conditions.
        out = iPeak;
        break;
    }
    
    //printf("Before freeing stuff.\n");
    
    free(ySpline);
    free(ySub);
    free(acf);
    free(troughs);
    free(peaks);
    
    return out;
    
}


================================================
FILE: C/PD_PeriodicityWang.h
================================================
//
//  PD_PeriodicityWang.h
//  C_polished
//
//  Created by Carl Henning Lubba on 28/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//

#ifndef PD_PeriodicityWang_h
#define PD_PeriodicityWang_h

#include <stdio.h>

extern int PD_PeriodicityWang_th0_01(const double * y, const int size);

#endif /* PD_PeriodicityWang_h */


================================================
FILE: C/SB_BinaryStats.c
================================================
//
//  SB_BinaryStats.c
//  C_polished
//
//  Created by Carl Henning Lubba on 22/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//

#include "SB_BinaryStats.h"
#include "stats.h"

double SB_BinaryStats_diff_longstretch0(const double y[], const int size){
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    // binarize
    int * yBin = malloc((size-1) * sizeof(int));
    for(int i = 0; i < size-1; i++){
        
        double diffTemp = y[i+1] - y[i];
        yBin[i] = diffTemp < 0 ? 0 : 1;
        
        /*
        if( i < 300)
            printf("%i, y[i+1]=%1.3f, y[i]=%1.3f, yBin[i]=%i\n", i, y[i+1], y[i], yBin[i]);
         */
        
    }
    
    int maxstretch0 = 0;
    int last1 = 0;
    for(int i = 0; i < size-1; i++){
        if(yBin[i] == 1 | i == size-2){
            double stretch0 = i - last1;
            if(stretch0 > maxstretch0){
                maxstretch0 = stretch0;
            }
            last1 = i;
        }
    }
    
    free(yBin);
    
    return maxstretch0;
}

double SB_BinaryStats_mean_longstretch1(const double y[], const int size){
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    // binarize
    int * yBin = malloc((size-1) * sizeof(int));
    double yMean = mean(y, size);
    for(int i = 0; i < size-1; i++){
        
        yBin[i] = (y[i] - yMean <= 0) ? 0 : 1;
        //printf("yBin[%i]=%i\n", i, yBin[i]);
        
    }
    
    int maxstretch1 = 0;
    int last1 = 0;
    for(int i = 0; i < size-1; i++){
        if(yBin[i] == 0 | i == size-2){
            double stretch1 = i - last1;
            if(stretch1 > maxstretch1){
                maxstretch1 = stretch1;
            }
            last1 = i;
        }
        
    }
    
    free(yBin);
    
    return maxstretch1;
}


================================================
FILE: C/SB_BinaryStats.h
================================================
//
//  SB_BinaryStats.h
//  C_polished
//
//  Created by Carl Henning Lubba on 22/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//

#ifndef SB_BinaryStats_h
#define SB_BinaryStats_h

#include <stdio.h>

extern double SB_BinaryStats_diff_longstretch0(const double y[], const int size);
extern double SB_BinaryStats_mean_longstretch1(const double y[], const int size);

#endif /* SB_BinaryStats_h */


================================================
FILE: C/SB_CoarseGrain.c
================================================
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "stats.h"
#include "helper_functions.h"

void sb_coarsegrain(const double y[], const int size, const char how[], const int num_groups, int labels[])
{
    int i, j;
    if (strcmp(how, "quantile") == 1) {
        fprintf(stdout, "ERROR in sb_coarsegrain: unknown coarse-graining method\n");
        exit(1);
    }
    
    /*
    for(int i = 0; i < size; i++){
        printf("yin coarsegrain[%i]=%1.4f\n", i, y[i]);
    }
    */
    
    double * th = malloc((num_groups + 1) * 2 * sizeof(th));
    double * ls = malloc((num_groups + 1) * 2 * sizeof(th));
    linspace(0, 1, num_groups + 1, ls);
    for (i = 0; i < num_groups + 1; i++) {
        //double quant = quantile(y, size, ls[i]);
        th[i] = quantile(y, size, ls[i]);
    }
    th[0] -= 1;
    for (i = 0; i < num_groups; i++) {
        for (j = 0; j < size; j++) {
            if (y[j] > th[i] && y[j] <= th[i + 1]) {
                labels[j] = i + 1;
            }
        }
    }
    
    free(th);
    free(ls);
}


================================================
FILE: C/SB_CoarseGrain.h
================================================
#ifndef SB_COARSEGRAIN_H
#define SB_COARSEGRAIN_H
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "stats.h"
#include "helper_functions.h"

extern void sb_coarsegrain(const double y[], const int size, const char how[], const int num_groups, int labels[]);

#endif


================================================
FILE: C/SB_MotifThree.c
================================================
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "SB_CoarseGrain.h"
#include "helper_functions.h"

double SB_MotifThree_quantile_hh(const double y[], const int size)
{
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    int tmp_idx, r_idx;
    int dynamic_idx;
    int alphabet_size = 3;
    int array_size;
    int * yt = malloc(size * sizeof(yt)); // alphabetized array
    double hh; // output
    double * out = malloc(124 * sizeof(out)); // output array
    
    // transfer to alphabet
    sb_coarsegrain(y, size, "quantile", 3, yt);
    
    // words of length 1
    array_size = alphabet_size;
    int ** r1 = malloc(array_size * sizeof(*r1));
    int * sizes_r1 = malloc(array_size * sizeof(sizes_r1));
    double * out1 = malloc(array_size * sizeof(out1));
    for (int i = 0; i < alphabet_size; i++) {
        r1[i] = malloc(size * sizeof(r1[i])); // probably can be rewritten
        // using selfresizing array for memory efficiency. Time complexity
        // should be comparable due to ammotization.
        r_idx = 0;
        sizes_r1[i] = 0;
        for (int j = 0; j < size; j++) {
            if (yt[j] == i + 1) {
                r1[i][r_idx++] = j;
                sizes_r1[i]++;
            }
        }
    }
    
    // words of length 2
    array_size *= alphabet_size;
    // removing last item if it is == max possible idx since later we are taking idx + 1
    // from yt
    for (int i = 0; i < alphabet_size; i++) {
        if (sizes_r1[i] != 0 && r1[i][sizes_r1[i] - 1] == size - 1) {
            //int * tmp_ar = malloc((sizes_r1[i] - 1) * sizeof(tmp_ar));
            int* tmp_ar = malloc(sizes_r1[i] * sizeof(tmp_ar));
            subset(r1[i], tmp_ar, 0, sizes_r1[i]);
            memcpy(r1[i], tmp_ar, (sizes_r1[i] - 1) * sizeof(tmp_ar));
            sizes_r1[i]--;
            free(tmp_ar);
        }
    }
    
    /*
    int *** r2 = malloc(array_size * sizeof(**r2));
    int ** sizes_r2 = malloc(array_size * sizeof(*sizes_r2));
    double ** out2 = malloc(array_size * sizeof(*out2));
    */
    int*** r2 = malloc(alphabet_size * sizeof(**r2));
    int** sizes_r2 = malloc(alphabet_size * sizeof(*sizes_r2));
    double** out2 = malloc(alphabet_size * sizeof(*out2));
    

    // allocate separately
    for (int i = 0; i < alphabet_size; i++) {
        r2[i] = malloc(alphabet_size * sizeof(*r2[i]));
        sizes_r2[i] = malloc(alphabet_size * sizeof(*sizes_r2[i]));
        //out2[i] = malloc(alphabet_size * sizeof(out2[i]));
        out2[i] = malloc(alphabet_size * sizeof(**out2));
        for (int j = 0; j < alphabet_size; j++) {
            r2[i][j] = malloc(size * sizeof(*r2[i][j]));
        }
    }

    // fill separately
    for (int i = 0; i < alphabet_size; i++) {
    // for (int i = 0; i < array_size; i++) {
        //r2[i] = malloc(alphabet_size * sizeof(r2[i]));
        //sizes_r2[i] = malloc(alphabet_size * sizeof(sizes_r2[i]));
        //out2[i] = malloc(alphabet_size * sizeof(out2[i]));
        for (int j = 0; j < alphabet_size; j++) {
            //r2[i][j] = malloc(size * sizeof(r2[i][j]));
            sizes_r2[i][j] = 0;
            dynamic_idx = 0; //workaround as you can't just add elements to array
            // like in python (list.append()) for example, so since for some k there will be no adding,
            // you need to keep track of the idx at which elements will be inserted
            for (int k = 0; k < sizes_r1[i]; k++) {
                tmp_idx = yt[r1[i][k] + 1];
                if (tmp_idx == (j + 1)) {
                    r2[i][j][dynamic_idx++] = r1[i][k];
                    sizes_r2[i][j]++;
                    // printf("dynamic_idx=%i, size = %i\n", dynamic_idx, size);
                }
            }
            double tmp = (double)sizes_r2[i][j] / ((double)(size) - (double)(1.0));
            out2[i][j] =  tmp;
        }
    }

    hh = 0.0;
    for (int i = 0; i < alphabet_size; i++) {
        hh += f_entropy(out2[i], alphabet_size);
    }

    free(yt);
    free(out);
    free(out1);

    free(sizes_r1);

    // free nested array
    for (int i = 0; i < alphabet_size; i++) {
        free(r1[i]);
    }
    free(r1);
    // free(sizes_r1);
    
    for (int i = 0; i < alphabet_size; i++) {
    //for (int i = alphabet_size - 1; i >= 0; i--) {

        free(sizes_r2[i]);
        free(out2[i]);
    }

    //for (int i = alphabet_size-1; i >= 0 ; i--) {
    for(int i = 0; i < alphabet_size; i++) {
        for (int j = 0; j < alphabet_size; j++) {
            free(r2[i][j]);
        }
        free(r2[i]);
    }
    
    free(r2);
    free(sizes_r2);
    free(out2);
    
    
    return hh;
    
}

double * sb_motifthree(const double y[], int size, const char how[])
{
    int tmp_idx, r_idx, i, j, k, l, m, array_size;
    int dynamic_idx;
    int * tmp_ar;
    int alphabet_size = 3;
    int out_idx = 0;
    int * yt = malloc(size * sizeof(yt));
    double tmp;
    double * out = malloc(124 * sizeof(out)); // output array
    if (strcmp(how, "quantile") == 0) {
        sb_coarsegrain(y, size, how, alphabet_size, yt);
    } else if (strcmp(how, "diffquant") == 0) {
        double * diff_y = malloc((size - 1) * sizeof(diff_y));
        diff(y, size, diff_y);
        sb_coarsegrain(diff_y, size, how, alphabet_size, yt);
        size--;
    } else {
        fprintf(stdout, "ERROR in sb_motifthree: Unknown how method");
        exit(1);
    }

    // words of length 1
    array_size = alphabet_size;
    int ** r1 = malloc(array_size * sizeof(*r1));
    int * sizes_r1 = malloc(array_size * sizeof(sizes_r1));
    double * out1 = malloc(array_size * sizeof(out1));
    for (i = 0; i < array_size; i++) {
        r1[i] = malloc(size * sizeof(r1[i])); // probably can be rewritten
        // using selfresizing array for memory efficiency. Time complexity
        // should be comparable due to ammotization.
        r_idx = 0;
        sizes_r1[i] = 0;
        for (j = 0; j < size; j++) {
            if (yt[j] == i + 1) {
                r1[i][r_idx++] = j;
                sizes_r1[i]++;
            }
        }
        tmp = (double)sizes_r1[i] / size;

        out1[i] = tmp;
        out[out_idx++] = tmp;
    }
    out[out_idx++] = f_entropy(out1, array_size);

    // words of length 2
    array_size *= alphabet_size;
    // removing last item if it is == max possible idx since later we are taking idx + 1
    // from yt
    for (i = 0; i < alphabet_size; i++) {
        if (sizes_r1[i] != 0 && r1[i][sizes_r1[i] - 1] == size - 1) {
            tmp_ar = malloc((sizes_r1[i] - 1) * sizeof(tmp_ar));
            subset(r1[i], tmp_ar, 0, sizes_r1[i]);
            memcpy(r1[i], tmp_ar, (sizes_r1[i] - 1) * sizeof(tmp_ar));
            sizes_r1[i]--;
        }
    }

    int *** r2 = malloc(array_size * sizeof(**r2));
    int ** sizes_r2 = malloc(array_size * sizeof(*sizes_r2));
    double ** out2 = malloc(array_size * sizeof(*out2));
    for (i = 0; i < alphabet_size; i++) {
        r2[i] = malloc(alphabet_size * sizeof(r2[i]));
        sizes_r2[i] = malloc(alphabet_size * sizeof(sizes_r2[i]));
        out2[i] = malloc(alphabet_size * sizeof(out2[i]));
        for (j = 0; j < alphabet_size; j++) {
            r2[i][j] = malloc(size * sizeof(r2[i][j]));
            sizes_r2[i][j] = 0;
            dynamic_idx = 0; //workaround as you can't just add elements to array
            // like in python (list.append()) for example, so since for some k there will be no adding,
            // you need to keep track of the idx at which elements will be inserted
            for (k = 0; k < sizes_r1[i]; k++) {
                tmp_idx = yt[r1[i][k] + 1];
                if (tmp_idx == (j + 1)) {
                    r2[i][j][dynamic_idx++] = r1[i][k];
                    sizes_r2[i][j]++;
                }
            }
            tmp = (double)sizes_r2[i][j] / (size - 1);
            out2[i][j] = tmp;
            out[out_idx++] = tmp;
        }
    }
    tmp = 0.0;
    for (i = 0; i < alphabet_size; i++) {
        tmp += f_entropy(out2[i], alphabet_size);
    }
    out[out_idx++] = tmp;

    // words of length 3
    array_size *= alphabet_size;
    for (i = 0; i < alphabet_size; i++) {
        for (j = 0; j < alphabet_size; j++) {
            if (sizes_r2[i][j] != 0 && r2[i][j][sizes_r2[i][j] - 1] == size - 2) {
                subset(r2[i][j], tmp_ar, 0, sizes_r2[i][j]);
                memcpy(r2[i][j], tmp_ar, (sizes_r2[i][j] - 1) * sizeof(tmp_ar));
                sizes_r2[i][j]--;
            }
        }
    }

    int **** r3 = malloc(array_size * sizeof(***r3));
    int *** sizes_r3 = malloc(array_size * sizeof(**sizes_r3));
    double *** out3 = malloc(array_size * sizeof(**out3));
    for (i = 0; i < alphabet_size; i++) {
        r3[i] = malloc(alphabet_size * sizeof(r3[i]));
        sizes_r3[i] = malloc(alphabet_size * sizeof(sizes_r3[i]));
        out3[i] = malloc(alphabet_size * sizeof(out3[i]));
        for (j = 0; j < alphabet_size; j++) {
            r3[i][j] = malloc(alphabet_size * sizeof(r3[i][j]));
            sizes_r3[i][j] = malloc(alphabet_size * sizeof(sizes_r3[i][j]));
            out3[i][j] = malloc(alphabet_size * sizeof(out3[i][j]));
            for (k = 0; k < alphabet_size; k++) {
                r3[i][j][k] = malloc(size * sizeof(r3[i][j][k]));
                sizes_r3[i][j][k] = 0;
                dynamic_idx = 0;
                for (l = 0; l < sizes_r2[i][j]; l++) {
                    tmp_idx = yt[r2[i][j][l] + 2];
                    if (tmp_idx == (k + 1)) {
                        r3[i][j][k][dynamic_idx++] = r2[i][j][l];
                        sizes_r3[i][j][k]++;
                    }
                }
                tmp = (double)sizes_r3[i][j][k] / (size - 2);
                out3[i][j][k] = tmp;
                out[out_idx++] = tmp;
            }
        }
    }
    tmp = 0.0;
    for (i = 0; i < alphabet_size; i++) {
        for (j = 0; j < alphabet_size; j++) {
            tmp += f_entropy(out3[i][j], alphabet_size);
        }
    }
    out[out_idx++] = tmp;

    // words of length 4
    array_size *= alphabet_size;
    for (i = 0; i < alphabet_size; i++) {
        for (j = 0; j < alphabet_size; j++) {
            for (k = 0; k < alphabet_size; k++) {
                if (sizes_r3[i][j][k] != 0 && r3[i][j][k][sizes_r3[i][j][k] - 1] == size - 3) {
                    subset(r3[i][j][k], tmp_ar, 0, sizes_r3[i][j][k]);
                    memcpy(r3[i][j][k], tmp_ar, (sizes_r3[i][j][k] - 1) * sizeof(tmp_ar));
                    sizes_r3[i][j][k]--;
                }
            }
        }
    }

    int ***** r4 = malloc(array_size * sizeof(****r4));
    // just an array of pointers of array of pointers of array of pointers
    // of array of pointers of array of ints... We need to go deeper (c)
    int **** sizes_r4 = malloc(array_size * sizeof(***sizes_r3));
    double **** out4 = malloc(array_size * sizeof(***out4));
    for (i = 0; i < alphabet_size; i++) {
        r4[i] = malloc(alphabet_size * sizeof(r4[i]));
        sizes_r4[i] = malloc(alphabet_size * sizeof(sizes_r4[i]));
        out4[i] = malloc(alphabet_size * sizeof(out4[i]));
        for (j = 0; j < alphabet_size; j++) {
            r4[i][j] = malloc(alphabet_size * sizeof(r4[i][j]));
            sizes_r4[i][j] = malloc(alphabet_size * sizeof(sizes_r4[i][j]));
            out4[i][j] = malloc(alphabet_size * sizeof(out4[i][j]));
            for (k = 0; k < alphabet_size; k++) {
                r4[i][j][k] = malloc(alphabet_size * sizeof(r4[i][j][k]));
                sizes_r4[i][j][k] = malloc(alphabet_size * sizeof(sizes_r4[i][j][k]));
                out4[i][j][k] = malloc(alphabet_size * sizeof(out4[i][j][k]));
                for (l = 0; l < alphabet_size; l++) {
                    r4[i][j][k][l] = malloc(size * sizeof(r4[i][j][k][l]));
                    sizes_r4[i][j][k][l] = 0;
                    dynamic_idx = 0;
                    for (m = 0; m < sizes_r3[i][j][k]; m++) {
                        tmp_idx = yt[r3[i][j][k][m] + 3];
                        if (tmp_idx == l + 1) {
                            r4[i][j][k][l][dynamic_idx++] = r3[i][j][k][m];
                            sizes_r4[i][j][k][l]++;
                        }
                    }
                    tmp = (double)sizes_r4[i][j][k][l] / (size - 3);
                    out4[i][j][k][l] = tmp;
                    out[out_idx++] = tmp;
                }
            }
        }
    }
    tmp = 0.0;
    for (i = 0; i < alphabet_size; i++) {
        for (j = 0; j < alphabet_size; j++) {
            for (k = 0; k < alphabet_size; k++) {
                tmp += f_entropy(out4[i][j][k], alphabet_size);
            }
        }
    }
    out[out_idx++] = tmp;

    return out;
}



























================================================
FILE: C/SB_MotifThree.h
================================================
#ifndef SB_MOTIFTHREE_H
#define SB_MOTIFTHREE_H
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "SB_CoarseGrain.h"
#include "helper_functions.h"

extern double SB_MotifThree_quantile_hh(const double y[], const int size);
extern double * sb_motifthree(const double y[], int size, const char how[]);

#endif


================================================
FILE: C/SB_TransitionMatrix.c
================================================
//
//  SB_TransitionMatrix.c
//  
//
//  Created by Carl Henning Lubba on 23/09/2018.
//

#include "SB_TransitionMatrix.h"
#include "butterworth.h"
#include "CO_AutoCorr.h"
#include "SB_CoarseGrain.h"
#include "stats.h"

double SB_TransitionMatrix_3ac_sumdiagcov(const double y[], const int size)
{
    
    // NaN and const check
    int constant = 1;
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
        if(y[i] != y[0]){
            constant = 0;
        }
    }
    if (constant){
        return NAN;
    }
    
    const int numGroups = 3;
    
    int tau = co_firstzero(y, size, size);
    
    double * yFilt = malloc(size * sizeof(double));
    
    // sometimes causes problems in filt!!! needs fixing.
    /*
    if(tau > 1){
        butterworthFilter(y, size, 4, 0.8/tau, yFilt);
    }
    */
    
    for(int i = 0; i < size; i++){
        yFilt[i] = y[i];
    }
    
    /*
    for(int i = 0; i < size; i++){
        printf("yFilt[%i]=%1.4f\n", i, yFilt[i]);
    }
     */
    
    int nDown = (size-1)/tau+1;
    double * yDown = malloc(nDown * sizeof(double));
    
    for(int i = 0; i < nDown; i++){
        yDown[i] = yFilt[i*tau];
    }
    
    /*
    for(int i = 0; i < nDown; i++){
        printf("yDown[%i]=%1.4f\n", i, yDown[i]);
    }
     */
    
    
    // transfer to alphabet
    int * yCG = malloc(nDown * sizeof(double));
    sb_coarsegrain(yDown, nDown, "quantile", numGroups, yCG);
    
    /*
    for(int i = 0; i < nDown; i++){
        printf("yCG[%i]=%i\n", i, yCG[i]);
    }
     */
    
    
    double T[3][3];
    for(int i = 0; i < numGroups; i++){
        for(int j = 0; j < numGroups; j++){
            T[i][j] = 0;
        }
    }
    
    // more efficient way of doing the below 
    for(int j = 0; j < nDown-1; j++){
        T[yCG[j]-1][yCG[j+1]-1] += 1;
    }
    
    /*
    for(int i = 0; i < numGroups; i++){
        for(int j = 0; j < numGroups; j++){
            printf("%1.f, ", T[i][j]);
        }
        printf("\n");
    }
     */
    
    /*
    for(int i = 0; i < numGroups; i++){
        for(int j = 0; j < nDown-1; j++){
            if(yCG[j] == i+1){
                T[i][yCG[j+1]-1] += 1;
            }
        }
    }
     */
    
    for(int i = 0; i < numGroups; i++){
        for(int j = 0; j < numGroups; j++){
            T[i][j] /= (nDown-1);
            // printf("T(%i, %i) = %1.3f\n", i, j, T[i][j]);
            
        }
    }
    
    double column1[3] = {0};
    double column2[3] = {0};
    double column3[3] = {0};
    
    for(int i = 0; i < numGroups; i++){
        column1[i] = T[i][0];
        column2[i] = T[i][1];
        column3[i] = T[i][2];
        // printf("column3(%i) = %1.3f\n", i, column3[i]);
    }
    
    double *columns[3];
    columns[0] = &(column1[0]);
    columns[1] = &(column2[0]);
    columns[2] = &(column3[0]);
    
    
    double COV[3][3];
    double covTemp = 0;
    for(int i = 0; i < numGroups; i++){
        for(int j = i; j < numGroups; j++){
            
            covTemp = cov(columns[i], columns[j], 3);
            
            COV[i][j] = covTemp;
            COV[j][i] = covTemp;
            
            // printf("COV(%i , %i) = %1.3f\n", i, j, COV[i][j]);
        }
    }
    
    double sumdiagcov = 0;
    for(int i = 0; i < numGroups; i++){
        sumdiagcov += COV[i][i];
    }
    
    free(yFilt);
    free(yDown);
    free(yCG);
    
    return sumdiagcov;
    
    
}


================================================
FILE: C/SB_TransitionMatrix.h
================================================
//
//  SB_TransitionMatrix.h
//  
//
//  Created by Carl Henning Lubba on 23/09/2018.
//

#ifndef SB_TransitionMatrix_h
#define SB_TransitionMatrix_h

#include <stdio.h>

extern double SB_TransitionMatrix_3ac_sumdiagcov(const double y[], const int size);

#endif /* SB_TransitionMatrix_h */


================================================
FILE: C/SC_FluctAnal.c
================================================
#include <math.h>
#include <string.h>
#include <time.h>
#include <float.h>
#include <stdio.h>
#include "stats.h"
#include "CO_AutoCorr.h"

double SC_FluctAnal_2_50_1_logi_prop_r1(const double y[], const int size, const int lag, const char how[])
{
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    // generate log spaced tau vector
    double linLow = log(5);
    double linHigh = log(size/2);
    
    int nTauSteps = 50;
    double tauStep = (linHigh - linLow) / (nTauSteps-1);
    
    int tau[50];
    for(int i = 0; i < nTauSteps; i++)
    {
        tau[i] = round(exp(linLow + i*tauStep));
    }
    
    // check for uniqueness, use ascending order
    int nTau = nTauSteps;
    for(int i = 0; i < nTauSteps-1; i++)
    {
        
        while (tau[i] == tau[i+1] && i < nTau-1)
        {
            for(int j = i+1; j < nTauSteps-1; j++)
            {
                tau[j] = tau[j+1];
            }
            // lost one
            nTau -= 1;
        }
    }
    
    // fewer than 12 points -> leave.
    if(nTau < 12){
        return 0;
    }
    
    int sizeCS = size/lag;
    double * yCS = malloc(sizeCS * sizeof(double));
    
    /*
    for(int i = 0; i < 50; i++)
    {
        printf("y[%i]=%1.3f\n", i, y[i]);
    }
     */
    
    // transform input vector to cumsum
    yCS[0] = y[0];
    for(int i = 0; i < sizeCS-1; i++)
    {
        yCS[i+1] = yCS[i] + y[(i+1)*lag];
        
        /*
        if(i<300)
            printf("yCS[%i]=%1.3f\n", i, yCS[i]);
         */
    }
    
    //for each value of tau, cut signal into snippets of length tau, detrend and
    
    // first generate a support for regression (detrending)
    double * xReg = malloc(tau[nTau-1] * sizeof * xReg);
    for(int i = 0; i < tau[nTau-1]; i++)
    {
        xReg[i] = i+1;
    }
    
    // iterate over taus, cut signal, detrend and save amplitude of remaining signal
    double * F = malloc(nTau * sizeof * F);
    for(int i = 0; i < nTau; i++)
    {
        int nBuffer = sizeCS/tau[i];
        double * buffer = malloc(tau[i] * sizeof * buffer);
        double m = 0.0, b = 0.0;
        
        //printf("tau[%i]=%i\n", i, tau[i]);
        
        F[i] = 0;
        for(int j = 0; j < nBuffer; j++)
        {
            
            //printf("%i th buffer\n", j);
            
            linreg(tau[i], xReg, yCS+j*tau[i], &m, &b);
            
            
            for(int k = 0; k < tau[i]; k++)
            {
                buffer[k] = yCS[j*tau[i]+k] - (m * (k+1) + b);
                //printf("buffer[%i]=%1.3f\n", k, buffer[k]);
            }
            
            if (strcmp(how, "rsrangefit") == 0) {
                F[i] += pow(max_(buffer, tau[i]) - min_(buffer, tau[i]), 2);
            }
            else if (strcmp(how, "dfa") == 0) {
                for(int k = 0; k<tau[i]; k++){
                    F[i] += buffer[k]*buffer[k];
                }
            }
            else{
                return 0.0;
            }
        }
        
        if (strcmp(how, "rsrangefit") == 0) {
            F[i] = sqrt(F[i]/nBuffer);
        }
        else if (strcmp(how, "dfa") == 0) {
            F[i] = sqrt(F[i]/(nBuffer*tau[i]));
        }
        //printf("F[%i]=%1.3f\n", i, F[i]);
        
        free(buffer);
        
    }
    
    double * logtt = malloc(nTau * sizeof * logtt);
    double * logFF = malloc(nTau * sizeof * logFF);
    int ntt = nTau;
    
    for (int i = 0; i < nTau; i++)
    {
        logtt[i] = log(tau[i]);
        logFF[i] = log(F[i]);
    }
    
    int minPoints = 6;
    int nsserr = (ntt - 2*minPoints + 1);
    double * sserr = malloc(nsserr * sizeof * sserr);
    double * buffer = malloc((ntt - minPoints + 1) * sizeof * buffer);
    for (int i = minPoints; i < ntt - minPoints + 1; i++)
    {
        // this could be done with less variables of course
        double m1 = 0.0, b1 = 0.0;
        double m2 = 0.0, b2 = 0.0;
        
        sserr[i - minPoints] = 0.0;
        
        linreg(i, logtt, logFF, &m1, &b1);
        linreg(ntt-i+1, logtt+i-1, logFF+i-1, &m2, &b2);
        
        for(int j = 0; j < i; j ++)
        {
            buffer[j] = logtt[j] * m1 + b1 - logFF[j];
        }
        
        sserr[i - minPoints] += norm_(buffer, i);
        
        for(int j = 0; j < ntt-i+1; j++)
        {
            buffer[j] = logtt[j+i-1] * m2 + b2 - logFF[j+i-1];
        }
        
        sserr[i - minPoints] += norm_(buffer, ntt-i+1);
        
    }
    
    double firstMinInd = 0.0;
    double minimum = min_(sserr, nsserr);
    for(int i = 0; i < nsserr; i++)
    {
        if(sserr[i] == minimum)
        {
            firstMinInd = i + minPoints - 1;
            break;
        }
    }
    
    free(yCS); // new
    
    free(xReg);
    free(F);
    free(logtt);
    free(logFF);
    free(sserr);
    free(buffer);
    
    return (firstMinInd+1)/ntt;
    
}

double SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1(const double y[], const int size){
    return SC_FluctAnal_2_50_1_logi_prop_r1(y, size, 2, "dfa");
}

double SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1(const double y[], const int size){
    return SC_FluctAnal_2_50_1_logi_prop_r1(y, size, 1, "rsrangefit");
}

/*
double SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1(double y[], int size)
{
    // generate log spaced tau vector
    double linLow = log(5);
    double linHigh = log(size/2);
    
    int nTauSteps = 50;
    double tauStep = (linHigh - linLow) / (nTauSteps-1);
    
    int tau[50];
    for(int i = 0; i < nTauSteps; i++)
    {
        tau[i] = round(exp(linLow + i*tauStep));
    }
    
   // check for uniqueness, use ascending order
    int nTau = nTauSteps;
    for(int i = 0; i < nTauSteps; i++)
    {
        
        while (tau[i] == tau[i+1] && i < nTau-1)
        {
            for(int j = i+1; j < nTauSteps-1; j++)
            {
                tau[j] = tau[j+1];
            }
            // lost one
            nTau -= 1;
        }
    }
    
    // fewer than 8 points -> leave.
    if(nTau < 8){
        return 0;
    }
    
    // transform input vector to cumsum
    for(int i = 0; i < size-1; i++)
    {
        y[i+1] = y[i] + y[i+1];
    }
    
    //for each value of tau, cut signal into snippets of length tau, detrend and
    
    // first generate a support for regression (detrending)
    double * xReg = malloc(tau[nTau-1] * sizeof * xReg);
    for(int i = 0; i < tau[nTau-1]; i++)
    {
        xReg[i] = i+1;
    }
    
    // iterate over taus, cut signal, detrend and save amplitude of remaining signal
    double * F = malloc(nTau * sizeof * F);
    for(int i = 0; i < nTau; i++)
    {
        int nBuffer = size/tau[i];
        double * buffer = malloc(tau[i] * sizeof * buffer);
        double m = 0.0, b = 0.0;
        
        F[i] = 0;
        for(int j = 0; j < nBuffer; j++)
        {
            
            linreg(tau[i], xReg, y+j*tau[i], &m, &b);
            
            for(int k = 0; k < tau[i]; k++)
            {
                buffer[k] = y[j*tau[i]+k] - (m * (k+1) + b);
            }
            
            F[i] += pow(max(buffer, tau[i]) - min(buffer, tau[i]), 2);
        }
        
        F[i] = sqrt(F[i]/nBuffer);
        
        free(buffer);
        
    }
    
    double * logtt = malloc(nTau * sizeof * logtt);
    double * logFF = malloc(nTau * sizeof * logFF);
    int ntt = nTau;
    
    for (int i = 0; i < nTau; i++)
    {
        logtt[i] = log(tau[i]);
        logFF[i] = log(F[i]);
    }
    
    int minPoints = 6;
    int nsserr = (ntt - 2*minPoints + 1);
    double * sserr = malloc(nsserr * sizeof * sserr);
    double * buffer = malloc((ntt - minPoints + 1) * sizeof * buffer);
    for (int i = minPoints; i < ntt - minPoints + 1; i++)
    {
        // this could be done with less variables of course
        double m1 = 0.0, b1 = 0.0;
        double m2 = 0.0, b2 = 0.0;
        
        sserr[i - minPoints] = 0.0;
        
        linreg(i, logtt, logFF, &m1, &b1);
        linreg(ntt-i+1, logtt+i-1, logFF+i-1, &m2, &b2);
        
        for(int j = 0; j < i; j ++)
        {
            buffer[j] = logtt[j] * m1 + b1 - logFF[j];
        }
        
        sserr[i - minPoints] += norm(buffer, i);
        
        for(int j = 0; j < ntt-i+1; j++)
        {
            buffer[j] = logtt[j+i-1] * m2 + b2 - logFF[j+i-1];
        }
        
        sserr[i - minPoints] += norm(buffer, ntt-i+1);
        
    }
    
    double firstMinInd = 0.0;
    double minimum = min(sserr, nsserr);
    for(int i = 0; i < nsserr; i++)
    {
        if(sserr[i] == minimum)
        {
            firstMinInd = i + minPoints - 1;
            break;
        }
    }
    
    free(xReg);
    free(F);
    free(logtt);
    free(logFF);
    free(sserr);
    free(buffer);
    
    return (firstMinInd+1)/ntt;
    
}
 */


================================================
FILE: C/SC_FluctAnal.h
================================================
#ifndef SC_FLUCTANAL
#define SC_FLUCTANAL
#include <math.h>
#include <string.h>
#include "stats.h"
#include "CO_AutoCorr.h"

extern double SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1(const double y[], const int size);
extern double SC_FluctAnal_2_50_1_logi_prop_r1(const double y[], const int size, const char how[]);
extern double SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1(const double y[], const int size);
#endif


================================================
FILE: C/SP_Summaries.c
================================================
//
//  SP_Summaries.c
//  
//
//  Created by Carl Henning Lubba on 23/09/2018.
//

#include "SP_Summaries.h"
#include "CO_AutoCorr.h"

int welch(const double y[], const int size, const int NFFT, const double Fs, const double window[], const int windowWidth, double ** Pxx, double ** f){
    
    double dt = 1.0/Fs;
    double df = 1.0/(nextpow2(windowWidth))/dt;
    double m = mean(y, size);
    
    // number of windows, should be 1
    int k = floor((double)size/((double)windowWidth/2.0))-1;
    
    // normalising scale factor
    double KMU = k * pow(norm_(window, windowWidth),2);
    
    double * P = malloc(NFFT * sizeof(double));
    for(int i = 0; i < NFFT; i++){
        P[i] = 0;
    }
    
    // fft variables
    cplx * F = malloc(NFFT * sizeof *F);
    cplx * tw = malloc(NFFT * sizeof *tw);
    twiddles(tw, NFFT);
    
    double * xw = malloc(windowWidth * sizeof(double));
    for(int i = 0; i<k; i++){
        
        // apply window
        for(int j = 0; j<windowWidth; j++){
            xw[j] = window[j]*y[j + (int)(i*(double)windowWidth/2.0)];
        }
        
        // initialise F (
        for (int i = 0; i < windowWidth; i++) {
            
	    #if defined(__GNUC__) || defined(__GNUG__)
		cplx tmp = xw[i] - m + 0.0 * I;
	    #elif defined(_MSC_VER)
		cplx tmp = { xw[i] - m, 0.0 };
	    #endif
            
            
            F[i] = tmp; // CMPLX(xw[i] - m, 0.0);
        }
        for (int i = windowWidth; i < NFFT; i++) {
            // F[i] = CMPLX(0.0, 0.0);
            //cplx tmp = { 0.0, 0.0 };
            #if defined(__GNUC__) || defined(__GNUG__)
		cplx tmp = 0.0 + 0.0 * I;
	    #elif defined(_MSC_VER)
		cplx tmp = { 0.0 , 0.0 };
	    #endif
            F[i] = tmp;
        }
        
        fft(F, NFFT, tw);
        /*
        for(int i = 0; i < NFFT; i++){
            printf("F1[%i] real: %1.3f, imag: %1.3f\n", i, creal(F[i]), cimag(F[i]));
        }
         */
        
        for(int l = 0; l < NFFT; l++){
            P[l] += pow(cabs(F[l]),2);
        }
        /*
        for(int i = 0; i < NFFT; i++){
            printf("P[%i]: %1.3f\n", i, P[i]);
        }
         */
        
    }
    
    int Nout = (NFFT/2+1);
    *Pxx = malloc(Nout * sizeof(double));
    for(int i = 0; i < Nout; i++){
        (*Pxx)[i] = P[i]/KMU*dt;
        if(i>0 & i < Nout-1){
            (*Pxx)[i] *= 2;
        }
    }
    /*
    for(int i = 0; i < Nout; i++){
        printf("Pxx[%i]: %1.3f\n", i, Pxx[i]);
    }
     */
    
    *f = malloc(Nout * sizeof(double));
    for(int i = 0; i < Nout; i++){
        (*f)[i] = (double)i*df;
    }
    /*
    for(int i = 0; i < Nout; i++){
        printf("f[%i]: %1.3f\n", i, (*f)[i]);
    }
     */
    
    free(P);
    free(F);
    free(tw);
    free(xw);
    
    return Nout;
}

double SP_Summaries_welch_rect(const double y[], const int size, const char what[])
{
    
    // NaN check
    for(int i = 0; i < size; i++)
    {
        if(isnan(y[i]))
        {
            return NAN;
        }
    }
    
    // rectangular window for Welch-spectrum
    double * window = malloc(size * sizeof(double));
    for(int i = 0; i < size; i++){
        window[i] = 1;
    }
    
    double Fs = 1.0; // sampling frequency
    int N = nextpow2(size);
    
    double * S;
    double * f;
    
    // compute Welch-power
    int nWelch = welch(y, size, N, Fs, window, size, &S, &f);
    free(window);
    
    // angualr frequency and spectrum on that
    double * w = malloc(nWelch * sizeof(double));
    double * Sw = malloc(nWelch * sizeof(double));
    
    double PI = 3.14159265359;
    for(int i = 0; i < nWelch; i++){
        w[i] = 2*PI*f[i];
        Sw[i] = S[i]/(2*PI);
        //printf("w[%i]=%1.3f, Sw[%i]=%1.3f\n", i, w[i], i, Sw[i]);
        if(isinf(Sw[i]) | isinf(-Sw[i])){
            return 0;
        }
    }
    
    double dw = w[1] - w[0];
    
    double * csS = malloc(nWelch * sizeof(double));
    cumsum(Sw, nWelch, csS);
    /*
    for(int i=0; i<nWelch; i++)
    {
        printf("csS[%i]=%1.3f\n", i, csS[i]);
    }
     */
    
    double output = 0;
    
    if(strcmp(what, "centroid") == 0){
        
        double csSThres = csS[nWelch-1]*0.5;
        double centroid = 0;
        for(int i = 0; i < nWelch; i ++){
            if(csS[i] > csSThres){
                centroid = w[i];
                break;
            }
        }
        
        output = centroid;
        
    }
    else if(strcmp(what, "area_5_1") == 0){
        double area_5_1 = 0;;
        for(int i=0; i<nWelch/5; i++){
            area_5_1 += Sw[i];
        }
        area_5_1 *= dw;
        
        output = area_5_1;
    }
    
    free(w);
    free(Sw);
    free(csS);
    free(f);
    free(S);
    
    return output;
    
    
}


double SP_Summaries_welch_rect_area_5_1(const double y[], const int size)
{
    return SP_Summaries_welch_rect(y, size, "area_5_1");
}
double SP_Summaries_welch_rect_centroid(const double y[], const int size)
{
    return SP_Summaries_welch_rect(y, size, "centroid");
    
}


================================================
FILE: C/SP_Summaries.h
================================================
//
//  SP_Summaries.h
//  
//
//  Created by Carl Henning Lubba on 23/09/2018.
//

#ifndef SP_Summaries_h
#define SP_Summaries_h

#include <stdio.h>

extern double SP_Summaries_welch_rect(const double y[], const int size, const char what[]);
extern double SP_Summaries_welch_rect_area_5_1(const double y[], const int size);
extern double SP_Summaries_welch_rect_centroid(const double y[], const int size);

#endif /* SP_Summaries_h */


================================================
FILE: C/butterworth.c
================================================
//
//  butterworth.c
//  
//
//  Created by Carl Henning Lubba on 23/09/2018.
//

#include <stdlib.h>
#include <math.h>

#if __cplusplus
#   include <complex>
typedef std::complex< double > cplx;
#else
#   include <complex.h>
#if defined(__GNUC__) || defined(__GNUG__)
    typedef double complex cplx;
#elif defined(_MSC_VER)
    typedef _Dcomplex cplx;
#endif
#endif

#include "helper_functions.h"
#include "butterworth.h"

#ifndef CMPLX
#define CMPLX(x, y) ((cplx)((double)(x) + _Imaginary_I * (double)(y)))
#endif

void poly(cplx x[], int size, cplx out[])
{
    /* Convert roots x to polynomial coefficients */
    
    // initialise
    #if defined(__GNUC__) || defined(__GNUG__)
        out[0] = 1;
        for(int i=1; i<size+1; i++){
            out[i] = 0;
        }
    #elif defined(_MSC_VER)
        cplx c1 = { 1, 0 };
        out[0] = c1;//1;
        for(int i=1; i<size+1; i++){
            c1._Val[0] = 0;
            out[i] = c1;
        }
    #endif
    
    
    cplx * outTemp = malloc((size+1)* sizeof(cplx));
    
    for(int i=1; i<size+1; i++){
        
        // save old out to not reuse some already changed values
        //(can be done more efficiently by only saving one old value, but who cares, pole number is usually ~4)
        for(int j=0; j<size+1; j++){
            outTemp[j] = out[j];
        }
        
        for(int j=1; j<i+1; j++){
            
            cplx temp1 = _Cmulcc(x[i - 1], outTemp[j - 1]);//x[i - 1] * outTemp[j - 1];
            cplx temp2 = out[j];
            out[j] = _Cminuscc(temp2, temp1);//x[i - 1] * outTemp[j - 1];
            
        }
        
    }
    
}

void filt(double y[], int size, double a[], double b[], int nCoeffs, double out[]){
    
    /* Filter a signal y with the filter coefficients a and b, output to array out.*/
    
    double offset = y[0];
    
    for(int i = 0; i < size; i++){
        out[i] = 0;
        for(int j = 0; j < nCoeffs; j++){
            if(i - j >= 0)
            {
                out[i] += b[j]*(y[i-j]-offset);
                out[i] -= a[j]*out[i-j];
            }
            else{
                out[i] += 0; //b[j]*offset; // 'padding'
                out[i] -= 0; //a[j]*offset;
            }
        }
    }
    
    for(int i = 0; i < size; i++){
        out[i] += offset;
    }
}

void reverse_array(double a[], int size){
    
    /* Reverse the order of the elements in an array. Write back into the input array.*/
    
    double temp;
    for(int i = 0; i < size/2; i++){
        temp = a[i];
        a[i] = a[size-i-1];
        a[size-1-i] = temp;
        /*
        printf("indFrom = %i, indTo = %i\n", i, size-1-i);
        for(int i=0; i < size; i++){
            printf("reversed[%i]=%1.3f\n", i, a[i]);
        }
         */
    }
}

void filt_reverse(double y[], int size, double a[], double b[], int nCoeffs, double out[]){
    
    /* Filter a signal y with the filter coefficients a and b _in reverse order_, output to array out.*/
    
    double * yTemp = malloc(size * sizeof(double));
    for(int i = 0; i < size; i++){
        yTemp[i] = y[i];
    }
    
    /*
    for(int i=0; i < size; i++){
        printf("yTemp[%i]=%1.3f\n", i, yTemp[i]);
    }
     */
    
    reverse_array(yTemp, size);
    
    /*
    for(int i=0; i < size; i++){
        printf("reversed[%i]=%1.3f\n", i, yTemp[i]);
    }
     */
    
    double offset = yTemp[0];
    
    for(int i = 0; i < size; i++){
        out[i] = 0;
        for(int j = 0; j < nCoeffs; j++){
            if(i - j >= 0)
            {
                out[i] += b[j]*(yTemp[i-j]-offset);
                out[i] -= a[j]*out[i-j];
            }
            else{
                out[i] += 0; //b[j]*offset; // 'padding'
                out[i] -= 0; //a[j]*offset;
            }
        }
    }
    
    for(int i = 0; i < size; i++){
        out[i] += offset;
    }
    
    reverse_array(out, size);
    
    free(yTemp);
    
}

/*
void butterworthFilter(const double y[], int size, const int nPoles, const double W, double out[]){
    
    double PI = 3.14159265359;

    double V = tan(W * PI/2);
    cplx * Q = malloc(nPoles * sizeof(cplx));
    
    for(int i = 0; i<nPoles; i++){
        cplx tmp1 = { 0, PI / 2 };
        cplx tmp2 = { nPoles, 0 };
        Q[i] =  conj(cexp((_Cdivcc(tmp1, tmp2)) * ((2 + nPoles - 1) + 2*i)));
        //printf("Q[%i]= real %1.3f imag %1.3f\n", i, creal(Q[i]), cimag(Q[i]));
        
    }
    
    double Sg = pow(V,nPoles);
    cplx * Sp = malloc(nPoles * sizeof(cplx));
    
    for(int i = 0; i<nPoles; i++){
        Sp[i] = V * Q[i];
        //printf("Sp[%i]= real %1.3f imag %1.3f\n", i, creal(Sp[i]), cimag(Sp[i]));
    }
    
    cplx * P = malloc(nPoles * sizeof(cplx));
    cplx * Z = malloc(nPoles * sizeof(cplx));
    
    cplx prod1mSp = 1; // %1 - Sp[0];
    
    // Bilinear transform for poles, fill zeros, compute products
    for(int i = 0; i<nPoles; i++){
        P[i] = (1 + Sp[i]) / (1 - Sp[i]);
        Z[i] = -1;
        
        // printf("P[%i]= real %1.3f imag %1.3f\n", i, creal(P[i]), cimag(P[i]));
        // printf("Z[%i]= real %1.3f imag %1.3f\n", i, creal(Z[i]), cimag(Z[i]));
        
        prod1mSp *= (1 - Sp[i]);
        
        //if(i > 0){
        //    prod1mSp *= (1 - Sp[i]);
        //}
         
    }

    double G = creal(Sg / prod1mSp);
    
    cplx * Zpoly = malloc((nPoles+1) * sizeof(cplx));
    cplx * Ppoly = malloc((nPoles+1) * sizeof(cplx));
    
    // polynomial coefficients from poles and zeros for filtering
    poly(Z, nPoles, Zpoly);
    
    //for(int i = 0; i < nPoles+1; i++){
    //    printf("Zpoly[%i]= %1.3f + %1.3f i\n", i, creal(Zpoly[i]), cimag(Zpoly[i]));
    //}
    
    poly(P, nPoles, Ppoly);
    
    //for(int i = 0; i < nPoles+1; i++){
    //    printf("Ppoly[%i]= %1.3f + %1.3f i\n", i, creal(Ppoly[i]), cimag(Ppoly[i]));
    //}
    
    
    // coeffs for filtering
    double * b = malloc((nPoles+1) * sizeof(double)); // zeros
    double * a = malloc((nPoles+1) * sizeof(double)); // poles
    
    for(int i = 0; i<nPoles+1; i++){
        b[i] = G * creal(Zpoly[i]);
        a[i] = creal(Ppoly[i]);
        //printf("a[%i]=%1.8f, b[%i]=%1.8f\n", i, a[i], i, b[i]);
    }
    
    
    // this is the simple solution, one forward filtering, phase not preserved.
    //filt(y, size, a, b, nPoles, out);
    
    // from here, better way of filtering. Forward and backward.
    // pad to both sides to avoid end-transients
    int nfact = 3*nPoles;
    double * yPadded = malloc((size + 2*nfact) * sizeof(double));
    
    for(int i = 0; i < nfact; i ++)
    {
        yPadded[i] = 2*y[0] - y[nfact-i];
        yPadded[nfact + size + i] = 2*y[size-1] - y[size-2-i];
        
    }
    for(int i = 0; i < size; i ++)
    {
        yPadded[nfact+i] = y[i];
    }
    
    // filter in both directions
    double * outPadded = malloc((size + 2*nfact) * sizeof(double));
    filt(yPadded, (size + 2*nfact), a, b, nPoles, outPadded);
    
    //for(int i=0; i < (size + 2*nfact); i++){
    //    printf("filtPadded[%i]=%1.3f\n", i, outPadded[i]);
    //}
     
    filt_reverse(outPadded, (size + 2*nfact), a, b, nPoles, outPadded);
    
    
    // for(int i=0; i < (size + 2*nfact); i++){
    //    printf("filtfiltPadded[%i]=%1.3f\n", i, outPadded[i]);
    //}
     
     
    for(int i = 0; i < size; i ++){
        out[i] = outPadded[nfact + i];
    }
    
    
    //for(int i=0; i < size; i++){
    //    printf("out[%i]=%1.3f\n", i, out[i]);
    //}
     
    
    free(Q);
    free(Sp);
    free(P);
    free(Z);
    free(a);
    free(b);
    free(Zpoly);
    free(Ppoly);
    free(outPadded);
    
}

*/

================================================
FILE: C/butterworth.h
================================================
//
//  butterworth.h
//  
//
//  Created by Carl Henning Lubba on 23/09/2018.
//

#ifndef butterworth_h
#define butterworth_h

#include <stdio.h>

extern void butterworthFilter(const double y[], const int size, const int nPoles, const double W, double out[]);

#endif /* butterworth_h */


================================================
FILE: C/fft.c
================================================
#include <stdlib.h>
#include <string.h>
#include <math.h>

#if __cplusplus
#   include <complex>
typedef std::complex< double > cplx;
#else
#   include <complex.h>
#if defined(__GNUC__) || defined(__GNUG__)
typedef double complex cplx;
#elif defined(_MSC_VER)
typedef _Dcomplex cplx;
#endif
#endif

#ifndef CMPLX
#define CMPLX(x, y) ((cplx)((double)(x) + _Imaginary_I * (double)(y)))
#endif

#include "helper_functions.h"

void twiddles(cplx a[], int size)
{

    double PI = 3.14159265359;

    for (int i = 0; i < size; i++) {
        // cplx tmp = { 0, -PI * i / size };
        #if defined(__GNUC__) || defined(__GNUG__)
	    cplx tmp = 0.0  - PI * i / size * I;
        #elif defined(_MSC_VER)
	    cplx tmp = {0.0, -PI * i / size };
        #endif
        a[i] = cexp(tmp);
        //a[i] = cexp(-I * M_PI * i / size);
    }
}

static void _fft(cplx a[], cplx out[], int size, int step, cplx tw[])
{   
    if (step < size) {
        _fft(out, a, size, step * 2, tw);
        _fft(out + step, a + step, size, step * 2, tw);

        for (int i = 0; i < size; i += 2 * step) {
            //cplx t = tw[i] * out[i + step];
            cplx t = _Cmulcc(tw[i], out[i + step]);
            a[i / 2] = _Caddcc(out[i], t);
            a[(i + size) / 2] = _Cminuscc(out[i], t);
        }
    }
}

void fft(cplx a[], int size, cplx tw[])
{
    cplx * out = malloc(size * sizeof(cplx));
    memcpy(out, a, size * sizeof(cplx));
    _fft(a, out, size, 1, tw);
    free(out);
}


================================================
FILE: C/fft.h
================================================
#ifndef FFT_H
#define FFT_H
//#include <complex.h>

#if __cplusplus
#   include <complex>
    typedef std::complex< double > cplx;
#else
#   include <complex.h>
#if defined(__GNUC__) || defined(__GNUG__)
typedef double complex cplx;
#elif defined(_MSC_VER)
typedef _Dcomplex cplx;
#endif
#endif

#include <stdlib.h>
#include <string.h>
#ifndef CMPLX
#define CMPLX(x, y) ((cplx)((double)(x) + _Complex_I * (double)(y)))
#endif
extern void twiddles(cplx a[], int size);
// extern void _fft(cplx a[], cplx out[], int size, int step, cplx tw[]);
extern void fft(cplx a[], int size, cplx tw[]);
extern void ifft(cplx a[], int size, cplx tw[]);
#endif


================================================
FILE: C/helper_functions.c
================================================
#if __cplusplus
#   include <complex>
typedef std::complex< double > cplx;
#else
#   include <complex.h>
#if defined(__GNUC__) || defined(__GNUG__)
typedef double complex cplx;
#elif defined(_MSC_VER)
typedef _Dcomplex cplx;
#endif
#endif

#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "stats.h"

// compare function for qsort, for array of doubles
static int compare (const void * a, const void * b)
{
    if (*(double*)a < *(double*)b) {
        return -1;
    } else if (*(double*)a > *(double*)b) {
        return 1;
    } else {
        return 0;
    }
}

// wrapper for qsort for array of doubles. Sorts in-place
void sort(double y[], int size)
{
    qsort(y, size, sizeof(*y), compare);
}

// linearly spaced vector
void linspace(double start, double end, int num_groups, double out[])
{
    double step_size = (end - start) / (num_groups - 1);
    for (int i = 0; i < num_groups; i++) {
        out[i] = start;
        start += step_size;
    }
    return;
}

double quantile(const double y[], const int size, const double quant)
{   
    double quant_idx, q, value;
    int idx_left, idx_right;
    double * tmp = malloc(size * sizeof(*y));
    memcpy(tmp, y, size * sizeof(*y));
    sort(tmp, size);
    
    /*
    for(int i=0; i < size; i++){
        printf("y[%i]=%1.4f\n", i, y[i]);
    }
    for(int i=0; i < size; i++){
        printf("sorted[%i]=%1.4f\n", i, tmp[i]);
    }
     */
    
    // out of range limit?
    q = 0.5 / size;
    if (quant < q) {
        value = tmp[0]; // min value
        free(tmp);
        return value; 
    } else if (quant > (1 - q)) {
        value = tmp[size - 1]; // max value
        free(tmp);
        return value; 
    }
    
    quant_idx = size * quant - 0.5;
    idx_left = (int)floor(quant_idx);
    idx_right = (int)ceil(quant_idx);
    value = tmp[idx_left] + (quant_idx - idx_left) * (tmp[idx_right] - tmp[idx_left]) / (idx_right - idx_left);
    free(tmp);
    return value;
}

void binarize(const double a[], const int size, int b[], const char how[])
{   
    double m = 0.0;
    if (strcmp(how, "mean") == 0) {
        m = mean(a, size);
    } else if (strcmp(how, "median") == 0) {
        m = median(a, size);
    }
    for (int i = 0; i < size; i++) {
        b[i] = (a[i] > m) ? 1 : 0;
    }  
    return;
}

double f_entropy(const double a[], const int size)
{
    double f = 0.0;
    for (int i = 0; i < size; i++) {
        if (a[i] > 0) {
            f += a[i] * log(a[i]);
        }
    }
    return -1 * f;
}

void subset(const int a[], int b[], const int start, const int end)
{
    int j = 0;
    for (int i = start; i < end; i++) {
        b[j++] = a[i];
    }
    return;
}

#if defined(__GNUC__) || defined(__GNUG__)
    cplx _Cmulcc(const cplx x, const cplx y) {
        /*double a = x._Val[0];
        double b = x._Val[1];

        double c = y._Val[0];
        double d = y._Val[1];

        cplx result = { (a * c - b * d), (a * d + c * b) };
         */
        return x*y;
    }

    cplx _Cminuscc(const cplx x, const cplx y) {
        //cplx result = { x._Val[0] - y._Val[0], x._Val[1] - y._Val[1] };
        return x - y;
    }

    cplx _Caddcc(const cplx x, const cplx y) {
        // cplx result = { x._Val[0] + y._Val[0], x._Val[1] + y._Val[1] };
        return x + y;
    }

    cplx _Cdivcc(const cplx x, const cplx y) {
        
        double a = creal(x);
        double b = cimag(x);

        double c = creal(y);
        double d = cimag(y);

        cplx result = (a*c + b*d) / (c*c + d*d) + (b*c - a*d)/(c*c + d*d) * I;
        
        return result;
         
        // return x / y;
    }

#elif defined(_MSC_VER)
    cplx _Cminuscc(const cplx x, const cplx y) {
        cplx result = { x._Val[0] - y._Val[0], x._Val[1] - y._Val[1] };
        return result;
    }

    cplx _Caddcc(const cplx x, const cplx y) {
        cplx result = { x._Val[0] + y._Val[0], x._Val[1] + y._Val[1] };
        return result;
    }

    cplx _Cdivcc(const cplx x, const cplx y) {
        double a = x._Val[0];
        double b = x._Val[1];

        double c = y._Val[0];
        double d = y._Val[1];

        cplx result = { (a*c + b*d) / (c*c + d*d), (b*c - a*d)/(c*c + d*d)};

        return result;
    }
#endif


================================================
FILE: C/helper_functions.h
================================================
#ifndef HELPER_FUNCTIONS_H
#define HELPER_FUNCTIONS_H
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "stats.h"

#if __cplusplus
#   include <complex>
typedef std::complex< double > cplx;
#else
#   include <complex.h>
#if defined(__GNUC__) || defined(__GNUG__)
typedef double complex cplx;
#elif defined(_MSC_VER)
typedef _Dcomplex cplx;
#endif
#endif

extern void linspace(double start, double end, int num_groups, double out[]);
extern double quantile(const double y[], const int size, const double quant);
extern void sort(double y[], int size);
extern void binarize(const double a[], const int size, int b[], const char how[]);
extern double f_entropy(const double a[], const int size);
extern void subset(const int a[], int b[], const int start, const int end);

extern cplx _Cminuscc(const cplx x, const cplx y);
extern cplx _Caddcc(const cplx x, const cplx y);
extern cplx _Cdivcc(const cplx x, const cplx y);
#if defined(__GNUC__) || defined(__GNUG__)
extern cplx _Cmulcc(const cplx x, const cplx y);
#endif

#endif


================================================
FILE: C/histcounts.c
================================================
//
//  histcounts.c
//  C_polished
//
//  Created by Carl Henning Lubba on 19/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//

#include <stdlib.h>
#include <float.h>

#include "stats.h"
#include "histcounts.h"

int num_bins_auto(const double y[], const int size){
    
    double maxVal = max_(y, size);
    double minVal = min_(y, size);
    
    if (stddev(y, size) < 0.001){
        return 0;
    }
    
    return ceil((maxVal-minVal)/(3.5*stddev(y, size)/pow(size, 1/3.)));
    
}

int histcounts_preallocated(const double y[], const int size, int nBins, int * binCounts, double * binEdges)
{
    
    int i = 0;
    
    // check min and max of input array
    double minVal = DBL_MAX, maxVal=-DBL_MAX;
    for(int i = 0; i < size; i++)
    {
        // printf("histcountInput %i: %1.3f\n", i, y[i]);
        
        if (y[i] < minVal)
        {
            minVal = y[i];
        }
        if (y[i] > maxVal)
        {
            maxVal = y[i];
        }
    }
    
    // and derive bin width from it
    double binStep = (maxVal - minVal)/nBins;
    
    // variable to store counted occurances in
    for(i = 0; i < nBins; i++)
    {
        binCounts[i] = 0;
    }
    
    for(i = 0; i < size; i++)
    {
        
        int binInd = (y[i]-minVal)/binStep;
        if(binInd < 0)
            binInd = 0;
        if(binInd >= nBins)
            binInd = nBins-1;
        //printf("histcounts, i=%i, binInd=%i, nBins=%i\n", i, binInd, nBins);
        binCounts[binInd] += 1;
        
    }
    
    for(i = 0; i < nBins+1; i++)
    {
        binEdges[i] = i * binStep + minVal;
    }
    
    /*
     // debug
     for(i=0;i<nBins;i++)
     {
     printf("%i: count %i, edge %1.3f\n", i, binCounts[i], binEdges[i]);
     }
     */
    
    return 0;
    
}

int histcounts(const double y[], const int size, int nBins, int ** binCounts, double ** binEdges)
{

    int i = 0;
    
    // check min and max of input array
    double minVal = DBL_MAX, maxVal=-DBL_MAX;
    for(int i = 0; i < size; i++)
    {
        // printf("histcountInput %i: %1.3f\n", i, y[i]);
        
        if (y[i] < minVal)
        {
            minVal = y[i];
        }
        if (y[i] > maxVal)
        {
            maxVal = y[i];
        }
    }
    
    // if no number of bins given, choose spaces automatically
    if (nBins <= 0){
        nBins = ceil((maxVal-minVal)/(3.5*stddev(y, size)/pow(size, 1/3.)));
    }
    
    // and derive bin width from it
    double binStep = (maxVal - minVal)/nBins;
    
    // variable to store counted occurances in
    *binCounts = malloc(nBins * sizeof(int));
    for(i = 0; i < nBins; i++)
    {
        (*binCounts)[i] = 0;
    }
    
    for(i = 0; i < size; i++)
    {
        
        int binInd = (y[i]-minVal)/binStep;
        if(binInd < 0)
            binInd = 0;
        if(binInd >= nBins)
            binInd = nBins-1;
        (*binCounts)[binInd] += 1;
        
    }
    
    *binEdges = malloc((nBins+1) * sizeof(double));
    for(i = 0; i < nBins+1; i++)
    {
        (*binEdges)[i] = i * binStep + minVal;
    }
   
    /*
    // debug
    for(i=0;i<nBins;i++)
    {
        printf("%i: count %i, edge %1.3f\n", i, binCounts[i], binEdges[i]);
    }
    */
    
    return nBins;
    
}

int * histbinassign(const double y[], const int size, const double binEdges[], const int nEdges)
{
    
    
    // variable to store counted occurances in
    int * binIdentity = malloc(size * sizeof(int));
    for(int i = 0; i < size; i++)
    {
        // if not in any bin -> 0
        binIdentity[i] = 0;
        
        // go through bin edges
        for(int j = 0; j < nEdges; j++){
            if(y[i] < binEdges[j]){
                binIdentity[i] = j;
                break;
            }
        }
    }
    
    return binIdentity;
    
}

int * histcount_edges(const double y[], const int size, const double binEdges[], const int nEdges)
{
    
    
    int * histcounts = malloc(nEdges * sizeof(int));
    for(int i = 0; i < nEdges; i++){
        histcounts[i] = 0;
    }
    
    for(int i = 0; i < size; i++)
    {
        // go through bin edges
        for(int j = 0; j < nEdges; j++){
            if(y[i] <= binEdges[j]){
                histcounts[j] += 1;
                break;
            }
        }
    }
    
    return histcounts;
    
}


================================================
FILE: C/histcounts.h
================================================
//
//  histcounts.h
//  C_polished
//
//  Created by Carl Henning Lubba on 19/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//

#ifndef histcounts_h
#define histcounts_h

#include <stdlib.h>
#include <float.h>
#include <stdio.h>

extern int num_bins_auto(const double y[], const int size);
extern int histcounts(const double y[], const int size, int nBins, int ** binCounts, double ** binEdges);
extern int histcounts_preallocated(const double y[], const int size, int nBins, int * binCounts, double * binEdges);
extern int * histcount_edges(const double y[], const int size, const double binEdges[], const int nEdges);
extern int * histbinassign(const double y[], const int size, const double binEdges[], const int nEdges);

#endif /* histcounts_h */


================================================
FILE: C/main.c
================================================
/* Include files */
#include "main.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//#include <dirent.h>

#include "DN_HistogramMode_5.h"
#include "DN_HistogramMode_10.h"
#include "DN_Mean.h"
#include "DN_Spread_Std.h"
#include "CO_AutoCorr.h"
#include "DN_OutlierInclude.h"
#include "FC_LocalSimple.h"
#include "IN_AutoMutualInfoStats.h"
#include "MD_hrv.h"
#include "SB_BinaryStats.h"
#include "SB_MotifThree.h"
#include "SC_FluctAnal.h"
#include "SP_Summaries.h"
#include "SB_TransitionMatrix.h"
#include "PD_PeriodicityWang.h"

#include "stats.h"

// check if data qualifies to be caught22
int quality_check(const double y[], const int size)
{
    int minSize = 10;

    if(size < minSize)
    {
        return 1;
    }
    for(int i = 0; i < size; i++)
    {
        double val = y[i];
        if(val == INFINITY || -val == INFINITY)
        {
            return 2;
        }
        if(isnan(val))
        {
            return 3;
        }
    }
    return 0;
}

void run_features(double y[], int size, FILE * outfile, bool catch24)
{
    int quality = quality_check(y, size);
    if(quality != 0)
    {
        fprintf(stdout, "Time series quality test not passed (code %i).\n", quality);
        return;
    }

    double * y_zscored = malloc(size * sizeof * y_zscored);

    // variables to keep time
    clock_t begin;
    double timeTaken;

    // output
    double result;

    // z-score first for all.
    zscore_norm2(y, size, y_zscored);

    // GOOD
    begin = clock();
    result = DN_OutlierInclude_n_001_mdrmd(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "DN_OutlierInclude_n_001_mdrmd", timeTaken);

    // GOOD
    begin = clock();
    result = DN_OutlierInclude_p_001_mdrmd(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "DN_OutlierInclude_p_001_mdrmd", timeTaken);
  
    // GOOD
    begin = clock();
    result = DN_HistogramMode_5(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "DN_HistogramMode_5", timeTaken);

    // GOOD
    begin = clock();
    result = DN_HistogramMode_10(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "DN_HistogramMode_10", timeTaken);

    //GOOD
    begin = clock();
    result = CO_Embed2_Dist_tau_d_expfit_meandiff(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "CO_Embed2_Dist_tau_d_expfit_meandiff", timeTaken);

    //GOOD (memory leak?)
    begin = clock();
    result = CO_f1ecac(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "CO_f1ecac", timeTaken);

    //GOOD
    begin = clock();
    result = CO_FirstMin_ac(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "CO_FirstMin_ac", timeTaken);

    // GOOD (memory leak?)
    begin = clock();
    result = CO_HistogramAMI_even_2_5(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "CO_HistogramAMI_even_2_5", timeTaken);

    // GOOD
    begin = clock();
    result = CO_trev_1_num(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "CO_trev_1_num", timeTaken);

    //GOOD
    begin = clock();
    result = FC_LocalSimple_mean1_tauresrat(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "FC_LocalSimple_mean1_tauresrat", timeTaken);

    //GOOD
    begin = clock();
    result = FC_LocalSimple_mean3_stderr(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "FC_LocalSimple_mean3_stderr", timeTaken);

    //GOOD (memory leak?)
    begin = clock();
    result = IN_AutoMutualInfoStats_40_gaussian_fmmi(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "IN_AutoMutualInfoStats_40_gaussian_fmmi", timeTaken);

    //GOOD
    begin = clock();
    result = MD_hrv_classic_pnn40(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "MD_hrv_classic_pnn40", timeTaken);

    //GOOD
    begin = clock();
    result = SB_BinaryStats_diff_longstretch0(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "SB_BinaryStats_diff_longstretch0", timeTaken);

    //GOOD
    begin = clock();
    result = SB_BinaryStats_mean_longstretch1(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "SB_BinaryStats_mean_longstretch1", timeTaken);

    //GOOD (memory leak?)
    begin = clock();
    result = SB_MotifThree_quantile_hh(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "SB_MotifThree_quantile_hh", timeTaken);

    //GOOD (memory leak?)
    begin = clock();
    result = SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1", timeTaken);

    //GOOD
    begin = clock();
    result = SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1", timeTaken);

    //GOOD
    begin = clock();
    result = SP_Summaries_welch_rect_area_5_1(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "SP_Summaries_welch_rect_area_5_1", timeTaken);

    //GOOD
    begin = clock();
    result = SP_Summaries_welch_rect_centroid(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "SP_Summaries_welch_rect_centroid", timeTaken);

    //OK, BUT filt in Butterworth sometimes diverges, now removed alltogether, let's see results.
    begin = clock();
    result = SB_TransitionMatrix_3ac_sumdiagcov(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "SB_TransitionMatrix_3ac_sumdiagcov", timeTaken);

    // GOOD
    begin = clock();
    result = PD_PeriodicityWang_th0_01(y_zscored, size);
    timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
    fprintf(outfile, "%.14f, %s, %f\n", result, "PD_PeriodicityWang_th0_01", timeTaken);

    if (catch24) {
        
        // GOOD
        begin = clock();
        result = DN_Mean(y, size);
        timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
        fprintf(outfile, "%.14f, %s, %f\n", result, "DN_Mean", timeTaken);

        // GOOD
        begin = clock();
        result = DN_Spread_Std(y, size);
        timeTaken = (double)(clock()-begin)*1000/CLOCKS_PER_SEC;
        fprintf(outfile, "%.14f, %s, %f\n", result, "DN_Spread_Std", timeTaken);
    } else {

    }
  
    fprintf(outfile, "\n");

    free(y_zscored);
}

void print_help(char *argv[], char msg[])
{
    if (strlen(msg) > 0) {
        fprintf(stdout, "ERROR: %s\n", msg);
    }
    fprintf(stdout, "Usage is %s <infile> <outfile>\n", argv[0]);
    fprintf(stdout, "\n\tSpecifying outfile is optional, by default it is stdout\n");
    // fprintf(stdout, "\tOutput order is:\n%s\n", HEADER);
    exit(1);
}

// memory leak check; use with valgrind.
#if 0
int main(int argc, char * argv[])
{
    double * y = malloc(1000 * sizeof(double));

    srand(42);
    for (int i = 0; i < 1000; ++i) {
        y[i] = rand() % RAND_MAX;
    }
    run_features(y, 1000, stdout);
    free(y);
}
#endif

#if 1
int main(int argc, char * argv[])
{
    FILE * infile, * outfile;
    int array_size;
    double * y;
    int size;
    double value;
    // DIR *d;
    struct dirent *dir;


    switch (argc) {
        case 1:
            print_help(argv, "");
            break;
        case 2:
            if ((infile = fopen(argv[1], "r")) == NULL) {
                print_help(argv, "Can't open input file\n");
            }
            outfile = stdout;
            break;
        case 3:
            if ((infile = fopen(argv[1], "r")) == NULL) {
                print_help(argv, "Can't open input file\n");
            }
            if ((outfile = fopen(argv[2], "w")) == NULL) {
                print_help(argv, "Can't open output file\n");
            }
            break;
    }

    /*
    // debug: fix these.
    infile = fopen("/Users/carl/PycharmProjects/catch22/C/timeSeries/tsid0244.txt", "r");
    outfile = stdout;
     */

    // fprintf(outfile, "%s", HEADER);
    array_size = 50;
    size = 0;
    y = malloc(array_size * sizeof *y);

    while (fscanf(infile, "%lf", &value) != EOF) {
        if (size == array_size) {
            y = realloc(y, 2 * array_size * sizeof *y);
            array_size *= 2;
        }
        y[size++] = value;
    }
    fclose(infile);
    y = realloc(y, size * sizeof *y);
    //printf("size=%i\n", size);

    // catch24 specification

    int catch24;
    printf("Do you want to run catch24? Enter 0 for catch22 or 1 for catch24.");
    scanf("%d", &catch24);

    if (catch24 == 1) {
        run_features(y, size, outfile, true);
    } else {
        run_features(y, size, outfile, false);
    }

    fclose(outfile);
    free(y);

    return 0;
}
#endif

#if 0
int main(int argc, char * argv[])
{
  (void)argc;
  (void)argv;

    /*
    // generate some data
    const int size = 31; // 211;

    double y[size];
    int i;
    double sinIn=0;
    for(i=0; i<size; i++)
    {
        sinIn = (double)(i-10)/10*6;
        y[i] = sin(sinIn);
        printf("%i: sinIn=%1.3f, sin=%1.3f\n", i, sinIn, y[i]);
    }*/

    // open a certain file
    FILE * infile;
    infile = fopen("C:\\Users\\Carl\\Documents\\catch22-master\\testData\\test.txt", "r");
    int array_size = 15000;
    double * y = malloc(array_size * sizeof(double));
    int size = 0;
    double value = 0;
    while (fscanf(infile, "%lf", &value) != EOF) {
        y[size++] = value;
    }

    // first, z-score.
    zscore_norm(y, size);

    double result;
  
    result = DN_OutlierInclude_n_001_mdrmd(y, size);
    printf("DN_OutlierInclude_n_001_mdrmd: %1.5f\n", result);
    result = DN_OutlierInclude_p_001_mdrmd(y, size);
    printf("DN_OutlierInclude_p_001_mdrmd: %1.5f\n", result);
    result = DN_HistogramMode_5(y, size);
    printf("DN_HistogramMode_5: %1.3f\n", result);
    result = DN_HistogramMode_10(y, size);
    printf("DN_HistogramMode_10: %1.3f\n", result);
    result = SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1(y, size);
    printf("SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1: %1.5f\n", result);
    result = SB_TransitionMatrix_3ac_sumdiagcov(y, size);
    printf("SB_TransitionMatrix_3ac_sumdiagcov: %1.5f\n", result);
    result = FC_LocalSimple_mean1_tauresrat(y, size);
    printf("FC_LocalSimple_mean1_tauresrat: %1.5f\n", result);
    result = SB_MotifThree_quantile_hh(y, size);
    printf("SB_MotifThree_quantile_hh: %1.5f\n", result);
    result = CO_HistogramAMI_even_2_5(y, size);
    printf("CO_HistogramAMI_even_2_5: %1.3f\n", result);
    result = CO_Embed2_Dist_tau_d_expfit_meandiff(y, size);
    printf("CO_Embed2_Dist_tau_d_expfit_meandiff: %1.3f\n", result);
    result = SB_BinaryStats_diff_longstretch0(y, size);
    printf("SB_BinaryStats_diff_longstretch0: %1.5f\n", result);
    result = MD_hrv_classic_pnn40(y, size);
    printf("MD_hrv_classic_pnn40: %1.5f\n", result);
    result = SB_BinaryStats_mean_longstretch1(y, size);
    printf("SB_BinaryStats_mean_longstretch1: %1.5f\n", result);
    result = FC_LocalSimple_mean3_stderr(y, size);
    printf("FC_LocalSimple_mean3_stderr: %1.5f\n", result);
    result = SP_Summaries_welch_rect_area_5_1(y, size);
    printf("SP_Summaries_welch_rect_area_5_1: %1.5f\n", result);
    result = SP_Summaries_welch_rect_centroid(y, size);
    printf("SP_Summaries_welch_rect_centroid: %1.5f\n", result);
    result = CO_f1ecac(y, size);
    printf("CO_f1ecac: %1.f\n", result);
    result = CO_FirstMin_ac(y, size);
    printf("CO_FirstMin_ac: %1.f\n", result);
    result = IN_AutoMutualInfoStats_40_gaussian_fmmi(y, size);
    printf("IN_AutoMutualInfoStats_40_gaussian_fmmi: %1.5f\n", result);
    result = PD_PeriodicityWang_th0_01(y, size);
    printf("PD_PeriodicityWang_th0_01: %1.f\n", result);
    result = SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1(y, size);
    printf("SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1: %1.5f\n", result);
    result = CO_trev_1_num(y, size);
    printf("CO_trev_1_num: %1.5f\n", result);

    int catch24;
    printf("Do you want to run catch24? Enter 0 for catch22 or 1 for catch24.");
    scanf("%d", &catch24);

    if (catch24 == 1) {
        result = DN_Mean(y, size);
        printf("DN_Mean: %1.5f\n", result);
        result = DN_Spread_Std(y, size);
        printf("DN_Spread_Std: %1.5f\n", result);
    } else {
    }

  return 0;
}
#endif


================================================
FILE: C/main.h
================================================
#ifndef MAIN_H
#define MAIN_H

/* Include files */
#include <math.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

/* Function Declarations */
//extern int main(int argc, const char * const argv[]);
extern int main(int argc, char * argv[]);

#endif

/* End of code generation (main.h) */


================================================
FILE: C/runAllTS.sh
================================================
#!/bin/bash

help()
{
   echo ""
   echo "Usage: $0 -i indir -o outdir -a append_string -s"
   echo -e "\t-h Show this help message"
   echo -e "\t-i Path to a directory containing input time-series files (.txt with one time series value per line). Default: './timeSeries'"
   echo -e "\t-o Path to a directory in which to save output feature values. Default: './featureOutput'"
   echo -e "\t-a A string (minus extension) appended to the input file names to create the output file names. Default: 'output'"
   echo -e "\t-s A switch to evaluate catch22 (0) or catch24 (1). Default: 0"
   exit 1
}

while getopts "i:o:a:s:h" opt
do
   case "$opt" in
      i) indir="$OPTARG" ;;
      o) outdir="$OPTARG" ;;
      a) append="$OPTARG" ;;
      s) catch24="$OPTARG" ;;
      h) help ;;
   esac
done

srcdir=$(dirname "$0}")

if [ -z "$indir" ]
then
   indir="./timeSeries"
fi

if [ -z "$outdir" ]
then
   outdir="./featureOutput"
fi

if [ -z "$append" ]
then
   append="output"
fi

if [ -z "$catch24" ]
then
   catch24=0
fi

indir="$(dirname $indir)/$(basename $indir)"
outdir="$(dirname $outdir)/$(basename $outdir)"
mkdir -p $outdir

# Loop through each file in indir and save the feature outputs
for entry in "${indir}"/*.txt
do
    filename=$(basename "$entry")
    extension="${filename##*.}"
    filename="${filename%.*}"
    fullfile="${outdir}/${filename}${append}.${extension}"
    if [ "${filename: -${#append}}" != "${append}" ]
    then
        yes $catch24 | "${srcdir}/run_features" $entry $fullfile > /dev/null

        if [ -s $fullfile ] # Remove file if catch22 errors
        then
            echo "Output written to ${fullfile}"
        else
            rm $fullfile
        fi

    fi
done


================================================
FILE: C/splinefit.c
================================================
//  Created by Carl Henning Lubba on 27/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//
// Based on the work of Jonas Lundgren in his Matlab Central contribution 'SPLINEFIT'.
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "splinefit.h"
#include "stats.h"

#define nCoeffs 3
#define nPoints 4

#define pieces 2
#define nBreaks 3
#define deg 3
#define nSpline 4
#define piecesExt 8 //3 * deg - 1


void matrix_multiply(const int sizeA1, const int sizeA2, const double *A, const int sizeB1, const int sizeB2, const double *B, double *C){
//void matrix_multiply(int sizeA1, int sizeA2, double **A, int sizeB1, int sizeB2, double **B, double C[sizeA1][sizeB2]){
    
    if(sizeA2 != sizeB1){
        return;
    }
    
    /*
    // show input
    for(int i = 0; i < sizeA1; i++){
        for(int j = 0; j < sizeA2; j++){
            printf("A[%i][%i] = %1.3f\n", i, j, A[i*sizeA2 + j]);
        }
    }
     */
    
    for(int i = 0; i < sizeA1; i++){
        for(int j = 0; j < sizeB2; j++){
            
            //C[i][j] = 0;
            C[i*sizeB2 + j] = 0;
            for(int k = 0; k < sizeB1; k++){
                // C[i][j] += A[i][k]*B[k][j];
                C[i*sizeB2 + j] += A[i * sizeA2 + k]*B[k * sizeB2 + j];
                //printf("C[%i][%i] (k=%i) = %1.3f\n", i, j, k, C[i * sizeB2 + j]);
            }
            
        }
    }
    
}

void matrix_times_vector(const int sizeA1, const int sizeA2, const double *A, const int sizeb, const double *b, double *c){ //c[sizeb]
    
    if(sizeA2 != sizeb){
        return;
    }
    
    // row
    for(int i = 0; i < sizeA1; i++){
        
        // column
        c[i] = 0;
        for(int k = 0; k < sizeb; k++){
            c[i] += A[i * sizeA2 + k]*b[k];
        }
        
    }
    
}

void gauss_elimination(int size, double *A, double *b, double *x){
// void gauss_elimination(int size, double A[size][size], double b[size], double x[size]){
    
    double factor;
    
    // create temp matrix and vector
    // double *AElim[size];
    double* AElim[nSpline + 1];
    for (int i = 0; i < size; i++)
        AElim[i] = (double *)malloc(size * sizeof(double));
    double * bElim = malloc(size * sizeof(double));
    
    // -- create triangular matrix
    
    // initialise to A and b
    for(int i = 0; i < size; i++){
        for(int j = 0; j < size; j++){
            AElim[i][j] = A[i*size + j];
        }
        bElim[i] = b[i];
    }
    
    /*
    printf("AElim\n");
    for(int i = 0; i < size; i++){
        for(int j = 0; j < size; j++){
            printf("%1.3f, ", AElim[i][j]);
        }
        printf("\n");
    }
     */
    
    // go through columns in outer loop
    for(int i = 0; i < size; i++){
    
        // go through rows to eliminate
        for(int j = i+1; j < size; j++){
            
            factor = AElim[j][i]/AElim[i][i];
            
            // subtract in vector
            bElim[j] = bElim[j] - factor*bElim[i];
            
            // go through entries of this row
            for(int k = i; k < size; k++){
                AElim[j][k] = AElim[j][k] - factor*AElim[i][k];
            }
            
            /*
            printf("AElim i=%i, j=%i\n", i, j);
            for(int i = 0; i < size; i++){
                for(int j = 0; j < size; j++){
                    printf("%1.3f, ", AElim[i][j]);
                }
                printf("\n");
            }
             */
            
        }
        
    }
    
    /*
    for(int i = 0; i < size; i++){
        for(int j = 0; j < size; j++){
            printf("AElim[%i][%i] = %1.3f\n", i, j, AElim[i][j]);
        }
    }
    for(int i = 0; i < size; i++){
        printf("bElim[%i] = %1.3f\n", i, bElim[i]);
    }
     */
    
    
    // -- go backwards through triangular matrix and solve for x
    
    // row
    double bMinusATemp;
    for(int i = size-1; i >= 0; i--){
        
        bMinusATemp = bElim[i];
        for(int j = i+1; j < size; j++){
            bMinusATemp -= x[j]*AElim[i][j];
        }
        
        x[i] = bMinusATemp/AElim[i][i];
    }
    /*
    for(int j = 0; j < size; j++){
        printf("x[%i] = %1.3f\n", j, x[j]);
    }
     */
    
    for (int i = 0; i < size; i++)
        free(AElim[i]);
    free(bElim);
}

void lsqsolve_sub(const int sizeA1, const int sizeA2, const double *A, const int sizeb, const double *b, double *x)
//void lsqsolve_sub(int sizeA1, int sizeA2, double A[sizeA1][sizeA2], int sizeb, double b[sizeb], double x[sizeA1])
{
    // create temp matrix and vector
    /*
    double *AT[sizeA1*sizeA2];
    for (int i = 0; i < sizeA2; i++)
        AT[i] = (double *)malloc(sizeA1 * sizeof(double));
    double *ATA[sizeA2];
    for (int i = 0; i < sizeA2; i++)
        ATA[i] = (double *)malloc(sizeA2 * sizeof(double));
    double * ATb = malloc(sizeA1 * sizeof(double));
     */
    
    double * AT = malloc(sizeA2 * sizeA1 * sizeof(double));
    double * ATA = malloc(sizeA2 * sizeA2 * sizeof(double));
    double * ATb = malloc(sizeA2 * sizeof(double));
    
    
    for(int i = 0; i < sizeA1; i++){
        for(int j = 0; j < sizeA2; j++){
            //AT[i,j] = A[j,i]
            AT[j * sizeA1 + i] = A[i * sizeA2 + j];
        }
    }
    
    /*
    printf("\n b \n");
    for(int i = 0; i < sizeA1; i++){
        printf("%i, %1.3f\n", i, b[i]);
    }
     */
    
    /*
    printf("\nA\n");
     for(int i = 0; i < sizeA2; i++){
         for(int j = 0; j < sizeA1; j++){
             printf("%1.3f, ", AT[i * sizeA1 + j]);
         }
         printf("\n");
     }
     */
     
    
    matrix_multiply(sizeA2, sizeA1, AT, sizeA1, sizeA2, A, ATA);
    
    /*
    printf("ATA\n");
    for(int i = 0; i < sizeA2; i++){
        for(int j = 0; j < sizeA2; j++){
            printf("%1.3f, ", ATA[i * sizeA2 + j]);
        }
        printf("\n");
    }
     */
    
    
    
    matrix_times_vector(sizeA2, sizeA1, AT, sizeA1, b, ATb);
    
    /*
    for(int i = 0; i < sizeA2; i++){
        ATb[i] = 0;
        for(int j = 0; j < sizeA1; j++){
            ATb[i] += AT[i*sizeA1 + j]*b[j];
            //printf("%i, ATb[%i]=%1.3f, AT[i*sizeA1 + j]=%1.3f, b[j]=%1.3f\n", i, i, ATb[i], AT[i*sizeA1 + j],b[j]);
        }
    }
     */
    
    /*
     for(int i = 0; i < nCoeffs; i++){
     printf("b[%i] = %1.3f\n", i, b[i]);
     }
     */
    
    /*
    for(int i = 0; i < sizeA2; i++){
        printf("ATb[%i] = %1.3f\n", i, ATb[i]);
    }
     */
    
    
    gauss_elimination(sizeA2, ATA, ATb, x);
    
    free(AT);
    free(ATA);
    free(ATb);
    
}

/*
int lsqsolve()
{
    //const int nPoints = 4;
    //const int nCoeffs = 3;
    
    //double A[nPoints][nCoeffs] = {};
	double A[4][3];
    A[0][0] = 1;
    A[1][0] = 3;
    A[2][0] = 6;
    A[3][0] = 8;
    A[0][1] = 4;
    A[1][1] = 5;
    A[2][1] = 3;
    A[3][1] = 12;
    A[0][2] = 4;
    A[1][2] = 1;
    A[2][2] = 0;
    A[3][2] = 7;
    //double b[nPoints] = {};
	double b[4];
    b[0] = 2;
    b[1] = 8;
    b[2] = 3;
    b[3] = 1;
    
    double x[4];
    
    double * Alin = malloc(nPoints * nCoeffs * sizeof(double));
    
    for(int i = 0; i < nPoints; i++){
        for(int j = 0; j < nCoeffs; j++){
            //AT[i,j] = A[j,i]
            Alin[i * nCoeffs + j] = A[i][j];
        }
    }
    
    lsqsolve_sub(nPoints, nCoeffs, Alin, nPoints, b, x);
    
    free(Alin);
    
    return 0;
    
    
}
*/

int iLimit(int x, int lim){
    return x<lim ? x : lim;
}

int splinefit(const double *y, const int size, double *yOut)
{
    // degree of spline
    //const int nSpline = 4;
    //const int deg = 3;
    
    // x-positions of spline-nodes
    //const int nBreaks = 3;
    int breaks[nBreaks];
    breaks[0] = 0;
    breaks[1] = (int)floor((double)size/2.0)-1;
    breaks[2] = size-1;
    
    // -- splinebase
    
    // spacing
    int h0[2];
    h0[0] = breaks[1] - breaks[0];
    h0[1] = breaks[2] - breaks[1];
    
    //const int pieces = 2;
    
    // repeat spacing
    int hCopy[4];
    hCopy[0] = h0[0], hCopy[1] = h0[1], hCopy[2] = h0[0], hCopy[3] = h0[1];
    
    // to the left
    int hl[deg];
    hl[0] = hCopy[deg-0];
    hl[1] = hCopy[deg-1];
    hl[2] = hCopy[deg-2];
    
    int hlCS[deg]; // cumulative sum
    icumsum(hl, deg, hlCS);
    
    int bl[deg];
    for(int i = 0; i < deg; i++){
        bl[i] = breaks[0] - hlCS[i];
    }
    
    // to the left
    int hr[deg];
    hr[0] = hCopy[0];
    hr[1] = hCopy[1];
    hr[2] = hCopy[2];
    
    int hrCS[deg]; // cumulative sum
    icumsum(hr, deg, hrCS);
    
    int br[deg];
    for(int i = 0; i < deg; i++){
        br[i] = breaks[2] + hrCS[i];
    }
    
    // add breaks
    int breaksExt[3*deg];
    for(int i = 0; i < deg; i++){
        breaksExt[i] = bl[deg-1-i];
        breaksExt[i + 3] = breaks[i];
        breaksExt[i + 6] = br[i];
    }
    int hExt[3*deg-1];
    for(int i = 0; i < deg*3-1; i++){
        hExt[i] = breaksExt[i+1] - breaksExt[i];
    }
    //const int piecesExt = 3*deg-1;
    
    // initialise polynomial coefficients
    double coefs[nSpline*piecesExt][nSpline+1];
    for(int i = 0; i < nSpline*piecesExt; i++){
        for(int j = 0; j < nSpline; j++){
        coefs[i][j] = 0;
        }
    }
    for(int i = 0; i < nSpline*piecesExt; i=i+nSpline){
        coefs[i][0] = 1;
    }
    
    // expand h using the index matrix ii
    int ii[deg+1][piecesExt];
    for(int i = 0; i < piecesExt; i++){
        ii[0][i] = iLimit(0+i, piecesExt-1);
        ii[1][i] = iLimit(1+i, piecesExt-1);
        ii[2][i] = iLimit(2+i, piecesExt-1);
        ii[3][i] = iLimit(3+i, piecesExt-1);
    }
    
    // expanded h
    double H[(deg+1)*piecesExt];
    int iiFlat;
    for(int i = 0; i < nSpline*piecesExt; i++){
        iiFlat = ii[i%nSpline][i/nSpline];
        H[i] = hExt[iiFlat];
    }
    
    //recursive generation of B-splines
    double Q[nSpline][piecesExt];
    for(int k = 1; k < nSpline; k++){
        
        //antiderivatives of splines
        for(int j = 0; j<k; j++){
            for(int l = 0; l<(nSpline*piecesExt); l++){
                coefs[l][j] *= H[l]/(k-j);
                //printf("coefs[%i][%i]=%1.3f\n", l, j, coefs[l][j]);
            }
        }
        
        for(int l = 0; l<(nSpline*piecesExt); l++){
            Q[l%nSpline][l/nSpline] = 0;
            for(int m = 0; m < nSpline; m++){
                Q[l%nSpline][l/nSpline] += coefs[l][m];
            }
        }
        
        /*
        printf("\nQ:\n");
        for(int i = 0; i < n; i++){
            for(int j = 0; j < piecesExt; j ++){
                printf("%1.3f, ", Q[i][j]);
            }
            printf("\n");
        }
        */
        
        //cumsum
        for(int l = 0; l<piecesExt; l++){
            for(int m = 1; m < nSpline; m++){
                Q[m][l] += Q[m-1][l];
            }
        }
        
        /*
        printf("\nQ cumsum:\n");
        for(int i = 0; i < n; i++){
            for(int j = 0; j < piecesExt; j ++){
                printf("%1.3f, ", Q[i][j]);
            }
            printf("\n");
        }
        */
        
        for(int l = 0; l<nSpline*piecesExt; l++){
            if(l%nSpline == 0)
                coefs[l][k] = 0;
            else{
                coefs[l][k] = Q[l%nSpline-1][l/nSpline]; // questionable
            }
            // printf("coefs[%i][%i]=%1.3f\n", l, k, coefs[l][k]);
        }
        
        // normalise antiderivatives by max value
        double fmax[piecesExt*nSpline];
        for(int i = 0; i < piecesExt; i++){
            for(int j = 0; j < nSpline; j++){
                
                fmax[i*nSpline+j] = Q[nSpline-1][i];
                
            }
        }
        
        /*
        printf("\n fmax:\n");
        for(int i = 0; i < piecesExt*n; i++){
            printf("%1.3f, \n", fmax[i]);
        }
        */
        
        for(int j = 0; j < k+1; j++){
            for(int l = 0; l < nSpline*piecesExt; l++){
                coefs[l][j] /= fmax[l];
                // printf("coefs[%i][%i]=%1.3f\n", l, j, coefs[l][j]);
            }
        }

        // diff to adjacent antiderivatives
        for(int i = 0; i < (nSpline*piecesExt)-deg; i++){
            for(int j = 0; j < k+1; j ++){
                coefs[i][j] -= coefs[deg+i][j];
                //printf("coefs[%i][%i]=%1.3f\n", i, j, coefs[i][j]);
            }
        }
        for(int i = 0; i < nSpline*piecesExt; i += nSpline){
            coefs[i][k] = 0;
        }
        
        /*
        printf("\ncoefs:\n");
        for(int i = 0; i < (n*piecesExt); i++){
            for(int j = 0; j < n; j ++){
                printf("%1.3f, ", coefs[i][j]);
            }
            printf("\n");
        }
        */
        
    }
    
    // scale coefficients
    double scale[nSpline*piecesExt];
    for(int i = 0; i < nSpline*piecesExt; i++)
    {
        scale[i] = 1;
    }
    for(int k = 0; k < nSpline-1; k++){
        for(int i = 0; i < (nSpline*piecesExt); i++){
            scale[i] /= H[i];
        }
        for(int i = 0; i < (nSpline*piecesExt); i++){
            coefs[i][(nSpline-1)-(k+1)] *= scale[i];
        }
    }
    
    /*
    printf("\ncoefs scaled:\n");
    for(int i = 0; i < (n*piecesExt); i++){
        for(int j = 0; j < n; j ++){
            printf("%1.4f, ", coefs[i][j]);
        }
        printf("\n");
    }
    */
    
    // reduce pieces and sort coefficients by interval number
    int jj[nSpline][pieces];
    for(int i = 0; i < nSpline; i++){
        for(int j = 0; j < pieces; j++){
            if(i == 0)
                jj[i][j] = nSpline*(1+j);
            else
                jj[i][j] = deg;
        }
    }
    
    /*
    printf("\n jj\n");
    for(int i = 0; i < n; i++){
        for(int j = 0; j < pieces; j++){
            printf("%i, ", jj[i][j]);
        }
        printf("\n");
    }
    */
        
    
    for(int i = 1; i < nSpline; i++){
        for(int j = 0; j < pieces; j++){
            jj[i][j] += jj[i-1][j];
        }
    }
    
    /*
    printf("\n jj cumsum\n");
    for(int i = 0; i < n; i++){
        for(int j = 0; j < pieces; j++){
            printf("%i, ", jj[i][j]);
        }
        printf("\n");
    }
    */
    
    double coefsOut[nSpline*pieces][nSpline];
    int jj_flat;
    for(int i = 0; i < nSpline*pieces; i++){
        jj_flat = jj[i%nSpline][i/nSpline]-1;
        //printf("jj_flat(%i) = %i\n", i, jj_flat);
        for(int j = 0; j < nSpline; j++){
            coefsOut[i][j] = coefs[jj_flat][j];
            //printf("coefsOut[%i][%i]=%1.3f\n", i, j, coefsOut[i][j]);
        }
        
    }
    
    /*
    printf("\n coefsOut * 1000\n");
    for(int i = 0; i < n*pieces; i++){
        for(int j = 0; j < n; j++){
            printf("%1.3f, ", coefsOut[i][j]*1000);
        }
        printf("\n");
    }
     */
    
    
    // -- create first B-splines to feed into optimization
    
    // x-values for B-splines
    int * xsB = malloc((size*nSpline)* sizeof(int));
    int * indexB = malloc((size*nSpline) * sizeof(int));
    
    int breakInd = 1;
    for(int i = 0; i < size; i++){
        if(i >= breaks[breakInd] & breakInd<nBreaks-1)
            breakInd += 1;
        for(int j = 0; j < nSpline; j++){
            xsB[i*nSpline+j] = i - breaks[breakInd-1];
            indexB[i*nSpline+j] = j + (breakInd-1)*nSpline;
        }
    }
    
    /*
    printf("\nxsB\n");
    for(int i = 0; i < size*n; i++){
        printf("%i, %i\n", i, xsB[i]);
    }
    printf("\nindexB\n");
    for(int i = 0; i < size*n; i++){
        printf("%i, %i\n", i, indexB[i]);
    }
     */
    
    double * vB = malloc((size*nSpline) * sizeof(double));
    for(int i = 0; i < size*nSpline; i++){
        vB[i] = coefsOut[indexB[i]][0];
    }
    
    /*
    printf("\nvB first iteration\n");
    for(int i = 0; i < size*n; i++){
        printf("%i, %1.4f\n", i, vB[i]);
    }
     */
    
    for(int i = 1; i < nSpline; i ++){
        for(int j = 0; j < size*nSpline; j++){
            vB[j] = vB[j]*xsB[j] + coefsOut[indexB[j]][i];
        }
        /*
        printf("\nvB k=%i\n", i+1);
        for(int i = 0; i < size*n; i++){
            printf("%i, %1.4f\n", i, vB[i]);
        }
         */
    }
    
    /*
    printf("\nvB final\n");
    for(int i = 0; i < size*n; i++){
        printf("%i, %1.4f\n", i, vB[i]);
    }
     */
    
    
    double * A = malloc(size*(nSpline+1) * sizeof(double));
    
    for(int i = 0; i < (nSpline+1)*size; i++){
        A[i] = 0;
    }
    breakInd = 0;
    for(int i = 0; i < nSpline*size; i++){
        if(i/nSpline >= breaks[1])
            breakInd = 1;
        A[(i%nSpline)+breakInd + (i/nSpline)*(nSpline+1)] = vB[i];
    }
    
    /*
    printf("\nA:\n");
    for(int i = 0; i < size; i++){
        for(int j = 0; j < n+1; j++){
            printf("%1.5f, ", A[i * (n+1) + j]);
        }
        printf("\n");
    }
     */
    
    
    
    double * x = malloc((nSpline+1)*sizeof(double));
    // lsqsolve_sub(int sizeA1, int sizeA2, double *A, int sizeb, double *b, double *x)
    lsqsolve_sub(size, nSpline+1, A, size, y, x);
    
    /*
    printf("\nsolved x\n");
    for(int i = 0; i < n+1; i++){
        printf("%i, %1.4f\n", i, x[i]);
    }
    */
    
    // coeffs of B-splines to combine by optimised weighting in x
    double C[pieces+nSpline-1][nSpline*pieces];
    // initialise to 0
    for(int i = 0; i < nSpline+1; i++){
        for(int j = 0; j < nSpline*pieces; j++){
            C[i][j] = 0;
        }
    }
    
    int CRow, CCol, coefRow, coefCol;
    for(int i = 0; i < nSpline*nSpline*pieces; i++){
        
        CRow = i%nSpline + (i/nSpline)%2;
        CCol = i/nSpline;
        
        coefRow = i%(nSpline*2);
        coefCol =i/(nSpline*2);
        
        C[CRow][CCol] = coefsOut[coefRow][coefCol];
        
    }
    
    /*
    printf("\nC:\n");
    for(int i = 0; i < n+1; i++){
        for(int j = 0; j < n*pieces; j++){
            printf("%1.5f, ", C[i][j]);
        }
        printf("\n");
    }
    */
    
    // final coefficients
    double coefsSpline[pieces][nSpline];
    for(int i = 0; i < pieces; i++){
        for(int j = 0; j < nSpline; j++){
            coefsSpline[i][j] = 0;
        }
    }
    
    //multiply with x
    for(int j = 0; j < nSpline*pieces; j++){
        coefCol = j/pieces;
        coefRow = j%pieces;
        
        for(int i = 0; i < nSpline+1; i++){
            
            coefsSpline[coefRow][coefCol] += C[i][j]*x[i];
            
        }
    }
    
    /*
    printf("\ncoefsSpline:\n");
    for(int i = 0; i < pieces; i++){
        for(int j = 0; j < n; j++){
            printf("%1.5f, ", coefsSpline[i][j]);
        }
        printf("\n");
    }
     */
     
    
    // compute piecewise polynomial
    
    int secondHalf = 0;
    for(int i = 0; i < size; i++){
        secondHalf = i < breaks[1] ? 0 : 1;
        yOut[i] = coefsSpline[secondHalf][0];
    }
    
    /*
    printf("\nvSpline first iter\n");
    for(int i = 0; i < size; i++){
        printf("%i, %1.5f\n", i, vSpline[i]);
    }
    */
    
    for(int i = 1; i < nSpline; i ++){
        for(int j = 0; j < size; j++){
            secondHalf = j < breaks[1] ? 0 : 1;
            yOut[j] = yOut[j]*(j - breaks[1]*secondHalf) + coefsSpline[secondHalf][i];
        }
        
        /*
        printf("\nvSpline %i th iter\n", i);
        for(int i = 0; i < size; i++){
            printf("%i, %1.4f\n", i, vSpline[i]);
        }
         */
    }
    
    /*
    printf("\nvSpline\n");
    for(int i = 0; i < size; i++){
        printf("%i, %1.4f\n", i, yOut[i]);
    }
     */
     
    free(xsB);
    free(indexB);
    free(vB);
    free(A);
    free(x);
    
    return 0;
    
}




================================================
FILE: C/splinefit.h
================================================
//
//  splinefit.h
//  C_polished
//
//  Created by Carl Henning Lubba on 27/09/2018.
//  Copyright © 2018 Carl Henning Lubba. All rights reserved.
//

#ifndef splinefit_h
#define splinefit_h

#include <stdio.h>

extern int splinefit(const double *y, const int size, double *yOut);

#endif /* splinefit_h */


================================================
FILE: C/stats.c
================================================
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "helper_functions.h"

double min_(const double a[], const int size)
{
    double m = a[0];
    for (int i = 1; i < size; i++) {
        if (a[i] < m) {
            m = a[i];
        }
    }
    return m;
}

double max_(const double a[], const int size)
{
    double m = a[0];
    for (int i = 1; i < size; i++) {
        if (a[i] > m) {
            m = a[i];
        }
    }
    return m;
}

double mean(const double a[], const int size)
{
    double m = 0.0;
    for (int i = 0; i < size; i++) {
        m += a[i];
    }
    m /= size;
    return m;
}

double sum(const double a[], const int size)
{
    double m = 0.0;
    for (int i = 0; i < size; i++) {
        m += a[i];
    }
    return m;
}

void cumsum(const double a[], const int size, double b[])
{
    b[0] = a[0];
    for (int i = 1; i < size; i++) {
        b[i] = a[i] + b[i-1];
        //printf("b[%i]%1.3f = a[%i]%1.3f + b[%i-1]%1.3f\n", i, b[i], i, a[i], i, a[i-1]);
    }
    
}

void icumsum(const int a[], const int size, int b[])
{
    b[0] = a[0];
    for (int i = 1; i < size; i++) {
        b[i] = a[i] + b[i-1];
        //printf("b[%i]%1.3f = a[%i]%1.3f + b[%i-1]%1.3f\n", i, b[i], i, a[i], i, a[i-1]);
    }
    
}

double isum(const int a[], const int size)
{
    double m = 0.0;
    for (int i = 0; i < size; i++) {
        m += a[i];
    }
    return m;
}

double median(const double a[], const int size)
{
    double m;
    double * b = malloc(size * sizeof *b);
    memcpy(b, a, size * sizeof *b);
    sort(b, size);
    if (size % 2 == 1) {
        m = b[size / 2];
    } else {
        int m1 = size / 2;
        int m2 = m1 - 1;
        m = (b[m1] + b[m2]) / (double)2.0;
    }
    free(b);
    return m;
}

double stddev(const double a[], const int size)
{
    double m = mean(a, size);
    double sd = 0.0;
    for (int i = 0; i < size; i++) {
        sd += pow(a[i] - m, 2);
    }
    sd = sqrt(sd / (size - 1));
    return sd;
}

double cov(const double x[], const double y[], const int size){
    
    double covariance = 0;
    
    double meanX = mean(x, size);
    double meanY = mean(y, size);
    
    for(int i = 0; i < size; i++){
        // double xi =x[i];
        // double yi =y[i];
        covariance += (x[i] - meanX) * (y[i] - meanY);
        
    }
    
    return covariance/(size-1);
    
}

double cov_mean(const double x[], const double y[], const int size){
    
    double covariance = 0;
    
    for(int i = 0; i < size; i++){
        // double xi =x[i];
        // double yi =y[i];
        covariance += x[i] * y[i];
        
    }
    
    return covariance/size;
    
}

double corr(const double x[], const double y[], const int size){
    
    double nom = 0;
    double denomX = 0;
    double denomY = 0;
    
    double meanX = mean(x, size);
    double meanY = mean(y, size);
    
    for(int i = 0; i < size; i++){
        nom += (x[i] - meanX) * (y[i] - meanY);
        denomX += (x[i] - meanX) * (x[i] - meanX);
        denomY += (y[i] - meanY) * (y[i] - meanY);
        
        //printf("x[%i]=%1.3f, y[%i]=%1.3f, nom[%i]=%1.3f, denomX[%i]=%1.3f, denomY[%i]=%1.3f\n", i, x[i], i, y[i], i, nom, i, denomX, i, denomY);
    }
    
    return nom/sqrt(denomX * denomY);
    
}

double autocorr_lag(const double x[], const int size, const int lag){
    
    return corr(x, &(x[lag]), size-lag);
    
}

double autocov_lag(const double x[], const int size, const int lag){
    
    return cov_mean(x, &(x[lag]), size-lag);
    
}

void zscore_norm(double a[], int size)
{
    double m = mean(a, size);
    double sd = stddev(a, size);
    for (int i = 0; i < size; i++) {
        a[i] = (a[i] - m) / sd;
    }
    return;
}

void zscore_norm2(const double a[], const int size, double b[])
{
    double m = mean(a, size);
    double sd = stddev(a, size);
    for (int i = 0; i < size; i++) {
        b[i] = (a[i] - m) / sd;
    }
    return;
}

double moment(const double a[], const int size, const int start, const int end, const int r)
{
    int win_size = end - start + 1;
    a += start;
    double m = mean(a, win_size);
    double mr = 0.0;
    for (int i = 0; i < win_size; i++) {
        mr += pow(a[i] - m, r);
    }
    mr /= win_size;
    mr /= stddev(a, win_size); //normalize
    return mr;
}

void diff(const double a[], const int size, double b[])
{
    for (int i = 1; i < size; i++) {
        b[i - 1] = a[i] - a[i - 1];
    }
}

int linreg(const int n, const double x[], const double y[], double* m, double* b) //, double* r)
{
    double   sumx = 0.0;                      /* sum of x     */
    double   sumx2 = 0.0;                     /* sum of x**2  */
    double   sumxy = 0.0;                     /* sum of x * y */
    double   sumy = 0.0;                      /* sum of y     */
    double   sumy2 = 0.0;                     /* sum of y**2  */
    
    /*
    for (int i = 0; i < n; i++)
    {
        fprintf(stdout, "x[%i] = %f, y[%i] = %f\n", i, x[i], i, y[i]);
    }
    */
    
    for (int i=0;i<n;i++){
        sumx  += x[i];
        sumx2 += x[i] * x[i];
        sumxy += x[i] * y[i];
        sumy  += y[i];
        sumy2 += y[i] * y[i];
    }
    
    double denom = (n * sumx2 - sumx * sumx);
    if (denom == 0) {
        // singular matrix. can't solve the problem.
        *m = 0;
        *b = 0;
        //if (r) *r = 0;
        return 1;
    }
    
    *m = (n * sumxy  -  sumx * sumy) / denom;
    *b = (sumy * sumx2  -  sumx * sumxy) / denom;
    
    /*if (r!=NULL) {
        *r = (sumxy - sumx * sumy / n) /    // compute correlation coeff
        sqrt((sumx2 - sumx * sumx/n) *
             (sumy2 - sumy * sumy/n));
    }
    */
    
    return 0;
}

double norm_(const double a[], const int size)
{
    
    double out = 0.0;
    
    for (int i = 0; i < size; i++)
    {
        out += a[i]*a[i];
    }
    
    out = sqrt(out);
    
    return out;
}


================================================
FILE: C/stats.h
================================================
#ifndef STATS_H
#define STATS_H
#include <math.h>
#include <stdlib.h>
#include <string.h>

extern double max_(const double a[], const int size);
extern double min_(const double a[], const int size);
extern double mean(const double a[], const int size);
extern double sum(const double a[], const int size);
extern void cumsum(const double a[], const int size, double b[]);
extern void icumsum(const int a[], const int size, int b[]);
extern double isum(const int a[], const int size);
extern double median(const double a[], const int size);
extern double stddev(const double a[], const int size);
extern double corr(const double x[], const double y[], const int size);
extern double cov(const double x[], const double y[], const int size);
extern double cov_mean(const double x[], const double y[], const int size);
extern double autocorr_lag(const double x[], const int size, const int lag);
extern double autocov_lag(const double x[], const int size, const int lag);
extern void zscore_norm(double a[], int size);
extern void zscore_norm2(const double a[], const int size, double b[]);
extern double moment(const double a[], const int size, const int start, const int end, const int r);
extern void diff(const double a[], const int size, double b[]);
extern int linreg(const int n, const double x[], const double y[], double* m, double* b); //, double* r);
extern double norm_(const double a[], const int size);

#endif


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
FILE: Matlab/BasisOperations/BF_Binarize.m
================================================
function yBin = BF_Binarize(y,binarizeHow)
% BF_Binarize    Converts an input vector into a binarized version

% ------------------------------------------------------------------------------
% Copyright (C) 2017, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This function is free software: you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
% ------------------------------------------------------------------------------

%-------------------------------------------------------------------------------
% Check inputs, set defaults:
%-------------------------------------------------------------------------------
if nargin < 2 || isempty(binarizeHow)
    binarizeHow = 'diff';
end

%-------------------------------------------------------------------------------
% function to transform real values to 0 if <=0 and 1 if >0:
%-------------------------------------------------------------------------------

function Y = stepBinary(X)

    Y = zeros(size(X),'like',X);
    Y(X > 0) = 1;
    
end

%-------------------------------------------------------------------------------
% Do the binary transformation:
%-------------------------------------------------------------------------------

switch binarizeHow
    case 'diff'
        % Binary signal: 1 for stepwise increases, 0 for stepwise decreases
        yBin = stepBinary(diff(y));

    case 'mean'
        % Binary signal: 1 for above mean, 0 for below mean
        yBin = stepBinary(y - mean(y));

    case 'median'
        % Binary signal: 1 for above median, 0 for below median
        yBin = stepBinary(y - median(y));

    case 'iqr'
        % Binary signal: 1 if inside interquartile range, 0 otherwise
        iqr = quantile(y,[0.25, 0.75]);
        iniqr = (y > iqr(1) & y <= iqr(2));
        yBin = zeros(length(y),1);
        yBin(iniqr) = 1;

    otherwise
        error('Unknown binary transformation setting ''%s''',binarizeHow)
end

end


================================================
FILE: Matlab/BasisOperations/CO_AutoCorr.m
================================================
function out = CO_AutoCorr(y,tau,whatMethod)
% CO_AutoCorr   Compute the autocorrelation of an input time series
%
%---INPUTS:
% y, a scalar time series column vector.
%
% tau, the time-delay. If tau is a scalar, returns autocorrelation for y at that
%       lag. If tau is a vector, returns autocorrelations for y at that set of
%       lags. Can set tau empty, [], to return the full function for the
%       'Fourier' estimation method.
%
% whatMethod, the method of computing the autocorrelation: 'Fourier',
%             'TimeDomainStat', or 'TimeDomain'.
%
%---OUTPUT: the autocorrelation at the given time-lag.
%
%---NOTES:
% Specifying whatMethod = 'TimeDomain' can tolerate NaN values in the time
% series.
%
% Computing mean/std across the full time series makes a significant difference
% for short time series, but can produce values outside [-1,+1]. The
% filtering-based method used by Matlab's autocorr, is probably the best for
% short time series, and is implemented here by specifying: whatMethod =
% 'Fourier'.

% ------------------------------------------------------------------------------
% Copyright (C) 2017, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This function is free software: you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
% ------------------------------------------------------------------------------

% ------------------------------------------------------------------------------
% Check inputs:
% ------------------------------------------------------------------------------
if nargin < 2
    tau = 1; % Use a lag of 1 by default
end

if nargin < 3 || isempty(whatMethod)
    whatMethod = 'Fourier';
end

% ------------------------------------------------------------------------------
% Evaluate the time-series autocorrelation
% ------------------------------------------------------------------------------

switch whatMethod
case 'Fourier'
    % ------------------------------------------------------------------------------
    % Estimation based on Matlab function autocorr, based on method of:
    % [1] Box, G. E. P., G. M. Jenkins, and G. C. Reinsel. Time Series
    %     Analysis: Forecasting and Control. 3rd edition. Upper Saddle River,
    %     NJ: Prentice-Hall, 1994.

    nFFT = 2^(nextpow2(length(y))+1);
    F = fft(y-mean(y),nFFT);
    F = F.*conj(F);
    acf = ifft(F);
    acf = acf./acf(1); % Normalize
    acf = real(acf);

    acf = acf(1:length(y));

    if isempty(tau) % return the full function
        out = acf;
    else % return a specific set of values
        out = zeros(length(tau),1);
        for i = 1:length(tau)
            if (tau(i) > length(acf)-1) || (tau(i) < 0)
                out(i) = NaN;
            else
                out(i) = acf(tau(i)+1);
            end
        end
    end



end

end


================================================
FILE: Matlab/BasisOperations/CO_FirstZero.m
================================================
function out = CO_FirstZero(y,corrFun,maxTau)
% CO_FirstZero      The first zero-crossing of a given autocorrelation function
%
%---INPUTS:
%
% y, the input time series
% corrFun, the self-correlation function to measure:
%         (i) 'ac': normal linear autocorrelation function. Uses CO_AutoCorr to
%                   calculate autocorrelations.
% maxTau, a maximum time-delay to search up to.
%
% In future, could add an option to return the point at which the function
% crosses the axis, rather than the first integer lag at which it has already
% crossed (what is currently implemented).

% ------------------------------------------------------------------------------
% Copyright (C) 2017, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This function is free software: you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
% ------------------------------------------------------------------------------

% ------------------------------------------------------------------------------
% Check inputs:
% ------------------------------------------------------------------------------

N = length(y); % the length of the time series

if nargin < 2 || isempty(corrFun)
    corrFun = 'ac'; % autocorrelation by default
end
if nargin < 3 || isempty(maxTau)
    maxTau = N; % search up to a maximum of the length of the time series
    % maxTau = 400; % searches up to this maximum time lag
    % maxTau = min(maxTau,N); % searched up to the length of the time series if this is less than maxTau
end

% ------------------------------------------------------------------------------
% Select the self-correlation function as an inline function
% Eventually could add additional self-correlation functions
switch corrFun
case 'ac'
    % Autocorrelation at all time lags
    corrs = CO_AutoCorr(y,[],'Fourier');
    corrs = corrs(2:end); % remove the zero-lag result
otherwise
    error('Unknown correlation function ''%s''',corrFun);
end

% Calculate autocorrelation at increasing lags, until you find a negative one
for tau = 1:maxTau-1
    if corrs(tau) < 0 % we know it starts positive (1), so first negative will be the zero-crossing
        out = tau; return
    end
end

% If haven't left yet, set output to maxTau
out = maxTau;

% make sure this is a scalar output
coder.varsize('out', [1, 1], [0 0])

end


================================================
FILE: Matlab/BasisOperations/CO_trev.m
================================================
function out = CO_trev(y, tau)
% CO_trev   Normalized nonlinear autocorrelation, trev function of a time series
%
% Calculates the trev function, a normalized nonlinear autocorrelation,
% mentioned in the documentation of the TSTOOL nonlinear time-series analysis
% package (available here: http://www.physik3.gwdg.de/tstool/).
%
% The quantity is often used as a nonlinearity statistic in surrogate data
% analysis, cf. "Surrogate time series", T. Schreiber and A. Schmitz, Physica D,
% 142(3-4) 346 (2000).
%
%---INPUTS:
%
% y, time series
%
% tau, time lag (can be 'ac' or 'mi' to set as the first zero-crossing of the
%       autocorrelation function, or the first minimum of the automutual
%       information function, respectively)
%
%---OUTPUTS:
% the trev numerator and the denominator.

% ------------------------------------------------------------------------------
% Copyright (C) 2017, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This function is free software: you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
% ------------------------------------------------------------------------------

% ------------------------------------------------------------------------------
%% Set defaults:
% ------------------------------------------------------------------------------
if nargin < 2 || isempty(tau)
    tau = 1;
end

% ------------------------------------------------------------------------------
% Compute trev quantities
% ------------------------------------------------------------------------------

yn = y(1:end-tau);
yn1 = y(1+tau:end); % yn, tau steps ahead

% ------------------------------------------------------------------------------
% Fill output struct
% ------------------------------------------------------------------------------

% % The numerator
out.num = mean((yn1-yn).^3);

% The denominator
out.denom = (mean((yn1-yn).^2))^(3/2);

end


================================================
FILE: Matlab/BasisOperations/DN_HistogramMode.m
================================================
function out = DN_HistogramMode(y,numBins)
% DN_HistogramMode      Mode of a data vector.
%
% Measures the mode of the data vector using histograms with a given number
% of bins.
%
%---INPUTS:
%
% y, the input data vector
%
% numBins, the number of bins to use in the histogram.

% ------------------------------------------------------------------------------
% Copyright (C) 2017, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This function is free software: you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
% ------------------------------------------------------------------------------

if nargin < 2
    numBins = 'auto'; % ceil(sqrt(length(y)));
end

% Compute the histogram from the data:
[N,binEdges] = histcounts_(y,numBins);

% Compute bin centers from bin edges:
binCenters = mean([binEdges(1:end-1); binEdges(2:end)]);

% Mean position of maximums (if multiple):
out = mean(binCenters(N == max(N)));

end


================================================
FILE: Matlab/BasisOperations/DN_OutlierInclude_001_mdrmd.m
================================================
function out = DN_OutlierInclude_001_mdrmd(y,thresholdHow)
% DN_OutlierInclude     How statistics depend on distributional outliers.
%
% Measures a range of different statistics about the time series as more and
% more outliers are included in the calculation according to a specified rule,
% of outliers being furthest from the mean, greatest positive, or negative
% deviations.
%
% The threshold for including time-series data points in the analysis increases
% from zero to the maximum deviation, in increments of 0.01*sigma (by default),
% where sigma is the standard deviation of the time series.
%
% At each threshold, the mean, standard error, proportion of time series points
% included, median, and standard deviation are calculated, and outputs from the
% algorithm measure how these statistical quantities change as more extreme
% points are included in the calculation.
%
%---INPUTS:
% y, the input time series (ideally z-scored)
%
% thresholdHow, the method of how to determine outliers:
%     (i) 'abs': outliers are furthest from the mean,
%     (ii) 'p': outliers are the greatest positive deviations from the mean, or
%     (iii) 'n': outliers are the greatest negative deviations from the mean.
%
% inc, the increment to move through (fraction of std if input time series is
%       z-scored)
%
% Most of the outputs measure either exponential, i.e., f(x) = Aexp(Bx)+C, or
% linear, i.e., f(x) = Ax + B, fits to the sequence of statistics obtained in
% this way.
%
% [future: could compare differences in outputs obtained with 'p', 'n', and
%               'abs' -- could give an idea as to asymmetries/nonstationarities??]

% ------------------------------------------------------------------------------
% Copyright (C) 2017, Ben D. Fulcher <ben.d.fulcher@gmail.com>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite the following two papers:
%
% (1) B.D. Fulcher and N.S. Jones, "hctsa: A Computational Framework for Automated
% Time-Series Phenotyping Using Massive Feature Extraction, Cell Systems 5: 527 (2017).
% DOI: 10.1016/j.cels.2017.10.001
%
% (2) B.D. Fulcher, M.A. Little, N.S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2013).
% DOI: 10.1098/rsif.2013.0048
%
% This function is free software: you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
% ------------------------------------------------------------------------------

% ------------------------------------------------------------------------------
%% Check Inputs
% ------------------------------------------------------------------------------
% If time series is all the same value -- ridiculous! ++BF 21/3/2010
if all(y == y(1)) % the whole time series is just a single value
%     fprintf(1,'The time series is a constant!\n');
    out = NaN; return % this method is not suitable for such time series: return a NaN
end

N = length(y); % length of the time series

inc = 0.01;

% ------------------------------------------------------------------------------
%% Initialize thresholds
% ------------------------------------------------------------------------------
switch thresholdHow

    case 'p' % analyze only positive deviations
        thr = (0:inc:max(y));
        tot = sum(y >= 0);

    otherwise % case 'n' % analyze only negative deviations
        thr = (0:inc:max(-y));
        tot = sum(y <= 0);
        
end

if isempty(thr)
    error('I suspect that this is a highly peculiar time series?!!!')
end

% msDt4 = zeros(length(thr),1); % median of index relative to middle
%                             
% for i = 1:length(thr)
%     th = thr(i); % the threshold
% 
%     % Construct a time series consisting of inter-event intervals for parts
%     % of the time serie exceeding the threshold, th
% 
%     if strcmp(thresholdHow,'n')% look at only positive deviations
%         r = find(y <= -th);
%     elseif strcmp(thresholdHow,'p')% look at only negative deviations
%         r = find(y >= th);
%     end
%     
%     msDt4 = median(r)/(N/2)-1;
% 
% end

msDt = zeros(length(thr),6); % mean, std, proportion_of_time_series_included,
                             % median of index relative to middle, mean,
                             % error
for i = 1:length(thr)
    th = thr(i); % the threshold

    % Construct a time series consisting of inter-event intervals for parts
    % of the time serie exceeding the threshold, th

    if strcmp(thresholdHow,'n')% look at only positive deviations
        r = find(y <= -th);
    else % if strcmp(thresholdHow,'p')% look at only negative deviations
        r = find(y >= th);
    end
    
    Dt_exc = diff(r); % Delta t (interval) time series; exceeding threshold

    msDt(i,1) = mean(Dt_exc); % the mean value of this sequence
    msDt(i,3) = length(Dt_exc)/tot*100; % this is just really measuring the distribution
                                      % : the proportion of possible values
                    
Download .txt
gitextract_0hyl0dq4/

├── .github/
│   └── workflows/
│       └── github-repo-stats.yml
├── .gitignore
├── C/
│   ├── .gitignore
│   ├── CO_AutoCorr.c
│   ├── CO_AutoCorr.h
│   ├── DN_HistogramMode_10.c
│   ├── DN_HistogramMode_10.h
│   ├── DN_HistogramMode_5.c
│   ├── DN_HistogramMode_5.h
│   ├── DN_Mean.c
│   ├── DN_Mean.h
│   ├── DN_OutlierInclude.c
│   ├── DN_OutlierInclude.h
│   ├── DN_Spread_Std.c
│   ├── DN_Spread_Std.h
│   ├── FC_LocalSimple.c
│   ├── FC_LocalSimple.h
│   ├── IN_AutoMutualInfoStats.c
│   ├── IN_AutoMutualInfoStats.h
│   ├── MD_hrv.c
│   ├── MD_hrv.h
│   ├── PD_PeriodicityWang.c
│   ├── PD_PeriodicityWang.h
│   ├── SB_BinaryStats.c
│   ├── SB_BinaryStats.h
│   ├── SB_CoarseGrain.c
│   ├── SB_CoarseGrain.h
│   ├── SB_MotifThree.c
│   ├── SB_MotifThree.h
│   ├── SB_TransitionMatrix.c
│   ├── SB_TransitionMatrix.h
│   ├── SC_FluctAnal.c
│   ├── SC_FluctAnal.h
│   ├── SP_Summaries.c
│   ├── SP_Summaries.h
│   ├── butterworth.c
│   ├── butterworth.h
│   ├── fft.c
│   ├── fft.h
│   ├── helper_functions.c
│   ├── helper_functions.h
│   ├── histcounts.c
│   ├── histcounts.h
│   ├── main.c
│   ├── main.h
│   ├── runAllTS.sh
│   ├── splinefit.c
│   ├── splinefit.h
│   ├── stats.c
│   └── stats.h
├── LICENSE
├── Matlab/
│   ├── BasisOperations/
│   │   ├── BF_Binarize.m
│   │   ├── CO_AutoCorr.m
│   │   ├── CO_FirstZero.m
│   │   ├── CO_trev.m
│   │   ├── DN_HistogramMode.m
│   │   ├── DN_OutlierInclude_001_mdrmd.m
│   │   ├── NK_hist2.m
│   │   ├── SB_CoarseGrain_quantile.m
│   │   ├── SB_TransitionMatrix.m
│   │   ├── SC_FluctAnal_q2_taustep50_k1_logi_prop_r1.m
│   │   ├── SP_Summaries_welch_rect.m
│   │   ├── buffer_.m
│   │   ├── decimate_.m
│   │   ├── downsample_.m
│   │   ├── filtfilt_.m
│   │   ├── histcounts_.m
│   │   ├── myButter.m
│   │   ├── poly_.m
│   │   ├── splinefit.m
│   │   ├── test_zp2ss.m
│   │   ├── testfilt.m
│   │   └── welchy.m
│   ├── CO_Embed2_Dist_tau_d_expfit_meandiff.m
│   ├── CO_FirstMin_ac.m
│   ├── CO_HistogramAMI_even_2_5.m
│   ├── CO_f1ecac.m
│   ├── CO_trev_1_num.m
│   ├── DN_HistogramMode_10.m
│   ├── DN_HistogramMode_5.m
│   ├── DN_Mean.m
│   ├── DN_OutlierInclude_n_001_mdrmd.m
│   ├── DN_OutlierInclude_p_001_mdrmd.m
│   ├── DN_Spread_Std.m
│   ├── FC_LocalSimple_mean1_tauresrat.m
│   ├── FC_LocalSimple_mean3_stderr.m
│   ├── IN_AutoMutualInfoStats_40_gaussian_fmmi.m
│   ├── MD_hrv_classic_pnn40.m
│   ├── PD_PeriodicityWang_th0_01.m
│   ├── SB_BinaryStats_diff_longstretch0.m
│   ├── SB_BinaryStats_mean_longstretch1.m
│   ├── SB_MotifThree_quantile_hh.m
│   ├── SB_TransitionMatrix_3ac_sumdiagcov.m
│   ├── SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1.m
│   ├── SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1.m
│   ├── SP_Summaries_welch_rect_area_5_1.m
│   └── SP_Summaries_welch_rect_centroid.m
├── README.md
├── catch22.m
├── featureList.txt
├── testData/
│   ├── runtests.sh
│   ├── test.txt
│   ├── test2.txt
│   ├── test2_output.txt
│   ├── testInf.txt
│   ├── testInfMinus.txt
│   ├── testNaN.txt
│   ├── testShort.txt
│   ├── testShort_output.txt
│   ├── testSinusoid.txt
│   ├── testSinusoid_output.txt
│   └── test_output.txt
└── wrap_Matlab/
    ├── GetAllFeatureNames.m
    ├── M_wrapper.c
    ├── M_wrapper.h
    ├── catch22_CO_Embed2_Dist_tau_d_expfit_meandiff.c
    ├── catch22_CO_FirstMin_ac.c
    ├── catch22_CO_HistogramAMI_even_2_5.c
    ├── catch22_CO_f1ecac.c
    ├── catch22_CO_trev_1_num.c
    ├── catch22_DN_HistogramMode_10.c
    ├── catch22_DN_HistogramMode_5.c
    ├── catch22_DN_Mean.c
    ├── catch22_DN_OutlierInclude_n_001_mdrmd.c
    ├── catch22_DN_OutlierInclude_p_001_mdrmd.c
    ├── catch22_DN_Spread_Std.c
    ├── catch22_FC_LocalSimple_mean1_tauresrat.c
    ├── catch22_FC_LocalSimple_mean3_stderr.c
    ├── catch22_IN_AutoMutualInfoStats_40_gaussian_fmmi.c
    ├── catch22_MD_hrv_classic_pnn40.c
    ├── catch22_PD_PeriodicityWang_th0_01.c
    ├── catch22_SB_BinaryStats_diff_longstretch0.c
    ├── catch22_SB_BinaryStats_mean_longstretch1.c
    ├── catch22_SB_MotifThree_quantile_hh.c
    ├── catch22_SB_TransitionMatrix_3ac_sumdiagcov.c
    ├── catch22_SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1.c
    ├── catch22_SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1.c
    ├── catch22_SP_Summaries_welch_rect_area_5_1.c
    ├── catch22_SP_Summaries_welch_rect_centroid.c
    ├── catch22_all.m
    ├── mexAll.m
    └── testing.m
Download .txt
SYMBOL INDEX (143 symbols across 51 files)

FILE: C/CO_AutoCorr.c
  type std (line 3) | typedef std::complex< double > cplx;
  type complex (line 7) | typedef double complex cplx;
  type _Dcomplex (line 9) | typedef _Dcomplex cplx;
  function nextpow2 (line 29) | int nextpow2(int n)
  function dot_multiply (line 59) | void dot_multiply(cplx a[], cplx b[], int size)
  function co_firstzero (line 160) | int co_firstzero(const double y[], const int size, const int maxtau)
  function CO_f1ecac (line 179) | double CO_f1ecac(const double y[], const int size)
  function CO_Embed2_Basic_tau_incircle (line 217) | double CO_Embed2_Basic_tau_incircle(const double y[], const int size, co...
  function CO_Embed2_Dist_tau_d_expfit_meandiff (line 241) | double CO_Embed2_Dist_tau_d_expfit_meandiff(const double y[], const int ...
  function CO_FirstMin_ac (line 351) | int CO_FirstMin_ac(const double y[], const int size)
  function CO_trev_1_num (line 381) | double CO_trev_1_num(const double y[], const int size)
  function CO_HistogramAMI_even_2_5 (line 414) | double CO_HistogramAMI_even_2_5(const double y[], const int size)

FILE: C/CO_AutoCorr.h
  type std (line 6) | typedef std::complex< double > cplx;
  type complex (line 10) | typedef double complex cplx;
  type _Dcomplex (line 12) | typedef _Dcomplex cplx;

FILE: C/DN_HistogramMode_10.c
  function DN_HistogramMode_10 (line 9) | double DN_HistogramMode_10(const double y[], const int size)

FILE: C/DN_HistogramMode_5.c
  function DN_HistogramMode_5 (line 8) | double DN_HistogramMode_5(const double y[], const int size)

FILE: C/DN_Mean.c
  function DN_Mean (line 3) | double DN_Mean(const double a[], const int size)

FILE: C/DN_OutlierInclude.c
  function DN_OutlierInclude_np_001_mdrmd (line 9) | double DN_OutlierInclude_np_001_mdrmd(const double y[], const int size, ...
  function DN_OutlierInclude_p_001_mdrmd (line 137) | double DN_OutlierInclude_p_001_mdrmd(const double y[], const int size)
  function DN_OutlierInclude_n_001_mdrmd (line 142) | double DN_OutlierInclude_n_001_mdrmd(const double y[], const int size)
  function DN_OutlierInclude_abs_001 (line 147) | double DN_OutlierInclude_abs_001(const double y[], const int size)

FILE: C/DN_Spread_Std.c
  function DN_Spread_Std (line 4) | double DN_Spread_Std(const double a[], const int size)

FILE: C/FC_LocalSimple.c
  function abs_diff (line 6) | static void abs_diff(const double a[], const int size, double b[])
  function fc_local_simple (line 13) | double fc_local_simple(const double y[], const int size, const int train...
  function FC_LocalSimple_mean_tauresrat (line 22) | double FC_LocalSimple_mean_tauresrat(const double y[], const int size, c...
  function FC_LocalSimple_mean_stderr (line 58) | double FC_LocalSimple_mean_stderr(const double y[], const int size, cons...
  function FC_LocalSimple_mean3_stderr (line 91) | double FC_LocalSimple_mean3_stderr(const double y[], const int size)
  function FC_LocalSimple_mean1_tauresrat (line 96) | double FC_LocalSimple_mean1_tauresrat(const double y[], const int size){
  function FC_LocalSimple_mean_taures (line 100) | double FC_LocalSimple_mean_taures(const double y[], const int size, cons...
  function FC_LocalSimple_lfit_taures (line 128) | double FC_LocalSimple_lfit_taures(const double y[], const int size)

FILE: C/IN_AutoMutualInfoStats.c
  function IN_AutoMutualInfoStats_40_gaussian_fmmi (line 14) | double IN_AutoMutualInfoStats_40_gaussian_fmmi(const double y[], const i...

FILE: C/MD_hrv.c
  function MD_hrv_classic_pnn40 (line 12) | double MD_hrv_classic_pnn40(const double y[], const int size){

FILE: C/PD_PeriodicityWang.c
  function PD_PeriodicityWang_th0_01 (line 16) | int PD_PeriodicityWang_th0_01(const double * y, const int size){

FILE: C/SB_BinaryStats.c
  function SB_BinaryStats_diff_longstretch0 (line 12) | double SB_BinaryStats_diff_longstretch0(const double y[], const int size){
  function SB_BinaryStats_mean_longstretch1 (line 54) | double SB_BinaryStats_mean_longstretch1(const double y[], const int size){

FILE: C/SB_CoarseGrain.c
  function sb_coarsegrain (line 8) | void sb_coarsegrain(const double y[], const int size, const char how[], ...

FILE: C/SB_MotifThree.c
  function SB_MotifThree_quantile_hh (line 8) | double SB_MotifThree_quantile_hh(const double y[], const int size)

FILE: C/SB_TransitionMatrix.c
  function SB_TransitionMatrix_3ac_sumdiagcov (line 14) | double SB_TransitionMatrix_3ac_sumdiagcov(const double y[], const int size)

FILE: C/SC_FluctAnal.c
  function SC_FluctAnal_2_50_1_logi_prop_r1 (line 9) | double SC_FluctAnal_2_50_1_logi_prop_r1(const double y[], const int size...
  function SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1 (line 200) | double SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1(const double y[], const in...
  function SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1 (line 204) | double SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1(const double y[], con...

FILE: C/SP_Summaries.c
  function welch (line 11) | int welch(const double y[], const int size, const int NFFT, const double...
  function SP_Summaries_welch_rect (line 114) | double SP_Summaries_welch_rect(const double y[], const int size, const c...
  function SP_Summaries_welch_rect_area_5_1 (line 205) | double SP_Summaries_welch_rect_area_5_1(const double y[], const int size)
  function SP_Summaries_welch_rect_centroid (line 209) | double SP_Summaries_welch_rect_centroid(const double y[], const int size)

FILE: C/butterworth.c
  type std (line 13) | typedef std::complex< double > cplx;
  type complex (line 17) | typedef double complex cplx;
  type _Dcomplex (line 19) | typedef _Dcomplex cplx;
  function poly (line 30) | void poly(cplx x[], int size, cplx out[])
  function filt (line 72) | void filt(double y[], int size, double a[], double b[], int nCoeffs, dou...
  function reverse_array (line 98) | void reverse_array(double a[], int size){
  function filt_reverse (line 116) | void filt_reverse(double y[], int size, double a[], double b[], int nCoe...

FILE: C/fft.c
  type std (line 7) | typedef std::complex< double > cplx;
  type complex (line 11) | typedef double complex cplx;
  type _Dcomplex (line 13) | typedef _Dcomplex cplx;
  function twiddles (line 23) | void twiddles(cplx a[], int size)
  function _fft (line 40) | static void _fft(cplx a[], cplx out[], int size, int step, cplx tw[])
  function fft (line 55) | void fft(cplx a[], int size, cplx tw[])

FILE: C/fft.h
  type std (line 7) | typedef std::complex< double > cplx;
  type complex (line 11) | typedef double complex cplx;
  type _Dcomplex (line 13) | typedef _Dcomplex cplx;

FILE: C/helper_functions.c
  type std (line 3) | typedef std::complex< double > cplx;
  type complex (line 7) | typedef double complex cplx;
  type _Dcomplex (line 9) | typedef _Dcomplex cplx;
  function compare (line 20) | static int compare (const void * a, const void * b)
  function sort (line 32) | void sort(double y[], int size)
  function linspace (line 38) | void linspace(double start, double end, int num_groups, double out[])
  function quantile (line 48) | double quantile(const double y[], const int size, const double quant)
  function binarize (line 85) | void binarize(const double a[], const int size, int b[], const char how[])
  function f_entropy (line 99) | double f_entropy(const double a[], const int size)
  function subset (line 110) | void subset(const int a[], int b[], const int start, const int end)
  function cplx (line 120) | cplx _Cmulcc(const cplx x, const cplx y) {
  function cplx (line 132) | cplx _Cminuscc(const cplx x, const cplx y) {
  function cplx (line 137) | cplx _Caddcc(const cplx x, const cplx y) {
  function cplx (line 142) | cplx _Cdivcc(const cplx x, const cplx y) {
  function cplx (line 158) | cplx _Cminuscc(const cplx x, const cplx y) {
  function cplx (line 163) | cplx _Caddcc(const cplx x, const cplx y) {
  function cplx (line 168) | cplx _Cdivcc(const cplx x, const cplx y) {

FILE: C/helper_functions.h
  type std (line 10) | typedef std::complex< double > cplx;
  type complex (line 14) | typedef double complex cplx;
  type _Dcomplex (line 16) | typedef _Dcomplex cplx;

FILE: C/histcounts.c
  function num_bins_auto (line 15) | int num_bins_auto(const double y[], const int size){
  function histcounts_preallocated (line 28) | int histcounts_preallocated(const double y[], const int size, int nBins,...
  function histcounts (line 88) | int histcounts(const double y[], const int size, int nBins, int ** binCo...

FILE: C/main.c
  function quality_check (line 28) | int quality_check(const double y[], const int size)
  function run_features (line 51) | void run_features(double y[], int size, FILE * outfile, bool catch24)
  function print_help (line 226) | void print_help(char *argv[], char msg[])
  function main (line 239) | int main(int argc, char * argv[])
  function main (line 253) | int main(int argc, char * argv[])
  function main (line 326) | int main(int argc, char * argv[])

FILE: C/splinefit.c
  function matrix_multiply (line 23) | void matrix_multiply(const int sizeA1, const int sizeA2, const double *A...
  function matrix_times_vector (line 55) | void matrix_times_vector(const int sizeA1, const int sizeA2, const doubl...
  function gauss_elimination (line 74) | void gauss_elimination(int size, double *A, double *b, double *x){
  function lsqsolve_sub (line 172) | void lsqsolve_sub(const int sizeA1, const int sizeA2, const double *A, c...
  function iLimit (line 311) | int iLimit(int x, int lim){
  function splinefit (line 315) | int splinefit(const double *y, const int size, double *yOut)

FILE: C/stats.c
  function min_ (line 7) | double min_(const double a[], const int size)
  function max_ (line 18) | double max_(const double a[], const int size)
  function mean (line 29) | double mean(const double a[], const int size)
  function sum (line 39) | double sum(const double a[], const int size)
  function cumsum (line 48) | void cumsum(const double a[], const int size, double b[])
  function icumsum (line 58) | void icumsum(const int a[], const int size, int b[])
  function isum (line 68) | double isum(const int a[], const int size)
  function median (line 77) | double median(const double a[], const int size)
  function stddev (line 94) | double stddev(const double a[], const int size)
  function cov (line 105) | double cov(const double x[], const double y[], const int size){
  function cov_mean (line 123) | double cov_mean(const double x[], const double y[], const int size){
  function corr (line 138) | double corr(const double x[], const double y[], const int size){
  function autocorr_lag (line 159) | double autocorr_lag(const double x[], const int size, const int lag){
  function autocov_lag (line 165) | double autocov_lag(const double x[], const int size, const int lag){
  function zscore_norm (line 171) | void zscore_norm(double a[], int size)
  function zscore_norm2 (line 181) | void zscore_norm2(const double a[], const int size, double b[])
  function moment (line 191) | double moment(const double a[], const int size, const int start, const i...
  function diff (line 205) | void diff(const double a[], const int size, double b[])
  function linreg (line 212) | int linreg(const int n, const double x[], const double y[], double* m, d...
  function norm_ (line 257) | double norm_(const double a[], const int size)

FILE: wrap_Matlab/M_wrapper.c
  function M_wrapper_double (line 26) | void M_wrapper_double( int nlhs, mxArray *plhs[],
  function M_wrapper_int (line 80) | void M_wrapper_int( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_CO_Embed2_Dist_tau_d_expfit_meandiff.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_CO_FirstMin_ac.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_CO_HistogramAMI_even_2_5.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_CO_f1ecac.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_CO_trev_1_num.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_DN_HistogramMode_10.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_DN_HistogramMode_5.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_DN_Mean.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_DN_OutlierInclude_n_001_mdrmd.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_DN_OutlierInclude_p_001_mdrmd.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_DN_Spread_Std.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_FC_LocalSimple_mean1_tauresrat.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_FC_LocalSimple_mean3_stderr.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_IN_AutoMutualInfoStats_40_gaussian_fmmi.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_MD_hrv_classic_pnn40.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_PD_PeriodicityWang_th0_01.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_SB_BinaryStats_diff_longstretch0.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_SB_BinaryStats_mean_longstretch1.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_SB_MotifThree_quantile_hh.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_SB_TransitionMatrix_3ac_sumdiagcov.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_SP_Summaries_welch_rect_area_5_1.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],

FILE: wrap_Matlab/catch22_SP_Summaries_welch_rect_centroid.c
  function mexFunction (line 33) | void mexFunction( int nlhs, mxArray *plhs[],
Condensed preview — 142 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (423K chars).
[
  {
    "path": ".github/workflows/github-repo-stats.yml",
    "chars": 524,
    "preview": "name: github-repo-stats\n\non:\n  schedule:\n    # Run this once per day, towards the end of the day for keeping the most\n  "
  },
  {
    "path": ".gitignore",
    "chars": 92,
    "preview": "*.prj\n*.mexmaci64\n*.mexmaca64\n*.mat\n*.m~\n.DS_Store\n*.vscode\n*.code-workspace\n*/run_features\n"
  },
  {
    "path": "C/.gitignore",
    "chars": 84,
    "preview": "codegen\n*.prj\n*.mexmaci64\n*.o\nC_polished\ngenerated\nheader\ntimeSeries*\nfeatureOutputs"
  },
  {
    "path": "C/CO_AutoCorr.c",
    "chars": 13346,
    "preview": "#if __cplusplus\n#   include <complex>\ntypedef std::complex< double > cplx;\n#else\n#   include <complex.h>\n#if defined(__G"
  },
  {
    "path": "C/CO_AutoCorr.h",
    "chars": 1189,
    "preview": "#ifndef CO_AUTOCORR_H\n#define CO_AUTOCORR_H\n\n#if __cplusplus\n#   include <complex>\ntypedef std::complex< double > cplx;\n"
  },
  {
    "path": "C/DN_HistogramMode_10.c",
    "chars": 2132,
    "preview": "#include <math.h>\n#include <string.h>\n#include <time.h>\n#include <float.h>\n\n#include \"stats.h\"\n#include \"histcounts.h\"\n\n"
  },
  {
    "path": "C/DN_HistogramMode_10.h",
    "chars": 191,
    "preview": "#ifndef DN_HISTOGRAMMODE_10\n#define DN_HISTOGRAMMODE_10\n#include <math.h>\n#include <string.h>\n#include \"stats.h\"\n\nextern"
  },
  {
    "path": "C/DN_HistogramMode_5.c",
    "chars": 2717,
    "preview": "#include <math.h>\n#include <string.h>\n#include <time.h>\n#include <float.h>\n#include \"stats.h\"\n#include \"histcounts.h\"\n\nd"
  },
  {
    "path": "C/DN_HistogramMode_5.h",
    "chars": 188,
    "preview": "#ifndef DN_HISTOGRAMMODE_5\n#define DN_HISTOGRAMMODE_5\n#include <math.h>\n#include <string.h>\n#include \"stats.h\"\n\nextern d"
  },
  {
    "path": "C/DN_Mean.c",
    "chars": 184,
    "preview": "#include <stdio.h>\n\ndouble DN_Mean(const double a[], const int size)\n{\n    double m = 0.0;\n    for (int i = 0; i < size;"
  },
  {
    "path": "C/DN_Mean.h",
    "chars": 187,
    "preview": "//\n//  Created by Trent Henderson 27 September 2021\n//\n\n#ifndef DN_MEAN\n#define DN_MEAN\n\n#include <stdio.h>\n\nextern doub"
  },
  {
    "path": "C/DN_OutlierInclude.c",
    "chars": 5111,
    "preview": "#include <math.h>\n#include <string.h>\n#include <time.h>\n#include <float.h>\n#include <stdio.h>\n#include <stdlib.h>\n#inclu"
  },
  {
    "path": "C/DN_OutlierInclude.h",
    "chars": 500,
    "preview": "#ifndef DN_OUTLIERINCLUDE_ABS_001\n#define DN_OUTLIERINCLUDE_ABS_001\n#include <math.h>\n#include <string.h>\n#include <time"
  },
  {
    "path": "C/DN_Spread_Std.c",
    "chars": 271,
    "preview": "#include <stdio.h>\n#include \"stats.h\"\n\ndouble DN_Spread_Std(const double a[], const int size)\n{\n    double m = mean(a, s"
  },
  {
    "path": "C/DN_Spread_Std.h",
    "chars": 208,
    "preview": "//\n//  Created by Trent Henderson 27 September 2021\n//\n\n#ifndef DN_SPREADSTD\n#define DN_SPREADSTD\n\n#include <stdio.h>\n\ne"
  },
  {
    "path": "C/FC_LocalSimple.c",
    "chars": 3772,
    "preview": "#include <math.h>\n#include <string.h>\n#include \"stats.h\"\n#include \"CO_AutoCorr.h\"\n\nstatic void abs_diff(const double a[]"
  },
  {
    "path": "C/FC_LocalSimple.h",
    "chars": 766,
    "preview": "#ifndef FC_LOCALSIMPLE_H\n#define FC_LOCALSIMPLE_H\n#include <math.h>\n#include <string.h>\n#include \"stats.h\"\n#include \"CO_"
  },
  {
    "path": "C/IN_AutoMutualInfoStats.c",
    "chars": 1272,
    "preview": "//\n//  IN_AutoMutualInfoStats.c\n//  C_polished\n//\n//  Created by Carl Henning Lubba on 22/09/2018.\n//  Copyright © 2018 "
  },
  {
    "path": "C/IN_AutoMutualInfoStats.h",
    "chars": 380,
    "preview": "//\n//  IN_AutoMutualInfoStats.h\n//  C_polished\n//\n//  Created by Carl Henning Lubba on 22/09/2018.\n//  Copyright © 2018 "
  },
  {
    "path": "C/MD_hrv.c",
    "chars": 714,
    "preview": "//\n//  MD_hrv.c\n//  C_polished\n//\n//  Created by Carl Henning Lubba on 22/09/2018.\n//  Copyright © 2018 Carl Henning Lub"
  },
  {
    "path": "C/MD_hrv.h",
    "chars": 297,
    "preview": "//\n//  MD_hrv.h\n//  C_polished\n//\n//  Created by Carl Henning Lubba on 22/09/2018.\n//  Copyright © 2018 Carl Henning Lub"
  },
  {
    "path": "C/PD_PeriodicityWang.c",
    "chars": 3650,
    "preview": "//\n//  PD_PeriodicityWang.c\n//  C_polished\n//\n//  Created by Carl Henning Lubba on 28/09/2018.\n//  Copyright © 2018 Carl"
  },
  {
    "path": "C/PD_PeriodicityWang.h",
    "chars": 347,
    "preview": "//\n//  PD_PeriodicityWang.h\n//  C_polished\n//\n//  Created by Carl Henning Lubba on 28/09/2018.\n//  Copyright © 2018 Carl"
  },
  {
    "path": "C/SB_BinaryStats.c",
    "chars": 1957,
    "preview": "//\n//  SB_BinaryStats.c\n//  C_polished\n//\n//  Created by Carl Henning Lubba on 22/09/2018.\n//  Copyright © 2018 Carl Hen"
  },
  {
    "path": "C/SB_BinaryStats.h",
    "chars": 423,
    "preview": "//\n//  SB_BinaryStats.h\n//  C_polished\n//\n//  Created by Carl Henning Lubba on 22/09/2018.\n//  Copyright © 2018 Carl Hen"
  },
  {
    "path": "C/SB_CoarseGrain.c",
    "chars": 1070,
    "preview": "#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include \"stats.h\"\n#include \"helper_functio"
  },
  {
    "path": "C/SB_CoarseGrain.h",
    "chars": 301,
    "preview": "#ifndef SB_COARSEGRAIN_H\n#define SB_COARSEGRAIN_H\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <st"
  },
  {
    "path": "C/SB_MotifThree.c",
    "chars": 12842,
    "preview": "#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include \"SB_CoarseGrain.h\"\n#include \"helpe"
  },
  {
    "path": "C/SB_MotifThree.h",
    "chars": 325,
    "preview": "#ifndef SB_MOTIFTHREE_H\n#define SB_MOTIFTHREE_H\n#include <math.h>\n#include <string.h>\n#include <stdlib.h>\n#include \"SB_C"
  },
  {
    "path": "C/SB_TransitionMatrix.c",
    "chars": 3472,
    "preview": "//\n//  SB_TransitionMatrix.c\n//  \n//\n//  Created by Carl Henning Lubba on 23/09/2018.\n//\n\n#include \"SB_TransitionMatrix."
  },
  {
    "path": "C/SB_TransitionMatrix.h",
    "chars": 291,
    "preview": "//\n//  SB_TransitionMatrix.h\n//  \n//\n//  Created by Carl Henning Lubba on 23/09/2018.\n//\n\n#ifndef SB_TransitionMatrix_h\n"
  },
  {
    "path": "C/SC_FluctAnal.c",
    "chars": 8854,
    "preview": "#include <math.h>\n#include <string.h>\n#include <time.h>\n#include <float.h>\n#include <stdio.h>\n#include \"stats.h\"\n#includ"
  },
  {
    "path": "C/SC_FluctAnal.h",
    "chars": 413,
    "preview": "#ifndef SC_FLUCTANAL\n#define SC_FLUCTANAL\n#include <math.h>\n#include <string.h>\n#include \"stats.h\"\n#include \"CO_AutoCorr"
  },
  {
    "path": "C/SP_Summaries.c",
    "chars": 5022,
    "preview": "//\n//  SP_Summaries.c\n//  \n//\n//  Created by Carl Henning Lubba on 23/09/2018.\n//\n\n#include \"SP_Summaries.h\"\n#include \"C"
  },
  {
    "path": "C/SP_Summaries.h",
    "chars": 435,
    "preview": "//\n//  SP_Summaries.h\n//  \n//\n//  Created by Carl Henning Lubba on 23/09/2018.\n//\n\n#ifndef SP_Summaries_h\n#define SP_Sum"
  },
  {
    "path": "C/butterworth.c",
    "chars": 7630,
    "preview": "//\n//  butterworth.c\n//  \n//\n//  Created by Carl Henning Lubba on 23/09/2018.\n//\n\n#include <stdlib.h>\n#include <math.h>\n"
  },
  {
    "path": "C/butterworth.h",
    "chars": 288,
    "preview": "//\n//  butterworth.h\n//  \n//\n//  Created by Carl Henning Lubba on 23/09/2018.\n//\n\n#ifndef butterworth_h\n#define butterwo"
  },
  {
    "path": "C/fft.c",
    "chars": 1473,
    "preview": "#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#if __cplusplus\n#   include <complex>\ntypedef std::complex< d"
  },
  {
    "path": "C/fft.h",
    "chars": 646,
    "preview": "#ifndef FFT_H\n#define FFT_H\n//#include <complex.h>\n\n#if __cplusplus\n#   include <complex>\n    typedef std::complex< doub"
  },
  {
    "path": "C/helper_functions.c",
    "chars": 4246,
    "preview": "#if __cplusplus\n#   include <complex>\ntypedef std::complex< double > cplx;\n#else\n#   include <complex.h>\n#if defined(__G"
  },
  {
    "path": "C/helper_functions.h",
    "chars": 1044,
    "preview": "#ifndef HELPER_FUNCTIONS_H\n#define HELPER_FUNCTIONS_H\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#includ"
  },
  {
    "path": "C/histcounts.c",
    "chars": 4334,
    "preview": "//\n//  histcounts.c\n//  C_polished\n//\n//  Created by Carl Henning Lubba on 19/09/2018.\n//  Copyright © 2018 Carl Henning"
  },
  {
    "path": "C/histcounts.h",
    "chars": 777,
    "preview": "//\n//  histcounts.h\n//  C_polished\n//\n//  Created by Carl Henning Lubba on 19/09/2018.\n//  Copyright © 2018 Carl Henning"
  },
  {
    "path": "C/main.c",
    "chars": 13510,
    "preview": "/* Include files */\n#include \"main.h\"\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n//#i"
  },
  {
    "path": "C/main.h",
    "chars": 303,
    "preview": "#ifndef MAIN_H\n#define MAIN_H\n\n/* Include files */\n#include <math.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <s"
  },
  {
    "path": "C/runAllTS.sh",
    "chars": 1708,
    "preview": "#!/bin/bash\n\nhelp()\n{\n   echo \"\"\n   echo \"Usage: $0 -i indir -o outdir -a append_string -s\"\n   echo -e \"\\t-h Show this h"
  },
  {
    "path": "C/splinefit.c",
    "chars": 19699,
    "preview": "//  Created by Carl Henning Lubba on 27/09/2018.\n//  Copyright © 2018 Carl Henning Lubba. All rights reserved.\n//\n// Bas"
  },
  {
    "path": "C/splinefit.h",
    "chars": 308,
    "preview": "//\n//  splinefit.h\n//  C_polished\n//\n//  Created by Carl Henning Lubba on 27/09/2018.\n//  Copyright © 2018 Carl Henning "
  },
  {
    "path": "C/stats.c",
    "chars": 5906,
    "preview": "#include <math.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include \"helper_functions.h\"\n\ndouble min_("
  },
  {
    "path": "C/stats.h",
    "chars": 1421,
    "preview": "#ifndef STATS_H\n#define STATS_H\n#include <math.h>\n#include <stdlib.h>\n#include <string.h>\n\nextern double max_(const doub"
  },
  {
    "path": "LICENSE",
    "chars": 35147,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "Matlab/BasisOperations/BF_Binarize.m",
    "chars": 3007,
    "preview": "function yBin = BF_Binarize(y,binarizeHow)\n% BF_Binarize    Converts an input vector into a binarized version\n\n% -------"
  },
  {
    "path": "Matlab/BasisOperations/CO_AutoCorr.m",
    "chars": 3888,
    "preview": "function out = CO_AutoCorr(y,tau,whatMethod)\n% CO_AutoCorr   Compute the autocorrelation of an input time series\n%\n%---I"
  },
  {
    "path": "Matlab/BasisOperations/CO_FirstZero.m",
    "chars": 3407,
    "preview": "function out = CO_FirstZero(y,corrFun,maxTau)\n% CO_FirstZero      The first zero-crossing of a given autocorrelation fun"
  },
  {
    "path": "Matlab/BasisOperations/CO_trev.m",
    "chars": 2979,
    "preview": "function out = CO_trev(y, tau)\n% CO_trev   Normalized nonlinear autocorrelation, trev function of a time series\n%\n% Calc"
  },
  {
    "path": "Matlab/BasisOperations/DN_HistogramMode.m",
    "chars": 2016,
    "preview": "function out = DN_HistogramMode(y,numBins)\n% DN_HistogramMode      Mode of a data vector.\n%\n% Measures the mode of the d"
  },
  {
    "path": "Matlab/BasisOperations/DN_OutlierInclude_001_mdrmd.m",
    "chars": 7307,
    "preview": "function out = DN_OutlierInclude_001_mdrmd(y,thresholdHow)\n% DN_OutlierInclude     How statistics depend on distribution"
  },
  {
    "path": "Matlab/BasisOperations/NK_hist2.m",
    "chars": 2489,
    "preview": "function [MN, xedges, yedges] = NK_hist2(x, y, xedges, yedges)\n% function MN = NK_hist2(x, y, xedges, yedges)\n%\n% 2D his"
  },
  {
    "path": "Matlab/BasisOperations/SB_CoarseGrain_quantile.m",
    "chars": 2431,
    "preview": "function yth = SB_CoarseGrain_quantile(y,numGroups)\n% SB_CoarseGrain   Coarse-grains a continuous time series to a discr"
  },
  {
    "path": "Matlab/BasisOperations/SB_TransitionMatrix.m",
    "chars": 6768,
    "preview": "function out = SB_TransitionMatrix(y, numGroups, tauIn)\n% SB_TransitionMatrix  Transition probabilities between differen"
  },
  {
    "path": "Matlab/BasisOperations/SC_FluctAnal_q2_taustep50_k1_logi_prop_r1.m",
    "chars": 9063,
    "preview": "function out = SC_FluctAnal_q2_taustep50_k1_logi_prop_r1(x,wtf,lag)\n% SC_FluctAnal   Implements fluctuation analysis by "
  },
  {
    "path": "Matlab/BasisOperations/SP_Summaries_welch_rect.m",
    "chars": 6146,
    "preview": "function out = SP_Summaries_welch_rect(y)\n% SP_Summaries  Statistics of the power spectrum of a time series\n%\n% The esti"
  },
  {
    "path": "Matlab/BasisOperations/buffer_.m",
    "chars": 201,
    "preview": "function y_buff = buffer_(y, tau)\n\n% replacement for y_buff = buffer(y,tau)\n\nnCols = ceil(length(y)/tau);\nyPadded = zero"
  },
  {
    "path": "Matlab/BasisOperations/decimate_.m",
    "chars": 407,
    "preview": "function out = decimate_(y, q)\n\n    nfilt = 4;\n    \n    nd = length(y);\n\n    [b,a] = myButter(nfilt, 0.8/q);\n\n    % be s"
  },
  {
    "path": "Matlab/BasisOperations/downsample_.m",
    "chars": 1727,
    "preview": "%-------------------------------------------------------------------------\nfunction  [y, h] = downsample_( x, q )\n\np = 1"
  },
  {
    "path": "Matlab/BasisOperations/filtfilt_.m",
    "chars": 1887,
    "preview": "function y = filtfilt_(b,a,x)\n%FILTFILT Zero-phase forward and reverse digital IIR filtering.\n%   Y = FILTFILT(B, A, X) "
  },
  {
    "path": "Matlab/BasisOperations/histcounts_.m",
    "chars": 939,
    "preview": "function [N, binEdges] = histcounts_(d, nBinsIn, normalise)\n    % own function for counting \n\n    if nargin<2 || isempty"
  },
  {
    "path": "Matlab/BasisOperations/myButter.m",
    "chars": 777,
    "preview": "function [Z_out, P_out] = myButter(n, W)\n% Digital Butterworth filter, either 2 or 3 outputs\n% Jan Simon, 2014, BSD lice"
  },
  {
    "path": "Matlab/BasisOperations/poly_.m",
    "chars": 1279,
    "preview": "function c = poly_(x)\n%POLY Convert roots to polynomial.\n%   POLY(A), when A is an N by N matrix, is a row vector with\n%"
  },
  {
    "path": "Matlab/BasisOperations/splinefit.m",
    "chars": 8827,
    "preview": "function pp = splinefit(y)\n%SPLINEFIT Fit a spline to noisy data.\n%   PP = SPLINEFIT(X,Y,BREAKS) fits a piecewise cubic "
  },
  {
    "path": "Matlab/BasisOperations/test_zp2ss.m",
    "chars": 57,
    "preview": "function out = test_zp2ss(z,p,k)\n\n    out = zp2ss(z,p,k);"
  },
  {
    "path": "Matlab/BasisOperations/testfilt.m",
    "chars": 208,
    "preview": "% testFilter\n\nfileID = fopen('/Users/carl/PycharmProjects/catch22/C/timeSeries/tsid0133.txt','r');\ntsData = fscanf(fileI"
  },
  {
    "path": "Matlab/BasisOperations/welchy.m",
    "chars": 2393,
    "preview": "function [Pxx, F] = calc_psd(X, NFFT, Fs, WINDOW)\r\n% Calculate Power Spectral Density \r\n%\t[Pxx ,F]= PSD(X, NFFT, Fs, WIN"
  },
  {
    "path": "Matlab/CO_Embed2_Dist_tau_d_expfit_meandiff.m",
    "chars": 3550,
    "preview": "function out = CO_Embed2_Dist_tau_d_expfit_meandiff(y)\n% CO_Embed2_Dist    Analyzes distances in a 2-d embedding space o"
  },
  {
    "path": "Matlab/CO_FirstMin_ac.m",
    "chars": 3243,
    "preview": "function out = CO_FirstMin_ac(y)\n% CO_FirstMin  Time of first minimum in a given correlation function\n%\n%---INPUTS:\n% y,"
  },
  {
    "path": "Matlab/CO_HistogramAMI_even_2_5.m",
    "chars": 3625,
    "preview": "function out = CO_HistogramAMI_even_2_5(y)\n% CO_HistogramAMI      The automutual information of the distribution using h"
  },
  {
    "path": "Matlab/CO_f1ecac.m",
    "chars": 2069,
    "preview": "function out = CO_f1ecac(y)\n% CO_f1ecac     The 1/e correlation length\n% \n% Finds where autocorrelation function first c"
  },
  {
    "path": "Matlab/CO_trev_1_num.m",
    "chars": 142,
    "preview": "function out = CO_trev_1_num(y)\n\n% no combination of single functions\ncoder.inline('never');\n\noutStruct = CO_trev(y, 1);"
  },
  {
    "path": "Matlab/DN_HistogramMode_10.m",
    "chars": 130,
    "preview": "function out = DN_HistogramMode_10(y)\n\n% no combination of single functions\ncoder.inline('never');\n\nout = DN_HistogramMo"
  },
  {
    "path": "Matlab/DN_HistogramMode_5.m",
    "chars": 128,
    "preview": "function out = DN_HistogramMode_5(y)\n\n% no combination of single functions\ncoder.inline('never');\n\nout = DN_HistogramMod"
  },
  {
    "path": "Matlab/DN_Mean.m",
    "chars": 124,
    "preview": "function out = DN_Mean(y)\n\n    % no combination of single functions\n    coder.inline('never');\n    \n    out = DN_Mean(y,"
  },
  {
    "path": "Matlab/DN_OutlierInclude_n_001_mdrmd.m",
    "chars": 165,
    "preview": "function out = DN_OutlierInclude_n_001_mdrmd(y)\n\n    % no combination of single functions\n    coder.inline('never');\n\n  "
  },
  {
    "path": "Matlab/DN_OutlierInclude_p_001_mdrmd.m",
    "chars": 165,
    "preview": "function out = DN_OutlierInclude_p_001_mdrmd(y)\n\n    % no combination of single functions\n    coder.inline('never');\n\n  "
  },
  {
    "path": "Matlab/DN_Spread_Std.m",
    "chars": 136,
    "preview": "function out = DN_Spread_Std(y)\n\n    % no combination of single functions\n    coder.inline('never');\n    \n    out = DN_S"
  },
  {
    "path": "Matlab/FC_LocalSimple_mean1_tauresrat.m",
    "chars": 2702,
    "preview": "function out = FC_LocalSimple_mean1_tauresrat(y)\n% FC_LocalSimple    Simple local time-series forecasting.\n%\n% Simple pr"
  },
  {
    "path": "Matlab/FC_LocalSimple_mean3_stderr.m",
    "chars": 2611,
    "preview": "function out = FC_LocalSimple_mean3_stderr(y)\n% FC_LocalSimple    Simple local time-series forecasting.\n%\n% Simple predi"
  },
  {
    "path": "Matlab/IN_AutoMutualInfoStats_40_gaussian_fmmi.m",
    "chars": 3459,
    "preview": "function out = IN_AutoMutualInfoStats_40_gaussian_fmmi(y)\n% IN_AutoMutualInfoStats  Statistics on automutual information"
  },
  {
    "path": "Matlab/MD_hrv_classic_pnn40.m",
    "chars": 2797,
    "preview": "function out = MD_hrv_classic_pnn40(y)\n% MD_hrv_classic    Classic heart rate variability (HRV) statistics.\n%\n% Typicall"
  },
  {
    "path": "Matlab/PD_PeriodicityWang_th0_01.m",
    "chars": 5172,
    "preview": "function out = PD_PeriodicityWang_th0_01(y_in)\n% PD_PeriodicityWang    Periodicity extraction measure of Wang et al.\n%\n%"
  },
  {
    "path": "Matlab/SB_BinaryStats_diff_longstretch0.m",
    "chars": 3256,
    "preview": "function out = SB_BinaryStats_diff_longstretch0(y)\n% SB_BinaryStats    Statistics on a binary symbolization of the time "
  },
  {
    "path": "Matlab/SB_BinaryStats_mean_longstretch1.m",
    "chars": 3253,
    "preview": "function out = SB_BinaryStats_mean_longstretch1(y)\n% SB_BinaryStats    Statistics on a binary symbolization of the time "
  },
  {
    "path": "Matlab/SB_MotifThree_quantile_hh.m",
    "chars": 3317,
    "preview": "function out = SB_MotifThree_quantile_hh(y)\n% SB_MotifThree     Motifs in a coarse-graining of a time series to a 3-lett"
  },
  {
    "path": "Matlab/SB_TransitionMatrix_3ac_sumdiagcov.m",
    "chars": 188,
    "preview": "function out = SB_TransitionMatrix_3ac_sumdiagcov(y)\n\n% no combination of single functions\ncoder.inline('never');\n\noutSt"
  },
  {
    "path": "Matlab/SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1.m",
    "chars": 192,
    "preview": "function out = SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1(y)\n\n    % no combination of single functions\n    coder.inline('nev"
  },
  {
    "path": "Matlab/SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1.m",
    "chars": 201,
    "preview": "function out = SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1(y)\n\n    % no combination of single functions\n    coder.inline"
  },
  {
    "path": "Matlab/SP_Summaries_welch_rect_area_5_1.m",
    "chars": 194,
    "preview": "function out = SP_Summaries_welch_rect_area_5_1(y)\n\n    % no combination of single functions\n    coder.inline('never');\n"
  },
  {
    "path": "Matlab/SP_Summaries_welch_rect_centroid.m",
    "chars": 195,
    "preview": "function out = SP_Summaries_welch_rect_centroid(y)\n\n    % no combination of single functions\n    coder.inline('never');\n"
  },
  {
    "path": "README.md",
    "chars": 4320,
    "preview": "<p align=\"center\"><img src=\"img/catch22_logo_square.png\" alt=\"catch22 logo\" height=\"220\"/></p>\n\n<h1 align=\"center\"><em>c"
  },
  {
    "path": "catch22.m",
    "chars": 1122,
    "preview": "function out = catch22(y)\n% catch22   Compute all 22 catch22 features\n\n% No combination of single functions\ncoder.inline"
  },
  {
    "path": "featureList.txt",
    "chars": 1583,
    "preview": "# Full_feature_name_code                        short_feature_name\n# ---------------------------------------------------"
  },
  {
    "path": "testData/runtests.sh",
    "chars": 173,
    "preview": "#!/bin/bash\n\n\"$(dirname -- $0)/../C/runAllTS.sh\" -i \"$(dirname -- $0)\" -o \"$(dirname -- $0)\" -a \"_output\" -s 1 -i \"$(dir"
  },
  {
    "path": "testData/test.txt",
    "chars": 2277,
    "preview": "-0.89094\n-0.86099\n-0.82438\n-0.78214\n-0.73573\n-0.68691\n-0.63754\n-0.58937\n-0.54342\n-0.50044\n-0.46082\n-0.42469\n-0.3924\n-0.3"
  },
  {
    "path": "testData/test2.txt",
    "chars": 2276,
    "preview": "-0.89094 -0.86099 -0.82438 -0.78214 -0.73573 -0.68691 -0.63754 -0.58937 -0.54342 -0.50044 -0.46082 -0.42469 -0.3924 -0.3"
  },
  {
    "path": "testData/test2_output.txt",
    "chars": 1247,
    "preview": "-0.23703703703704, DN_OutlierInclude_n_001_mdrmd, 0.248000\n0.40740740740741, DN_OutlierInclude_p_001_mdrmd, 0.342000\n-0."
  },
  {
    "path": "testData/testInf.txt",
    "chars": 2182,
    "preview": "inf\n-0.42469\n-0.3924\n-0.36389\n-0.33906\n-0.31795\n-0.30056\n-0.28692\n-0.27727\n-0.27105\n-0.26777\n-0.26678\n-0.26742\n-0.26927\n"
  },
  {
    "path": "testData/testInfMinus.txt",
    "chars": 2183,
    "preview": "-inf\n-0.42469\n-0.3924\n-0.36389\n-0.33906\n-0.31795\n-0.30056\n-0.28692\n-0.27727\n-0.27105\n-0.26777\n-0.26678\n-0.26742\n-0.26927"
  },
  {
    "path": "testData/testNaN.txt",
    "chars": 2182,
    "preview": "nan\n-0.42469\n-0.3924\n-0.36389\n-0.33906\n-0.31795\n-0.30056\n-0.28692\n-0.27727\n-0.27105\n-0.26777\n-0.26678\n-0.26742\n-0.26927\n"
  },
  {
    "path": "testData/testShort.txt",
    "chars": 108,
    "preview": "-0.89094\n-0.86099\n-0.82438\n-0.78214\n-0.73573\n-0.68691\n-0.63754\n-0.58937\n-0.54342\n-0.50044\n-0.46082\n-0.42469\n"
  },
  {
    "path": "testData/testShort_output.txt",
    "chars": 1240,
    "preview": "-0.58333333333333, DN_OutlierInclude_n_001_mdrmd, 0.019000\n0.75000000000000, DN_OutlierInclude_p_001_mdrmd, 0.017000\n0.0"
  },
  {
    "path": "testData/testSinusoid.txt",
    "chars": 57281,
    "preview": "0.07278102\n0.04887893\n0.08751903\n0.13499968\n0.12611472\n0.32822557\n0.07535813\n0.24774287\n0.12878436\n0.34140028\n0.15010170"
  },
  {
    "path": "testData/testSinusoid_output.txt",
    "chars": 1250,
    "preview": "0.13687262547490, DN_OutlierInclude_n_001_mdrmd, 8.703000\n-0.13777244551090, DN_OutlierInclude_p_001_mdrmd, 6.593000\n1.2"
  },
  {
    "path": "testData/test_output.txt",
    "chars": 1247,
    "preview": "-0.23703703703704, DN_OutlierInclude_n_001_mdrmd, 0.252000\n0.40740740740741, DN_OutlierInclude_p_001_mdrmd, 0.302000\n-0."
  },
  {
    "path": "wrap_Matlab/GetAllFeatureNames.m",
    "chars": 1106,
    "preview": "function [featureNamesLong,featureNamesShort] = GetAllFeatureNames(doCatch24)\n% Retrieve all feature names from featureL"
  },
  {
    "path": "wrap_Matlab/M_wrapper.c",
    "chars": 3360,
    "preview": "#include \"mex.h\"\n\n#include \"CO_AutoCorr.h\"\n#include \"DN_HistogramMode_10.h\"\n#include \"DN_HistogramMode_5.h\"\n#include \"DN"
  },
  {
    "path": "wrap_Matlab/M_wrapper.h",
    "chars": 324,
    "preview": "#include \"mex.h\"\n\nextern void M_wrapper_double( int nlhs, mxArray *plhs[], \n    int nrhs, const mxArray*prhs[], \n    dou"
  },
  {
    "path": "wrap_Matlab/catch22_CO_Embed2_Dist_tau_d_expfit_meandiff.c",
    "chars": 1051,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_CO_FirstMin_ac.c",
    "chars": 1008,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_CO_HistogramAMI_even_2_5.c",
    "chars": 1039,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_CO_f1ecac.c",
    "chars": 1006,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_CO_trev_1_num.c",
    "chars": 1028,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_DN_HistogramMode_10.c",
    "chars": 1034,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_DN_HistogramMode_5.c",
    "chars": 1033,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_DN_Mean.c",
    "chars": 1023,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_DN_OutlierInclude_n_001_mdrmd.c",
    "chars": 1044,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_DN_OutlierInclude_p_001_mdrmd.c",
    "chars": 1044,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_DN_Spread_Std.c",
    "chars": 1029,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_FC_LocalSimple_mean1_tauresrat.c",
    "chars": 1045,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_FC_LocalSimple_mean3_stderr.c",
    "chars": 1042,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_IN_AutoMutualInfoStats_40_gaussian_fmmi.c",
    "chars": 1054,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_MD_hrv_classic_pnn40.c",
    "chars": 1035,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_PD_PeriodicityWang_th0_01.c",
    "chars": 1037,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_SB_BinaryStats_diff_longstretch0.c",
    "chars": 1047,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_SB_BinaryStats_mean_longstretch1.c",
    "chars": 1047,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_SB_MotifThree_quantile_hh.c",
    "chars": 1040,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_SB_TransitionMatrix_3ac_sumdiagcov.c",
    "chars": 1049,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_SC_FluctAnal_2_dfa_50_1_2_logi_prop_r1.c",
    "chars": 1053,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_SC_FluctAnal_2_rsrangefit_50_1_logi_prop_r1.c",
    "chars": 1058,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_SP_Summaries_welch_rect_area_5_1.c",
    "chars": 1047,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_SP_Summaries_welch_rect_centroid.c",
    "chars": 1047,
    "preview": "/*=================================================================\n *\n *\n *============================================"
  },
  {
    "path": "wrap_Matlab/catch22_all.m",
    "chars": 1397,
    "preview": "function [featureValues, featureNamesLong, featureNamesShort] = catch22_all(data, doCatch24)\n% catch22_all   Calculate a"
  },
  {
    "path": "wrap_Matlab/mexAll.m",
    "chars": 843,
    "preview": "% mexAll    Mex compile all .c files to be runnable from Matlab.\n\n% Path where the C implementation lives\nbasePath = '.."
  },
  {
    "path": "wrap_Matlab/testing.m",
    "chars": 1077,
    "preview": "%-------------------------------------------------------------------------------\n% Get the function names\n[featureNamesL"
  }
]

About this extraction

This page contains the full source code of the chlubba/catch22 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 142 files (385.6 KB), approximately 135.8k tokens, and a symbol index with 143 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!