本文整理汇总了Python中pymatbridge.Matlab.run_code方法的典型用法代码示例。如果您正苦于以下问题:Python Matlab.run_code方法的具体用法?Python Matlab.run_code怎么用?Python Matlab.run_code使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymatbridge.Matlab
的用法示例。
在下文中一共展示了Matlab.run_code方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: random_sampling_matlab
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [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'])
示例2: test_init_end_to_end_distance
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [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()
示例3: __init__
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [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)
示例4: MatlabEngine
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [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
示例5: MatlabProcessor
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [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
示例6: MatlabEngine
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [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()))
示例7: len
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [as 别名]
im = utils.modcrop(im, UP_SCALE).astype(np.float32)
im_gt += [im]
im_l = []
if len(IMAGE_FILE)>0:
assert(len(im_gt)==1)
im_l = [np.array(Image.open(IMAGE_FILE)).astype(np.float32)]
else: #down scale from ground truth using Matlab
try:
from pymatbridge import Matlab
mlab = Matlab()
mlab.start()
for im in im_gt:
mlab.set_variable('a', im)
mlab.set_variable('s', 1.0/UP_SCALE)
mlab.run_code('b=imresize(a, s);')
im_l += [mlab.get_variable('b')]
mlab.stop()
except:
print 'failed to load Matlab!'
assert(0)
#im_l = utils.imresize(im_gt, 1.0/UP_SCALE)
#upscaling
#sr = Bicubic()
sr = SCN(MODEL_FILE)
res_all = []
for i in range(len(im_l)):
t=time.time();
im_h, im_h_y=sr.upscale(im_l[i], UP_SCALE)
t=time.time()-t;
示例8: Matlab
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [as 别名]
# Parameters Setting
filename = "./Input_data/example_lena.png"
npixs = 512
Nstd = 0.4
NE = 20
seedNo = 1
numImf = 6
runCEEMD = 1
maxSift = 10
typeSpline = 2
toModifyBC = 1
randType = 2
checksignal = 1
##
mlab = Matlab()
mlab.start()
mlab.run_code("addpaths")
# Fast 2dEEMD
res = mlab.run_func(
"meemd", filename, npixs, Nstd, NE, numImf, runCEEMD, maxSift, typeSpline, toModifyBC, randType, seedNo, checksignal
)
imfs = res["result"]
# Plot Results
HHTplots.example_lena(filename, imfs)
mlab.stop()
示例9: get_ipython
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [as 别名]
from IPython.display import clear_output
import matplotlib.pyplot as plt
import numpy as np
from numpy import sin, cos
from pymatbridge import Matlab
get_ipython().magic(u'matplotlib inline')
execfile('../../matplotlibrc.py')
# Run Matlab code and fetch relevant data
mlab = Matlab()
mlab.start()
results = mlab.run_code(open('fem1d.m').read())
K = mlab.get_variable('K')
U = mlab.get_variable('U')
nodeLocs = mlab.get_variable('nodeLocs')
mlab.stop()
clear_output()
print('K')
print(K)
print('U')
print(U)
x = nodeLocs[:,0]
xex = np.linspace(0, 1);
w = np.sqrt(2);
uex = (cos(w) - 1)*sin(w*xex)/(2.0*sin(w)) - 0.5*cos(w*xex) + 0.5
fig, ax = plt.subplots(figsize=(14, 10))
ax.plot(xex, uex, 'k-', label='Exact')
ax.plot(x, U, 'b-o', label='FEM')
示例10: Matlab
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [as 别名]
#!/usr/bin/python
from pymatbridge import Matlab
mlab = Matlab()
mlab.start()
print "Matlab started?", mlab.started
print "Matlab is connected?", mlab.is_connected()
mlab.run_code("conteo = 1:10")
mlab.run_code("magica = magic(5)")
mlab.stop()
示例11: Matlab
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [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'
print 'Processing ', file
示例12: Matlab
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [as 别名]
from pymatbridge import Matlab
mlab = Matlab()
mlab.start()
res = mlab.run_code('a=10, b=a+3')
mlab.stop()
示例13: MatlabKernel
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [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()
示例14: Matlab
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [as 别名]
#!/usr/bin/env python
# coding: UTF-8
from pymatbridge import Matlab
mlab = Matlab(executable='/Applications/MATLAB_R2014a.app/bin/matlab')
mlab.start()
results = mlab.run_code('a=1;')
var = mlab.get_variable('a')
print var
mlab.stop()
示例15: list
# 需要导入模块: from pymatbridge import Matlab [as 别名]
# 或者: from pymatbridge.Matlab import run_code [as 别名]
if __name__ == "__main__":
output_queue_list = list()
sys.stdout.write("Finding control VM\n")
service_list = get_service_list(sys.argv)
video_ip = service_list.get(SERVICE_META.VIDEO_TCP_STREAMING_ADDRESS)
video_port = service_list.get(SERVICE_META.VIDEO_TCP_STREAMING_PORT)
acc_ip = service_list.get(SERVICE_META.ACC_TCP_STREAMING_ADDRESS)
acc_port = service_list.get(SERVICE_META.ACC_TCP_STREAMING_PORT)
return_addresses = service_list.get(SERVICE_META.RESULT_RETURN_SERVER_LIST)
#session = pymatlab.session_factory();
mlab = Matlab('/home/ivashish/Matlab/bin/matlab');
mlab.start();
mlab.run_code("tempModels = load('/home/ivashish/exemplarsvm-master/ketchups-final');");
mlab.run_code("ketchup_models = tempModels.combineModels");
mlab.run_code("tempModels = load('/home/ivashish/exemplarsvm-master/cup_comb.mat');");
mlab.run_code("cup_models = tempModels.allEsvms");
mlab.run_code("tempModels = load('/home/ivashish/voc-dpm-master/VOC2007/person_final.mat');");
mlab.run_code("dpm_model = tempModels.model");
LOG.info("loaded models");
# dummy video app
image_queue = Queue.Queue(1)
video_ip ='10.2.12.4'
video_client = AppProxyStreamingClient((video_ip, video_port), image_queue)