File: truncnorm.py

package info (click to toggle)
python-truncnorm 0.0.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 100 kB
  • sloc: python: 280; makefile: 3
file content (350 lines) | stat: -rw-r--r-- 9,268 bytes parent folder | download
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import itertools

import numpy as np
from scipy import stats


def mvdot(A, b):
    return np.einsum("...ik,...k->...i", A, b)


def diag(A):
    return np.einsum("...ii->...i", A)


def integral(mu, Sigma, a, b):
    """P(a<=x<=b) for x~N(mu,Sigma) """

    N = np.shape(mu)[-1]

    # If we don't have an upper bound, flip everything and use the lower bound
    # as the upper bound.
    if b is None:
        # Swap the axes
        b = None if a is None else -a
        a = None
        mu = -mu

    if a is None:
        if b is None:
            # Trivial integral
            return 1

        if N == 1:
            return stats.norm.cdf(b, mu, Sigma[...,0])[...,0]

        # If only upper bound, we can compute P(x<=b) with a single evaluation
        # of CDF
        #
        # TODO: SciPy multivariate normal has no support for arrays, so we need
        # to loop over each ourselves
        sh = np.broadcast_shapes(
            np.shape(b)[:-1],
            np.shape(mu)[:-1],
            np.shape(Sigma)[:-2],
        )
        N = np.shape(mu)[-1]
        b = np.broadcast_to(b, sh + (N,))
        mu = np.broadcast_to(mu, sh + (N,))
        Sigma = np.broadcast_to(Sigma, sh + (N,N))
        p = np.zeros(sh)

        for ind in itertools.product(*(np.arange(s) for s in sh)):
            p[ind] = stats.multivariate_normal.cdf(
                b[ind],
                mean=mu[ind],
                cov=Sigma[ind],
            )

        return p

    if N == 1:
        s = np.sqrt(Sigma)[...,0]
        p = stats.norm.cdf(b, mu, s) - stats.norm.cdf(a, mu, s)
        return p[...,0]

    raise NotImplementedError()

    # TODO: Broadcasting

    y = np.stack([a,b])
    [
        ((1, bi,),) if np.isneginf(ai) else ((0, ai), (1, bi))
        for (ai, bi) in zip(a, b)
    ]

    # To get max benefit of the below optimization, flip dimensions for which
    # a[i]>-inf but b[i]=inf
    # flip = ~np.isneginf(a) & np.isposinf(b)
    # b = np.where(flip, -a, b)
    # a = np.where(flip, -np.inf, a)
    # mu = np.where(flip, -mu, mu)

    # Optimization: skip combinations with any a[i]=-inf
    [
        ((1, bi,),) if np.isneginf(ai) else ((0, ai), (1, bi))
        for (ai, bi) in zip(a, b)
    ]

    P = 0
    for (i, y) in foo:
        # TODO: Maybe discard dimensions with b[i]=inf so it's lower dimensional?
        pass


def _remove_diag(A):
    """Removes diagonal elements from a matrix"""
    # See: https://stackoverflow.com/a/46736275
    return A[~np.eye(A.shape[0],dtype=bool)].reshape(A.shape[0],-1)


def _remove_each_row_and_column(x):
    n = np.shape(x)[-1]
    inds = _remove_diag(
        np.repeat(np.arange(n)[None,:], n, axis=0)
    )
    y = x[...,inds,:]
    return np.take_along_axis(
        y,
        np.broadcast_to(
            inds[...,None,:],
            np.shape(y)[:-1] + (n-1,),
        ),
        axis=-1,
    )


def _remove_each_column(x):
    n = np.shape(x)[-1]
    inds = _remove_diag(
        np.repeat(np.arange(n)[None,:], n, axis=0)
    )
    return x[...,inds]


def _remove_each_row(x):
    n = np.shape(x)[-1]
    inds = _remove_diag(
        np.repeat(np.arange(n)[None,:], n, axis=0)
    )
    return x[...,inds,:]


def _geometric_sum(x, a, b):
    """sum_a^{b-1} x**i"""
    z = 1 - x
    return np.where(
        a >= b,
        0,
        np.where(
            z == 0,
            b - a, # case x==1
            (x**a - x**b) / z,
        )
    )


def _get_g(G, k, N, m):

    # We are interested in G[i][...]
    i = np.sum(k, axis=-1)

    # How many (N-1) length axes there are in total for all G[j] for j<i
    d = np.rint(_geometric_sum(N-1, 0, i)).astype(int)

    v = np.cumsum(np.insert(k, 0, 0, axis=-1), axis=-1)
    r = np.rint(_geometric_sum(N-1, v[...,:-1], v[...,1:])).astype(int)

    inds = (
        # Choose the correct G[i] (each has shape (N-1)^i)
        d +
        # Choose the correct element from each N-1 length axis
        np.sum(np.arange(N-1) * r, axis=-1)
    )

    return G[...,np.arange(N),inds]


def _get_f(F, k, N, ndim):
    sh0 = np.shape(F)
    sh = (
        sh0 if ndim == 0 else
        sh0[:-ndim]
    )
    # Reshape into a vector
    mask = np.any(k < 0, axis=-1, keepdims=True)
    f = np.reshape(F, sh + (-1,))

    v = np.cumsum(
        np.insert(
            np.where(
                mask,
                0,
                k,
            ),
            0,
            0,
            axis=-1,
        ),
        axis=-1,
    )
    # Force convert to integers what they should be anyway
    r = np.rint(_geometric_sum(N, v[...,:-1], v[...,1:])).astype(int)

    inds = np.sum(np.arange(N) * r, axis=-1)
    return np.where(
        mask[...,0],
        0,
        np.reshape(f[...,inds], sh + np.shape(k)[:-1]),
    )


def _recurrent_integrals(mu, Sigma, a, b, m):

    N = np.shape(mu)[-1]

    # Base case for 1D, that is, scalars
    if N == 1:
        Fs = []
        L = integral(mu, Sigma, a, b)
        Fs.append(L)
        s2 = Sigma[...,0]
        s = np.sqrt(s2)
        for k in range(0, m):
            c1 = 0 if k < 1 else k*s2*Fs[k-1][...,None,None]
            c2 = 0 if a is None else a**k * stats.norm.pdf((a-mu)/s)
            c3 = 0 if b is None else b**k * stats.norm.pdf((b-mu)/s)
            F = (mu * Fs[k][...,None] + c1 + s * (c2 - c3))
            Fs.append(F)
        return Fs

    s2 = diag(Sigma)

    # Compute the lower dimensional integrals
    if m > 0:

        def compute_lower_dimensional_integrals(y):
            Sigmaj = _remove_each_row(Sigma)
            Sigmajj = _remove_each_row_and_column(Sigma)
            muj = _remove_each_column(mu)
            # Shapes:
            #
            # Gs[0] :: (...) + ()
            # Gs[1] :: (...) + (N-1)
            # Gs[2] :: (...) + (N-1,N-1)
            # Gs[3] :: (...) + (N-1,N-1,N-1)
            Gs = _recurrent_integrals(
                muj + np.einsum("...jij,...j->...ji", Sigmaj, (y - mu) / s2),
                Sigmajj - np.einsum("...jaj,...jbj->...jab", Sigmaj, Sigmaj) / s2[...,None,None],
                None if a is None else _remove_each_column(a),
                None if b is None else _remove_each_column(b),
                m - 1,
            )
            # Put all in one huge vector for more efficient accessing
            sh = np.shape(Gs[0])
            return np.concatenate(
                [np.reshape(Gi, sh + (-1,)) for Gi in Gs],
                axis=-1,
            )

        Ga = (
            None if a is None else
            compute_lower_dimensional_integrals(a)
        )
        Gb = (
            None if b is None else
            compute_lower_dimensional_integrals(b)
        )

    # Compute the different total power integrals
    #
    # Shapes:
    #
    # Fs[0] :: (...) + ()
    # Fs[1] :: (...) + (N,)
    # Fs[2] :: (...) + (N,N)
    # Fs[3] :: (...) + (N,N,N)
    # and so on
    Fs = []
    Fs.append(np.asarray(integral(mu, Sigma, a, b)))
    al = a
    bl = b
    mul = mu
    Sigmal = Sigma
    stdl = np.sqrt(s2)
    k = np.zeros(N, dtype=int)
    I = np.eye(N, dtype=int)
    Il = I
    for l in range(1, m+1):
        c1 = (
            np.zeros(N) if l < 2 else
            k * _get_f(Fs[l-2], k[...,None,:] - I, N, ndim=l-2)
        )
        c2 = (
            0 if al is None else
            np.where(
                np.isneginf(al),
                0,
                al**k * stats.norm.pdf(al, mul, stdl) * _get_g(
                    Ga,
                    _remove_each_column(k),
                    N,
                    m-1,
                ),
            )
        )
        c3 = (
            0 if bl is None else
            np.where(
                np.isposinf(bl),
                0,
                bl**k * stats.norm.pdf(bl, mul, stdl) * _get_g(
                    Gb,
                    _remove_each_column(k),
                    N,
                    m-1,
                ),
            )
        )
        c = c1 + c2 - c3
        F = mul * Fs[l-1][...,None] + mvdot(Sigmal, c)
        Fs.append(F)

        # Add new axes for the next iteration round
        al = (None if al is None else al[...,None,:])
        bl = (None if bl is None else bl[...,None,:])
        mul = mul[...,None,:]
        stdl = stdl[...,None,:]
        Sigmal = Sigmal[...,None,:,:]
        k = k + Il
        Il = Il[...,None,:]

    return Fs


def moments(mu, Sigma, a, b, m):

    # Broadcast and convert to arrays
    # sh = np.broadcast_shapes(
    #     np.shape(mu)[:-1],
    #     np.shape(Sigma)[:-2],
    #     () if a is None else np.shape(a)[:-1],
    #     () if b is None else np.shape(b)[:-1],
    # )
    # N = np.shape(mu)[-1]
    # mu = np.broadcast_to(mu, sh + (N,))
    # Sigma = np.broadcast_to(Sigma, sh + (N,N))
    # a = None if a is None else np.broadcast_to(a, sh + (N,))
    # b = None if b is None else np.broadcast_to(b, sh + (N,))

    Fs = _recurrent_integrals(
        np.asarray(mu),
        np.asarray(Sigma),
        None if a is None else np.asarray(a),
        None if b is None else np.asarray(b),
        m,
    )
    L = Fs[0]
    # Treat the first element a bit differently by not dividing as it would give
    # trivial 1. But divide the other elements so you'll get the expectations.
    return [L] + [Fi / L for Fi in Fs[1:]]