Salome HOME
4e2d8f6c6eec96bd98797b86e6872ec389a641c2
[modules/shaper.git] / src / InitializationPlugin / InitializationPlugin_EvalListener.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <pyconfig.h>
21
22 #include <InitializationPlugin_EvalListener.h>
23 #include <InitializationPlugin_PyInterp.h>
24
25 #include <BuildPlugin_Interpolation.h>
26
27 #include <ParametersPlugin_Parameter.h>
28
29 #include <Events_InfoMessage.h>
30
31 #include <Locale_Convert.h>
32
33 #include <ModelAPI_AttributeDouble.h>
34 #include <ModelAPI_AttributeInteger.h>
35 #include <ModelAPI_AttributeRefList.h>
36 #include <ModelAPI_AttributeString.h>
37 #include <ModelAPI_AttributeTables.h>
38 #include <ModelAPI_AttributeValidator.h>
39 #include <ModelAPI_Document.h>
40 #include <ModelAPI_Events.h>
41 #include <ModelAPI_ResultParameter.h>
42 #include <ModelAPI_Session.h>
43 #include <ModelAPI_Tools.h>
44
45 #include <GeomDataAPI_Point.h>
46 #include <GeomDataAPI_Point2D.h>
47
48 #include <string>
49 #include <set>
50 #include <sstream>
51 #include <iostream>
52 #include <algorithm>
53
54 //=================================================================================================
55 // Tools
56
57 std::wstring toString(double theValue)
58 {
59   std::wostringstream sstream;
60   // write value in scientific format with 16 digits,
61   // thus, not check the dot position
62   sstream.precision(16);
63   sstream << std::scientific << theValue;
64   return sstream.str();
65 }
66
67 std::set<std::wstring> toSet(const std::list<std::wstring>& theContainer)
68 {
69   return std::set<std::wstring>(theContainer.begin(), theContainer.end());
70 }
71
72 //=================================================================================================
73 InitializationPlugin_EvalListener::InitializationPlugin_EvalListener()
74 {
75   Events_Loop* aLoop = Events_Loop::loop();
76
77   aLoop->registerListener(this, ModelAPI_AttributeEvalMessage::eventId(), NULL, true);
78   aLoop->registerListener(this, ModelAPI_ParameterEvalMessage::eventId(), NULL, true);
79   aLoop->registerListener(this, ModelAPI_BuildEvalMessage::eventId(), NULL, true);
80   aLoop->registerListener(this, ModelAPI_ComputePositionsMessage::eventId(), NULL, true);
81
82   myInterp = std::shared_ptr<InitializationPlugin_PyInterp>(new InitializationPlugin_PyInterp());
83   myInterp->initialize();
84 }
85
86 //=================================================================================================
87 InitializationPlugin_EvalListener::~InitializationPlugin_EvalListener()
88 {
89 }
90
91 //=================================================================================================
92 void InitializationPlugin_EvalListener::processEvent(
93     const std::shared_ptr<Events_Message>& theMessage)
94 {
95   if (!theMessage.get())
96     return;
97
98   if (theMessage->eventID() == ModelAPI_AttributeEvalMessage::eventId()) {
99     processEvaluationEvent(theMessage);
100   } else if (theMessage->eventID() == ModelAPI_ParameterEvalMessage::eventId()) {
101     std::shared_ptr<ModelAPI_ParameterEvalMessage> aMsg =
102       std::dynamic_pointer_cast<ModelAPI_ParameterEvalMessage>(theMessage);
103     FeaturePtr aParam = aMsg->parameter();
104     AttributeStringPtr anExprAttr = aParam->string(ParametersPlugin_Parameter::EXPRESSION_ID());
105     std::wstring anExp = anExprAttr->isUValue() ?
106         Locale::Convert::toWString(anExprAttr->valueU()) :
107         Locale::Convert::toWString(anExprAttr->value());
108     std::string anError;
109     std::list<std::shared_ptr<ModelAPI_ResultParameter> > aParamsList;
110     double aResult = evaluate(aParam, anExp, anError, aParamsList, true);
111     aMsg->setResults(aParamsList, aResult, anError);
112   } else if (theMessage->eventID() == ModelAPI_ComputePositionsMessage::eventId()) {
113     std::shared_ptr<ModelAPI_ComputePositionsMessage> aMsg =
114       std::dynamic_pointer_cast<ModelAPI_ComputePositionsMessage>(theMessage);
115     aMsg->setPositions(myInterp->positions(aMsg->expression(), aMsg->parameter()));
116   } else if (theMessage->eventID() == ModelAPI_BuildEvalMessage::eventId()) {
117     std::shared_ptr<ModelAPI_BuildEvalMessage> aMsg =
118       std::dynamic_pointer_cast<ModelAPI_BuildEvalMessage>(theMessage);
119     FeaturePtr aParam = aMsg->parameter();
120
121     AttributeStringPtr anVariableAttr = aParam->string(BuildPlugin_Interpolation::VARIABLE_ID());
122     std::wstring anVar = anVariableAttr->isUValue() ?
123         Locale::Convert::toWString(anVariableAttr->valueU()) :
124         Locale::Convert::toWString(anVariableAttr->value());
125     AttributeTablesPtr anValueAttr = aParam->tables(BuildPlugin_Interpolation::VALUE_ID());
126     std::string anError;
127
128     std::list<std::shared_ptr<ModelAPI_ResultParameter> > aParamsList;
129
130     AttributeStringPtr anExprAttr;
131     ModelAPI_AttributeTables::Value aVal;
132     bool anIsFirstTime = true;
133     anExprAttr = aParam->string(BuildPlugin_Interpolation::XT_ID());
134     std::wstring anExpX = anExprAttr->isUValue() ?
135     Locale::Convert::toWString(anExprAttr->valueU()) :
136     Locale::Convert::toWString(anExprAttr->value());
137     anExpX.erase(std::remove(anExpX.begin(), anExpX.end(), ' '), anExpX.end());
138     anExprAttr = aParam->string(BuildPlugin_Interpolation::YT_ID());
139     std::wstring anExpY = anExprAttr->isUValue() ?
140     Locale::Convert::toWString(anExprAttr->valueU()) :
141     Locale::Convert::toWString(anExprAttr->value());
142     anExpY.erase(std::remove(anExpY.begin(), anExpY.end(), ' '), anExpY.end());
143     anExprAttr = aParam->string(BuildPlugin_Interpolation::ZT_ID());
144     std::wstring anExpZ = anExprAttr->isUValue() ?
145     Locale::Convert::toWString(anExprAttr->valueU()) :
146     Locale::Convert::toWString(anExprAttr->value());
147     anExpZ.erase(std::remove(anExpZ.begin(),anExpZ.end(), ' '), anExpZ.end());
148
149     for (int step =0; step < anValueAttr->rows(); step++) {
150       aVal.myDouble = evaluate(anVar,
151                                 anValueAttr->value(step,0).myDouble,
152                                 aParam,
153                                 anExpX,
154                                 anError,
155                                 aParamsList,
156                                 anIsFirstTime);
157       if (!anError.empty()) break;
158       anValueAttr->setValue(aVal,step,1);
159       aVal.myDouble = evaluate(anVar,
160                               anValueAttr->value(step,0).myDouble,
161                               aParam,
162                               anExpY,
163                               anError,
164                               aParamsList,
165                               anIsFirstTime);
166       if (!anError.empty()) break;
167       anValueAttr->setValue(aVal,step,2);
168       aVal.myDouble = evaluate(anVar,
169                                 anValueAttr->value(step,0).myDouble,
170                                 aParam,
171                                 anExpZ,
172                                 anError,
173                                 aParamsList,
174                                 anIsFirstTime);
175       if (!anError.empty()) break;
176       anValueAttr->setValue(aVal,step,3);
177       if (anIsFirstTime)
178           anIsFirstTime = false;
179     }
180     aMsg->setResults(aParamsList, anError);
181   }
182 }
183
184 //=================================================================================================
185 double InitializationPlugin_EvalListener::evaluate(std::wstring& theVariable,
186                               double theValueVariable,
187                               FeaturePtr theParameter,
188                               const std::wstring& theExpression,
189                               std::string& theError,
190                               std::list<std::shared_ptr<ModelAPI_ResultParameter> >& theParamsList,
191                               bool theIsFirstTime)
192 {
193   std::list<std::wstring> aContext;
194   aContext.push_back(theVariable + L"=" + toString(theValueVariable));
195   myInterp->extendLocalContext(aContext);
196   aContext.clear();
197
198   std::list<std::wstring> anExprParams = myInterp->compile(theExpression);
199   // find expression's params in the model
200   std::list<std::wstring>::iterator it = anExprParams.begin();
201   for (; it != anExprParams.end(); it++) {
202     double aValue;
203     ResultParameterPtr aParamRes;
204     // If variable does not exist python interpreter will generate an error.
205     if (!ModelAPI_Tools::findVariable(FeaturePtr(),
206                            *it, aValue, aParamRes, theParameter->document()))
207       continue;
208
209     if (theIsFirstTime)
210     {
211       std::list<ResultParameterPtr>::iterator anIter =
212                           std::find(theParamsList.begin(),theParamsList.end(), aParamRes);
213       if (anIter == theParamsList.end())
214         theParamsList.push_back(aParamRes);
215     }
216
217     aContext.push_back(*it + L"=" + toString(aValue));
218   }
219   myInterp->extendLocalContext(aContext);
220   double result = myInterp->evaluate(theExpression, theError);
221   myInterp->clearLocalContext();
222   return result;
223 }
224
225 //=================================================================================================
226 double InitializationPlugin_EvalListener::evaluate(FeaturePtr theParameter,
227   const std::wstring& theExpression, std::string& theError,
228   std::list<std::shared_ptr<ModelAPI_ResultParameter> >& theParamsList,
229   const bool theIsParameter)
230 {
231   std::list<std::wstring> anExprParams = myInterp->compile(theExpression);
232   // find expression's params in the model
233   std::list<std::wstring> aContext;
234   std::list<std::wstring>::iterator it = anExprParams.begin();
235   for (; it != anExprParams.end(); it++) {
236     double aValue;
237     ResultParameterPtr aParamRes;
238     // If variable does not exist python interpreter will generate an error. It is OK.
239     // But due to the issue 1479 it should not check the history position of parameters relatively
240     // to feature that contains expression
241     if (!ModelAPI_Tools::findVariable(theIsParameter ? theParameter : FeaturePtr(),
242       *it, aValue, aParamRes, theParameter->document()))
243       continue;
244
245     if (theIsParameter)
246       theParamsList.push_back(aParamRes);
247     aContext.push_back(*it + L"=" + toString(aValue));
248   }
249   myInterp->extendLocalContext(aContext);
250   double result = myInterp->evaluate(theExpression, theError);
251   myInterp->clearLocalContext();
252   return result;
253 }
254
255 //=================================================================================================
256 void InitializationPlugin_EvalListener::processEvaluationEvent(
257     const std::shared_ptr<Events_Message>& theMessage)
258 {
259   std::shared_ptr<ModelAPI_AttributeEvalMessage> aMessage =
260       std::dynamic_pointer_cast<ModelAPI_AttributeEvalMessage>(theMessage);
261
262   std::list<std::shared_ptr<ModelAPI_ResultParameter> > aParamsList;
263   FeaturePtr aParamFeature =
264     std::dynamic_pointer_cast<ModelAPI_Feature>(aMessage->attribute()->owner());
265   if (aMessage->attribute()->attributeType() == ModelAPI_AttributeInteger::typeId()) {
266     AttributeIntegerPtr anAttribute =
267         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(aMessage->attribute());
268     std::string anError;
269     int aValue = (int)evaluate(aParamFeature, anAttribute->text(), anError, aParamsList);
270     bool isValid = anError.empty();
271     if (isValid)
272       anAttribute->setCalculatedValue(aValue);
273     anAttribute->setUsedParameters(isValid ?
274       toSet(myInterp->compile(anAttribute->text())) : std::set<std::wstring>());
275     anAttribute->setExpressionInvalid(!isValid);
276     anAttribute->setExpressionError(anAttribute->text().empty() ? "" : anError);
277   } else if (aMessage->attribute()->attributeType() == ModelAPI_AttributeDouble::typeId()) {
278     AttributeDoublePtr anAttribute =
279         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(aMessage->attribute());
280     std::string anError;
281     double aValue = evaluate(aParamFeature, anAttribute->text(), anError, aParamsList);
282     bool isValid = anError.empty();
283     if (isValid)
284       anAttribute->setCalculatedValue(aValue);
285     anAttribute->setUsedParameters(isValid ?
286       toSet(myInterp->compile(anAttribute->text())) : std::set<std::wstring>());
287     anAttribute->setExpressionInvalid(!isValid);
288     anAttribute->setExpressionError(anAttribute->text().empty() ? "" : anError);
289   } else if (aMessage->attribute()->attributeType() == GeomDataAPI_Point::typeId()) {
290     AttributePointPtr anAttribute =
291         std::dynamic_pointer_cast<GeomDataAPI_Point>(aMessage->attribute());
292     std::wstring aText[] = {
293       anAttribute->textX(),
294       anAttribute->textY(),
295       anAttribute->textZ()
296     };
297     double aCalculatedValue[] = {
298       anAttribute->x(),
299       anAttribute->y(),
300       anAttribute->z()
301     };
302     for (int i = 0; i < 3; ++i) {
303       std::string anError;
304       double aValue = evaluate(aParamFeature, aText[i], anError, aParamsList);
305       bool isValid = anError.empty();
306       if (isValid) aCalculatedValue[i] = aValue;
307       anAttribute->setUsedParameters(i,
308         isValid ? toSet(myInterp->compile(aText[i])) : std::set<std::wstring>());
309       anAttribute->setExpressionInvalid(i, !isValid);
310       anAttribute->setExpressionError(i, aText[i].empty() ? "" : anError);
311     }
312     anAttribute->setCalculatedValue(aCalculatedValue[0],
313                                     aCalculatedValue[1],
314                                     aCalculatedValue[2]);
315   } else if (aMessage->attribute()->attributeType() == GeomDataAPI_Point2D::typeId()) {
316     AttributePoint2DPtr anAttribute =
317         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aMessage->attribute());
318     std::wstring aText[] = {
319       anAttribute->textX(),
320       anAttribute->textY()
321     };
322     double aCalculatedValue[] = {
323       anAttribute->x(),
324       anAttribute->y()
325     };
326     for (int i = 0; i < 2; ++i) {
327       std::string anError;
328       double aValue = evaluate(aParamFeature, aText[i], anError, aParamsList);
329       bool isValid = anError.empty();
330       if (isValid) aCalculatedValue[i] = aValue;
331       anAttribute->setUsedParameters(i,
332         isValid ? toSet(myInterp->compile(aText[i])) : std::set<std::wstring>());
333       anAttribute->setExpressionInvalid(i, !isValid);
334       anAttribute->setExpressionError(i, aText[i].empty() ? "" : anError);
335     }
336     anAttribute->setCalculatedValue(aCalculatedValue[0],
337                                     aCalculatedValue[1]);
338   }
339 }
340
341 //=================================================================================================
342 void InitializationPlugin_EvalListener::initDataModel()
343 {
344   myInterp->runString("import salome_iapp;salome_iapp.register_module_in_study(\"Shaper\")");
345 }