'3,0',
])

#=================================================================================================#
# Prepare reference data.                                                                         #
#=================================================================================================#
#ref_folder = 'RobotArena/{0}/'.format(sys.argv[1].strip())

ref_data = np.zeros((len(ref_folders), len(ROUTE), 3))

# stack the route from each folder up along the 3rd axis
for repeat, ref_folder in enumerate(ref_folders):
    for filename in os.listdir(ref_folder):
        file_path = os.path.join(ref_folder, filename)
        if os.path.isfile(file_path):  # no folders (just in case)
            summary = mflog_utils.summarise_file(file_path)

            # put the data in this file at the right position along the route
            index = np.where(ROUTE == summary['location'])

            ref_data[repeat, index, :] = [
                summary['x']['median'],
                summary['y']['median'],
                summary['z']['median'],
            ]

# take the diff of each repeat at once and take their mean
# ref_diff = np.insert(np.diff(ref_data, axis=1), 0, 0, axis=1)
ref_diff = np.diff(ref_data, axis=1)
ref_diff = np.mean(ref_diff, axis=0)
from mpl_toolkits.mplot3d import Axes3D
import mflog_utils

summaries = {}

# run numbers to use
run_numbers = [int(num) for num in sys.argv[1:-1]]

for run_number in run_numbers:
    for dirpath, _, filenames in os.walk('RobotArena/' + str(run_number)):
        # Yay, order!
        print('Doing run #' + str(run_number))
        summaries[run_number] = {}

        for file in filenames:
            summary = mflog_utils.summarise_file(os.path.join(dirpath, file))
            summaries[run_number][summary['location']] = summary

        # just the once - no subdirs
        break

print('Got {} runs'.format(len(summaries)))

# matplotlib setup
mpl.rc('font', family='Arial')
#plt.style.use('ggplot')

fig, ax = plt.subplots(len(summaries), 3, figsize=(15, 2.5 * len(summaries) + 2), squeeze=False,
    sharex='col', sharey='row')
ax[-1, 1].set_xlabel('Position on path around robot arena', size='x-large')
ax[0, 0].set_title('x', fontsize=16)
import os
import numpy as np
import mflog_utils
import tabulate

files = []

for dirpath, _, filenames in os.walk('./TimeTesting'):
    for filename in filenames:
        if filename.endswith('.mflog'):
            files.append(os.path.join(dirpath, filename))

    break

tests = []

for filename in files:
    summary, data = mflog_utils.summarise_file(filename, True)
    tests.append([summary['duration'], summary['sample_count'], summary['x']['median'],
        summary['x']['range'], summary['x']['std']**2])

tests.sort()
print(tabulate.tabulate(tests,
    headers=('Duration', 'Samples', 'Median (x)', 'Range (x)', 'Var (x)')))

with open('./TimeTesting/summary.csv', 'w') as out:
    for test in tests:
        out.write(','.join([str(t) for t in test]) + '\n')
