-
Notifications
You must be signed in to change notification settings - Fork 95
/
JavaTriesWithFrequencies.m
301 lines (217 loc) · 11 KB
/
JavaTriesWithFrequencies.m
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
(*
Java tries with frequencies Mathematica package
Copyright (C) 2017 Anton Antonov
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written by Anton Antonov,
antononcube @ gmai l . c om,
Windermere, Florida, USA.
*)
(*
Mathematica is (C) Copyright 1988-2017 Wolfram Research, Inc.
Protected by copyright law and international treaties.
Unauthorized reproduction or distribution subject to severe civil
and criminal penalties.
Mathematica is a registered trademark of Wolfram Research, Inc.
*)
(* :Title: JavaTriesWithFrequencies *)
(* :Context: JavaTriesWithFrequencies` *)
(* :Author: antonov *)
(* :Date: 2017-01-08 *)
(* :Package Version: 1.0 *)
(* :Mathematica Version: *)
(* :Copyright: (c) 2017 Anton Antonov *)
(* :Keywords: prefix tree, trie, Java, Mathematica, Wolfram Language *)
(* :Discussion:
This package provides Mathematica functions for easier use of the Java implementation of tries with frequencies:
https://github.com/antononcube/MathematicaForPrediction/tree/master/Java/TriesWithFrequencies
Although the functions in this package are very close to the ones in the Mathematica package TriesWithFrequencies.m:
https://github.com/antononcube/MathematicaForPrediction/blob/master/TriesWithFrequencies.m
the functions in this package can be used indepenedently of TriesWithFrequencies.m -- that is why I made this
separate package.
This package can convert the Java tries to JSON, and TriesWithFrequencies.m can convert JSON experessions to tries.
Therefore, functions of TriesWithFrequencies.m (like TrieForm) can be used over the tries made with this package.
Before using the package there are two necessary steps:
1. the building of the jar file TriesWithFrequencies.jar, and
2. the appropriate Java installation in Mathematica.
Prescriptions for Step 1 are given in :
https://github.com/antononcube/MathematicaForPrediction/blob/master/Java/TriesWithFrequencies/README.md
Here is the Mathematica code for Step 2:
AppendTo[$Path, "/Users/antonov/MathFiles/MathematicaForPrediction"];
Needs["JavaTriesWithFrequencies`"]
$JavaTriesWithFrequenciesPath =
"/Users/antonov/MathFiles/MathematicaForPrediction/Java/TriesWithFrequencies";
JavaTrieInstall[$JavaTriesWithFrequenciesPath]
Several examples of building tries and operations over them follow.
words = {"barks", "barkers", "barked", "barkeeps", "barkeepers", "barking"};
jTr = JavaTrieCreateBySplit[words];
JavaTrieCompleteMatch[jTr, Characters@"bark"]
(* False *)
JavaTrieContains[jTr, Characters@"barked"]
(* True *)
JavaTrieToJSON@JavaTrieShrink@jTr
(* {"value" -> 6., "key" -> "",
"children" -> {{"value" -> 6., "key" -> "ba",
"children" -> {{"value" -> 7., "key" -> "r",
"children" -> {{"value" -> 6., "key" -> "k",
"children" -> {{"value" -> 1., "key" -> "s",
"children" -> {}}, {"value" -> 1., "key" -> "ing",
"children" -> {}}, {"value" -> 4., "key" -> "e",
"children" -> {{"value" -> 1., "key" -> "rs",
"children" -> {}}, {"value" -> 1., "key" -> "d",
"children" -> {}}, {"value" -> 2., "key" -> "ep",
"children" -> {{"value" -> 1., "key" -> "s",
"children" -> {}}, {"value" -> 1., "key" -> "ers",
"children" -> {}}}}}}}}}}}}}} *)
For more usage examples see the corresponding unit tests file:
https://github.com/antononcube/MathematicaForPrediction/blob/master/UnitTests/JavaTriesWithFrequencies-Unit-Tests.wlt
Anton Antonov
Windermere, FL
January 2017
*)
(* This file was created with the Mathematica plug-in for IntelliJ IDEA. *)
BeginPackage["JavaTriesWithFrequencies`"]
JavaTrieClone::usage = "JavaTrieClone[ jTr ] makes a deep clone of a given Java trie."
JavaTrieCompleteMatch::usage = "JavaTrieCompleteMatch[ jTr_, sw:{_String..}] finds is fraction\
of the list of strings sw a complete match in the Java trie jTr."
JavaTrieContains::usage = "JavaTrieContains[ jTr_, sw:{_String..}] finds is the list of strings\
sw a complete match in the Java trie jTr."
JavaTrieCreate::usage = "JavaTrieCreate[ ws:{{_String..}..}] creates a Java trie object from a list of string lists."
JavaTrieCreateBySplit::usage = "JavaTrieCreate[ ws:{_String..}, regex_String:\"\"] creates a Java trie object\
from a list of strings that are split with a given regex."
JavaTrieEqualQ::usage = "JavaTrieEqualQ[ jTr1, jTr2] compares two Java tries and returns True if\
the tries have the same shape and all corresponding keys and values are the same."
JavaTrieGetWords::usage = "JavaTrieGetWords[ jTr_, sw:{_String..}] gives a list words in jTr that start with sw."
JavaTrieInsert::usage = "JavaTrieInsert[ jTr_, sw:{_String..}] inserts a list of strings into the Java trie jTr.\
JavaTrieInsert[ jTr_, sws:{{_String..}..}] inserts each of the \"words\" of sws into jTr."
JavaTrieInstall::usage = "JavaTrieInstall[path_String] installs Java and loads the JavaTrie classes\
from the jar file in the specified class path."
JavaTrieMapOptimizationCall::usage = "Used for optimization calls over lists of \"words\"."
JavaTrieMemberQ::usage = "Same as JavaTrieContains."
JavaTrieMerge::usage = "Merges two Java tries."
JavaTrieNodeCounts::usage = "Returns the node counts in trie (total, internal, leaves.)"
JavaTrieNodeProbabilities::usage = "Gives the corresponding Java trie with node frequencies converted\
to probabilities."
JavaTrieRetrieve::usage = "JavaTrieRetrieve[ jTr_, sw:{_String..}] retrieves the sub-trie in jTr\
that corresponds to sw. Note that only a leading part of sw can be found jTr. \
The last found element of sw is the root of the returned sub-trie."
JavaTrieRootToLeafPaths::usage = "Gives lists of key-value pairs corresponding to the root-to-leaf paths\
in a given trie."
JavaTrieShrink::usage = "JavaTrieShrink[ jTr_, sep_String:\"\"] concatenates the \"single path\" nodes\
in the trie jTr using the given separator sep."
JavaTrieToJSON::usage = "Converts a Java trie to a corresponding JSON expression."
Begin["`Private`"]
Needs["JLink`"]
Clear[JavaTrieClone]
JavaTrieClone[ jTr_?JavaObjectQ ] := jTr@clone[];
Clear[JavaTrieCreateBySplit]
JavaTrieCreateBySplit[words : {_String ..}, regex_String: ""] :=
Block[{jWords, jSp},
jWords = MakeJavaObject[words];
jWords = Arrays`asList[jWords];
jSp = MakeJavaObject[regex];
TrieFunctions`createBySplit[jWords, jSp]
];
JavaTrieCreateBySplit[ swords : {{_String ..} ..}, regex_String: "®ø®"] :=
Block[{jWords, jSp},
jWords = MakeJavaObject[Map[StringJoin @@ Riffle[#, regex] &, swords]];
jWords = Arrays`asList[jWords];
jSp = MakeJavaObject[regex];
TrieFunctions`createBySplit[jWords, jSp]
];
Clear[JavaTrieCreate]
JavaTrieCreate[swords : {{_String ..} ..}] :=
Block[{jWords, jW},
jWords = JavaNew["java.util.ArrayList"];
Do[
jW = JavaNew["java.util.ArrayList"];
jW@add[MakeJavaObject@#] & /@ wl;
jWords@add[jW],
{wl, swords}];
TrieFunctions`create[jWords]
];
Clear[JavaTrieEqualQ]
JavaTrieEqualQ[ jTr1_?JavaObjectQ, jTr2_?JavaObjectQ ] := jTr1@equals[ jTr2 ];
Clear[JavaTrieMerge]
JavaTrieMerge[jTr1_?JavaObjectQ, jTr2_?JavaObjectQ] :=
TrieFunctions`merge[jTr1, jTr2];
Clear[JavaTrieInsert]
JavaTrieInsert[jTr_?JavaObjectQ, word : {_String ..}] :=
TrieFunctions`insert[jTr, Arrays`asList[MakeJavaObject[word]]];
JavaTrieInsert[jTr_?JavaObjectQ, words : {{_String ..} ..}] :=
Block[{jTr2},
jTr2 = JavaTrieCreate[words];
TrieFunctions`merge[jTr, jTr2]
];
Clear[JavaTrieInstall]
JavaTrieInstall[path_String, opts:OptionsPattern[]] :=
Block[{},
Needs["JLink`"];
JLink`AddToClassPath[path];
If[ Length[{opts}] > 0,
JLink`ReinstallJava[opts],
JLink`ReinstallJava[JLink`JVMArguments -> "-Xmx2g"]
];
JLink`LoadJavaClass["java.util.Collections"];
JLink`LoadJavaClass["java.util.Arrays"];
JLink`LoadJavaClass["Trie"];
JLink`LoadJavaClass["TrieFunctions"];
];
Clear[JavaTrieNodeCounts]
JavaTrieNodeCounts[jTr_?JavaObjectQ] :=
AssociationThread[{"total","internal","leaves"}->JLink`JavaObjectToExpression[TrieFunctions`nodeCounts[jTr]]];
Clear[JavaTrieNodeProbabilities]
JavaTrieNodeProbabilities[jTr_?JavaObjectQ] :=
TrieFunctions`nodeProbabilities[jTr];
Clear[JavaTrieShrink]
JavaTrieShrink[jTr_?JavaObjectQ, sep_String: ""] := TrieFunctions`shrink[jTr, sep];
Clear[JavaTrieToJSON]
JavaTrieToJSON[jTr_?JavaObjectQ] := ImportString[jTr@toJSON[], "JSON"];
Clear[JavaTrieRetrieve]
JavaTrieRetrieve[jTr_?JavaObjectQ, sword : {_String ..}] :=
TrieFunctions`retrieve[jTr, Arrays`asList[MakeJavaObject[sword]]];
JavaTrieRetrieve[jTr_?JavaObjectQ, swords : {{_String ..} ..}] :=
JavaTrieMapOptimizationCall[TrieFunctions`mapRetrieve, jTr, swords];
Clear[JavaTrieCompleteMatch]
JavaTrieCompleteMatch[jTr_?JavaObjectQ, sword : {_String ..}] :=
TrieFunctions`completeMatch[jTr, Arrays`asList[MakeJavaObject[sword]]];
JavaTrieCompleteMatch[jTr_?JavaObjectQ, swords : {{_String ..} ..}] :=
JavaTrieMapOptimizationCall[TrieFunctions`mapCompleteMatch, jTr, swords];
Clear[JavaTrieContains]
JavaTrieContains[jTr_?JavaObjectQ, sword : {_String ..}] :=
TrieFunctions`contains[jTr, Arrays`asList[MakeJavaObject[sword]]];
JavaTrieContains[jTr_?JavaObjectQ, swords : {{_String ..} ..}] :=
JavaTrieMapOptimizationCall[TrieFunctions`mapContains, jTr, swords];
JavaTrieMemberQ = JavaTrieContains;
Clear[JavaTrieMapOptimizationCall]
JavaTrieMapOptimizationCall[func_, jTr_?JavaObjectQ,
swords : {{_String ..} ..}, splitRegex_String: "®ø®"] :=
Block[{jWords},
(*jWords=MakeJavaObject[Map[StringRiffle[#,splitRegex]&,swords]];*)(* 3 times slower*)
jWords = MakeJavaObject[Map[StringJoin @@ Riffle[#, splitRegex] &, swords]];
jWords = Arrays`asList[jWords];
jWords = TrieFunctions`splitWords[jWords, splitRegex];
func[jTr, jWords]
];
Clear[JavaTrieGetWords]
JavaTrieGetWords[jTr_?JavaObjectQ, sword : {_String ..}] :=
Block[{res},
res = JavaObjectToExpression /@
JavaObjectToExpression[
TrieFunctions`getWords[jTr, Arrays`asList[MakeJavaObject[sword]]]];
If[res === Null, {}, res]
];
Clear[JavaTrieRootToLeafPaths]
JavaTrieRootToLeafPaths[jTr_?JavaObjectQ] :=
Map[{"key", "value"} /. # &,
ImportString[TrieFunctions`pathsToJSON[TrieFunctions`rootToLeafPaths[jTr]], "JSON"], {2}];
End[] (* `Private` *)
EndPackage[]