code
stringlengths
11
173k
docstring
stringlengths
2
593k
func_name
stringlengths
2
189
language
stringclasses
1 value
repo
stringclasses
833 values
path
stringlengths
11
294
url
stringlengths
60
339
license
stringclasses
4 values
public static Integer[] removeIndex(Integer[] data, int index) { if (data == null) return null; if (data.length < 1) return data; int len = data.length; Integer[] result = new Integer[len - 1]; System.arraycopy(data, 0, result, 0, index); System.arraycopy(data, index + 1, result, index, len - index - 1); return result; }
Returns the array with the item in index removed, if the array is empty it will return the array itself @param data the data to remove data from @param index the index of the item to remove @return a copy of the array with the removed item, or the array itself if empty
ArrayUtil::removeIndex
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int[] calcStridesFortran(int[] shape, int startNum) { if (shape.length == 2 && (shape[0] == 1 || shape[1] == 1)) { int[] ret = new int[2]; Arrays.fill(ret, startNum); return ret; } int dimensions = shape.length; int[] stride = new int[dimensions]; int st = startNum; for (int j = 0; j < stride.length; j++) { stride[j] = st; st *= shape[j]; } return stride; }
Computes the standard packed array strides for a given shape. @param shape the shape of a matrix: @param startNum the start number for the strides @return the strides for a matrix of n dimensions
ArrayUtil::calcStridesFortran
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int[] calcStridesFortran(int[] shape) { return calcStridesFortran(shape, 1); }
Computes the standard packed array strides for a given shape. @param shape the shape of a matrix: @return the strides for a matrix of n dimensions
ArrayUtil::calcStridesFortran
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int[] calcStrides(int[] shape, int startValue) { if (shape.length == 2 && (shape[0] == 1 || shape[1] == 1)) { int[] ret = new int[2]; Arrays.fill(ret, startValue); return ret; } int dimensions = shape.length; int[] stride = new int[dimensions]; int st = startValue; for (int j = dimensions - 1; j >= 0; j--) { stride[j] = st; st *= shape[j]; } return stride; }
Computes the standard packed array strides for a given shape. @param shape the shape of a matrix: @param startValue the startValue for the strides @return the strides for a matrix of n dimensions
ArrayUtil::calcStrides
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static boolean isInverse(int[] first, int[] second) { int backWardCount = second.length - 1; for (int i = 0; i < first.length; i++) { if (first[i] != second[backWardCount--]) return false; } return true; }
Returns true if the given two arrays are reverse copies of each other @param first @param second @return
ArrayUtil::isInverse
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int nonOneStride(int[] arr) { for (int i = 0; i < arr.length; i++) if (arr[i] != 1) return arr[i]; return 1; }
For use with row vectors to ensure consistent strides with varying offsets @param arr the array to get the stride for @return the stride
ArrayUtil::nonOneStride
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int[] reverseCopy(int[] e) { if (e.length < 1) return e; int[] copy = new int[e.length]; for (int i = 0; i <= e.length / 2; i++) { int temp = e[i]; copy[i] = e[e.length - i - 1]; copy[e.length - i - 1] = temp; } return copy; }
Create a backwards copy of the given array @param e the array to createComplex a reverse clone of @return the reversed copy
ArrayUtil::reverseCopy
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static void multiplyBy(int[] arr, int mult) { for (int i = 0; i < arr.length; i++) arr[i] *= mult; }
Multiply the given array by the given scalar @param arr the array to multily @param mult the scalar to multiply by
ArrayUtil::multiplyBy
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static void reverse(int[] e) { for (int i = 0; i <= e.length / 2; i++) { int temp = e[i]; e[i] = e[e.length - i - 1]; e[e.length - i - 1] = temp; } }
Reverse the passed in array in place @param e the array to reverse
ArrayUtil::reverse
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static double[] flatten(double[][] arr) { if(arr.length == 0 || arr[0].length == 0 ) return new double[0]; double[] ret = new double[arr.length * arr[0].length]; int count = 0; for (int i = 0; i < arr.length; i++) { System.arraycopy(arr[i], 0, ret, count, arr[i].length); count += arr[i].length; } return ret; }
Convert a 2darray in to a flat array (row wise) @param arr the array to flatten @return a flattened representation of the array
ArrayUtil::flatten
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static double[][] toDouble(int[][] arr) { double[][] ret = new double[arr.length][arr[0].length]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) ret[i][j] = arr[i][j]; } return ret; }
Cast an int array to a double array @param arr the array to cast @return the elements of this array cast as an int
ArrayUtil::toDouble
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static float[] combineFloat(List<float[]> nums) { int length = 0; for (int i = 0; i < nums.size(); i++) length += nums.get(i).length; float[] ret = new float[length]; int count = 0; for (float[] i : nums) { for (int j = 0; j < i.length; j++) { ret[count++] = i[j]; } } return ret; }
Combines a applyTransformToDestination of int arrays in to one flat int array @param nums the int arrays to combineDouble @return one combined int array
ArrayUtil::combineFloat
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static float[] combine(List<float[]> nums) { int length = 0; for (int i = 0; i < nums.size(); i++) length += nums.get(i).length; float[] ret = new float[length]; int count = 0; for (float[] i : nums) { for (int j = 0; j < i.length; j++) { ret[count++] = i[j]; } } return ret; }
Combines a apply of int arrays in to one flat int array @param nums the int arrays to combineDouble @return one combined int array
ArrayUtil::combine
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static double[] combine(float[]... ints) { int length = 0; for (int i = 0; i < ints.length; i++) length += ints[i].length; double[] ret = new double[length]; int count = 0; for (float[] i : ints) { for (int j = 0; j < i.length; j++) { ret[count++] = i[j]; } } return ret; }
Combines a apply of int arrays in to one flat int array @param ints the int arrays to combineDouble @return one combined int array
ArrayUtil::combine
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static long[] combine(long[]... ints) { int length = 0; for (int i = 0; i < ints.length; i++) length += ints[i].length; long[] ret = new long[length]; int count = 0; for (long[] i : ints) { for (int j = 0; j < i.length; j++) { ret[count++] = i[j]; } } return ret; }
Combines a apply of long arrays in to one flat long array @param ints the int arrays to combineDouble @return one combined int array
ArrayUtil::combine
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static double[] flattenDoubleArray(Object doubleArray) { if (doubleArray instanceof double[]) return (double[]) doubleArray; LinkedList<Object> stack = new LinkedList<>(); stack.push(doubleArray); int[] shape = arrayShape(doubleArray); int length = ArrayUtil.prod(shape); double[] flat = new double[length]; int count = 0; while (!stack.isEmpty()) { Object current = stack.pop(); if (current instanceof double[]) { double[] arr = (double[]) current; for (int i = 0; i < arr.length; i++) flat[count++] = arr[i]; } else if (current instanceof Object[]) { Object[] o = (Object[]) current; for (int i = o.length - 1; i >= 0; i--) stack.push(o[i]); } else throw new IllegalArgumentException("Base array is not double[]"); } if (count != flat.length) throw new IllegalArgumentException("Fewer elements than expected. Array is ragged?"); return flat; }
Convert an arbitrary-dimensional rectangular double array to flat vector.<br> Can pass double[], double[][], double[][][], etc.
ArrayUtil::flattenDoubleArray
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static float[] flattenFloatArray(Object floatArray) { if (floatArray instanceof float[]) return (float[]) floatArray; LinkedList<Object> stack = new LinkedList<>(); stack.push(floatArray); int[] shape = arrayShape(floatArray); int length = ArrayUtil.prod(shape); float[] flat = new float[length]; int count = 0; while (!stack.isEmpty()) { Object current = stack.pop(); if (current instanceof float[]) { float[] arr = (float[]) current; for (int i = 0; i < arr.length; i++) flat[count++] = arr[i]; } else if (current instanceof Object[]) { Object[] o = (Object[]) current; for (int i = o.length - 1; i >= 0; i--) stack.push(o[i]); } else throw new IllegalArgumentException("Base array is not float[]"); } if (count != flat.length) throw new IllegalArgumentException("Fewer elements than expected. Array is ragged?"); return flat; }
Convert an arbitrary-dimensional rectangular float array to flat vector.<br> Can pass float[], float[][], float[][][], etc.
ArrayUtil::flattenFloatArray
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int[] arrayShape(Object array) { return arrayShape(array, false); }
Calculate the shape of an arbitrary multi-dimensional array. Assumes:<br> (a) array is rectangular (not ragged) and first elements (i.e., array[0][0][0]...) are non-null <br> (b) First elements have > 0 length. So array[0].length > 0, array[0][0].length > 0, etc.<br> Can pass any Java array opType: double[], Object[][][], float[][], etc.<br> Length of returned array is number of dimensions; returned[i] is size of ith dimension.
ArrayUtil::arrayShape
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int[] arrayShape(Object array, boolean allowSize0Dims) { int nDimensions = 0; Class<?> c = array.getClass().getComponentType(); while (c != null) { nDimensions++; c = c.getComponentType(); } int[] shape = new int[nDimensions]; Object current = array; for (int i = 0; i < shape.length - 1; i++) { shape[i] = ((Object[]) current).length; if(shape[i] == 0){ if(allowSize0Dims){ return shape; } throw new IllegalStateException("Cannot calculate array shape: Array has size 0 for dimension " + i ); } current = ((Object[]) current)[0]; } if (current instanceof Object[]) { shape[shape.length - 1] = ((Object[]) current).length; } else if (current instanceof double[]) { shape[shape.length - 1] = ((double[]) current).length; } else if (current instanceof float[]) { shape[shape.length - 1] = ((float[]) current).length; } else if (current instanceof long[]) { shape[shape.length - 1] = ((long[]) current).length; } else if (current instanceof int[]) { shape[shape.length - 1] = ((int[]) current).length; } else if (current instanceof byte[]) { shape[shape.length - 1] = ((byte[]) current).length; } else if (current instanceof char[]) { shape[shape.length - 1] = ((char[]) current).length; } else if (current instanceof boolean[]) { shape[shape.length - 1] = ((boolean[]) current).length; } else if (current instanceof short[]) { shape[shape.length - 1] = ((short[]) current).length; } else throw new IllegalStateException("Unknown array type"); //Should never happen return shape; }
Calculate the shape of an arbitrary multi-dimensional array.<br> Note that the method assumes the array is rectangular (not ragged) and first elements (i.e., array[0][0][0]...) are non-null <br> Note also that if allowSize0Dims is true, any elements are length 0, all subsequent dimensions will be reported as 0. i.e., a double[3][0][2] would be reported as shape [3,0,0]. If allowSize0Dims is false, an exception will be thrown for this case instead. Can pass any Java array opType: double[], Object[][][], float[][], etc.<br> Length of returned array is number of dimensions; returned[i] is size of ith dimension.
ArrayUtil::arrayShape
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int max(int[] in) { int max = Integer.MIN_VALUE; for (int i = 0; i < in.length; i++) if (in[i] > max) max = in[i]; return max; }
Calculate the shape of an arbitrary multi-dimensional array.<br> Note that the method assumes the array is rectangular (not ragged) and first elements (i.e., array[0][0][0]...) are non-null <br> Note also that if allowSize0Dims is true, any elements are length 0, all subsequent dimensions will be reported as 0. i.e., a double[3][0][2] would be reported as shape [3,0,0]. If allowSize0Dims is false, an exception will be thrown for this case instead. Can pass any Java array opType: double[], Object[][][], float[][], etc.<br> Length of returned array is number of dimensions; returned[i] is size of ith dimension. public static int[] arrayShape(Object array, boolean allowSize0Dims) { int nDimensions = 0; Class<?> c = array.getClass().getComponentType(); while (c != null) { nDimensions++; c = c.getComponentType(); } int[] shape = new int[nDimensions]; Object current = array; for (int i = 0; i < shape.length - 1; i++) { shape[i] = ((Object[]) current).length; if(shape[i] == 0){ if(allowSize0Dims){ return shape; } throw new IllegalStateException("Cannot calculate array shape: Array has size 0 for dimension " + i ); } current = ((Object[]) current)[0]; } if (current instanceof Object[]) { shape[shape.length - 1] = ((Object[]) current).length; } else if (current instanceof double[]) { shape[shape.length - 1] = ((double[]) current).length; } else if (current instanceof float[]) { shape[shape.length - 1] = ((float[]) current).length; } else if (current instanceof long[]) { shape[shape.length - 1] = ((long[]) current).length; } else if (current instanceof int[]) { shape[shape.length - 1] = ((int[]) current).length; } else if (current instanceof byte[]) { shape[shape.length - 1] = ((byte[]) current).length; } else if (current instanceof char[]) { shape[shape.length - 1] = ((char[]) current).length; } else if (current instanceof boolean[]) { shape[shape.length - 1] = ((boolean[]) current).length; } else if (current instanceof short[]) { shape[shape.length - 1] = ((short[]) current).length; } else throw new IllegalStateException("Unknown array type"); //Should never happen return shape; } /** Returns the maximum value in the array
ArrayUtil::max
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int min(int[] in) { int min = Integer.MAX_VALUE; for (int i = 0; i < in.length; i++) if (in[i] < min) min = in[i]; return min; }
Calculate the shape of an arbitrary multi-dimensional array.<br> Note that the method assumes the array is rectangular (not ragged) and first elements (i.e., array[0][0][0]...) are non-null <br> Note also that if allowSize0Dims is true, any elements are length 0, all subsequent dimensions will be reported as 0. i.e., a double[3][0][2] would be reported as shape [3,0,0]. If allowSize0Dims is false, an exception will be thrown for this case instead. Can pass any Java array opType: double[], Object[][][], float[][], etc.<br> Length of returned array is number of dimensions; returned[i] is size of ith dimension. public static int[] arrayShape(Object array, boolean allowSize0Dims) { int nDimensions = 0; Class<?> c = array.getClass().getComponentType(); while (c != null) { nDimensions++; c = c.getComponentType(); } int[] shape = new int[nDimensions]; Object current = array; for (int i = 0; i < shape.length - 1; i++) { shape[i] = ((Object[]) current).length; if(shape[i] == 0){ if(allowSize0Dims){ return shape; } throw new IllegalStateException("Cannot calculate array shape: Array has size 0 for dimension " + i ); } current = ((Object[]) current)[0]; } if (current instanceof Object[]) { shape[shape.length - 1] = ((Object[]) current).length; } else if (current instanceof double[]) { shape[shape.length - 1] = ((double[]) current).length; } else if (current instanceof float[]) { shape[shape.length - 1] = ((float[]) current).length; } else if (current instanceof long[]) { shape[shape.length - 1] = ((long[]) current).length; } else if (current instanceof int[]) { shape[shape.length - 1] = ((int[]) current).length; } else if (current instanceof byte[]) { shape[shape.length - 1] = ((byte[]) current).length; } else if (current instanceof char[]) { shape[shape.length - 1] = ((char[]) current).length; } else if (current instanceof boolean[]) { shape[shape.length - 1] = ((boolean[]) current).length; } else if (current instanceof short[]) { shape[shape.length - 1] = ((short[]) current).length; } else throw new IllegalStateException("Unknown array type"); //Should never happen return shape; } /** Returns the maximum value in the array public static int max(int[] in) { int max = Integer.MIN_VALUE; for (int i = 0; i < in.length; i++) if (in[i] > max) max = in[i]; return max; } /** Returns the minimum value in the array
ArrayUtil::min
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int argMax(int[] in) { int maxIdx = 0; for (int i = 1; i < in.length; i++) if (in[i] > in[maxIdx]) maxIdx = i; return maxIdx; }
Returns the index of the maximum value in the array. * If two entries have same maximum value, index of the first one is returned.
ArrayUtil::argMax
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int argMin(int[] in) { int minIdx = 0; for (int i = 1; i < in.length; i++) if (in[i] < in[minIdx]) minIdx = i; return minIdx; }
Returns the index of the minimum value in the array. * If two entries have same minimum value, index of the first one is returned.
ArrayUtil::argMin
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int fromBoolean(boolean bool) { return bool ? 1 : 0; }
Convert an int @param bool @return
ArrayUtil::fromBoolean
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static <T> void assertNotRagged(T[] array){ Class<?> c = array.getClass().getComponentType(); int[] arrayShape = ArrayUtil.arrayShape(array, true); int rank = arrayShape.length; if(rank == 1){ //Rank 1 cannot be ragged return; } if(rank >= 2){ for( int i = 1; i < arrayShape[0]; i++) { Object subArray = array[i]; int len = arrayLength(subArray); Preconditions.checkState(arrayShape[1] == len, "Ragged array detected: array[0].length=%s does not match array[%s].length=%s", arrayShape[1], i, len); } if(rank == 2) return; } if(rank >= 3){ for( int i = 0; i < arrayShape[0]; i++) { for( int j = 0; j < arrayShape[1]; j++) { Object subArray = ((Object[][])array)[i][j]; int len = arrayLength(subArray); Preconditions.checkState(arrayShape[2] == len, "Ragged array detected: array[0][0].length=%s does not match array[%s][%s].length=%s", arrayShape[2], i, j, len); } } if(rank == 3) return; } if(rank >= 4){ for( int i = 0; i < arrayShape[0]; i++) { for( int j = 0; j<arrayShape[1]; j++) { for( int k = 0; k < arrayShape[2]; k++) { Object subArray = ((Object[][][])array)[i][j][k]; int len = arrayLength(subArray); Preconditions.checkState(arrayShape[3] == len, "Ragged array detected: array[0][0][0].length=%s does not match array[%s][%s][%s].length=%s", arrayShape[3], i, j, k, len); } } } } }
Assert that the specified array is not ragged (i.e., is rectangular).<br> Can be used to check Object arrays with any number of dimensions (up to rank 4), or primitive arrays with rank 2 or higher<br> An IllegalStateException is thrown if the array is ragged @param array Array to check
ArrayUtil::assertNotRagged
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int arrayLength(Object current){ if (current instanceof Object[]) { return ((Object[]) current).length; } else if (current instanceof double[]) { return ((double[]) current).length; } else if (current instanceof float[]) { return ((float[]) current).length; } else if (current instanceof long[]) { return ((long[]) current).length; } else if (current instanceof int[]) { return ((int[]) current).length; } else if (current instanceof byte[]) { return ((byte[]) current).length; } else if (current instanceof char[]) { return ((char[]) current).length; } else if (current instanceof boolean[]) { return ((boolean[]) current).length; } else if (current instanceof short[]) { return ((short[]) current).length; } else throw new IllegalStateException("Unknown array type (or not an array): " + current.getClass()); //Should never happen }
Calculate the length of the object or primitive array. If @param current @return
ArrayUtil::arrayLength
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static int[] invertPermutation(int... input){ int[] target = new int[input.length]; for(int i = 0 ; i < input.length ; i++){ target[input[i]] = i; } return target; }
Compute the inverse permutation indices for a permutation operation<br> Example: if input is [2, 0, 1] then output is [1, 2, 0]<br> The idea is that x.permute(input).permute(invertPermutation(input)) == x @param input 1D indices for permutation @return 1D inverted permutation
ArrayUtil::invertPermutation
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static long[] invertPermutation(long... input){ long[] target = new long[input.length]; for(int i = 0 ; i < input.length ; i++){ target[(int) input[i]] = i; } return target; }
@see #invertPermutation(int...) @param input 1D indices for permutation @return 1D inverted permutation
ArrayUtil::invertPermutation
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public static boolean isEmptyShape(long[] shape){ for( long l : shape){ if(l == 0) return true; } return false; }
Is this shape an empty shape? Shape is considered to be an empty shape if it contains any zeros. Note: a length 0 shape is NOT considered empty (it's rank 0 scalar) @param shape Shape to check @return True if shape contains zeros
ArrayUtil::isEmptyShape
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/ArrayUtil.java
Apache-2.0
public Factorial() { if (a.isEmpty()) { a.add(BigInteger.ONE); a.add(BigInteger.ONE); } }
ctor(). Initialize the vector of the factorials with 0!=1 and 1!=1.
Factorial::Factorial
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/Factorial.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/Factorial.java
Apache-2.0
public BigInteger at(int n) { while (a.size() <= n) { final int lastn = a.size() - 1; final BigInteger nextn = BigInteger.valueOf(lastn + 1); a.add(a.get(lastn).multiply(nextn)); } return a.get(n); }
Compute the factorial of the non-negative integer. @param n the argument to the factorial, non-negative. @return the factorial of n.
Factorial::at
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/Factorial.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/Factorial.java
Apache-2.0
public static boolean nameExistsInPath(String name) { String path = System.getenv(PATH_ENV_VARIABLE); String[] dirs = path.split(File.pathSeparator); for (String dir : dirs) { File dirFile = new File(dir); if (!dirFile.exists()) continue; if (dirFile.isFile() && dirFile.getName().equals(name)) return true; else { Iterator<File> files = FileUtils.iterateFiles(dirFile, null, false); while (files.hasNext()) { File curr = files.next(); if (curr.getName().equals(name)) return true; } } } return false; }
Check if a file exists in the path @param name the name of the file @return true if the name exists false otherwise
Paths::nameExistsInPath
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/Paths.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/Paths.java
Apache-2.0
protected void set(final int n, final Rational value) { final int nindx = n / 2; if (nindx < a.size()) { a.set(nindx, value); } else { while (a.size() < nindx) { a.add(Rational.ZERO); } a.add(value); } }
Set a coefficient in the internal table. @param n the zero-based index of the coefficient. n=0 for the constant term. @param value the new value of the coefficient.
Bernoulli::set
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/Bernoulli.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/Bernoulli.java
Apache-2.0
public Rational at(int n) { if (n == 1) { return (new Rational(-1, 2)); } else if (n % 2 != 0) { return Rational.ZERO; } else { final int nindx = n / 2; if (a.size() <= nindx) { for (int i = 2 * a.size(); i <= n; i += 2) { set(i, doubleSum(i)); } } return a.get(nindx); } }
The Bernoulli number at the index provided. @param n the index, non-negative. @return the B_0=1 for n=0, B_1=-1/2 for n=1, B_2=1/6 for n=2 etc
Bernoulli::at
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/Bernoulli.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/Bernoulli.java
Apache-2.0
public static StackTraceElement[] trimStackTrace(StackTraceElement[] stackTrace, List<StackTraceQuery> ignorePackages, List<StackTraceQuery> skipFullPatterns) { if(skipFullPatterns != null && !skipFullPatterns.isEmpty()) { if(StackTraceQuery.stackTraceFillsAnyCriteria(skipFullPatterns,stackTrace)) { return new StackTraceElement[0]; } } if(ignorePackages != null && !ignorePackages.isEmpty()) { StackTraceElement[] reverse = reverseCopy(stackTrace); List<StackTraceElement> ret = new ArrayList<>(); //start backwards to find the index of the first non ignored package. //we loop backwards to avoid typical unrelated boilerplate //like unit tests or ide stack traces int startingIndex = -1; for(int i = 0; i < reverse.length; i++) { if(!StackTraceQuery.stackTraceElementMatchesCriteria(ignorePackages,reverse[i],i)) { startingIndex = i; break; } } //if we didn't find a match, just start at the beginning if(startingIndex < 0) { startingIndex = 0; } //loop backwards to present original stack trace for(int i = reverse.length - 1; i >= startingIndex; i--) { ret.add(reverse[i]); } return ret.toArray(new StackTraceElement[0]); } else { List<StackTraceElement> ret = new ArrayList<>(); for (StackTraceElement stackTraceElement : stackTrace) { //note we break because it doesn't make sense to continue rendering when we've hit a package we should be ignoring. //this allows a user to specify 1 namespace and ignore anything after it. ret.add(stackTraceElement); } return ret.toArray(new StackTraceElement[0]); } }
Returns a potentially reduced stacktrace based on the namepsaces specified in the ignore packages and skipFullPatterns lists @param stackTrace the stack trace to filter @param ignorePackages the packages to ignore @param skipFullPatterns the full patterns to skip @return the filtered stack trace
StackTraceUtils::trimStackTrace
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
Apache-2.0
public static String renderStackTrace(StackTraceElement[] stackTrace, List<StackTraceQuery> ignorePackages, List<StackTraceQuery> skipFullPatterns) { StringBuilder stringBuilder = new StringBuilder(); StackTraceElement[] stackTrace1 = trimStackTrace(stackTrace,ignorePackages,skipFullPatterns); for (StackTraceElement stackTraceElement : stackTrace1) { stringBuilder.append(stackTraceElement.toString() + "\n"); } return stringBuilder.toString(); }
Get the current stack trace as a string. @return
StackTraceUtils::renderStackTrace
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
Apache-2.0
public static Set<StackTraceElement> parentOfInvocation(StackTraceElement[] elements, StackTraceElement pointOfOrigin, StackTraceElement pointOfInvocation) { if(elements == null || elements.length < 1) return null; int pointOfInvocationIndex = -1; for(int i = 0; i < elements.length; i++) { if(elements[i].equals(pointOfInvocation)) { pointOfInvocationIndex = i; break; } } if(pointOfInvocationIndex <= 0) { return new HashSet<>(Arrays.asList(elements)); } if(pointOfInvocationIndex < 0) throw new IllegalArgumentException("Invalid stack trace. Point of invocation not found!"); int pointOfOriginIndex = -1; Set<StackTraceElement> ret = new HashSet<>(); //loop backwards to find the first non nd4j class for(int i = pointOfInvocationIndex + 1; i < elements.length; i++) { StackTraceElement element = elements[i]; if(!StackTraceQuery.stackTraceElementMatchesCriteria(invalidPointOfInvocationClasses,elements[i],i) && !StackTraceQuery.stackTraceElementMatchesCriteria(invalidPointOfInvocationPatterns,elements[i],i) && !element.getClassName().equals(pointOfOrigin.getClassName()) && !element.getClassName().equals(pointOfInvocation.getClassName())) { pointOfOriginIndex = i; break; } } if(pointOfOriginIndex < 0) { return new HashSet<>(Arrays.asList(elements)); } //this is what we'll call the "interesting parents", we need to index //by multiple parents in order to capture the different parts of the stack tree that could be applicable. for(int i = pointOfOriginIndex; i < elements.length; i++) { StackTraceElement element = elements[i]; if(StackTraceQuery.stackTraceElementMatchesCriteria(invalidPointOfInvocationClasses,elements[i],i) || StackTraceQuery.stackTraceElementMatchesCriteria(invalidPointOfInvocationPatterns,elements[i],i) || element.getClassName().equals(pointOfOrigin.getClassName()) || element.getClassName().equals(pointOfInvocation.getClassName())) { break; } ret.add(elements[i]); } return ret; }
Parent of invocation is an element of the stack trace with a different class altogether. The goal is to be able to segment what is calling a method within the same class. @param elements the elements to get the parent of invocation for @return
StackTraceUtils::parentOfInvocation
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
Apache-2.0
public static StackTraceElement[] callsFromClass(StackTraceElement[] elements, String className) { if(elements == null || elements.length < 1) return null; List<StackTraceElement> ret = new ArrayList<>(); for(int i = 0; i < elements.length; i++) { if(elements[i].getClassName().equals(className)) { ret.add(elements[i]); } } return ret.toArray(new StackTraceElement[0]); }
Calls from class is a method that returns all stack trace elements that are from a given class. @param elements the elements to get the calls from class for @param className the class name to get the calls from @return the stack trace elements from the given class
StackTraceUtils::callsFromClass
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
Apache-2.0
public static StackTraceElement pointOfOrigin(StackTraceElement[] elements) { if(elements == null || elements.length < 1) return null; int pointOfOriginIndex = 0; //loop backwards to find the first non nd4j class for(int i = elements.length - 1; i >= 0; i--) { if(!StackTraceQuery.stackTraceElementMatchesCriteria(invalidPointOfInvocationClasses,elements[i],i) && !StackTraceQuery.stackTraceElementMatchesCriteria(invalidPointOfInvocationPatterns,elements[i],i)) { pointOfOriginIndex = i; break; } } return elements[pointOfOriginIndex]; }
Point of origin is the first non nd4j class in the stack trace. @param elements the elements to get the point of origin for @return
StackTraceUtils::pointOfOrigin
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
Apache-2.0
public static StackTraceElement pointOfInvocation(StackTraceElement[] elements) { if(elements == null || elements.length < 1) return null; int pointOfInvocationIndex = 0; for(int i = 0; i < elements.length; i++) { if(!StackTraceQuery.stackTraceElementMatchesCriteria(invalidPointOfInvocationClasses,elements[i],i) && !StackTraceQuery.stackTraceElementMatchesCriteria(invalidPointOfInvocationPatterns,elements[i],i)) { pointOfInvocationIndex = i; break; } } return elements[pointOfInvocationIndex]; }
@param elements @return
StackTraceUtils::pointOfInvocation
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/StackTraceUtils.java
Apache-2.0
public static int countLines(InputStream is) throws IOException { try { byte[] c = new byte[1024]; int count = 0; int readChars = 0; boolean empty = true; while ((readChars = is.read(c)) != -1) { empty = false; for (int i = 0; i < readChars; ++i) { if (c[i] == '\n') { ++count; } } } return (count == 0 && !empty) ? 1 : count; } finally { is.close(); } }
Count number of lines in a file @param is @return @throws IOException
InputStreamUtil::countLines
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/InputStreamUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/InputStreamUtil.java
Apache-2.0
public static int countLines(String filename) throws IOException { FileInputStream fis = new FileInputStream(filename); try { return countLines(new BufferedInputStream(fis)); } finally { fis.close(); } }
Count number of lines in a file @param filename @return @throws IOException
InputStreamUtil::countLines
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/util/InputStreamUtil.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/util/InputStreamUtil.java
Apache-2.0
public static ObjectMapper getJsonMapper() { return objectMapper; }
Get a single object mapper for use with reading and writing json @return
ObjectMapperHolder::getJsonMapper
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/holder/ObjectMapperHolder.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/holder/ObjectMapperHolder.java
Apache-2.0
public static <K,V> Map<K,Pair<List<V>,List<V>>> cogroup(List<Pair<K,V>> left,List<Pair<K,V>> right) { Map<K,Pair<List<V>,List<V>>> ret = new HashMap<>(); //group by key first to consolidate values Map<K,List<V>> leftMap = groupByKey(left); Map<K,List<V>> rightMap = groupByKey(right); /** * Iterate over each key in the list * adding values to the left items * as values are found in the list. */ for(Map.Entry<K,List<V>> entry : leftMap.entrySet()) { K key = entry.getKey(); if(!ret.containsKey(key)) { List<V> leftListPair = new ArrayList<>(); List<V> rightListPair = new ArrayList<>(); Pair<List<V>,List<V>> p = Pair.of(leftListPair,rightListPair); ret.put(key,p); } Pair<List<V>,List<V>> p = ret.get(key); p.getFirst().addAll(entry.getValue()); } /** * Iterate over each key in the list * adding values to the right items * as values are found in the list. */ for(Map.Entry<K,List<V>> entry : rightMap.entrySet()) { K key = entry.getKey(); if(!ret.containsKey(key)) { List<V> leftListPair = new ArrayList<>(); List<V> rightListPair = new ArrayList<>(); Pair<List<V>,List<V>> p = Pair.of(leftListPair,rightListPair); ret.put(key,p); } Pair<List<V>,List<V>> p = ret.get(key); p.getSecond().addAll(entry.getValue()); } return ret; }
For each key in left and right, cogroup returns the list of values as a pair for each value present in left as well as right. @param left the left list of pairs to join @param right the right list of pairs to join @param <K> the key type @param <V> the value type @return a map of the list of values by key for each value in the left as well as the right with each element in the pair representing the values in left and right respectively.
FunctionalUtils::cogroup
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/function/FunctionalUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/function/FunctionalUtils.java
Apache-2.0
public static <K,V> Map<K,List<V>> groupByKey(List<Pair<K,V>> listInput) { Map<K,List<V>> ret = new HashMap<>(); for(Pair<K,V> pair : listInput) { List<V> currList = ret.get(pair.getFirst()); if(currList == null) { currList = new ArrayList<>(); ret.put(pair.getFirst(),currList); } currList.add(pair.getSecond()); } return ret; }
Group the input pairs by the key of each pair. @param listInput the list of pairs to group @param <K> the key type @param <V> the value type @return a map representing a grouping of the keys by the given input key type and list of values in the grouping.
FunctionalUtils::groupByKey
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/function/FunctionalUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/function/FunctionalUtils.java
Apache-2.0
public static <K,V> List<Pair<K,V>> mapToPair(Map<K,V> map) { List<Pair<K,V>> ret = new ArrayList<>(map.size()); for(Map.Entry<K,V> entry : map.entrySet()) { ret.add(Pair.of(entry.getKey(),entry.getValue())); } return ret; }
Convert a map with a set of entries of type K for key and V for value in to a list of {@link Pair} @param map the map to collapse @param <K> the key type @param <V> the value type @return the collapsed map as a {@link List}
FunctionalUtils::mapToPair
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/function/FunctionalUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/function/FunctionalUtils.java
Apache-2.0
public static void checkArgument(boolean b) { if (!b) { throw new IllegalArgumentException(); } }
Check the specified boolean argument. Throws an IllegalArgumentException if {@code b} is false @param b Argument to check
Preconditions::checkArgument
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static void checkArgument(boolean b, String message) { if (!b) { throwEx(message); } }
Check the specified boolean argument. Throws an IllegalArgumentException with the specified message if {@code b} is false @param b Argument to check @param message Message for exception. May be null
Preconditions::checkArgument
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static void checkArgument(boolean b, String msg, int arg1) { if (!b) { throwEx(msg, arg1); } }
See {@link #checkArgument(boolean, String, Object...)}
Preconditions::checkArgument
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static void checkArgument(boolean b, String message, Object... args) { if (!b) { throwEx(message, args); } }
Check the specified boolean argument. Throws an IllegalArgumentException with the specified message if {@code b} is false. Note that the message may specify argument locations using "%s" - for example, {@code checkArgument(false, "Got %s values, expected %s", 3, "more"} would throw an IllegalArgumentException with the message "Got 3 values, expected more" @param b Argument to check @param message Message for exception. May be null. @param args Arguments to place in message
Preconditions::checkArgument
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static void checkState(boolean b) { if (!b) { throw new IllegalStateException(); } }
Check the specified boolean argument. Throws an IllegalStateException if {@code b} is false @param b State to check
Preconditions::checkState
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static void checkState(boolean b, String message) { if (!b) { throwStateEx(message); } }
Check the specified boolean argument. Throws an IllegalStateException with the specified message if {@code b} is false @param b State to check @param message Message for exception. May be null
Preconditions::checkState
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static void checkState(boolean b, String msg, int arg1) { if (!b) { throwStateEx(msg, arg1); } }
See {@link #checkState(boolean, String, Object...)}
Preconditions::checkState
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static void checkState(boolean b, String message, Object... args) { if (!b) { throwStateEx(message, args); } }
Check the specified boolean argument. Throws an IllegalStateException with the specified message if {@code b} is false. Note that the message may specify argument locations using "%s" - for example, {@code checkArgument(false, "Got %s values, expected %s", 3, "more"} would throw an IllegalStateException with the message "Got 3 values, expected more" @param b Argument to check @param message Message for exception. May be null. @param args Arguments to place in message
Preconditions::checkState
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static void checkNotNull(Object o) { if (o == null) { throw new NullPointerException(); } }
Check the specified boolean argument. Throws an NullPointerException if {@code o} is false @param o Object to check
Preconditions::checkNotNull
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static void checkNotNull(Object o, String message) { if (o == null) { throwNullPointerEx(message); } }
Check the specified boolean argument. Throws an NullPointerException with the specified message if {@code o} is false @param o Object to check @param message Message for exception. May be null
Preconditions::checkNotNull
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static void checkNotNull(Object o, String msg, int arg1) { if (o == null) { throwNullPointerEx(msg, arg1); } }
See {@link #checkNotNull(Object, String, Object...)}
Preconditions::checkNotNull
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static void checkNotNull(Object o, String message, Object... args) { if (o == null) { throwStateEx(message, args); } }
Check the specified boolean argument. Throws an IllegalStateException with the specified message if {@code o} is false. Note that the message may specify argument locations using "%s" - for example, {@code checkArgument(false, "Got %s values, expected %s", 3, "more"} would throw an IllegalStateException with the message "Got 3 values, expected more" @param o Object to check @param message Message for exception. May be null. @param args Arguments to place in message
Preconditions::checkNotNull
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/base/Preconditions.java
Apache-2.0
public static FileBatch readFromZip(File file) throws IOException { try (FileInputStream fis = new FileInputStream(file)) { return readFromZip(fis); } }
Read a FileBatch from the specified file. This method assumes the FileBatch was previously saved to zip format using {@link #writeAsZip(File)} or {@link #writeAsZip(OutputStream)} @param file File to read from @return The loaded FileBatch @throws IOException If an error occurs during reading
FileBatch::readFromZip
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/FileBatch.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/FileBatch.java
Apache-2.0
public static FileBatch readFromZip(InputStream is) throws IOException { String originalUris = null; Map<Integer, byte[]> bytesMap = new HashMap<>(); try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is))) { ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { String name = ze.getName(); byte[] bytes = IOUtils.toByteArray(zis); if (name.equals(ORIGINAL_PATHS_FILENAME)) { originalUris = new String(bytes, 0, bytes.length, StandardCharsets.UTF_8); } else { int idxSplit = name.indexOf("_"); int idxSplit2 = name.indexOf("."); int fileIdx = Integer.parseInt(name.substring(idxSplit + 1, idxSplit2)); bytesMap.put(fileIdx, bytes); } } } List<byte[]> list = new ArrayList<>(bytesMap.size()); for (int i = 0; i < bytesMap.size(); i++) { list.add(bytesMap.get(i)); } List<String> origPaths = Arrays.asList(originalUris.split("\n")); return new FileBatch(list, origPaths); }
Read a FileBatch from the specified input stream. This method assumes the FileBatch was previously saved to zip format using {@link #writeAsZip(File)} or {@link #writeAsZip(OutputStream)} @param is Input stream to read from @return The loaded FileBatch @throws IOException If an error occurs during reading
FileBatch::readFromZip
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/FileBatch.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/FileBatch.java
Apache-2.0
public static FileBatch forFiles(File... files) throws IOException { return forFiles(Arrays.asList(files)); }
Create a FileBatch from the specified files @param files Files to create the FileBatch from @return The created FileBatch @throws IOException If an error occurs during reading of the file content
FileBatch::forFiles
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/FileBatch.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/FileBatch.java
Apache-2.0
public void writeAsZip(File f) throws IOException { writeAsZip(new FileOutputStream(f)); }
Write the FileBatch to the specified File, in zip file format @param f File to write to @throws IOException If an error occurs during writing
FileBatch::writeAsZip
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/FileBatch.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/FileBatch.java
Apache-2.0
public void writeAsZip(OutputStream os) throws IOException { try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(os))) { //Write original paths as a text file: ZipEntry ze = new ZipEntry(ORIGINAL_PATHS_FILENAME); String originalUrisJoined = StringUtils.join(originalUris, "\n"); //Java String.join is Java 8 zos.putNextEntry(ze); zos.write(originalUrisJoined.getBytes(StandardCharsets.UTF_8)); for (int i = 0; i < fileBytes.size(); i++) { String ext = FilenameUtils.getExtension(originalUris.get(i)); if (ext == null || ext.isEmpty()) ext = "bin"; String name = "file_" + i + "." + ext; ze = new ZipEntry(name); zos.putNextEntry(ze); zos.write(fileBytes.get(i)); } } }
@param os Write the FileBatch to the specified output stream, in zip file format @throws IOException If an error occurs during writing
FileBatch::writeAsZip
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/FileBatch.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/FileBatch.java
Apache-2.0
public CompactHeapStringList(int reallocationBlockSizeBytes, int intReallocationBlockSizeBytes) { this.reallocationBlockSizeBytes = reallocationBlockSizeBytes; this.reallocationIntegerBlockSizeBytes = intReallocationBlockSizeBytes; this.data = new char[this.reallocationBlockSizeBytes / 2]; this.offsetAndLength = new int[this.reallocationIntegerBlockSizeBytes / 4]; }
@param reallocationBlockSizeBytes Number of bytes by which to increase the char[], when allocating a new storage array @param intReallocationBlockSizeBytes Number of bytes by which to increase the int[], when allocating a new storage array
CompactHeapStringList::CompactHeapStringList
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/collection/CompactHeapStringList.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/collection/CompactHeapStringList.java
Apache-2.0
public static <K, T, V> MultiDimensionalMap<K, T, V> newThreadSafeTreeBackedMap() { return new MultiDimensionalMap<>(new ConcurrentSkipListMap<Pair<K, T>, V>()); }
Thread safe sorted map implementation @param <K> @param <T> @param <V> @return
MultiDimensionalMap::newThreadSafeTreeBackedMap
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/collection/MultiDimensionalMap.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/collection/MultiDimensionalMap.java
Apache-2.0
public static <K, T, V> MultiDimensionalMap<K, T, V> newThreadSafeHashBackedMap() { return new MultiDimensionalMap<>(new ConcurrentHashMap<Pair<K, T>, V>()); }
Thread safe hash map implementation @param <K> @param <T> @param <V> @return
MultiDimensionalMap::newThreadSafeHashBackedMap
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/collection/MultiDimensionalMap.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/collection/MultiDimensionalMap.java
Apache-2.0
public static <K, T, V> MultiDimensionalMap<K, T, V> newHashBackedMap() { return new MultiDimensionalMap<>(new HashMap<Pair<K, T>, V>()); }
Thread safe hash map impl @param <K> @param <T> @param <V> @return
MultiDimensionalMap::newHashBackedMap
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/collection/MultiDimensionalMap.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/collection/MultiDimensionalMap.java
Apache-2.0
public static <K, T, V> MultiDimensionalMap<K, T, V> newTreeBackedMap() { return new MultiDimensionalMap<>(new TreeMap<Pair<K, T>, V>()); }
Tree map implementation @param <K> @param <T> @param <V> @return
MultiDimensionalMap::newTreeBackedMap
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/collection/MultiDimensionalMap.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/collection/MultiDimensionalMap.java
Apache-2.0
public File getTempFileFromArchive() throws IOException { return getTempFileFromArchive(null); }
Get a temp file from the classpath.<br> This is for resources where a file is needed and the classpath resource is in a jar file. The file is copied to the default temporary directory, using {@link Files#createTempFile(String, String, FileAttribute[])}. Consequently, the extracted file will have a different filename to the extracted one. @return the temp file @throws IOException If an error occurs when files are being copied @see #getTempFileFromArchive(File)
ClassPathResource::getTempFileFromArchive
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/io/ClassPathResource.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/io/ClassPathResource.java
Apache-2.0
public File getTempFileFromArchive(File rootDirectory) throws IOException { InputStream is = getInputStream(); File tmpFile; if(rootDirectory != null){ //Maintain original file names, as it's going in a directory... tmpFile = new File(rootDirectory, FilenameUtils.getName(path)); } else { tmpFile = Files.createTempFile(FilenameUtils.getName(path), "tmp").toFile(); } tmpFile.deleteOnExit(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile)); IOUtils.copy(is, bos); bos.flush(); bos.close(); return tmpFile; }
Get a temp file from the classpath, and (optionally) place it in the specified directory<br> Note that:<br> - If the directory is not specified, the file is copied to the default temporary directory, using {@link Files#createTempFile(String, String, FileAttribute[])}. Consequently, the extracted file will have a different filename to the extracted one.<br> - If the directory *is* specified, the file is copied directly - and the original filename is maintained @param rootDirectory May be null. If non-null, copy to the specified directory @return the temp file @throws IOException If an error occurs when files are being copied @see #getTempFileFromArchive(File)
ClassPathResource::getTempFileFromArchive
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/io/ClassPathResource.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/io/ClassPathResource.java
Apache-2.0
public void copyDirectory(File destination) throws IOException { Preconditions.checkState(destination.exists() && destination.isDirectory(), "Destination directory must exist and be a directory: %s", destination); URL url = this.getUrl(); if (isJarURL(url)) { /* This is actually request for file, that's packed into jar. Probably the current one, but that doesn't matters. */ InputStream stream = null; ZipFile zipFile = null; try { GetStreamFromZip getStreamFromZip = new GetStreamFromZip(url, path).invoke(); ZipEntry entry = getStreamFromZip.getEntry(); stream = getStreamFromZip.getStream(); zipFile = getStreamFromZip.getZipFile(); Preconditions.checkState(entry.isDirectory(), "Source must be a directory: %s", entry.getName()); String pathNoSlash = this.path; if(pathNoSlash.endsWith("/") || pathNoSlash.endsWith("\\")){ pathNoSlash = pathNoSlash.substring(0, pathNoSlash.length()-1); } Enumeration<? extends ZipEntry> entries = zipFile.entries(); while(entries.hasMoreElements()){ ZipEntry e = entries.nextElement(); String name = e.getName(); if(name.startsWith(pathNoSlash) && name.length() > pathNoSlash.length() && (name.charAt(pathNoSlash.length()) == '/' || name.charAt(pathNoSlash.length()) == '\\')){ //second condition: to avoid "/dir/a/" and "/dir/abc/" both matching startsWith String relativePath = name.substring(this.path.length()); File extractTo = new File(destination, relativePath); if(e.isDirectory()){ extractTo.mkdirs(); } else { try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(extractTo))){ InputStream is = getInputStream(name, clazz, classLoader); IOUtils.copy(is, bos); } } } } stream.close(); zipFile.close(); } catch (Exception e) { throw new RuntimeException(e); } finally { if(stream != null) IOUtils.closeQuietly(stream); if(zipFile != null) IOUtils.closeQuietly(zipFile); } } else { File source; try{ source = new File(url.toURI()); } catch (URISyntaxException e) { throw new IOException("Error converting URL to a URI - path may be invalid? Path=" + url); } Preconditions.checkState(source.isDirectory(), "Source must be a directory: %s", source); Preconditions.checkState(destination.exists() && destination.isDirectory(), "Destination must be a directory and must exist: %s", destination); FileUtils.copyDirectory(source, destination); } }
Extract the directory recursively to the specified location. Current ClassPathResource must point to a directory.<br> For example, if classpathresource points to "some/dir/", then the contents - not including the parent directory "dir" - will be extracted or copied to the specified destination.<br> @param destination Destination directory. Must exist
ClassPathResource::copyDirectory
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/io/ClassPathResource.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/io/ClassPathResource.java
Apache-2.0
private URL extractActualUrl(URL jarUrl) throws MalformedURLException { String urlFile = jarUrl.getFile(); int separatorIndex = urlFile.indexOf("!/"); if (separatorIndex != -1) { String jarFile = urlFile.substring(0, separatorIndex); try { return new URL(jarFile); } catch (MalformedURLException var5) { if (!jarFile.startsWith("/")) { jarFile = "/" + jarFile; } return new URL("file:" + jarFile); } } else { return jarUrl; } }
Extracts parent Jar URL from original ClassPath entry URL. @param jarUrl Original URL of the resource @return URL of the Jar file, containing requested resource @throws MalformedURLException
GetStreamFromZip::extractActualUrl
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/common/io/ClassPathResource.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/common/io/ClassPathResource.java
Apache-2.0
public static List<StackTraceQuery> ofClassPatterns(boolean regex, String... classes) { List<StackTraceQuery> ret = new ArrayList<>(); for (String s : classes) { if(regex) { cachedPatterns.put(s, Pattern.compile(s)); } ret.add(StackTraceQuery.builder() .regexMatch(regex) .className(s).build()); } return ret; }
Create a list of queries based on the fully qualified class name patterns. @param regex @param classes the classes to create queries for @return the list of queries
StackTraceQuery::ofClassPatterns
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQuery.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQuery.java
Apache-2.0
public static boolean stackTraceFillsAnyCriteria(List<StackTraceQuery> queries, StackTraceElement[] stackTrace) { if(stackTrace == null) return false; if(queries == null) return false; for (int j = 0; j < stackTrace.length; j++) { StackTraceElement line = stackTrace[j]; //parse line like this: org.deeplearning4j.nn.layers.recurrent.BidirectionalLayer.backpropGradient(BidirectionalLayer.java:153) if (stackTraceElementMatchesCriteria(queries, line, j)) return true; } return false; }
Returns true if the stack trace element matches the given criteria @param queries the queries to match on @param stackTrace the stack trace to match on (note that the stack trace is in reverse order) @return true if the stack trace element matches the given criteria
StackTraceQuery::stackTraceFillsAnyCriteria
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQuery.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQuery.java
Apache-2.0
public static boolean stackTraceElementMatchesCriteria(List<StackTraceQuery> queries, StackTraceElement line, int j) { if(queries == null || queries.isEmpty()) { return false; } for (StackTraceQuery query : queries) { //allow -1 on line number to mean any line number also allow methods that are unspecified to mean any method //also check for the line count occurrence -1 means any boolean classNameMatch = isClassNameMatch(query.getClassName(), query, line.getClassName()); //null or empty method name means any method name, depending on whether an exact match is required //return we consider it a match boolean methodNameMatch = isClassNameMatch(query.getMethodName(), query, line.getMethodName()); //< 0 line means any line number boolean lineNumberMatch = query.getLineNumber() < 0 || query.getLineNumber() == line.getLineNumber(); //whether the user specifies if the match is within the stack trace depth. what this is for is //to filter stack trace matches to a certain depth. for example, if you want to match a stack trace //that occurs within a certain method, you can specify the depth of the stack trace to match on. boolean matchesStackTraceDepth = (query.getOccursWithinLineCount() <= j || query.getOccursWithinLineCount() < 0); boolean inLineRange = (query.getLineNumberBegin() <= line.getLineNumber() && query.getLineNumberEnd() >= line.getLineNumber()) || (query.getLineNumberBegin() < 0 && query.getLineNumberEnd() < 0); if (classNameMatch && methodNameMatch && lineNumberMatch && inLineRange && matchesStackTraceDepth) { return true; } } return false; }
Returns true if the stack trace element matches the given criteria @param queries the queries to match on @param line the stack trace element to match on @param j the index of the line @return true if the stack trace element matches the given criteria
StackTraceQuery::stackTraceElementMatchesCriteria
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQuery.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQuery.java
Apache-2.0
public boolean filter(StackTraceElement stackTraceElement) { if (exclude != null && !exclude.isEmpty()) { for (StackTraceQuery query : exclude) { if (query.filter(stackTraceElement)) { return true; } } } if (include != null && !include.isEmpty()) { for (StackTraceQuery query : include) { if (query.filter(stackTraceElement)) { return false; } } return false; } return false; }
Returns true if the stack trace element should be filtered @param stackTraceElement the stack trace element to filter @return true if the stack trace element should be filtered, false otherwise
StackTraceQueryFilters::filter
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQueryFilters.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQueryFilters.java
Apache-2.0
public static boolean shouldFilter(StackTraceElement stackTraceElement[], StackTraceQueryFilters stackTraceQueryFilters) { if(stackTraceQueryFilters == null || stackTraceElement == null) { return false; } for(StackTraceElement stackTraceElement1 : stackTraceElement) { if(stackTraceElement1 == null) continue; if (stackTraceQueryFilters.filter(stackTraceElement1)) { return true; } } return false; }
Returns true if the stack trace element should be filtered @param stackTraceElement the stack trace element to filter @param stackTraceQueryFilters the filters to apply @return true if the stack trace element should be filtered, false otherwise
StackTraceQueryFilters::shouldFilter
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQueryFilters.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQueryFilters.java
Apache-2.0
public static boolean shouldFilter(StackTraceElement stackTraceElement, StackTraceQueryFilters stackTraceQueryFilters) { if(stackTraceQueryFilters == null || stackTraceElement == null) return false; return stackTraceQueryFilters.filter(stackTraceElement); }
Returns true if the stack trace element should be filtered @param stackTraceElement the stack trace element to filter @param stackTraceQueryFilters the filters to apply @return
StackTraceQueryFilters::shouldFilter
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQueryFilters.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceQueryFilters.java
Apache-2.0
public static StackTraceElement lookup(StackTraceLookupKey key) { if(!cache.containsKey(key)) { storeStackTrace(Thread.currentThread().getStackTrace()); } return cache.get(key); }
Lookup a stack trace element by key. Note you can also directly use {@link #lookup(String, String, int)} This method is mainly for use cases where you have to deal with multiple stack traces and it could be verbose. Note that when looking up stack traces sometimes user space code can be missing. If a cache entry is missing, we'll attempt to cache the current thread's stack trace elements. Since user input is not guaranteed to be valid, we don't just dynamically create stack trace entries. If your stack trace is missing, ensure you call {@link #storeStackTrace(StackTraceElement[])} on your calling thread. Usually this should be a transparent process included in certain constructors related to the Environment's NDArray logging being set to true. @param key the key to lookup
StackTraceElementCache::lookup
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
Apache-2.0
public static Map<StackTraceLookupKey,StackTraceElement> getCache() { return cache; }
Get the cache @return the cache
StackTraceElementCache::getCache
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
Apache-2.0
public static void storeStackTrace(StackTraceElement[] stackTrace) { if(stackTrace == null) { return; } for (StackTraceElement stackTraceElement : stackTrace) { if(stackTrace != null) storeStackTraceElement(stackTraceElement); } }
Store a stack trace in the cache @param stackTrace the stack trace to store
StackTraceElementCache::storeStackTrace
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
Apache-2.0
public static void storeStackTraceElement(StackTraceElement stackTraceElement) { if(stackTraceElement == null) { return; } StackTraceLookupKey key = StackTraceLookupKey.builder() .className(stackTraceElement.getClassName()) .methodName(stackTraceElement.getMethodName()) .lineNumber(stackTraceElement.getLineNumber()).build(); cache.put(key,stackTraceElement); }
Store a stack trace element in the cache @param stackTraceElement the stack trace element to store
StackTraceElementCache::storeStackTraceElement
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
Apache-2.0
public static boolean containsKey(String className,String methodName,int lineNumber) { StackTraceLookupKey key = StackTraceLookupKey.builder().className(className).methodName(methodName).lineNumber(lineNumber).build(); return cache.containsKey(key); }
Check if the cache contains a stack trace element @param className the class name to check @param methodName the method name to check @param lineNumber the line number to check @return
StackTraceElementCache::containsKey
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
Apache-2.0
public static StackTraceElement lookup(String className,String methodName,int lineNumber) { StackTraceLookupKey key = StackTraceLookupKey.builder().className(className).methodName(methodName).lineNumber(lineNumber).build(); return cache.get(key); }
Lookup a stack trace element by class name, method name, and line number @param className the class name to check @param methodName the method name to check @param lineNumber the line number to check @return the stack trace element if it exists, or null if it does not exist
StackTraceElementCache::lookup
java
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/profiler/data/stacktrace/StackTraceElementCache.java
Apache-2.0
public static INDArray fromTensor(Tensor tensor) { byte b = tensor.typeType(); int[] shape = new int[tensor.shapeLength()]; int[] stride = new int[tensor.stridesLength()]; for(int i = 0; i < shape.length; i++) { shape[i] = (int) tensor.shape(i).size(); stride[i] = (int) tensor.strides(i); } int length = ArrayUtil.prod(shape); Buffer buffer = tensor.data(); if(buffer == null) { throw new ND4JIllegalStateException("Buffer was not serialized properly."); } //deduce element size int elementSize = (int) buffer.length() / length; //nd4j strides aren't based on element size for(int i = 0; i < stride.length; i++) { stride[i] /= elementSize; } DataType type = typeFromTensorType(b,elementSize); DataBuffer dataBuffer = DataBufferStruct.createFromByteBuffer(tensor.getByteBuffer(),(int) tensor.data().offset(),type,length); INDArray arr = Nd4j.create(dataBuffer,shape); arr.setShapeAndStride(shape,stride); return arr; }
Convert a {@link Tensor} to an {@link INDArray} @param tensor the input tensor @return the equivalent {@link INDArray}
ArrowSerde::fromTensor
java
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
Apache-2.0
public static Tensor toTensor(INDArray arr) { FlatBufferBuilder bufferBuilder = new FlatBufferBuilder(1024); long[] strides = getArrowStrides(arr); int shapeOffset = createDims(bufferBuilder,arr); int stridesOffset = Tensor.createStridesVector(bufferBuilder,strides); Tensor.startTensor(bufferBuilder); Tensor.addShape(bufferBuilder,shapeOffset); Tensor.addStrides(bufferBuilder,stridesOffset); int dataOffset = addDataForArr(bufferBuilder,arr); Tensor.addData(bufferBuilder,dataOffset); Tensor.addType(bufferBuilder,bufferBuilder.offset()); addTypeTypeRelativeToNDArray(bufferBuilder,arr); int endTensor = Tensor.endTensor(bufferBuilder); Tensor.finishTensorBuffer(bufferBuilder,endTensor); return Tensor.getRootAsTensor(bufferBuilder.dataBuffer()); }
Convert an {@link INDArray} to an arrow {@link Tensor} @param arr the array to convert @return the equivalent {@link Tensor}
ArrowSerde::toTensor
java
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
Apache-2.0
public static int addDataForArr(FlatBufferBuilder bufferBuilder, INDArray arr) { DataBuffer toAdd = arr.isView() ? arr.dup().data() : arr.data(); int offset = DataBufferStruct.createDataBufferStruct(bufferBuilder,toAdd); return Buffer.createBuffer(bufferBuilder,offset,toAdd.length() * toAdd.getElementSize()); }
Create a {@link Buffer} representing the location metadata of the actual data contents for the ndarrays' {@link DataBuffer} @param bufferBuilder the buffer builder in use @param arr the array to add the underlying data for @return the offset added
ArrowSerde::addDataForArr
java
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
Apache-2.0
public static void addTypeTypeRelativeToNDArray(FlatBufferBuilder bufferBuilder,INDArray arr) { switch(arr.data().dataType()) { case LONG: case INT: Tensor.addTypeType(bufferBuilder,Type.Int); break; case FLOAT: Tensor.addTypeType(bufferBuilder,Type.FloatingPoint); break; case DOUBLE: Tensor.addTypeType(bufferBuilder,Type.Decimal); break; } }
Convert the given {@link INDArray} data type to the proper data type for the tensor. @param bufferBuilder the buffer builder in use @param arr the array to conver tthe data type for
ArrowSerde::addTypeTypeRelativeToNDArray
java
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
Apache-2.0
public static int createDims(FlatBufferBuilder bufferBuilder,INDArray arr) { int[] tensorDimOffsets = new int[arr.rank()]; int[] nameOffset = new int[arr.rank()]; for(int i = 0; i < tensorDimOffsets.length; i++) { nameOffset[i] = bufferBuilder.createString(""); tensorDimOffsets[i] = TensorDim.createTensorDim(bufferBuilder,arr.size(i),nameOffset[i]); } return Tensor.createShapeVector(bufferBuilder,tensorDimOffsets); }
Create the dimensions for the flatbuffer builder @param bufferBuilder the buffer builder to use @param arr the input array @return
ArrowSerde::createDims
java
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
Apache-2.0
public static long[] getArrowStrides(INDArray arr) { long[] ret = new long[arr.rank()]; for(int i = 0; i < arr.rank(); i++) { ret[i] = arr.stride(i) * arr.data().getElementSize(); } return ret; }
Get the strides of this {@link INDArray} multiplieed by the element size. This is the {@link Tensor} and numpy format @param arr the array to convert @return
ArrowSerde::getArrowStrides
java
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
Apache-2.0
public static DataType typeFromTensorType(byte type, int elementSize) { if(type == Type.FloatingPoint) { return DataType.FLOAT; } else if(type == Type.Decimal) { return DataType.DOUBLE; } else if(type == Type.Int) { if(elementSize == 4) { return DataType.INT; } else if(elementSize == 8) { return DataType.LONG; } } else { throw new IllegalArgumentException("Only valid types are Type.Decimal and Type.Int"); } throw new IllegalArgumentException("Unable to determine data type"); }
Create thee databuffer type frm the given type, relative to the bytes in arrow in class: {@link Type} @param type the type to create the nd4j {@link DataType} from @param elementSize the element size @return the data buffer type
ArrowSerde::typeFromTensorType
java
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/ArrowSerde.java
Apache-2.0
public static DataBuffer createFromByteBuffer(ByteBuffer bb, int bb_pos, DataType type, int length) { bb.order(ByteOrder.LITTLE_ENDIAN); int elementSize = DataTypeUtil.lengthForDtype(type); DataBuffer ret = Nd4j.createBuffer(ByteBuffer.allocateDirect(length * elementSize),type,length); switch(type) { case DOUBLE: for(int i = 0; i < ret.length(); i++) { double doubleGet = bb.getDouble(bb.capacity() - bb_pos + (i * elementSize)); ret.put(i,doubleGet); } break; case FLOAT: for(int i = 0; i < ret.length(); i++) { float floatGet = bb.getFloat(bb.capacity() - bb_pos + (i * elementSize)); ret.put(i,floatGet); } break; case INT: for(int i = 0; i < ret.length(); i++) { int intGet = bb.getInt(bb.capacity() - bb_pos + (i * elementSize)); ret.put(i,intGet); } break; case LONG: for(int i = 0; i < ret.length(); i++) { long longGet = bb.getLong(bb.capacity() - bb_pos + (i * elementSize)); ret.put(i,longGet); } break; } return ret; }
Create a {@link DataBuffer} from a byte buffer. This is meant to be used with flatbuffers @param bb the flat buffers buffer @param bb_pos the position to start from @param type the type of buffer to create @param length the length of the buffer to create @return the created databuffer
DataBufferStruct::createFromByteBuffer
java
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/DataBufferStruct.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/DataBufferStruct.java
Apache-2.0
public static int createDataBufferStruct(FlatBufferBuilder bufferBuilder,DataBuffer create) { bufferBuilder.prep(create.getElementSize(), (int) create.length() * create.getElementSize()); for(int i = (int) (create.length() - 1); i >= 0; i--) { switch(create.dataType()) { case DOUBLE: double putDouble = create.getDouble(i); bufferBuilder.putDouble(putDouble); break; case FLOAT: float putFloat = create.getFloat(i); bufferBuilder.putFloat(putFloat); break; case INT: int putInt = create.getInt(i); bufferBuilder.putInt(putInt); break; case LONG: long putLong = create.getLong(i); bufferBuilder.putLong(putLong); } } return bufferBuilder.offset(); }
Create a data buffer struct within the passed in {@link FlatBufferBuilder} @param bufferBuilder the existing flatbuffer to use to serialize the {@link DataBuffer} @param create the databuffer to serialize @return an int representing the offset of the buffer
DataBufferStruct::createDataBufferStruct
java
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/DataBufferStruct.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-serde/nd4j-arrow/src/main/java/org/nd4j/arrow/DataBufferStruct.java
Apache-2.0
public static void recordGC(long currMemory) { MemoryCounter.currMemory.set(currMemory); }
Record the current amount of memory used when a system.gc runs. This {@link #currMemory} is meant to be sampled. @param currMemory the current amount of memory used
MemoryCounter::recordGC
java
deeplearning4j/deeplearning4j
nd4j/nd4j-profiler/src/main/java/org/nd4j/profiler/MemoryCounter.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-profiler/src/main/java/org/nd4j/profiler/MemoryCounter.java
Apache-2.0
public static DataType dataTypeForTvmType(DLDataType dataType) { if(dataType.code() == kDLInt && dataType.bits() == 8) { return INT8; } else if(dataType.code() == kDLInt && dataType.bits() == 16) { return INT16; } else if(dataType.code() == kDLInt && dataType.bits() == 32) { return INT32; } else if(dataType.code() == kDLInt && dataType.bits() == 64) { return INT64; } else if(dataType.code() == kDLUInt && dataType.bits() == 8) { return UINT8; } else if(dataType.code() == kDLUInt && dataType.bits() == 16) { return UINT16; } else if(dataType.code() == kDLUInt && dataType.bits() == 32) { return UINT32; } else if(dataType.code() == kDLUInt && dataType.bits() == 64) { return UINT64; } else if(dataType.code() == kDLFloat && dataType.bits() == 16) { return FLOAT16; } else if(dataType.code() == kDLFloat && dataType.bits() == 32) { return FLOAT; } else if(dataType.code() == kDLFloat && dataType.bits() == 64) { return DOUBLE; } else if(dataType.code() == kDLBfloat && dataType.bits() == 16) { return BFLOAT16; } else throw new IllegalArgumentException("Illegal data type code " + dataType.code() + " with bits " + dataType.bits()); }
Return a {@link DataType} for the tvm data type @param dataType the equivalent nd4j data type @return
TVMUtils::dataTypeForTvmType
java
deeplearning4j/deeplearning4j
nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/util/TVMUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/util/TVMUtils.java
Apache-2.0
public static DLDataType tvmTypeForDataType(DataType dataType) { if(dataType == INT8) { return new DLDataType().code((byte)kDLInt).bits((byte)8).lanes((short)1); } else if(dataType == INT16) { return new DLDataType().code((byte)kDLInt).bits((byte)16).lanes((short)1); } else if(dataType == INT32) { return new DLDataType().code((byte)kDLInt).bits((byte)32).lanes((short)1); } else if(dataType == INT64) { return new DLDataType().code((byte)kDLInt).bits((byte)64).lanes((short)1); } else if(dataType == UINT8) { return new DLDataType().code((byte)kDLUInt).bits((byte)8).lanes((short)1); } else if(dataType == UINT16) { return new DLDataType().code((byte)kDLUInt).bits((byte)16).lanes((short)1); } else if(dataType == UINT32) { return new DLDataType().code((byte)kDLUInt).bits((byte)32).lanes((short)1); } else if(dataType == UINT64) { return new DLDataType().code((byte)kDLUInt).bits((byte)64).lanes((short)1); } else if(dataType == FLOAT16) { return new DLDataType().code((byte)kDLFloat).bits((byte)16).lanes((short)1); } else if(dataType == FLOAT) { return new DLDataType().code((byte)kDLFloat).bits((byte)32).lanes((short)1); } else if(dataType == DOUBLE) { return new DLDataType().code((byte)kDLFloat).bits((byte)64).lanes((short)1); } else if(dataType == BFLOAT16) { return new DLDataType().code((byte)kDLBfloat).bits((byte)16).lanes((short)1); } else throw new IllegalArgumentException("Illegal data type " + dataType); }
Convert the tvm type for the given data type @param dataType @return
TVMUtils::tvmTypeForDataType
java
deeplearning4j/deeplearning4j
nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/util/TVMUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/util/TVMUtils.java
Apache-2.0
public static INDArray getArray(DLTensor value) { DataType dataType = dataTypeForTvmType(value.dtype()); LongPointer shape = value.shape(); LongPointer stride = value.strides(); long[] shapeConvert; if(shape != null) { shapeConvert = new long[value.ndim()]; shape.get(shapeConvert); } else { shapeConvert = new long[]{1}; } long[] strideConvert; if(stride != null) { strideConvert = new long[value.ndim()]; stride.get(strideConvert); } else { strideConvert = Nd4j.getStrides(shapeConvert); } long size = 1; for (int i = 0; i < shapeConvert.length; i++) { size *= shapeConvert[i]; } size *= value.dtype().bits() / 8; DataBuffer getBuffer = getDataBuffer(value,size); Preconditions.checkState(dataType.equals(getBuffer.dataType()),"Data type must be equivalent as specified by the tvm metadata."); return Nd4j.create(getBuffer,shapeConvert,strideConvert,0); }
Convert an tvm {@link DLTensor} in to an {@link INDArray} @param value the tensor to convert @return
TVMUtils::getArray
java
deeplearning4j/deeplearning4j
nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/util/TVMUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/util/TVMUtils.java
Apache-2.0
public static DLTensor getTensor(INDArray ndArray, DLDevice ctx) { DLTensor ret = new DLTensor(); ret.data(ndArray.data().pointer()); ret.device(ctx); ret.ndim(ndArray.rank()); ret.dtype(tvmTypeForDataType(ndArray.dataType())); ret.shape(new LongPointer(ndArray.shape())); ret.strides(new LongPointer(ndArray.stride())); ret.byte_offset(ndArray.offset()); return ret; }
Get an tvm tensor from an ndarray. @param ndArray the ndarray to get the value from @param ctx the {@link DLDevice} to use. @return
TVMUtils::getTensor
java
deeplearning4j/deeplearning4j
nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/util/TVMUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/util/TVMUtils.java
Apache-2.0
public static DataBuffer getDataBuffer(DLTensor tens, long size) { DataBuffer buffer = null; DataType type = dataTypeForTvmType(tens.dtype()); switch (type) { case BYTE: BytePointer pInt8 = new BytePointer(tens.data()).capacity(size); Indexer int8Indexer = ByteIndexer.create(pInt8); buffer = Nd4j.createBuffer(pInt8, type, size, int8Indexer); break; case SHORT: ShortPointer pInt16 = new ShortPointer(tens.data()).capacity(size); Indexer int16Indexer = ShortIndexer.create(pInt16); buffer = Nd4j.createBuffer(pInt16, type, size, int16Indexer); break; case INT: IntPointer pInt32 = new IntPointer(tens.data()).capacity(size); Indexer int32Indexer = IntIndexer.create(pInt32); buffer = Nd4j.createBuffer(pInt32, type, size, int32Indexer); break; case LONG: LongPointer pInt64 = new LongPointer(tens.data()).capacity(size); Indexer int64Indexer = LongIndexer.create(pInt64); buffer = Nd4j.createBuffer(pInt64, type, size, int64Indexer); break; case UBYTE: BytePointer pUint8 = new BytePointer(tens.data()).capacity(size); Indexer uint8Indexer = UByteIndexer.create(pUint8); buffer = Nd4j.createBuffer(pUint8, type, size, uint8Indexer); break; case UINT16: ShortPointer pUint16 = new ShortPointer(tens.data()).capacity(size); Indexer uint16Indexer = UShortIndexer.create(pUint16); buffer = Nd4j.createBuffer(pUint16, type, size, uint16Indexer); break; case UINT32: IntPointer pUint32 = new IntPointer(tens.data()).capacity(size); Indexer uint32Indexer = UIntIndexer.create(pUint32); buffer = Nd4j.createBuffer(pUint32, type, size, uint32Indexer); break; case UINT64: LongPointer pUint64 = new LongPointer(tens.data()).capacity(size); Indexer uint64Indexer = LongIndexer.create(pUint64); buffer = Nd4j.createBuffer(pUint64, type, size, uint64Indexer); break; case HALF: ShortPointer pFloat16 = new ShortPointer(tens.data()).capacity(size); Indexer float16Indexer = HalfIndexer.create(pFloat16); buffer = Nd4j.createBuffer(pFloat16, type, size, float16Indexer); break; case FLOAT: FloatPointer pFloat = new FloatPointer(tens.data()).capacity(size); FloatIndexer floatIndexer = FloatIndexer.create(pFloat); buffer = Nd4j.createBuffer(pFloat, type, size, floatIndexer); break; case DOUBLE: DoublePointer pDouble = new DoublePointer(tens.data()).capacity(size); Indexer doubleIndexer = DoubleIndexer.create(pDouble); buffer = Nd4j.createBuffer(pDouble, type, size, doubleIndexer); break; case BFLOAT16: ShortPointer pBfloat16 = new ShortPointer(tens.data()).capacity(size); Indexer bfloat16Indexer = Bfloat16Indexer.create(pBfloat16); buffer = Nd4j.createBuffer(pBfloat16, type, size, bfloat16Indexer); break; default: throw new RuntimeException("Unsupported data type encountered"); } return buffer; }
Get the data buffer from the given value @param tens the values to get @return the equivalent data buffer
TVMUtils::getDataBuffer
java
deeplearning4j/deeplearning4j
nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/util/TVMUtils.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/util/TVMUtils.java
Apache-2.0
public Map<String,INDArray> exec(Map<String,INDArray> input) { try (PointerScope scope = new PointerScope()) { getNumInputs.CallPacked(new TVMArgs(values, codes, 0), rv); long numInputNodes = rv.asLong(); getNumOutputs.CallPacked(new TVMArgs(values, codes, 0), rv); long numOutputNodes = rv.asLong(); // set the right input for (Map.Entry<String,INDArray> e : input.entrySet()) { String name = e.getKey(); INDArray arr = e.getValue(); DLTensor inputTensor = getTensor(arr, ctx); Preconditions.checkState(inputTensor != null,"Input must be a tensor."); setter.apply(0, new BytePointer(name)); setter.apply(1, inputTensor); setInput.CallPacked(new TVMArgs(values, codes, 2), rv); } // run the code run.CallPacked(new TVMArgs(values, codes, 0), rv); Map<String, INDArray> ret = new LinkedHashMap<>(); // get the output for (int i = 0; i < numOutputNodes; i++) { setter.apply(0, i); getOutput.CallPacked(new TVMArgs(values, codes, 1), rv); DLTensor outputTensor = rv.asDLTensor(); ret.put(Integer.toString(i), getArray(outputTensor)); } return ret; } }
Execute the {@link #run} function using the given input {@link Map} @param input the input map @return a map of the names of the ndarrays
TvmRunner::exec
java
deeplearning4j/deeplearning4j
nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/runner/TvmRunner.java
https://github.com/deeplearning4j/deeplearning4j/blob/master/nd4j/nd4j-tvm/src/main/java/org/nd4j/tvm/runner/TvmRunner.java
Apache-2.0