Exemplo n.º 1
0
    def reset(self):
        """
        Reset environment and setup for new episode.

        Returns:
            initial state of reset environment.
        """

        if self.solver_step > 0:
            mean_accumulated_drag = self.accumulated_drag / self.solver_step
            mean_accumulated_lift = self.accumulated_lift / self.solver_step

            if self.verbose > -1:
                printi("mean accumulated drag on the whole episode: {}".format(mean_accumulated_drag))

        if self.inspection_params["show_all_at_reset"]:
            self.show_drag()
            self.show_control()

        self.start_class()

        next_state = np.transpose(np.array(self.probes_values))
        if self.verbose > 0:
            printiv(next_state)

        self.episode_number += 1

        return(next_state)
def one_run():

    printi("start simulation")
    state = environment.reset()
    environment.render = True
    null_action = np.zeros(environment.actions['shape'])
    for k in range(env.nb_actuations):
        #environment.print_state()
        action = agent.act(state, deterministic=deterministic)
        state, terminal, reward = environment.execute(null_action)
    # just for test, too few timesteps
    # runner.run(episodes=10000, max_episode_timesteps=20, episode_finished=episode_finished)

    data = np.genfromtxt("saved_models/test_strategy.csv", delimiter=";")
    data = data[1:,1:]
    m_data = np.average(data[len(data)//2:], axis=0)
    nb_jets = len(m_data)-4
    # Print statistics
    print("Single Run finished. AvgDrag : {}, AvgRecircArea : {}".format(m_data[1], m_data[2]))

    name = "test_strategy_avg.csv"
    if(not os.path.exists("saved_models")):
        os.mkdir("saved_models")
    if(not os.path.exists("saved_models/"+name)):
        with open("saved_models/"+name, "w") as csv_file:
            spam_writer=csv.writer(csv_file, delimiter=";", lineterminator="\n")
            spam_writer.writerow(["Name", "Drag", "Lift", "RecircArea"] + ["Jet" + str(v) for v in range(nb_jets)])
            spam_writer.writerow([environment.simu_name] + m_data[1:].tolist())
    else:
        with open("saved_models/"+name, "a") as csv_file:
            spam_writer=csv.writer(csv_file, delimiter=";", lineterminator="\n")
            spam_writer.writerow([environment.simu_name] + m_data[1:].tolist())
Exemplo n.º 3
0
def test_printi_function_call_wrapper():
    printi("enter test_printi_function_call_wrapper")

    @printidf
    def some_function():
        printi("this is the core")

    some_function()
    def compute_SWH(self):
        """Compute SWH using double integration of vertical acceleration."""

        # SWH
        self.SWH = 4.0 * np.std(self.elev_proc)

        if self.verbose > 1:
            printi("SWH = " + str(self.SWH))
    def open_serial_to_arduino(self):
        '''Find available serial ports to Arduino
        '''
        available_ports = glob.glob('/dev/ttyACM*')
        self.serial_port = serial.Serial(available_ports[0], baudrate=115200)
        self.serial_port.flushInput()
        self.serial_port.flushOutput()

        if self.verbose > 0:
            printi('Using port: ' + str(available_ports[0]))
Exemplo n.º 6
0
    def __init__(self, path_root, geometry_params, flow_params, solver_params, output_params,
                 optimization_params, inspection_params, n_iter_make_ready=None, verbose=0, size_history=2000,
                 reward_function='plain_drag', size_time_state=50, number_steps_execution=1, simu_name="Simu"):
        """

        """

        # TODO: should actually save the dicts in to double check when loading that using compatible simulations together

        printi("--- call init ---")

        self.path_root = path_root
        self.flow_params = flow_params
        self.geometry_params = geometry_params
        self.solver_params = solver_params
        self.output_params = output_params
        self.optimization_params = optimization_params
        self.inspection_params = inspection_params
        self.verbose = verbose
        self.n_iter_make_ready = n_iter_make_ready
        self.size_history = size_history
        self.reward_function = reward_function
        self.size_time_state = size_time_state
        self.number_steps_execution = number_steps_execution

        self.simu_name = simu_name


        #Relatif a l'ecriture des .csv
        name="output.csv"
        last_row = None
        if(os.path.exists("saved_models/"+name)):
            with open("saved_models/"+name, 'r') as f:
                for row in reversed(list(csv.reader(f, delimiter=";", lineterminator="\n"))):
                    last_row = row
                    break
        if(not last_row is None):
            self.episode_number = int(last_row[0])
            self.last_episode_number = int(last_row[0])
        else:
            self.last_episode_number = 0
            self.episode_number = 0
        self.episode_drags = np.array([])
        self.episode_areas = np.array([])
        self.episode_lifts = np.array([])

        self.initialized_visualization = False

        self.start_class()

        printi("--- done init ---")
    def launch_RPi_command(self):
        """Launch all RPi processing."""

        if self.verbose > 0:
            printi("Start RPi processing")

        self.open_serial_to_arduino()
        self.connect_to_Arduino()
        self.receive_from_Arduino()
        self.save_all()
        self.processing()
        self.send_over_Iridium()

        if self.verbose > 0:
            printi("Done with everything!")

        self.confirm_finished()
    def compute_zerocrossing(self):
        """Compute zero-crossing from time series"""

        # estimate zero crossing from timeseries
        indices = find((self.elev_proc[1:] >= 0) & (self.elev_proc[:-1] < 0))

        # More accurate, using linear interpolation to find intersample
        # zero-crossings
        crossings = [
            i - self.elev_proc[i] / (self.elev_proc[i + 1] - self.elev_proc[i])
            for i in indices
        ]
        # calculate mean period by averaging indices over total indices / divided by fs
        self.T_z0 = np.mean(np.diff(crossings) / self.fs)

        if self.verbose > 1:
            printi('T_z0 = {}'.format(self.T_z0))
Exemplo n.º 9
0
def episode_finished(r):
    print("Finished episode {ep} after {ts} timesteps (reward: {reward})".format(ep=r.episode, ts=r.episode_timestep,
                                                                                 reward=r.episode_rewards[-1]))

    printi("save the mode")

    name_save = "./saved_models/ppo_model"
    # NOTE: need to check if should create the dir
    r.agent.save_model(name_save, append_timestep=False)

    # show for plotting
    # r.environment.show_control()
    # r.environment.show_drag()

    # print(sess.run(tf.global_variables()))

    return True
    def compute_wave_spectrum_moments(self):
        """Compute the moments of the wave spectrum."""

        omega = 2 * np.pi * self.freq

        # note: integrate only on the 'valid' part of the spectrum

        self.M0 = integrate.trapz(self.a0, x=omega)
        self.M1 = integrate.trapz(self.a0 * (omega), x=omega)
        self.M2 = integrate.trapz(self.a0 * (omega**2), x=omega)
        self.M3 = integrate.trapz(self.a0 * (omega**3), x=omega)
        self.M4 = integrate.trapz(self.a0 * (omega**4), x=omega)
        self.MM1 = integrate.trapz(self.a0 * (omega**(-1)), x=omega)
        self.MM2 = integrate.trapz(self.a0 * (omega**(-2)), x=omega)

        if self.verbose > 1:
            printi('min, max of freq is {}, {}'.format(self.freq.min(),
                                                       self.freq.max()))
            printi('f shape is {}'.format(self.freq.shape))
 def _wrapper(*args, **kwargs):
     if class_containing is None:
         printi("call {} --".format(wrapped.__name__))
         result = wrapped(*args, **kwargs)
         printi("exit {} --".format(wrapped.__name__))
         return (result)
     else:
         printi("call {} from {} --".format(wrapped.__name__,
                                            class_containing))
         result = wrapped(*args, **kwargs)
         printi("exit {} from {} --".format(wrapped.__name__,
                                            class_containing))
         return (result)
Exemplo n.º 12
0
    def show_interpolation(self, show=True, n_points=100):
        """display the interpolation."""

        x_min = np.min(self.table_x_values)
        x_max = np.max(self.table_x_values)
        step = float(x_max - x_min) / n_points

        if self.verbose > 0:
            printi("x_min: " + str(x_min))
            printi("x_max: " + str(x_max))
            printi("step : " + str(step))

        array_x_values = np.arange(x_min, x_max, step)
        array_interpolated_values = self.interpolator(array_x_values)

        plt.figure()
        plt.plot(self.table_x_values,
                 self.table_coefficient_values,
                 'o',
                 label="data")
        plt.plot(array_x_values,
                 array_interpolated_values,
                 '--',
                 label='interpolated')
        plt.legend()
        plt.grid()
        if show:
            plt.show()
    def compute_spectral_properties(self):
        """Compute SWH and the peak period, both zero up-crossing and peak-to-peak,
        from spectral moments."""

        self.Hs = np.sqrt(self.M0) * 4.0 / np.sqrt(2 * np.pi)
        self.T_z = 2.0 * np.pi * np.sqrt(self.M0 / self.M2)
        self.T_c = 2.0 * np.pi * np.sqrt(self.M2 / self.M4)
        self.T_p = 1.0 / self.freq[np.argmax(self.a0)]

        if self.verbose > 2:
            printi('Hs (from M0) = {}'.format(self.Hs))
            printi('T_z = {}'.format(self.T_z))
            printi('T_c = {}'.format(self.T_c))
            printi('T_p = {}'.format(self.T_p))
Exemplo n.º 14
0
    def f_1(debug=0):
        printi('start f_1', debug=debug)
        printi('f_1 again!')

        f_2()

        f_3()

        printi('end f_1')
    def reset(self):
        """
        Reset environment and setup for new episode.

        Returns:
            initial state of reset environment.
        """

        if self.solver_step > 0:
            mean_accumulated_drag = self.accumulated_drag / self.solver_step
            mean_accumulated_lift = self.accumulated_lift / self.solver_step

            if self.verbose > -1:
                printi("mean accumulated drag on the whole episode: {}".format(mean_accumulated_drag))

        if self.inspection_params["show_all_at_reset"]:
            self.show_drag()
            self.show_control()

	chance = random.random()
	
	probability_hard_reset = 0.2

	if chance < probability_hard_reset:
	        self.start_class(complete_reset=True)
	else:
		self.start_class(complete_reset=False)
		# print(chance)

        next_state = np.transpose(np.array(self.probes_values))
        if self.verbose > 0:
            printiv(next_state)

        self.episode_number += 1

        return(next_state)
    def connect_to_Arduino(self):
        """Connect to the Arduino: acknowledge that listening."""

        wait_for_acknowledged_connection = True

        # clear the incoming buffer except last received char
        while self.serial_port.in_waiting > 1:
            self.serial_port.read()

        # look at last received char
        while wait_for_acknowledged_connection:
            if self.serial_port.in_waiting > 0:
                crrt_char = self.serial_port.read()

                if self.verbose > 5:
                    printi('Received char: ' + str(crrt_char))

                if crrt_char == 'B':
                    self.serial_port.write('R')

                wait_for_acknowledged_connection = False

        if self.verbose > 5:
            printi("Connection Acknowledged")
    def compute_subsample(self):
        """delete first and last IMU_buffer lengths"""

        self.pitch_proc = self.pitch_det[IMU_buffer:-IMU_buffer]
        self.roll_proc = self.roll_det[IMU_buffer:-IMU_buffer]
        self.elev_proc = self.elev[IMU_buffer:-IMU_buffer]
        self.accz_proc = self.accz_det[IMU_buffer:-IMU_buffer]

        if self.verbose > 3:
            printi("self.elev = " + str(self.elev_proc))
            printi("max elev: " + str(np.max(self.elev_proc)))
            printi("min elev: " + str(np.min(self.elev_proc)))
Exemplo n.º 18
0
def test_printi_functions():
    class TestClass(object):
        def __init__(self):
            self.some_var = "some_var"

        def print_self(self):
            printiv(self.some_var)

    def f_1(debug=0):
        printi('start f_1', debug=debug)
        printi('f_1 again!')

        f_2()

        f_3()

        printi('end f_1')

    def f_2():
        printi('start f_2')

        f_3()

        printi('f_2, this is the end!')

    def f_3():
        printi('start f_3')

        a = 4
        printiv(a)

    printi('this is the script')
    printi('the script is executing')
    f_1()
    printi('end of the script')

    test_class = TestClass()
    test_class.print_self()
    def save_all(self):
        """Save received commands and data, and append the filename list."""

        if self.verbose > 0:
            printi("Append filename_list.txt")

        with open(self.main_path + 'filename_list.txt', "a") as myfile:
            myfile.write(self.filename)
            myfile.write('\n')
            myfile.write("\n")

        if self.verbose > 0:
            printi("Add entry in Commands")

        with open(self.main_path + 'Commands/' + self.filename, "w") as myfile:
            for current_command in self.list_of_commands:
                myfile.write(current_command)
                myfile.write('\n')

        if self.verbose > 0:
            printi("Add entry in Data")

        with open(self.main_path + 'Data/' + self.filename, "w") as myfile:
            myfile.write(self.data)
from tensorforce.agents import PPOAgent
from tensorforce.execution import Runner
import env
import os
import csv

"""
import sys
import os
cwd = os.getcwd()
sys.path.append(cwd + "/../Simulation/")

from Env2DCylinder import Env2DCylinder
"""

printi("resume env")

environment = resume_env(plot=500, dump=10, single_run=True)
deterministic=True

printi("define network specs")

network_spec = [
    dict(type='dense', size=512),
    dict(type='dense', size=512),
]

printi("define agent")

printiv(environment.states)
printiv(environment.actions)
    def reduce_wave_spectrum(self):
        """A reduced wave spectrum, so that easier to transmit (less information).
        Reduction in information is obtained by restraining the frequency domain,
        reducing to 16 bits per frequency"""

        # reduce spectra with resample
        # pwr = -1
        # t0 = np.linspace(global_highcut**pwr, global_lowcut**pwr, global_downsample_length+1)
        # f0 = np.sort(t0**pwr)
        f1 = np.log(global_lowcut)
        f2 = np.log(global_highcut)
        self.freq_reduc = np.exp(np.linspace(f1, f2, global_downsample_length))
        # f0 = np.linspace(global_lowcut, global_highcut, global_downsample_length+1)
        # self.freq_reduc = 0.5 * (f0[0:-1] + f0[1:])

        self.a0_reduc, self.a0_reduc_max = DownSampleNbit(
            self.freq, self.a0, self.freq_reduc)
        self.a1_reduc, self.a1_reduc_max = DownSampleNbit(
            self.freq, self.a1, self.freq_reduc)
        self.b1_reduc, self.b1_reduc_max = DownSampleNbit(
            self.freq, self.b1, self.freq_reduc)
        self.a2_reduc, self.a2_reduc_max = DownSampleNbit(
            self.freq, self.a2, self.freq_reduc)
        self.b2_reduc, self.b2_reduc_max = DownSampleNbit(
            self.freq, self.b2, self.freq_reduc)
        self.R_reduc, self.R_reduc_max = DownSampleNbit(
            self.freq, self.R, self.freq_reduc)

        # normalize by max value and change to int16
        norm_val = 2**(global_nbit - 1) - 1

        M0_reduc = integrate.trapz(self.a0_reduc * self.a0_reduc_max /
                                   norm_val,
                                   x=2 * np.pi * self.freq_reduc)
        Hs_reduc = np.sqrt(M0_reduc) * 4.0 / np.sqrt(2 * np.pi)

        if self.verbose > 3:
            printi('limited_frequencies_frequencies = {}'.format(
                self.freq_reduc))
            printi('limited periods = {}'.format(1 / self.freq_reduc))
            printi("array_discretized_spectrum = " + str(self.a0_reduc))
            printi("max a0 reduced = " + str(self.a0_reduc_max))
            printi("max a1 reduced = " + str(self.a1_reduc_max))
            printi("max a2 reduced = " + str(self.a2_reduc_max))
            printi("max b1 reduced = " + str(self.b1_reduc_max))
            printi("max b2 reduced = " + str(self.b2_reduc_max))
            printi('Hs reduced = {}'.format(Hs_reduc))

        if self.verbose > 3:
            plt.figure()
            plt.plot(self.freq, self.a0)
            plt.plot(self.freq_reduc,
                     self.a0_reduc * self.a0_reduc_max / norm_val, '-ro')
            plt.plot(self.freq,
                     global_noise_acc * ((2 * np.pi * self.freq)**(-4)), 'k--')
            plt.xlim([global_lowcut, global_highcut])
            plt.yscale('log')
            plt.ylabel('a0')

            plt.figure()
            plt.plot(self.freq, self.a1)
            plt.plot(self.freq_reduc,
                     self.a1_reduc * self.a1_reduc_max / norm_val, '-ro')
            plt.xlim([global_lowcut, global_highcut])
            plt.yscale('linear')
            plt.ylabel('a1')

            plt.figure()
            plt.plot(self.freq, self.b1)
            plt.plot(self.freq_reduc,
                     self.b1_reduc * self.b1_reduc_max / norm_val, '-ro')
            plt.xlim([global_lowcut, global_highcut])
            plt.yscale('linear')
            plt.ylabel('b1')

            plt.figure()
            plt.plot(self.freq, self.a2)
            plt.plot(self.freq_reduc,
                     self.a2_reduc * self.a2_reduc_max / norm_val, '-ro')
            plt.xlim([global_lowcut, global_highcut])
            plt.yscale('linear')
            plt.ylabel('a2')

            plt.figure()
            plt.plot(self.freq, self.b2)
            plt.plot(self.freq_reduc,
                     self.b2_reduc * self.b2_reduc_max / norm_val, '-ro')
            plt.xlim([global_lowcut, global_highcut])
            plt.yscale('linear')
            plt.ylabel('b2')

            plt.figure()
            plt.plot(self.freq, self.R)
            plt.plot(self.freq_reduc,
                     (self.R_reduc * self.R_reduc_max / norm_val), '-ro')
            plt.xlim([global_lowcut, global_highcut])
            plt.yscale('linear')
            plt.ylabel('R')

            plt.show()
Exemplo n.º 22
0
import os
import numpy as np
from tensorforce.agents import PPOAgent
from tensorforce.execution import Runner

"""
import sys
import os
cwd = os.getcwd()
sys.path.append(cwd + "/../Simulation/")

from Env2DCylinder import Env2DCylinder
"""

printi("resume env")

environment = resume_env(plot=False, step=50, dump=100)

printi("define network specs")

network_spec = [
    dict(type='dense', size=512),
    dict(type='dense', size=512),
]

printi("define agent")

printiv(environment.states)
printiv(environment.actions)
printiv(network_spec)
Exemplo n.º 23
0
def test_decorator_on_all_methods():
    @printi_methods(printidf)
    class some_class(object):
        def __init__(self):
            printi("this is the init core")

        def some_method(self):
            printi("this is a method")

    some_instance = some_class()
    some_instance.some_method()


def test_printi_all_method_calls():
    @printidc()
    class some_class_2(object):
        def __init__(self):
            printi("this is the init core")

        def some_method(self):
            printi("this is a method")

    some_instance = some_class_2()
    some_instance.some_method()


if __name__ == "__main__":
    printi("Main call")

    callifile(verbose=False)
Exemplo n.º 24
0
 def some_function():
     printi("this is the core")
    def load_VN100_data(self):
        """Load in VN100 IMU data.
        Data is ordered in each line as"
        MagX, MagY, MagZ, AccX, AccY, AccZ, GyroX, GyroY, GyroZ,
        Temp, Pres, Yaw, Pitch, Roll,
        DCM1, DCM2, DCM3, DCM4, DCM5, DCM6, DCM7, DCM8, DCM9,
        MagNED1, MagNED2, MagNED3, AccNED1, AccNED2, ACCNED3"""

        # declare a few global variables that might need to be changed in this function
        global last_IMU_point_to_use
        global num_points_to_use

        # read line by line and detect errors
        bad_rec = 0
        good_rec = 0
        pitch = np.NaN * np.ones([
            int(last_IMU_point_to_use + first_IMU_point_to_use),
        ])
        roll = np.NaN * np.ones_like(pitch)
        accz = np.NaN * np.ones_like(pitch)
        if self.verbose > 3:
            printi('last IMU index is {}'.format(last_IMU_point_to_use))

        # open file
        with open(self.path_in + '/' + self.filename, 'r') as f:
            f.readline()  # read header
            ind = 0
            for line in f:
                dat = np.fromstring(line, sep=",")
                if len(dat) == 30:
                    pitch[ind] = dat[12]
                    roll[ind] = dat[13]
                    accz[ind] = dat[28]
                    ind = ind + 1
                    good_rec = good_rec + 1
                else:
                    pitch[ind] = np.NaN
                    roll[ind] = np.NaN
                    accz[ind] = np.NaN
                    ind = ind + 1
                    bad_rec = bad_rec + 1
                if ind >= last_IMU_point_to_use + first_IMU_point_to_use - 1:
                    if self.verbose > 3:
                        printi("index is {}".format(ind))
                    break
        if self.verbose > 3:
            printi('Total number of records are {}'.format(ind))
            printi('Number of good records are {}'.format(good_rec))
            printi('Number of bad records are {}'.format(bad_rec))

        # check that there are enough records
        if ind < last_IMU_point_to_use + first_IMU_point_to_use - 1:
            if self.verbose > 3:
                printi('Only {} records but require {}. Changing param length'.
                       format(ind,
                              last_IMU_point_to_use + first_IMU_point_to_use))
            # change the parameters to fit this new length
            last_IMU_point_to_use = int(ind)
            num_points_to_use = last_IMU_point_to_use - 2 * IMU_buffer - first_IMU_point_to_use
            if self.verbose > 3:
                printi('last IMU index changed to {}'.format(
                    last_IMU_point_to_use))
                printi('Calculating spectrum from {} minutes'.format(
                    num_points_to_use / (global_fs * 60)))

        # if NaNs exist then linearly interpolate
        if bad_rec > 0:
            nans, x = nan_helper(pitch)
            pitch[nans] = np.interp(x(nans), x(~nans), pitch[~nans])
            roll[nans] = np.interp(x(nans), x(~nans), roll[~nans])
            accz[nans] = np.interp(x(nans), x(~nans), accz[~nans])

        self.PITCH = np.deg2rad(
            pitch[first_IMU_point_to_use:last_IMU_point_to_use])
        self.ROLL = np.deg2rad(
            roll[first_IMU_point_to_use:last_IMU_point_to_use])
        self.ACCZ = accz[first_IMU_point_to_use:last_IMU_point_to_use]

        # simple detrend - remove mean
        self.pitch_det = signal.detrend(self.PITCH, type=IMU_detrend)
        self.roll_det = signal.detrend(self.ROLL, type=IMU_detrend)
        self.accz_det = signal.detrend(self.ACCZ, type=IMU_detrend)

        ## # apply filter
        ## butter = BandPass(fs=self.fs, lowcut=0.04, highcut=0.5)
        ## self.pitch_det = butter.filter_data(self.PITCH)
        ## self.roll_det = butter.filter_data(self.ROLL)
        ## self.accz_det = butter.filter_data(self.ACCZ)

        if self.verbose > 3:
            printi('Mean PITCH = {}'.format(np.mean(self.PITCH)))
            printi('Mean ROLL = {}'.format(np.mean(self.ROLL)))
            printi('Mean ACCZ = {}'.format(np.mean(self.ACCZ)))
            printi('Std PITCH = {}'.format(np.std(self.PITCH)))
            printi('Std ROLL = {}'.format(np.std(self.ROLL)))
            printi('Std ACCZ = {}'.format(np.std(self.ACCZ)))
            plt.figure()
            plt.plot(self.ACCZ, label='ACCZ')
            plt.plot(self.accz_det, label='ACCZ_det')
            plt.legend()
            plt.figure()
            plt.plot(self.PITCH, label='PITCH')
            plt.plot(self.ROLL, label='ROLL')
            plt.plot(self.pitch_det, label='PITCH_det')
            plt.plot(self.roll_det, label='ROLL_det')
            plt.legend()
    def load_test_data(self):
        """ load in synthetic data"""

        self.data_I = np.genfromtxt(self.path_in + '/' + self.filename,
                                    delimiter=',')

        self.PITCH = self.data_I[first_IMU_point_to_use:last_IMU_point_to_use,
                                 0]
        self.ROLL = self.data_I[first_IMU_point_to_use:last_IMU_point_to_use,
                                1]
        self.ACCZ = self.data_I[first_IMU_point_to_use:last_IMU_point_to_use,
                                2]

        self.PITCH_mean = np.mean(self.PITCH)
        self.ROLL_mean = np.mean(self.ROLL)
        self.ACCZ_mean = np.mean(self.ACCZ)
        self.PITCH_std = np.std(self.PITCH)
        self.ROLL_std = np.std(self.ROLL)
        self.ACCZ_std = np.std(self.ACCZ)

        self.pitch_det = signal.detrend(self.PITCH)
        self.roll_det = signal.detrend(self.ROLL)
        self.accz_det = signal.detrend(self.ACCZ)

        if self.verbose > 3:
            printi('Time duration of record is {} minutes'.format(
                len(self.ACCZ) / self.fs / 60))
            printi('Mean PITCH = {}'.format(self.PITCH_mean))
            printi('Mean ROLL = {}'.format(self.ROLL_mean))
            printi('Mean ACCZ = {}'.format(self.ACCZ_mean))
            printi('Std PITCH = {}'.format(self.PITCH_std))
            printi('Std ROLL = {}'.format(self.ROLL_std))
            printi('Std ACCZ = {}'.format(self.ACCZ_std))
    def receive_from_Arduino(self):

        self.list_of_commands = ['DEFAULT']
        self.filename = ""
        self.data = ""

        # received commands ----------------------------------------------------
        if self.verbose > 0:
            printi("Receive commands")

        wait_for_commands = True
        current_command = []

        while wait_for_commands:
            if self.serial_port.in_waiting > 0:
                crrt_char = self.serial_port.read()

                if self.verbose > 5:
                    printi('Received char: ' + str(crrt_char))

                if crrt_char == 'C':
                    self.list_of_commands.append(''.join(current_command))
                    current_command = []

                elif crrt_char == 'N':
                    self.list_of_commands.append(''.join(current_command))
                    wait_for_commands = False

                else:
                    current_command.append(crrt_char)

        # receive filename ----------------------------------------------------
        if self.verbose > 5:
            printi("Receive Filename")

        self.serial_port.write('N')

        wait_for_filename = True
        filename_list = []

        while wait_for_filename:
            if self.serial_port.in_waiting > 0:
                crrt_char = self.serial_port.read()

                if self.verbose > 5:
                    printi('Received char: ' + str(crrt_char))

                if crrt_char == 'N':
                    wait_for_filename = False
                    self.serial_port.write('N')

                else:
                    filename_list.append(crrt_char)

        self.filename = ''.join(filename_list)

        if self.verbose > 0:
            print("filename received: " + self.filename)

        # receive data ---------------------------------------------------------
        if self.verbose > 0:
            printi("Receive data")

        data_list = []
        message_start = "START_TRANSMIT_FILE"
        message_end = "END_TRANSMIT_FILE"

        # receive the start message
        analyze_stream = AnalyzeStream(message_start)

        while not analyze_stream.has_found_message():
            if self.serial_port.in_waiting > 0:
                crrt_char = self.serial_port.read()
                analyze_stream.read_char(crrt_char)

        if self.verbose > 0:
            print("received " + message_start)

        time_start = time()

        # receive the data including the end message
        analyze_stream = AnalyzeStream(message_end)

        while not analyze_stream.has_found_message():
            """
            if self.serial_port.in_waiting > 0:
                crrt_char = self.serial_port.read()
                data_list.append(crrt_char)
                analyze_stream.read_char(crrt_char)
            """

            number_bytes_available = self.serial_port.in_waiting

            if number_bytes_available > 0:

                crrt_char = self.serial_port.read()
                data_list.append(crrt_char)
                analyze_stream.read_char(crrt_char)

            if number_bytes_available < 32:

                self.serial_port.write("O")

        if self.verbose > 0:
            print("received " + message_end)
            print("time elapsed (s): {}".format(time() - time_start))

        # generate the data, taking away end message
        self.data = ''.join(data_list[:-len(message_end)])
Exemplo n.º 28
0
 def __init__(self):
     printi("this is the init core")
Exemplo n.º 29
0
 def some_method(self):
     printi("this is a method")
    def load_VN100_data(self):
        """Load in VN100 IMU data.
        Data is ordered in each line as"
        MagX, MagY, MagZ, AccX, AccY, AccZ, GyroX, GyroY, GyroZ,
        Temp, Pres, Yaw, Pitch, Roll,
        DCM1, DCM2, DCM3, DCM4, DCM5, DCM6, DCM7, DCM8, DCM9,
        MagNED1, MagNED2, MagNED3, AccNED1, AccNED2, ACCNED3"""

        self.data_I = np.genfromtxt(self.path_in + '/' + self.filename,
                                    skip_header=1,
                                    delimiter=',')

        if self.verbose > 3:
            printi('Shape of input data is {}'.format(self.data_I.shape))
            printi('Time duration of record is {} minutes'.format(
                len(self.data_I) / self.fs / 60))

        self.PITCH = np.deg2rad(
            self.data_I[first_IMU_point_to_use:last_IMU_point_to_use, 12])
        self.ROLL = np.deg2rad(
            self.data_I[first_IMU_point_to_use:last_IMU_point_to_use, 13])
        self.YAW = np.deg2rad(
            self.data_I[first_IMU_point_to_use:last_IMU_point_to_use, 11])
        self.ACCZ = self.data_I[first_IMU_point_to_use:last_IMU_point_to_use,
                                28]

        self.pitch_det = signal.detrend(self.PITCH)
        self.roll_det = signal.detrend(self.ROLL)
        self.accz_det = signal.detrend(self.ACCZ)

        # apply filter
        # butter = BandPass(fs=self.fs)
        # self.pitch_det = bp.filter_data(self.pitch_det)
        # self.roll_det = bp.filter_data(self.roll_det)
        # self.accz_det = bp.filter_data(self.accz_det)

        if self.verbose > 3:
            printi('Mean PITCH = {}'.format(np.mean(self.PITCH)))
            printi('Mean ROLL = {}'.format(np.mean(self.ROLL)))
            printi('Mean YAW = {}'.format(np.mean(self.YAW)))
            printi('Mean ACCZ = {}'.format(np.mean(self.ACCZ)))
            printi('Std PITCH = {}'.format(np.std(self.PITCH)))
            printi('Std ROLL = {}'.format(np.std(self.ROLL)))
            printi('Std YAW = {}'.format(np.std(self.YAW)))
            printi('Std ACCZ = {}'.format(np.std(self.ACCZ)))