1# Lint as: python3
2# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#         http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15# ==============================================================================
16# pylint: disable=g-bad-import-order
17
18"""Load data from the specified paths and format them for training."""
19
20from __future__ import absolute_import
21from __future__ import division
22from __future__ import print_function
23
24import json
25
26import numpy as np
27import tensorflow as tf
28
29from data_augmentation import augment_data
30
31LABEL_NAME = "gesture"
32DATA_NAME = "accel_ms2_xyz"
33
34
35class DataLoader(object):
36    """Loads data and prepares for training."""
37
38    def __init__(self, train_data_path, valid_data_path, test_data_path,
39                             seq_length):
40        self.dim = 3
41        self.seq_length = seq_length
42        self.label2id = {"wing": 0, "ring": 1, "slope": 2, "negative": 3}
43        self.train_data, self.train_label, self.train_len = self.get_data_file(
44                train_data_path, "train")
45        self.valid_data, self.valid_label, self.valid_len = self.get_data_file(
46                valid_data_path, "valid")
47        self.test_data, self.test_label, self.test_len = self.get_data_file(
48                test_data_path, "test")
49
50    def get_data_file(self, data_path, data_type):    # pylint: disable=no-self-use
51        """Get train, valid and test data from files."""
52        data = []
53        label = []
54        with open(data_path, "r") as f:
55            lines = f.readlines()
56            for idx, line in enumerate(lines):    # pylint: disable=unused-variable
57                dic = json.loads(line)
58                data.append(dic[DATA_NAME])
59                label.append(dic[LABEL_NAME])
60        if data_type == "train":
61            data, label = augment_data(data, label)
62        length = len(label)
63        print(data_type + "_data_length:" + str(length))
64        return data, label, length
65
66    def pad(self, data, seq_length, dim):    # pylint: disable=no-self-use
67        """Get neighbour padding."""
68        noise_level = 20
69        padded_data = []
70        # Before- Neighbour padding
71        tmp_data = (np.random.rand(seq_length, dim) - 0.5) * noise_level + data[0]
72        tmp_data[(seq_length -
73                            min(len(data), seq_length)):] = data[:min(len(data), seq_length)]
74        padded_data.append(tmp_data)
75        # After- Neighbour padding
76        tmp_data = (np.random.rand(seq_length, dim) - 0.5) * noise_level + data[-1]
77        tmp_data[:min(len(data), seq_length)] = data[:min(len(data), seq_length)]
78        padded_data.append(tmp_data)
79        return padded_data
80
81    def format_support_func(self, padded_num, length, data, label):
82        """Support function for format.(Helps format train, valid and test.)"""
83        # Add 2 padding, initialize data and label
84        length *= padded_num
85        features = np.zeros((length, self.seq_length, self.dim))
86        labels = np.zeros(length)
87        # Get padding for train, valid and test
88        for idx, (data, label) in enumerate(zip(data, label)):    # pylint: disable=redefined-argument-from-local
89            padded_data = self.pad(data, self.seq_length, self.dim)
90            for num in range(padded_num):
91                features[padded_num * idx + num] = padded_data[num]
92                labels[padded_num * idx + num] = self.label2id[label]
93        # Turn into tf.data.Dataset
94        dataset = tf.data.Dataset.from_tensor_slices(
95                (features, labels.astype("int32")))
96        return length, dataset
97
98    def format(self):
99        """Format data(including padding, etc.) and get the dataset for the model."""
100        padded_num = 2
101        self.train_len, self.train_data = self.format_support_func(
102                padded_num, self.train_len, self.train_data, self.train_label)
103        self.valid_len, self.valid_data = self.format_support_func(
104                padded_num, self.valid_len, self.valid_data, self.valid_label)
105        self.test_len, self.test_data = self.format_support_func(
106                padded_num, self.test_len, self.test_data, self.test_label)
107