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

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.TreeMap;

import com.carrotsearch.hppc.IntIntOpenHashMap;

/**
 * Other FSA-related utilities not directly associated with the class hierarchy.
 */
public final class FSAUtils {
    public final static class IntIntHolder {
        public int a;
        public int b;
        
        public IntIntHolder(int a, int b) {
            this.a = a;
            this.b = b;
        }

        public IntIntHolder() {
        }
    }

    /**
     * Returns the right-language reachable from a given FSA node, formatted
     * as an input for the graphviz package (expressed in the <code>dot</code>
     * language).
     */
	public static String toDot(FSA fsa, int node) {
		try {
    		StringWriter w = new StringWriter();
    		toDot(w, fsa, node);
    		return w.toString();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Saves the right-language reachable from a given FSA node, formatted
	 * as an input for the graphviz package (expressed in the <code>dot</code>
	 * language), to the given writer.
	 */
	public static void toDot(Writer w, FSA fsa, int node) throws IOException {
		w.write("digraph Automaton {\n");
		w.write("  rankdir = LR;\n");

		final BitSet visited = new BitSet();

		w.write("  stop [shape=doublecircle,label=\"\"];\n");
		w.write("  initial [shape=plaintext,label=\"\"];\n");
		w.write("  initial -> " + node + "\n\n");

		visitNode(w, 0, fsa, node, visited);
		w.write("}\n"); 
	}

	private static void visitNode(Writer w, int d, FSA fsa, int s, BitSet visited) throws IOException {
		visited.set(s);
		w.write("  "); w.write(Integer.toString(s));

		if (fsa.getFlags().contains(FSAFlags.NUMBERS)) {
			int nodeNumber = fsa.getRightLanguageCount(s);
			w.write(" [shape=circle,label=\"" + nodeNumber + "\"];\n");
		} else {
			w.write(" [shape=circle,label=\"\"];\n");
		}

		for (int arc = fsa.getFirstArc(s); arc != 0; arc = fsa.getNextArc(arc)) {
			w.write("  ");
			w.write(Integer.toString(s));
			w.write(" -> ");
			if (fsa.isArcTerminal(arc)) {
				w.write("stop");
			} else {
				w.write(Integer.toString(fsa.getEndNode(arc)));
			}

			final byte label = fsa.getArcLabel(arc);
			w.write(" [label=\"");
			if (Character.isLetterOrDigit(label))
				w.write((char) label);
			else {
				w.write("0x");
				w.write(Integer.toHexString(label & 0xFF));
			}
			w.write("\"");
			if (fsa.isArcFinal(arc)) w.write(" arrowhead=\"tee\"");
			if (fsa instanceof FSA5) {
				if (((FSA5) fsa).isNextSet(arc)) {
					w.write(" color=\"blue\"");
				}
			}

			w.write("]\n");
		}

		for (int arc = fsa.getFirstArc(s); arc != 0; arc = fsa.getNextArc(arc)) {
			if (!fsa.isArcTerminal(arc)) {
				int endNode = fsa.getEndNode(arc);
				if (!visited.get(endNode)) {
					visitNode(w, d + 1, fsa, endNode, visited);
				}
			}
		}
    }

    /**
     * All byte sequences generated as the right language of <code>state</code>.
     */
    public static ArrayList<byte[]> rightLanguage(FSA fsa, int state) {
        final ArrayList<byte[]> rl = new ArrayList<byte[]>();
        final byte [] buffer = new byte [0];

        descend(fsa, state, buffer, 0, rl);

        return rl;
    }

    /**
     * Recursive descend and collection of the right language.
     */
    private static byte [] descend(FSA fsa, int state, byte [] b, int position, ArrayList<byte[]> rl) {

        if (b.length <= position) {
            b = Arrays.copyOf(b, position + 1);
        }

        for (int arc = fsa.getFirstArc(state); arc != 0; arc = fsa.getNextArc(arc)) {
            b[position] = fsa.getArcLabel(arc);

            if (fsa.isArcFinal(arc)) {
                rl.add(Arrays.copyOf(b, position + 1));
            }

            if (!fsa.isArcTerminal(arc))
                b = descend(fsa, fsa.getEndNode(arc), b, position + 1, rl);
        }

        return b;
    }

    /**
     * Calculate fan-out ratio.
     * @return The returned array: result[outgoing-arcs]
     */
    public static TreeMap<Integer, Integer> calculateFanOuts(final FSA fsa, int root) {
        final int [] result = new int [256];
        fsa.visitInPreOrder(new StateVisitor() {
            public boolean accept(int state) {
                int count = 0;
                for (int arc = fsa.getFirstArc(state); arc != 0; arc = fsa.getNextArc(arc))
                    count++;
                result[count]++;
                return true;
            }
        });

        TreeMap<Integer, Integer> output = new TreeMap<Integer, Integer>();
        
        int low = 1; // Omit #0, there is always a single node like that (dummy).
        while (low < result.length && result[low] == 0) low++;

        int high = result.length - 1;
        while (high >= 0 && result[high] == 0) high--;

        for (int i = low; i <= high; i++) {
            output.put(i, result[i]);
        }

        return output;
    }

    /**
     * Calculate the size of right language for each state in an FSA.
     */
    public static IntIntOpenHashMap rightLanguageForAllStates(final FSA fsa) {
        final IntIntOpenHashMap numbers = new IntIntOpenHashMap();

        fsa.visitInPostOrder(new StateVisitor() {
            public boolean accept(int state) {
                int thisNodeNumber = 0;
                for (int arc = fsa.getFirstArc(state); arc != 0; arc = fsa.getNextArc(arc)) {
                    thisNodeNumber +=
                        (fsa.isArcFinal(arc) ? 1 : 0) +
                        (fsa.isArcTerminal(arc) ? 0 : numbers.get(fsa.getEndNode(arc)));
                }
                numbers.put(state, thisNodeNumber);

                return true;
            }
        });
        
        return numbers;
    }
}