Skip to content

Instantly share code, notes, and snippets.

@ioggstream
Last active August 1, 2016 20:44
Show Gist options
  • Save ioggstream/f3e1347033d856a4083f8a3cd11ebd84 to your computer and use it in GitHub Desktop.
Save ioggstream/f3e1347033d856a4083f8a3cd11ebd84 to your computer and use it in GitHub Desktop.
Use sklearn to decide whether the computer is in tablet or laptop mode.
"""
Use sklearn to decide whether the computer is in tablet or laptop mode.
To play:
#tablet-mode-sensor.py gather # gather data in 2 csv files
#tablet-mode-sensor.py fit # create and store with pickle the predictor
#tablet-mode-sensor.py check # read the sensors and predict the laptop mode
To disable keyboard|touchpad get your device_ids with xinput and uncomment the
xinput lines.
"""
from __future__ import print_function
from glob import glob
from time import sleep
import csv
import pickle
from sklearn import svm
import pandas as pd
sensor_path = "/sys/bus/iio/devices/iio:device3/in_incli_*_raw"
scale = open("/sys/bus/iio/devices/iio:device3/in_incli_scale").read().strip()
scale = float(scale)
def get_incli():
"""Return the inclination sensor triple (x, y, z).
"""
line = x, y, z = [ float(open(f).read().strip()) * scale
for f in glob(sensor_path)
]
return line
def store_data(dest="tablet.csv", count=3000):
"""Gather `count` sensor data and store them in csv.
A laptop-mode line ends with 0
A tablet-mode line ends with 1
"""
target = dest.startswith("tablet")
with open(dest, 'w+') as fh:
writer = csv.writer(fh)
writer.writerow("x,y,z,is_tablet".split(","))
for i in range(count):
writer.writerow(get_incli() + [target])
sleep(.01)
def fit_data():
clf = svm.SVC(gamma=0.001, C=100.)
df_laptop = pd.read_csv('laptop.csv')
df_tablet = pd.read_csv('tablet.csv')
reg = pd.concat([df_laptop, df_tablet])
clf.fit(reg[['x','y','z']], reg[['is_tablet']])
return clf
if __name__ == '__main__':
from sys import argv
if 'gather' in argv:
raw_input("Gathering sensor data for laptop mode for 30 seconds. Move your PC keeping it in laptop mode.")
store_data("laptop.csv")
print("Completed!")
raw_input("Gathering sensor data for tablet mode for 30 seconds. Move your PC keeping it in tablet mode.")
store_data("tablet.csv")
elif 'fit' in argv:
with open('ai-lid.pickle', 'wb') as fh:
pickle.dump(fit_data(), fh)
elif 'check' in argv:
with open('ai-lid.pickle') as fh
clf = pickle.load(fh)
while True:
line = get_incli()
is_tablet = clf.predict(line)[0]
print("Laptop is in {} mode".format("tablet" if is_tablet else "laptop"))
# if is_tablet:
# check_output(split("xinput disable KEYBOARD_ID"))
# check_output(split("xinput disable TOUCHPAD_ID"))
sleep(1)
else:
raise SystemExit("Specify one of the following options: gather, fit, check")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment