summaryrefslogtreecommitdiff
path: root/morfologik-fsa/src/main/java/morfologik/fsa/FSA5Serializer.java
blob: e4821d1d729ed22decc387be55939f125904b3cf (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
package morfologik.fsa;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.*;

import com.carrotsearch.hppc.*;
import com.carrotsearch.hppc.BitSet;

import static morfologik.fsa.FSAFlags.*;

/**
 * Serializes in-memory {@link FSA} graphs to a binary format compatible with
 * Jan Daciuk's <code>fsa</code>'s package <code>FSA5</code> format.
 * 
 * <p>
 * It is possible to serialize the automaton with numbers required for perfect
 * hashing. See {@link #withNumbers()} method.
 * </p>
 * 
 * @see FSA5
 * @see FSA#read(java.io.InputStream)
 */
public final class FSA5Serializer implements FSASerializer {
    /**
     * Maximum number of bytes for a serialized arc.
     */
    private final static int MAX_ARC_SIZE = 1 + 5;

    /**
     * Maximum number of bytes for per-node data.
     */
    private final static int MAX_NODE_DATA_SIZE = 16;

    /**
     * Number of bytes for the arc's flags header (arc representation without
     * the goto address).
     */
    private final static int SIZEOF_FLAGS = 1;

    /**
     * Supported flags.
     */
    private final static EnumSet<FSAFlags> flags = EnumSet.of(NUMBERS, SEPARATORS, FLEXIBLE, STOPBIT, NEXTBIT);
    
    /**
     * @see FSA5#filler
     */
    public byte fillerByte = FSA5.DEFAULT_FILLER;

    /**
     * @see FSA5#annotation
     */
    public byte annotationByte = FSA5.DEFAULT_ANNOTATION;

    /**
     * <code>true</code> if we should serialize with numbers.
     * 
     * @see #withNumbers()
     */
    private boolean withNumbers;

    /**
     * A hash map of [state, offset] pairs.
     */
    private IntIntHashMap offsets = new IntIntHashMap();

    /**
     * A hash map of [state, right-language-count] pairs.
     */
    private IntIntHashMap numbers = new IntIntHashMap();

    /**
     * Serialize the automaton with the number of right-language sequences in
     * each node. This is required to implement perfect hashing. The numbering
     * also preserves the order of input sequences.
     * 
     * @return Returns the same object for easier call chaining.
     */
    public FSA5Serializer withNumbers() {
        withNumbers = true;
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public FSA5Serializer withFiller(byte filler) {
        this.fillerByte = filler;
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public FSA5Serializer withAnnotationSeparator(byte annotationSeparator) {
        this.annotationByte = annotationSeparator;
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public FSASerializer withLogger(IMessageLogger logger) {
        return this;
    }

    /**
     * Serialize root state <code>s</code> to an output stream in
     * <code>FSA5</code> format.
     * 
     * @see #withNumbers
     * @return Returns <code>os</code> for chaining.
     */
    @Override
    public <T extends OutputStream> T serialize(final FSA fsa, T os)
            throws IOException {

        // Prepare space for arc offsets and linearize all the states.
        int[] linearized = linearize(fsa);

        /*
         * Calculate the number of bytes required for the node data, if
         * serializing with numbers.
         */
        int nodeDataLength = 0;
        if (withNumbers) {
            this.numbers = FSAUtils.rightLanguageForAllStates(fsa);
            int maxNumber = numbers.get(fsa.getRootNode());
            while (maxNumber > 0) {
                nodeDataLength++;
                maxNumber >>>= 8;
            }
        }

        // Calculate minimal goto length.
        int gtl = 1;
        while (true) {
            // First pass: calculate offsets of states.
            if (!emitArcs(fsa, null, linearized, gtl, nodeDataLength)) {
                gtl++;
                continue;
            }

            // Second pass: check if goto overflows anywhere.
            if (emitArcs(fsa, null, linearized, gtl, nodeDataLength))
                break;

            gtl++;
        }

        /*
         * Emit the header.
         */
        os.write(new byte[] { '\\', 'f', 's', 'a' });
        os.write(FSA5.VERSION);
        os.write(fillerByte);
        os.write(annotationByte);
        os.write((nodeDataLength << 4) | gtl);

        /*
         * Emit the automaton.
         */
        boolean gtlUnchanged = emitArcs(fsa, os, linearized, gtl, nodeDataLength);
        assert gtlUnchanged : "gtl changed in the final pass.";

        return os;
    }

    /**
     * Return supported flags.
     */
    @Override
    public Set<FSAFlags> getFlags() {
        return flags;
    }

    /**
     * Linearization of states.
     */
    private int[] linearize(final FSA fsa) {
        int[] linearized = new int[0];
        int last = 0;

        BitSet visited = new BitSet();
        IntStack nodes = new IntStack();
        nodes.push(fsa.getRootNode());

        while (!nodes.isEmpty()) {
            final int node = nodes.pop();
            if (visited.get(node))
                continue;

            if (last >= linearized.length) {
                linearized = Arrays.copyOf(linearized, linearized.length + 100000);
            }

            visited.set(node);
            linearized[last++] = node;

            for (int arc = fsa.getFirstArc(node); arc != 0; arc = fsa.getNextArc(arc)) {
                if (!fsa.isArcTerminal(arc)) {
                    int target = fsa.getEndNode(arc);
                    if (!visited.get(target))
                        nodes.push(target);
                }
            }
        }

        return Arrays.copyOf(linearized, last);
    }

    /**
     * Update arc offsets assuming the given goto length.
     */
    private boolean emitArcs(FSA fsa, OutputStream os, int[] linearized,
            int gtl, int nodeDataLength) throws IOException {
        final ByteBuffer bb = ByteBuffer.allocate(Math.max(MAX_NODE_DATA_SIZE,
                MAX_ARC_SIZE));

        int offset = 0;

        // Add dummy terminal state.
        offset += emitNodeData(bb, os, nodeDataLength, 0);
        offset += emitArc(bb, os, gtl, 0, (byte) 0, 0);

        // Add epsilon state.
        offset += emitNodeData(bb, os, nodeDataLength, 0);        
        if (fsa.getRootNode() != 0)
            offset += emitArc(bb, os, gtl, FSA5.BIT_LAST_ARC | FSA5.BIT_TARGET_NEXT, (byte) '^', 0);
        else
            offset += emitArc(bb, os, gtl, FSA5.BIT_LAST_ARC                       , (byte) '^', 0);

        int maxStates = linearized.length;
        for (int j = 0; j < maxStates; j++) {
            final int s = linearized[j];

            if (os == null) {
                offsets.put(s, offset);
            } else {
                assert offsets.get(s) == offset : s + " " + offsets.get(s) + " " + offset;
            }

            offset += emitNodeData(bb, os, nodeDataLength, withNumbers ? numbers.get(s) : 0);

            for (int arc = fsa.getFirstArc(s); arc != 0; arc = fsa.getNextArc(arc)) {
                int targetOffset;
                final int target;
                if (fsa.isArcTerminal(arc)) {
                    targetOffset = 0;
                    target = 0;
                } else {
                    target = fsa.getEndNode(arc);
                    targetOffset = offsets.get(target);
                }

                int flags = 0;
                if (fsa.isArcFinal(arc)) {
                    flags |= FSA5.BIT_FINAL_ARC;
                }

                if (fsa.getNextArc(arc) == 0) {
                    flags |= FSA5.BIT_LAST_ARC;

                    if (j + 1 < maxStates && target == linearized[j + 1]
                            && targetOffset != 0) {
                        flags |= FSA5.BIT_TARGET_NEXT;
                        targetOffset = 0;
                    }
                }

                int bytes = emitArc(bb, os, gtl, flags, fsa.getArcLabel(arc), targetOffset);
                if (bytes < 0)
                    // gtl too small. interrupt eagerly.
                    return false;

                offset += bytes;
            }
        }

        return true;
    }

    /** */
    private int emitArc(ByteBuffer bb, OutputStream os, int gtl, int flags, byte label, int targetOffset)
        throws IOException
    {
        int arcBytes = (flags & FSA5.BIT_TARGET_NEXT) != 0 ? SIZEOF_FLAGS : gtl;

        flags |= (targetOffset << 3);
        bb.put(label);
        for (int b = 0; b < arcBytes; b++) {
            bb.put((byte) flags);
            flags >>>= 8;
        }

        if (flags != 0) {
            // gtl too small. interrupt eagerly.
            return -1;
        }

        bb.flip();
        int bytes = bb.remaining();
        if (os != null) {
            os.write(bb.array(), bb.position(), bb.remaining());
        }
        bb.clear();
        
        return bytes;
    }

    /** */
    private int emitNodeData(ByteBuffer bb, OutputStream os,
            int nodeDataLength, int number) throws IOException {
        if (nodeDataLength > 0 && os != null) {
            for (int i = 0; i < nodeDataLength; i++) {
                bb.put((byte) number);
                number >>>= 8;
            }

            bb.flip();
            os.write(bb.array(), bb.position(), bb.remaining());
            bb.clear();
        }

        return nodeDataLength;
    }
}