public
Created

  • Download Gist
gsm.h
C++
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
#ifndef GSM_H
#define GSM_H
 
#include "Eigen/Core"
#include "distribution.h"
#include "exception.h"
#include <iostream>
#include <cmath>
 
using namespace Eigen;
using std::sqrt;
 
class GSM : public Distribution {
public:
GSM(int dim = 1, int numScales = 10);
 
inline int dim();
inline int numScales();
 
inline ArrayXd scales();
inline void setScales(MatrixXd scales);
 
inline double variance();
inline void normalize();
 
virtual bool train(const MatrixXd& data, int maxIter = 100, double tol = 1e-5);
 
virtual MatrixXd sample(int numSamples = 1);
 
virtual Array<double, 1, Dynamic> samplePosterior(const MatrixXd& data);
 
virtual ArrayXXd posterior(const MatrixXd& data);
virtual ArrayXXd posterior(const MatrixXd& data, const RowVectorXd& sqNorms);
 
virtual ArrayXXd logJoint(const MatrixXd& data);
virtual ArrayXXd logJoint(const MatrixXd& data, const RowVectorXd& sqNorms);
 
virtual Array<double, 1, Dynamic> logLikelihood(const MatrixXd& data);
virtual Array<double, 1, Dynamic> logLikelihood(const MatrixXd& data, const RowVectorXd& sqNorms);
 
virtual Array<double, 1, Dynamic> energy(const MatrixXd& data);
virtual Array<double, 1, Dynamic> energy(const MatrixXd& data, const RowVectorXd& sqNorms);
 
virtual ArrayXXd energyGradient(const MatrixXd& data);
 
protected:
int mDim;
int mNumScales;
ArrayXd mScales;
};
 
 
 
inline int GSM::dim() {
return mDim;
}
 
 
 
inline int GSM::numScales() {
return mNumScales;
}
 
 
 
inline ArrayXd GSM::scales() {
return mScales;
}
 
 
 
inline double GSM::variance() {
return mScales.square().mean();
}
 
 
 
inline void GSM::normalize() {
mScales /= sqrt(variance());
}
 
 
 
inline void GSM::setScales(MatrixXd scales) {
// turn row vector into column vector
if(scales.cols() > scales.rows())
scales.transposeInPlace();
 
if(scales.rows() != mNumScales || scales.cols() != 1)
throw Exception("Wrong number of scales.");
 
mScales = scales;
}
 
#endif
gsminterface.h
C
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 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
 
#ifndef GSMINTERFACE_H
#define GSMINTERFACE_H
 
#include "gsm.h"
#include "exception.h"
#include "pyutils.h"
#include "Eigen/Core"
#include <iostream>
 
using namespace Eigen;
 
struct GSMObject {
PyObject_HEAD
GSM* gsm;
};
 
 
 
/**
* Create a new GSM object.
*/
static PyObject* GSM_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
PyObject* self = type->tp_alloc(type, 0);
 
if(self)
reinterpret_cast<GSMObject*>(self)->gsm = 0;
 
return self;
}
 
 
 
/**
* Initialize GSM object.
*/
static int GSM_init(GSMObject* self, PyObject* args, PyObject* kwds) {
char* kwlist[] = {"dim", "num_scales", 0};
int dim;
int num_scales = 10;
 
// read arguments
if(!PyArg_ParseTupleAndKeywords(args, kwds, "i|i", kwlist,
&dim, &num_scales))
return -1;
 
// create actual GSM instance
self->gsm = new GSM(dim, num_scales);
 
return 0;
}
 
 
 
/**
* Delete GSM object.
*/
static void GSM_dealloc(GSMObject* self) {
// delete actual GSM instance
delete self->gsm;
 
// delete GSM object
self->ob_type->tp_free(reinterpret_cast<PyObject*>(self));
}
 
 
 
/**
* Return number of visible units.
*/
static PyObject* GSM_dim(GSMObject* self, PyObject*, void*) {
return PyInt_FromLong(self->gsm->dim());
}
 
 
 
/**
* Return number of hidden units.
*/
static PyObject* GSM_num_scales(GSMObject* self, PyObject*, void*) {
return PyInt_FromLong(self->gsm->numScales());
}
 
 
 
/**
* Return copy of linear basis.
*/
static PyObject* GSM_scales(GSMObject* self, PyObject*, void*) {
return PyArray_FromMatrixXd(self->gsm->scales());
}
 
 
 
/**
* Replace linear basis.
*/
static int GSM_set_scales(GSMObject* self, PyObject* value, void*) {
if(!PyArray_Check(value)) {
PyErr_SetString(PyExc_TypeError, "Scales should be of type `ndarray`.");
return -1;
}
 
try {
self->gsm->setScales(PyArray_ToMatrixXd(value));
 
} catch(Exception exception) {
PyErr_SetString(PyExc_RuntimeError, exception.message());
return -1;
}
 
return 0;
}
 
 
 
static PyObject* GSM_variance(GSMObject* self, PyObject*, PyObject*) {
try {
return PyFloat_FromDouble(self->gsm->variance());
} catch(Exception exception) {
PyErr_SetString(PyExc_RuntimeError, exception.message());
return 0;
}
}
 
 
 
static PyObject* GSM_normalize(GSMObject* self, PyObject*, PyObject*) {
try {
self->gsm->normalize();
} catch(Exception exception) {
PyErr_SetString(PyExc_RuntimeError, exception.message());
return 0;
}
 
Py_INCREF(Py_None);
return Py_None;
}
 
 
 
static PyObject* GSM_train(GSMObject* self, PyObject* args, PyObject* kwds) {
char* kwlist[] = {"data", "max_iter", "tol", 0};
 
PyObject* data;
int max_iter = 100;
double tol = 1e-5;
 
// read arguments
if(!PyArg_ParseTupleAndKeywords(args, kwds, "O|id", kwlist, &data, &max_iter, &tol))
return 0;
 
// make sure data is stored in NumPy array
if(!PyArray_Check(data)) {
PyErr_SetString(PyExc_TypeError, "Data has to be stored in a NumPy array.");
return 0;
}
 
try {
if(self->gsm->train(PyArray_ToMatrixXd(data), max_iter, tol)) {
Py_INCREF(Py_True);
return Py_True;
} else {
Py_INCREF(Py_False);
return Py_False;
}
} catch(Exception exception) {
PyErr_SetString(PyExc_RuntimeError, exception.message());
return 0;
}
 
return 0;
}
 
 
 
static PyObject* GSM_posterior(GSMObject* self, PyObject* args, PyObject* kwds) {
char* kwlist[] = {"data", 0};
 
PyObject* data;
 
// read arguments
if(!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &data))
return 0;
 
// make sure data is stored in NumPy array
if(!PyArray_Check(data)) {
PyErr_SetString(PyExc_TypeError, "Data has to be stored in a NumPy array.");
return 0;
}
 
try {
return PyArray_FromMatrixXd(self->gsm->posterior(PyArray_ToMatrixXd(data)));
} catch(Exception exception) {
PyErr_SetString(PyExc_RuntimeError, exception.message());
return 0;
}
}
 
 
 
static PyObject* GSM_sample(GSMObject* self, PyObject* args, PyObject* kwds) {
char* kwlist[] = {"num_samples", 0};
 
int num_samples = 1;
 
if(!PyArg_ParseTupleAndKeywords(args, kwds, "|i", kwlist, &num_samples))
return 0;
 
try {
return PyArray_FromMatrixXd(self->gsm->sample(num_samples));
} catch(Exception exception) {
PyErr_SetString(PyExc_RuntimeError, exception.message());
return 0;
}
}
 
 
 
static PyObject* GSM_sample_posterior(GSMObject* self, PyObject* args, PyObject* kwds) {
char* kwlist[] = {"data", 0};
 
PyObject* data;
 
// read arguments
if(!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &data))
return 0;
 
// make sure data is stored in NumPy array
if(!PyArray_Check(data)) {
PyErr_SetString(PyExc_TypeError, "Data has to be stored in a NumPy array.");
return 0;
}
 
try {
return PyArray_FromMatrixXd(self->gsm->samplePosterior(PyArray_ToMatrixXd(data)));
} catch(Exception exception) {
PyErr_SetString(PyExc_RuntimeError, exception.message());
return 0;
}
}
 
 
 
static PyObject* GSM_loglikelihood(GSMObject* self, PyObject* args, PyObject* kwds) {
char* kwlist[] = {"data", 0};
 
PyObject* data;
 
// read arguments
if(!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &data))
return 0;
 
// make sure data is stored in NumPy array
if(!PyArray_Check(data)) {
PyErr_SetString(PyExc_TypeError, "Data has to be stored in a NumPy array.");
return 0;
}
 
try {
return PyArray_FromMatrixXd(self->gsm->logLikelihood(PyArray_ToMatrixXd(data)));
} catch(Exception exception) {
PyErr_SetString(PyExc_RuntimeError, exception.message());
return 0;
}
}
 
 
 
static PyObject* GSM_energy(GSMObject* self, PyObject* args, PyObject* kwds) {
char* kwlist[] = {"data", 0};
 
PyObject* data;
 
// read arguments
if(!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &data))
return 0;
 
