Blame view

src/InputOutput/IHMImpl/Tools/IHMExpressionParserClass.php 24.8 KB
22521f1c   Benjamin Renard   First commit
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
<?php

/**
 * @class IHMExpressionParserClass
 * @brief Parser for IHM expression
 * @details
 */
class IHMExpressionParserClass
{
	//constants
	private static $constantTag     = '@';
	private static $constantNode    = 'constant';
	private static $constantNameAtt = 'name';

	//aliases
	private static $aliasTag     = '#';
	private static $aliasNode    = 'alias';
	private static $aliasNameAtt = 'name';

	//functions
	private static $functionsNode    = 'function';
	private static $functionsNameAtt = 'name';
	private static $functionsArgsAtt = 'args';
	private static $functionsNewKernelNode = 'new_kernel';

	//operator
	private static $operators = array(
			//standard operators
			"+" => array("type" => "operator"),
			"-" => array("type" => "operator"),
			"*" => array("type" => "operator"),
			"/" => array("type" => "operator"),
			//operators that's need to be translate by a function for the kernel
			"^" => array("type" => "function", "function" => "pow"),
			"<" => array("type" => "function", "function" => "lower_than"),
			">" => array("type" => "function", "function" => "greater_than"),
			"&" => array("type" => "function", "function" => "And"),
			"|" => array("type" => "function", "function" => "Or")
	);

	private $constantsArray;

	private $aliasesArray;

	private $functionsArray;
e4545ed5   Benjamin Renard   Implement templat...
46
47
	
	private $templatedParamMgr = NULL;
ffc5cb81   Elena.Budnik   temporary commit
48
	private $impexParamMgr = NULL;
f25e55ba   Benjamin Renard   Add sum in table ...
49
50
	
	private $isTest = FALSE;
22521f1c   Benjamin Renard   First commit
51
52
53
54

	/*
	 * @brief Constructor
	*/
f25e55ba   Benjamin Renard   Add sum in table ...
55
	function __construct($isTest = FALSE)
22521f1c   Benjamin Renard   First commit
56
	{
f25e55ba   Benjamin Renard   Add sum in table ...
57
58
59
		$this->isTest = $isTest;
		if (!$isTest)
			$this->templatedParamMgr = new IHMParamTemplateClass();
22521f1c   Benjamin Renard   First commit
60
61
62
63
64
65
66
67
68
	}

