Blame view

src/InputOutput/IHMImpl/Tools/IHMExpressionParserClass.php 25.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
<?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';
224a3ea9   Benjamin Renard   Fix expression pa...
24
	private static $functionsParamsAtt = 'params';
22521f1c   Benjamin Renard   First commit
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
	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...
47
48
	
	private $templatedParamMgr = NULL;
ffc5cb81   Elena.Budnik   temporary commit
49
	private $impexParamMgr = NULL;
f25e55ba   Benjamin Renard   Add sum in table ...
50
51
	
	private $isTest = FALSE;
22521f1c   Benjamin Renard   First commit
52
53
54
55

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

	/*
	 * @brief test function
	*/
	public function test()
	{
		//tests
		$tests = array(
9dbbc3b0   Benjamin Renard   Fix expression pa...
70
71
72
73
74
				"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...
75
76
77
78
79
				"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...
80
				"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 ...
81
				"(-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...
82
83
				"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...
84
85
				"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"))),
224a3ea9   Benjamin Renard   Fix expression pa...
86
				"cross(vect_1,vect_2)"  => array("expression" => "(cross(\$vect_1,\$vect_2))", "params" => array(array("paramid" => "vect_1"), array("paramid" => "vect_2"))),
f2c5542d   Benjamin Renard   Fix expression pa...
87
				"cross(cross(vect_1,vect_2),vect_3)"  => array("expression" => "(cross((cross(\$vect_1,\$vect_2)),\$vect_3))","params" => array(array("paramid" => "vect_1"), array("paramid" => "vect_2"), array("paramid" => "vect_3"))),
22521f1c   Benjamin Renard   First commit
88
89
90
91
92
93
94
95
96
97
98
99
100
101
		);

		//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(
224a3ea9   Benjamin Renard   Fix expression pa...
102
103
104
105
106
107
108
109
				"func_old" => array("kernel_name" => "func_new", "nb_args" => 0, "nb_params" => 1),
				"atan" => array("kernel_name" => "atan", "nb_args" => 0, "nb_params" => 1),
				"shiftT_" => array("kernel_name" => "#timeShift", "nb_args" => 1, "nb_params" => 1),
				"smooth_" => array("kernel_name" => "#boxcar", "nb_args" => 1, "nb_params" => 1),
				"deriv" => array("kernel_name" => "#deriv", "nb_args" => 0, "nb_params" => 1),
				"abs" => array("kernel_name" => "abs", "nb_args" => 0, "nb_params" => 1),
				"sqrt" => array("kernel_name" => "sqrt", "nb_args" => 0, "nb_params" => 1),
				"cross" => array("kernel_name" => "cross", "nb_args" => 0, "nb_params" => 2),
22521f1c   Benjamin Renard   First commit
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
		);

		//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...
152

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

22521f1c   Benjamin Renard   First commit
156
157
158
		//translate
		$params_full = array();
		$translated = $this->translate($tree,$params_full);
8f40e2b8   Benjamin Renard   Fix expression pa...
159

22521f1c   Benjamin Renard   First commit
160
161
		//keep only params id
		$params = array();
ffc5cb81   Elena.Budnik   temporary commit
162
		foreach ($params_full as $param_full) { 		 
f25e55ba   Benjamin Renard   Add sum in table ...
163
164
165
166
167
			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
168
				);			
f25e55ba   Benjamin Renard   Add sum in table ...
169
170
			}
			else if (!$this->isTest && (($templated_param_info = $this->templatedParamMgr->parseTemplatedParam($param_full["id"])) !== FALSE)) {
ffc5cb81   Elena.Budnik   temporary commit
171
172
173
174
175
176
177
178
179
180
				$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...
181
182
183
184
			}
			else
				$params[] = array("paramid" => $param_full["id"]);
		}
ffc5cb81   Elena.Budnik   temporary commit
185
		 	
22521f1c   Benjamin Renard   First commit
186
187
		return array("expression" => $translated, "params" => $params);
	}
ffc5cb81   Elena.Budnik   temporary commit
188
189
190
	
	private function isImpexParam($paramID)
	{
8f40e2b8   Benjamin Renard   Fix expression pa...
191
192
193
		if (!$this->isTest)
			return preg_match("#^".IHMImpexParamClass::$paramPrefix."#",$paramID);
		return FALSE;
ffc5cb81   Elena.Budnik   temporary commit
194
195
	}
	
22521f1c   Benjamin Renard   First commit
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
	/*
	 * @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);
224a3ea9   Benjamin Renard   Fix expression pa...
311
			$nbParams = $functions_->item($i)->getAttribute(self::$functionsParamsAtt);
22521f1c   Benjamin Renard   First commit
312
313
314
315
316
317
318
319
			$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),
224a3ea9   Benjamin Renard   Fix expression pa...
320
				"nb_params"     => intval($nbParams),
22521f1c   Benjamin Renard   First commit
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
				"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 ...
345
346
347
348
349
350
351
352
	
	/*
	 * @brief detect if the element is "range"
	 */
	private function isRange($element)
	{
		return ($element == "range");
	}
22521f1c   Benjamin Renard   First commit
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

	/*
	 * @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...
461
	
22521f1c   Benjamin Renard   First commit
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
		//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...
486
		//Obsolete cf. https://projects.irap.omp.eu/issues/5239
9dbbc3b0   Benjamin Renard   Fix expression pa...
487

bc8ee588   Benjamin Renard   Fix expression pa...
488
		/*$els = array();
22521f1c   Benjamin Renard   First commit
489
490
491
		$i = 0;
		for ($i; $i < count($elements)-2; ++$i)
		{
8f40e2b8   Benjamin Renard   Fix expression pa...
492
			if ($elements[$i+1] == "*" || $elements[$i+1] == "/" || $elements[$i+1] == "^" || $elements[$i+1] == "<" || $elements[$i+1] == ">")
22521f1c   Benjamin Renard   First commit
493
			{
bc8ee588   Benjamin Renard   Fix expression pa...
494
				if ($elements[$i] != ")" && ($this->isDecimal($elements[$i+2]) || $this->isInteger($elements[$i+2])))
22521f1c   Benjamin Renard   First commit
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
				{
					$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...
510
			$els[] = $elements[$j];*/
22521f1c   Benjamin Renard   First commit
511
512
513

		//split parameters and components
		$elements = $els;
9dbbc3b0   Benjamin Renard   Fix expression pa...
514
	
22521f1c   Benjamin Renard   First commit
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
		$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...
536

22521f1c   Benjamin Renard   First commit
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
565
566
567
568
569
570
		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...
571

22521f1c   Benjamin Renard   First commit
572
573
574
575
576
577
578
579
580
581
582
583
584
585
		$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 ...
586
587
				!$this->isRange($element) &&
				($element != ",") && ($element != ";") && ($element != "("));
22521f1c   Benjamin Renard   First commit
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
	}

	/*
	 * @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 ...
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
	
	/*
	 * @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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642

	/*
	 * @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 ...
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
	
	/*
	 * @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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682

	/*
	 * @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 ...
683
				
22521f1c   Benjamin Renard   First commit
684
685
				if ($i < count($tree) - 1)
				{
f25e55ba   Benjamin Renard   Add sum in table ...
686
					if ($this->isParameterRange($tree,$i+1))
22521f1c   Benjamin Renard   First commit
687
					{
f25e55ba   Benjamin Renard   Add sum in table ...
688
689
						$sum_parameter_id = $this->addParameterRangeInParameterArray($param, $tree[$i+1], $params);
						$param = $sum_parameter_id;
22521f1c   Benjamin Renard   First commit
690
691
						++$i;
					}
f25e55ba   Benjamin Renard   Add sum in table ...
692
693
694
695
696
697
698
699
700
701
					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
702
				}
f25e55ba   Benjamin Renard   Add sum in table ...
703
704
705
				else 
					$this->addParameterIdInParameterArray($param,$params);
					
22521f1c   Benjamin Renard   First commit
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
766
767
768
769
770
771
				$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...
772
773
774

	private function fixGroupFunction($tree,&$result) {
		$result = array();
8f40e2b8   Benjamin Renard   Fix expression pa...
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
		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
795
796
797
798
	
	/*
	 * @brief process used to replace "," by ";" for function
	*/
f2c5542d   Benjamin Renard   Fix expression pa...
799
	private function fixComaFunction($tree,$crt_function,&$result)
22521f1c   Benjamin Renard   First commit
800
	{
f2c5542d   Benjamin Renard   Fix expression pa...
801
		$nbParams = 0;
22521f1c   Benjamin Renard   First commit
802
803
804
805
806
807
808
809
810
811
		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();
f2c5542d   Benjamin Renard   Fix expression pa...
812
				$this->fixComaFunction($tree[$i],$groupFunc ? $tree[$i-1] : "",$res);
22521f1c   Benjamin Renard   First commit
813
814
815
816
				$result[] = $res;
			}
			else
			{
224a3ea9   Benjamin Renard   Fix expression pa...
817
818
819
820
821
822
				if (!empty($crt_function) && ($tree[$i] == ',')) {
					$nb_func_params = $this->functionsArray[$crt_function]["nb_params"];
					$result[] = ($nb_func_params <= $nbParams) ? ';' : ',';
				}
				else {
					++$nbParams;
22521f1c   Benjamin Renard   First commit
823
					$result[] = $tree[$i];
224a3ea9   Benjamin Renard   Fix expression pa...
824
				}
22521f1c   Benjamin Renard   First commit
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
854
855
856
857
858
859
860
861
862
863
864
			}
		}
	}

	/*
	 * @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
865
				// echo "DOT COMA".PHP_EOL;
22521f1c   Benjamin Renard   First commit
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
				$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 ...
884
885
886
887
888
889
890
					if (array_key_exists("template_args", $param))
					{
						$founded = true;
						$translated .= "\$".$param["fullparamid"];
						break;
					}
					else if ($param["id"] == $tree[$i])
22521f1c   Benjamin Renard   First commit
891
892
893
894
895
					{
						$founded = true;
						$translated .= ("\$".$tree[$i]);
						break;
					}
f25e55ba   Benjamin Renard   Add sum in table ...
896
					
22521f1c   Benjamin Renard   First commit
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
					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...
929

22521f1c   Benjamin Renard   First commit
930
		$res_2 = array();
8f40e2b8   Benjamin Renard   Fix expression pa...
931
		$this->fixGroupFunction($res_1,$res_2);
22521f1c   Benjamin Renard   First commit
932
933

		$res_3 = array();
f2c5542d   Benjamin Renard   Fix expression pa...
934
		$this->fixComaFunction($res_2,"",$res_3);
8f40e2b8   Benjamin Renard   Fix expression pa...
935
936
937
938
939

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

		return $this->writeTranslate($res_4,$params);
22521f1c   Benjamin Renard   First commit
940
941
942
	}
}

f25e55ba   Benjamin Renard   Add sum in table ...
943
/*$parser = new IHMExpressionParserClass(TRUE);
22521f1c   Benjamin Renard   First commit
944
945
946
947
948
949
950
 try {
$parser->test();
} catch (Exception $e) {
echo 'Exception detected : '.$e->getMessage().PHP_EOL;
}*/

?>