def make_view(engine, eval_str): """ :param engine: matlab engine as returned by matlab.engine.connect_matlab() :param eval_str: string to evaluate :return: """ try: with io.StringIO() as dump: f_info = engine.eval('functions(@%s)' % eval_str, stdout=dump, stderr=dump) if f_info['type'] == 'simple' and f_info['file'] == '': pass else: return MATLABFunctionView(engine, eval_str) except matlab.engine.MatlabExecutionError: pass except SyntaxError: pass if engine.eval('isstruct(%s)' % eval_str): return MATLABStructView(engine, eval_str) elif engine.eval('iscell(%s)' % eval_str): return MATLABCellView(engine, eval_str) elif engine.eval('istable(%s)' % eval_str): return MATLABTableView(engine, eval_str) else: return engine.eval(eval_str)
def wait_startup(args): from io import StringIO global engine m_stdout = StringIO() m_stderr = StringIO() matlab_adaptor_lib_path = os.path.dirname(__file__) + '/matlab' try: return_vscode( message_type='info', command='wait_startup', message='', success=True, data={'matlab_adaptor_lib_path': matlab_adaptor_lib_path}) engine.eval("addpath('{}');".format(matlab_adaptor_lib_path), nargout=0, stdout=m_stdout, stderr=m_stderr) engine.aMiInhibitDebugEdit(nargout=0) return_vscode(message_type='response', command='wait_startup', success=True, message='Matlab is ready.', data={}) except MatlabEngineError as error: return_vscode(message_type='response', command='wait_startup', success=False, message=str(error), data={'args': args})
def get_exception_info(args): from io import StringIO global engine global log_python_adaptor global input_event_log m_stdout = StringIO() m_stderr = StringIO() # MException.last can only be called from command prompt... engine.eval('aMiException = MException.last;', nargout=0) engine.aMiGetExceptionInfo(nargout=0, stdout=m_stdout, stderr=m_stderr) exception_info = m_stdout.getvalue() engine.eval('MException.last(\'reset\');', nargout=0) engine.eval('lastwarn(\'\');', nargout=0) engine.eval('clear aMiException;', nargout=0) if log_python_adaptor: input_event_log.write(exception_info + '\n') input_event_log.flush() exception_info = json.loads(exception_info) exception_info[u'response'] = args return_vscode(message_type='response', command='get_exception_info', success=True, message='', data=exception_info)
def basic(engine): a, b = 1.0, 2.0 engine.workspace['a'] = a engine.workspace['b'] = b #engine.eval('c = a + b;') # Error. engine.eval('c = a + b;', nargout=0) c = engine.workspace['c'] print('{} + {} = {}'.format(a, b, c)) x = 4.0 engine.workspace['y'] = x a = engine.eval('sqrt(y)') print('sqrt({}) = {}'.format(x, a)) a = matlab.double([1, 4, 9, 16, 25]) b = engine.sqrt(a) print('sqrt({}) = {}'.format(a, b))
def prob_samples_matlab(engine: MatlabEngine, max_num_hyperparameters: int = 50, num_samples: int = 20) -> np.ndarray: """Sample from low discrepancy Sobol sequence using MATLAB. Returns a num_samples x max_num_hyperparameters array. """ engine.evalc(f"p = sobolset({max_num_hyperparameters}, 'Skip', 1e3, 'Leap', 1e2);") engine.evalc("p = scramble(p,'MatousekAffineOwen');") engine.evalc(f"probability_samples = net(p, {num_samples})") probability_samples = engine.eval("probability_samples") return np.array(probability_samples)
def update_exception_breakpoints(args): global engine global stop_on_warnings engine.eval(str(args[u'errors']) + ' if error;', nargout=0) engine.eval(str(args[u'caughterrors']) + ' if caught error;', nargout=0) engine.eval(str(args[u'warnings']) + ' if warning;', nargout=0) if args[u'warnings'] == u'dbstop': stop_on_warnings = True else: stop_on_warnings = False
def eval_in_local(statement, **kwargs): return engine.eval(statement, **kwargs)
def makeVad(wavIn, wavOut, thres=0.2): engine.eval( 'vad(\'{0:s}\', \'\', \'data/log\', {1:.1f}, \'{2:s}\')'.format( wavIn, thres, wavOut), nargout=0) os.system('rm matlab.mat')
import matlab.engine import os engine = matlab.engine.start_matlab() engine.eval('addpath functions/vad', nargout=0) engine.eval( 'vad(\'recordings/mobile/Beg.wav\', \'\', \'data/log\', 0.1, \'temp.wav\')', nargout=0) os.system('rm temp.wav') os.system('rm matlab.mat') def makeVad(wavIn, wavOut, thres=0.2): engine.eval( 'vad(\'{0:s}\', \'\', \'data/log\', {1:.1f}, \'{2:s}\')'.format( wavIn, thres, wavOut), nargout=0) os.system('rm matlab.mat')
def mtypes(builder): dir_parts = builder.project[0].name.split(os.path.sep)[:-1] src_dir = "" for part in dir_parts: src_dir = src_dir + part + os.path.sep #src_dir = src_dir dst_dir = src_dir + "m2cpp_temp" + os.path.sep #if directory m2cpp_temp does not exist, create it if not os.path.isdir(dst_dir): os.mkdir(dst_dir) #copy file in directory to m2cpp_temp #print src_dir #print dst_dir src_files = os.listdir(src_dir) for file_name in src_files: full_file_name = os.path.join(src_dir, file_name) if (os.path.isfile(full_file_name)): shutil.copy(full_file_name, dst_dir) #write whos_f.m to folder. Similar to matlab whos function, #but writes to file f = open(dst_dir + "whos_f.m", "w") f.write(matlab2cpp.mwhos.code) f.close() ##Create new matlab file in m2cpp_temp #Loop for each script and function .m file #print "- Program loop start\n\n" for program in builder.project: #get program code from matlab file f = open(program.name, "r") code = f.read() f.close() #Get name of file after splitting path, set file path "m2cpp_temp/file" file_path = dst_dir + program.name.split(os.path.sep)[-1] #print file_path #Program is main script file, add whos_f at end of file #program[1][0].cls is Main if script file if program[1][0].cls == "Main": #Modify the code, main file file_name = (program.name.split(os.path.sep)[-1])[:-2] code += "\nwhos_f" else: #Modify the code, funtion file code = function_code(program, code) #insert whos_f before return statements func_name = "whos_f" lines = code.splitlines() code_temp = [] for line in lines: #lstrip line and compare with "return" if line.lstrip()[:6] == "return": #Insert left stripped whitespace + func_name code_temp.append(lstripped(line) + func_name) #Add the "original" code line code_temp.append(line) #Convert string list to string code = "\n".join(code_temp) #write file to m2cpp_temp/ #print "writing file: " + file_path f = open(file_path, "w") f.write(code) f.close() try: import matlab.engine cwdir = os.getcwd() os.chdir(dst_dir) engine = matlab.engine.start_matlab() engine.eval(file_name, nargout=0) os.chdir(cwdir) except: print "matlab did not load correctly, check that you have matlab engine API for python installed" ##Process .m.txt files to extract data types #I could have this under the previous loop, #but then the loop becomes so long program_number = 0 for program in builder.project: #reset funcs_types dictionary for each iteration funcs_types = {} file_path = dst_dir + program.name.split(os.path.sep)[-1] + ".txt" #print file_path funcs_types = extract_ftypes(funcs_types, file_path) ##Copy data types to program.ftypes funcs = program.ftypes for func_key in funcs_types.keys(): for var_key in funcs_types[func_key].keys(): funcs[func_key][var_key] = funcs_types[func_key][var_key] #print file_path #print funcs_types #print funcs #print "---------" #print funcs_types #set ftypes for the current program builder[program_number].ftypes = funcs program_number += 1 return builder
def render_diagram(app, node, docname): global engine uri = node['uri'] # do not regenerate if os.path.exists(uri): pass ensuredir(os.path.dirname(uri)) try: # reuse last engine to save loading time if engine == None: engine = matlab.engine.start_matlab() else: # clean up used engines engine.restoredefaultpath(nargout=0) engine.close('all', nargout=0) engine.bdclose('all', nargout=0) engine.clear('classes', nargout=0) # start engine from document directory engine.cd(os.path.dirname(app.env.doc2path(docname))) # then, support changing directory (relative to document) dir = node.get('dir') if dir: engine.cd(dir) # finally, add the MATLAB paths relative to the changed directory pathlist = node.get('addpath') if pathlist: for path in pathlist: engine.addpath(path) # preload script preload = node.get('preload') if preload: engine.eval(preload + ';', nargout=0) # load system system = node.get('system') if system: engine.load_system(system) # if subsystem specified, print from this layer subsystem = node.get('subsystem') if subsystem: system = "/".join([system, subsystem]) # print from Simulink handle to .png engine.eval( "print( get_param( '{}', 'Handle' ), '-dpng', '{}' )".format( system, uri), nargout=0) except matlab.engine.MatlabExecutionError as err: raise SimulinkDiagramError('Unable to render Simulink diagram due ' + 'to MATLAB execution error')
def render_diagram(app, node, docname): global engine uri = node['uri'] # do not regenerate if os.path.exists( uri ): pass ensuredir( os.path.dirname( uri ) ) try: # reuse last engine to save loading time if engine == None: engine = matlab.engine.start_matlab() else: # clean up used engines engine.restoredefaultpath(nargout=0) engine.close('all', nargout=0) engine.bdclose('all', nargout=0) engine.clear('classes', nargout=0) # start engine from document directory engine.cd( os.path.dirname( app.env.doc2path( docname ) ) ) # then, support changing directory (relative to document) dir = node.get('dir') if dir: engine.cd( dir ) # finally, add the MATLAB paths relative to the changed directory pathlist = node.get('addpath') if pathlist: for path in pathlist: engine.addpath( path ) # preload script preload = node.get('preload') if preload: engine.eval( preload + ';', nargout=0) # load system system = node.get('system') if system: engine.load_system( system ); # if subsystem specified, print from this layer subsystem = node.get('subsystem') if subsystem: system = "/".join( [ system, subsystem ] ) # print from Simulink handle to .png engine.eval( "print( get_param( '{}', 'Handle' ), '-dpng', '{}' )". format( system, uri ), nargout=0 ) except matlab.engine.MatlabExecutionError as err: raise SimulinkDiagramError('Unable to render Simulink diagram due ' + 'to MATLAB execution error' )