variational_models.py 5.54 KB
Newer Older
Jakob Knollmüller's avatar
Jakob Knollmüller committed
1
2
import numpy as np
from ..operators.multifield_flattener import MultifieldFlattener
Jakob Knollmüller's avatar
Jakob Knollmüller committed
3
from ..operators.simple_linear_operators import FieldAdapter, PartialExtractor
Jakob Knollmüller's avatar
Jakob Knollmüller committed
4
5
from ..operators.energy_operators import EnergyOperator
from ..operators.sandwich_operator import SandwichOperator
Jakob Knollmüller's avatar
Jakob Knollmüller committed
6
7
8
from ..operators.linear_operator import LinearOperator
from ..operators.einsum import MultiLinearEinsum
from ..sugar import full, from_random, makeField, domain_union
Jakob Knollmüller's avatar
Jakob Knollmüller committed
9
10
11
from ..linearization import Linearization
from ..field import Field
from ..multi_field import MultiField
Jakob Knollmüller's avatar
Jakob Knollmüller committed
12
13
from ..domain_tuple import DomainTuple
from ..domains.unstructured_domain import UnstructuredDomain
Jakob Knollmüller's avatar
Jakob Knollmüller committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

class MeanfieldModel():
    def __init__(self, domain):
        self.domain = domain
        self.Flat = MultifieldFlattener(self.domain)

        self.std = FieldAdapter(self.Flat.target,'var').absolute()
        self.latent = FieldAdapter(self.Flat.target,'latent')
        self.mean = FieldAdapter(self.Flat.target,'mean')
        self.generator = self.Flat.adjoint(self.mean + self.std * self.latent)
        self.entropy = GaussianEntropy(self.std.target) @ self.std

    def get_initial_pos(self, initial_mean=None):
        initial_pos = from_random(self.generator.domain).to_dict()
        initial_pos['latent'] = full(self.generator.domain['latent'], 0.)
        initial_pos['var'] = full(self.generator.domain['var'], 1.)

        if initial_mean is None:
            initial_mean = 0.1*from_random(self.generator.target)

        initial_pos['mean'] = self.Flat(initial_mean)
        return MultiField.from_dict(initial_pos)

Jakob Knollmüller's avatar
Jakob Knollmüller committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class FullCovarianceModel():
    def __init__(self, domain):
        self.domain = domain
        self.Flat = MultifieldFlattener(self.domain)
        one_space = UnstructuredDomain(1)
        self.latent_domain = self.Flat.target[0]
        N_tri = self.latent_domain.shape[0]*(self.latent_domain.shape[0]+1)//2
        triangular_space = DomainTuple.make(UnstructuredDomain(N_tri))
        tri = FieldAdapter(triangular_space, 'cov')
        mat_space = DomainTuple.make((self.latent_domain,self.latent_domain))
        lat_mat_space = DomainTuple.make((one_space,self.latent_domain))
        lat = FieldAdapter(lat_mat_space,'latent')
        LT = LowerTriangularProjector(triangular_space,mat_space)
        mean = FieldAdapter(self.latent_domain,'mean')
        cov = LT @ tri
        co = FieldAdapter(cov.target, 'co')

        matmul_setup_dom = domain_union((co.domain,lat.domain))
        co_part = PartialExtractor(matmul_setup_dom, co.domain)
        lat_part = PartialExtractor(matmul_setup_dom, lat.domain)
        matmul_setup = lat_part.adjoint @ lat.adjoint @ lat + co_part.adjoint @ co.adjoint @ cov
Jakob Knollmüller's avatar
debug    
Jakob Knollmüller committed
58
        breakpoint()
Jakob Knollmüller's avatar
Jakob Knollmüller committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
        MatMult = MultiLinearEinsum(matmul_setup.domain,'ij,ki->jk', key_order=('co','latent'))

        Resp = Respacer(MatMult.target, mean.target)
        self.generator = self.Flat.adjoint @ (mean + Resp @ MatMult @ matmul_setup)
        
        Diag = DiagonalSelector(cov.target, self.Flat.target)
        diag_cov = Diag(cov).absolute()
        self.entropy = GaussianEntropy(diag_cov.target) @ diag_cov

    def get_initial_pos(self, initial_mean = None):
        initial_pos = from_random(self.generator.domain).to_dict()
        initial_pos['latent'] = full(self.latent_domain.domain['latent'], 0.)
        diag_tri = np.diag(np.ones(self.latent_domain.shape[0]))[np.tril_indices(self.latent_domain.shape[0])]
        initial_pos['cov'] = makeField(self.generator.domain['cov'], diag_tri)
        if initial_mean is None:
            initial_mean = 0.1*from_random(self.generator.target)
        initial_pos['mean'] = self.Flat(initial_mean)
        return MultiField.from_dict(initial_pos)


Jakob Knollmüller's avatar
Jakob Knollmüller committed
79
80
81
82
83
84
85
86
87
88
89
90

class GaussianEntropy(EnergyOperator):
    def __init__(self, domain):
        self._domain = domain

    def apply(self, x):
        self._check_input(x)
        res =  -0.5* (2*np.pi*np.e*x**2).log().sum()
        if not isinstance(x, Linearization):
            return Field.scalar(res)
        if not x.want_metric:
            return res
Jakob Knollmüller's avatar
Jakob Knollmüller committed
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
        return res.add_metric(SandwichOperator.make(res.jac)) #FIXME not sure about metric


class LowerTriangularProjector(LinearOperator):
    def __init__(self, domain, target):
        self._domain = domain
        self._target = target
        self._indices=np.tril_indices(target.shape[1])
        self._capability = self.TIMES | self.ADJOINT_TIMES

    def apply(self, x, mode):
        self._check_mode(mode)
        if mode == self.TIMES:
            mat = np.zeros(self._target.shape[1:])
            mat[self._indices] = x.val
            return makeField(self._target,mat.reshape((1,)+mat.shape))
        return makeField(self._domain, x.val[0][self._indices].reshape(self._domain.shape))

class DiagonalSelector(LinearOperator):
    def __init__(self, domain, target):
        self._domain = domain
        self._target = target
        self._capability = self.TIMES | self.ADJOINT_TIMES

    def apply(self, x, mode):
        self._check_mode(mode)
        if mode == self.TIMES:
            result = np.diag(x.val[0])
            return makeField(self._target,result)
        return makeField(self._domain,np.diag(x.val).reshape(self._domain.shape))


class Respacer(LinearOperator):
    def __init__(self, domain, target):
        self._domain = domain
        self._target = target
        self._capability = self.TIMES | self.ADJOINT_TIMES


    def apply(self,x,mode):
        self._check_mode(mode)
        if mode == self.TIMES:
            return makeField(self._target,x.val.reshape(self._target.shape))
        return makeField(self._domain,x.val.reshape(self._domain.shape))