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


Python Matlab.start方法代码示例

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


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

示例1: __init__

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
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,代码行数:31,代码来源:MATLAB.py

示例2: random_sampling_matlab

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
    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,代码行数:27,代码来源:SolverCS.py

示例3: __init__

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
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,代码行数:32,代码来源:bridge_util.py

示例4: MatlabEngine

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
class MatlabEngine(object):

    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)

    def run_code(self, code):
        if matlab_native:
            return self._run_native(code)
        return self._engine.run_code(code)

    def stop(self):
        if matlab_native:
            self._engine.exit()
        else:
            self._engine.stop()

    def _run_native(self, code):
        resp = dict(success=True, content=dict())
        out = StringIO()
        err = StringIO()
        if sys.version_info[0] < 3:
            code = str(code)
        try:
            self._engine.eval(code, nargout=0, stdout=out, stderr=err)
            self._engine.eval('''
                figures = {};
                handles = get(0, 'children');
                for hi = 1:length(handles)
                    datadir = fullfile(tempdir(), 'MatlabData');
                    if ~exist(datadir, 'dir'); mkdir(datadir); end
                    figures{hi} = [fullfile(datadir, ['MatlabFig', sprintf('%03d', hi)]), '.png'];
                    saveas(handles(hi), figures{hi});
                    if (strcmp(get(handles(hi), 'visible'), 'off')); close(handles(hi)); end
                end''', nargout=0, stdout=out, stderr=err)
            figures = self._engine.workspace['figures']
        except (SyntaxError, MatlabExecutionError) as exc:
            resp['content']['stdout'] = exc.args[0]
            resp['success'] = False
        else:
            resp['content']['stdout'] = out.getvalue()
            if figures:
                resp['content']['figures'] = figures
        return resp
开发者ID:bernardosabatinilab,项目名称:VC-FlowIn-Analysis-Banghart-Neufeld-2015,代码行数:61,代码来源:kernel.py

示例5: start_mlab

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
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,代码行数:11,代码来源:matlab.py

示例6: network_hill

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
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,代码行数:58,代码来源:models.py

示例7: MatlabProcessor

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
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,代码行数:57,代码来源:processors.py

示例8: fix_model

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
 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,代码行数:13,代码来源:kbmf.py

示例9: test_init_end_to_end_distance

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
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,代码行数:13,代码来源:tests.py

示例10: start_matlab

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
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,代码行数:14,代码来源:testbench.py

示例11: plot_deltahist

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
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,代码行数:14,代码来源:testbench.py

示例12: objective_function

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
    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,代码行数:21,代码来源:walker.py

示例13: MatlabEngine

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
class MatlabEngine(object):

    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)

    def run_code(self, code):
        if matlab_native:
            return self._run_native(code)
        return self._engine.run_code(code)

    def stop(self):
        if matlab_native:
            self._engine.exit()
        else:
            self._engine.stop()

    def _run_native(self, code):
        out = StringIO()
        err = StringIO()
        if sys.version_info[0] < 3:
            code = str(code)
        try:
            self._engine.eval(code, nargout=0, stdout=out, stderr=err)
        except (SyntaxError, MatlabExecutionError) as exc:
            return dict(success=False, content=dict(stdout=exc.args[0]))
        return dict(success=True, content=dict(stdout=out.getvalue()))
开发者ID:benjamin-heasly,项目名称:matlab_kernel,代码行数:44,代码来源:kernel.py

示例14: MatlabKernel

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
class MatlabKernel(MetaKernel):
    implementation = "Matlab Kernel"
    implementation_version = (__version__,)
    language = "matlab"
    language_version = ("0.1",)
    banner = "Matlab Kernel"
    language_info = {
        "mimetype": "text/x-matlab",
        "name": "octave",
        "file_extension": ".m",
        "codemirror_mode": "Octave",
        "help_links": MetaKernel.help_links,
    }

    _first = True

    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()

    def get_usage(self):
        return "This is the Matlab kernel."

    def do_execute_direct(self, code):
        if self._first:
            self._first = False
            fig_code = "set(0, 'defaultfigurepaperunits', 'inches');"
            self._matlab.run_code(fig_code)
            self._matlab.run_code("set(0, 'defaultfigureunits', 'inches');")
            self.handle_plot_settings()

        self.log.debug("execute: %s" % code)
        resp = self._matlab.run_code(code.strip())
        self.log.debug("execute done")
        if "stdout" not in resp["content"]:
            raise ValueError(resp)
        if "figures" in resp["content"]:
            for fname in resp["content"]["figures"]:
                try:
                    im = Image(filename=fname)
                    self.Display(im)
                except Exception as e:
                    self.Error(e)
        if not resp["success"]:
            self.Error(resp["content"]["stdout"].strip())
        else:
            return resp["content"]["stdout"].strip() or None

    def get_kernel_help_on(self, info, level=0, none_on_fail=False):
        obj = info.get("help_obj", "")
        if not obj or len(obj.split()) > 1:
            if none_on_fail:
                return None
            else:
                return ""
        return self.do_execute_direct("help %s" % obj)

    def handle_plot_settings(self):
        """Handle the current plot settings"""
        settings = self.plot_settings
        settings.setdefault("size", "560,420")

        width, height = 560, 420
        if isinstance(settings["size"], tuple):
            width, height = settings["size"]
        elif settings["size"]:
            try:
                width, height = settings["size"].split(",")
                width, height = int(width), int(height)
            except Exception as e:
                self.Error(e)

        size = "set(0, 'defaultfigurepaperposition', [0 0 %s %s])\n;"
        self.do_execute_direct(size % (width / 150.0, height / 150.0))

    def repr(self, obj):
        return obj

    def restart_kernel(self):
        """Restart the kernel"""
        self._matlab.stop()

    def do_shutdown(self, restart):
        with open("test.txt", "w") as fid:
            fid.write("hey hey\n")
        self._matlab.stop()
开发者ID:kirk86,项目名称:VirtEnvs-umc-matlab,代码行数:91,代码来源:matlab_kernel.py

示例15: Matlab

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import start [as 别名]
"""

__author__ = 'bejar'

from pymatbridge import Matlab

from config.experiments import experiments, lexperiments
import time


# lexperiments = ['e130716', 'e130827', 'e130903', 'e141113', 'e141029', 'e141016', 'e140911', 'e140311', 'e140225', 'e140220']
lexperiments = ['130827']#'e130827','e140225', 'e140220', 'e141016', 'e140911']

mlab = Matlab(executable='/home/bejar/bin/MATLAB/R2014b/bin/matlab')

mlab.start()
a = mlab.run_code('cd(\'/home/bejar/PycharmProjects/PeakDataAnalysis/Matlab/\')')
print a

datasufix = ''#'-RawResampled'

wtime = '120e-3' # Window length in miliseconds

for expname in lexperiments:
    datainfo = experiments[expname]
    sampling = datainfo.sampling #/ 6.0

    for file in [datainfo.datafiles[0]]:
        print time.ctime()
        nfile = '/home/bejar/Data/Cinvestav/' + file + datasufix + '.mat'
        nfiler = '/home/bejar/Data/Cinvestav/' + file + datasufix + '-peaks2.mat'
开发者ID:bejar,项目名称:PeakDataAnalysis,代码行数:33,代码来源:PeaksDataProcessML.py


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