| 1 | package morfologik.fsa; |
| 2 | |
| 3 | import java.io.ByteArrayOutputStream; |
| 4 | import java.io.IOException; |
| 5 | import java.io.InputStream; |
| 6 | import java.nio.ByteBuffer; |
| 7 | import java.util.BitSet; |
| 8 | import java.util.Collections; |
| 9 | import java.util.Iterator; |
| 10 | import java.util.Locale; |
| 11 | import java.util.Set; |
| 12 | |
| 13 | /** |
| 14 | * This is a top abstract class for handling finite state automata. These |
| 15 | * automata are arc-based, a design described in Jan Daciuk's <i>Incremental |
| 16 | * Construction of Finite-State Automata and Transducers, and Their Use in the |
| 17 | * Natural Language Processing</i> (PhD thesis, Technical University of Gdansk). |
| 18 | */ |
| 19 | public abstract class FSA implements Iterable<ByteBuffer> { |
| 20 | /** |
| 21 | * @return Returns the identifier of the root node of this automaton. Returns |
| 22 | * 0 if the start node is also the end node (the automaton is empty). |
| 23 | */ |
| 24 | public abstract int getRootNode(); |
| 25 | |
| 26 | /** |
| 27 | * @param node |
| 28 | * Identifier of the node. |
| 29 | * @return Returns the identifier of the first arc leaving <code>node</code> |
| 30 | * or 0 if the node has no outgoing arcs. |
| 31 | */ |
| 32 | public abstract int getFirstArc(int node); |
| 33 | |
| 34 | /** |
| 35 | * @param arc |
| 36 | * The arc's identifier. |
| 37 | * @return Returns the identifier of the next arc after <code>arc</code> and |
| 38 | * leaving <code>node</code>. Zero is returned if no more arcs are |
| 39 | * available for the node. |
| 40 | */ |
| 41 | public abstract int getNextArc(int arc); |
| 42 | |
| 43 | /** |
| 44 | * @param node |
| 45 | * Identifier of the node. |
| 46 | * @param label |
| 47 | * The arc's label. |
| 48 | * @return Returns the identifier of an arc leaving <code>node</code> and |
| 49 | * labeled with <code>label</code>. An identifier equal to 0 means the |
| 50 | * node has no outgoing arc labeled <code>label</code>. |
| 51 | */ |
| 52 | public abstract int getArc(int node, byte label); |
| 53 | |
| 54 | /** |
| 55 | * @param arc |
| 56 | * The arc's identifier. |
| 57 | * @return Return the label associated with a given <code>arc</code>. |
| 58 | */ |
| 59 | public abstract byte getArcLabel(int arc); |
| 60 | |
| 61 | /** |
| 62 | * @param arc |
| 63 | * The arc's identifier. |
| 64 | * @return Returns <code>true</code> if the destination node at the end of |
| 65 | * this <code>arc</code> corresponds to an input sequence created when |
| 66 | * building this automaton. |
| 67 | */ |
| 68 | public abstract boolean isArcFinal(int arc); |
| 69 | |
| 70 | /** |
| 71 | * @param arc |
| 72 | * The arc's identifier. |
| 73 | * @return Returns <code>true</code> if this <code>arc</code> does not have a |
| 74 | * terminating node (@link {@link #getEndNode(int)} will throw an |
| 75 | * exception). Implies {@link #isArcFinal(int)}. |
| 76 | */ |
| 77 | public abstract boolean isArcTerminal(int arc); |
| 78 | |
| 79 | /** |
| 80 | * @param arc |
| 81 | * The arc's identifier. |
| 82 | * @return Return the end node pointed to by a given <code>arc</code>. |
| 83 | * Terminal arcs (those that point to a terminal state) have no end |
| 84 | * node representation and throw a runtime exception. |
| 85 | */ |
| 86 | public abstract int getEndNode(int arc); |
| 87 | |
| 88 | /** |
| 89 | * @return Returns a set of flags for this FSA instance. |
| 90 | */ |
| 91 | public abstract Set<FSAFlags> getFlags(); |
| 92 | |
| 93 | /** |
| 94 | * @param node |
| 95 | * Identifier of the node. |
| 96 | * @return Calculates and returns the number of arcs of a given node. |
| 97 | */ |
| 98 | public int getArcCount(int node) { |
| 99 | int count = 0; |
| 100 | for (int arc = getFirstArc(node); arc != 0; arc = getNextArc(arc)) { |
| 101 | count++; |
| 102 | } |
| 103 | return count; |
| 104 | } |
| 105 | |
| 106 | /** |
| 107 | * @param node |
| 108 | * Identifier of the node. |
| 109 | * |
| 110 | * @return Returns the number of sequences reachable from the given state if |
| 111 | * the automaton was compiled with {@link FSAFlags#NUMBERS}. The size |
| 112 | * of the right language of the state, in other words. |
| 113 | * |
| 114 | * @throws UnsupportedOperationException |
| 115 | * If the automaton was not compiled with {@link FSAFlags#NUMBERS}. |
| 116 | * The value can then be computed by manual count of |
| 117 | * {@link #getSequences}. |
| 118 | */ |
| 119 | public int getRightLanguageCount(int node) { |
| 120 | throw new UnsupportedOperationException("Automaton not compiled with " + FSAFlags.NUMBERS); |
| 121 | } |
| 122 | |
| 123 | /** |
| 124 | * Returns an iterator over all binary sequences starting at the given FSA |
| 125 | * state (node) and ending in final nodes. This corresponds to a set of |
| 126 | * suffixes of a given prefix from all sequences stored in the automaton. |
| 127 | * |
| 128 | * <p> |
| 129 | * The returned iterator is a {@link ByteBuffer} whose contents changes on |
| 130 | * each call to {@link Iterator#next()}. The keep the contents between calls |
| 131 | * to {@link Iterator#next()}, one must copy the buffer to some other |
| 132 | * location. |
| 133 | * </p> |
| 134 | * |
| 135 | * <p> |
| 136 | * <b>Important.</b> It is guaranteed that the returned byte buffer is backed |
| 137 | * by a byte array and that the content of the byte buffer starts at the |
| 138 | * array's index 0. |
| 139 | * </p> |
| 140 | * |
| 141 | * @param node |
| 142 | * Identifier of the starting node from which to return subsequences. |
| 143 | * @return An iterable over all sequences encoded starting at the given node. |
| 144 | */ |
| 145 | public Iterable<ByteBuffer> getSequences(final int node) { |
| 146 | if (node == 0) { |
| 147 | return Collections.<ByteBuffer> emptyList(); |
| 148 | } |
| 149 | |
| 150 | return new Iterable<ByteBuffer>() { |
| 151 | public Iterator<ByteBuffer> iterator() { |
| 152 | return new ByteSequenceIterator(FSA.this, node); |
| 153 | } |
| 154 | }; |
| 155 | } |
| 156 | |
| 157 | /** |
| 158 | * An alias of calling {@link #iterator} directly ({@link FSA} is also |
| 159 | * {@link Iterable}). |
| 160 | * |
| 161 | * @return Returns all sequences encoded in the automaton. |
| 162 | */ |
| 163 | public final Iterable<ByteBuffer> getSequences() { |
| 164 | return getSequences(getRootNode()); |
| 165 | } |
| 166 | |
| 167 | /** |
| 168 | * Returns an iterator over all binary sequences starting from the initial FSA |
| 169 | * state (node) and ending in final nodes. The returned iterator is a |
| 170 | * {@link ByteBuffer} whose contents changes on each call to |
| 171 | * {@link Iterator#next()}. The keep the contents between calls to |
| 172 | * {@link Iterator#next()}, one must copy the buffer to some other location. |
| 173 | * |
| 174 | * <p> |
| 175 | * <b>Important.</b> It is guaranteed that the returned byte buffer is backed |
| 176 | * by a byte array and that the content of the byte buffer starts at the |
| 177 | * array's index 0. |
| 178 | * </p> |
| 179 | */ |
| 180 | public final Iterator<ByteBuffer> iterator() { |
| 181 | return getSequences().iterator(); |
| 182 | } |
| 183 | |
| 184 | /** |
| 185 | * Visit all states. The order of visiting is undefined. This method may be |
| 186 | * faster than traversing the automaton in post or preorder since it can scan |
| 187 | * states linearly. Returning false from {@link StateVisitor#accept(int)} |
| 188 | * immediately terminates the traversal. |
| 189 | * |
| 190 | * @param v Visitor to receive traversal calls. |
| 191 | * @param <T> A subclass of {@link StateVisitor}. |
| 192 | * @return Returns the argument (for access to anonymous class fields). |
| 193 | */ |
| 194 | public <T extends StateVisitor> T visitAllStates(T v) { |
| 195 | return visitInPostOrder(v); |
| 196 | } |
| 197 | |
| 198 | /** |
| 199 | * Same as {@link #visitInPostOrder(StateVisitor, int)}, starting from root |
| 200 | * automaton node. |
| 201 | * |
| 202 | * @param v Visitor to receive traversal calls. |
| 203 | * @param <T> A subclass of {@link StateVisitor}. |
| 204 | * @return Returns the argument (for access to anonymous class fields). |
| 205 | */ |
| 206 | public <T extends StateVisitor> T visitInPostOrder(T v) { |
| 207 | return visitInPostOrder(v, getRootNode()); |
| 208 | } |
| 209 | |
| 210 | /** |
| 211 | * Visits all states reachable from <code>node</code> in postorder. Returning |
| 212 | * false from {@link StateVisitor#accept(int)} immediately terminates the |
| 213 | * traversal. |
| 214 | * |
| 215 | * @param v Visitor to receive traversal calls. |
| 216 | * @param <T> A subclass of {@link StateVisitor}. |
| 217 | * @param node Identifier of the node. |
| 218 | * @return Returns the argument (for access to anonymous class fields). |
| 219 | */ |
| 220 | public <T extends StateVisitor> T visitInPostOrder(T v, int node) { |
| 221 | visitInPostOrder(v, node, new BitSet()); |
| 222 | return v; |
| 223 | } |
| 224 | |
| 225 | /** Private recursion. */ |
| 226 | private boolean visitInPostOrder(StateVisitor v, int node, BitSet visited) { |
| 227 | if (visited.get(node)) |
| 228 | return true; |
| 229 | visited.set(node); |
| 230 | |
| 231 | for (int arc = getFirstArc(node); arc != 0; arc = getNextArc(arc)) { |
| 232 | if (!isArcTerminal(arc)) { |
| 233 | if (!visitInPostOrder(v, getEndNode(arc), visited)) |
| 234 | return false; |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | return v.accept(node); |
| 239 | } |
| 240 | |
| 241 | /** |
| 242 | * Same as {@link #visitInPreOrder(StateVisitor, int)}, starting from root |
| 243 | * automaton node. |
| 244 | * |
| 245 | * @param v Visitor to receive traversal calls. |
| 246 | * @param <T> A subclass of {@link StateVisitor}. |
| 247 | * @return Returns the argument (for access to anonymous class fields). |
| 248 | */ |
| 249 | public <T extends StateVisitor> T visitInPreOrder(T v) { |
| 250 | return visitInPreOrder(v, getRootNode()); |
| 251 | } |
| 252 | |
| 253 | /** |
| 254 | * Visits all states in preorder. Returning false from |
| 255 | * {@link StateVisitor#accept(int)} skips traversal of all sub-states of a |
| 256 | * given state. |
| 257 | * |
| 258 | * @param v Visitor to receive traversal calls. |
| 259 | * @param <T> A subclass of {@link StateVisitor}. |
| 260 | * @param node Identifier of the node. |
| 261 | * @return Returns the argument (for access to anonymous class fields). |
| 262 | */ |
| 263 | public <T extends StateVisitor> T visitInPreOrder(T v, int node) { |
| 264 | visitInPreOrder(v, node, new BitSet()); |
| 265 | return v; |
| 266 | } |
| 267 | |
| 268 | /** |
| 269 | * @param in The input stream. |
| 270 | * @return Reads all remaining bytes from an input stream and returns |
| 271 | * them as a byte array. |
| 272 | * @throws IOException Rethrown if an I/O exception occurs. |
| 273 | */ |
| 274 | protected static final byte[] readRemaining(InputStream in) throws IOException { |
| 275 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
| 276 | byte[] buffer = new byte[1024 * 8]; |
| 277 | int len; |
| 278 | while ((len = in.read(buffer)) >= 0) { |
| 279 | baos.write(buffer, 0, len); |
| 280 | } |
| 281 | return baos.toByteArray(); |
| 282 | } |
| 283 | |
| 284 | /** Private recursion. */ |
| 285 | private void visitInPreOrder(StateVisitor v, int node, BitSet visited) { |
| 286 | if (visited.get(node)) { |
| 287 | return; |
| 288 | } |
| 289 | visited.set(node); |
| 290 | |
| 291 | if (v.accept(node)) { |
| 292 | for (int arc = getFirstArc(node); arc != 0; arc = getNextArc(arc)) { |
| 293 | if (!isArcTerminal(arc)) { |
| 294 | visitInPreOrder(v, getEndNode(arc), visited); |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | /** |
| 301 | * A factory for reading automata in any of the supported versions. |
| 302 | * |
| 303 | * @param stream |
| 304 | * The input stream to read automaton data from. The stream is not |
| 305 | * closed. |
| 306 | * @return Returns an instantiated automaton. Never null. |
| 307 | * @throws IOException |
| 308 | * If the input stream does not represent an automaton or is |
| 309 | * otherwise invalid. |
| 310 | */ |
| 311 | public static FSA read(InputStream stream) throws IOException { |
| 312 | final FSAHeader header = FSAHeader.read(stream); |
| 313 | |
| 314 | switch (header.version) { |
| 315 | case FSA5.VERSION: |
| 316 | return new FSA5(stream); |
| 317 | case CFSA.VERSION: |
| 318 | return new CFSA(stream); |
| 319 | case CFSA2.VERSION: |
| 320 | return new CFSA2(stream); |
| 321 | default: |
| 322 | throw new IOException( |
| 323 | String.format(Locale.ROOT, "Unsupported automaton version: 0x%02x", header.version & 0xFF)); |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | /** |
| 328 | * A factory for reading a specific FSA subclass, including proper casting. |
| 329 | * |
| 330 | * @param stream |
| 331 | * The input stream to read automaton data from. The stream is not |
| 332 | * closed. |
| 333 | * @param clazz A subclass of {@link FSA} to cast the read automaton to. |
| 334 | * @param <T> A subclass of {@link FSA} to cast the read automaton to. |
| 335 | * @return Returns an instantiated automaton. Never null. |
| 336 | * @throws IOException |
| 337 | * If the input stream does not represent an automaton, is otherwise |
| 338 | * invalid or the class of the automaton read from the input stream |
| 339 | * is not assignable to <code>clazz</code>. |
| 340 | */ |
| 341 | public static <T extends FSA> T read(InputStream stream, Class<? extends T> clazz) throws IOException { |
| 342 | FSA fsa = read(stream); |
| 343 | if (!clazz.isInstance(fsa)) { |
| 344 | throw new IOException(String.format(Locale.ROOT, "Expected FSA type %s, but read an incompatible type %s.", |
| 345 | clazz.getName(), fsa.getClass().getName())); |
| 346 | } |
| 347 | return clazz.cast(fsa); |
| 348 | } |
| 349 | } |