aboutsummaryrefslogtreecommitdiffstats
path: root/tools/java/org/unicode/cldr/util/TestStateDictionaryBuilder.java
blob: 110a3404e0dab875ae463a8369bb48d60ec28a11 (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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*
 **********************************************************************
 * Copyright (c) 2006-2007, Google and others.  All Rights Reserved.
 **********************************************************************
 * Author: Mark Davis
 **********************************************************************
 */
package org.unicode.cldr.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import org.unicode.cldr.util.CharUtilities.CharSourceWrapper;
import org.unicode.cldr.util.Dictionary.Matcher;
import org.unicode.cldr.util.Dictionary.Matcher.Filter;
import org.unicode.cldr.util.Dictionary.Matcher.Status;
import org.unicode.cldr.util.SimpleDictionary.SimpleDictionaryBuilder;

import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.text.SimpleDateFormat;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.text.UnicodeSetIterator;
import com.ibm.icu.util.TimeZone;
import com.ibm.icu.util.ULocale;

/**
 * Should be in the package usertest, but it's a pain to rename files in CVS.
 *
 * @author markdavis
 *
 * @param <T>
 */
public class TestStateDictionaryBuilder<T> {
    private static final boolean SHORT_TEST = true;

    private static final boolean SHOW_CONTENTS = true;

    private static final boolean CHECK_BOOLEAN = false;

    private final boolean SHOW_STATES = true;

    boolean SIMPLE_ONLY = false;

    boolean TEST_AGAINST_SIMPLE = true;

    Dictionary<T> stateDictionary;
    Dictionary.Matcher<T> stateMatcher;

    Dictionary<T> simpleDictionary;
    Dictionary.Matcher<T> simpleMatcher;

    Map<CharSequence, T> baseMapping = new TreeMap<CharSequence, T>();

    final StateDictionaryBuilder<T> stateDictionaryBuilder = new StateDictionaryBuilder<T>();
    final SimpleDictionaryBuilder<T> simpleDictionaryBuilder = new SimpleDictionaryBuilder<T>();

    // TODO: convert to TestFramework
    public static void main(String[] args) {

        try {
            new TestStateDictionaryBuilder<String>().test(args);
        } finally {
            System.out.println("DONE");
        }
    }

    @SuppressWarnings({ "unchecked" })
    public void test(String[] args) {

        for (String arg : args) {
            if (arg.equalsIgnoreCase("utf8")) {
                stateDictionaryBuilder.setByteConverter(new Utf8StringByteConverter());
            } else if (arg.equalsIgnoreCase("normal")) {
                stateDictionaryBuilder.setByteConverter(new CompactStringByteConverter(false));
            } else if (arg.equalsIgnoreCase("compact")) {
                stateDictionaryBuilder.setByteConverter(new CompactStringByteConverter(true));
            }
        }
        baseMapping.put("GMT+0000", (T) ("t"));
        baseMapping.put("GMT+0100", (T) ("t"));
        baseMapping.put("GMT+0200", (T) ("t"));
        baseMapping.put("GMT+0300", (T) ("t"));
        baseMapping.put("GMT+0307", (T) ("t"));
        showDictionaryContents();

        addToBoth("man", 1);
        addToBoth("manner", 100);
        addToBoth("many", 10);
        addToBoth("any", 83);
        showDictionaryContents();

        baseMapping.put("man", (T) "Woman");
        baseMapping.put("many", (T) "Few");
        baseMapping.put("any", (T) "All");
        showDictionaryContents();

        for (Filter filter : Filter.values()) {
            final String string = "many manners ma";
            tryFind(string, new CharSourceWrapper<CharSequence>(string), stateDictionary, filter);
        }

        showWords("ma");
        showWords("ma!");
        showWords("!ma");
        showWords("man");
        showWords("man!");
        showWords("mann");
        showWords("mann!");
        showWords("many");
        showWords("many!");
        compare();

        addToBoth("m\u03B1nner", 1000);
        showDictionaryContents();
        showWords("m\u03B1");
        compare();

        // if (true) return;
        // clear out

        addToBoth("fish", 10);
        showDictionaryContents();
        showWords("a fisherman");
        compare();

        addToBoth("fisher", 13);
        showDictionaryContents();
        showWords("a fisherman");
        compare();

        addToBoth("her", 55);
        showDictionaryContents();
        showWords("a fisherman");
        compare();

        // clear out

        // check some non-latin
        String[] zoneIDs = TimeZone.getAvailableIDs();
        SimpleDateFormat dt = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.LONG, new ULocale("hi"));
        dt.applyPattern("vvvv");
        for (String zoneID : zoneIDs) {
            TimeZone zone = TimeZone.getTimeZone(zoneID);
            dt.setTimeZone(zone);
            String zoneName = dt.format(0);
            addToBoth(zoneName, (T) (CHECK_BOOLEAN ? "t" : zoneID));
        }
        compare();
        showDictionaryContents();
        ((StateDictionary<T>) stateDictionary).flatten();

        if (SIMPLE_ONLY) {
            testWithUnicodeNames();

            ((StateDictionary<T>) stateDictionary).flatten();
            compare();
            System.out.println();
            showDictionaryContents();
        }

    }

    static public <U> void tryFind(CharSequence originalText, CharSource charListText, Dictionary<U> dictionary,
        Filter filter) {
        System.out.println("Using dictionary: "
            + Dictionary.load(dictionary.getMapping(), new TreeMap<CharSequence, U>()));
        System.out.println("Searching in: {" + originalText + "} with filter=" + filter);
        // Dictionaries are immutable, so we create a Matcher to search/test text.
        Matcher<U> matcher = dictionary.getMatcher();
        matcher.setText(charListText);
        while (true) {
            Status status = matcher.find(filter);
            String unique = ""; // only set if needed
            if (status == Status.NONE) {
                break;
            } else if (status == Status.PARTIAL) {
                // sets the match value to the "first" partial match
                if (matcher.nextUniquePartial()) {
                    unique = "\tUnique";
                } else {
                    unique = "\tNot Unique";
                }
            }
            // Show results
            System.out.println("{"
                + showBoth(charListText, 0, matcher.getOffset()) + "[["
                + showBoth(charListText, matcher.getOffset(), matcher.getMatchEnd())
                + "]]" + showBoth(charListText, matcher.getMatchEnd(), charListText.getKnownLength())
                + "}\t" + status + "  \t{" + matcher.getMatchValue() + "}\t" + unique);
        }
        System.out.println();
    }

    static public CharSequence showBoth(CharSource source, int start, int end) {
        if (source instanceof CharSourceWrapper) {
            CharSourceWrapper new_name = (CharSourceWrapper) source;
            return new_name.sourceSubSequence(start, end);
        }
        return source.subSequence(start, end);
    }

    private void showDictionaryContents() {
        // build stuff to use from now on
        simpleDictionary = simpleDictionaryBuilder.make(baseMapping);
        simpleMatcher = simpleDictionary.getMatcher();
        stateDictionary = stateDictionaryBuilder.make(baseMapping);
        stateMatcher = stateDictionary.getMatcher();
        baseMapping.clear();

        // ((Dictionary.Builder) simpleDictionary).addMapping(string, i);
        // ((Dictionary.Builder) stateDictionary).addMapping(string, i);

        System.out.println("Dictionary: "
            + Dictionary.load(stateDictionary.getMapping(), new TreeMap<CharSequence, T>()));
        System.out.println();
        if (SHOW_STATES) {
            System.out.println("States:" + CldrUtility.LINE_SEPARATOR + stateDictionary);
            System.out.println();
        }
        if (SHOW_CONTENTS) {
            System.out.println("Structure:" + CldrUtility.LINE_SEPARATOR + stateDictionary.debugShow());
            System.out.println();
        }
    }

    @SuppressWarnings("unchecked")
    private void testWithUnicodeNames() {
        UnicodeSet testSet = new UnicodeSet(
            "[[:assigned:] - [:ideographic:] - [:Co:] - [:Cs:]]"); // &
        // [\\u0000-\\u0FFF]
        int count = 0;
        Map<String, T> data = new TreeMap<String, T>();
        for (UnicodeSetIterator it = new UnicodeSetIterator(testSet); it.next();) {
            String name = UCharacter.getExtendedName(it.codepoint);
            if (name == null) {
                continue;
            }
            if ((++count & 0xFF) == 0) {
                System.out.println(count + ":\t"
                    + com.ibm.icu.impl.Utility.hex(it.codepoint) + "\t" + name);
            }
            data.put(name, (T) com.ibm.icu.impl.Utility.hex(it.codepoint, 4));
        }
        count = 0;
        for (String item : data.keySet()) {
            if (SHORT_TEST && count++ > 500) continue; //
            addToBoth(item, data.get(item));
        }
        simpleDictionary = simpleDictionaryBuilder.make(baseMapping);
        stateDictionary = stateDictionaryBuilder.make(baseMapping);
        baseMapping.clear();
        compare();
    }

    private void compare() {
        System.out.println("Comparing results: ");

        Map<CharSequence, T> dictionaryData = Dictionary.load(stateDictionary.getMapping(),
            new HashMap<CharSequence, T>());
        Map<CharSequence, T> simpleDictionaryData = Dictionary.load(simpleDictionary.getMapping(),
            new HashMap<CharSequence, T>());

        assert dictionaryData.equals(simpleDictionaryData) : showDifference(dictionaryData, simpleDictionaryData);
        if (SHOW_STATES) {
            System.out.println("Size: " + dictionaryData.size());
            System.out.println("Rows: "
                + ((StateDictionary<T>) stateDictionary).getRowCount());
        }

        System.out.println("Checking values: state dictionary");
        checkSimpleMatches(stateMatcher, dictionaryData);
        System.out.println("Checking values: simple dictionary");
        checkSimpleMatches(simpleMatcher, simpleDictionaryData);
        int count = 0;
        System.out.println("Cross-checking all values");
        for (CharSequence myText : simpleDictionaryData.keySet()) {
            if ((++count & 0xFF) == 0xFF) {
                System.out.println(count + ":\t" + myText);
            }
            crossCheck(new CharSourceWrapper<CharSequence>(myText));
            crossCheck("!" + myText);
            crossCheck(myText + "!");
        }
    }

    private String showDifference(Map<CharSequence, T> dictionaryData, Map<CharSequence, T> simpleDictionaryData) {
        System.out.println(dictionaryData.size() + ", " + simpleDictionaryData.size());
        Iterator<Entry<CharSequence, T>> it1 = dictionaryData.entrySet().iterator();
        Iterator<Entry<CharSequence, T>> it2 = simpleDictionaryData.entrySet().iterator();
        while (it1.hasNext() || it2.hasNext()) {
            Entry<CharSequence, T> item1 = it1.hasNext() ? it1.next() : null;
            Entry<CharSequence, T> item2 = it2.hasNext() ? it2.next() : null;
            System.out.println(item1 + ", " + item2);
            if (item1 == null || item2 == null || !item1.equals(item2)) {
                return item1 + "!=" + item2;
            }
        }
        return "no difference";
    }

    private void crossCheck(CharSequence myText) {
        crossCheck(new CharSourceWrapper<CharSequence>(myText));
    }

    private void crossCheck(CharSource myText) {
        stateMatcher.setText(myText); // set the text to operate on
        simpleMatcher.setText(myText); // set the text to operate on
        for (int i = 0; stateMatcher.getText().hasCharAt(i); ++i) {
            stateMatcher.setOffset(i);
            simpleMatcher.setOffset(i);
            while (true) {
                Status stateStatus = stateMatcher.next();
                Status simpleStatus = simpleMatcher.next();
                assert stateStatus == simpleStatus : showValues(stateStatus, simpleStatus);
                final int stateEnd = stateMatcher.getMatchEnd();
                final int simpleEnd = simpleMatcher.getMatchEnd();
                assert stateEnd == simpleEnd : showValues(stateStatus, simpleStatus);
                if (stateStatus == Status.PARTIAL) {
                    boolean stateUnique = stateMatcher.nextUniquePartial();
                    boolean simpleUnique = simpleMatcher.nextUniquePartial();
                    assert stateUnique == simpleUnique : showValues(stateStatus, simpleStatus);
                }
                // test this after checking PARTIAL
                assert stateMatcher.getMatchValue() == simpleMatcher.getMatchValue() : showValues(stateStatus,
                    simpleStatus);
                if (stateStatus != Status.MATCH) {
                    break;
                }
            }
        }
    }

    private String showValues(Status stateStatus, Status simpleStatus) {
        return CldrUtility.LINE_SEPARATOR + "TEXT:\t" + stateMatcher.text + CldrUtility.LINE_SEPARATOR + "STATE:\t"
            + showValues(stateStatus, stateMatcher) + CldrUtility.LINE_SEPARATOR + "SIMPLE:\t"
            + showValues(simpleStatus, simpleMatcher);
    }

    private String showValues(Status status, Matcher<T> matcher) {
        boolean uniquePartial = status == Status.PARTIAL && matcher.nextUniquePartial(); // sets matchValue for PARTIAL
        return String.format("\tOffsets: %s,%s\tStatus: %s\tString: \"%s\"\tValue: %s %s",
            matcher.getOffset(),
            matcher.getMatchEnd(),
            status,
            matcher.getMatchText(),
            matcher.getMatchValue(),
            status == Status.PARTIAL && uniquePartial ? "\tUNIQUE" : "");
    }

    /**
     * Check that the words all match against themselves.
     *
     * @param matcher
     * @param data
     */
    private void checkSimpleMatches(Matcher<T> matcher, Map<CharSequence, T> data) {
        int count = 0;
        for (CharSequence myText : data.keySet()) {
            if ((count++ & 0xFF) == 0xFF) {
                System.out.println(count + ":\t" + myText);
            }
            matcher.setText(myText); // set the text to operate on

            matcher.setOffset(0);
            int matchEnd = -1;
            T matchValue = null;
            // find the longest match
            while (true) {
                Dictionary.Matcher.Status next1 = matcher.next();
                if (next1 == Dictionary.Matcher.Status.MATCH) {
                    matchEnd = matcher.getMatchEnd();
                    matchValue = matcher.getMatchValue();
                } else {
                    break;
                }
            }
            assert matchEnd == myText.length() : "failed to find end of <" + myText + "> got instead " + matchEnd;
            assert matchValue == data.get(myText);
        }
    }

    @SuppressWarnings("unchecked")
    private void addToBoth(CharSequence string, int i) {
        baseMapping.put(string, (T) (i + "/" + string));
    }

    private void addToBoth(CharSequence string, T i) {
        baseMapping.put(string, i);
        // if (simpleDictionary.contains(string)) return;
        // if (!stateDictionary.contains(string)) {
        // stateDictionary.contains(string);
        // }
        // assert stateDictionary.contains(string);
    }

    private void showWords(String myText) {
        System.out.format("Finding words in: \"%s\"" + CldrUtility.LINE_SEPARATOR, myText);
        if (SIMPLE_ONLY) {
            showWords("", simpleMatcher, myText);
        } else {
            Set<String> simpleResult = showWords("Simple", simpleMatcher, myText);
            Set<String> stateResult = showWords("STATE", stateMatcher, myText);
            if (!simpleResult.equals(stateResult)) {
                // repeat, for debugging
                System.out.println("  DIFFERENCE");
                showWords("Simple", simpleMatcher, myText);
                showWords("STATE", stateMatcher, myText);
                Set<String> simpleMinusState = new LinkedHashSet<String>(simpleResult);
                simpleMinusState.removeAll(stateResult);
                System.out.println("Simple-State" + simpleMinusState);
                Set<String> stateMinusSimple = new LinkedHashSet<String>(stateResult);
                stateMinusSimple.removeAll(simpleResult);
                System.out.println("State-Simple" + stateMinusSimple);
            }
        }
    }

    private Set<String> showWords(String title, Matcher<T> matcher, String myText) {
        title = title.equals("") ? "" : "\tType: " + title;
        // Walk through a strings and gather information about what we find
        // according to the matcher
        Set<String> result = new LinkedHashSet<String>();
        // Set the text to operate on
        matcher.setText(myText);
        boolean uniquePartial = false;
        for (int i = 0; matcher.hasCharAt(i); ++i) {
            matcher.setOffset(i);
            Status status;
            // We might get multiple matches at each point, so walk through all of
            // them. The last one might be a partial, so collect some extra
            // information in that case.
            do {
                // Sets matchValue if there is a MATCH
                status = matcher.next();
                if (status == Status.PARTIAL) {
                    // Sets matchValue if the next() status was PARTIAL
                    uniquePartial = matcher.nextUniquePartial();
                }
                // Format all of the information
                String info = String.format(
                    "\tOffsets: %s,%s\tStatus: %s\tString: \"%s\"\tValue: %s%s", //
                    matcher.getOffset(), matcher.getMatchEnd(), status, //
                    matcher.getMatchText(), matcher.getMatchValue(), //
                    status == Status.PARTIAL && uniquePartial ? "\tUNIQUE" : "");
                result.add(info);
                if (status != Status.NONE) {
                    // If there was a match or partial match, show what we got
                    System.out.println(title + info);
                }
            } while (status == Status.MATCH);
        }
        return result;
    }
}