potential.i 9.34 KB
Newer Older
1 2 3 4 5
%ignore gum::MultiDimWithOffset;
%ignore gum::MultiDimImplementation;
%ignore gum::MultiDimInterface;
%ignore gum::MultiDimDecorator;
%ignore gum::MultiDimArray;
6

7
/* Synchronisation between gum::Potential and numpy array */
8
%pythonappend gum::Potential<double>::Potential %{
9
        self._notSync=True
10
%}
11
%pythonappend gum::Potential<double>::remove %{
12 13
        self._notSync=True
%}
14
%pythonappend gum::Potential<double>::set %{
15
        self._notSync=True
16 17
%}

18 19
%define CHANGE_THEN_RETURN_SELF(methodname)
%pythonappend gum::Potential<double>::methodname %{
20 21 22
        self._notSync=True
        return self
%}
23 24 25 26 27 28 29 30 31 32
%enddef

CHANGE_THEN_RETURN_SELF(add)
CHANGE_THEN_RETURN_SELF(abs)
CHANGE_THEN_RETURN_SELF(normalize)
CHANGE_THEN_RETURN_SELF(fillWith)
CHANGE_THEN_RETURN_SELF(sq)
CHANGE_THEN_RETURN_SELF(scale)
CHANGE_THEN_RETURN_SELF(translate)
CHANGE_THEN_RETURN_SELF(normalizeAsCPT)
33
CHANGE_THEN_RETURN_SELF(set)
34

35 36 37 38
%rename ("$ignore", fullname=1) gum::Potential<double>::margSumOut(const Set<const DiscreteVariable*>& del_vars) const;
%rename ("$ignore", fullname=1) gum::Potential<double>::margProdOut(const Set<const DiscreteVariable*>& del_vars) const;
%rename ("$ignore", fullname=1) gum::Potential<double>::margMaxOut(const Set<const DiscreteVariable*>& del_vars) const;
%rename ("$ignore", fullname=1) gum::Potential<double>::margMinOut(const Set<const DiscreteVariable*>& del_vars) const;
39 40 41 42
%rename ("$ignore", fullname=1) gum::Potential<double>::margSumIn(const Set<const DiscreteVariable*>& kept_vars) const;
%rename ("$ignore", fullname=1) gum::Potential<double>::margProdIn(const Set<const DiscreteVariable*>& kept_vars) const;
%rename ("$ignore", fullname=1) gum::Potential<double>::margMaxIn(const Set<const DiscreteVariable*>& kept_vars) const;
%rename ("$ignore", fullname=1) gum::Potential<double>::margMinIn(const Set<const DiscreteVariable*>& kept_vars) const;
43

44 45 46
%rename ("$ignore", fullname=1) gum::Potential<double>::reorganize(const Set<const DiscreteVariable*>& vars) const;
%rename ("$ignore", fullname=1) gum::Potential<double>::putFirst(const DiscreteVariable* var) const;

47
%extend gum::Potential<double> {
48 49 50 51 52 53
    Potential<double> extract(PyObject* dict) {
      gum::Instantiation inst;
      PyAgrumHelper::fillInstantiationFromPyObject(self,inst,dict);
      return self->extract(inst);
    }

54 55 56 57 58 59 60 61 62 63 64 65 66 67
    Potential<double>
    reorganize(PyObject* varnames ) const {
      std::vector<const gum::DiscreteVariable*> v;
      PyAgrumHelper::fillDVVectorFromPyObject(self,v,varnames); //from helpers.h
      return self->reorganize(v);
    }

    Potential<double>
    putFirst(PyObject* varname ) const {
      const gum::DiscreteVariable* v;
      PyAgrumHelper::fillDVFromPyObject(self,v,varname); //from helpers.h
      return self->putFirst(v);
    }

68 69 70 71 72 73
    Potential<double>
    margSumOut( PyObject* varnames ) const {
      gum::Set<const gum::DiscreteVariable*> s;
      PyAgrumHelper::fillDVSetFromPyObject(self,s,varnames); //from helpers.h
      return self->margSumOut(s);
    }
74

75 76 77 78 79 80
    Potential<double>
    margProdOut( PyObject* varnames ) const {
      gum::Set<const gum::DiscreteVariable*> s;
      PyAgrumHelper::fillDVSetFromPyObject(self,s,varnames); //from helpers.h
      return self->margProdOut(s);
    }
81

82 83 84 85 86 87
    Potential<double>
    margMaxOut( PyObject* varnames ) const {
      gum::Set<const gum::DiscreteVariable*> s;
      PyAgrumHelper::fillDVSetFromPyObject(self,s,varnames); //from helpers.h
      return self->margMaxOut(s);
    }
88

89 90 91 92 93 94
    Potential<double>
    margMinOut( PyObject* varnames ) const {
      gum::Set<const gum::DiscreteVariable*> s;
      PyAgrumHelper::fillDVSetFromPyObject(self,s,varnames); //from helpers.h
      return self->margMinOut(s);
    }
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
    Potential<double>
    margSumIn( PyObject* varnames ) const {
      gum::Set<const gum::DiscreteVariable*> s;
      PyAgrumHelper::fillDVSetFromPyObject(self,s,varnames); //from helpers.h
      return self->margSumIn(s);
    }

    Potential<double>
    margProdIn( PyObject* varnames ) const {
      gum::Set<const gum::DiscreteVariable*> s;
      PyAgrumHelper::fillDVSetFromPyObject(self,s,varnames); //from helpers.h
      return self->margProdIn(s);
    }

    Potential<double>
    margMaxIn( PyObject* varnames ) const {
      gum::Set<const gum::DiscreteVariable*> s;
      PyAgrumHelper::fillDVSetFromPyObject(self,s,varnames); //from helpers.h
      return self->margMaxIn(s);
    }

    Potential<double>
    margMinIn( PyObject* varnames ) const {
      gum::Set<const gum::DiscreteVariable*> s;
      PyAgrumHelper::fillDVSetFromPyObject(self,s,varnames); //from helpers.h
      return self->margMinIn(s);
    }
123

124 125 126 127
    // division for python3
    gum::Potential<double> __truediv__(const gum::Potential<double>& b) {
      return *self /b;
    }
128

129 130 131 132
    // division for python2
    gum::Potential<double> __div__(const gum::Potential<double>& b) {
      return *self/b;
    }
133

134 135 136 137
    // equality
    bool __eq__(const gum::Potential<double>& b) {
      return *self==b;
    }
138

139 140 141 142
    // non equality
    bool __ne__(const gum::Potential<double>& b) {
      return *self!=b;
    }
143 144


145
  %pythoncode {
146

147
    def variablesSequence(self):
148 149 150 151 152 153
        """
        Returns
        -------
        list
            a list containing the sequence of variables
        """
154 155 156 157
        varlist = []
        for i in range(0, self.nbrDim()):
            varlist.append(self.variable(i))
        return varlist
158
  }
159 160 161 162 163
}

// copy: M indicates the modifications
%feature("shadow") gum::Potential<double>::__fill_distrib__ %{
    def __fill_distrib__(self):
164 165 166 167 168
      if not hasattr(self,'_notSync'):
        self._notSync=True

      if self._notSync:
        self._notSync=False
169 170 171
        self._var_names = []
        self._var_dims = []
        if self.empty():
172 173
            i = Instantiation(self)
            content = [self.get(i)]
174 175
            self.__distrib__ = numpy.array(content, dtype=numpy.float64) #M
            return
176

177
        content = []
178
        i = Instantiation(self)
179
        i.setFirst()
180 181 182 183 184 185
        while not i.end():
            content.append(self.get(i))
            i.inc()
        self.__distrib__ = numpy.array(content, dtype=numpy.float64) #M
        for var in self.variablesSequence():
            self._var_names.append(var.name())
186
            self._var_dims.append(var.domainSize())
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
        self._var_names.reverse()
        self._var_dims.reverse()
        self.__distrib__.shape = tuple(self._var_dims)
%}


%feature("shadow") gum::Potential::__indexfromdict__ %{
    def __indexfromdict__(self, id_dict):
        index = []
        for name, dim in zip(self._var_names, self._var_dims):
            if name in id_dict:
                id_value = id_dict[name]
                if isinstance(id_value, str):
                    # id_value is a label of a LabelizedVar
                    i = self._var_names.index(name)
                    var = self.variable(len(self._var_names) - 1 - i)
                    id_value = var[id_value]
                if id_value >= dim:
                    raise IndexError("\"%s\" size is %d !"%(name, dim))
                index.append(id_value)
            else:
                index.append(slice(None, None, None)) # equivalent to ':'
        return tuple(index)
%}

%feature("shadow") gum::Potential::tolist %{
    def tolist(self):
214 215 216 217 218 219
        """
        Returns
        -------
        list
            the potential as a list
        """
220 221 222 223 224 225
        self.__fill_distrib__()
        return self.__distrib__.tolist()
%}

%feature("shadow") gum::Potential::toarray %{
    def toarray(self):
226 227 228 229 230 231
        """
        Returns
        -------
        array
            the potential as an array
        """
232 233 234 235 236 237 238 239
        return numpy.array(self.tolist())
%}


%feature("shadow") gum::Potential::__getitem__ %{
    def __getitem__(self, id):
        self.__fill_distrib__()
        if self.empty():
240
            return self.__distrib__[0]
241

242 243 244 245 246 247 248 249 250 251 252 253
        if isinstance(id, dict):
            id_slice = self.__indexfromdict__(id)
        else:
            id_slice = id
        return self.__distrib__[id_slice]
%}


%feature("shadow") gum::Potential::__setitem__ %{
    def __setitem__(self, id, value):
        self.__fill_distrib__()
        if self.empty():
254 255
            self.fill(value)
            self.__distrib__= numpy.array([value], dtype=numpy.float64) #M
256 257
            return

258 259 260 261 262
        if isinstance(id, dict):
            id_slice = self.__indexfromdict__(id)
        else:
            id_slice = id
        self.__distrib__[id_slice] = value
263
        self.fillWith(self.__distrib__.reshape(self.__distrib__.size).tolist())
264 265 266 267 268 269
%}


%feature("shadow") gum::Potential::var_names %{
    @property
    def var_names(self):
270 271 272 273 274 275
        """
        Returns
        -------
        list
            a list containing the name of each variables in the potential
        """
276 277 278 279 280 281 282 283
        self.__fill_distrib__()
        return self._var_names
%}


%feature("shadow") gum::Potential::var_dims %{
    @property
    def var_dims(self):
284 285 286 287 288 289
        """
        Returns
        -------
        list
            a list containing the dimensions of each variables in the potential
        """
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
        self.__fill_distrib__()
        return self._var_dims
%}


// these void class extensions are rewritten by "shadow" declarations
%extend gum::Potential<double> {
    void __fill_distrib__() {}
    PyObject * __indexfromdict__(PyObject *id_dict) { return NULL; }
    PyObject *tolist() { return NULL; }
    PyObject *toarray() { return NULL; }
    void __getitem__(PyObject *id) {}
    void __setitem__(PyObject *id, PyObject *value) {}
    void var_names() {}
    void var_dims() {}
}