• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 package org.tensorflow;
17 
18 import java.lang.reflect.Array;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 
22 /** Static utility functions. */
23 public class TestUtil {
24 
25   public static final class AutoCloseableList<E extends AutoCloseable> extends ArrayList<E>
26       implements AutoCloseable {
AutoCloseableList(Collection<? extends E> c)27     public AutoCloseableList(Collection<? extends E> c) {
28       super(c);
29     }
30 
31     @Override
close()32     public void close() {
33       Exception toThrow = null;
34       for (AutoCloseable c : this) {
35         try {
36           c.close();
37         } catch (Exception e) {
38           toThrow = e;
39         }
40       }
41       if (toThrow != null) {
42         throw new RuntimeException(toThrow);
43       }
44     }
45   }
46 
constant(Graph g, String name, Object value)47   public static <T> Output<T> constant(Graph g, String name, Object value) {
48     try (Tensor<?> t = Tensor.create(value)) {
49       return g.opBuilder("Const", name)
50           .setAttr("dtype", t.dataType())
51           .setAttr("value", t)
52           .build()
53           .<T>output(0);
54     }
55   }
56 
placeholder(Graph g, String name, Class<T> type)57   public static <T> Output<T> placeholder(Graph g, String name, Class<T> type) {
58     return g.opBuilder("Placeholder", name)
59         .setAttr("dtype", DataType.fromClass(type))
60         .build()
61         .<T>output(0);
62   }
63 
addN(Graph g, Output<?>... inputs)64   public static <T> Output<T> addN(Graph g, Output<?>... inputs) {
65     return g.opBuilder("AddN", "AddN").addInputList(inputs).build().output(0);
66   }
67 
matmul( Graph g, String name, Output<T> a, Output<T> b, boolean transposeA, boolean transposeB)68   public static <T> Output<T> matmul(
69       Graph g, String name, Output<T> a, Output<T> b, boolean transposeA, boolean transposeB) {
70     return g.opBuilder("MatMul", name)
71         .addInput(a)
72         .addInput(b)
73         .setAttr("transpose_a", transposeA)
74         .setAttr("transpose_b", transposeB)
75         .build()
76         .<T>output(0);
77   }
78 
split(Graph g, String name, int[] values, int numSplit)79   public static Operation split(Graph g, String name, int[] values, int numSplit) {
80     return g.opBuilder("Split", name)
81         .addInput(constant(g, "split_dim", 0))
82         .addInput(constant(g, "values", values))
83         .setAttr("num_split", numSplit)
84         .build();
85   }
86 
square(Graph g, String name, Output<T> value)87   public static <T> Output<T> square(Graph g, String name, Output<T> value) {
88     return g.opBuilder("Square", name)
89         .addInput(value)
90         .build()
91         .<T>output(0);
92   }
93 
transpose_A_times_X(Graph g, int[][] a)94   public static void transpose_A_times_X(Graph g, int[][] a) {
95     Output<Integer> aa = constant(g, "A", a);
96     matmul(g, "Y", aa, placeholder(g, "X", Integer.class), true, false);
97   }
98 
99   /**
100    * Counts the total number of elements in an ND array.
101    *
102    * @param array the array to count the elements of
103    * @return the number of elements
104    */
flattenedNumElements(Object array)105   public static int flattenedNumElements(Object array) {
106     int count = 0;
107     for (int i = 0; i < Array.getLength(array); i++) {
108       Object e = Array.get(array, i);
109       if (!e.getClass().isArray()) {
110         count += 1;
111       } else {
112         count += flattenedNumElements(e);
113       }
114     }
115     return count;
116   }
117 
118   /**
119    * Flattens an ND-array into a 1D-array with the same elements.
120    *
121    * @param array the array to flatten
122    * @param elementType the element class (e.g. {@code Integer.TYPE} for an {@code int[]})
123    * @return a flattened array
124    */
flatten(Object array, Class<?> elementType)125   public static Object flatten(Object array, Class<?> elementType) {
126     Object out = Array.newInstance(elementType, flattenedNumElements(array));
127     flatten(array, out, 0);
128     return out;
129   }
130 
flatten(Object array, Object out, int next)131   private static int flatten(Object array, Object out, int next) {
132     for (int i = 0; i < Array.getLength(array); i++) {
133       Object e = Array.get(array, i);
134       if (!e.getClass().isArray()) {
135         Array.set(out, next++, e);
136       } else {
137         next = flatten(e, out, next);
138       }
139     }
140     return next;
141   }
142 
143   /**
144    * Converts a {@code boolean[]} to a {@code byte[]}.
145    *
146    * <p>Suitable for creating tensors of type {@link DataType#BOOL} using {@link
147    * java.nio.ByteBuffer}.
148    */
bool2byte(boolean[] array)149   public static byte[] bool2byte(boolean[] array) {
150     byte[] out = new byte[array.length];
151     for (int i = 0; i < array.length; i++) {
152       out[i] = array[i] ? (byte) 1 : (byte) 0;
153     }
154     return out;
155   }
156 
157   /**
158    * Converts a {@code byte[]} to a {@code boolean[]}.
159    *
160    * <p>Suitable for reading tensors of type {@link DataType#BOOL} using {@link
161    * java.nio.ByteBuffer}.
162    */
byte2bool(byte[] array)163   public static boolean[] byte2bool(byte[] array) {
164     boolean[] out = new boolean[array.length];
165     for (int i = 0; i < array.length; i++) {
166       out[i] = array[i] != 0;
167     }
168     return out;
169   }
170 
TestUtil()171   private TestUtil() {}
172 }
173