Commit 4df8130f authored by Hakan GIRGIN's avatar Hakan GIRGIN
Browse files

Compatibility with Python3

parent 1f269f77
......@@ -13,12 +13,12 @@ from .mtmm import MTMM, VBayesianGMM, VMBayesianGMM, VBayesianHMM
try:
import gui
except ImportError as e:
print "Could not import gui: {0}".format(e.message)
print "run : sudo apt-get install tkinter"
print("Could not import gui: {0}".format(e.message))
print("run : sudo apt-get install tkinter")
except:
print "Unexpected error:", sys.exc_info()[0]
print("Unexpected error:", sys.exc_info()[0])
raise
import utils
import plot
from . import utils
from . import plot
import numpy as np
from model import *
from functions import multi_variate_normal
from .model import *
from .functions import multi_variate_normal
from scipy.linalg import block_diag
from termcolor import colored
from mvn import MVN
from .mvn import MVN
class GMM(Model):
......@@ -364,10 +364,10 @@ class GMM(Model):
'acj,aic->aij', np.einsum('aic,ac->aci', dx, GAMMA2), dx) + reg_finish
if verbose:
print colored('Converged after %d iterations: %.3e' % (it, LL[it]), 'red', 'on_white')
print(colored('Converged after %d iterations: %.3e' % (it, LL[it]), 'red', 'on_white'))
return GAMMA
if verbose:
print "GMM did not converge before reaching max iteration. Consider augmenting the number of max iterations."
print("GMM did not converge before reaching max iteration. Consider augmenting the number of max iterations.")
return GAMMA
......
from interactive import Interactive
from multi_cs_demos import MutliCsInteractiveDemos, MultiCsInteractive
from demos import InteractiveDemos
\ No newline at end of file
from .interactive import Interactive
from .multi_cs_demos import MutliCsInteractiveDemos, MultiCsInteractive
from .demos import InteractiveDemos
\ No newline at end of file
#!/usr/bin/env python2.7
import numpy as np
import os
import matplotlib.pyplot as plt
from pbdlib.gui import Interactive
from .interactive import Interactive
from termcolor import colored
try:
import sys
if sys.version_info[0] == 3:
import tkinter as tk
except ImportError:
from tkinter.filedialog import asksaveasfilename
else:
import Tkinter as tk
except:
raise
from tkFileDialog import asksaveasfilename
from tkFileDialog import asksaveasfilename
from matplotlib import gridspec
import pbdlib as pbd
from ... import pbdlib as pbd
class Robot(object):
def __init__(self, T):
......@@ -80,13 +78,13 @@ class InteractiveDemos(Interactive, Robot):
try:
self.demos = np.load(self.path + filename + '.npy')[()]
self.nb_demos = self.demos['x'].__len__(); self.params['current_demo'][2] = self.nb_demos - 1
print colored('Existing skill, demos loaded', 'green')
print(colored('Existing skill, demos loaded', 'green'))
self.replot_demos()
self.fig.canvas.draw()
self.loaded = True
except:
self.demos = {'x': [], 'dx': []}
print colored('Not existing skill', 'red')
print(colored('Not existing skill', 'red'))
def highlight_demos(self):
data = self.demos['x'][self.params['current_demo'][0]]
......
......@@ -19,7 +19,7 @@ class Interactive(object):
def key_event(self, event):
c = event.key
print c
print(c)
if c in ['\x1b', '\x03']:
done = True
elif c in self.bindings:
......@@ -51,7 +51,7 @@ class Interactive(object):
@staticmethod
def pretty_print(text):
print colored("#" * 60, 'green'), "\n", colored(text, 'green'),"\n", colored("#" * 60, 'green')
print(colored("#" * 60, 'green'), "\n", colored(text, 'green'),"\n", colored("#" * 60, 'green'))
def move_event(self, event):
pass
......
from demos import *
from .demos import *
from ... import pbdlib as pbd
class CoordinateSys2D(object):
x, alpha, d = np.array([0, 0]), 0, 0
......
from termcolor import colored
import numpy as np
from pbdlib.functions import *
from pbdlib.model import *
from pbdlib.gmm import *
from .functions import *
from .model import *
from .gmm import *
import math
from numpy.linalg import inv, pinv, norm, det
......@@ -20,7 +20,7 @@ class HMM(GMM):
@property
def init_priors(self):
if self._init_priors is None:
print colored("HMM init priors not defined, initializing to uniform", 'red', 'on_white')
print(colored("HMM init priors not defined, initializing to uniform", 'red', 'on_white'))
self._init_priors = np.ones(self.nb_states) / self.nb_states
return self._init_priors
......@@ -32,7 +32,7 @@ class HMM(GMM):
@property
def trans(self):
if self._trans is None:
print colored("HMM transition matrix not defined, initializing to uniform", 'red', 'on_white')
print(colored("HMM transition matrix not defined, initializing to uniform", 'red', 'on_white'))
self._trans = np.ones((self.nb_states, self.nb_states)) / self.nb_states
return self._trans
......@@ -425,7 +425,7 @@ class HMM(GMM):
# Check for convergence
if it > nb_min_steps and LL[it] - LL[it - 1] < max_diff_ll:
print "EM converges"
print("EM converges")
if end_cov:
for i in range(self.nb_states):
# recompute covariances without regularization
......@@ -450,7 +450,7 @@ class HMM(GMM):
return True
print "EM did not converge"
print("EM did not converge")
return False
def score(self, demos):
......
import numpy as np
from hmm import *
from .hmm import *
from .functions import *
from .model import *
......@@ -395,7 +395,7 @@ class HSMM(HMM):
self.Trans_Fw = self.Trans_Pd
# print self.Trans_Fw
except:
print "No task-parametrized transition matrix : normal transition matrix will be used"
print("No task-parametrized transition matrix : normal transition matrix will be used")
self.Trans_Fw = self.Trans_Pd
# print self.Trans_Fw
else: # compute the transition matrix for current parameters
......@@ -513,7 +513,7 @@ class HSMM(HMM):
self.Pd[i, :] = self.Pd[i, :] / np.sum(self.Pd[i, :])
if np.isnan(self.Pd).any():
print "Problem of duration probabilities"
print("Problem of duration probabilities")
return
h = np.zeros((self.nb_states, n_step))
......
......@@ -143,7 +143,7 @@ class LQR(pbdc.LQR):
# print Sc.real
return Sc.real
except:
print "Singular matrix"
print("Singular matrix")
def setProblem(self, r, q, target):
......
import numpy as np
from functions import *
from utils import gaussian_moment_matching
from plot import plot_gmm
from .functions import *
from .utils.gaussian_utils import gaussian_moment_matching
from .plot import plot_gmm
class Model(object):
"""
......
import numpy as np
from .gmm import GMM, MVN
from .hmm import HMM
from functions import multi_variate_normal, multi_variate_t
from utils import gaussian_moment_matching
from .functions import multi_variate_normal, multi_variate_t
from .utils.gaussian_utils import gaussian_moment_matching
from scipy.special import gamma, gammaln, logsumexp
class MTMM(GMM):
......
import numpy as np
prec_min = 1e-15
import sys
from utils.gaussian_utils import gaussian_conditioning
from functions import mvn_pdf
from functions import multi_variate_normal
import pbdlib as pbd
from .utils.gaussian_utils import gaussian_conditioning
from .functions import mvn_pdf
from .functions import multi_variate_normal
from .. import pbdlib as pbd
class MVN(object):
def __init__(self, mu=None, sigma=None, lmbda=None, lmbda_ns=None, sigma_cv=None, nb_dim=2):
......
......@@ -3,7 +3,7 @@ import matplotlib.pyplot as plt
import scipy as sp
from scipy.stats import multivariate_normal
from .. import pbdlib as pbd
from .functions import *
from matplotlib.path import Path
import matplotlib.patches as patches
......@@ -443,7 +443,7 @@ def plot_gmm(Mu, Sigma, dim=None, color=[1, 0, 0], alpha=0.5, linewidth=1, marke
if not isinstance(color, list) and not isinstance(color, np.ndarray):
color = [color] * nbStates
elif not isinstance(color[0], basestring) and not isinstance(color, np.ndarray):
elif not isinstance(color[0], str) and not isinstance(color, np.ndarray):
color = [color] * nbStates
if not isinstance(alpha, np.ndarray):
......
import numpy as np
from utils.utils import lifted_transfer_matrix
import pbdlib as pbd
from .utils.utils import lifted_transfer_matrix
from .. import pbdlib as pbd
class LQR(object):
def __init__(self, A=None, B=None, nb_dim=2, dt=0.01, horizon=50):
......@@ -166,7 +166,7 @@ class LQR(object):
elif isinstance(self._gmm_xi, pbd.MVN):
return self._gmm_xi.lmbda, self._gmm_xi.mu
else:
raise ValueError, "Not supported gmm_xi"
raise ValueError("Not supported gmm_xi")
def get_R(self, t):
if isinstance(self._gmm_u, pbd.MVN):
......@@ -177,7 +177,7 @@ class LQR(object):
elif isinstance(self._gmm_u, pbd.GMM):
return self._gmm_u.lmbda[t]
else:
raise ValueError, "Not supported gmm_u"
raise ValueError("Not supported gmm_u")
def ricatti(self):
"""
......
from utils import *
from jupyter_utils import *
from gaussian_utils import *
\ No newline at end of file
from .utils import *
from .jupyter_utils import *
from .gaussian_utils import *
\ No newline at end of file
import numpy as np
import tensorflow as tf
def vec(x):
"""
......
......@@ -6,7 +6,9 @@ import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.special import factorial
from dtw import dtw
from .. import plot as pblt
from ... import pbdlib as pbd
plt.style.use('ggplot')
import scipy.sparse as ss
......@@ -218,7 +220,7 @@ def align_trajectories(data, additional_data=[], hsmm=True, nb_states=5):
:param data: [list of np.array([nb_timestep, M, N, ...])]
:return:
"""
from dtw import dtw
if hsmm:
time = align_trajectories_hsmm(data, nb_states)
......@@ -252,7 +254,9 @@ def angle_to_rotation(theta):
def feature_to_slice(nb_dim=2, nb_frames=None, nb_attractor=2,
features=None):
# type: (int, list of int, int, list of list of string) -> object
## type: (int, list of int, int, list of list of string) -> object
index = []
l = 0
for i, nb_frame, feature in zip(range(nb_attractor), nb_frames, features):
......@@ -383,7 +387,7 @@ def plot_demos_3d(demos, figsize=(15, 5), angle=[60, 45]):
# ax[nb].plot(demos[i]['Data'][7,:], demos[i]['Data'][8,:],'H',color=c,ms=10,alpha=a)
def repro_plot(model, demos, save=False, tp_list=[], figsize=(3.5, 5)):
def repro_plot(model, demos, skill_name='temp', save=False, tp_list=[], figsize=(3.5, 5)):
nb_states = model.nb_states
nb_tp = len(tp_list)
idx = np.floor(np.linspace(1, 255, model.nb_states)).astype(int)
......@@ -604,7 +608,7 @@ def train_test(demos, demo_idx=0, nb_states=5, test=True, sensory=True, kbins=Tr
best['model'] = deepcopy(model)
print 'Best :', best['score']
print('Best :', best['score'])
model = best['model']
model.compute_duration(demos_train)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment