当前位置: 首页>>代码示例>>Python>>正文


Python pymatbridge.Matlab类代码示例

本文整理汇总了Python中pymatbridge.Matlab的典型用法代码示例。如果您正苦于以下问题:Python Matlab类的具体用法?Python Matlab怎么用?Python Matlab使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Matlab类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

class MatlabCaller:
    """
    bridging class with matlab
    """

    def __init__(self, port=14001, id=None):
        if id is None:
            id = numpy.random.RandomState(1234)

        # Initialise MATLAB
        self.mlab = Matlab(port=port, id=id)

    def start(self):
        # Start the server
        self.mlab.start()

    def stop(self):
        self.mlab.stop()
        os.system('pkill MATLAB')


    def call_fn(self, path=None, params=None):
        """
        path: the path to your .m function
        params: dictionary contains all parameters
        """
        assert path is not None
        assert isinstance(params, dict)

        return self.mlab.run(path, params)['result']
开发者ID:xiaoyili,项目名称:xylearn,代码行数:30,代码来源:bridge_util.py

示例2: start_mlab

def start_mlab():
    dir_path = os.path.dirname(os.path.realpath(__file__))
    dir_list = ['/HHT_MATLAB_package', '/HHT_MATLAB_package/EEMD',
                '/HHT_MATLAB_package/checkIMFs', '/HHT_MATLAB_package/HSA']
    mlab = Matlab()
    mlab.start()
    for d in dir_list:
        res = mlab.run_func('addpath', dir_path + d)
    return mlab
开发者ID:HHTpy,项目名称:HHTpywrapper,代码行数:9,代码来源:matlab.py

示例3: MatlabProcessor

class MatlabProcessor(PwebProcessor):
    """Runs Matlab code usinng python-matlab-brigde"""

    def __init__(self, parsed, source, mode, formatdict):
        from pymatbridge import Matlab
        self.matlab = Matlab()
        self.matlab.start()
        PwebProcessor.__init__(self, parsed, source, mode, formatdict)

    def getresults(self):
        self.matlab.stop()
        return copy.copy(self.executed)

    def loadstring(self, code_string, chunk=None, scope=PwebProcessorGlobals.globals):
        result = self.matlab.run_code(code_string)
        if chunk is not None and len(result["content"]["figures"]) > 0:
            chunk["matlab_figures"] = result["content"]["figures"]
        return result["content"]["stdout"]

    def loadterm(self, code_string, chunk=None):
        result = self.loadstring(code_string)
        return result

    def init_matplotlib(self):
        pass

    def savefigs(self, chunk):
        if not "matlab_figures" in chunk:
            return []


        if chunk['name'] is None:
            prefix = self.basename + '_figure' + str(chunk['number'])
        else:
            prefix = self.basename + '_' + chunk['name']

        figdir = os.path.join(self.cwd, rcParams["figdir"])
        if not os.path.isdir(figdir):
            os.mkdir(figdir)

        fignames = []

        i = 1
        for fig in reversed(chunk["matlab_figures"]): #python-matlab-bridge returns figures in reverse order
            #TODO See if its possible to get diffent figure formats. Either fork python-matlab-bridge or use imagemagick
            name = figdir + "/" + prefix + "_" + str(i) + ".png" #self.formatdict['figfmt']
            shutil.copyfile(fig, name)
            fignames.append(name)
            i += 1

        return fignames

    def add_echo(self, code_str):
        """Format inline chunk code to show results"""
        return "disp(%s)" % code_str
开发者ID:abukaj,项目名称:Pweave,代码行数:55,代码来源:processors.py

示例4: start_matlab

def start_matlab():

    prog = find_executable('matlab')
    if not prog:
        sys.exit("Could not find MATLAB on the PATH. Exiting...")
    else:
        print("Found MATLAB in "+prog) 

    mlab = Matlab(executable=prog)
    mlab.start()

    return mlab
开发者ID:asarhegyi,项目名称:adcpp,代码行数:12,代码来源:testbench.py