	/*
	 * @brief test function
	*/
	public function test()
	{
		//tests
		$tests = array(
9dbbc3b0   Benjamin Renard   Fix expression pa...
69
70
71
72
73
				"dst>3" => array ("expression" => "greater_than(\$dst,3)", "params" => array(array("paramid" => "dst"))),
				"@const_1<dst" => array("expression" => "lower_than(1.0E-10,\$dst)", "params" => array(array("paramid" =>"dst"))),
				"dst^#alias_2" => array("expression" => "pow(\$dst,\$imf[1])", "params" => array(array("paramid" => "dst"),array("paramid" => "imf"))),
				"dst^2+@const_2" => array("expression" => "pow(\$dst,2)+-2.8", "params" => array(array("paramid" => "dst"))),
				"atan(imf(2)/imf(1))+speed/100.0" => array("expression" => "(atan(\$imf[2]/\$imf[1]))+\$speed/100.0", "params" => array(array("paramid" => "imf"), array("paramid" => "speed"))),
8f40e2b8   Benjamin Renard   Fix expression pa...
74
75
76
77
78
				"shiftT_(clust1_hia_pad,60)" => array("expression" => "(#timeShift(\$clust1_hia_pad;60))", "params" => array(array("paramid" => "clust1_hia_pad"))),
				"smooth_(density,1200)" => array("expression" => "(#boxcar(\$density;1200))", "params" => array(array("paramid" => "density"))),
				"shiftT_(density,-600)" => array("expression" => "(#timeShift(\$density;-600))", "params" => array(array("paramid" => "density"))),
				"deriv(density)" => array("expression" => "(#deriv(\$density))", "params" => array(array("paramid" => "density"))),
				"abs(dst)" =>array("expression" => "(abs(\$dst))", "params" => array(array("paramid" => "dst"))),
9dbbc3b0   Benjamin Renard   Fix expression pa...
79
				"density*speed+(density^2-1.0)/speed" => array("expression" => "\$density*\$speed+(pow(\$density,2)-1.0)/\$speed", "params" => array(array("paramid" => "density"),array("paramid" => "speed"))),
f25e55ba   Benjamin Renard   Add sum in table ...
80
				"(-7<dst)&(dst<-3)" => array("expression" => "And((lower_than(-7,\$dst)),(lower_than(\$dst,-3)))", "params" => array(array("paramid" => "dst"))),
8f40e2b8   Benjamin Renard   Fix expression pa...
81
82
				"cass_caps_elssec4(range[0,10])" => array("expression" => "\$sum_into_table_range_cass_caps_elssec4_0_0_10", "params" => array(array("paramid" => "sum_into_table_range", "fullparamid" => "sum_into_table_range_cass_caps_elssec4_0_0_10", "template_args" => array("paramid"=>"cass_caps_elssec4","relateddim"=>0,"min"=>"0","max"=>"10")))),
				"abs(dst)>0" => array("expression" => "greater_than((abs(\$dst)),0)", "params" => array(array("paramid" => "dst"))),
9dbbc3b0   Benjamin Renard   Fix expression pa...
83
84
				"2/(1+dst)" => array("expression" => "2/(1+\$dst)", "params" => array(array("paramid" => "dst"))),
				"2/abs(1+dst)" => array("expression" => "2/(abs(1+\$dst))", "params" => array(array("paramid" => "dst"))),
22521f1c   Benjamin Renard   First commit
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
		);

		//init constants, aliases and functions for test
		$this->constantsArray = array(
				"@const_1" => 1e-10,
				"@const_2" => -2.8
		);

		$this->aliasesArray = array(
				"#alias_1" => "dst",
				"#alias_2" => "imf(1)"
		);

		$this->functionsArray = array(
				"func_old" => array("kernel_name" => "func_new", "nb_args" => 0),
				"atan" => array("kernel_name" => "atan", "nb_args" => 0),
				"shiftT_" => array("kernel_name" => "#timeShift", "nb_args" => 1),
				"smooth_" => array("kernel_name" => "#boxcar", "nb_args" => 1),
				"deriv" => array("kernel_name" => "#deriv", "nb_args" => 0),
8f40e2b8   Benjamin Renard   Fix expression pa...
104
				"abs" => array("kernel_name" => "abs", "nb_args" => 0),
9dbbc3b0   Benjamin Renard   Fix expression pa...
105
				"sqrt" => array("kernel_name" => "sqrt", "nb_args" => 0),
22521f1c   Benjamin Renard   First commit
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
		);

		//add operator to change in function
		foreach (self::$operators as $operator)
		{
			if ($operator["type"] == "function")
				$this->functionsArray[$operator["function"]] = 
					array("kernel_name" => $operator["function"], "nb_args" => 0);
		}

		//
		foreach ($tests as $key => $value)
		{
			echo "==> Test : ".$key.PHP_EOL;

			$res = $this->parse($key);
				
			echo "Result : ".$res["expression"].PHP_EOL;
				
			echo json_encode($value).PHP_EOL.json_encode($res).PHP_EOL;
				
			if (json_encode($value) == json_encode($res))
				echo "OK !".PHP_EOL;
			else
				echo "ERROR !".PHP_EOL;
		}
	}

	/*
	 * @brief main method to parse a IHM expression
	*/
	public function parse($expression)
	{
		//echo "Source expression : ".$expression.PHP_EOL;
		//clean expression and replace constants and aliases by associated value
		$this->clean($expression);
		$this->replaceConstants($expression);
		$this->replaceAliases($expression);
		$this->clean($expression);

		//explode expression
		$elements = $this->explodeExpression($expression);
8f40e2b8   Benjamin Renard   Fix expression pa...
148

22521f1c   Benjamin Renard   First commit
149
150
		//group elements in tree
		$tree = $this->buildTreeElements($elements);
8f40e2b8   Benjamin Renard   Fix expression pa...
151

22521f1c   Benjamin Renard   First commit
152
153
154
		//translate
		$params_full = array();
		$translated = $this->translate($tree,$params_full);
8f40e2b8   Benjamin Renard   Fix expression pa...
155

22521f1c   Benjamin Renard   First commit
156
157
		//keep only params id
		$params = array();
ffc5cb81   Elena.Budnik   temporary commit
158
		foreach ($params_full as $param_full) { 		 
f25e55ba   Benjamin Renard   Add sum in table ...
159
160
161
162
163
			if (array_key_exists("template_args", $param_full)) {
				$params[] = array(
					"paramid" => $param_full['id'],
					"fullparamid" => $param_full['fullparamid'],
					"template_args" => $param_full['template_args']
ffc5cb81   Elena.Budnik   temporary commit
164
				);			
f25e55ba   Benjamin Renard   Add sum in table ...
165
166
			}
			else if (!$this->isTest && (($templated_param_info = $this->templatedParamMgr->parseTemplatedParam($param_full["id"])) !== FALSE)) {
ffc5cb81   Elena.Budnik   temporary commit
167
168
169
170
171
172
173
174
175
176
				$params[] = $templated_param_info;					
			}
			else if ($this->isImpexParam($param_full["id"]))
			{
				if (!$this->impexParamMgr) 
				{
					$this->impexParamMgr = new IHMImpexParamClass();					
				}
				$templated_param_info = $this->impexParamMgr->parseImpexParam($param_full["id"]);
				$params[] = $templated_param_info;	
e4545ed5   Benjamin Renard   Implement templat...
177
178
179
180
			}
			else
				$params[] = array("paramid" => $param_full["id"]);
		}
ffc5cb81   Elena.Budnik   temporary commit
181
		 	
22521f1c   Benjamin Renard   First commit
182
183
		return array("expression" => $translated, "params" => $params);
	}
ffc5cb81   Elena.Budnik   temporary commit
184
185
186
	
	private function isImpexParam($paramID)
	{
8f40e2b8   Benjamin Renard   Fix expression pa...
187
188
189
		if (!$this->isTest)
			return preg_match("#^".IHMImpexParamClass::$paramPrefix."#",$paramID);
		return FALSE;
ffc5cb81   Elena.Budnik   temporary commit
190
191
	}
	
22521f1c   Benjamin Renard   First commit
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
	/*
	 * @brief clean expression
	*/
	private function clean(&$expression)
	{
		//remove all " "
		$expression = str_replace(" ", "", $expression);

		//replace [ and { by (
		$expression = str_replace(array("[","{"), "(", $expression);

		//replace ] and } by )
		$expression = str_replace(array("]","}"), ")", $expression);
	}

	/*
	 * @brief detect if some constants are defined in the expression
	*/
	private function isConstantDetected($expression)
	{
		return preg_match('/'.self::$constantTag.'/', $expression);
	}

	/*
	 * @brief replace constants by real values in expression
	*/
	private function replaceConstants(&$expression)
	{
		if (!$this->isConstantDetected($expression))
			return;

		if (!isset($this->constantsArray))
		{
			//load constants array
			$dom = new DomDocument("1.0");
			$constantsXMLFile = IHMConfigClass::getConstantsFilePath();
			if (!$dom->load($constantsXMLFile))
				throw new Exception('Cannot load constants file');
				
			$this->constantsArray = array();
				
			$constants_ = $dom->getElementsByTagName(self::$constantNode);
			for ($i = 1; $i <  $constants_->length; $i++)
				$this->constantsArray[self::$constantTag.$constants_->item($i)->getAttribute(self::$constantNameAtt)] = $constants_->item($i)->nodeValue;
		}

		//replace
		$expression = strtr($expression, $this->constantsArray);

		//be sure that all constants are replaced
		if ($this->isConstantDetected($expression))
			throw new Exception('Cannot replace some constants : '.$expression);
	}

	/*
	 * @brief detect if at least one aliases is defined in the expression
	*/
	private function isAliasDetected($expression)
	{
		return preg_match('/'.self::$aliasTag.'/', $expression);
	}

	/*
	 * @brief replace aliases by real parameter id in expression
	*/
	private function replaceAliases(&$expression)
	{
		if (!$this->isAliasDetected($expression))
			return;

		if (!isset($this->aliasesArray))
		{
			//load aliases array
			$dom = new DomDocument("1.0");
			$aliasesXMLFile = IHMConfigClass::getUserAliasesFilePath();
			if (!$dom->load($aliasesXMLFile))
				throw new Exception('Cannot load aliases file');
				
			$this->aliasesArray = array();
				
			$aliases_ = $dom->getElementsByTagName(self::$aliasNode);
			for ($i = 1; $i <  $aliases_->length; $i++)
				$this->aliasesArray[self::$alias_tag.$aliases_->item($i)->getAttribute(self::$aliasNameAtt)] = $aliases_->item($i)->nodeValue;
		}

		//replace
		$expression = strtr($expression, $this->aliasesArray);

		//be sure that all aliases are replaced
		if ($this->isAliasDetected($expression))
			throw new Exception('Cannot replace some aliases : '.$expression);
	}

	/*
	 * @brief load list of available functions
	*/
	private function loadFunctions()
	{
		if (isset($this->functionsArray))
			return;
			
		$dom = new DomDocument("1.0");
		$functionsXMLFile = IHMConfigClass::getFunctionsFilePath();

		if (!$dom->load($functionsXMLFile))
			throw new Exception('Cannot load functions file');
			
		$this->functionsArray = array();

		$functions_ = $dom->getElementsByTagName(self::$functionsNode);
		 
		for ($i = 0; $i < $functions_->length; $i++)
		{
			$tempArr =  explode('(', $functions_->item($i)->getAttribute(self::$functionsNameAtt));
			$nbArgs  =  $functions_->item($i)->getAttribute(self::$functionsArgsAtt);
			$kernelFunctions_ = $functions_->item($i)->getElementsByTagName(self::$functionsNewKernelNode);
			if ($kernelFunctions_->length == 0)
				$kernelFunction = "";
			else
				$kernelFunction = $kernelFunctions_->item(0)->nodeValue;
			$this->functionsArray[$tempArr[0]] = array(
				"kernel_name" => $kernelFunction,
				"nb_args"     => intval($nbArgs),
				"isOperator"  => false
			);
		}

		//add operator to change in function
		foreach (self::$operators as $operator)
		{
			if ($operator["type"] == "function")
				$this->functionsArray[$operator["function"]] = array(
					"kernel_name" => $operator["function"],
					"nb_args"     => 0,
					"isOperator"  => true
			);
		}
	}

	/*
	 * @brief detect if the element is a function
	*/
	private function isFunction($element)
	{
		$this->loadFunctions();
		return array_key_exists($element,$this->functionsArray);
	}
f25e55ba   Benjamin Renard   Add sum in table ...
339
340
341
342
343
344
345
346
	
	/*
	 * @brief detect if the element is "range"
	 */
	private function isRange($element)
	{
		return ($element == "range");
	}
22521f1c   Benjamin Renard   First commit
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

	/*
	 * @brief detect if the element is an operator
	*/
	private function isOperator($c)
	{
		foreach (self::$operators as $key => $value)
		if ($key == $c)
			return true;
	}

	/*
	 * @brief get the function associated to an operator
	*/
	private function getOperatorAssociatedFunction($c)
	{
		foreach (self::$operators as $key => $value)
		if ($key == $c)
		if ($value["type"] == "function")
			return $value["function"];
		return "";
	}

	/*
	 * @brief detect if the operator needed to be replace by a function
	*/
	private function isOperatorToFunction($c)
	{
		return ($this->getOperatorAssociatedFunction($c) != "");
	}

	/*
	 * @brief detect if the element is a separator
	*/
	private function isSeparator($c)
	{
		return ($this->isOperator($c) || $c == "(" || $c == ")" || $c == ",");
	}

	/*
	 * @brief detect a decimal value
	*/
	private function isDecimal($element)
	{
		return preg_match("/^[+\-]?(?:0|[1-9]\d*)(?:\.?\d*)?(?:[eE][+\-]?\d+)?/",$element);
		//return preg_match("/[+\-]?(?:0|[1-9]\d*)(?:\.?\d*)?(?:[eE][+\-]?\d+)/",$element);
	}

	/*
	 * @brief detect an integer value
	*/
	private function isInteger($element)
	{
		return preg_match("/^\d+$/",$element);
	}

	/*
	 * @brief explode expression for parsing
	*/
	private function explodeExpression($expression)
	{
		$crt = "";
		$elements = array();
		for ($i = 0; $i < strlen($expression); ++$i)
		{
			$c = $expression[$i];
			if ($this->isSeparator($c))
			{
				if ((($c == "+") || ($c == "-")) &&
				preg_match('/^\d*\.?\d*[eE]$/',$crt))
				{
					//scientific decimal element => false positive separator
					$crt .= $c;
					continue;
				}
				//push in elements list
				if ($crt != "")
					$elements[] = $crt;
				$elements[] = $c;
				$crt = "";
				continue;
			}
			$crt .= $c;
		}
		if ($crt != "")
			$elements[] = $crt;
		
		//regroup parameters and components before to add brackets for operators priority
		$els = array();
		$i = 0;
		for ($i; $i < count($elements)-3; ++$i)
		{
			if (($elements[$i+1] == "(")          &&
				$this->isParameter($elements[$i]) &&
				$this->isInteger($elements[$i+2]) &&
				($elements[$i+3] == ")"))
			{
				$els[] = ($elements[$i].$elements[$i+1].$elements[$i+2].$elements[$i+3]);
				$i = $i+3;
				continue;
			}
			$els[] = $elements[$i];
		}

		for ($j = $i; $j < count($elements); ++$j)
			$els[] = $elements[$j];
		
		$elements = $els;
9dbbc3b0   Benjamin Renard   Fix expression pa...
455
	
22521f1c   Benjamin Renard   First commit
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
		//regroup negative number
		$els = array();
		$i = 0;
		for ($i; $i < count($elements)-1; ++$i)
		{
			if (($elements[$i] == "-") && (
					$this->isDecimal($elements[$i+1]) || $this->isInteger($elements[$i+1])))
			{
				if (($i == 0) || (!$this->isDecimal($elements[$i-1]) && !$this->isInteger($elements[$i-1]) && !$this->isParameter($elements[$i-1])))
				{
					$els[] = ($elements[$i].$elements[$i+1]);
					$i = $i+1;
					continue;
				}
			}
			$els[] = $elements[$i];
		}
		
		for ($j = $i; $j < count($elements); ++$j)
			$els[] = $elements[$j];
		
		$elements = $els;
		
		//add brackets for operators priority
bc8ee588   Benjamin Renard   Fix expression pa...
480
		//Obsolete cf. https://projects.irap.omp.eu/issues/5239
9dbbc3b0   Benjamin Renard   Fix expression pa...
481

bc8ee588   Benjamin Renard   Fix expression pa...
482
		/*$els = array();
22521f1c   Benjamin Renard   First commit
483
484
485
		$i = 0;
		for ($i; $i < count($elements)-2; ++$i)
		{
8f40e2b8   Benjamin Renard   Fix expression pa...
486
			if ($elements[$i+1] == "*" || $elements[$i+1] == "/" || $elements[$i+1] == "^" || $elements[$i+1] == "<" || $elements[$i+1] == ">")
22521f1c   Benjamin Renard   First commit
487
			{
bc8ee588   Benjamin Renard   Fix expression pa...
488
				if ($elements[$i] != ")" && ($this->isDecimal($elements[$i+2]) || $this->isInteger($elements[$i+2])))
22521f1c   Benjamin Renard   First commit
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
				{
					$els[] = "(";
					$els[] = $elements[$i];
					$els[] = $elements[$i+1];
					$els[] = $elements[$i+2];
					$els[] = ")";
					$i += 2;
				}
				else
					$els[] = $elements[$i];
			}
			else
				$els[] = $elements[$i];
		}
		for ($j = $i; $j < count($elements); ++$j)
bc8ee588   Benjamin Renard   Fix expression pa...
504
			$els[] = $elements[$j];*/
22521f1c   Benjamin Renard   First commit
505
506
507

		//split parameters and components
		$elements = $els;
9dbbc3b0   Benjamin Renard   Fix expression pa...
508
	
22521f1c   Benjamin Renard   First commit
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
		$els = array();
		$i = 0;
		for ($i; $i < count($elements); ++$i)
		{
			$tmpArray = explode('(',$elements[$i]);
			if ((count($tmpArray) == 2) && ($tmpArray[0] != "") && ($tmpArray[1] != ""))
			{
				$tmpArray2 = explode(')',$tmpArray[1]);
				if ((count($tmpArray2) == 2) && ($tmpArray2[0] != "") && ($tmpArray2[1] == ""))
				{
					$els[] = "(";
					$els[] = $tmpArray[0];
					$els[] = "(";
					$els[] = $tmpArray2[0];
					$els[] = ")";
					$els[] = ")";
					continue;
				}
			}
			$els[] = $elements[$i];
		}
8f40e2b8   Benjamin Renard   Fix expression pa...
530

22521f1c   Benjamin Renard   First commit
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
		return $els;
	}

	/*
	 * @brief build a tree of the expression
	*/
	private function buildTreeElements($elements)
	{
		$expression_group = array();
		$crt_group = &$expression_group;
		$opened_groups = array($expression_group);
		for($i = 0; $i < count($elements); ++$i)
		{
			if ($elements[$i] == "(")
			{
				array_push($opened_groups,array());
				continue;
			}
			if ($elements[$i] == ")")
			{
				$group_to_close = $opened_groups[count($opened_groups)-1];
				array_pop($opened_groups);
				if (count($opened_groups) <= 0)
					throw new Exception('Expression error - Brackets definition');
				array_push($opened_groups[count($opened_groups)-1],$group_to_close);
				continue;
			}
			if (count($opened_groups) <= 0)
				throw new Exception('Expression error - Brackets definition');
			array_push($opened_groups[count($opened_groups)-1],$elements[$i]);
		}

		if (count($opened_groups) != 1)
			throw new Exception('Expression error - Brackets definition');
8f40e2b8   Benjamin Renard   Fix expression pa...
565

22521f1c   Benjamin Renard   First commit
566
567
568
569
570
571
572
573
574
575
576
577
578
579
		$expression_group = $opened_groups[0];

		return $expression_group;
	}

	/*
	 * @brief detect if the element is a parameter
	*/
	private function isParameter($element)
	{
		return (!is_array($element) &&
				!$this->isDecimal($element) &&
				!$this->isOperator($element) &&
				!$this->isFunction($element) &&
f25e55ba   Benjamin Renard   Add sum in table ...
580
581
				!$this->isRange($element) &&
				($element != ",") && ($element != ";") && ($element != "("));
22521f1c   Benjamin Renard   First commit
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
	}

	/*
	 * @brief detect if the element is a component for a parameter
	*/
	private function isParameterComponent($tree, $i)
	{
		$paramId = "";
		if ($i <= 0)
			return false;
		if (!$this->isParameter($tree[$i-1]))
			return false;
		return (is_array($tree[$i]) &&
				(count($tree[$i] == 1)) &&
				$this->isInteger($tree[$i][0]));
	}
f25e55ba   Benjamin Renard   Add sum in table ...
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
	
	/*
	 * @brief detect if the element is a range for a parameter
	*/
	private function isParameterRange($tree, $i)
	{
		$paramId = "";
		if ($i <= 0)
			return false;
		if (!$this->isParameter($tree[$i-1]))
			return false;
		return (is_array($tree[$i]) &&
				(count($tree[$i] == 1)) &&
				$this->isRange($tree[$i][0]));
	}
22521f1c   Benjamin Renard   First commit
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636

	/*
	 * @brief add a parameter
	*/
	private function addParameterIdInParameterArray($paramId, &$params)
	{
		foreach ($params as $param)
		if ($param["id"] == $paramId)
			return;
		$params[] = array("id" => $paramId, "indexes" => array(), "calib_infos" => array());
	}

	/*
	 * @brief add a parameter component
	*/
	private function addParameterComponentInParameterArray($paramId, $component, &$params)
	{
		foreach ($params as &$param)
		if ($param["id"] == $paramId)
		{
			array_push($param["indexes"],$component);
			return;
		}
	}
f25e55ba   Benjamin Renard   Add sum in table ...
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
	
	/*
	 * @brief add a parameter range
	*/
	private function addParameterRangeInParameterArray($paramId, $range, &$params)
	{
		$sum_parameter_id = "";
		if ((count($range) == 2) && (count($range[1]) == 3) && ($this->isInteger($range[1][0])) && ($this->isInteger($range[1][2])) & ($range[1][1] == ",")) {
			$sum_parameter_id = "sum_into_table_range_".$paramId."_0_".$range[1][0]."_".$range[1][2];
			$params[] = array("id"      => "sum_into_table_range",
					          "fullparamid"  => $sum_parameter_id,
							  "indexes" => array(),
							  "calib_infos" => array(),
					          "template_args" => array(
					          		"paramid" => $paramId,
									"relateddim" => 0,
					          		"min" => $range[1][0],
					          		"max" => $range[1][2]
							  )
					);
		}
		return $sum_parameter_id;
	}
22521f1c   Benjamin Renard   First commit
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676

	/*
	 * @brief process used to treat parameter components
	*/
	private function regroupParameterAndComponent($tree,&$params,&$result)
	{
		for ($i = 0; $i < count($tree); ++$i)
		{
			if (is_array($tree[$i]) && (count($tree[$i]) > 0))
			{
				$res = array();
				$this->regroupParameterAndComponent($tree[$i],$params,$res);
				$result[] = $res;
			}
			else if ($this->isParameter($tree[$i]))
			{
				$param = $tree[$i];
f25e55ba   Benjamin Renard   Add sum in table ...
677
				
22521f1c   Benjamin Renard   First commit
678
679
				if ($i < count($tree) - 1)
				{
f25e55ba   Benjamin Renard   Add sum in table ...
680
					if ($this->isParameterRange($tree,$i+1))
22521f1c   Benjamin Renard   First commit
681
					{
f25e55ba   Benjamin Renard   Add sum in table ...
682
683
						$sum_parameter_id = $this->addParameterRangeInParameterArray($param, $tree[$i+1], $params);
						$param = $sum_parameter_id;
22521f1c   Benjamin Renard   First commit
684
685
						++$i;
					}
f25e55ba   Benjamin Renard   Add sum in table ...
686
687
688
689
690
691
692
693
694
695
					else
					{
						$this->addParameterIdInParameterArray($param,$params);
						if ($this->isParameterComponent($tree,$i+1))
						{
							$this->addParameterComponentInParameterArray($param, $tree[$i+1][0], $params);
							$param .= ("[".$tree[$i+1][0]."]");
							++$i;
						}
					}
22521f1c   Benjamin Renard   First commit
696
				}
f25e55ba   Benjamin Renard   Add sum in table ...
697
698
699
				else 
					$this->addParameterIdInParameterArray($param,$params);
					
22521f1c   Benjamin Renard   First commit
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
				$result[] = $param;
			}
			else
			{
				$result[] = $tree[$i];
			}
		}
	}

	/*
	 * @brief replace all operators that's needed to be replace by a function
	*/
	private function fixOperatorToFunction($tree,&$result)
	{
		$i = 0;
		for ($i; $i < count($tree)-1; ++$i)
		{
			if ($this->isOperatorToFunction($tree[$i+1]))
			{
				if ($i >= count($tree)-2)
					throw new Exception('Expression error - Error in operator definition');
				
				if (is_array($tree[$i]))
				{
					$left = array();
					$this->fixOperatorToFunction($tree[$i],$left);
				}
				else
					$left     = $tree[$i];
				$function = $this->getOperatorAssociatedFunction($tree[$i+1]);
				if (is_array($tree[$i+2]))
				{
					$right = array();
					$this->fixOperatorToFunction($tree[$i+2],$right);
				}
				else
					$right    = $tree[$i+2];
				$result[] = $function;
				$result[] = array($left,",",$right);
				$i += 2;
			}
			else
			{
				if (is_array($tree[$i]))
				{
					$res = array();
					$this->fixOperatorToFunction($tree[$i],$res);
					$result[] = $res;
				}
				else
					$result[] = $tree[$i];
			}
		}

		for ($j = $i; $j < count($tree); ++$j)
		{
			if (is_array($tree[$j]))
			{
				$res = array();
				$this->fixOperatorToFunction($tree[$j],$res);
				$result[] = $res;			
			}
			else
				$result[] = $tree[$j];
		}
	}
8f40e2b8   Benjamin Renard   Fix expression pa...
766
767
768

	private function fixGroupFunction($tree,&$result) {
		$result = array();
8f40e2b8   Benjamin Renard   Fix expression pa...
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
		for ($i = 0; $i < count($tree); ++$i)
		{
			if (is_array($tree[$i])) {
				$res = array();
				$this->fixGroupFunction($tree[$i],$res);
				$result[] = $res;
			}
			else if ($this->isFunction($tree[$i])) {
				if ($i == count($tree) - 1) {
					throw new Exception('Expression error - Error in function call');
				}
				$res = array();
                                $this->fixGroupFunction($tree[$i+1],$res);
				$result[] = array($tree[$i],$res);
				++$i;
			}
			else
				$result[] = $tree[$i];
		}
	}
22521f1c   Benjamin Renard   First commit
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
	
	/*
	 * @brief process used to replace "," by ";" for function
	*/
	private function fixComaFunction($tree,$isFunctionGroup,&$result)
	{
		for ($i = 0; $i < count($tree); ++$i)
		{
			if (is_array($tree[$i]) && (count($tree[$i]) > 0))
			{
				$groupFunc = false;
				if (($i > 0) && (!is_array($tree[$i-1])))
				{
					$groupFunc = $this->isFunction($tree[$i-1]);
				}
				$res = array();
				$this->fixComaFunction($tree[$i],$groupFunc,$res);
				$result[] = $res;
			}
			else
			{
				if ($isFunctionGroup && ($tree[$i] == ','))
					$result[] = ';';
				else
					$result[] = $tree[$i];
			}
		}
	}

