def _connect_matlab_engine(self, use_existing=True, persistent=True): """ Connect to a matlab engine, starting a new one if it hasn't been started yet :return: """ found_eng = False if use_existing: eng_names = engine.find_matlab() for eng_name in eng_names: try: self.eng = engine.connect_matlab(eng_name) self.eng_name = eng_name found_eng = True # unable to connect to an instance because it already has a connection except matlab.engine.EngineError: pass if found_eng: break if not found_eng: # if we're making a new persistent engine, create it if persistent: self.eng_name = self._start_persistent_shared_matlab() self.eng = engine.connect_matlab(self.eng_name) # otherwise, make a new engine just for the lifetime of self else: self.eng = engine.start_matlab() self.eng_name = None # to be explicit self.eng_deleted = False
def _connect(self, name_prefix=None): sessions = me.find_matlab() if not sessions: return if not name_prefix: name = sessions[0] else: name = '' for s in sessions: if s.startswith(name_prefix): name = s break if not name: return False try: self._engine = me.connect_matlab(name) logger.info('Connected to Matlab engine "{}"', name) except me.EngineError: logger.exception('Cannot connect to Matlab engine "{}"', name) return False self._name = name return True
def _connect(self, name_prefix=None): sessions = me.find_matlab() if not sessions: return if not name_prefix: name = sessions[0] else: name = '' for s in sessions: if s.startswith(name_prefix): name = s break if not name: return False try: print('Connecting to Matlab shared engine {}'.format(name)) self._engine = me.connect_matlab(name) print('Connected to Matlab shared engine {}'.format(name)) except me.EngineError: return False self._name = name return True
def __init__( self, m_file_path, benchmark_os_path, parallel, shared_engine=None #TAG:MSH ): self.parallel = parallel import matlab.engine as matlab_engine import matlab as matlab # Don't seem to nee matlab.engine other than to start the matlab # session. # self.matlab_engine = matlab_engine self.matlab = matlab #TAG:MSH if shared_engine is None: print 'starting matlab...' self.eng = matlab_engine.start_matlab() print 'done' else: print 'attempting to connect to an existing matlab session' self.eng = matlab_engine.connect_matlab(shared_engine) self.m_file = m_file_path m_file_name_split = self.m_file.split('.') if m_file_name_split[1].strip() != 'm': raise err.Fatal('internal error!') self.m_fun_str = m_file_name_split[0].strip() # self.sim_fun = self.eng.simulate_m_file(1) # add paths # comm.call_function([], 'addpath', [SQ + benchmark_os_path + SQ]) self.eng.addpath(benchmark_os_path) #TAG:CLSS # TODO: Remove this hack. Added for backwards compatibility # detect if the simulator file is a function or a class # source: http://blogs.mathworks.com/loren/2013/08/26/what-kind-of-matlab-file-is-this/ # classy = 8 if class else is 0 (function or a script) classy = self.eng.exist(self.m_fun_str, 'class') if classy == 0.0: print 'maltab file is a function' self.sim_is_class = False elif classy == 8.0: print 'maltab file is a class' self.sim_is_class = True self.sim_obj = self.eng.init_plant(self.m_fun_str) else: raise err.Fatal( '''Supplied matlab simulator is neither a class or a function: possible floating point error?. exist() returned: {}'''.format( classy))
def __init__( self, m_file_path, benchmark_os_path, parallel, shared_engine=None #TAG:MSH ): self.parallel = parallel import matlab.engine as matlab_engine import matlab as matlab # Don't seem to nee matlab.engine other than to start the matlab # session. # self.matlab_engine = matlab_engine self.matlab = matlab #TAG:MSH if shared_engine is None: print 'starting matlab...' self.eng = matlab_engine.start_matlab() print 'done' else: print 'attempting to connect to an existing matlab session' self.eng = matlab_engine.connect_matlab(shared_engine) self.m_file = m_file_path m_file_name_split = self.m_file.split('.') if m_file_name_split[1].strip() != 'm': raise err.Fatal('internal error!') self.m_fun_str = m_file_name_split[0].strip() # self.sim_fun = self.eng.simulate_m_file(1) # add paths # comm.call_function([], 'addpath', [SQ + benchmark_os_path + SQ]) self.eng.addpath(benchmark_os_path) #TAG:CLSS # TODO: Remove this hack. Added for backwards compatibility # detect if the simulator file is a function or a class # source: http://blogs.mathworks.com/loren/2013/08/26/what-kind-of-matlab-file-is-this/ # classy = 8 if class else is 0 (function or a script) classy = self.eng.exist(self.m_fun_str, 'class') if classy == 0.0: print 'maltab file is a function' self.sim_is_class = False elif classy == 8.0: print 'maltab file is a class' self.sim_is_class = True self.sim_obj = self.eng.init_plant(self.m_fun_str) else: raise err.Fatal('''Supplied matlab simulator is neither a class or a function: possible floating point error?. exist() returned: {}'''.format(classy))
def post(self, server): global matlab matlab = matlabEngine.connect_matlab(matlabEngine.find_matlab()[0]) opcClient = "opcClient" + server.replace(".", "") opcItemGroup = "opcItemGroup" + server.replace(".", "") matlab.eval(opcClient + " = opcda('localhost','" + server + "')", nargout=0) matlab.eval("connect(" + opcClient + ")", nargout=0) matlab.eval(opcItemGroup + " = addgroup(" + opcClient + ")", nargout=0) matlab.eval("opcClientStatus = " + opcClient + ".Status", nargout=0) opcServers[server] = {"id": server, "client": opcClient, "status": matlab.workspace["opcClientStatus"], "itemGroup": opcItemGroup, "items": []} return matlab.workspace["opcClientStatus"]
def engine(): try: eng = connect_matlab('pytest') # Keep the existing Matlab path except EngineError: eng = start_matlab() # Add the local AT path eng.addpath(eng.genpath(os.path.join(ROOT_DIR, 'atintegrators/'))) eng.addpath(eng.genpath(os.path.join(ROOT_DIR, 'atmat/'))) # Add the local test_matlab directory eng.addpath(os.path.dirname(__file__)) yield eng eng.quit()
def main(signal_index,bers): import matlab import matlab.engine as eng engine = eng.connect_matlab() qam_order = 4 # bers = [0.00223,0.00264,0.00262,0.00275,0.00294,0.00206,0.00566] signal_power = 1 # signal_index = [2,3,4,5,6,7,8] gn_snr = gn_results(signal_power,signal_index) snrs = [] for ber in bers: snrs.append(calc_snr(qam_order,ber)) error = matlab.double((np.array(gn_snr) - np.array(snrs)).tolist()) return error
def runHATL(script, modelfile, modelname=None, fromMATLAB=False): global scriptFile scriptFile = script s = FileStream(script) parser = ReaffirmParser(CommonTokenStream(ReaffirmLexer(s))) tree = parser.prog() print(tree.toStringTree(recog=parser)) sessions = engine.find_matlab() eng = None if sessions == () or fromMATLAB: print("Starting MATLAB engine") eng = engine.start_matlab() else: print("Connecting to MATLAB engine") eng = engine.connect_matlab(sessions[0]) #set the appropriate path and then restore the cwd oldpwd = eng.pwd() assert ('REAFFIRM_ROOT' in os.environ) eng.cd(os.environ['REAFFIRM_ROOT']) eng.addpath(eng.genpath('functions')) eng.cd(oldpwd) print("Loading Initial Model") eng.clear('all', nargout=0) eng.bdclose('all', nargout=0) try: eng.load_system(modelfile) except MatlabExecutionError as e: print("Unable to open model '" + modelfile + "'", file=sys.stderr) exit() v = MATLABVisitor(eng, modelfile, modelname) v.visit(tree) print(v) return v
def __init__(self, inputargs): self.matlab = {} # declare a dictionay of equivalent functions self.funcMap = {'replace': 'strrep', 'addTransition': 'add_transition'} self.fieldMap = {'flow': 'Label', 'guardLabel': 'LabelString'} sessions = engine.find_matlab() if sessions == (): print("Starting MATLAB engine") self.eng = engine.start_matlab() else: print("Connecting to MATLAB engine") self.eng = engine.connect_matlab(sessions[0]) print("loading model") # TODO: how do we handle/catch MatlabExecutionErrors? self.eng.load_system(args['modelName']) e = self.eng self.model = e.find( e.find(e.sfroot(), '-isa', 'Simulink.BlockDiagram'), '-isa', 'Stateflow.Chart')
def get(self): matlab = matlabEngine.connect_matlab(matlabEngine.find_matlab()[0]) return matlab.opcserverinfo('localhost', nargout=1)["ServerID"]