summaryrefslogtreecommitdiff
path: root/morfologik-fsa/src/main/java/morfologik/fsa/CFSA2.java
blob: 6955da484d1d7380a17791c0e96567fb850a560d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package morfologik.fsa;

import static morfologik.util.FileUtils.readFully;

import java.io.IOException;
import java.io.InputStream;
import java.util.EnumSet;
import java.util.Set;

import morfologik.util.FileUtils;

/**
 * CFSA (Compact Finite State Automaton) binary format implementation, version 2:
 * <ul>
 *  <li>{@link #BIT_TARGET_NEXT} applicable on all arcs, not necessarily the last one.</li>
 *  <li>v-coded goto field</li>
 *  <li>v-coded perfect hashing numbers, if any</li>
 *  <li>31 most frequent labels integrated with flags byte</li>
 * </ul>
 * 
 * <p>The encoding of automaton body is as follows.</p>
 * 
 * <pre>
 * ---- CFSA header
 * Byte                            Description 
 *       +-+-+-+-+-+-+-+-+\
 *     0 | | | | | | | | | +------ '\'
 *       +-+-+-+-+-+-+-+-+/
 *       +-+-+-+-+-+-+-+-+\
 *     1 | | | | | | | | | +------ 'f'
 *       +-+-+-+-+-+-+-+-+/
 *       +-+-+-+-+-+-+-+-+\
 *     2 | | | | | | | | | +------ 's'
 *       +-+-+-+-+-+-+-+-+/
 *       +-+-+-+-+-+-+-+-+\
 *     3 | | | | | | | | | +------ 'a'
 *       +-+-+-+-+-+-+-+-+/
 *       +-+-+-+-+-+-+-+-+\
 *     4 | | | | | | | | | +------ version (fixed 0xc6)
 *       +-+-+-+-+-+-+-+-+/
 *       +-+-+-+-+-+-+-+-+\
 *     5 | | | | | | | | | +----\
 *       +-+-+-+-+-+-+-+-+/      \ flags [MSB first]
 *       +-+-+-+-+-+-+-+-+\      /
 *     6 | | | | | | | | | +----/
 *       +-+-+-+-+-+-+-+-+/
 *       +-+-+-+-+-+-+-+-+\
 *     7 | | | | | | | | | +------ label lookup table size
 *       +-+-+-+-+-+-+-+-+/
 *       +-+-+-+-+-+-+-+-+\
 *  8-32 | | | | | | | | | +------ label value lookup table 
 *       : : : : : : : : : |
 *       +-+-+-+-+-+-+-+-+/
 * 
 * ---- Start of a node; only if automaton was compiled with NUMBERS option.
 * 
 * Byte
 *        +-+-+-+-+-+-+-+-+\
 *      0 | | | | | | | | | \  
 *        +-+-+-+-+-+-+-+-+  +
 *      1 | | | | | | | | |  |      number of strings recognized
 *        +-+-+-+-+-+-+-+-+  +----- by the automaton starting
 *        : : : : : : : : :  |      from this node. v-coding
 *        +-+-+-+-+-+-+-+-+  +
 *        | | | | | | | | | /  
 *        +-+-+-+-+-+-+-+-+/
 *
 * ---- A vector of this node's arcs. An arc's layout depends on the combination of flags.
 * 
 * 1) NEXT bit set, mapped arc label. 
 * 
 *        +----------------------- node pointed to is next
 *        | +--------------------- the last arc of the node
 *        | | +------------------- this arc leads to a final state (acceptor)
 *        | | |  _______+--------- arc's label; indexed if M > 0, otherwise explicit label follows
 *        | | | / | | | |
 *       +-+-+-+-+-+-+-+-+\
 *     0 |N|L|F|M|M|M|M|M| +------ flags + (M) index of the mapped label.
 *       +-+-+-+-+-+-+-+-+/
 *       +-+-+-+-+-+-+-+-+\
 *     1 | | | | | | | | | +------ optional label if M == 0
 *       +-+-+-+-+-+-+-+-+/
 *       : : : : : : : : :
 *       +-+-+-+-+-+-+-+-+\
 *       |A|A|A|A|A|A|A|A| +------ v-coded goto address
 *       +-+-+-+-+-+-+-+-+/
 * </pre>
 */
