Debian Codegraph @

extensions/Math/tests/phpunit/unit/WikiTexVC/MMLComparator.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\Math\WikiTexVC\MMLmappings\Util;
4
5 use MediaWiki\Extension\Math\WikiTexVC\XMLNode;
6
7 /**
8 * Algorithm to make a simple, but customizable comparison of two MathML-Strings for automated testing.
9 * It compares all element keys in the tree without order and calculates an F-score based on similarity.
10 * Also, it gives information the elements which differ both trees.
11 *
12 * @author Johannes Stegmüller
13 */
14 class MMLComparator {
15
16 /**
17 * These keys for mathml-elements get not
18 * considered for similarity comparison.
19 */
20 private const IGNOREDELEMENTKEYS = [
21 "semantics",
22 "annotation",
23 "annotation-xml",
24 "csymbol",
25 "mrow",
26 "mstyle"
27 ];
28
29 /**
30 * Although the keys mentioned here may be on the ignore list.
31 * Keys containing one of the specific attribute get checked.
32 */
33 private const CHECKEXPLICITLY = [
34 "mstyle" => [ "mathcolor" ]
35 ];
36
37 /**
38 * Attributes which are not considered for similarity checks.
39 * Attributes are always defined for a specific mathml key.
40 */
41 private const IGNOREDATTRIBUTES = [
42 "mrow" => [ "class", "data-mjx-texclass" ],
43 "math" => [ "alttext", "display" ],
44 "mi" => [ "class", "data-mjx-variant", "mathvariant", "data-mjx-texclass", "data-mjx-alternate" ],
45 "mo" => [ "data-mjx-pseudoscript", "stretchy", "fence", "data-mjx-texclass", "texClass", "class",
46 "data-mjx-alternate", "form", "accent", "lspace", "rspace", "xref", "id" ],
47 "mtext" => [ "texClass", "class" ],
48 "mspace" => [ "width" ]
49 ];
50
51 public static function functionObtainTreeInBrackets( string $mml ): string {
52 $xml = simplexml_load_string( $mml );
53 $nodes = self::xmlToNode( $xml );
54 return self::convertToBracketFormat( $nodes );
55 }
56
57 /**
58 * Compares the base to the comparison MathML.
59 * The base is considered the reference MathML. Calculates an F-Score for similarity of elements.
60 * MathML elements which are not considered for similarity checks can be specified within this class.
61 * Gives back the differing elements relative to the base.
62 * If any issue with the input, the returned F-Score has value '-0.0'
63 *
64 * @param string $mmlBase MathML base element as string
65 * @param string $mmlComp MathML comparison element as string
66 * @return array with 'similarityF': Calculated F-Score for similarity, 'more/less': diffs relative to the base.
67 */
68 public function compareMathML( $mmlBase, $mmlComp ): array {
69 $compRes = [
70 "similarityF" => -0.0,
71 "more" => [],
72 "less" => []
73 ];
74
75 if ( !$mmlBase || !$mmlComp || trim( $mmlBase ) == "" || trim( $mmlComp ) == "" ) {
76 return $compRes;
77 }
78
79 $xmlBase = simplexml_load_string( $mmlBase );
80 $xmlComp = simplexml_load_string( $mmlComp );
81
82 // Create flattened Arrays of MathML
83 $mbase = $this->createComparisonArray( $xmlBase );
84 $mcomp = $this->createComparisonArray( $xmlComp );
85
86 // Compare base and comp arrays, tbd: eventually extract this function
87 $countsBase = $this->countArraySize( $mbase );
88 $countsComp = $this->countArraySize( $mcomp );
89 $overallRelevantSum = $countsBase[0];
90 $overallRetrievedSum = $countsComp[0];
91
92 $ctrSame = $this->compareMathMLKeyArrays( $compRes, $mbase, $mcomp );
93
94 $compRes['similarityF'] = $this->calculateFscore( $ctrSame, $overallRelevantSum, $overallRetrievedSum );
95 return $compRes;
96 }
97
98 public static function xmlToNode( \SimpleXMLElement $xml ): XMLNode {
99 $node = new XMLNode( $xml->getName() );
100
101 foreach ( $xml->children() as $child ) {
102 $node->children[] = self::xmlToNode( $child );
103 }
104
105 return $node;
106 }
107
108 private function treeEditDistance( XMLNode $root1, XMLNode $root2 ): array {
109 $n = count( $root1->children );
110 $m = count( $root2->children );
111
112 $dp = [];
113 for ( $i = 0; $i <= $n; $i++ ) {
114 $dp[$i] = [];
115 for ( $j = 0; $j <= $m; $j++ ) {
116 $dp[$i][$j] = 0;
117 }
118 }
119
120 for ( $i = 0; $i <= $n; $i++ ) {
121 for ( $j = 0; $j <= $m; $j++ ) {
122 if ( $i == 0 ) {
123 $dp[$i][$j] = $j;
124 } elseif ( $j == 0 ) {
125 $dp[$i][$j] = $i;
126 } elseif ( $root1->children[$i - 1]->value == $root2->children[$j - 1]->value ) {
127 $dp[$i][$j] = $dp[$i - 1][$j - 1];
128 } else {
129 $dp[$i][$j] = 1 + min(
130 $dp[$i][$j - 1], // Insert
131 $dp[$i - 1][$j], // Remove
132 $dp[$i - 1][$j - 1] // Replace
133 );
134 }
135 }
136 }
137
138 $ted = $dp[$n][$m];
139 $totalNodes = $n + $m; // Total nodes in both trees
140 if ( $totalNodes != 0 ) {
141 $normalizedTED = $ted / $totalNodes;
142 } else {
143 $normalizedTED = -1;
144 }
145
146 return [ "TED" => $ted, "normalizedTED" => $normalizedTED ];
147 }
148
149 public static function convertToBracketFormat( \SimpleXMLElement $root ): string {
150 if ( empty( $root->children ) ) {
151 return "{" . $root->value . "}";
152 }
153
154 $result = $root->value . '{';
155
156 foreach ( $root->children as $child ) {
157 $result .= self::convertToBracketFormat( $child );
158 }
159
160 $result .= '}';
161 return $result;
162 }
163
164 private function compareMathMLKeyArrays( array &$compRes, array $mbase, array $mcomp ): int {
165 $intersections = 0;
166 foreach ( $mbase as $key => $baseElement ) {
167 $compElement = $mcomp[$key] ?? null;
168 if ( $compElement == null ) {
169 // The base has this mml element(s), but not the comparison
170 continue;
171 }
172 $compRet = $this->compareArrays( $baseElement, $compElement );
173 $intersections += $compRet['sameCtr'];
174 if ( count( $compRet['more'] ) > 0 ) {
175 $compRes['more'][$key] = $compRet['more'];
176 }
177 if ( count( $compRet['less'] ) > 0 ) {
178 $compRes['less'][$key] = $compRet['less'];
179 }
180 }
181 return $intersections;
182 }
183
184 private function calculateFscore( int $intersection, int $sumRelevant, int $sumRetrieved ): float {
185 if ( $sumRelevant == 0 && $sumRetrieved == 0 ) {
186 return 1.0;
187 }
188
189 if ( $sumRetrieved == 0 && $sumRelevant != 0 ) {
190 return 0;
191 }
192
193 if ( $sumRelevant == 0 && $sumRetrieved != 0 ) {
194 $recall = 1;
195 } else {
196 $recall = $intersection / $sumRelevant;
197 }
198
199 $prec = $intersection / $sumRetrieved;
200 if ( ( $prec + $recall ) == 0 ) {
201 return 0;
202 }
203 // Calculate F-Score
204 return 2 * ( ( $prec * $recall ) / ( $prec + $recall ) );
205 }
206
207 private function countArraySize( array $arr ): array {
208 $overallSize = 0;
209 $overallAttrs = 0;
210 foreach ( $arr as $element ) {
211 foreach ( $element as $attrs ) {
212 $overallSize += 1;
213 $overallAttrs += count( $attrs );
214 }
215 }
216
217 return [ $overallSize, $overallAttrs ];
218 }
219
220 private function compareArrays( array $base, array $comp ): array {
221 $sameCtr = 0;
222 $compRet = [
223 "sameCtr" => 0,
224 "less" => [],
225 "more" => [],
226 ];
227
228 // Return score how many same or very similar items are in array
229 foreach ( $base as $keyBase => $baseEl ) {
230 foreach ( $comp as $keyComp => $compEl ) {
231 if ( $compEl == -1 ) {
232 continue;
233 }
234 if ( $this->compareTwoBaseElements( $compEl, $baseEl ) ) {
235 $base[$keyBase] = -1;
236 $comp[$keyComp] = -1;
237 $sameCtr += 1;
238 break;
239 }
240 }
241 }
242 $compRet['sameCtr'] = $sameCtr;
243 $compRet = $this->addRemainingElements( $compRet, 'less', $base );
244 return $this->addRemainingElements( $compRet, 'more', $comp );
245 }
246
247 private function addRemainingElements( array $compRet, string $key, array $data ): array {
248 foreach ( $data as $el ) {
249 if ( $el !== null && $el != -1 ) {
250 $compRet[$key][] = $el;
251 }
252 }
253 return $compRet;
254 }
255
256 private function compareTwoBaseElements( array $compEl, array $baseEl ): bool {
257 // Most basic comparison, this works for elements without attributes
258 if ( $compEl === $baseEl ) {
259 return true;
260 }
261 // The array and sub-elements are exactly the same
262 if ( array_diff( $compEl, $baseEl ) == [] && array_diff( $baseEl, $compEl ) == [] ) {
263 return true;
264 }
265
266 return false;
267 }
268
269 private function createComparisonArray( \SimpleXMLElement $xml ): array {
270 $allKeys = [];
271 $this->prepareMMLElements( $xml, $allKeys );
272 $finalMMLKeys = $this->filterKeys( $allKeys );
273 return $finalMMLKeys;
274 }
275
276 private function filterKeys( array $allMMLElements ): array {
277 $finalKeys = [];
278 foreach ( $allMMLElements as $key => $element ) {
279 if ( in_array( $key, self::IGNOREDELEMENTKEYS, true ) ) {
280 $finalKeys = $this->checkExplicitKeys( $key, $element, $finalKeys );
281 continue;
282 }
283 $finalKeys[$key] = $element;
284 }
285 return $finalKeys;
286 }
287
288 private function prepareMMLElements( \SimpleXMLElement $xml, array &$finalArray, bool $alwaysSetVal = false ) {
289 foreach ( $xml as $key => $element ) {
290 if ( $element instanceof \SimpleXMLElement ) {
291 $el = $this->filterAttributes( $key, $element->attributes() );
292 $value = trim( (string)$element );
293 if ( $alwaysSetVal || $value !== "" ) {
294 $el["val"] = $value;
295 }
296 $finalArray[$key][] = $el ?? [];
297
298 } else {
299 $finalArray[$key][] = $element;
300 }
301 $this->prepareMMLElements( $element, $finalArray );
302 }
303 }
304
305 private function filterAttributes( string $elementKey, \SimpleXMLElement $attributes ): array {
306 $ignoredAttrs = self::IGNOREDATTRIBUTES[$elementKey] ?? [];
307 $finalAttributes = [];
308 foreach ( $attributes as $akey => $aval ) {
309
310 if ( in_array( $akey, $ignoredAttrs, true ) ) {
311 continue;
312 }
313 $finalAttributes[$akey] = $aval[0];
314 }
315 return $finalAttributes;
316 }
317
318 private function checkExplicitKeys( string $key, array $element, array $finalKeys ): array {
319 $check = self::CHECKEXPLICITLY[$key] ?? null;
320 if ( $check ) {
321 foreach ( $element as $added ) {
322 foreach ( $check as $checkEl ) {
323 if ( array_key_exists( $checkEl, $added ) ) {
324 $finalKeys[$key] = $element;
325 }
326 }
327
328 }
329 }
330 return $finalKeys;
331 }
332 }