/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.chromium.latency.walt; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.annotation.StringRes; import java.util.ArrayList; import java.util.Collections; /** * Kitchen sink for small utility functions */ public class Utils { public static double median(ArrayList arrList) { ArrayList lst = new ArrayList<>(arrList); Collections.sort(lst); int len = lst.size(); if (len == 0) { return Double.NaN; } if (len % 2 == 1) { return lst.get(len / 2); } else { return 0.5 * (lst.get(len / 2) + lst.get(len / 2 - 1)); } } public static double mean(double[] x) { double s = 0; for (double v: x) s += v; return s / x.length; } /** * Linear interpolation styled after numpy.interp() * returns values at points x interpolated using xp, yp data points * Both x and xp must be monotonically increasing. */ public static double[] interp(double[] x, double[] xp, double[] yp) { // assuming that x and xp are already sorted. // go over x and xp as if we are merging them double[] y = new double[x.length]; int i = 0; int ip = 0; // skip x points that are outside the data while (i < x.length && x[i] < xp[0]) i++; while (ip < xp.length && i < x.length) { // skip until we see an xp >= current x while (ip < xp.length && xp[ip] < x[i]) ip++; if (ip >= xp.length) break; if (xp[ip] == x[i]) { y[i] = yp[ip]; } else { double dy = yp[ip] - yp[ip-1]; double dx = xp[ip] - xp[ip-1]; y[i] = yp[ip-1] + dy/dx * (x[i] - xp[ip-1]); } i++; } return y; } public static double stdev(double[] a) { double m = mean(a); double sumsq = 0; for (double v : a) sumsq += (v-m)*(v-m); return Math.sqrt(sumsq / a.length); } /** * Similar to numpy.extract() * returns a shorter array with values taken from x at indices where indicator == value */ public static double[] extract(int[] indicator, int value, double[] arr) { if (arr.length != indicator.length) { throw new IllegalArgumentException("Length of arr and indicator must be the same."); } int newLen = 0; for (int v: indicator) if (v == value) newLen++; double[] newx = new double[newLen]; int j = 0; for (int i=0; i