Esempio n. 1
0
    def __init__(self):
        n_motor = 13
        n_sensor = 4
        output_scale = diva_output_scale
        min_motor_values = np.array(
            [-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, 0., 0., 0.])
        max_motor_values = np.array(
            [3.3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1., 1., 1.])

        name = 'DivaWrapper'
        self.name = name

        self.n_motor = n_motor
        self.n_sensor = n_sensor

        self.min_motor_values = min_motor_values
        self.max_motor_values = max_motor_values

        self.motor_command = [0.0] * n_motor
        self.sensor_out = [0.0] * n_sensor

        self.matlabSession = ml.session_factory()
        abs_path = os.path.dirname(os.path.abspath(__file__))

        command_ = 'cd ' + abs_path + '/DivaMatlab/'

        self.matlabSession.run(command_)  # Path to DivaMatlab functions
        self.matlabSession.putvalue('outputScale', output_scale)
Esempio n. 2
0
    def __init__(self):
        logger.info('instantiating matlab')
        import pymatlab

# self.session = pymatlab.session_factory('-nodisplay -nosplash')
# self.session = pymatlab.session_factory('-nosplash -nodesktop -nodisplay')

        self.session = pymatlab.session_factory()
Esempio n. 3
0
    def __init__(self):
        logger.info('instantiating matlab')
        import pymatlab

# self.session = pymatlab.session_factory('-nodisplay -nosplash')
# self.session = pymatlab.session_factory('-nosplash -nodesktop -nodisplay')

        self.session = pymatlab.session_factory()
Esempio n. 4
0
def script_sda_detector(resolution):

    import pymatlab
    session = pymatlab.session_factory()

    nruns = 20
    partiDetMethod = 'log_detector'

    for nrun in range(18, nruns + 1):

        basefilename = '../final_results/baseline_resized/{0:05d}/models/res_baseline_resized_{0:05d}_111111/{1:05d}_{2:03d}_'.format(
            resolution, nrun, resolution)

        trainfilename = basefilename + 'train_ids.pkl.gz'
        valfilename = basefilename + 'val_ids.pkl.gz'
        trainfinalfilename = basefilename + 'trainfinal_ids.pkl.gz'
        valfinalfilename = basefilename + 'valfinal_ids.pkl.gz'
        testfilename = basefilename + 'test_ids.pkl.gz'

        # [0,max_ids] -> [1,max_ids+1]
        train_ids = load_savedgzdata(trainfilename) + 1
        val_ids = load_savedgzdata(valfilename) + 1
        trainfinal_ids = load_savedgzdata(trainfinalfilename) + 1
        valfinal_ids = load_savedgzdata(valfinalfilename) + 1
        test_ids = load_savedgzdata(testfilename) + 1

        print >> sys.stderr, train_ids
        print >> sys.stderr, val_ids
        print >> sys.stderr, trainfinal_ids
        print >> sys.stderr, valfinal_ids
        print >> sys.stderr, test_ids

        session.putvalue('partiDetMethod', partiDetMethod)
        session.putvalue('resolution', str(resolution) + '_' + str(nrun))
        session.putvalue('train_ids', train_ids)
        session.putvalue('val_ids', val_ids)
        session.putvalue('trainfinal_ids', trainfinal_ids)
        session.putvalue('valfinal_ids', valfinal_ids)
        session.putvalue('test_ids', test_ids)

        mscript = """
        data = struct();
        data.partiDetMethod = partiDetMethod;
        data.resolution     = resolution;
        data.train_ids      = train_ids;
        data.val_ids        = val_ids;
        data.trainfinal_ids = trainfinal_ids;
        data.valfinal_ids   = valfinal_ids;
        data.test_ids       = test_ids;
        res = script_sda_detector( data )
        """

        session.putvalue('MSCRIPT', mscript)
        session.run('eval(MSCRIPT)')
        res = session.getvalue('res')
        print res
Esempio n. 5
0
 def __init__(self,limitCoresTo = None):
     if limitCoresTo is None:
         os.system('comsol server &')
     else:
         os.system('comsol server -np '+str(int(limitCoresTo))+' &')
     #time.sleep(1)
     self.session = pymatlab.session_factory()
     self.session.run('mphstart(2036)')
     self.session.run('import com.comsol.model.*')
     self.session.run('import com.comsol.model.util.*')
Esempio n. 6
0
def script_sda_detector(resolution):

    import pymatlab
    session = pymatlab.session_factory()
    
    nruns      = 20
    partiDetMethod = 'log_detector'
 
    for nrun in range(18,nruns+1):
    
        basefilename = '../final_results/baseline_resized/{0:05d}/models/res_baseline_resized_{0:05d}_111111/{1:05d}_{2:03d}_'.format(resolution,nrun,resolution)

        trainfilename      = basefilename + 'train_ids.pkl.gz'
        valfilename        = basefilename + 'val_ids.pkl.gz'
        trainfinalfilename = basefilename + 'trainfinal_ids.pkl.gz'
        valfinalfilename   = basefilename + 'valfinal_ids.pkl.gz'
        testfilename       = basefilename + 'test_ids.pkl.gz'

        # [0,max_ids] -> [1,max_ids+1]
        train_ids      = load_savedgzdata(trainfilename)+1
        val_ids        = load_savedgzdata(valfilename)+1
        trainfinal_ids = load_savedgzdata(trainfinalfilename)+1
        valfinal_ids   = load_savedgzdata(valfinalfilename)+1
        test_ids       = load_savedgzdata(testfilename)+1

        print >> sys.stderr, train_ids
        print >> sys.stderr, val_ids
        print >> sys.stderr, trainfinal_ids
        print >> sys.stderr, valfinal_ids
        print >> sys.stderr, test_ids

        session.putvalue('partiDetMethod',partiDetMethod)
        session.putvalue('resolution',str(resolution) + '_' + str(nrun))
        session.putvalue('train_ids',train_ids)
        session.putvalue('val_ids',val_ids)
        session.putvalue('trainfinal_ids',trainfinal_ids)
        session.putvalue('valfinal_ids',valfinal_ids)
        session.putvalue('test_ids',test_ids)
        
        mscript = """
        data = struct();
        data.partiDetMethod = partiDetMethod;
        data.resolution     = resolution;
        data.train_ids      = train_ids;
        data.val_ids        = val_ids;
        data.trainfinal_ids = trainfinal_ids;
        data.valfinal_ids   = valfinal_ids;
        data.test_ids       = test_ids;
        res = script_sda_detector( data )
        """
        
        session.putvalue('MSCRIPT', mscript)
        session.run('eval(MSCRIPT)')
        res = session.getvalue('res')
        print res
def decompose_tensor(filters):
    """ filters is of type input feature maps, output feature maps, wxh of filter
        Output is a structure P which contains lambda, U{1}, U{2}, U{3}    
    """
    # Set logging to DEBUG to see CP-ALS information
    logging.basicConfig(level=logging.DEBUG)
    print filters.shape
    filters = np.array(filters)   
    print filters.shape 
    print filters.dtype
    nbr_filters = filters.shape[0]
    fwidth = filters.shape[2]
    fheight = filters.shape[3]
    Pstruct = []
    for chanel in range(filters.shape[1]):
        filter_for_channel = filters[:,chanel,:,:]
        filter_for_channel.reshape(nbr_filters, fwidth, fheight)
        filter_for_channel = np.swapaxes(filter_for_channel, 0,2);
        print 'Number of filters ', nbr_filters
        print 'filter_for channel shape ', filter_for_channel.shape
        fig, axes = plt.subplots(nrows=5, ncols=4)
        fig.tight_layout() 
        
        for f in xrange(nbr_filters):
            img = filter_for_channel[:,:,f]
            plt.subplot(5,4,f)
            plt.imshow(img)
        plt.show(block=False)
        T  = dtensor(filter_for_channel);
        rank = np.floor(nbr_filters*0.6);
        print 'rank is ', rank
        session = pymatlab.session_factory()
        session.putvalue('A',rank)
        del session
        ## P.U, P.lmbda
        print 'P U0,U1,U2, lambda sizes: ', P.U[0].size, P.U[1].size, P.U[2].size, P.lmbda
        print 'fit was ', fit        
        Pstruct.append(P)
        #dtensor(ktensor(U).toarray())
        print np.allclose(T, P.totensor())
    
    
    U = [np.random.rand(i,3) for i in (20, 10, 14)]
    
    Tn = dtensor(ktensor(U).toarray())
    P, fit, itr, _ = cp_als(Tn, 10)
    print 'P U0,U1,U2, lambda sizes: ', P.U[0].size, P.U[1].size, P.U[2].size, P.lmbda
    print 'fit was ', fit  
    print np.allclose(Tn, P.totensor())
    
    return Pstruct
Esempio n. 8
0
    def __init__(self):
        self.session = mlb.session_factory()
        self.session.run('cd ./voc-dpm/')
        self.model = None

        def trainDPMmodel(self, model, pos, neg, warp, randneg, nbiter, nbnegiter, 
                          maxnumexamples, overlap, numfp, cont, tag, C):
            """ Trains a model opptimizing a WL-SSVM or LSVM. 
            (thin wrapper around matlab code by Girshick, R. B.)
            Returns:
            model     The new model

            Arguments
            warp      1 => use warped positives
                      0 => use latent positives
            randneg   1 => use random negaties
                      0 => use hard negatives
            iter      The number of training iterations
            negiter   The number of data-mining steps within each training iteration
            max_num_examples  
                      The maximum number of negative examples that the feature vector
                      cache may hold
            overlap   The minimum overlap in latent positive search
            cont      True => restart training from a previous run
            C         Regularization/surrogate loss tradeoff parameter
            """
            self.session.run('cd ./train/')
            self.session.putvalue('model', model)
            self.session.putvalue('pos', pos)
            self.session.putvalue('neg', neg)
            self.session.putvalue('warp', warp)
            self.session.putvalue('randneg', randneg)
            self.session.putvalue('iter', nbiter)
            self.session.putvalue('negiter', nbnegiter)
            self.session.putvalue('maximum_examples', maximumexamples)
            self.session.putvalue('overlap', overlap)
            self.session.putvalue('num_fp', numfp)
            self.session.putvalue('cont', cont)
            self.session.putvalue('tag', tag)
            self.session.putvalue('C', C)
            self.session.run('nmodel = train(model,pos,neg.warp,randneg,iter,negiter,max_num_exampples,overlap,num_fp,cont,tag,C)')
            self.model = self.session.getvalue('nmodel')
            self.session.run('cd ../')

        def detectObject(image, thresh, max_num):
            if self.model == None:
                
            self.session.run('cd ./features/')
            self.session.putvalue('im', image)
            self.session.putvalue('model', self.model)
Esempio n. 9
0
def matlab_launcher(job):
    # Run it as a Matlab function.

    try:
        import pymatlab
    except:
        raise Exception(
            "Cannot import pymatlab. pymatlab is required for Matlab jobs. It is installable with pip."
        )

    sys.stderr.write("Booting up Matlab...\n")
    session = pymatlab.session_factory()

    # Add directory to the Matlab path.
    session.run("cd('%s')" % os.path.realpath(job['expt_dir']))

    session.run('params = struct()')
    for name, param in job['params'].iteritems():
        vals = param['values']

        # sys.stderr.write('%s = %s\n' % (param['name'], str(vals)))

        # should have dtype=float explicitly, otherwise
        # if they are ints it will automatically do int64, which
        # matlab will receive, and will tend to break matlab scripts
        # because in matlab things tend to always be double type
        session.putvalue('params_%s' % name, np.array(vals, dtype=float))
        session.run("params.%s = params_%s" % (name, name))
        # pymatlab sucks, so I cannot put the value directly into a struct
        # instead i do this silly workaround to put it in a variable and then
        # copy that over into the struct
        # session.run('params_%s'%param['name'])

    sys.stderr.write('Running function %s\n' % job['function-name'])

    # Execute the function
    session.run('result = %s(params)' % job['function-name'])

    # Get the result
    result = session.getvalue('result')

    # TODO: this only works for single-task right now
    result = float(result)
    sys.stderr.write("Got result %s\n" % (result))

    del session

    return result
Esempio n. 10
0
def interpac(t, px, py):
    
    newpx = []
    newpy = []
    
    session = pymatlab.session_factory()
    session.putvalue('t', t)
    session.putvalue('x', np.darray(px))
    session.putvalue('y', np.darray(py))
    
    session.run('out=interpac(t,x,y)')
    outval = session.getvalue('out') 
    
    newpx = outval[:,0]
    newpy = outval[:,1]   
    
    return newpx, newpy
Esempio n. 11
0
def matlab_launcher(job):
    # Run it as a Matlab function.

    try:
        import pymatlab
    except:
        raise Exception("Cannot import pymatlab. pymatlab is required for Matlab jobs. It is installable with pip.")

    sys.stderr.write("Booting up Matlab...\n")
    session = pymatlab.session_factory()

    # Add directory to the Matlab path.
    session.run("cd('%s')" % os.path.realpath(job['expt_dir']))

    session.run('params = struct()')
    for name, param in job['params'].iteritems():
        vals = param['values']

        # sys.stderr.write('%s = %s\n' % (param['name'], str(vals)))

        # should have dtype=float explicitly, otherwise
        # if they are ints it will automatically do int64, which
        # matlab will receive, and will tend to break matlab scripts
        # because in matlab things tend to always be double type
        session.putvalue('params_%s' % name, np.array(vals, dtype=float))
        session.run("params.%s = params_%s" % (name, name))
        # pymatlab sucks, so I cannot put the value directly into a struct
        # instead i do this silly workaround to put it in a variable and then
        # copy that over into the struct
        # session.run('params_%s'%param['name'])

    sys.stderr.write('Running function %s\n' % job['function-name'])

    # Execute the function
    session.run('result = %s(params)' % job['function-name'])

    # Get the result
    result = session.getvalue('result')

    # TODO: this only works for single-task right now
    result = float(result)
    sys.stderr.write("Got result %s\n" % (result))

    del session

    return result
Esempio n. 12
0
 def setUpClass(cls):
     cls.session = pymatlab.session_factory()
Esempio n. 13
0
 def __init__(self, diva_path, sample_rate=11025):
     self.session = pymatlab.session_factory()
     self.session.run('path(\'' + diva_path + '\', path)')
     self.session.putvalue('sr', np.array([sample_rate]))
     diva_path = os.path.abspath(diva_path)
     self.session.run(['path(\'', diva_path, '\', path)'])
import sys

__author__ = 'Sancar'

from gurobipy import *
import os
import copy
import pymatlab
import numpy as np
import ggplot as gg
from scipy import stats as st

from pandas import DataFrame as pd_df

pr_dir = os.environ.get('PROJECT_DIR')
session = pymatlab.session_factory()


#pr_dir = '~/projects/'
print pr_dir

root_dir = os.path.join(pr_dir, 'SeededGraphMatch')



n = 45
m = 10

mplusn = m+n
p = 0.2
corr = 0.6
Esempio n. 15
0
 def __init__(self, sample_rate=11025):
     self.session = pymatlab.session_factory()
     # sample rate setting not working yet
     self.session.putvalue('sr', array([sample_rate]))
import pymatlab

if __name__ == '__main__':
    print 'Start Example'
    numTraj = 0
    numPrediction = 0
    baseDir = "./"
    obsTrajCsvFile = baseDir + "csvFiles/obsTraj.csv"
    predTrajCsvFile = baseDir + "csvFiles/predTraj.csv"
    testTrajCsvFile = baseDir + "csvFiles/testTraj.csv"
    modelDir = baseDir + "TRO_model.mat"
    print 'baseDir:%s' % baseDir
    # Initialize Matlab
    print 'Loading MATLAB.'
    session = pymatlab.session_factory()
    print 'Finish loading MATLAB.'
    session.run('cd ' + baseDir)
    # Initialize Model
    print 'Start Initializing the model.'
    session.run('UOLA_init(\'' + modelDir + '\')')
    print 'Finish Initializing the model'
    # Model Update
    print 'Start Updating the model using one trajectory'
    session.run('UOLA_learn(\'' + modelDir + '\',\'' + obsTrajCsvFile + '\')')
    print 'Finish Updating the model using one trajectory'
    # Prediction
    print 'Start Predicting the given trajectory.'
    session.run('UOLA_predict(\'' + modelDir + '\',\'' + testTrajCsvFile +
                '\',\'' + predTrajCsvFile + '\')')
    print 'Finish Predicting the given trajectory.'
    print 'End Example'
Esempio n. 17
0
 def __init__(self, sample_rate=11025):
     import pymatlab
     self.session = pymatlab.session_factory()
     # sample rate setting not working yet
     self.session.putvalue('sr', array([sample_rate]))
Esempio n. 18
0
 def __init__(self):
     """Initializes the model parameters"""
     super(Shapiro, self).__init__()
     self._session = pymatlab.session_factory('-nodisplay -nojvm')
Esempio n. 19
0
            gevent.sleep(1)
        print 'Matlab over'


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='EEG signal recorder.')
    parser.add_argument('var', metavar='var', type=str, nargs='?')
    args = parser.parse_args(sys.argv[1:])

    # Creating headset Object. No console output. No research headset
    headset = Emotiv(False, SERIAL, False)
    connect = MatlabConnect(headset)

    # Matlab needs to be started the current workspace to be used
    raw_input("Press Enter when Matlab is started")
    connect.session = pymatlab.session_factory()

    # Create a Greenlet for the setup...
    setupGLet = gevent.spawn(headset.setup)
    gevent.sleep(1) # ... and pass the control

    if not setupGLet.started:
        print 'Error: Is the device connected?'
        headset.close()
        quit()

    connect.isRunning = True
    # Create the sensor data generator
    g1 = gevent.spawn(connect.get_sensors_info)
    # Create plot routine
    g2 = gevent.spawn(connect.matlabBridge, args.var or 'data')
Esempio n. 20
0
            gevent.sleep(1)
        print 'Matlab over'


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='EEG signal recorder.')
    parser.add_argument('var', metavar='var', type=str, nargs='?')
    args = parser.parse_args(sys.argv[1:])

    # Creating headset Object. No console output. No research headset
    headset = Emotiv(False, SERIAL, False)
    connect = MatlabConnect(headset)

    # Matlab needs to be started the current workspace to be used
    raw_input("Press Enter when Matlab is started")
    connect.session = pymatlab.session_factory()

    # Create a Greenlet for the setup...
    setupGLet = gevent.spawn(headset.setup)
    gevent.sleep(1)  # ... and pass the control

    if not setupGLet.started:
        print 'Error: Is the device connected?'
        headset.close()
        quit()

    connect.isRunning = True
    # Create the sensor data generator
    g1 = gevent.spawn(connect.get_sensors_info)
    # Create plot routine
    g2 = gevent.spawn(connect.matlabBridge, args.var or 'data')
Esempio n. 21
0
 def __init__(self, diva_path, sample_rate = 11025):
     self.session = pymatlab.session_factory()
     self.session.run('path(\'' + diva_path + '\', path)')
     self.session.putvalue('sr', np.array([sample_rate]))
     diva_path = os.path.abspath(diva_path)
     self.session.run(['path(\'', diva_path, '\', path)'])
Esempio n. 22
0
 def setUpClass(cls):
     cls.session = pymatlab.session_factory()
Esempio n. 23
0
#!/usr/bin/env python
from tf.transformations import euler_from_quaternion, quaternion_from_euler
from jcontroller import jcontroller
import pymatlab
import time
import numpy as np
from math import *
from random import *

#def main():
# initiate robot
j = jcontroller()
# Start matlab session
matSess = pymatlab.session_factory()
matSess.run("addpath(genpath('~/catkin_ws/src'))")


def joinLists(a, b, steps=30):
    # generate intermediary stepts
    c = []
    loa = []  # list of actuators
    ini = a[-1]
    end = b[0]
    for i in range(4):  # for each leg
        for j in range(3):  # for each motor
            step = (end[i][j] - ini[i][j]) / steps
            if step == 0:
                loa.append([ini[i][j]] * steps)
            else:
                loa.append(np.arange(ini[i][j], end[i][j], step).tolist())
    for i in range(steps):
import time
import copy

import numpy as np
import ggplot as gg
from scipy import stats as st
from pandas import DataFrame as pd_df


os.environ["LD_LIBRARY_PATH"] = os.environ["LD_LIBRARY_PATH"] + ":/usr/lib/x86_64-linux-gnu/libstdc++.so.6"
import pymatlab



pr_dir = os.environ.get('PROJECT_DIR')
session = pymatlab.session_factory(options=" -logfile sgm_ip_run_log"+time.strftime("%H:%M:%S")+".txt")

#pr_dir = 'G:\Sancar\Documents\projects'
pr_dir = '~/projects/'
print pr_dir

pr_dir =  '/home/sadali1/projects/'
root_dir  = os.path.join(pr_dir, 'SeededGraphMatch')
models_dir = os.path.join(root_dir, 'optim_models')


chdir_script = """cd """ + root_dir
#chdir_script = """cd G:\\Sancar\\Documents\\projects\\SeededGraphMatch"""
session.putvalue('chdir_script', chdir_script)