~josef-pktd/statsmodels/statsmodels-devel-tmp

« back to all changes in this revision

Viewing changes to scikits/statsmodels/tsa/var/util.py

  • Committer: joep
  • Author(s): Wes McKinney
  • Date: 2011-01-31 05:31:55 UTC
  • Revision ID: josef.pktd@gmail.com-20110131053155-lp8dlh9ainmz78i8
merge Wes 2034

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
from cStringIO import StringIO
 
1
"""
 
2
Miscellaneous utility code for VAR estimation
 
3
"""
2
4
 
3
5
import numpy as np
 
6
import scipy.stats as stats
 
7
 
 
8
def interpret_data(data, names):
 
9
    """
 
10
    Convert passed data structure to form required by VAR estimation classes
 
11
 
 
12
    Parameters
 
13
    ----------
 
14
 
 
15
    Returns
 
16
    -------
 
17
 
 
18
    """
 
19
    if isinstance(data, np.ndarray):
 
20
        provided_names = data.dtype.names
 
21
 
 
22
        # structured array type
 
23
        if provided_names:
 
24
            if names is None:
 
25
                names = provided_names
 
26
            else:
 
27
                assert(len(names) == len(provided_names))
 
28
 
 
29
            Y = struct_to_ndarray(data)
 
30
        else:
 
31
            Y = data
 
32
    else:
 
33
        raise Exception('cannot handle other input types at the moment')
 
34
 
 
35
    return Y, names
 
36
 
 
37
def struct_to_ndarray(arr):
 
38
    return arr.view((float, len(arr.dtype.names)))
4
39
 
5
40
def parse_data(path):
6
41
    """
56
91
    return data, date_range
57
92
 
58
93
 
59
 
def pprint_matrix(values, rlabels, clabels, col_space=None):
60
 
    buf = StringIO()
61
 
 
62
 
    T, K = len(rlabels), len(clabels)
63
 
 
64
 
    if col_space is None:
65
 
        min_space = 10
66
 
        col_space = [max(len(str(c)) + 2, min_space) for c in clabels]
67
 
    else:
68
 
        col_space = (col_space,) * K
69
 
 
70
 
    row_space = max([len(str(x)) for x in rlabels]) + 2
71
 
 
72
 
    head = _pfixed('', row_space)
73
 
 
74
 
    for j, h in enumerate(clabels):
75
 
        head += _pfixed(h, col_space[j])
76
 
 
77
 
    print >> buf, head
78
 
 
79
 
    for i, rlab in enumerate(rlabels):
80
 
        line = ('%s' % rlab).ljust(row_space)
81
 
 
82
 
        for j in range(K):
83
 
            line += _pfixed(values[i,j], col_space[j])
84
 
 
85
 
        print >> buf, line
86
 
 
87
 
    return buf.getvalue()
88
 
 
89
 
def _pfixed(s, space, nanRep=None, float_format=None):
90
 
    if isinstance(s, float):
91
 
        if float_format:
92
 
            formatted = float_format(s)
93
 
        else:
94
 
            formatted = "%#8.6F" % s
95
 
 
96
 
        return formatted.rjust(space)
97
 
    else:
98
 
        return ('%s' % s)[:space].rjust(space)
 
94
def comp_matrix(coefs):
 
95
    """
 
96
    Return compansion matrix for the VAR(1) representation for a VAR(p) process
 
97
    (companion form)
 
98
 
 
99
    A = [A_1 A_2 ... A_p-1 A_p
 
100
         I_K 0       0     0
 
101
         0   I_K ... 0     0
 
102
         0 ...       I_K   0]
 
103
    """
 
104
    p, k, k2 = coefs.shape
 
105
    assert(k == k2)
 
106
 
 
107
    kp = k * p
 
108
 
 
109
    result = np.zeros((kp, kp))
 
110
    result[:k] = np.concatenate(coefs, axis=1)
 
111
 
 
112
    # Set I_K matrices
 
113
    if p > 1:
 
114
        result[np.arange(k, kp), np.arange(kp-k)] = 1
 
115
 
 
116
    return result
 
117
 
 
118
def get_logdet(m):
 
119
    from scikits.statsmodels.compatibility import np_slogdet
 
120
    logdet = np_slogdet(m)
 
121
 
 
122
    if logdet[0] == -1:
 
123
        raise ValueError("Matrix is not positive definite")
 
124
    elif logdet[0] == 0:
 
125
        raise ValueError("Matrix is singluar")
 
126
    else:
 
127
        logdet = logdet[1]
 
128
 
 
129
    return logdet
 
130
 
 
131
def norm_signif_level(alpha=0.05):
 
132
    return stats.norm.ppf(1 - alpha / 2)
 
133
 
 
134
 
 
135
def acf_to_acorr(acf):
 
136
    diag = np.diag(acf[0])
 
137
    # numpy broadcasting sufficient
 
138
    return acf / np.sqrt(np.outer(diag, diag))