List of usage examples for java.util Arrays binarySearch
public static int binarySearch(Object[] a, int fromIndex, int toIndex, Object key)
From source file:com.milaboratory.core.mutations.generator.SubstitutionModel.java
public int sampleAsMutation(RandomGenerator generator, int position, int letter) { double value = generator.nextDouble(); int index = Arrays.binarySearch(cdf, letter * size, (letter + 1) * size, value); if (index < 0) index = -index - 1;// w w w . j a va2s .com index -= letter * size; assert index < size; if (index != letter) return Mutation.createSubstitution(position, letter, index); else return Mutation.NON_MUTATION; }
From source file:com.milaboratory.core.mutations.generator.GenericNucleotideMutationModel.java
@Override public int generateMutation(int position, int inputLetter) { double r = generator.nextDouble(); if (insertionProbability > r) return Mutation.createInsertion(position, generator.nextInt(4)); if (inputLetter >= 0) { int event = Arrays.binarySearch(events, inputLetter * 5, (inputLetter + 1) * 5, r); if (event < 0) event = -event - 1;/*from w ww.j a v a2 s . c o m*/ event -= inputLetter * 5; if (event == 0) return Mutation.createDeletion(position, inputLetter); if ((event - 1) != inputLetter) return Mutation.createSubstitution(position, inputLetter, (event - 1)); } return Mutation.NON_MUTATION; }
From source file:net.sf.jasperreports.engine.base.ElementsBlockList.java
protected int blockIndex(int index) { if (index < 0) { throw new IndexOutOfBoundsException("index: " + index); }/*from w w w . j ava 2s . c o m*/ // see if the index falls in the lastIndex block if (lastIndex >= 0 && lastIndex < blockCount) { if (index >= offsets[lastIndex] && (lastIndex + 1 == blockCount || index < offsets[lastIndex + 1])) { return lastIndex; } } int blockIndex = Arrays.binarySearch(offsets, 0, blockCount, index); if (blockIndex < 0) { blockIndex = -blockIndex - 2; } // caching last index for fast serial access lastIndex = blockIndex; return blockIndex; }
From source file:org.apache.sysml.runtime.codegen.SpoofOperator.java
protected static double getValue(double[] avals, int[] aix, int ai, int alen, int colIndex) { int pos = Arrays.binarySearch(aix, ai, ai + alen, colIndex); return (pos >= 0) ? avals[pos] : 0; }
From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java
/** * Constructs a stock quad tree for the given resolution * @param resolution/*from www. j a v a 2 s. c o m*/ */ StockQuadTree(int resolution) { this.resolution = resolution; this.r = new int[resolution * resolution]; final int[] z = new int[resolution * resolution]; // The list of all nodes Vector<Node> nodes = new Vector<Node>(); // Compute the Z-order of all values for (int i = 0; i < z.length; i++) { short x = (short) (i % resolution); short y = (short) (i / resolution); int zorder = AggregateQuadTree.computeZOrder(x, y); z[i] = zorder; r[i] = i; } // Sort ArrayToZOrder1200 by Z-Order and keep the original position of // each element by mirroring all swaps to ZOrderToArray1200 new QuickSort().sort(new IndexedSortable() { @Override public void swap(int i, int j) { int temp; // Swap z-values (which are to be sorted) temp = z[i]; z[i] = z[j]; z[j] = temp; // Swap their relative positions in the other array temp = r[i]; r[i] = r[j]; r[j] = temp; } @Override public int compare(int i, int j) { return z[i] - z[j]; } }, 0, z.length); // Construct the structure of the quad tree based on Z-values // Maximum number of values per node. Set it to a very small number to // construct as many levels as possible. Notice that when quad trees // are aggregated, a single value might become 366 values in the same pos. final int capacity = 100; Node root = new Node(); root.startPosition = 0; root.endPosition = z.length; root.id = 1; Queue<Node> nodesToCheckForSplit = new ArrayDeque<Node>(); nodesToCheckForSplit.add(root); int numOfSignificantBitsInTree = getNumOfSignificantBits(resolution * resolution - 1); if ((numOfSignificantBitsInTree & 1) == 1) numOfSignificantBitsInTree++; // Round to next even value int maxId = 0; while (!nodesToCheckForSplit.isEmpty()) { Node nodeToCheckForSplit = nodesToCheckForSplit.poll(); boolean needsToSplit = nodeToCheckForSplit.getNumOfElements() > capacity; if (nodeToCheckForSplit.id > maxId) maxId = nodeToCheckForSplit.id; nodes.add(nodeToCheckForSplit); if (needsToSplit) { // Need to split // Determine split points based on the Z-order values of the first and // last elements in this node int depth = nodeToCheckForSplit.id == 0 ? 0 : (getNumOfSignificantBits(nodeToCheckForSplit.id - 1) / 2 + 1); depth = (getNumOfSignificantBits(nodeToCheckForSplit.id) - 1) / 2; int numOfSignificantBitsInNode = numOfSignificantBitsInTree - depth * 2; // Create four child nodes under this node int zOrderCommonBits = z[nodeToCheckForSplit.startPosition] & (0xffffffff << numOfSignificantBitsInNode); int childStartPosition = nodeToCheckForSplit.startPosition; for (int iChild = 0; iChild < 4; iChild++) { int zOrderUpperBound = zOrderCommonBits + ((iChild + 1) << (numOfSignificantBitsInNode - 2)); int childEndPosition = Arrays.binarySearch(z, childStartPosition, nodeToCheckForSplit.endPosition, zOrderUpperBound); if (childEndPosition < 0) childEndPosition = -(childEndPosition + 1); Node child = new Node(); child.startPosition = childStartPosition; child.endPosition = childEndPosition; child.id = nodeToCheckForSplit.id * 4 + iChild; nodesToCheckForSplit.add(child); // Prepare for next iteration childStartPosition = childEndPosition; } if (childStartPosition != nodeToCheckForSplit.endPosition) throw new RuntimeException(); } } // Convert nodes to column format for memory efficiency nodesID = new int[nodes.size()]; nodesStartPosition = new int[nodes.size()]; nodesEndPosition = new int[nodes.size()]; for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); nodesID[i] = node.id; nodesStartPosition[i] = node.startPosition; nodesEndPosition[i] = node.endPosition; } }
From source file:com.ojcoleman.ahni.util.DoubleVector.java
/** * Searches the vector for the specified value using the binary search algorithm. * The array must be sorted (as by the sort() method) prior to making this call. * If it is not sorted, the results are undefined. * If the vector contains multiple elements with the specified value, there is no guarantee which one will be found. * This method considers all NaN values to be equivalent and equal. * @param key - the value to be searched for * @return index of the search key, if it is contained in the vector; otherwise, (-(insertion point) - 1). * The insertion point is defined as the point at which the key would be inserted into the vector: * the index of the first element greater than the key, or size() if all elements in the vector are less than the specified key. * Note that this guarantees that the return value will be >= 0 if and only if the key is found. *///from ww w . j a va2 s. c o m public int binarySearch(double key) { return Arrays.binarySearch(_data, 0, _size, key); }
From source file:gedi.util.datastructure.collections.doublecollections.DoubleArrayList.java
/** * Searches for the specified value using the * binary search algorithm.//from w ww . j a v a 2s . com * The array must be sorted (as * by the {@link #sort(int[], int, int)} method) * prior to making this call. If it * is not sorted, the results are undefined. If the array contains * multiple elements with the specified value, there is no guarantee which * one will be found. * * @param index the value to be searched for * @return index of the search key, if it is contained in the array * within the specified range; * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The * <i>insertion point</i> is defined as the point at which the * key would be inserted into the array: the index of the first * element in the range greater than the key, * or <tt>toIndex</tt> if all * elements in the range are less than the specified key. Note * that this guarantees that the return value will be >= 0 if * and only if the key is found. * @throws IllegalArgumentException * if {@code fromIndex > toIndex} * @throws ArrayIndexOutOfBoundsException * if {@code fromIndex < 0 or toIndex > a.length} * @since 1.6 */ public int binarySearch(int index) { return Arrays.binarySearch(doubleArray, 0, count, index); }
From source file:com.ojcoleman.ahni.util.DoubleVector.java
/** * Searches the vector for the specified value or the insertion point of the specified value using the binary search algorithm. * The array must be sorted (as by the sort() method) prior to making this call. * If it is not sorted, the results are undefined. * If the vector contains multiple elements with the specified value, there is no guarantee which one will be found. * This method considers all NaN values to be equivalent and equal. * @param key - the value to be searched for * @return index of the search key or the index at which the key would be inserted into the vector: * the index of the first element greater than the key, or size() if all elements in the vector are less than the specified key. */// w ww . j a v a 2s .c o m public int binarySearchIP(double key) { int ip = Arrays.binarySearch(_data, 0, _size, key); if (ip >= 0) return ip; return -ip - 1; }
From source file:io.warp10.continuum.gts.GTSOutliersHelper.java
/** * Applying STL-ESD test./*from ww w. ja v a2s .c o m*/ * ESD test is passed on residual of STL decompostition. * * @param gts * @param k Upper bound of suspected number of outliers * @param alpha Significance level with which to accept or reject anomalies. Default is 0.05 * @param params Optional map of parameters used for stl calls * * @return anomalous_ticks * * @throws WarpScriptException */ public static List<Long> STLESDTest(GeoTimeSerie gts, int buckets_per_period, int k, double alpha, Map<String, Object> params) throws WarpScriptException { doubleCheck(gts); List<Long> anomalous_ticks = new ArrayList<Long>(); if (!GTSHelper.isBucketized(gts)) { throw new WarpScriptException("GTS must be bucketized"); } // // Handling parameters of stl calls // if (null == params) { params = new HashMap<String, Object>(); } // Parameters PERIOD and BANDWIDTH_S must be set if (null != params.get(PERIOD_PARAM)) { if (buckets_per_period != (int) params.get(PERIOD_PARAM)) { throw new WarpScriptException( "Incoherence between PERIOD parameter of test and PERIOD parameter of STL"); } } else { params.put(PERIOD_PARAM, buckets_per_period); } params.put(BANDWIDTH_S_PARAM, Math.min(gts.bucketcount, 7)); // FIXME(JCV): do unit test for stl with outer > 0 so it can be changed here params.put(PRECISION_PARAM, 10); params.put(ROBUSTNESS_PARAM, 0); // the other parameters of stl are either already present in params, or their default values fixed in STL class are used List<GeoTimeSerie> stl_output = (List<GeoTimeSerie>) new STL("STL").doGtsOp(params, gts); GeoTimeSerie seasonal = stl_output.get(0); GeoTimeSerie trend = stl_output.get(1); // reuse seasonal body to not reallocate arrays GeoTimeSerie remainder = seasonal; int idx = 0; for (int i = 0; i < gts.values; i++) { idx = Arrays.binarySearch(seasonal.ticks, idx, seasonal.values, gts.ticks[i]); if (idx < 0) { throw new WarpScriptException("Internal bug method STLESDTest"); } else { remainder.doubleValues[i] = gts.doubleValues[idx] - (seasonal.doubleValues[idx] + trend.doubleValues[idx]); } } remainder.values = gts.values; remainder.bucketcount = gts.bucketcount; remainder.bucketspan = gts.bucketspan; remainder.lastbucket = gts.lastbucket; anomalous_ticks.addAll(ESDTest(remainder, k, true, alpha)); return anomalous_ticks; }
From source file:io.warp10.continuum.gts.GTSOutliersHelper.java
/** * Applying Seasonal Hybrid ESD.// w w w. jav a 2 s . c o m * This test is based on piecewise median and STL seasonal extraction, completed by an ESD test. * It was developed at Twitter. * @see https://www.usenix.org/system/files/conference/hotcloud14/hotcloud14-vallis.pdf * @see https://github.com/twitter/AnomalyDetection * * @param gts * @param k Upper bound of suspected number of outliers * @param alpha Significance level with which to accept or reject anomalies. Default is 0.05 * @param params Optional map of parameters used for stl calls * * @return anomalous_ticks * * @throws WarpScriptException */ public static List<Long> hybridTest(GeoTimeSerie gts, int buckets_per_period, int periods_per_piece, int k, double alpha, Map<String, Object> params) throws WarpScriptException { doubleCheck(gts); List<Long> anomalous_ticks = new ArrayList<Long>(); if (!GTSHelper.isBucketized(gts)) { throw new WarpScriptException("GTS must be bucketized"); } if (k >= periods_per_piece * buckets_per_period / 2) { throw new WarpScriptException( "Upper bound of number of outliers must be less than half of the number of observations per piece"); } // // SubSerie attributes // GeoTimeSerie subgts = null; GeoTimeSerie seasonal = null; // number of pieces long pieces = gts.bucketcount / buckets_per_period / periods_per_piece; // number of buckets per piece int bpp = periods_per_piece * buckets_per_period; long lb = gts.lastbucket; long bs = gts.bucketspan; // // Handling parameters of stl calls // if (null == params) { params = new HashMap<String, Object>(); } // Parameters PERIOD and BANDWIDTH_S must be set if (null != params.get(PERIOD_PARAM)) { if (buckets_per_period != (int) params.get(PERIOD_PARAM)) { throw new WarpScriptException( "Incoherence between PERIOD parameter of test and PERIOD parameter of STL"); } } else { params.put(PERIOD_PARAM, buckets_per_period); } params.put(BANDWIDTH_S_PARAM, periods_per_piece); // FIXME(JCV): do unit test for stl with outer > 0 so it can be changed here params.put(PRECISION_PARAM, 10); params.put(ROBUSTNESS_PARAM, 0); // the other parameters of stl are either already present in params, or their default values fixed in STL class are used // instanciating STL STL stl = new STL("STL"); for (int u = 0; u < pieces; u++) { long start = lb - bs * ((pieces - u) * bpp - 1); long stop = lb - bs * (pieces - u - 1) * bpp; // we don't start from the first bucket subgts = GTSHelper.subSerie(gts, start, stop, false, false, subgts); subgts.lastbucket = stop; subgts.bucketcount = bpp; subgts.bucketspan = bs; seasonal = ((List<GeoTimeSerie>) stl.doGtsOp(params, subgts)).get(0); double m = median(seasonal); int idx = 0; for (int i = 0; i < subgts.values; i++) { idx = Arrays.binarySearch(seasonal.ticks, idx, seasonal.values, subgts.ticks[i]); if (idx < 0) { throw new WarpScriptException("Internal bug method hybridTest: can't find tick " + subgts.ticks[i] + " in seasonal.ticks"); } else { subgts.doubleValues[i] -= (seasonal.doubleValues[idx] + m); } } anomalous_ticks.addAll(ESDTest(subgts, k, true, alpha)); } return anomalous_ticks; }