示例5: __init__

 def __init__(self, *args, **kwargs):
     super(MatlabKernel, self).__init__(*args, **kwargs)
     executable = os.environ.get('MATLAB_EXECUTABLE', 'matlab')
     subprocess.check_call([executable, '-e'], stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
     self._matlab = Matlab(executable)
     self._matlab.start()
开发者ID:zharl,项目名称:matlab_kernel,代码行数:7,代码来源:matlab_kernel.py

示例6: __init__

    def __init__(self):
        super().__init__()
        self.matlab = Matlab()

        # As of July 2016, there seems to be a bug which wrecks the data
        # dimensionality when feeding it to MATLAB, causing a matrix dimension
        # mismatch to happen.
        raise ValueError("MATLAB interop via pymatbridge doesn't work.")
开发者ID:AndreiBarsan,项目名称:crowd,代码行数:8,代码来源:bridge.py

示例7: random_sampling_matlab

    def random_sampling_matlab(self):
        # Perform test via MATLAB
        from pymatbridge import Matlab
        mlab = Matlab()
        mlab.start()
        mlab.run_code('cvx_solver mosek;')
        mlab.run_code("addpath '~/mosek/7/toolbox/r2012a';")
        self.mlab = mlab

        if self.block_sizes is not None and len(self.block_sizes) == \
                self.A.shape[1]:
            self.output['error'] = "Trivial example: nblocks == nroutes"
            logging.error(self.output['error'])
            self.mlab.stop()
            self.mlab = None
            return

        duration_time = time.time()
        p = self.mlab.run_func('%s/scenario_to_output.m' % self.CS_PATH,
                               { 'filename' : self.fname, 'type': self.test,
                                 'algorithm' : self.method,
                                 'outpath' : self.OUT_PATH })
        duration_time = time.time() - duration_time
        self.mlab.stop()
        return array(p['result'])
开发者ID:megacell,项目名称:traffic-estimation-comparison,代码行数:25,代码来源:SolverCS.py

示例8: __init__

 def __init__(self):
     if 'OCTAVE_EXECUTABLE' in os.environ:
         self._engine = Octave(os.environ['OCTAVE_EXECUTABLE'])
         self._engine.start()
         self.name = 'octave'
     elif matlab_native:
         self._engine = matlab.engine.start_matlab()
         self.name = 'matlab'
     else:
         executable = os.environ.get('MATLAB_EXECUTABLE', 'matlab')
         self._engine = Matlab(executable)
         self._engine.start()
         self.name = 'pymatbridge'
     # add MATLAB-side helper functions to MATLAB's path
     if self.name != 'octave':
         kernel_path = os.path.dirname(os.path.realpath(__file__))
         toolbox_path = os.path.join(kernel_path, 'toolbox')
         self.run_code("addpath('%s');" % toolbox_path)
开发者ID:benjamin-heasly,项目名称:matlab_kernel,代码行数:18,代码来源:kernel.py

示例9: __init__

class MATLAB:

    def __init__(self):
        print "Initializing MATLAB."
        self.mlab = Matlab()
        print "Done initializing MATLAB."

    def connect(self):
        self.mlab.start()

    def disconnect(self):
        if(self.mlab.started):
            self.mlab.stop()
        else:
            print "Tried to disconnect from MATLAB without being connected."

    def run_code(self, code):

        try:
            r = self.mlab.run_code(code)
        except Exception as exc:
            raise RuntimeError("Problem executing matlab code: %s" % exc)
        else:
            if(not r['success']):
                raise RuntimeError(
                    "Problem executing matlab code: %s: %s" % (code, r['content']))

    def getvalue(self, var):
        return self.mlab.get_variable(var)
开发者ID:wonkykludge,项目名称:fsspmnl,代码行数:29,代码来源:MATLAB.py

示例10: __init__

    def __init__(self, worker_id, mlab_path, socket_prefix, id_prefix):
        threading.Thread.__init__(self)
        self.redis_obj = redis.Redis()
        self.worker_id = worker_id

        #Create a matlab instance; ie one matlab instance is created per worker
        cv_socket = socket_prefix + worker_id
        mlab_id = id_prefix + worker_id
        self.mlab_inst = Matlab(matlab=mlab_path, socket_addr=cv_socket, id=mlab_id)
        self.mlab_inst.start()

        time.sleep(2)
        self.createHash()
开发者ID:ahmedosman,项目名称:CloudCV_Server,代码行数:13,代码来源:cloudcvWorker.py

示例11: test_init_end_to_end_distance

def test_init_end_to_end_distance(run_dir):
    """
    Plot the end-to-end distance distribution for a set of runs' r0 versus the
    theoretical distribution.
    """
    if not os.path.isdir(os.path.join(run_dir, 'data', 'end_to_end_r0')):
        wdata.aggregate_r0_group_NP_L0(run_dir)
    m = Matlab()
    m.start()
    m.run_code("help pcalc")
    m.stop()
开发者ID:SpakowitzLab,项目名称:BasicWLC,代码行数:11,代码来源:tests.py

示例12: network_hill

def network_hill(panel, prior_graph=[], lambdas=[], max_indegree=3, reg_mode='full', stdise=1, silent=0, maxtime=120):
    '''
    run_hill(panel)

    input: dataframe
    should be a T x N dataframe with T time points and N samples.

    output: dict containing key 'e' and key 'i' from Hill's code
    '''
    from scipy.io import savemat
    from scipy.io import loadmat

    # start matlab
    mlab = Matlab(maxtime=maxtime)
    mlab.start()

    # .mat shuttle files
    # add path check
    inPath = os.path.join('..', 'cache', 'dbn_wrapper_in.mat')
    outPath = os.path.join('..', 'cache', 'dbn_wrapper_out.mat')
    
    D = np.transpose(panel.values)
    num_rows = np.shape(D)[0]
    num_cols = np.shape(D)[1]
    D = np.reshape(D, (num_rows, num_cols, 1))
    
    #D = np.transpose(panel, (2,1,0))
    

    # save the matlab object that the DBN wrapper will load
    # contains all the required parameters for the DBN code
    savemat(inPath, {"D" : D,
                     "max_indegree" : max_indegree,
                     "prior_graph" : prior_graph,
                     "lambdas" : lambdas,
                     "reg_mode" : reg_mode,
                     "stdise" : stdise,
                     "silent" : silent})

    # DBN wrapper just needs an input and output path
    args = {"inPath" : inPath, "outPath" : outPath}

    # call DBN code
    res = mlab.run_func('dbn_wrapper.m', args, maxtime=maxtime)

    mlab.stop()

    out = loadmat(outPath)
    
    edge_prob = pd.DataFrame(out['e'], index=panel.columns, columns=panel.columns)
    edge_sign = pd.DataFrame(out['i'], index=panel.columns, columns=panel.columns)
    
    #edge_prob = out['e']
    #edge_sign = out['i']

    return (edge_prob, edge_sign)
开发者ID:szairis,项目名称:DREAM8,代码行数:56,代码来源:models.py

示例13: fix_model

 def fix_model(self, W, intMat, drugMat, targetMat, seed=None):
     R = W*intMat
     drugMat = (drugMat+drugMat.T)/2
     targetMat = (targetMat+targetMat.T)/2
     mlab = Matlab()
     mlab.start()
     # print os.getcwd()
     # self.predictR = mlab.run_func(os.sep.join([os.getcwd(), "kbmf2k", "kbmf.m"]), {'Kx': drugMat, 'Kz': targetMat, 'Y': R, 'R': self.num_factors})['result']
     self.predictR = mlab.run_func(os.path.realpath(os.sep.join(['../kbmf2k', "kbmf.m"])), {'Kx': drugMat, 'Kz': targetMat, 'Y': R, 'R': self.num_factors})['result']
     # print os.path.realpath(os.sep.join(['../kbmf2k', "kbmf.m"]))
     mlab.stop()
开发者ID:hansaimlim,项目名称:PyDTI,代码行数:11,代码来源:kbmf.py

示例14: plot_deltahist

def plot_deltahist(fileName1, fileName2):

    prog = find_executable('matlab')
    if not prog:
        sys.exit("Could not find MATLAB on the PATH. Exiting...")
    else:
        print("Found MATLAB in "+prog) 

    mlab = Matlab(executable=prog)
    mlab.start()
    results = mlab.run_func('./plot_deltahist.m', {'arg1': fileName1, 'arg2': fileName2})
    mlab.stop()
开发者ID:asarhegyi,项目名称:adcpp,代码行数:12,代码来源:testbench.py

示例15: objective_function

    def objective_function(self, x):
        '''
        matlabpath: we need the path to matlab since we need to run it.
        
        IMPORTANT: walker_simulation.m must be included in the 
        WGCCM_three_link_walker_example file in order to work. 
        So simply modify the path below.
        '''
		mlab = Matlab(executable= matlabpath)
		mlab.start()
		output = mlab.run_func(os.path.join(self.matlab_code_directory, 'walker_simulation.m'), 
						   {'arg1': x[:, 0],'arg2': x[:, 1],'arg3': x[:, 2],
						   'arg4': x[:, 3],'arg5':x[:, 4],'arg6': x[:, 5],
						   'arg7': x[:, 6],'arg8': x[:, 7],'arg9': self.num_steps})
						   

		answer = output['result']
		simul_output = answer['speed']
		mlab.stop()
开发者ID:aaronkl,项目名称:RoBO,代码行数:19,代码来源:walker.py


注:本文中的pymatbridge.Matlab类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。