示例#4
0
def draw_xyz_plot(files,
                  save=None,
                  location_as_label=False,
                  label_prefix='L',
                  dim_height=3,
                  colors=mflog_utils.tableau20[0::2]):
    """ Draws a grid of plots, with a row for each file's x, y and z dimensions. `files` is a
        string list of names of .mflog files. If `save` is given and is a string, the plot is
        saved to `save`.
    """
    matplotlib.rc('font', family='Arial', weight='bold')
    #plt.style.use('ggplot')

    figure, axes = plt.subplots(len(files),
                                3,
                                sharex='col',
                                figsize=(12, dim_height * len(files)),
                                squeeze=False)

    axes[0, 0].set_title('x', size=24, position=[0.5, 1.05])
    axes[0, 1].set_title('y', size=24, position=[0.5, 1.05])
    axes[0, 2].set_title('z', size=24, position=[0.5, 1.05])

    axes[-1, 0].set_xlabel(u'μT', fontweight='bold', fontsize=16)
    axes[-1, 1].set_xlabel(u'μT', fontweight='bold', fontsize=16)
    axes[-1, 2].set_xlabel(u'μT', fontweight='bold', fontsize=16)

    location_keys = {}

    for (file_index, file_name) in enumerate(files):
        summary, data = mflog_utils.summarise_file(file_name,
                                                   include_data=True)

        if location_as_label:
            location_key = summary['location']
        else:
            location_key = label_prefix + str(file_index)

        location_keys[location_key] = summary
        axes[file_index, 0].set_ylabel(location_key,
                                       rotation=0,
                                       size=20,
                                       labelpad=40)

        for dimension in range(3):
            these_axes = axes[file_index, dimension]
            these_axes.tick_params(axis='y',
                                   which='both',
                                   left='off',
                                   right='off',
                                   labelleft='off')
            these_axes.tick_params(axis='x',
                                   which='both',
                                   top='off',
                                   labelsize=16)
            these_axes.xaxis.grid(True)

            #these_axes.get_xaxis().tick_bottom()
            #these_axes.get_yaxis().tick_left()

            # Good to disable spines in default style
            # these_axes.spines["top"].set_visible(False)
            # #these_axes.spines["bottom"].set_visible(False)
            # these_axes.spines["right"].set_visible(False)
            # these_axes.spines["left"].set_visible(False)

            # these_axes.hist(data.T[dimension], 25, normed=1,
            #     color=mflog_utils.tableau20[0::2][file_index % 10], linewidth=0)
            these_axes.hist(data.T[dimension],
                            25,
                            normed=1,
                            color=colors[file_index % len(colors)],
                            linewidth=0)

    figure.tight_layout()

    if isinstance(save, str):
        plt.savefig(save + '.png')  # woo, duck typing
        save_meta_file(save + '.txt', location_keys)

    plt.show()
    mean_6090 = np.mean(data[3048:, :], axis=0)

    with open(save_name + '.txt', 'w') as f:
        f.write(title + '\n\n')
        f.write('dim,all,-,0-30,-,30-60,-,60-90,-\n')

        for i in range(3):
            f.write('{},{},{},{},{},{},{},{},{}\n'.format(
                dims[i],
                mean_full[i],
                stds_full[i],
                mean_0030[i],
                stds_0030[i],
                mean_3060[i],
                stds_3060[i],
                mean_6090[i],
                stds_6090[i],
            ))

    plt.savefig(save_name + 'png')
    plt.show()


if __name__ == '__main__':
    _, data = mflog_utils.summarise_file('./PeopleTesting/Experiment1.mflog',
                                         include_data=True)
    plot_xyz(data, 'People Experiment 1', 'Plots/final/people1')

    _, data = mflog_utils.summarise_file('./PeopleTesting/Experiment2.mflog',
                                         include_data=True)
    plot_xyz(data, 'People Experiment 2', 'Plots/final/people2')
示例#6
0
                              color=spot_detail[1],
                              zorder=0)
    ax.add_patch(spot)
    art3d.patch_2d_to_3d(spot, z=0)

# Read files
arrow_magnitudes = np.zeros((16, 3))
arrow_positions = np.zeros((16, 3))
arrows = None  # for now
first_file_activity = ''
first_file_datetime = ''
first_file_filename = ''

for file in files:
    # pylint: disable=invalid-sequence-index
    summary = mflog_utils.summarise_file(file)

    # The location of arena files is set to "x,y" where x and y are integers between 0 and 3
    locx, locy = summary['location'].split(',', 1)
    locx = int(locx)
    locy = int(locy)

    if locx == 0 and locy == 0:
        # The first file!
        first_file_activity = summary['activity']
        first_file_datetime = summary['time_string']
        first_file_filename = file.split('/')[-1].split('.')[0]

    # Get the position of this arrow in the same order as the spots
    ordinal = locy * 4 + locx
示例#7
0
for dirpath, _, filenames in os.walk('RobotArena'):
    # Assuming we never revisit the same directory
    dirpath_parts = list(filter(None, dirpath.split('\\')))

    # First item yielded by walk is just the "RobotArena" directory. No want.
    if len(dirpath_parts) < 2:
        continue
    else:
        run_number = int(dirpath_parts[1])

    # Yay, order!
    print('Doing run #' + str(run_number))
    
    if run_number == TEST_RUN_NUMBER:
        for file in filenames:
            summary, data = mflog_utils.summarise_file(os.path.join(dirpath, file), True)

            # guaranteed only once
            post_data[summary['location']] = data

            if summary['location'] == '0,0': # first point
                post_file_meta = {
                    'activity': summary['room'],
                    'time_string': summary['time_string']
                }
    else:
        for file in filenames:
            summary, data = mflog_utils.summarise_file(os.path.join(dirpath, file), True)
            coords = summary['location']

            if coords not in prior_data: