def benchop(problem, method): oc = oct2py.Oct2Py() oc.addpath('./') oc = oct2py.Oct2Py() x = oc.feval("benchop", problem, method) print(x) return x
def detect(fname): attribute_names = os.path.join(os.path.abspath(os.path.dirname(__file__)), "attribute_names.txt") with open(attribute_names) as fp: cats = fp.readlines() cats = numpy.array([cat.strip() for cat in cats]) cats.shape = (1, 64) oc = oct2py.Oct2Py() _ = oc.addpath(oc.genpath("./")) _ = oc.eval("pkg load image") codewords = oc.load_codewords() att_classifiers = oc.load_att_classifiers() im = oc.imread(fname) aspect_r = 1024.0 / im.shape[1] dim = (1024, int(im.shape[0] * aspect_r)) if aspect_r > 1.: im = cv2.resize(im, dim, interpolation=cv2.INTER_AREA) bbox = numpy.array([1, 1, im.shape[1], im.shape[0]]) pred = oc.extract_predictions(im, bbox, att_classifiers, codewords) return sorted(zip(cats[pred > 0.25], pred[pred > 0.25]), key=lambda x: x[1], reverse=True)
def getClassNumbers(self, HDR, classTags): octave = oct2py.Oct2Py() octave.addpath('Octave') labels = list() for tag in classTags: labels.append(octave.call('getClassNumber.m', HDR, tag)) return labels
def test_002_t (self): self.vector_len = 2**12 self.num_max_vals = 5 # generate vector from octave oc = oct2py.Oct2Py() oc.addpath(os.path.dirname(__file__)) data, expected_pks, expected_t_pks = oc.test002_findpeaks(self.num_max_vals, self.vector_len) data = data.flatten().tolist() ################################################## # Blocks ################################################## self.blocks_vector_source_x_0 = blocks.vector_source_f(data, False, self.vector_len, []) self.doa_find_local_max_0 = doa.find_local_max(self.num_max_vals, self.vector_len, 0.0, 2*numpy.pi) self.blocks_vector_sink_x_0 = blocks.vector_sink_f(self.num_max_vals) self.blocks_vector_sink_x_1 = blocks.vector_sink_f(self.num_max_vals) ################################################## # Connections ################################################## self.tb.connect((self.blocks_vector_source_x_0, 0), (self.doa_find_local_max_0, 0)) self.tb.connect((self.doa_find_local_max_0, 0), (self.blocks_vector_sink_x_0, 0)) self.tb.connect((self.doa_find_local_max_0, 1), (self.blocks_vector_sink_x_1, 0)) # set up fg self.tb.run () # get data from sink measured_pks = self.blocks_vector_sink_x_0.data() measured_pks_locs = self.blocks_vector_sink_x_1.data() # check data for i in range(len(measured_pks)): self.assertAlmostEqual(expected_pks[i], measured_pks[i], 5) and self.assertAlmostEqual(expected_t_pks[i], measured_t_pks[i], 5)
def f(n): oc = oct2py.Oct2Py() oc.addpath("common_HF") oc.eval("pkg load statistics;") a = oc.batch_hf(n, nc) oc.exit() return a
def start_kernel(self): self.DTYPE = self._dtype # Get const values self.MASS_LEN = len(self) self.SIM_DIM = len(self._mass_list[0]._r) # Allocate memory: Object parameters self.mass_r_array = np.zeros((self.MASS_LEN, self.SIM_DIM), dtype = self.DTYPE) mass_m_array = np.zeros((self.MASS_LEN,), dtype = self.DTYPE) # Copy const data into Numpy infrastructure for pm_index, pm in enumerate(self._mass_list): mass_m_array[pm_index] = pm._m # Start octave session self.oc = oct2py.Oct2Py( temp_dir = '/dev/shm', convert_to_float = False, ) self.oc.addpath(os.path.dirname(__file__)) for name, var in [ ('m', mass_m_array), ('G', self._G), ('SIM_DIM', self.SIM_DIM), ('MASS_LEN', self.MASS_LEN), ]: self.oc.eval('global %s' % name) self.oc.push(name, var, verbose = True)
def demo_fir(): m = 7 p = 0.2 with oct2py.Oct2Py() as oc: oc.eval('pkg load signal') bmat = oc.fir1(m, p).squeeze() # %% Python bpy = scipy.signal.firwin(m + 1, p) # %% plot wmat, hmat = scipy.signal.freqz(bmat) wpy, hpy = scipy.signal.freqz(bpy) hmat_db = 20 * np.log10(abs(hmat)) hpy_db = 20 * np.log10(abs(hpy)) assert (hmat_db[:130] > -6).all() assert (hpy_db[:130] > -6).all() assert (hmat_db[278:] < -20).all() assert (hpy_db[278:] < -20).all() # disabled for old Octave 3.6 # np.testing.assert_allclose(hpy_db, hmat_db, atol=5) # dB return wmat, hmat, wpy, hpy, hmat_db, hpy_db
def init_worker_context(worker_id, m, G, SIM_DIM, MASS_LEN): # Set up "shared memory path" for octave oc_path = '/dev/shm/oc%02d' % worker_id try: os.mkdir(oc_path) except FileExistsError: pass # Start octave sessions oc = oct2py.Oct2Py( temp_dir=oc_path, convert_to_float=False, ) oc.addpath(os.path.dirname(__file__)) for name, var in [ ('m', m), ('G', G), ('SIM_DIM', SIM_DIM), ('MASS_LEN', MASS_LEN), ]: oc.eval('global %s' % name) oc.push(name, var, verbose=True) # Store context information in global namespace of worker context.update({ 'oc': oc, }) return True
def main(): path = Path("Dia 2 - 240518 - Estagio 4") numTomates = 20 nomeTxt = "resultados-Dia-2-240518-Estágio-4" #Nome do arquivo txt cujos resultados serão salvos nomeTxt += ".txt" #inicia a sessão do octave e carrega a biblioteca bsltl oc = oct2py.Oct2Py() oc.eval("pkg install -forge bsltl") oc.eval("pkg load bsltl") avds = [] ims = [] #inicia o processamento de todos os tomates with open(nomeTxt, "w") as file: numTomates += 1 for i in range(1, numTomates): #Pasta do tomate, formatada aqui como "tomate@", sendo @ o seu número pastaAtual = path / ("tomate" + str(i)) #contador para a face atual count = 1 #itera pelas filmagens feitas (no caso 3) for pasta in os.listdir(pastaAtual): print("Estamos processando o tomate ", i, " face ", count) #diretorio onde se encontram as bmps imagesdirAux = pastaAtual / pasta / "pastaBMP" IMAGESDIR = str(imagesdirAux.resolve()) oc.push("IMAGESDIR", IMAGESDIR) oc.eval("DATA = datapack(IMAGESDIR, '', 1, 128, 'bmp')", verbose=False) #Calcula o indice da metade da imagem em DATA oc.eval("[nRows, nCols, nFrames] = size(DATA)") oc.eval("thspCol = floor(nCols/2)") oc.eval("thspRow = floor(nRows/2)") oc.eval("THSP = thsp(DATA,1,thspRow)") oc.eval("COM = coom(THSP)") oc.eval("[AVD1, AVD2, AVD3, AVD4] = avd(COM,2,3,4)") oc.eval("[IM1, IM2] = inertiamoment(COM, 2)") #salvar as variaveis no ambiente python aux1 = ["AVD1", "AVD2", "AVD3", "AVD4"] [avd1, avd2, avd3, avd4] = oc.pull(aux1) aux2 = ["IM1", "IM2"] [im1, im2] = oc.pull(aux2) avds.append([avd1, avd2, avd3, avd4]) ims.append([im1, im2]) salvaResutados(file, count, avds, ims, i) #salva os resultados em um arquivo count += 1 return
def pr_gls_interface(): input_data = request.get_json() # Calling PR-GLS static file with oct2py.Oct2Py() as oc: oc.eval('cd %s/PR-GLS/CPD' % current_app.static_folder) oc.eval('mex cpd_P.c') oc.eval('mex cpd_Pappmex.c') oc.eval('mex cpd_Pcorrespondence.c;') oc.eval('cd ..') res = oc.feval('prlgdemo') # Calling PR-GLS static file # with oct2py.Oct2Py() as oc: # oc.eval('cd %s/PR-GLS' % current_app.static_folder) # oc.eval('load ./data/save_fish_def_5_1.mat') # oc.eval('X = x1') # oc.eval('Y = y2a') # x = oc.eval('compute_prgls(X, Y)') # print(x) # except oc.utils.Oct2PyError: # abort(500) return current_app.response_class(response=json.dumps(input_data), status=200, mimetype='application/json')
def __init__(self, diva_path=None): import oct2py self.diva_path = diva_path or os.path.join(os.getenv("HOME"), 'software/DIVAsimulink/') assert os.path.exists(self.diva_path) self.octave = oct2py.Oct2Py() self.restart_iter = 500 self.init_oct()
def test_002_rootMUSIC_aoa52(self): # length of each snapshot len_ss = 1024 # overlap size of each snapshot overlap_size = 64 # apply Forward-Backward Averaging? FB = True # normalized_spacing norm_spacing = 0.5 # number of sources num_srcs = 1 # expected angle-of-arrival expected_aoa = 52.0 # number of array elements num_arr_ele = 4 # simulate perturbation? PERTURB = False # Generate auto-correlation vector from octave oc = oct2py.Oct2Py() oc.addpath( os.path.join(os.path.dirname(os.path.dirname(__file__)), 'examples')) rootmusic_linear_input = oc.doa_testbench_create( 'music_test_input_gen', len_ss, overlap_size, num_arr_ele, FB, 'linear', num_arr_ele, norm_spacing, PERTURB, expected_aoa) rootmusic_linear_input = rootmusic_linear_input.flatten().tolist() ################################################## # Blocks ################################################## self.doa_rootMUSIC_0 = doa.rootMUSIC_linear_array( norm_spacing, num_srcs, num_arr_ele) self.vec_sink = blocks.vector_sink_f(1) self.vec_source = blocks.vector_source_c(rootmusic_linear_input, False, num_arr_ele * num_arr_ele) ################################################## # Connections ################################################## self.tb.connect((self.vec_source, 0), (self.doa_rootMUSIC_0, 0)) self.tb.connect((self.doa_rootMUSIC_0, 0), (self.vec_sink, 0)) # set up fg self.tb.run() # get data from sink aoa_output_52 = self.vec_sink.data() # check measured_aoa_is_52 = True for i in range(len(aoa_output_52)): # print(aoa_output_52[i]) if (abs(aoa_output_52[i] - expected_aoa) > 2.0): print(oa_output_52[i]) measured_aoa_is_52 = False self.assertTrue(measured_aoa_is_52)
def _svd_octave(A): """ Uses the LAPACK dgesvd function """ U, S, V = oct2py.Oct2Py().svd(A) S = np.matrix(S) U = np.matrix(U) V = np.matrix(V) return U, S, V
def gas_1phase(): """ MRST Compressible Gas Simulation (Variable Viscosity over Pressure) """ import oct2py as op # Execute simulation program "gas_1phase.m" # After executed, new .mat files (that contains PRESSURE, PORO, PERM result) # is created inside new directory "result_gas_1phase" octave = op.Oct2Py() octave.run("/content/pyMRST/gas_1phase.m")
def water_1phase(): """ MRST Incompressible Water Simulation """ import oct2py as op # Execute simulation program "water_1phase.m" # After executed, new .mat files (that contains PRESSURE, PORO, PERM result) # is created inside new directory "result_water_1phase" octave = op.Oct2Py() octave.run("/content/pyMRST/water_1phase.m")
def oilwater_2phase(): """ MRST Two-phase Oil-water Simulation """ import oct2py as op # Execute simulation program "oilwater_2phase.m" # After executed, new .mat files is created inside new directory # "result_oilwater_2phase" octave = op.Oct2Py() octave.run("/content/pyMRST/oilwater_2phase.m")
def fun(p): import oct2py import tempfile import shutil tmpdir = tempfile.mkdtemp() oc = oct2py.Oct2Py() ret = oc.antenna_sim(p, tmpdir) oc.exit() shutil.rmtree(tmpdir) return ret
def oil_1phase(): """ MRST Slightly Compressible Oil Simulation (Constant Viscosity over Pressure) """ import oct2py as op # Execute simulation program "oil_1phase.m" # After executed, new .mat files (that contains PRESSURE, PORO, PERM result) # is created inside new directory "result_oil_1phase" octave = op.Oct2Py() octave.run("/content/pyMRST/oil_1phase.m")
def cubData(): """Reads cubature data from file 'cubData2D.m' """ import oct2py oc=oct2py.Oct2Py() oc.addpath('/home/achyut/ddp/galerkin/newCodes') cub2D=oc.cubData2D() #change structure for python compatibility cub2D[0]=numpy.array([cub2D[0]]) return(cub2D)
def test_001_MUSIC_aoa23(self): # length of each snapshot len_ss = 256 # overlap size of each snapshot overlap_size = 32 # apply Forward-Backward Averaging? FB = True # normalized_spacing norm_spacing = 0.4 # number of sources num_srcs = 1 # expected angle-of-arrival expected_aoa = 23.0 # number of array elements num_arr_ele = 8 # simulate perturbation? PERTURB = False # Generate auto-correlation vector from octave oc = oct2py.Oct2Py() oc.addpath(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'examples')) music_linear_input = oc.doa_testbench_create('music_test_input_gen', len_ss, overlap_size, num_arr_ele, FB, 'linear', num_arr_ele, norm_spacing, PERTURB, expected_aoa) music_linear_input = music_linear_input.flatten().tolist() ################################################## # Blocks ################################################## self.doa_MUSIC_0 = doa.MUSIC_lin_array(norm_spacing, num_srcs, num_arr_ele, self.pspectrum_len) self.doa_find_local_max_0 = doa.find_local_max(num_srcs, self.pspectrum_len, 0.0, 180.0) self.blocks_null_sink_0 = blocks.null_sink(gr.sizeof_float*num_srcs) self.vec_sink = blocks.vector_sink_f(num_srcs) self.vec_source = blocks.vector_source_c(music_linear_input, False, num_arr_ele * num_arr_ele) ################################################## # Connections ################################################## self.tb.connect((self.vec_source, 0), (self.doa_MUSIC_0, 0)) self.tb.connect((self.doa_MUSIC_0, 0), (self.doa_find_local_max_0, 0)) self.tb.connect((self.doa_find_local_max_0, 1), (self.vec_sink, 0)) self.tb.connect((self.doa_find_local_max_0, 0), (self.blocks_null_sink_0, 0)) # set up fg self.tb.run() # get data from sink aoa_output_23 = self.vec_sink.data() # check measured_aoa_is_23 = True for i in range(len(aoa_output_23)): if (abs(aoa_output_23[i] - expected_aoa) > 2.0): measured_aoa_is_23 = False self.assertTrue(measured_aoa_is_23)
def solvedbo(u_q): oct_session = op.Oct2Py() oct_session.addpath(os.path.join(os.path.expanduser('~'), 'work/github/phenology-two-trait-migratory-bird')) oct_session.run('[x_cV, yzV, nV, z_n] = solvedbowrapper(%f)' % u_q) return { 'x_cV': oct_session.get('x_cV'), 'yzV': oct_session.get('yzV'), 'nV': oct_session.get('nV'), 'z_n': oct_session.get('z_n'), }
def __call__(self, observations, taxa_metadata=None): oct2py.octave.addpath(SPECTRALTREE_LLT_PATH) oc = oct2py.Oct2Py() num_taxa = observations.shape[0] adj_mat = oc.feval(os.path.join(SPECTRALTREE_LLT_PATH, "bin_forrest_wrapper.m"), observations + 1, 4, verbose=False) tree_Forrest = utils.adjacency_matrix_to_tree(adj_mat, num_taxa, taxa_metadata) return tree_Forrest
def __call__(self, observations, taxa_metadata=None): oct2py.octave.addpath('./spectraltree/ChoilatentTree/') oc = oct2py.Oct2Py() num_taxa = observations.shape[0] adj_mat = oc.feval(os.path.join(SPECTRALTREE_CHOI_PATH, "toolbox", "CLRGb.m"), observations + 1, 0, verbose=False) adj_mat = np.array(scipy.sparse.csr_matrix.todense(adj_mat)) tree_CLRG = adjacency_matrix_to_tree(adj_mat, num_taxa, taxa_metadata) return tree_CLRG
def test_001_t(self): # length of each snapshot len_ss = 2048 # overlap size of each snapshot overlap_size = 512 # num of inputs num_inputs = 4 # apply Forward-Backward Averaging? FB = False # Generate auto-correlation vector from octave oc = oct2py.Oct2Py() oc.addpath( os.path.join(os.path.dirname(os.path.dirname(__file__)), 'examples')) print oc [expected_S_x, data] = oc.doa_testbench_create('autocorrelate_test_input_gen', len_ss, overlap_size, num_inputs, FB) expected_S_x = tuple(expected_S_x) expected_S_x = list(itertools.chain.from_iterable(expected_S_x)) # num of snapshots n_ss = len(expected_S_x) / (num_inputs * num_inputs) ################################################## # Blocks & Connections ################################################## self.doa_autocorrelate_0 = doa.autocorrelate(num_inputs, len_ss, overlap_size, FB) self.vec_sink = blocks.vector_sink_c(num_inputs * num_inputs) # setup sources for p in range(num_inputs): # Add vector source object_name_vs = 'vec_source_' + str(p) setattr(self, object_name_vs, blocks.vector_source_c(data[:, p].tolist(), False)) # Connect self.tb.connect((getattr(self, object_name_vs), 0), (self.doa_autocorrelate_0, p)) self.tb.connect((self.doa_autocorrelate_0, 0), (self.vec_sink, 0)) # set up fg self.tb.run() observed_S_x = self.vec_sink.data() # check data expected_S_x_equals_observed_S_x = True for ii in range(n_ss * num_inputs * num_inputs): if abs(expected_S_x[ii] - observed_S_x[ii]) > 1.0: expected_S_x_equals_observed_S_x = False self.assertTrue(expected_S_x_equals_observed_S_x)
def __init__(self, shell): """ Parameters ---------- shell : IPython shell """ super(OctaveMagics, self).__init__(shell) self._oct = oct2py.Oct2Py() self._plot_format = 'png' # Allow publish_display_data to be overridden for # testing purposes. self._publish_display_data = publish_display_data
def extract_deep_chroma_to_file(dataset_path, output_file): dcp = DeepChromaProcessor() octave_engine = oct2py.Oct2Py() octave_engine.eval('pkg load signal') with open(os.path.join(dataset_path, 'listfiles'), 'r') as list_of_files: with open( os.path.join(dataset_path, 'YTC.madmom_deepchromas_smoothed=octave.txt') if not output_file else os.path.join(dataset_path, output_file), 'w') as output_file: for cover_file in list_of_files.readlines(): song_path = '%s%s.mp3' % (dataset_path, cover_file.strip()) for chroma in octave_engine.smoothDownsampleFeature( np.transpose(dcp(song_path))): output_file.write('%s\n' % string_for_chroma(chroma))
def fun(p): global mcode try: install('oct2py') except: pass import oct2py import tempfile import shutil import os fd, matfile = tempfile.mkstemp(suffix='.m') with os.fdopen(fd, 'wb') as f: f.write(mcode) f.flush() tmpdir = tempfile.mkdtemp() print('evaluating objective function with p = %s' % (str(p), )) oc = oct2py.Oct2Py() ret = oc.feval(matfile, p, tmpdir) print('f(%s) = %f' % ( str(p), ret, )) try: oc.exit() except: pass try: f.close() except: pass try: os.close(fd) except: pass try: os.remove(matfile) except: pass try: shutil.rmtree(tmpdir) except: pass return ret
def __init__(self, TrainingFile, ClassifierScript): self.DetectionStarted = False self.TrainingFile = TrainingFile self.ClassifierScript = ClassifierScript C = Classifiers() self.OctaveFunctionsPath = C.getFunctionsPath() self.OctaveTrainFunction = C.getTrainFunction(ClassifierScript) self.OctaveDetectFunction = C.getDetectFunction(ClassifierScript) #Octave self.octave = oct2py.Oct2Py() self.octave.call('addpath', self.OctaveFunctionsPath) self.DetectThread = DetectDirectionThread(self.octave, self.OctaveDetectFunction)
def main(): p = ArgumentParser() p.add_argument('direc', help='directory to plot') p.add_argument( 'max_threads', help='maximum number of threads to use (large grids use lots of RAM)', nargs='?', type=int, default=5) p.add_argument('-s', '--saveplots', help='plot type to save (png, eps) [default png]', nargs='+', default=['png']) p = p.parse_args() direc = Path(p.direc).expanduser() config = direc / 'inputs/config.ini' # works single-threaded, was just a first test # with oct2py.Oct2Py() as octave: # octave.plotall(p.direc, p.saveplots) # %% setup with oct2py.Oct2Py() as octave: octave.addpath('../script_utils') ymd0, UTsec0, tdur, dtout = octave.readconfig(str(config), nout=4) Nt = int((UTsec0 + tdur - UTsec0) // dtout) + 1 ymd = deepcopy(ymd0) UTsec = deepcopy(UTsec0) # %% setup threading ymds = [] UTsecs = [] for _ in range(Nt): ymd, UTsec = octave.dateinc(dtout, ymd, UTsec, nout=2) ymds.append(ymd) UTsecs.append(UTsec) # %% threading # set max_workers as high as your PC can handle with concurrent.futures.ThreadPoolExecutor( max_workers=p.max_threads) as exc: exc.map(frame, itertools.repeat(direc), ymds, UTsecs, itertools.repeat(p.saveplots))
def test_savgol(): k = 3 # filter length n = 5 # filter order # %% noisy signal x = np.array([0., 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]) x += np.random.randn(x.size) # %% Octave with oct2py.Oct2Py(oned_as='column') as oc: oc.eval('pkg load signal') ymat = oc.sgolayfilt(x, k, n).squeeze() # %% Python ypy = scipy.signal.savgol_filter(x, n, k) # %% plot np.testing.assert_allclose(ypy, ymat)