コード例 #1
0
def kuramoto_sivashinsky(sequence_length=1000,
                         n_sequence=1,
                         spatial_points=100):
    '''
    solution of the Kuramoto–Sivashinsky equation, u_t + u*u_x + α*u_xx + γ*u_xxxx = 0,
    computed by tanh-function method.
    '''
    # Octave functions are download from https://github.com/qyxiao/machine-learning-2016-spring/blob/master
    from oct2py import octave
    N = spatial_points
    h = 0.25  # time step length
    nstp = sequence_length
    # a0 = np.zeros([N - 2, 1])
    L = 22.
    input_data = np.zeros(
        (n_sequence, sequence_length + 1, spatial_points + 1))
    tt = np.zeros((n_sequence, 1, sequence_length + 1))
    xx = np.zeros((n_sequence, spatial_points + 1, 1))
    for idx in range(n_sequence):
        a0 = np.random.rand(N - 2, 1) / 4  # just some initial condition
        [tt[idx], fdata] = octave.feval('ksfmstp', a0, L, h, nstp, 1, nout=2)
        [xx[idx], input_data[idx, :, :]] = octave.feval('ksfm2real',
                                                        fdata,
                                                        L,
                                                        nout=2)
    # we remove first time and spatial indices because sometimes they get bad values
    input_data = input_data[:, 1:, 1:]
    tt = np.linspace(np.min(tt[:, :, :-1]), np.max(tt[:, :, :-1]),
                     sequence_length)
    xx = xx[0, :-1, 0]
    return input_data, xx, tt
コード例 #2
0
def get_kuramoto_sivashinsky_lyap_exp(sequence_length=1000,
                                      n_sequence=100,
                                      spatial_points=64):
    '''
    Lyapunov exponent for the Kuramoto–Sivashinsky equation, u_t + u*u_x + α*u_xx + γ*u_xxxx = 0.
    The method is adapted and modified from "Physica D 65 (1993) 117-134" paper, also from
    https://blog.abhranil.net/2014/07/22/calculating-the-lyapunov-exponent-of-a-time-series-with-python-code/
    '''
    from oct2py import octave
    N = spatial_points
    h = 0.25  # time step length
    nstp = sequence_length
    L = 22.
    dlist = [[] for i in range(sequence_length)]
    for i0 in range(n_sequence):
        a0 = np.random.rand(N - 2, 1) / 2  # just some initial condition
        [_, fdata] = octave.feval('ksfmstp', a0, L, h, nstp, 1, nout=2)
        [_, input_data0] = octave.feval('ksfm2real', fdata, L, nout=2)

        a1 = a0 + 10**(-7)
        [_, fdata] = octave.feval('ksfmstp', a1, L, h, nstp, 1, nout=2)
        [_, input_data1] = octave.feval('ksfm2real', fdata, L, nout=2)

        for k in range(sequence_length):
            dlist[k].append(
                np.log(np.linalg.norm(input_data0[k, :] - input_data1[k, :])))

    spectrum = np.zeros((sequence_length))
    for i in range(sequence_length):
        spectrum[i] = sum(dlist[i]) / len(dlist[i])

    lyap_exp = np.polyfit(range(len(spectrum)), spectrum, 1)[0] / h

    return lyap_exp
コード例 #3
0
def test_apply_OBM():
    """Test apply_OBM by comparing to Octave"""
    obm_m, _ = octave.feval('octave/thirdoct.m',
                            float(FS), float(NFFT), float(NUMBAND),
                            float(MINFREQ), nout=2)
    x = np.random.randn(2 * FS)
    x_tob_m = octave.feval('octave/applyOBM',
                           x, obm_m, float(N_FRAME), float(NFFT),
                           float(NUMBAND))
    x_tob_m = np.array(x_tob_m)
    x_spec = stft(x, N_FRAME, NFFT, overlap=2).transpose()
    x_tob = np.zeros((NUMBAND, x_spec.shape[1]))
    for i in range(x_tob.shape[1]):
        x_tob[:, i] = np.sqrt(np.matmul(OBM, np.square(np.abs(x_spec[:, i]))))
    assert_allclose(x_tob, x_tob_m, atol=ATOL)
コード例 #4
0
    def set_data_matlab(self, bind : str = None) -> None :
        """
            Get data from matlab file format
        """
        try :
            oct.eval("cd .")
            self._raw_data = oct.feval(bind)
        except :
            print("Please install oct2py and its dependencies if you want to use set_data_matlab()")
            raise
        
        self._network = Network()
        buses = []
        for i in range(0, self._raw_data["bus"].shape[0]):
            buses.append(Bus(data = self._raw_data["bus"][i]))

        ### merge "gen" and "gencost" matrix 
        self._raw_data["all_gen"] = np.concatenate((self._raw_data["gen"],self._raw_data["gencost"]),axis=1)

        ### Adding generators
        for i in range(0, self._raw_data["gen"].shape[0]):
            buses[int(self._raw_data["gen"][i][0] - 1)].add_generator(data = self._raw_data["all_gen"][i])
        
        ### Adding buses
        self._network.add_buses(buses)

        ### Adding branches
        for i in range(0,self._raw_data["branch"].shape[0]):
            self._network.add_branch(Branch(self._raw_data["branch"][i]))
コード例 #5
0
def test_estoi_good_fs():
    """ Test extended STOI at sampling frequency of 10kHz. """
    x = np.random.randn(2 * FS)
    y = np.random.randn(2 * FS)
    estoi_out = stoi(x, y, FS, extended=True)
    estoi_out_m = octave.feval('octave/estoi.m', x, y, float(FS))
    assert_allclose(estoi_out, estoi_out_m, atol=ATOL, rtol=RTOL)
コード例 #6
0
def test_stoi_good_fs():
    """ Test STOI at sampling frequency of 10kHz. """
    x = np.random.randn(2 * FS)
    y = np.random.randn(2 * FS)
    stoi_out = stoi(x, y, FS)
    stoi_out_m = octave.feval('octave/stoi.m', x, y, float(FS))
    assert_allclose(stoi_out, stoi_out_m, atol=ATOL, rtol=RTOL)
コード例 #7
0
def run_octave_script2(pk):
	out = None
	obj = ScriptCode.objects.get(pk=pk)
	user_folder = obj.get_user_folder()
	
	from oct2py import octave as oc
	import oct2py
	oc.addpath(user_folder)

	lst = tuple([2, 3])
	try:
		out = oc.feval(obj.get_file_name(), *lst, plot_dir=user_folder + '/images/', timeout=3)
	except oct2py.Oct2PyError:
		print('Octave Error happened')
		self.update_state(state='FAILED',
			meta={'message': 'Octave Error Happened'})
		oc.exit()
		oct2py.kill_octave()
		return None
	except TypeError:
		self.update_state(state='FAILED',
			meta={'message': 'type Error Happened'})
		oc.exit()
		oct2py.kill_octave()
		return None

	oc.exit()
	oct2py.kill_octave()

	result = {}
	result['somethings'] = 0
	result['out'] = out
	return result
コード例 #8
0
def test_stdft():
    """Test stdft by comparing to Octave"""
    x = np.random.randn(2 * FS)
    spec_m = octave.feval('octave/stdft.m', x, float(N_FRAME),
                          float(N_FRAME / 2), float(NFFT))
    spec_m = spec_m[:, 0:(NFFT // 2 + 1)].transpose()
    spec = stft(x, N_FRAME, NFFT, overlap=2).transpose()
    assert_allclose(spec, spec_m, atol=ATOL)
コード例 #9
0
def test_stoi_upsample():
    """ Test STOI at sampling frequency above 10 kHz. """
    for fs in [8000]:
        x = np.random.randn(2 * fs)
        y = np.random.randn(2 * fs)
        octave.eval('pkg load signal')
        stoi_out = stoi(x, y, fs)
        stoi_out_m = octave.feval('octave/stoi.m', x, y, float(fs))
        assert_allclose(stoi_out, stoi_out_m, atol=ATOL, rtol=RTOL)
コード例 #10
0
def test_stoi_downsample():
    """ Test STOI at sampling frequency below 10 kHz. """
    for fs in [11025, 16000, 22050, 32000, 44100, 48000]:
        x = np.random.randn(2 * fs)
        y = np.random.randn(2 * fs)
        octave.eval('pkg load signal')
        stoi_out = stoi(x, y, fs)
        stoi_out_m = octave.feval('octave/stoi.m', x, y, float(fs))
        assert_allclose(stoi_out, stoi_out_m, atol=ATOL, rtol=RTOL)
コード例 #11
0
ファイル: test_python_octave.py プロジェクト: yunzqq/pystoi
def test_hanning():
    """ Compare scipy and Matlab hanning window.

        Matlab returns a N+2 size window without first and last samples.
        A custom Octave function has been written to mimic this
        behavior."""
    hanning = scipy.hanning(N_FRAME+2)[1:-1]
    hanning_m = np.squeeze(octave.feval('octave/ml_hanning.m', N_FRAME))
    assert_allclose(hanning, hanning_m, atol=ATOL)
コード例 #12
0
def test_thirdoct():
    """Test thirdoct by comparing to Octave"""
    obm_m, cf_m = octave.feval('octave/thirdoct.m',
                               float(FS), float(NFFT), float(NUMBAND),
                               float(MINFREQ), nout=2)
    obm, cf = thirdoct(FS, NFFT, NUMBAND, MINFREQ)
    obm_m = np.array(obm_m)
    cf_m = np.array(cf_m).transpose().squeeze()
    assert_allclose(obm, obm_m, atol=ATOL)
    assert_allclose(cf, cf_m, atol=ATOL)
コード例 #13
0
def test_removesf():
    """Test remove_silent_frames by comparing to Octave"""
    # Initialize
    x = np.random.randn(2 * FS)
    y = np.random.randn(2 * FS)
    # Add silence segment
    silence = np.zeros(3 * NFFT, )
    x = np.concatenate([x[:FS], silence, x[FS:]])
    y = np.concatenate([y[:FS], silence, y[FS:]])
    xs, ys = remove_silent_frames(x, y, DYN_RANGE, N_FRAME, N_FRAME // 2)
    xs_m, ys_m = octave.feval('octave/removeSilentFrames.m',
                              x, y, float(DYN_RANGE),
                              float(N_FRAME),
                              float(N_FRAME / 2),
                              nout=2)
    xs_m = np.squeeze(xs_m)
    ys_m = np.squeeze(ys_m)
    assert_allclose(xs, xs_m, atol=ATOL)
    assert_allclose(ys, ys_m, atol=ATOL)
コード例 #14
0
ファイル: transform.py プロジェクト: hchen13/dialect
def denoise(wave):
    from oct2py import octave
    output = octave.feval('logmmse', np.trim_zeros(wave), 16000)
    return np.float32(np.squeeze(output))
コード例 #15
0
for i, f in enumerate(hull.simplices):
    for j in range(3):
        cube.vectors[i][j] = hull.points[f[j], :]

# Write the mesh to file "cube.stl"
cube.save(
    'D:\matlab_useful_codes\Mesh_voxelisation\Mesh_voxelisation\cube2.stl')
############################running matlab scripts in python #################################
from oct2py import octave as oct
# octave = oct.oct2py('D:\Octave\Octave-5.1.0.0\mingw64\\bin\octave-cli.exe')
import os
oct.eval("cd D:\matlab_useful_codes\Mesh_voxelisation\Mesh_voxelisation")
cwd = os.getcwd()
oct.addpath(cwd)
oct.addpath('D:\matlab_useful_codes\Mesh_voxelisation\Mesh_voxelisation')
oct.feval('VOXELISE_example_function', 'cube2.stl', rmax2 - rmin2,
          cmax2 - cmin2, zmax2 - zmin2)
# oct.feval('VOXELISE_example_function','cube2.stl',100,100,100)
oct.eval("cd D:\matlab_useful_codes\Mesh_voxelisation")
# oct.eval("save -v7 myworkspace.mat")
from scipy.io import loadmat
D = loadmat(
    "D:\matlab_useful_codes\Mesh_voxelisation\Mesh_voxelisation\myworkspace.mat"
)
print(D.keys())
########reading the .mat matrix convert it to numpy array and save it as .nrrd image using SimpleITK
# z=sio.loadmat('test_voxel.mat')
zz = np.zeros((d1, h1, w1), dtype=int)
z2 = D['OUTPUTgrid']
# os.remove('cube2.stl')
rmin3, rmax3, cmin3, cmax3, zmin3, zmax3 = bbox2_3D(z2)
# zz[rmin2:,cmin2:,zmin2:]=z2
コード例 #16
0
                        'length(cm)': lengthset,
                        'time': timeset,
                        columns[0]: wifi0,
                        columns[1]: wifi1,
                        columns[2]: wifi2,
                        columns[3]: wifi3,
                        columns[4]: wifi4,
                        columns[5]: wifi5
                    }

                    with open(filename, "w+") as f:
                        json.dump(data, f)
                    print "New file %s has been written.\n" % filename

                    #plot graph
                    octave.addpath('/home/pi')
                    octave.addpath('/home/pi/jsonlab')
                    octave.feval("plot_signal_strength", filename)

                    #set all values to the initial state
                    delta = 0
                    accumulated_delta = 0
                    length = 0
                    last_heading = 0
                    count = 0
                    break

finally:
    print "Exiting program!\n"
    GPIO.cleanup()  # resets all input/output configurations
コード例 #17
0
def differential_evolution(fobj,
                           bounds,
                           use_octave=False,
                           mut=0.9,
                           crossp=0.7,
                           popsize=100,
                           its=100):

    fitness_list = []
    generations = []

    dimensions = len(bounds)

    pop = np.random.rand(popsize, dimensions)

    min_b, max_b = np.asarray(bounds).T
    diff = np.fabs(min_b - max_b)

    pop_denorm = min_b + pop * diff

    if (use_octave):
        fitness = np.asarray(
            [octave.feval('peaks', ind) for ind in pop_denorm])
    else:
        fitness = np.asarray(
            [octave.feval('rastrigin', ind) for ind in pop_denorm])

    best_idx = np.argmin(fitness)
    best = pop_denorm[best_idx]

    for i in range(its):

        for j in range(popsize):

            idxs = [idx for idx in range(popsize) if idx != j]
            a, b, c = pop[np.random.choice(idxs, 3, replace=False)]

            mutant = np.clip(a + mut * (b - c), 0, 1)
            cross_points = np.random.rand(dimensions) < crossp

            if not np.any(cross_points):
                cross_points[np.random.randint(0, dimensions)] = True

            trial = np.where(cross_points, mutant, pop[j])
            trial_denorm = min_b + trial * diff

            if (use_octave):
                f = octave.feval('peaks', trial_denorm)
            else:
                f = fobj(trial_denorm)

            if f < fitness[j]:
                fitness[j] = f
                pop[j] = trial

                if f < fitness[best_idx]:
                    best_idx = j
                    best = trial_denorm

        yield best, fitness[best_idx]
        print("Best individual in generation %s : %f , %f" %
              (i + 1, best[0], best[1]))
        print("Best individual score in generation %s : %s" %
              (i + 1, fitness[best_idx]))
        fitness_list.append(fitness[best_idx])
        generations.append(i + 1)

    plot_chart(fitness_list, generations)
コード例 #18
0
    def test_mc(self):

        # Test all common algorithmstest_bc
        for algorithm in self.common_algorithms_mc:
            print("Testing ", algorithm, " (mc)")

            # Test all files in directory
            for filename in self.mc_files:

                path = self.mc_test_dir + '/' + filename
                path_octave = '/test/mc/' + filename

                # Octave execution
                mean_err_oct, std_error_oct, mean_nSV_oct, std_nSV_oct, mean_time_oct, std_time_oct = octave.feval(
                    './LIBOL-0.3/demo.m',
                    'mc',
                    algorithm,
                    path_octave,
                    'libsvm',
                    nout=6)

                # Python execution
                result_python = run('mc',
                                    algorithm,
                                    path,
                                    'libsvm',
                                    print_results=False,
                                    test_parameters=True)
                mean_err_py = result_python[0]
                mean_nSV_py = result_python[1]
                mean_time_py = result_python[2]

                # Test for similar performance
                error_diff = abs(mean_err_oct - mean_err_py)
                self.assertLessEqual(error_diff, 6 * std_error_oct)

                # Test for better execution time
                self.assertLessEqual(mean_time_py, mean_time_oct)
コード例 #19
0
ファイル: main.py プロジェクト: pengy8/ARM-Computer-Vision
def track(camera):
    # EVENT LISTENER
    octave.addpath('/home/Shuyang/Downloads/update/Velocity_Control_Constrained_ABB_OpenRAVE')

    egm=rpi_abb_irc5.EGM()

# Initialize Robot Parameters
    
    [ex,ey,ez,n,P,q_nouse,H,ttype,dq_bounds] = octave.feval('robotParams', nout=9)

# Initialize Control Parameters
# initial joint angles
    q = np.zeros((6, 1))
    [R,pos] = octave.feval('fwdkin', q,ttype,H,P,n, nout=2)
    dq = np.zeros((int(n),1))
    
    # velocities
    w_t = np.zeros((3, 1))
    v_t = np.zeros((3, 1))
    
    # create a handle of these parameters for interactive modifications
    obj = ControlParams(ex,ey,ez,n,P,H,ttype,dq_bounds,q,dq,pos,orien,pos_v,ang_v[None, :],w_t,v_t,epsilon,view_port,axes_lim,inc_pos_v,inc_ang_v,0,er,ep,0)

    dt = 0
    counter = 0
       
    req_exit = []
    StateVector = []
    listener = threading.Thread(target=input_thread, args=(req_exit,))
    listener.start()
    tag_index = 0
    Roc = np.array([[0.4860,-0.1868,-0.8537], [0.0583,   -0.9678,    0.2450], [-0.8720,   -0.1688,   -0.4595]])    
    Poc = np.array([[3579.5], [-826.5], [1416.7]])

    # Kalman Filter Parameters
    Phi = np.matrix('1 0 0 1 0 0; 0 1 0 0 1 0; 0 0 1 0 0 1; 0 0 0 1 0 0; 0 0 0 0 1 0; 0 0 0 0 0 1')
    R = np.eye(3,3)*1000 
    Q = np.eye(6)*1000
    H = np.eye(3,6)
    Cov = np.eye(6,6)*1500

    while not req_exit:
        if counter != 0:
        	end = time.time()
        	dt = end-start
            
        start = time.time()
        counter = counter + 1
        
        if counter != 0:               
            J_eef = octave.feval('getJacobian', obj.params['controls']['q'], obj.params['defi']['ttype'], obj.params['defi']['H'], obj.params['defi']['P'], obj.params['defi']['n'])
            
            data = []
            
            # Search if the camera module fails to find the tag for 30 consecutive frames
            for x in range(0,30):
            	data = camera.get_all_poses()[tag_index]
            	if data != []:
            	    break;

        	# SEARCH TERMINATED DUE TO BREAK SIGNAL
            if data == []:
            	print "No data."
            	return
        
			# Follow tag while it is in view
            else:                
            	Z = data[0] 
            	
            	# Kalman Filter: Initialization 
            	if StateVector == []:
            		StateVector = np.concatenate( (Z,np.array([[10],[10],[10]])),axis =0 )	    
    	        	# Kalman Filter: Prediction
            		StateVector = np.matmul(Phi, StateVector)
            		Cov = np.matmul(np.matmul(Phi, Cov),np.transpose(Phi)) + Q
            	
            		# Kalman Filter: Update
            		K = np.matmul(np.matmul(Cov, np.transpose(H)),np.linalg.inv(np.matmul(H,np.matmul(Cov, np.transpose(H))) +R))
            		StateVector = StateVector + np.matmul(K,(Z-np.matmul(H,StateVector)))
            		Cov = (np.eye(6,6)-K*H)*Cov        
            		Z_est = np.array(StateVector[:3]) 
            
            		Poa = np.matmul(Roc, Z_est) + Poc
            		Poa = Coordinate_mapping(Poa)
            		print "Poa:", np.transpose(Poa)
            		obj.params['controls']['dq'] = np.linalg.inv(J_eef[3:6, :])*(Poa - obj.params['controls']['q'])
            		
            		# desired joint velocity
            		obj.params['controls']['q'] = obj.params['controls']['q'] + obj.params['controls']['dq']*dt
            		res, state = egm.receive_from_robot(0.01)
      
            		if res:
		                a = np.array(state.joint_angles)
        		        a = a * 180 / np.pi
        		        print "Joints: " + str(a)
        		        egm.send_to_robot([float(x)*180/np.pi for x in obj.params['controls']['q']])
        		        print "Target Joints: " + str([float(x)*90/np.pi for x in obj.params['controls']['q']])
コード例 #20
0
def CRP(filepath, file):
    octave.eval('pkg load signal')
    crp = octave.feval('extract_CRP', filepath, file)
    return crp