def discharge_battery(targetlevel, currlevel=None, model=None): if not model: model = get_default_phone_model() if not currlevel: currlevel = get_battery_level() model.disable_charging() # In case it wasn't already disabled while currlevel != targetlevel: wait_for_drop() currlevel = get_battery_level() write_same_line("Discharging to {}, currently at {}".format( str(targetlevel), str(get_battery_level()))) finish_same_line()
def wait_for_drop(): dropped = False level = parse_battery_info(get_battery_info())["Charge counter"] starttime = time.time() finish_same_line() while not dropped: currlevel = parse_battery_info(get_battery_info())["Charge counter"] if level != currlevel: dropped = True break time.sleep(5) currtime = time.time() write_same_line("Time elapsed waiting for drop: {} seconds".format( str(currtime - starttime))) finish_same_line()
def charge_battery(targetlevel, model=None): if not model: model = get_default_phone_model() currlevel = get_battery_level() decrease = False if currlevel == targetlevel: discharge_battery(currlevel - 1, currlevel=currlevel, model=model) currlevel = get_battery_level() print("Started charging...") model.enable_charging() while currlevel < targetlevel: time.sleep(5) currlevel = get_battery_level() write_same_line("Charging to {}, curently at {}".format( str(targetlevel), str(currlevel))) finish_same_line() print("Finished charging, disabling it now...") model.disable_charging()
def main(args): print("Running Android Pre/Post test.") print("Running %s background color test.\n" % args.color) print("Make sure you have no extra apps running in the background.") print("Make sure that there is a wakelock app running" "(if going passed 30 minutes of testing).") print("Charging is disabled before the test starts. It is") print("enabled automatically when we reach the end of the test.") custom_input("Press enter when ready...", args.ignore_input) ds = DataSaver(args.output) ds.start() print("Getting Phone Model...") model = get_phone_model() print("Is the model %s correct?" % model.model) custom_input("Press Enter to confirm...", args.ignore_input) print("Disabling charging...") model.disable_charging() custom_input("Is it disabled?", args.ignore_input) old_screentimeout = get_screen_timeout() print("Old screen timeout: {}".format(old_screentimeout)) set_screen_timeout(12000000) # Ensure that it's sorted from low to high args.test_percent_range.sort() for trial in range(args.trials): currlevel = get_battery_level() if currlevel > args.test_percent_range[1]: discharge_battery(args.test_percent_range[1], model=model) elif currlevel < args.test_percent_range[0]: charge_battery(args.test_percent_range[1], model=model) print("\nOn trial {} \n".format(str(trial))) print("Installing app...") if args.browser_apk: install_package(args.browser_apk) print("Attempting to start %s test..." % args.color) start_color_test(args.color) custom_input( "When the test is ready, start the measurements by pressing enter...", args.ignore_input) print("Waiting for a charge counter drop...") wait_for_drop() print("Drop detected, starting test") print("Start time: {}".format(datetime.datetime.utcnow())) info = parse_battery_info(get_battery_info()) info["timestamp"] = time.time() starttime = info["timestamp"] ds.add(info, "batterydata") print("Starting values:") for k, v in info.items(): print("{}: {}".format(k, v)) start_cc = int(info["Charge counter"]) start_pc = int(info["level"]) currtime = 0 testtime_seconds = args.testtime * 60 while currtime - starttime < testtime_seconds: time.sleep(RESOLUTION) currtime = time.time() write_same_line("Elapsed time (seconds): {}".format( str(currtime - starttime))) finish_same_line() info = parse_battery_info(get_battery_info()) info["timestamp"] = time.time() ds.add(info, "batterydata") print("End time: {}".format(datetime.datetime.utcnow())) print("Final values:") for k, v in info.items(): print("{}: {}".format(k, v)) end_cc = int(info["Charge counter"]) end_pc = int(info["level"]) results = { 'Charge counter used': start_cc - end_cc, 'Percent used': start_pc - end_pc } ds.add(results, "summary{}_".format(str(trial))) print("\nCharge counter used: {}".format( str(results['Charge counter used']))) print("Percent used: {} \n".format(str(results['Percent used']))) set_screen_timeout(old_screentimeout) if args.browser_apk: uninstall_package() print("Enabling charging...") model.enable_charging() print("Stopping data saver...") ds.stop_running() print("Done.")
def main(args): OUTPUT = args.output print("Running OS baseline (percent-split) test.\n") print("Make sure you have no apps running in the background.") print("Make sure that there is a wakelock app running.") print("Charging is disabled and enabled periodically throughout " "the tests to gather {} trials for {} percentage ranges.".format( str(TRIALS), str(len(PERCENT_INTERVALS)))) _ = input("Press enter when ready...") ds = DataSaver(OUTPUT) ds.start() print("Getting Phone Model...") model = get_phone_model() print("Is the model %s correct?" % model.model) input("Press Enter to confirm...") print("Disabling charging...") model.disable_charging() input("Is it disabled?") for startpercent, endpercent in PERCENT_INTERVALS: print("\nOn percent interval: {} to {}".format(startpercent, endpercent)) trialtimes = [] for trialnum in range(TRIALS): print("\nRunning trial {}, current times are {}".format( trialnum, str(trialtimes))) print("Start time: {}".format(datetime.datetime.utcnow())) info = parse_battery_info(get_battery_info()) if int(info["level"]) <= startpercent: charge_battery(startpercent, model=model) elif int(info["level"]) > startpercent: discharge_battery(startpercent, model=model) dname = "pc_breakdown_{}-{}-{}".format(startpercent, endpercent, trialnum) outputdir = os.path.join(ds.output, dname) os.mkdir(outputdir) starttime = time.time() try: level = 1000 prevcharge = 0 prevlevel = 0 prevtemp = 0 while level > endpercent: # end percent is inclusive start = time.time() info = parse_battery_info(get_battery_info()) info["timestamp"] = time.time() ds.add(info, os.path.join(dname, "batterydata")) level = int(info["level"]) if (prevcharge != info["Charge counter"] or prevlevel != level or prevtemp != info["temperature"]): finish_same_line() write_same_line( "{} | Current capacity: {}%, {}, Temp: {}".format( datetime.datetime.utcnow(), str(level), info["Charge counter"], info["temperature"], )) prevlevel = level prevcharge = info["Charge counter"] prevtemp = info["temperature"] end = time.time() telapsed = end - start if telapsed < RESOLUTION: time.sleep(RESOLUTION - telapsed) except Exception as e: model.enable_charging() raise endtime = time.time() trialtimes.append(endtime - starttime) finish_same_line() print("Trial times for {} to {}: {}".format(startpercent, endpercent, str(trialtimes))) ds.add( {"trial-times": trialtimes}, "ttimes_pc_breakdown_{}-{}".format(startpercent, endpercent), ) print("Enabling charging...") model.enable_charging() print("Stopping data saver...") ds.stop_running() print("Done.")
def get_similarity(self, old_videos_info, new_videos_info, output, prefix="", most_similar=False): """Calculates a similarity score for two groupings of videos. The technique works as follows: 2. For each UxV video pairings, build a cross-correlation matrix: 1. Get each of the videos and calculate their histograms across the full videos. 2. Calculate the correlation coefficient between these two. 3. Average the cross-correlation matrix to obtain the score. Args: old_videos: List of old videos. new_videos: List of new videos (from this task). output: Location to output videos with low similarity scores. prefix: Prefix a string to the output. Returns: A dictionary containing the worst pairing and the 3D similarity score. """ def _get_frames(video): """Gets all frames from a video into a list.""" allframes = [] orange_pixind = 0 orange_frameind = 0 frame_count = 0 check_for_orange = True while video.isOpened(): ret, frame = video.read() if ret: # Convert to gray to simplify the process allframes.append(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)) # Check if it's orange still if check_for_orange: frame = allframes[-1] histo, _, _ = plt.hist(np.asarray(frame).flatten(), bins=255) maxi = np.argmax(histo) if not orange_pixind: if maxi > 130: continue orange_pixind = maxi elif maxi == orange_pixind: orange_frameind = frame_count else: check_for_orange = False frame_count += 1 else: video.release() break return allframes[orange_frameind:], orange_frameind nhists = [] old_videos = [entry["data"] for entry in old_videos_info] new_videos = [entry["data"] for entry in new_videos_info] new_orange_frameinds = [] old_orange_frameinds = [] total_vids = min(len(old_videos), len(new_videos)) xcorr = np.zeros((total_vids, total_vids)) for i in range(total_vids): datao, old_orange_frameind = _get_frames(old_videos[i]) datao = np.asarray(datao) old_orange_frameinds.append(old_orange_frameind) histo, _, _ = plt.hist(datao.flatten(), bins=255) plt.clf() gc.collect() for j in range(total_vids): write_same_line("Comparing old video %s to new video %s" % (i + 1, j + 1)) if i == 0: # Only calculate the histograms once; it takes time datan, new_orange_frameind = _get_frames(new_videos[j]) datan = np.asarray(datan) new_orange_frameinds.append(new_orange_frameind) histn, _, _ = plt.hist(datan.flatten(), bins=255) plt.clf() gc.collect() nhists.append(histn) else: histn = nhists[j] rho, _ = spearmanr(histo, histn) xcorr[i, j] = rho finish_same_line() similarity = np.nanmean(xcorr) print("Average 3D similarity: %s" % str(np.round(similarity, 5))) if most_similar: inds = np.unravel_index(np.argmax(xcorr, axis=None), xcorr.shape) else: inds = np.unravel_index(np.argmin(xcorr, axis=None), xcorr.shape) oldvid = old_videos_info[inds[0]]["path"] oldvidnewpath = str(pathlib.Path(output, "%sold_video.mp4" % prefix)) shutil.copyfile(oldvid, oldvidnewpath) newvid = new_videos_info[inds[1]]["path"] newvidnewpath = str(pathlib.Path(output, "%snew_video.mp4" % prefix)) shutil.copyfile(newvid, newvidnewpath) return { "sim3": np.round(similarity, 5), "oldvid": oldvidnewpath, "oldvid_ind": old_orange_frameinds[inds[0]], "newvid": newvidnewpath, "newvid_ind": new_orange_frameinds[inds[1]], }
def main(args): OUTPUT = args.output print("Running OS baseline test.\n") print("Make sure you have no apps running in the background.") print("Make sure that there is a wakelock app running.") print("Charging is disabled at the beginning of the test") print("and then enabled when we reach 5%.") _ = input("Press enter when ready...") ds = DataSaver(OUTPUT) ds.start() print("Getting Phone Model...") model = get_phone_model() print("Is the model %s correct?" % model.model) input("Press Enter to confirm...") print("Disabling charging...") model.disable_charging() input("Is it disabled?") print("Start time: {}".format(datetime.datetime.utcnow())) try: level = 1000 prevcharge = 0 prevlevel = 0 prevtemp = 0 while level != FINALLEVEL: start = time.time() info = parse_battery_info(get_battery_info()) info["timestamp"] = time.time() ds.add(info, "batterydata") level = int(info["level"]) if ( prevcharge != info["Charge counter"] or prevlevel != level or prevtemp != info["temperature"] ): finish_same_line() write_same_line( "{} | Current capacity: {}%, {}, Temp: {}".format( datetime.datetime.utcnow(), str(level), info["Charge counter"], info["temperature"], ) ) prevlevel = level prevcharge = info["Charge counter"] prevtemp = info["temperature"] end = time.time() telapsed = end - start if telapsed < RESOLUTION: time.sleep(RESOLUTION - telapsed) except Exception as e: model.enable_charging() raise finish_same_line() print("Enabling charging...") model.enable_charging() print("Stopping data saver...") ds.stop_running() print("Done.")