def test_octave_error(self): oc = Oct2Py() self.assertRaises(Oct2PyError, oc.run, 'a = ones2(1)')
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 == 'pro': zeta = np.math.acos(np.sqrt( 2. / 3)) # Approximately 35 deg for prolate shape elif shape == 'sph': zeta = np.math.acos(np.sqrt(1 / 3.)) elif shape == 'obl': zeta = 70. * np.pi / 180. # Hardcoded to 70 deg, to achive oblate b-tensor elif shape == 'pla': zeta = np.pi / 2. else: parser.error( 'btensor shape (shape) need to be one of lin, pro, sph, obl ,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 main(args): ''' Runs the whole sequence of FCS processing/analysis, using TASBE (a Matlab program) in an Oct2Py instance. The arguments above indicate the five configuration .json files needed, plus the output directory for the XML file which will indicate warnings and errors during processing. In many places, we still have hard-coded default values in the manifest_to_fcs_etl_params reactor (which largey generates and assembles the .json files needed here). One major assumption that will likely need to change as things evolve is that there is only one channel of data. Inputs: analysis-parameters: A .json file (e.g. analysis_parameters.json) specifying some information about the analyses to be performed, the parameters of these analyses, input/output locations of files, etc. If reanalysis of the same data set is being performed, this is generally the file that will be changed (most likely by TA1). Currently, this gets built automatically by the manifest_to_fcs_etl_params reactor, based on some assumptions about default values. cytometer-configuration: A .json file (e.g. cytometer_configuration.json) describing the state of the cytometer used to collect the data. This file will generally be provided by the TA3 performer, and will tend to change infrequently (if at all). experimental-data: A .json file (e.g. experimental_data.json) describing the URI and file locations for the raw data files to be included. This file gets generated automatically by the manifest_to_fcs_etl_params reactor, based on the manifest. color-model-parameters: A .json file (e.g. color_model_parameters.json) describing the species being analyzed, channels, bead peak config, etc. This file currently gets built automatically by the manifest_to_fcs_etl_params reactor, based on information in the cytometer-configuration file, though it is likely that this process will need to change as things evolve. process-control: A .json file (e.g. process_control.json) specifying some information about bead file, and control files, for each channel. This file gets generated automatically by the manifest_to_fcs_etl_params reactor, basedon on information in the manifest, plan, and cytometer-configuration files. junit-directory: Where the status XML gets written The steps below must be run in order; much of the work depends on the state of the octave object, which changes with each step. ''' octave = Oct2Py() cytometer = Cytometer(args.cytometer_configuration, octave) process = ProcessControl(args.process_control, octave) color_model = ColorModel(args.color_model_parameters, args.analysis_parameters, octave, process, cytometer) experiment_data = Experiment(args.experimental_data, octave) experiment_analysis = Analysis(args.analysis_parameters, args.cytometer_configuration, args.experimental_data, args.color_model_parameters, octave) color_model.make_gating(experiment_data) color_model.make_color_model() experiment_analysis.analyze() quicklook = Quicklook(args, experiment_analysis, octave) quicklook.make_notebook() try: if not os.path.exists(args.junit_directory): os.mkdir(args.junit_directory) octave.eval('TASBESession.to_xml(\'{}\')'.format( os.path.join(args.junit_directory, 'TASBESession.xml'))) except Exception as e: logging.error("Error writing JUnit directory {}: {}".format( args.junit_directory, e))
def __init__(self): from oct2py import Oct2Py self.engine = Oct2Py() self.engine.cd("octave") self.engine.run("gpml/startup.m")
def test_using_exited_session(self): with Oct2Py() as oc: oc.exit() with pytest.raises(Oct2PyError): oc.eval("ones")
def test_call_path(self): with Oct2Py() as oc: oc.addpath(os.path.dirname(__file__)) DATA = oc.test_datatypes() assert DATA.string.basic == 'spam'
def setup_class(cls): cls.oc = Oct2Py() cls.oc.addpath(os.path.realpath(os.path.dirname(__file__)))
from numpy import array from numpy.testing import run_module_suite, assert_array_almost_equal, assert_almost_equal from oct2py import Oct2Py """ generate test problems from Julia by using MatrixDepot matrixdepot("deriv2",3,false) """ A = array([[-0.0277778, -0.0277778, -0.00925926], [-0.0277778, -0.0648148, -0.0277778], [-0.00925926, -0.0277778, -0.0277778]]) b = array([-0.01514653483985129, -0.03474793286789414, -0.022274315940957783]) x_true = array([0.09622504486493762, 0.28867513459481287, 0.48112522432468807]) oc = Oct2Py(timeout=10, convert_to_float=True, oned_as='column') oc.addpath('../matlab') def test_maxent(): #%% first with Python from airtools.maxent import maxent x_python, rho, eta = maxent(A, b, 0.00002) assert_array_almost_equal(x_python, x_true) #%% then with Octave using original Matlab code x_matlab = oc.maxent(A, b, 0.00002).squeeze() assert_array_almost_equal(x_matlab, x_true)
def oc_addgenpath(path, oc=None): if oc == None: oc = Oct2Py() oc.addpath(oc.genpath(path)) return oc
from __future__ import division, absolute_import import os import unittest import numpy as np import seawater as sw from oct2py import Oct2Py from seawater.constants import c3515 from seawater.library import T90conv, T68conv, atleast_2d rootpath = os.path.dirname(__file__) octave = Oct2Py(timeout=3) path = os.path.join(rootpath, 'seawater_v3_3') _ = octave.addpath(octave.genpath(path)) functions = dict({ 'adtg': octave.sw_adtg, 'alpha': octave.sw_alpha, 'aonb': octave.sw_aonb, 'beta': octave.sw_beta, 'bfrq': octave.sw_bfrq, 'c3515': octave.sw_c3515, 'cndr': octave.sw_cndr, 'cp': octave.sw_cp, 'dens0': octave.sw_dens0, 'dens': octave.sw_dens, 'dist': octave.sw_dist, 'dpth': octave.sw_dpth, 'f': octave.sw_f, 'fp': octave.sw_fp,
def collocation(N, order, a0, l, w, h, r): octave = Oct2Py() octave.addpath(PATH) A, W = octave.Collocation_method_sparse_grids(a0, order, l, h, w, r, N) octave.exit() return A, W
def __init__(self): """Create our Octave instance and initialize the data array """ self.octave = Oct2Py() self.array = []
def run(problem, method): oc = Oct2Py() x = oc.qtable2(problem, method) # qtable2(1,'COS') return x
def setUp(self): self.oc = Oct2Py() self.oc.addpath(self.oc.genpath(os.path.dirname(__file__)))
def singleMethod(problem, method): oc = Oct2Py() oc.chdir('/home/ubuntu/BENCHOPaaS/BENCHOP/BENCHOP') time, relerr = oc.feval('singleMethod', problem, method, nout=2) return [time, relerr]
def reboot(self): self.octave = Oct2Py() self.init_oct()
def setup_class(cls): cls.oc = Oct2Py() cls.oc.addpath(os.path.dirname(__file__)) cls.data = cls.oc.test_datatypes()
def execute_oct2py(self): """ Uses oct2py Octave to Python bridge to execute all required analysis in BECAS. This way of executing BECAS was abandoned since it had some weird conflict with OpenMDAO's CaseIteratorDriver - probably due to the fact that both CaseIteratorDriver and Oct2Py use multiprocessing. """ from oct2py import Oct2Py self.load_input_vars() def isNoneType(x): if x is None: return True else: return False # check if the path to the BECAS program is properly defined if self.path_becas is '': msg = "path_becas is empty, please define a valid absolute path to BECAS" raise ValueError, msg # self._logger.info('executing BECAS ...') # to run concurrently you need a unique instance of oct2py, ie Oct2Py() # but this still seems to leave old instances of octave floating around # self.octave = octave t0 = time.time() self.octave = Oct2Py() # self.octave = Oct2Py(logger=self._logger) # self._logger.info('getting Oct2Py instance: % 10.6f seconds' % (time.time() - t0)) # this will produce a lot of output to the openmdao_log.txt file # self.octave = Oct2Py(logger=self._logger) self.octave.timeout = self.timeout # short hand notation oc = self.octave.run # set working dir of Octave to the BECAS source folder # oc("cd('%s')" % self.path_becas) t0 = time.time() self.setup_path() oc('BECAS_SetupPath') # self._logger.info('BECAS_SetupPath: % 10.6f seconds' % (time.time() - t0)) try: t0 = time.time() # Build arrays for BECAS # use BECAS input file loader when there is valid input path defined if self.path_input is not '': oc("options.foldername='%s'" % os.path.join(os.getcwd(), self.path_input)) oc("[utils] = BECAS_Utils(options);") else: # make sure we have the inputs defined correctly seq = (self.nl_2d, self.el_2d, self.emat, self.matprops) if any(map(isNoneType, seq)): raise ValueError, 'Not all BECAS inputs are defined' self.put_input_vars() oc("[utils] = BECAS_Utils(options, nl_2d, el_2d, emat, matprops);" ) # self._logger.info('BECAS_Utils: % 10.6f seconds' % (time.time() - t0)) # Check mesh quality if self.checkmesh: oc("[ meshcheck ] = BECAS_CheckMesh( utils );") # BECAS module for the evaluation of the cross section stiffness matrix t0 = time.time() oc("[ constitutive.Ks, solutions ] = BECAS_Constitutive_Ks(utils);" ) # self._logger.info('BECAS_Constitutive_Ks: % 10.6f seconds' % (time.time() - t0)) t0 = time.time() # BECAS module for the evaluation of the cross section mass matrix # self._logger.info('BECAS_Constitutive_Ms: % 10.6f seconds' % (time.time() - t0)) oc("[ constitutive.Ms ] = BECAS_Constitutive_Ms(utils);") t0 = time.time() # BECAS module for the evaluation of the cross section properties # self._logger.info('BECAS_CrossSectionProps: % 10.6f seconds' % (time.time() - t0)) oc("[ csprops ] = BECAS_CrossSectionProps(constitutive.Ks, utils);" ) # Output of results to HAWC2 st file t0 = time.time() oc("RadPos=1;") # Define radial position inputs = 'false, RadPos, constitutive, csprops, utils,' + str( self.hawc2_FPM).lower() oc("[cs_props] = BECAS_Becas2Hawc2(%s);" % inputs) # self._logger.info('BECAS_Becas2Hawc2: % 10.6f seconds' % (time.time() - t0)) self.paraview_octave() # obtain the output variables from Octave t0 = time.time() self.get_output_vars() # self._logger.info('get_output_vars: % 10.6f seconds' % (time.time() - t0)) # compute stresses and strains and check for failures t0 = time.time() self.stress_recovery_octave() # self._logger.info('stress_recovery: % 10.6f seconds' % (time.time() - t0)) except: if self.hawc2_FPM: h2c = np.zeros(30) else: h2c = np.zeros(19) h2c[1] = 2.e3 self.paraview_octave(force=True) # self._logger.info('BECAS crashed ...') self.octave.close()
def config(): oc = Oct2Py() oc.chdir('BENCHOP/') return oc
def test_timeout(self): with Oct2Py(timeout=2) as oc: oc.pause(2.1, timeout=5, nout=0) with pytest.raises(Oct2PyError): oc.pause(3, nout=0)
def Call_Values(op, n, typ): #Guarda en un txt numeros aleatorios en punto flotante oc = Oct2Py() oc.call_values("Decimal_A.txt", "Decimal_B.txt", n, op, typ)
# -*- coding: utf-8 -*- """ Integrates the K-Means Algorithm of Data clustering @author: Ujjaini """ import pandas as pd import matplotlib.pyplot as plt from pandas import DataFrame from oct2py import Oct2Py oc = Oct2Py() def find_closest_centroids(X, centroids): print("A") K = oc.size(centroids, 1) print("B") idx = oc.zeros(oc.size(X, 1), 1) print("C") m = oc.size(X, 1) print("D") for i in range(int(m)): min_dist = 1000000000 for j in range(int(K)): vector = X.iloc[i, :] - centroids.iloc[j, :] dist = oc.sum(vector ^ 2) if dist < min_dist: idx[i] = j min_dist = dist print("**********") print(str(i) + " " + str(j))
def result_error(typ, n): oc = Oct2Py() oc.finalresult(n, typ) oc.grapgresult(0)
def setUpClass(cls): cls.oc = Oct2Py() cls.oc.addpath(os.path.dirname(__file__))
R1 = A.dot(V) end = time.time() print('Native numpy MV: ', end - start, ' sec') # Test native rsb dot product AR = rsb_matrix(ACSR) #AR.autotune() start = time.time() R2 = AR.dot(V) end = time.time() print('PyRSB SpMV: ', end - start, ' sec') # Test SpMV serial implementation start = time.time() R3 = computeMatVecDotParfor(ACSR, V, False) end = time.time() print('Serial SpMV: ', end - start, ' sec') # Test SpMV parallel implementation start = time.time() R4 = computeMatVecDotParfor(ACSR, V, True) end = time.time() print('Parallel SpMV: ', end - start, ' sec') # Test SpMV from Octave bridge oc = Oct2Py(temp_dir='/dev/shm/') start = time.time() R5 = oc.mtimes(A, V) end = time.time() print('Octave SpMV: ', end - start, ' sec')
""" from __future__ import absolute_import, print_function import logging import os import pickle import sys import numpy as np import numpy.testing as test import oct2py from oct2py import Oct2Py, Oct2PyError from oct2py.utils import Struct from oct2py.compat import unicode, long, StringIO octave = Oct2Py() octave.addpath(os.path.dirname(__file__)) DATA = octave.test_datatypes() TYPE_CONVERSIONS = [ (int, 'int32', np.int32), (long, 'int64', np.int64), (float, 'double', np.float64), (complex, 'double', np.complex128), (str, 'char', unicode), (unicode, 'cell', unicode), (bool, 'int8', np.int8), (None, 'double', np.float64), (dict, 'struct', Struct), (np.int8, 'int8', np.int8), (np.int16, 'int16', np.int16),
#!/usr/bin/env python import numpy as np from oct2py import Oct2Py fs = 8000 # Hz T = 1. # second, arbitrary length of tone # 1 kHz sine wave, 1 second long, sampled at 8 kHz t = np.arange(0, T, 1 / fs) x = 0.5 * np.sin( 2 * np.pi * 1000 * t) # 0.5 is arbitrary to avoid clipping sound card DAC x = (x * 32768).astype(np.int16) # scale to int16 for sound card with Oct2Py() as oc: # print(oc.audiodevinfo()) a = oc.audioplayer(x, fs) oc.play(a)
def test_narg_out(): oc = Oct2Py() s = oc.svd(np.array([[1, 2], [1, 3]])) assert s.shape == (2, 1) U, S, V = oc.svd([[1, 2], [1, 3]]) assert U.shape == S.shape == V.shape == (2, 2)
# Copyright 2019 Richard Lincoln import logging from oct2py import Oct2Py logging.basicConfig(level=logging.INFO, format='%(message)s') mp = Oct2Py(logger=logging.getLogger()) mp.addpath("/usr/local/matpower")