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


Python Matlab.stop方法代码示例

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


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

示例1: __init__

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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: __init__

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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

示例3: MatlabEngine

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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

示例4: network_hill

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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

示例5: MatlabProcessor

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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

示例6: fix_model

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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

示例7: test_init_end_to_end_distance

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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

示例8: plot_deltahist

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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

示例9: objective_function

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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

示例10: MatlabEngine

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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

示例11: MatlabKernel

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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',
        '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()

    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., height / 150.))

    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:zharl,项目名称:matlab_kernel,代码行数:91,代码来源:matlab_kernel.py

示例12: str

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [as 别名]
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'
        print 'Processing ', file
        print 'IN= ', nfile
        print 'OUT= ', nfiler
        a = mlab.run_code('cdp_identification(\'' + nfile + '\', \'' + nfiler + '\', '+ wtime + ',' + str(sampling) + ')')
        print a
        print '************************************************'
        print time.ctime()

mlab.stop()


# print results
# print mlab.get_variable('a')

#res = mlab.run_func('jk.m', {'arg1': 3, 'arg2': 5})
开发者ID:bejar,项目名称:PeakDataAnalysis,代码行数:32,代码来源:PeaksDataProcessML.py

示例13: backtest

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [as 别名]
def backtest(filename, data, schedule_data):
  f = open(filename)
  f.readline()
  player_data = {}
  time_data = []
  for i in xrange(50):
    line = f.readline()
    if line is None or len(line) == 0:
      break
    date = int(line[:3])
    print date
    jsonvalue = "{"+f.readline()+"}"
    value = json.loads(jsonvalue)
    time_data.insert(0,(date,value))
    for p in value:
      if not p in player_data:
        player_data[p] = [0]
      player_data[p].insert(0,value[p])

  time_data2 = convertToPlayersTimeData(time_data, data)

  teams = set([i.team for i in data])

  for i in xrange(len(time_data2)):
    stamp_data = time_data2[i][1]
  Tracer()()
  portfolio = ["rohit sharma", "ajinkya rahane", "david warner", "glenn maxwell", "robin uthappa", "shane watson", "sandeep sharma", "sunil narine", "pravin tambe", "yuzvendra chahal", "bhuvneshwar kumar"]
  # portfolio = ["yuzvendra chahal", "shakib al hasan", "shane watson", "rohit sharma", "sandeep sharma", "sunil narine", "ajinkya rahane", "jacques kallis", "robin uthappa", "jayant yadav","bhuvneshwar kumar"]
  # portfolio = ["manish pandey", "rohit sharma","jacques kallis","robin uthappa", "aditya tare", "ambati rayudu", "morne morkel","piyush chawla","sunil narine","lasith malinga","pragyan ojha"]
  power_player = "glenn maxwell"
  # power_player = "bhuvneshwar kumar"
  portfolio_p = set([getPlayer(data, p)[0] for p in portfolio])
  power_player_p = getPlayer(data, power_player)[0]
  points = 0
  subs = 75

  mlab = Matlab(matlab='/Applications/MATLAB_R2013a.app/bin/matlab')
  mlab.start()
  for i in xrange(4,len(time_data2)):
    # START = str(time_data2[i][0])
    # CURRENT_TEAM = set(portfolio)
    # SUBSTITUTIONS = subs
    # PAST_STATS = time_data[i][1]
    print "\n\n\n\n\n\n"
    print (subs, str(time_data2[i][0]))
    print set(portfolio_p)
    print points
    print "\n\n\n\n\n\n"
    # print time_data[i-1][1]
    # Tracer()()

    inp = (subs, str(time_data2[i][0]), set(portfolio), time_data[i-1][1])
    backtest_pickteam.pickTeam(data, schedule_data, inp)



    res = mlab.run_func('/Users/deedy/Dev/FantasyIPL-Moneyball/python2matlab.m', {}, maxtime = 500)
    changes = backtest_results.getResults(data, schedule_data, res['result'])
    subs -= changes[2]
    portfolio_p = changes[0]
    power_player_p = changes[1]
    # Tracer()()
    # update portfolio
    # update subs
    # update power player
    # Tracer()()

    teams = [(p,time_data2[i][1][p] - time_data2[i-1][1][p] ) for p in time_data2[i][1] if p in portfolio_p]
    print teams
    pthis = 0
    for i in teams:
      if power_player_p == i[0]:
        pthis += 2*i[1]
      else:
        pthis += i[1]
    points+= pthis
    print "{0}\t{1}\t{2}\n\n".format(points, pthis, subs)


    # print "{0}\t{1}".format(time_data2[i][0] , teams)

  mlab.stop()
  Tracer()()
  f.close()