// make sure data is stored in NumPy array
if(!PyArray_Check(data)) {
PyErr_SetString(PyExc_TypeError, "Data has to be stored in a NumPy array.");
return 0;
}
 
try {
return PyArray_FromMatrixXd(self->gsm->energy(PyArray_ToMatrixXd(data)));
} catch(Exception exception) {
PyErr_SetString(PyExc_RuntimeError, exception.message());
return 0;
}
}
 
 
 
static PyObject* GSM_energy_gradient(GSMObject* self, PyObject* args, PyObject* kwds) {
char* kwlist[] = {"data", 0};
 
PyObject* data;
 
// read arguments
if(!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &data))
return 0;
 
// make sure data is stored in NumPy array
if(!PyArray_Check(data)) {
PyErr_SetString(PyExc_TypeError, "Data has to be stored in a NumPy array.");
return 0;
}
 
try {
return PyArray_FromMatrixXd(self->gsm->energyGradient(PyArray_ToMatrixXd(data)));
} catch(Exception exception) {
PyErr_SetString(PyExc_RuntimeError, exception.message());
return 0;
}
}
 
 
 
static PyGetSetDef GSM_getset[] = {
{"dim", (getter)GSM_dim, 0, 0},
{"num_scales", (getter)GSM_num_scales, 0, 0},
{"scales", (getter)GSM_scales, (setter)GSM_set_scales, 0},
{0}
};
 
 
 
static PyMethodDef GSM_methods[] = {
{"train", (PyCFunction)GSM_train, METH_VARARGS|METH_KEYWORDS, 0},
{"posterior", (PyCFunction)GSM_posterior, METH_VARARGS|METH_KEYWORDS, 0},
{"variance", (PyCFunction)GSM_variance, METH_NOARGS, 0},
{"normalize", (PyCFunction)GSM_normalize, METH_NOARGS, 0},
{"sample", (PyCFunction)GSM_sample, METH_VARARGS|METH_KEYWORDS, 0},
{"sample_posterior", (PyCFunction)GSM_sample_posterior, METH_VARARGS|METH_KEYWORDS, 0},
{"loglikelihood", (PyCFunction)GSM_loglikelihood, METH_VARARGS|METH_KEYWORDS, 0},
{"energy", (PyCFunction)GSM_energy, METH_VARARGS|METH_KEYWORDS, 0},
{"energy_gradient", (PyCFunction)GSM_energy_gradient, METH_VARARGS|METH_KEYWORDS, 0},
{0}
};
 
 
 
static PyTypeObject GSM_type = {
PyObject_HEAD_INIT(0)
0, /*ob_size*/
"isa.GSM", /*tp_name*/
sizeof(GSMObject), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)GSM_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
GSM_methods, /*tp_methods*/
0, /*tp_members*/
GSM_getset, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
(initproc)GSM_init, /*tp_init*/
0, /*tp_alloc*/
GSM_new, /*tp_new*/
};
 
#endif
module.cpp
C++
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
#include <Python.h>
#include <arrayobject.h>
#include <structmember.h>
#include <stdlib.h>
#include <time.h>
#include "isainterface.h"
#include "gsminterface.h"
 
PyMODINIT_FUNC initisa() {
// set random seed
timeval time;
gettimeofday(&time, 0);
srand(time.tv_usec * time.tv_sec);
 
// initialize NumPy
import_array();
 
// create module object
PyObject* module = Py_InitModule("isa", 0);
 
// initialize types
if(PyType_Ready(&ISA_type) < 0)
return;
if(PyType_Ready(&GSM_type) < 0)
return;
 
// add types to module
Py_INCREF(&ISA_type);
PyModule_AddObject(module, "ISA", reinterpret_cast<PyObject*>(&ISA_type));
Py_INCREF(&GSM_type);
PyModule_AddObject(module, "GSM", reinterpret_cast<PyObject*>(&GSM_type));
}
setup.py
Python
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
import os
import numpy
from distutils.core import setup, Extension
from distutils.ccompiler import new_compiler
 
modules = [
Extension('isa',
language='c++',
sources=[
'code/isa/src/isa.cpp',
'code/isa/src/gsm.cpp',
'code/isa/src/utils.cpp',
'code/isa/src/module.cpp',
'code/isa/src/distribution.cpp'],
include_dirs=[
'code',
'code/isa/include',
os.path.join(numpy.__path__[0], 'core/include/numpy')],
library_dirs=[],
libraries=[],
extra_link_args=[
'-lgomp'],
extra_compile_args=[
'-fopenmp',
'-Wno-parentheses',
'-Wno-write-strings'])]
 
setup(
name='isa',
version='0.1',
description='',
ext_modules=modules)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.