def train_data():
    from navigation import r
    r.m1.use_pwm = False
    r.m2.use_pwm = False
    r.init_log()
    sleep(1)
    r.left(2)
    sleep(1)
    r.right(2)
    sleep(1)
    r.fw(2)
    sleep(1)
    r.rw(2)
    sleep(1)
    r.left(2)
    sleep(1)
    r.right(2)
    sleep(1)
    r.fw(2)
    sleep(1)
    r.rw(2)
    sleep(1)
    r.left(2)
    sleep(1)
    r.right(2)
    sleep(1)
    r.fw(2)
    sleep(1)
    r.rw(2)
    sleep(1)
    r.save_log(savepath='data/navigation_calibration/')
def calibrate(r, model=None):
    # load default model
    if model is None: model = Model.load('models/rover_calibration.pkl')
    # calibration movements | left & right using only one motor (easier)
    r.init_log()
    sleep(1)
    r.left(2, motor=1)
    sleep(1)
    r.left(2, motor=2)
    sleep(1)  # sequence: 1,3
    r.right(2, motor=1)
    sleep(1)
    r.right(2, motor=2)
    sleep(1)  # sequence: 5,7
    # end of calibration movements
    # get log, process data and remove stops
    logdata = r.save_log()
    logdata['fname'] = 'dropme'
    logdata.index.name = 'time'
    data = process_df(logdata)
    preds = data[model.features].groupby(level=['seq']).apply(
        lambda x: model.labels[model.predict_proba(x).sum(axis=0).argmax()])

    # check if movements are correctly calibrated
    if preds[1] == 'left' and preds[3] == 'left' and preds[
            5] == 'right' and preds[7] == 'right':
        print "Rover calibrated correctly (Motor1 gpio1_is_fw: %s | Motor2 gpio1_is_fw: %s)" % (
            r.m1.gpio1_is_fw, r.m2.gpio1_is_fw)
        return True
    else:
        if preds[1] == 'left' and preds[5] == 'right':
            r.m2.gpio1_is_fw = not r.m2.gpio1_is_fw
            print "Rover re-calibrated changing direction of Motor 1, testing..."
            return calibrate(r, model)
        elif preds[3] == 'left' and preds[7] == 'right':
            r.m1.gpio1_is_fw = not r.m1.gpio1_is_fw
            print "Rover re-calibrated changing direction of Motor 2, testing..."
            return calibrate(r, model)
        else:
            print "Error calibrating"
            return False