public final class CFSA2 extends FSA {
	/**
	 * Automaton header version value. 
	 */
	public static final byte VERSION = (byte) 0xc6;

    /**
     * The target node of this arc follows the last arc of the current state
     * (no goto field).
     */
    public static final int BIT_TARGET_NEXT = 1 << 7;

    /**
     * The arc is the last one from the current node's arcs list.
     */
    public static final int BIT_LAST_ARC = 1 << 6;

	/**
	 * The arc corresponds to the last character of a sequence 
	 * available when building the automaton (acceptor transition).
	 */
	public static final int BIT_FINAL_ARC = 1 << 5;

	/**
	 * The count of bits assigned to storing an indexed label. 
	 */
	static final int LABEL_INDEX_BITS = 5;
	
	/**
	 * Masks only the M bits of a flag byte.
	 */
	static final int LABEL_INDEX_MASK = (1 << LABEL_INDEX_BITS) - 1;

	/**
	 * Maximum size of the labels index.
	 */
    static final int LABEL_INDEX_SIZE = (1 << LABEL_INDEX_BITS) - 1;

	/**
	 * An array of bytes with the internal representation of the automaton.
	 * Please see the documentation of this class for more information on how
	 * this structure is organized.
	 */
	public byte[] arcs;

	/**
	 * Flags for this automaton version.
	 */
    private final EnumSet<FSAFlags> flags;

	/**
	 * Label mapping for M-indexed labels.
	 */
	public final byte[] labelMapping;
	
	/**
	 * If <code>true</code> states are prepended with numbers.
	 */
	private final boolean hasNumbers;
	
	/**
	 * Epsilon node's offset.
	 */
	private final int epsilon = 0;

	/**
	 * Reads an automaton from a byte stream.
	 */
	public CFSA2(InputStream in) throws IOException {
		// Read the header first.
        if (FSAHeader.FSA_MAGIC != FileUtils.readInt(in))
            throw new IOException("Invalid file header magic bytes.");

		// Ensure we have the correct version.
        final int version = FileUtils.readByte(in);
		if (version != VERSION) {
			throw new IOException("This class can only read FSA version: " + VERSION);
		}

		// Read flags.
		short flagBits = FileUtils.readShort(in);
		flags = EnumSet.noneOf(FSAFlags.class);
		for (FSAFlags f : FSAFlags.values()) {
		    if (FSAFlags.isSet(flagBits, f))
		        flags.add(f);
		}

		if (flagBits != FSAFlags.asShort(flags))
		    throw new IOException("Unrecognized flags remained: 0x" + Integer.toHexString(flagBits));

		this.hasNumbers = flags.contains(FSAFlags.NUMBERS);

		/*
		 * Read mapping dictionary.
		 */
		int labelMappingSize = FileUtils.readByte(in) & 0xff;
		labelMapping = new byte[labelMappingSize];
		readFully(in, labelMapping);

		/*
		 * Read arcs' data.
		 */
		arcs = readFully(in);		
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int getRootNode() {
        // Skip dummy node marking terminating state.
	    return getDestinationNodeOffset(getFirstArc(epsilon));
	}

	/**
     * {@inheritDoc} 
     */
	@Override
	public final int getFirstArc(int node) {
	    if (hasNumbers) {
	        return skipVInt(node);
	    } else {
	        return node;
	    }
	}

	/**
     * {@inheritDoc} 
     */
	@Override
	public final int getNextArc(int arc) {
		if (isArcLast(arc))
			return 0;
		else
			return skipArc(arc);
	}

	/**
     * {@inheritDoc} 
     */
	@Override
	public int getArc(int node, byte label) {
		for (int arc = getFirstArc(node); arc != 0; arc = getNextArc(arc)) {
			if (getArcLabel(arc) == label)
				return arc;
		}

		// An arc labeled with "label" not found.
		return 0;
	}

	/**
     * {@inheritDoc} 
     */
	@Override
	public int getEndNode(int arc) {
		final int nodeOffset = getDestinationNodeOffset(arc);
		assert nodeOffset != 0 : "Can't follow a terminal arc: " + arc;
		assert nodeOffset < arcs.length : "Node out of bounds.";
		return nodeOffset;
	}

	/**
     * {@inheritDoc} 
     */
	@Override
	public byte getArcLabel(int arc) {
	    int index = arcs[arc] & LABEL_INDEX_MASK;
		if (index > 0) {
			return this.labelMapping[index];
		} else {
			return arcs[arc + 1];
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int getRightLanguageCount(int node) {
        assert getFlags().contains(FSAFlags.NUMBERS): "This FSA was not compiled with NUMBERS.";
	    return readVInt(arcs, node);
    }

	/**
     * {@inheritDoc} 
     */
	@Override
	public boolean isArcFinal(int arc) {
		return (arcs[arc] & BIT_FINAL_ARC) != 0;
	}

	/**
     * {@inheritDoc} 
     */
	@Override
	public boolean isArcTerminal(int arc) {
		return (0 == getDestinationNodeOffset(arc));
	}

	/**
	 * Returns <code>true</code> if this arc has <code>NEXT</code> bit set.
	 * 
	 * @see #BIT_LAST_ARC
	 */
	public boolean isArcLast(int arc) {
		return (arcs[arc] & BIT_LAST_ARC) != 0;
	}

	/**
	 * @see #BIT_TARGET_NEXT
	 */
	public boolean isNextSet(int arc) {
		return (arcs[arc] & BIT_TARGET_NEXT) != 0;
	}

	/**
	 * {@inheritDoc}
	 */
	public Set<FSAFlags> getFlags() {
	    return flags;
	}

	/**
	 * Returns the address of the node pointed to by this arc.
	 */
	final int getDestinationNodeOffset(int arc) {
		if (isNextSet(arc)) {
		    /* Follow until the last arc of this state. */
		    while (!isArcLast(arc)) { 
		        arc = getNextArc(arc);
		    }

			/* And return the byte right after it. */
			return skipArc(arc);
		} else {
			/*
			 * The destination node address is v-coded. v-code starts either
			 * at the next byte (label indexed) or after the next byte (label explicit).
			 */
		    return readVInt(arcs, arc + ((arcs[arc] & LABEL_INDEX_MASK) == 0 ? 2 : 1));
		}
	}

	/**
	 * Read the arc's layout and skip as many bytes, as needed, to skip it.
	 */
	private int skipArc(int offset) {
	    int flag = arcs[offset++];

	    // Explicit label?
	    if ((flag & LABEL_INDEX_MASK) == 0) {
	        offset++;
	    }

	    // Explicit goto?
	    if ((flag & BIT_TARGET_NEXT) == 0) {
	        offset = skipVInt(offset);
	    }

	    assert offset < this.arcs.length;
	    return offset;
	}

    /**
     * Read a v-int.
     */
    static int readVInt(byte[] array, int offset) {
        byte b = array[offset];
        int value = b & 0x7F;

        for (int shift = 7; b < 0; shift += 7) {
          b = array[++offset];
          value |= (b & 0x7F) << shift;
        }
    
        return value;
    }
    
    /**
     * Write a v-int to a byte array.
     */
    static int writeVInt(byte[] array, int offset, int value) {
        assert value >= 0 : "Can't v-code negative ints.";

        while (value > 0x7F) {
            array[offset++] = (byte) (0x80 | (value & 0x7F));
            value >>= 7;
        }
        array[offset++] = (byte) value;
        
        return offset;
    }    

    /**
     * Return the byte-length of a v-coded int.
     */
    static int vIntLength(int value) {
        assert value >= 0 : "Can't v-code negative ints.";

        int bytes;
        for (bytes = 1; value >= 0x80; bytes++) {
            value >>= 7;
        }

        return bytes;
    }    

    /**
     * Skip a v-int.
     */
    private int skipVInt(int offset) {
        while (arcs[offset++] < 0);
        return offset;
    }
}