	/*
	 * @brief write the result expression from tree elements
	*/
	private function writeTranslate($tree,$params)
	{
		$translated = "";
		
		for ($i = 0; $i < count($tree); ++$i)
		{
			//echo "=> ".$tree[$i].PHP_EOL;
			if (is_array($tree[$i]))
			{
				//echo "ARRAY".PHP_EOL;
				if ((count($tree[$i]) > 1) || 
					(count($tree[$i]) == 1) && ($i>0) && (!is_array($tree[$i-1]) && $this->isFunction($tree[$i-1])))
					$translated .= ("(".$this->writeTranslate($tree[$i],$params).")");
				else
					$translated .= ($this->writeTranslate($tree[$i],$params));
			}
			else if ($this->isDecimal($tree[$i]))
			{
				//echo "DECIMAL ".$tree[$i].PHP_EOL;
				$translated .= $tree[$i];
			}
			else if ($this->isOperator($tree[$i]))
			{
				//echo "OPERATOR".PHP_EOL;
				$translated .= $tree[$i];
			}
			else if ($tree[$i] == ",")
			{
				//echo "COMA".PHP_EOL;
				$translated .= ",";
			}
			else if ($tree[$i] == ";")
			{
fa98426d   Elena.Budnik   comment debug info
854
				// echo "DOT COMA".PHP_EOL;
22521f1c   Benjamin Renard   First commit
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
				$translated .= ";";
			}
			else if ($this->isFunction($tree[$i]))
			{
				//echo "FUNCTION".PHP_EOL;
				$kernelFunction = $this->functionsArray[$tree[$i]]["kernel_name"];
				if ($kernelFunction == "")
					throw new Exception('Expression error - Function '.$tree[$i]." not implemented");
				$firstArgForFunc = ($this->functionsArray[$tree[$i]]["nb_args"] != 0);
				$translated .= $kernelFunction;
			}
			else
			{
				$founded = false;
				foreach ($params as $param)
				{
					//echo "TEST ".$param["id"].PHP_EOL;

f25e55ba   Benjamin Renard   Add sum in table ...
873
874
875
876
877
878
879
					if (array_key_exists("template_args", $param))
					{
						$founded = true;
						$translated .= "\$".$param["fullparamid"];
						break;
					}
					else if ($param["id"] == $tree[$i])
22521f1c   Benjamin Renard   First commit
880
881
882
883
884
					{
						$founded = true;
						$translated .= ("\$".$tree[$i]);
						break;
					}
f25e55ba   Benjamin Renard   Add sum in table ...
885
					
22521f1c   Benjamin Renard   First commit
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
					foreach ($param["indexes"] as $index)
					{
						$temp = "";
						$temp .= ($param["id"]."[".$index."]");
						//echo "TEST 2 ".$temp.PHP_EOL;
						if ($temp == $tree[$i])
						{
							$founded = true;
							$translated .= ("\$".$tree[$i]);
							break;
						}
					}
					if ($founded)
						break;
				}
				if (!$founded)
				{
					throw new Exception('Expression error - Unknown element '.$tree[$i]);
				}
			}
		}

		return $translated;
	}

	/*
	 * @brief sequence used to translate a tree elements
	*/
	private function translate($tree,&$params)
	{
		$res_1 = array();
		$this->regroupParameterAndComponent($tree,$params,$res_1);
8f40e2b8   Benjamin Renard   Fix expression pa...
918

22521f1c   Benjamin Renard   First commit
919
		$res_2 = array();
8f40e2b8   Benjamin Renard   Fix expression pa...
920
		$this->fixGroupFunction($res_1,$res_2);
22521f1c   Benjamin Renard   First commit
921
922

		$res_3 = array();
8f40e2b8   Benjamin Renard   Fix expression pa...
923
924
925
926
927
928
		$this->fixComaFunction($res_2,false,$res_3);

		$res_4 = array();
		$this->fixOperatorToFunction($res_3,$res_4);

		return $this->writeTranslate($res_4,$params);
22521f1c   Benjamin Renard   First commit
929
930
931
	}
}

f25e55ba   Benjamin Renard   Add sum in table ...
932
/*$parser = new IHMExpressionParserClass(TRUE);
22521f1c   Benjamin Renard   First commit
933
934
935
936
937
938
939
 try {
$parser->test();
} catch (Exception $e) {
echo 'Exception detected : '.$e->getMessage().PHP_EOL;
}*/

?>