File: olbm.c

package info (click to toggle)
r-cran-mcmc 0.9-7-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 2,352 kB
  • sloc: ansic: 1,298; makefile: 14; sh: 8
file content (79 lines) | stat: -rw-r--r-- 1,699 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

#include <R.h>
#include "mcmc.h"

/* overlapping batch means for vector time series
*
*  input:
*
*    x       time series, n x p matrix, n time points and p components
*    len     batch length
*
*  output:
*
*    mean    sample mean, a p vector
*    var     estimated variance of sample mean, a p x p matrix
*
*/

#define X(I,J)    	x[(I) + n * (J)]
#define VAR(I,J)    var[(I) + p * (J)]

void olbm(double *x, int *nin, int *pin, int *lin, double *mean,
    double *var, int *nocalcin)
{
    int n = nin[0];
    int p = pin[0];
    int len = lin[0];
    double nbatch = n - len + 1;
    int nocalc = nocalcin[0];
    double *work = (double *) R_alloc(p, sizeof(double));

    int i, j, k, l;

    if (len > n)
    	error("len > n\n");

    if (! nocalc)
    	for (i=0; i<p; i++) {
    		double sum = 0.0;
    		for (k=0; k<n; k++)
    			sum += X(k,i);
    		mean[i] = sum / n;
    	}

    /* easier to work with len * means, change means to that until
     * further notice
     */
    for (i=0; i<p; i++)
    	mean[i] *= len;

    for (i=0; i<p; i++) {
    	work[i] = 0.0;
    	for (k=0; k<len; k++)
    		work[i] += X(k,i);
    	for (j=i; j>=0; j--)
    		VAR(i,j) = (work[i] - mean[i]) * (work[j] - mean[j]);
    }

    for (k=0, l=len; l<n; k++, l++)
    	for (i=0; i<p; i++) {
    		work[i] -= X(k,i);
    		work[i] += X(l,i);
    		for (j=i; j>=0; j--)
    			VAR(i,j) += (work[i] - mean[i]) *
    				(work[j] - mean[j]);
    	}

    /* fix up means and variances, divide out factors of len and len^2 */
    for (i=0; i<p; i++)
    	mean[i] /= len;

    for (i=0; i<p; i++)
    	for (j=0; j<=i; j++) {
    		VAR(i,j) /= nbatch * n * len;
    		if (j < i) VAR(j,i) = VAR(i,j);
    	}

}