def test_context_manager(self): """Make sure oct2py works within a context manager""" with Oct2Py() as oc1: ones = oc1.ones(1) assert ones == np.ones(1) with Oct2Py() as oc2: ones = oc2.ones(1) assert ones == np.ones(1)
def test_call_path(): oc = Oct2Py() octave.addpath(os.path.dirname(__file__)) DATA = octave.call('test_datatypes.m') assert DATA.string.basic == 'spam' oc = Oct2Py() path = os.path.join(os.path.dirname(__file__), 'test_datatypes.m') DATA = oc.call(path) assert DATA.string.basic == 'spam'
def test_syntax_error(self): """Make sure a syntax error in Octave throws an Oct2PyError """ oc = Oct2Py() self.assertRaises(Oct2PyError, oc._eval, "a='1") oc = Oct2Py() self.assertRaises(Oct2PyError, oc._eval, "a=1++3") if not oc._session.use_pexpect: self.assertRaises(Oct2PyError, oc._eval, "a=1") else: oc.put('a', 1) a = oc.get('a') self.assertEqual(a, 1)
def __init__(self, octave_bin: Optional[str] = None, **kwargs: Any) -> None: """Quadriga Octave interface object initialization. Args: octave_bin (str, optional): Path to the octave cli executable. kwargs (Any): Interface arguments. """ # Init base class QuadrigaInterface.__init__(self, **kwargs) # Init octave session self.__logger = getLogger('octave_logger') self.__octave = Oct2Py(logger=self.__logger) # executable=octave_bin) # Add quadriga source folder to octave lookup paths self.__octave.addpath(self.path_quadriga_src) # Add launch script folder to octave loopkup paths self.__octave.addpath(self.path_launch_script)
def read_AE(folder_path,rupe_df): oc = Oct2Py() steps = [5, 10, 15, 20, 30, 40] # in khz AE_data_dict = {'name': []} for step in steps: for i in range(math.ceil(350/step)): start=50+i*step end=50+step+i*step if end>400: end=400 AE_data_dict['{}-{}'.format(int(start),int(end))]=[] #r'e:\DIPLOMSKI2019\Diplomski112019\Indirektna mjerenja' for column in rupe_df.columns: AE_data=process_AE(pd.read_csv(folder_path+'\\'+column+'-ae.txt',squeeze=True).values.tolist(), oc) ime_split=column.split('-') novo_ime='-'.join([ime_split[0],ime_split[1],ime_split[2][0:4],ime_split[3],ime_split[4]]) AE_data_dict['name'].append(novo_ime) for key in AE_data: AE_data_dict[key].append(AE_data[key]) print(column) # for key in AE_data_dict.keys(): # if key!='name': # AE_data_dict[key]=AE_data_dict[key][0] rupe_AE_df=pd.DataFrame.from_dict(AE_data_dict) return rupe_AE_df
def run(self): print("Calculating Masks") window.label_2.setText("Calculating Masks") #start instance of Octave with oct2py oc = Oct2Py() #packages needed for the calculations oc.eval('pkg load statistics') oc.eval('pkg load image') path, dirs, files = next( os.walk(os.path.join(os.path.expanduser('~'), cfd, run, 'images'))) imagecount = len(files) progressBar(0) for x in range(0, imagecount): if not os.path.isfile( os.path.join(os.path.expanduser('~'), cfd, run, 'masks', 'image' + str(x) + '_mask.jpg')): #if mask doesnt already exist, calculate it with detect_sherd function print("Calculation Image" + str(x) + ".jpg") window.label_2.setText("Calculating Mask for Image " + str(x + 1)) oc.detect_sherd( os.path.join(os.path.expanduser('~'), cfd, run), 'image' + str(x) + '.jpg') progressBar((x + 1) / imagecount * 100) #Open Folder containing the masks subprocess.Popen([ "xdg-open", os.path.join(os.path.expanduser('~'), cfd, run, 'masks') ])
def test_temp_dir(self): temp_dir = tempfile.mkdtemp() oc = Oct2Py(temp_dir=temp_dir) oc.push("a", 1) assert len(os.listdir(temp_dir)) shutil.rmtree(temp_dir, ignore_errors=True) oc.exit()
def __init__(self, sample_rate=11025): # sample rate setting not working yet self.diva_path = os.path.join(os.getenv("HOME"), 'software/DIVAsimulink/') assert os.path.exists(self.diva_path) self.octave = Oct2Py() self.restart_iter = 500 self.init_oct()
def loadMapTask(clip): value = clip.value path = lpp.getLppDir() mapFile = os.path.join(path, "octave/maps/mapQ1Q17DR24-DVMed6084.mat") #This isn't sufficient. I have to massage this to #become acceptable to oct2py as a matlab struct of arrays print "Cp1 %i" % value lppObj = sio.loadmat(mapFile, squeeze_me=True, struct_as_record=False)['map'] print "Cp2 %i" % value struct = dict() struct['nDim'] = lppObj.nDim struct['knn'] = lppObj.knn struct['knnGood'] = lppObj.knnGood struct['mapped'] = lppObj.mapped clip['lppObj'] = struct print "Cp3 %i" % value octave = Oct2Py() path = lpp.getLppDir() octave.addpath(path) # octave.addpath(os.getcwd()) # mapping = octave.testFunc2(struct) # print "mapping is %s" %(str(mapping)) # clip['mapping'] = mapping return clip
def test_func_without_docstring(): oc = Oct2Py() oc.addpath(os.path.dirname(__file__)) out = oc.test_nodocstring(5) assert out == 5 assert 'user-defined function' in oc.test_nodocstring.__doc__ assert os.path.dirname(__file__) in oc.test_nodocstring.__doc__
def palette_cbd(cls, capacities): """ Runs Palette's cut-based algorithm. WARNING: the result is not always equivalent! Arguments: cls: classifier capacities: switch capacities Returns: The number of rules per node or None if capacities are not satisfied """ octave = Oct2Py() _, _, [subclassifiers] = octave.feval(PALETTE_TEMPLATE.format('DAG_alg'), _to_octave_tcam(cls), len(capacities), METIS_DIR, 20, nout=3) if min(capacities) < max(len(sc) for sc in subclassifiers): return None return [len(sc) for sc in subclassifiers]
def count_nout(path): '''count_nout Count number of output of .m function. ''' if not osp.isabs(func_path): from oct2py import Oct2Py oc = Oct2Py() func_path = oc.which(func_path) nout = 0 status = 'NOT FUNCTION' with open(func_path, encoding='utf8') as f: for l in f: if l[0] != 'f': #not function if status == 'NOT FUNCTION': continue l = l.translate(str.maketrans('', '', '[]()')).split() try: l.remove('function') except: pass for s in l: if s == '...': status = 'FUNCTION' continue if s != '=': nout += 1 else: return nout return nout
def getContChannels(fileName, oc=ac): """ Utility function that retrieves all continuous channel recordings from a .plx file, using a 3rd-party library derived from the Plexon Matlab SDK (THIS NEEDS TO BE FIXED). Currently (2018.3.12) the library is compiled under Octave instead of Matlab, so it uses an oct2py ipython kernel to evaluate functions in Octave and results to the python environment. Continuous channel data is written as a binary data file ('.dat'), usable in most cluster sorting software (e.g. klusta, tridesclous) Inputs: fileName: Same scheme as in getVT_Data function oc: Ditto, except it's an Oct2Py instance instead of Matlab Python Engine & uses a different library Outputs: None """ if not oc: oc = Oct2Py() else: oc.restart() oc.eval("a = readPLXFileC('" + fileName + "', 'continuous');", verbose=False) oc.eval("b = {a.ContinuousChannels(:).Values};", verbose=False) oc.eval("c = cat(2, b{:});") c = oc.pull("c") d = np.reshape(c, c.size) d.tofile(fileName[:-4] + ".dat")
def save(self, location, name): # remove lambda functions, they cannot be pickled self.gb.fwdmodel = None for i in range(len(self.gb.wschemes)): if type(self.gb.wschemes[i]).__name__ == 'LoudnessWeighting': self.gb.wschemes[i].fct = None # remove octave binding temporarily try: self.ambSp.octave_binding = None except: pass if not name.endswith(".pickle"): name = name + ".pickle" f = open(os.path.join(location, name), 'wb') pickle.dump(self, f) # add again temporarily removed object try: if self.ambSp.featureMode == "gbfb": octave_scripts_dir = self.config['locations']['octavescripts'] from oct2py import Oct2Py while True: try: self.ambSp.octave_binding = Oct2Py() break except: continue self.ambSp.octave_binding.addpath(octave_scripts_dir) except: pass
def api(): op = Oct2Py() varnames = [ 'base', 'altura', 'resistencia_concreto', 'resistencia_escoamento_aco', 'resistencia_ultima_aco', 'deformacao_ultima_aco', 'forca_dada', 'numero_camadas_aco', ] listnames = ['posicao_armadura', 'elem_area_aco'] params = request.get_json() txt1 = ''.join( ['\n' + varname + '=' + params[varname] for varname in varnames]) if params['numero_camadas_aco'] != '0': txt1 += ''.join([ '\n' + name + '=[' + ' '.join(params[name]) + ']' for name in listnames ]) with open('mphi.m', 'r') as myfile: txt2 = myfile.read() txt = txt1.encode('utf-8') + txt2 op.eval(txt) mphi = op.pull('result') return json.dumps(mphi.tolist())
def calcLPPone(time, flux, mapFile, period, duration, phase): """ Calculate the LPP transit metric given a time, flux (detrended) inputs ---------- time : Time array in days array period : in days float duration : in hours float phase : in days .float This runs octave code. outputs ------- Tlpp : LPP transit metric value binnedFlux : The sorted, folded, binned flux values input to LPP """ octave = Oct2Py() octave.addpath('/home/sthomp/DAVE/dave/lpp/octave/transitLike') octave.addpath('/home/sthomp/DAVE/dave/lpp/octave/createLightCurves/') octave.addpath('/home/sthomp/DAVE/dave/lpp/octave/drtoolbox/') octave.addpath('/home/sthomp/DAVE/dave/lpp/octave/drtoolbox/techniques/') #octave.addpath('/home/sthomp/DAVE/dave/lpp/octave/drtoolbox') Tlpp, Y, binnedFlux = octave.calcLPPMetricLCarray(time, flux, period, duration, phase, mapFile) return Tlpp, binnedFlux
def _run_netcon(legLinks, legCosts, graph_id, time_file, cost_file, order_file, netcon_path='netcon/', timeout=7200, name="", allowOPs=False, verbose=False): """ See netcon/examples.md for descriptions of the diverse parameters used by the MATLAB netcon() function. """ costType = 1 muCap = 1 octave = Oct2Py(timeout=timeout) try: octave.warning('off','all') octave.feval( f"{netcon_path}/netcon.m", legLinks, int(verbose), costType, muCap, int(allowOPs), legCosts, graph_id, time_file, cost_file, order_file ) print(f"{name} execution has successfully completed") return True except Oct2PyError as e: if str(e) != "Timed out, interrupting": raise e print(f"{name} has been stopped after {timeout} seconds") return False
def run_octave_source(source_code): result = {} console_output = [] print('run_octave script get source code') print(source_code) octave_session = Oct2Py() out = None try: out = octave_session.eval(source_code, stream_handler=console_output.append) except Oct2PyError as exc: print('Octave Error Happened') print(exc) result['state'] = 'FAILURE' result['message'] = 'Octave Error' except TypeError as exc: print('Type Error Happened') print(exc) result['state'] = 'FAILURE' result['message'] = 'Type Error' else: result['state'] = 'SUCCESS' result['message'] = out octave_session.exit() result['console_output'] = console_output return result
def run_main(args): dat = args['alg_loader'].dataset.data.to_numpy() outDir = args['alg_loader'].result_path nr_of_processors = args['nr_of_procs'] if args['platform'] == 'octave': from oct2py import Oct2Py eng = Oct2Py() if sys.platform == 'win32': setup_paths_win(eng) else: setup_paths_posix(eng) #data = eng.transpose(eng.double(dat.tolist())) data = eng.double(dat.tolist()) out = eng.neunetnue_wrapper_octave(data, nr_of_processors, outDir) else: import matlab.engine eng = matlab.engine.start_matlab() if sys.platform == 'win32': setup_paths_win(eng) else: setup_paths_posix(eng) data = matlab.double(dat.tolist()) output = eng.neunetnue_wrapper(data, nr_of_processors, outDir) out = np.array(output._data).reshape( args['alg_loader'].dataset.features, args['alg_loader'].dataset.features) return out
def main(): parser = buildArgsParser() args = parser.parse_args() gmax = args.gmax if gmax >= 10: print( '!!! maximum grad str (gmax) >= 10 T/m, this is suspicious, check your units' ) tau = args.tau if tau >= 100e-3: print( '!!! waveform duration (tau) >= 100 ms, this is suspicious, check your units' ) elif tau <= 1e-3: print( '!!! waveform duration (tau) <= 1 ms, this is suspicious, check your units' ) shape = args.shape # custom zeta eventually if shape == 'lin': zeta = 0 elif shape == 'pla': zeta = np.pi / 2. elif shape == 'sph': zeta = np.math.acos(1 / np.sqrt(3.)) else: parser.error('btensor shape (shape) need to be one of lin,pla,sph') return outpath = args.outpath outname = args.outname if outname[-3:] != '.gp': parser.error('output name (outname) need to end in .gp') return print('output = {}'.format(outpath + outname)) theta = args.theta phi = args.phi print('orientation = ({}, {})'.format(theta, phi)) plotting = args.plot if plotting: print('plot the waveform') saving = args.save if not saving: print('not saving the waveform') oc = Oct2Py() bb = oc.make_waveform(gmax, tau, zeta, outpath, outname, theta, phi, plotting, saving) # bvalue seems to scale with tau^3, which make sense because we KINd of have DELTA=delta # with normal trapeze pulse b ~ (G*delta)**2 * (DELTA-delta/3) ~ 2/3 G^2 delta^3 print('b = {:.2e} s / m^2'.format(bb)) print('b = {:.3f} ms / um^2'.format(bb * 1e-9))
def test_oned_as(self): x = np.ones(10) self.oc.push("x", x) assert self.oc.pull("x").shape == x[:, np.newaxis].T.shape oc = Oct2Py(oned_as="column") oc.push("x", x) assert oc.pull("x").shape == x[:, np.newaxis].shape oc.exit()
def test_oned_as(self): x = np.ones(10) self.oc.push('x', x) assert self.oc.pull('x').shape == x[:, np.newaxis].T.shape oc = Oct2Py(oned_as='column') oc.push('x', x) assert oc.pull('x').shape == x[:, np.newaxis].shape oc.exit()
def _get_octave(): octave = Oct2Py() current_dir = os.path.dirname(os.path.abspath(__file__)) octave.addpath( os.path.join(current_dir, 'lib/grmf/exp-grmf-nips15/grmf-core/octave/')) return octave
def singleMethodWithParams(problem, method, params): oc = Oct2Py() oc.chdir('/home/ubuntu/BENCHOPaaS/BENCHOP/BENCHOP') time, relerr = oc.feval('singleMethodWithParams', problem, method, params, nout=2) return [time, relerr]
def error_FPGA(typ, n): oc = Oct2Py() print "Presionar botón en la FPGA para ejecutar" if typ == 0: #Formato simple oc.serialcom32("/dev/ttyUSB1", 9600, 4096) elif typ == 1: #Formato doble oc.serialcom("/dev/ttyUSB1", 9600, 8192) oc.grapgresult(1)
def test_temp_dir(self): temp_dir = tempfile.mkdtemp() oc = Oct2Py(temp_dir=temp_dir) oc._reader.create_file(oc.temp_dir) oc._writer.create_file(oc.temp_dir, []) assert oc._reader.out_file.startswith(temp_dir) assert oc._writer.in_file.startswith(temp_dir) shutil.rmtree(temp_dir, ignore_errors=True) oc.exit()
def test_singleton_sparses(): '''Make sure a singleton sparse matrix works''' import scipy.sparse data = scipy.sparse.csc.csc_matrix(1) oc = Oct2Py() oc.put('x', data) assert np.allclose(data.toarray(), oc.get('x').toarray()) oc.put('y', [data]) assert np.allclose(data.toarray(), oc.get('y').toarray())
def __init__(self, jit_enable=True): from oct2py import Oct2Py from oct2py import Struct self._struct = Struct self._eng = Oct2Py() if jit_enable: self._eng.eval('jit_enable(1)', verbose=0) self._eng.eval('pkg load statistics', verbose=0)
def test_context_manager(): '''Make sure oct2py works within a context manager''' oc = Oct2Py() with oc as oc1: ones = oc1.ones(1) assert ones == np.ones(1) with oc as oc2: ones = oc2.ones(1) assert ones == np.ones(1)
def test_logging(): # create a stringio and a handler to log to it def get_handler(): sobj = StringIO() hdlr = logging.StreamHandler(sobj) hdlr.setLevel(logging.DEBUG) return hdlr oc = Oct2Py() hdlr = get_handler() oc.logger.addHandler(hdlr) # generate some messages (logged and not logged) oc.ones(1, verbose=True) oc.logger.setLevel(logging.DEBUG) oc.zeros(1) # check the output lines = hdlr.stream.getvalue().strip().split('\n') resp = '\n'.join(lines) assert 'zeros(A__)' in resp assert 'ans = 1' in resp assert lines[0].startswith('load') # now make an object with a desired logger logger = oct2py.get_log('test') hdlr = get_handler() logger.addHandler(hdlr) logger.setLevel(logging.INFO) oc2 = Oct2Py(logger=logger) # generate some messages (logged and not logged) oc2.ones(1, verbose=True) oc2.logger.setLevel(logging.DEBUG) oc2.zeros(1) # check the output lines = hdlr.stream.getvalue().strip().split('\n') resp = '\n'.join(lines) assert 'zeros(A__)' in resp assert 'ans = 1' in resp assert lines[0].startswith('load')