开发者ID:deedy,项目名称:FantasyIPL-Moneyball,代码行数:86,代码来源:backtest.py

示例14: cvWorker

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [as 别名]
class cvWorker (threading.Thread):

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

    def createHash(self):
        self.redis_obj.hmset('cloudcv_worker:'+self.worker_id, {'status' : 'Started'})

    def run(self):
        # Keep polling the redis queue for jobs
        # If present, execute it else keep polling till instructed to stop
        loop = 1
        self.redis_obj.rpush('cloudcv:'+self.worker_id+':status', 'Running')

        while loop == 1:
            json_args = self.redis_obj.lpop('cloudcv_jobs')
            if json_args is not None:
                parsed_dict = json.loads(json_args)
                re.run(parsed_dict, self.mlab_inst)
                print json_args
            

            '''
            if task_id is not None:
                # Set status to "Executing Job<ID> @ Time" and execute the task
                json_args = self.redis_obj.get('cloudcv:'+task_id+':args')
                exec_path = self.redis_obj.get('cloudcv:'+task_id+':exec')
                ## HAVE TO CLEAN UP REDIS AFTER THIS
                task_args = json.loads(json_args)
                #task_args = {'imagePath': '/home/mclint/pythonbridge/testin','outputPath': '/home/mclint/pythonbridge/testout','featList': 'lbp','verbosity': '2' }
                ## HAVE TO ADD TIME
                time_str = time.asctime(time.localtime(time.time()))
                self.redis_obj.rpush('cloudcv:'+self.worker_id+':status', 'Executing Job: ' + task_id + ' at ' + time_str)
                self.redis_obj.set('cloudcv:'+task_id+':status', 'Executing on Worker: ' + self.worker_id + ' at ' + time_str)

                res = self.mlab_inst.run_func(exec_path, task_args)
                print res

                self.redis_obj.set('cloudcv:'+task_id+':result', res)
                ## HAVE TO ADD TIME
                time_str = time.asctime(time.localtime(time.time()))
                if res['result'] == 0:
                    # Set status to "Completed Job<ID> @ Time"
                    print task_id + ' Completed Successfully by Worker: ' + self.worker_id + ' at ' + time_str
                    self.redis_obj.set('cloudcv:'+task_id+':status', 'Completed by Worker: ' + self.worker_id + ' at ' + time_str)
                    self.redis_obj.rpush('cloudcv:'+self.worker_id+':status', 'Completed Job: ' + task_id + ' at ' + time_str)
                else:
                    # Set status to "FAILED Job<ID> @ Time"
                    print task_id + ' FAILED - worker: ' + self.worker_id + ' at ' + time_str
                    self.redis_obj.set('cloudcv:'+task_id+':status', 'Job FAILED - Worker: ' + self.worker_id + ' at ' + time_str)
                    self.redis_obj.rpush('cloudcv:'+self.worker_id+':status', 'Job FAILED: ' + task_id + ' at ' + time_str)
            '''
            if self.redis_obj.get('cloudcv:stop') != 'False':
                loop = 0
                self.redis_obj.rpush('cloudcv:'+self.worker_id+':status', 'Stopping Matlab')
                print 'Quit command issued'
            time.sleep(0.1)
        # Go to terminate here
        self.terminate()

    def terminate(self):
        # Stop Matlab instance and set status
        self.mlab_inst.stop()
        self.redis_obj.rpush('cloudcv:'+self.worker_id+':status', 'Stoped Matlab')
        self.redis_obj.rpush('cloudcv:'+self.worker_id+':status', 'Exiting Thread')
开发者ID:ahmedosman,项目名称:CloudCV_Server,代码行数:78,代码来源:cloudcvWorker.py

示例15: MatlabKernel

# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import stop [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


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