Blame view

src/InputOutput/IHMImpl/Tools/IHMExpressionParserClass.php 26.4 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"))),
fb7f73aa   Benjamin Renard   Fix expression pa...
88
				"c1_hia_pad(0,0)/c1_hia_pad(0,1)" => array ("expression" => "\$c1_hia_pad[0][0]/\$c1_hia_pad[0][1]", "params" => array(array("paramid" => "c1_hia_pad"))),
22521f1c   Benjamin Renard   First commit
89
90
91
92
93
94
95
96
97
98
99
100
101
102
		);

		//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...
103
104
105
106
107
108
109
110
				"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
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
		);

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

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

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

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

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

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

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

22521f1c   Benjamin Renard   First commit
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
571
		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...
572

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

	/*
	 * @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 ...
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
	
	/*
	 * @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
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)
	{
fb7f73aa   Benjamin Renard   Fix expression pa...
637
638
639
640
641
642
		foreach ($params as &$param) {
			if ($param["id"] == $paramId)
			{
				array_push($param["indexes"],$component);
				return;
			}
22521f1c   Benjamin Renard   First commit
643
644
		}
	}
f25e55ba   Benjamin Renard   Add sum in table ...
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
	
	/*
	 * @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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684

	/*
	 * @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 ...
685
				
22521f1c   Benjamin Renard   First commit
686
687
				if ($i < count($tree) - 1)
				{
f25e55ba   Benjamin Renard   Add sum in table ...
688
					if ($this->isParameterRange($tree,$i+1))
22521f1c   Benjamin Renard   First commit
689
					{
f25e55ba   Benjamin Renard   Add sum in table ...
690
691
						$sum_parameter_id = $this->addParameterRangeInParameterArray($param, $tree[$i+1], $params);
						$param = $sum_parameter_id;
22521f1c   Benjamin Renard   First commit
692
693
						++$i;
					}
f25e55ba   Benjamin Renard   Add sum in table ...
694
695
696
697
698
					else
					{
						$this->addParameterIdInParameterArray($param,$params);
						if ($this->isParameterComponent($tree,$i+1))
						{
fb7f73aa   Benjamin Renard   Fix expression pa...
699
700
701
702
703
704
705
706
707
708
							if ((count($tree[$i+1]) == 3) && ($tree[$i+1][1] == ',') && $this->isInteger($tree[$i+1][2])) {
								//2D
								$this->addParameterComponentInParameterArray($param, array($tree[$i+1][0], $tree[$i+1][2]), $params);
								$param .= ("[".$tree[$i+1][0]."][".$tree[$i+1][2]."]");
							}
							else {
								//1D
								$this->addParameterComponentInParameterArray($param, $tree[$i+1][0], $params);
								$param .= ("[".$tree[$i+1][0]."]");
							}
f25e55ba   Benjamin Renard   Add sum in table ...
709
710
711
							++$i;
						}
					}
22521f1c   Benjamin Renard   First commit
712
				}
f25e55ba   Benjamin Renard   Add sum in table ...
713
714
715
				else 
					$this->addParameterIdInParameterArray($param,$params);
					
22521f1c   Benjamin Renard   First commit
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
772
773
774
775
776
777
778
779
780
781
				$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...
782
783
784

	private function fixGroupFunction($tree,&$result) {
		$result = array();
8f40e2b8   Benjamin Renard   Fix expression pa...
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
		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
805
806
807
808
	
	/*
	 * @brief process used to replace "," by ";" for function
	*/
f2c5542d   Benjamin Renard   Fix expression pa...
809
	private function fixComaFunction($tree,$crt_function,&$result)
22521f1c   Benjamin Renard   First commit
810
	{
f2c5542d   Benjamin Renard   Fix expression pa...
811
		$nbParams = 0;
22521f1c   Benjamin Renard   First commit
812
813
814
815
816
817
818
819
820
821
		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...
822
				$this->fixComaFunction($tree[$i],$groupFunc ? $tree[$i-1] : "",$res);
22521f1c   Benjamin Renard   First commit
823
824
825
826
				$result[] = $res;
			}
			else
			{
224a3ea9   Benjamin Renard   Fix expression pa...
827
828
829
830
831
832
				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
833
					$result[] = $tree[$i];
224a3ea9   Benjamin Renard   Fix expression pa...
834
				}
22521f1c   Benjamin Renard   First commit
835
836
837
838
839
840
841
842
843
844
845
846
847
			}
		}
	}

	/*
	 * @brief write the result expression from tree elements
	*/
	private function writeTranslate($tree,$params)
	{
		$translated = "";
		
		for ($i = 0; $i < count($tree); ++$i)
		{
fb7f73aa   Benjamin Renard   Fix expression pa...
848
			#echo "=> ".$tree[$i].PHP_EOL;
22521f1c   Benjamin Renard   First commit
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
			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
875
				// echo "DOT COMA".PHP_EOL;
22521f1c   Benjamin Renard   First commit
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
				$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)
				{
fb7f73aa   Benjamin Renard   Fix expression pa...
892
					#echo "TEST ".$param["id"].PHP_EOL;
22521f1c   Benjamin Renard   First commit
893

f25e55ba   Benjamin Renard   Add sum in table ...
894
895
896
897
898
899
900
					if (array_key_exists("template_args", $param))
					{
						$founded = true;
						$translated .= "\$".$param["fullparamid"];
						break;
					}
					else if ($param["id"] == $tree[$i])
22521f1c   Benjamin Renard   First commit
901
902
903
904
905
					{
						$founded = true;
						$translated .= ("\$".$tree[$i]);
						break;
					}
f25e55ba   Benjamin Renard   Add sum in table ...
906
					
22521f1c   Benjamin Renard   First commit
907
908
909
					foreach ($param["indexes"] as $index)
					{
						$temp = "";
fb7f73aa   Benjamin Renard   Fix expression pa...
910
911
912
913
914
915
916
917
918
						if (is_array($index) && (count($index) == 2)) {
							//2D
							$temp .= ($param["id"]."[".$index[0]."][".$index[1]."]");
						}
						else {
							//1D
							$temp .= ($param["id"]."[".$index."]");
						}
						#echo "TEST 2 ".$temp.PHP_EOL;
22521f1c   Benjamin Renard   First commit
919
920
921
922
923
924
925
						if ($temp == $tree[$i])
						{
							$founded = true;
							$translated .= ("\$".$tree[$i]);
							break;
						}
					}
fb7f73aa   Benjamin Renard   Fix expression pa...
926

22521f1c   Benjamin Renard   First commit
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
					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...
947

22521f1c   Benjamin Renard   First commit
948
		$res_2 = array();
8f40e2b8   Benjamin Renard   Fix expression pa...
949
		$this->fixGroupFunction($res_1,$res_2);
22521f1c   Benjamin Renard   First commit
950
951

		$res_3 = array();
f2c5542d   Benjamin Renard   Fix expression pa...
952
		$this->fixComaFunction($res_2,"",$res_3);
8f40e2b8   Benjamin Renard   Fix expression pa...
953
954
955
956
957

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

		return $this->writeTranslate($res_4,$params);
22521f1c   Benjamin Renard   First commit
958
959
960
	}
}

f25e55ba   Benjamin Renard   Add sum in table ...
961
/*$parser = new IHMExpressionParserClass(TRUE);
22521f1c   Benjamin Renard   First commit
962
963
964
965
966
967
968
 try {
$parser->test();
} catch (Exception $e) {
echo 'Exception detected : '.$e->getMessage().PHP_EOL;
}*/

?>