• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pymatbridge.Matlab类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Matlab

from pymatbridge import Matlab
mlab = Matlab(matlab='/Applications/MATLAB_R2014a.app/bin/matlab')
mlab.start()
res = mlab.run('/Users/yanguango/Lab/SpamFilter/Project/src/PCA.m', {'arg1': 3, 'arg2': 5})
print res['result']
开发者ID:yanguango,项目名称:spam_filter,代码行数:5,代码来源:test.py


示例17: Matlab

""" This script was used to generate dwt_matlabR2012a_result.npz by storing
the outputs from Matlab R2012a. """

from __future__ import division, print_function, absolute_import

import numpy as np
import pywt

try:
    from pymatbridge import Matlab
    mlab = Matlab()
    _matlab_missing = False
except ImportError:
    print("To run Matlab compatibility tests you need to have MathWorks "
          "MATLAB, MathWorks Wavelet Toolbox and the pymatbridge Python "
          "package installed.")
    _matlab_missing = True

if _matlab_missing:
    raise EnvironmentError("Can't generate matlab data files without MATLAB")

size_set = 'reduced'

# list of mode names in pywt and matlab
modes = [('zero', 'zpd'),
         ('constant', 'sp0'),
         ('symmetric', 'sym'),
         ('periodic', 'ppd'),
         ('smooth', 'sp1'),
         ('periodization', 'per')]
开发者ID:aaren,项目名称:pywt,代码行数:30,代码来源:generate_matlab_data.py


示例18: __init__

 def __init__(self, *args, **kwargs):
     super(MatlabKernel, self).__init__(*args, **kwargs)
     executable = os.environ.get('MATLAB_EXECUTABLE', 'matlab')
     self._matlab = Matlab(executable)
     self._matlab.start()
开发者ID:febret,项目名称:matlab_kernel,代码行数:5,代码来源:matlab_kernel.py


示例19: __init__

 def __init__(self, *args, **kwargs):
     excecutable = kwargs.pop('excecutable', 'matlab')
     super(MatlabKernel, self).__init__(*args, **kwargs)
     self._matlab = Matlab(excecutable)
     self._matlab.start()
开发者ID:antimatter15,项目名称:matlab_kernel,代码行数:5,代码来源:matlab_kernel.py


示例20: Matlab

from pymatbridge import Matlab
mlab = Matlab()
mlab.start()

res = mlab.run_code('a=10, b=a+3')

mlab.stop()
开发者ID:TmanTman,项目名称:SkripsieKode,代码行数:7,代码来源:pymatlabTest.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pymatgen.Lattice类代码示例发布时间:2022-05-25
下一篇:
Python pymarkovchain.MarkovChain类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap