Salome HOME
Merge branch 'CR26444'
[modules/shaper.git] / src / InitializationPlugin / InitializationPlugin_EvalListener.cpp
1 // Copyright (C) 2014-2021  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   aLoop->registerListener(this, ModelAPI_ImportParametersMessage::eventId(), NULL, true);
82
83   myInterp = std::shared_ptr<InitializationPlugin_PyInterp>(new InitializationPlugin_PyInterp());
84   myInterp->initialize();
85 }
86
87 //=================================================================================================
88 InitializationPlugin_EvalListener::~InitializationPlugin_EvalListener()
89 {
90 }
91
92 //=================================================================================================
93 void InitializationPlugin_EvalListener::processEvent(
94     const std::shared_ptr<Events_Message>& theMessage)
95 {
96   if (!theMessage.get())
97     return;
98
99   if (theMessage->eventID() == ModelAPI_AttributeEvalMessage::eventId()) {
100     processEvaluationEvent(theMessage);
101   } else if (theMessage->eventID() == ModelAPI_ParameterEvalMessage::eventId()) {
102     std::shared_ptr<ModelAPI_ParameterEvalMessage> aMsg =
103       std::dynamic_pointer_cast<ModelAPI_ParameterEvalMessage>(theMessage);
104     FeaturePtr aParam = aMsg->parameter();
105     AttributeStringPtr anExprAttr = aParam->string(ParametersPlugin_Parameter::EXPRESSION_ID());
106     std::wstring anExp = anExprAttr->isUValue() ?
107         Locale::Convert::toWString(anExprAttr->valueU()) :
108         Locale::Convert::toWString(anExprAttr->value());
109     std::string anError;
110     std::list<std::shared_ptr<ModelAPI_ResultParameter> > aParamsList;
111     double aResult = evaluate(aParam, anExp, anError, aParamsList, true);
112     aMsg->setResults(aParamsList, aResult, anError);
113   } else if (theMessage->eventID() == ModelAPI_ComputePositionsMessage::eventId()) {
114     std::shared_ptr<ModelAPI_ComputePositionsMessage> aMsg =
115       std::dynamic_pointer_cast<ModelAPI_ComputePositionsMessage>(theMessage);
116     aMsg->setPositions(myInterp->positions(aMsg->expression(), aMsg->parameter()));
117   } else if (theMessage->eventID() == ModelAPI_BuildEvalMessage::eventId()) {
118     std::shared_ptr<ModelAPI_BuildEvalMessage> aMsg =
119       std::dynamic_pointer_cast<ModelAPI_BuildEvalMessage>(theMessage);
120     FeaturePtr aParam = aMsg->parameter();
121
122     AttributeStringPtr anVariableAttr = aParam->string(BuildPlugin_Interpolation::VARIABLE_ID());
123     std::wstring anVar = anVariableAttr->isUValue() ?
124         Locale::Convert::toWString(anVariableAttr->valueU()) :
125         Locale::Convert::toWString(anVariableAttr->value());
126     AttributeTablesPtr anValueAttr = aParam->tables(BuildPlugin_Interpolation::VALUE_ID());
127     std::string anError;
128
129     std::list<std::shared_ptr<ModelAPI_ResultParameter> > aParamsList;
130
131     AttributeStringPtr anExprAttr;
132     ModelAPI_AttributeTables::Value aVal;
133     bool anIsFirstTime = true;
134     anExprAttr = aParam->string(BuildPlugin_Interpolation::XT_ID());
135     std::wstring anExpX = anExprAttr->isUValue() ?
136     Locale::Convert::toWString(anExprAttr->valueU()) :
137     Locale::Convert::toWString(anExprAttr->value());
138     anExpX.erase(std::remove(anExpX.begin(), anExpX.end(), ' '), anExpX.end());
139     anExprAttr = aParam->string(BuildPlugin_Interpolation::YT_ID());
140     std::wstring anExpY = anExprAttr->isUValue() ?
141     Locale::Convert::toWString(anExprAttr->valueU()) :
142     Locale::Convert::toWString(anExprAttr->value());
143     anExpY.erase(std::remove(anExpY.begin(), anExpY.end(), ' '), anExpY.end());
144     anExprAttr = aParam->string(BuildPlugin_Interpolation::ZT_ID());
145     std::wstring anExpZ = anExprAttr->isUValue() ?
146     Locale::Convert::toWString(anExprAttr->valueU()) :
147     Locale::Convert::toWString(anExprAttr->value());
148     anExpZ.erase(std::remove(anExpZ.begin(),anExpZ.end(), ' '), anExpZ.end());
149
150     for (int step =0; step < anValueAttr->rows(); step++) {
151       aVal.myDouble = evaluate(anVar,
152                                 anValueAttr->value(step,0).myDouble,
153                                 aParam,
154                                 anExpX,
155                                 anError,
156                                 aParamsList,
157                                 anIsFirstTime);
158       if (!anError.empty()) break;
159       anValueAttr->setValue(aVal,step,1);
160       aVal.myDouble = evaluate(anVar,
161                               anValueAttr->value(step,0).myDouble,
162                               aParam,
163                               anExpY,
164                               anError,
165                               aParamsList,
166                               anIsFirstTime);
167       if (!anError.empty()) break;
168       anValueAttr->setValue(aVal,step,2);
169       aVal.myDouble = evaluate(anVar,
170                                 anValueAttr->value(step,0).myDouble,
171                                 aParam,
172                                 anExpZ,
173                                 anError,
174                                 aParamsList,
175                                 anIsFirstTime);
176       if (!anError.empty()) break;
177       anValueAttr->setValue(aVal,step,3);
178       if (anIsFirstTime)
179           anIsFirstTime = false;
180     }
181     aMsg->setResults(aParamsList, anError);
182   }
183   else if (theMessage->eventID() == ModelAPI_ImportParametersMessage::eventId())
184   {
185     std::shared_ptr<ModelAPI_ImportParametersMessage> aMsg =
186       std::dynamic_pointer_cast<ModelAPI_ImportParametersMessage>(theMessage);
187     std::string anImportScript("from salome.shaper import model;");
188     std::string aDocScript("doc = model.activeDocument();");
189     std::string anParamImpScript("model.importParameters(doc, \"");
190     std::string aPath = aMsg->filename();
191     myInterp->runString(anImportScript + aDocScript + anParamImpScript + aPath + "\")");
192   }
193 }
194
195 //=================================================================================================
196 double InitializationPlugin_EvalListener::evaluate(std::wstring& theVariable,
197                               double theValueVariable,
198                               FeaturePtr theParameter,
199                               const std::wstring& theExpression,
200                               std::string& theError,
201                               std::list<std::shared_ptr<ModelAPI_ResultParameter> >& theParamsList,
202                               bool theIsFirstTime)
203 {
204   std::list<std::wstring> aContext;
205   aContext.push_back(theVariable + L"=" + toString(theValueVariable));
206   myInterp->extendLocalContext(aContext);
207   aContext.clear();
208
209   std::list<std::wstring> anExprParams = myInterp->compile(theExpression);
210   // find expression's params in the model
211   std::list<std::wstring>::iterator it = anExprParams.begin();
212   for (; it != anExprParams.end(); it++) {
213     double aValue;
214     ResultParameterPtr aParamRes;
215     // If variable does not exist python interpreter will generate an error.
216     if (!ModelAPI_Tools::findVariable(FeaturePtr(),
217                            *it, aValue, aParamRes, theParameter->document()))
218       continue;
219
220     if (theIsFirstTime)
221     {
222       std::list<ResultParameterPtr>::iterator anIter =
223                           std::find(theParamsList.begin(),theParamsList.end(), aParamRes);
224       if (anIter == theParamsList.end())
225         theParamsList.push_back(aParamRes);
226     }
227
228     aContext.push_back(*it + L"=" + toString(aValue));
229   }
230   myInterp->extendLocalContext(aContext);
231   double result = myInterp->evaluate(theExpression, theError);
232   myInterp->clearLocalContext();
233   return result;
234 }
235
236 //=================================================================================================
237 double InitializationPlugin_EvalListener::evaluate(FeaturePtr theParameter,
238   const std::wstring& theExpression, std::string& theError,
239   std::list<std::shared_ptr<ModelAPI_ResultParameter> >& theParamsList,
240   const bool theIsParameter)
241 {
242   std::list<std::wstring> anExprParams = myInterp->compile(theExpression);
243   // find expression's params in the model
244   std::list<std::wstring> aContext;
245   std::list<std::wstring>::iterator it = anExprParams.begin();
246   for (; it != anExprParams.end(); it++) {
247     double aValue;
248     ResultParameterPtr aParamRes;
249     // If variable does not exist python interpreter will generate an error. It is OK.
250     // But due to the issue 1479 it should not check the history position of parameters relatively
251     // to feature that contains expression
252     if (!ModelAPI_Tools::findVariable(theIsParameter ? theParameter : FeaturePtr(),
253       *it, aValue, aParamRes, theParameter->document()))
254       continue;
255
256     if (theIsParameter)
257       theParamsList.push_back(aParamRes);
258     aContext.push_back(*it + L"=" + toString(aValue));
259   }
260   myInterp->extendLocalContext(aContext);
261   double result = myInterp->evaluate(theExpression, theError);
262   myInterp->clearLocalContext();
263   return result;
264 }
265
266 //=================================================================================================
267 void InitializationPlugin_EvalListener::processEvaluationEvent(
268     const std::shared_ptr<Events_Message>& theMessage)
269 {
270   std::shared_ptr<ModelAPI_AttributeEvalMessage> aMessage =
271       std::dynamic_pointer_cast<ModelAPI_AttributeEvalMessage>(theMessage);
272
273   std::list<std::shared_ptr<ModelAPI_ResultParameter> > aParamsList;
274   FeaturePtr aParamFeature =
275     std::dynamic_pointer_cast<ModelAPI_Feature>(aMessage->attribute()->owner());
276   if (aMessage->attribute()->attributeType() == ModelAPI_AttributeInteger::typeId()) {
277     AttributeIntegerPtr anAttribute =
278         std::dynamic_pointer_cast<ModelAPI_AttributeInteger>(aMessage->attribute());
279     std::string anError;
280     int aValue = (int)evaluate(aParamFeature, anAttribute->text(), anError, aParamsList);
281     bool isValid = anError.empty();
282     if (isValid)
283       anAttribute->setCalculatedValue(aValue);
284     anAttribute->setUsedParameters(isValid ?
285       toSet(myInterp->compile(anAttribute->text())) : std::set<std::wstring>());
286     anAttribute->setExpressionInvalid(!isValid);
287     anAttribute->setExpressionError(anAttribute->text().empty() ? "" : anError);
288   } else if (aMessage->attribute()->attributeType() == ModelAPI_AttributeDouble::typeId()) {
289     AttributeDoublePtr anAttribute =
290         std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(aMessage->attribute());
291     std::string anError;
292     double aValue = evaluate(aParamFeature, anAttribute->text(), anError, aParamsList);
293     bool isValid = anError.empty();
294     if (isValid)
295       anAttribute->setCalculatedValue(aValue);
296     anAttribute->setUsedParameters(isValid ?
297       toSet(myInterp->compile(anAttribute->text())) : std::set<std::wstring>());
298     anAttribute->setExpressionInvalid(!isValid);
299     anAttribute->setExpressionError(anAttribute->text().empty() ? "" : anError);
300   } else if (aMessage->attribute()->attributeType() == GeomDataAPI_Point::typeId()) {
301     AttributePointPtr anAttribute =
302         std::dynamic_pointer_cast<GeomDataAPI_Point>(aMessage->attribute());
303     std::wstring aText[] = {
304       anAttribute->textX(),
305       anAttribute->textY(),
306       anAttribute->textZ()
307     };
308     double aCalculatedValue[] = {
309       anAttribute->x(),
310       anAttribute->y(),
311       anAttribute->z()
312     };
313     for (int i = 0; i < 3; ++i) {
314       std::string anError;
315       double aValue = evaluate(aParamFeature, aText[i], anError, aParamsList);
316       bool isValid = anError.empty();
317       if (isValid) aCalculatedValue[i] = aValue;
318       anAttribute->setUsedParameters(i,
319         isValid ? toSet(myInterp->compile(aText[i])) : std::set<std::wstring>());
320       anAttribute->setExpressionInvalid(i, !isValid);
321       anAttribute->setExpressionError(i, aText[i].empty() ? "" : anError);
322     }
323     anAttribute->setCalculatedValue(aCalculatedValue[0],
324                                     aCalculatedValue[1],
325                                     aCalculatedValue[2]);
326   } else if (aMessage->attribute()->attributeType() == GeomDataAPI_Point2D::typeId()) {
327     AttributePoint2DPtr anAttribute =
328         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aMessage->attribute());
329     std::wstring aText[] = {
330       anAttribute->textX(),
331       anAttribute->textY()
332     };
333     double aCalculatedValue[] = {
334       anAttribute->x(),
335       anAttribute->y()
336     };
337     for (int i = 0; i < 2; ++i) {
338       std::string anError;
339       double aValue = evaluate(aParamFeature, aText[i], anError, aParamsList);
340       bool isValid = anError.empty();
341       if (isValid) aCalculatedValue[i] = aValue;
342       anAttribute->setUsedParameters(i,
343         isValid ? toSet(myInterp->compile(aText[i])) : std::set<std::wstring>());
344       anAttribute->setExpressionInvalid(i, !isValid);
345       anAttribute->setExpressionError(i, aText[i].empty() ? "" : anError);
346     }
347     anAttribute->setCalculatedValue(aCalculatedValue[0],
348                                     aCalculatedValue[1]);
349   }
350 }
351
352 //=================================================================================================
353 void InitializationPlugin_EvalListener::initDataModel()
354 {
355   myInterp->runString("import salome_iapp;salome_iapp.register_module_in_study(\"Shaper\")");
356 }