1 // Copyright (C) 2011-2019 CEA/DEN, EDF R&D
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 // Authors: A Bruneton (CEA), C Aguerre (EdF)
21 #include "MEDPyLockWrapper.hxx"
22 #include "MEDFactoryClient.hxx"
23 #include "MEDPresentation.hxx"
24 #include "MEDPresentationException.hxx"
25 #include "MEDCouplingRefCountObject.hxx"
26 #include <SALOME_KernelServices.hxx>
28 #include <Basics_Utils.hxx>
32 #if PY_VERSION_HEX < 0x03050000
34 Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
36 return _Py_wchar2char(text, error_pos);
40 const std::string MEDPresentation::PROP_NAME = "name";
41 const std::string MEDPresentation::PROP_NB_COMPONENTS = "nbComponents";
42 const std::string MEDPresentation::PROP_SELECTED_COMPONENT = "selectedComponent";
43 const std::string MEDPresentation::PROP_COMPONENT = "component_";
44 const std::string MEDPresentation::PROP_COLOR_MAP = "colorMap";
45 const std::string MEDPresentation::PROP_SCALAR_BAR_RANGE = "scalarBarRange";
47 MEDPresentation::MEDPresentation(MEDPresentation::TypeID handlerId, const std::string& name,
48 const MEDCALC::ViewModeType viewMode,
49 const MEDCALC::ColorMapType colorMap,
50 const MEDCALC::ScalarBarRangeType sbRange)
51 : _handlerId(handlerId), _propertiesStr(),
52 _mcFieldType(MEDCoupling::ON_CELLS),
53 _pvFieldType(""), _meshName(""), _fieldName(""), _fileName(""),
54 _selectedComponentIndex(-1),
58 _renderViewPyId(-1), // will be set by MEDPresentationManager_i::_makePresentation()
61 setStringProperty(MEDPresentation::PROP_NAME, name);
63 setIntProperty(MEDPresentation::PROP_NB_COMPONENTS, 0);
64 setIntProperty(MEDPresentation::PROP_SELECTED_COMPONENT, 0);
66 setIntProperty(MEDPresentation::PROP_COLOR_MAP, static_cast<int>(colorMap));
67 setIntProperty(MEDPresentation::PROP_SCALAR_BAR_RANGE, static_cast<int>(sbRange));
70 int id = GeneratePythonId();
71 std::ostringstream oss_o, oss_d, oss_l, oss_s, oss_r;
72 oss_o << "__obj" << id;
73 oss_s << "__srcObj" << id;
74 oss_d << "__disp" << id;
75 oss_l << "__lut" << id;
76 oss_r << "__range" << id;
77 _objVar = oss_o.str();
78 _srcObjVar = oss_s.str();
79 _dispVar = oss_d.str();
80 _lutVar = oss_l.str();
81 _rangeVar = oss_r.str();
85 * For most of the presentations the field name etc is required.
86 * For the MEDPresentationMeshView however, the handler ID is a mesh handler ID, not a field, and the
87 * treatment is specific.
90 MEDPresentation::initFieldMeshInfos()
92 MEDCALC::MEDDataManager_ptr dataManager(MEDFactoryClient::getDataManager());
93 MEDCALC::FieldHandler* fieldHandler = dataManager->getFieldHandler(_handlerId);
94 MEDCALC::MeshHandler* meshHandler = dataManager->getMeshHandler(fieldHandler->meshid);
95 MEDCALC::DatasourceHandler* dataSHandler = dataManager->getDatasourceHandlerFromID(meshHandler->sourceid);
97 extractFileName(std::string(dataSHandler->uri));
99 _fieldName = fieldHandler->fieldname;
100 _mcFieldType = (MEDCoupling::TypeOfField) fieldHandler->type;
101 _pvFieldType = getPVFieldTypeString(_mcFieldType);
102 _colorByType = _pvFieldType; // by default the same; overridden in DeflectionShape, VectorField, PointSprite and Contour
103 _meshName = meshHandler->name;
107 MEDPresentation::extractFileName(const std::string& name)
110 if (_fileName.substr(0, 7) != std::string("file://")) {
111 const char* msg = "MEDPresentation(): Data source is not a file! Can not proceed.";
113 throw MEDPresentationException(msg);
115 _fileName = _fileName.substr(7, _fileName.size());
118 MEDPresentation::~MEDPresentation()
120 STDLOG("~MEDPresentation(): clear display");
122 MEDPyLockWrapper lock;
123 std::ostringstream oss;
125 oss << "pvs.Hide(" << _objVar << ", view=" << getRenderViewVar() << ");";
126 execPyLine(oss.str());
127 // :TRICKY: The two following lines raise an exception when closing MED module
128 // after sequence: MED - load file - PARAVIS - MED - close SALOME
129 // (see Mantis #23461)
130 //execPyLine(getRenderViewVar() + ".ResetCamera();");
131 //execPyLine("pvs.Render();");
136 MEDPresentation::generatePipeline()
138 // Might be more complicated in the future:
140 this->internalGeneratePipeline();
144 //MEDPresentation::pushPyObjects(PyObjectId obj, PyObjectId disp)
146 // _pipeline.push_back(obj);
147 // _display.push_back(disp);
151 MEDPresentation::pushAndExecPyLine(const std::string & lin)
154 _pythonCmds.push_back(lin);
158 MEDPresentation::execPyLine(const std::string & lin)
160 MEDPyLockWrapper lock;
161 STDLOG("@@@@ MEDPresentation::execPyLine() about to exec >> " << lin);
162 if(PyRun_SimpleString(lin.c_str()))
164 std::ostringstream oss;
165 oss << "MEDPresentation::execPyLine(): following Python command failed!\n";
168 throw KERNEL::createSalomeException(oss.str().c_str());
173 MEDPresentation::setStringProperty(const std::string& propName, const std::string& propValue)
175 _propertiesStr[propName] = propValue;
179 MEDPresentation::getStringProperty(const std::string& propName) const
181 std::map<std::string, std::string>::const_iterator it = _propertiesStr.find(propName);
182 if (it != _propertiesStr.end()) {
186 STDLOG("MEDPresentation::getStringProperty(): no property named " + propName);
187 throw MEDPresentationException("MEDPresentation::getStringProperty(): no property named " + propName);
192 MEDPresentation::setIntProperty(const std::string& propName, const int propValue)
194 _propertiesInt[propName] = propValue;
198 MEDPresentation::getIntProperty(const std::string& propName) const
200 std::map<std::string, int>::const_iterator it = _propertiesInt.find(propName);
201 if (it != _propertiesInt.end()) {
205 STDLOG("MEDPresentation::getIntProperty(): no property named " + propName);
206 throw MEDPresentationException("MEDPresentation::getIntProperty(): no property named " + propName);
211 MEDPresentation::dumpIntProperties() const
213 std::map<std::string, int>::const_iterator it = _propertiesInt.begin();
214 STDLOG("@@@ Dumping INT properties");
215 for(; it != _propertiesInt.end(); ++it)
217 std::ostringstream oss;
218 oss << (*it).first << " -> " << (*it).second;
224 MEDPresentation::dumpStringProperties() const
226 std::map<std::string, std::string>::const_iterator it = _propertiesStr.begin();
227 STDLOG("@@@ Dumping STR properties");
228 for(; it != _propertiesStr.end(); ++it)
230 std::ostringstream oss;
231 oss << (*it).first << " -> " << (*it).second;
237 MEDPresentation::internalGeneratePipeline()
239 MEDPyLockWrapper lock;
240 pushAndExecPyLine( "import pvsimple as pvs;");
241 pushAndExecPyLine( "import medcalc");
246 * @return a borrowed reference. Do not DECRREF!
249 MEDPresentation::getPythonObjectFromMain(const char* python_var) const
253 // All the calls below returns *borrowed* references
254 PyObject* main_module = PyImport_AddModule((char*)"__main__");
255 _globalDict = PyModule_GetDict(main_module);
257 return PyDict_GetItemString(_globalDict, python_var);
261 MEDPresentation::getPVFieldTypeString(MEDCoupling::TypeOfField fieldType) const
265 case MEDCoupling::ON_CELLS:
267 case MEDCoupling::ON_NODES:
269 case MEDCoupling::ON_GAUSS_PT:
270 return "POINTS"; // because internally after application of the ELGA filter, the field will appear as a POINT field
271 case MEDCoupling::ON_GAUSS_NE:
272 return "POINTS"; // because internally after application of the ELNO mesh filter, the field will appear as a POINT field
274 STDLOG("MEDPresentation::getPVFieldTypeString() -- Not implemented ! ELNO field?");
280 MEDPresentation::getRenderViewVar() const
282 std::ostringstream oss;
283 oss << "__view" << _renderViewPyId;
288 * Creates the MEDReader source in the pipeline, and potentially apply GAUSS/ELNO filters.
291 MEDPresentation::createSource()
294 switch(_mcFieldType) {
295 case MEDCoupling::ON_CELLS: typ = "P0"; break;
296 case MEDCoupling::ON_NODES: typ = "P1"; break;
297 case MEDCoupling::ON_GAUSS_PT: typ = "GAUSS"; break;
298 case MEDCoupling::ON_GAUSS_NE: typ = "GSSNE"; break;
300 const char * msg ="MEDPresentation::createSource(): field type not impl. yet!";
302 throw KERNEL::createSalomeException(msg);
305 std::ostringstream oss;
306 oss << _srcObjVar << " = pvs.MEDReader(FileName='" << _fileName << "');";
307 pushAndExecPyLine(oss.str()); oss.str("");
308 oss << "medcalc.SelectSourceField(" << _srcObjVar << ", '" << _meshName << "', '"
309 << _fieldName << "', '" << typ << "');";
310 pushAndExecPyLine(oss.str()); oss.str("");
311 // Generate complete vector fields: fields with 2 components will copied into <name>_vector and
312 // have a third null component added.
313 oss << _srcObjVar << ".GenerateVectors = 1;";
314 pushAndExecPyLine(oss.str()); oss.str("");
316 // Make sure this is set so we stick to time steps:
317 pushAndExecPyLine("pvs.GetAnimationScene().PlayMode = 'Snap To TimeSteps'");
319 // Deal with GAUSS fields:
320 if(_mcFieldType == MEDCoupling::ON_GAUSS_PT)
322 std::ostringstream oss, oss2;
323 oss2 << "__srcObj" << GeneratePythonId();
324 oss << oss2.str() << " = pvs.GaussPoints(Input=" << _srcObjVar << ");";
325 pushAndExecPyLine(oss.str()); oss.str("");
326 // Now the source becomes the result of the CellDatatoPointData:
327 _srcObjVar = oss2.str();
328 oss << _srcObjVar << ".SelectSourceArray = ['CELLS', 'ELGA@0'];";
329 pushAndExecPyLine(oss.str()); oss.str("");
331 if(_mcFieldType == MEDCoupling::ON_GAUSS_NE)
333 std::ostringstream oss, oss2;
334 oss2 << "__srcObj" << GeneratePythonId();
335 oss << oss2.str() << " = pvs.ELNOMesh(Input=" << _srcObjVar << ");";
336 pushAndExecPyLine(oss.str()); oss.str("");
337 // Now the source becomes the result of the CellDatatoPointData:
338 _srcObjVar = oss2.str();
343 MEDPresentation::setOrCreateRenderView()
345 std::ostringstream oss2;
347 std::string view(getRenderViewVar());
348 oss2 << "pvs._DisableFirstRenderCameraReset();";
349 pushAndExecPyLine(oss2.str()); oss2.str("");
350 if (_viewMode == MEDCALC::VIEW_MODE_OVERLAP) {
351 // this might potentially re-assign to an existing view variable, but this is OK, we
352 // normally reassign exactly the same RenderView object.
353 oss2 << view << " = pvs.GetActiveViewOrCreate('RenderView');";
354 pushAndExecPyLine(oss2.str()); oss2.str("");
355 } else if (_viewMode == MEDCALC::VIEW_MODE_REPLACE) {
357 oss2 << view << " = pvs.GetActiveViewOrCreate('RenderView');";
358 pushAndExecPyLine(oss2.str()); oss2.str("");
359 oss2 << "pvs.active_objects.source and pvs.Hide(view=" << view << ");";
360 pushAndExecPyLine(oss2.str()); oss2.str("");
361 oss2 << "pvs.Render();";
362 pushAndExecPyLine(oss2.str()); oss2.str("");
363 } else if (_viewMode == MEDCALC::VIEW_MODE_NEW_LAYOUT) {
364 oss2 << "__layout1 = pvs.servermanager.misc.ViewLayout(registrationGroup='layouts');";
365 pushAndExecPyLine(oss2.str()); oss2.str("");
366 oss2 << view << " = pvs.CreateView('RenderView');";
367 pushAndExecPyLine(oss2.str()); oss2.str("");
368 } else if (_viewMode == MEDCALC::VIEW_MODE_SPLIT_VIEW) {
369 oss2 << view << " = pvs.CreateView('RenderView');";
370 pushAndExecPyLine(oss2.str()); oss2.str("");
375 MEDPresentation::resetCameraAndRender()
377 pushAndExecPyLine(getRenderViewVar() + ".ResetCamera();");
378 pushAndExecPyLine("pvs.Render();");
382 MEDPresentation::selectFieldComponent()
384 std::ostringstream oss, oss_l;
387 if (_selectedComponentIndex != -1)
389 oss << _lutVar << ".VectorMode = 'Component';";
390 pushAndExecPyLine(oss.str()); oss.str("");
391 oss << _lutVar << ".VectorComponent = " << _selectedComponentIndex << ";";
392 pushAndExecPyLine(oss.str()); oss.str("");
394 else // Euclidean norm
396 oss << _lutVar << ".VectorMode = 'Magnitude';";
397 pushAndExecPyLine(oss.str()); oss.str("");
402 * Needs the LUT, so to be called after selectColorMap for the first time.
405 MEDPresentation::scalarBarTitle()
407 // get selected component name:
408 std::string compoName;
409 if (_selectedComponentIndex != -1)
411 std::ostringstream oss1;
412 oss1 << MEDPresentation::PROP_COMPONENT << _selectedComponentIndex;
413 compoName = getStringProperty(oss1.str());
417 if (getIntProperty(MEDPresentation::PROP_NB_COMPONENTS) == 1)
420 compoName = "Magnitude";
422 std::ostringstream oss;
423 oss << "pvs.GetScalarBar(" << _lutVar << ").ComponentTitle = '" << compoName << "';";
424 pushAndExecPyLine(oss.str()); oss.str("");
428 MEDPresentation::selectColorMap()
430 std::ostringstream oss, oss2;
432 oss2 << _lutVar << " = pvs.GetColorTransferFunction('" << _fieldName << "');";
433 pushAndExecPyLine(oss2.str());
436 case MEDCALC::COLOR_MAP_BLUE_TO_RED_RAINBOW:
437 oss << _lutVar << ".ApplyPreset('Blue to Red Rainbow',True);";
439 case MEDCALC::COLOR_MAP_COOL_TO_WARM:
440 oss << _lutVar << ".ApplyPreset('Cool to Warm',True);";
443 STDLOG("MEDPresentation::getColorMapCommand(): invalid colormap!");
444 throw KERNEL::createSalomeException("MEDPresentation::getColorMapCommand(): invalid colormap!");
446 pushAndExecPyLine(oss.str());
448 selectFieldComponent(); // somehow PV keeps the LUT parameters of the previous presentation, so better reset this.
452 MEDPresentation::showObject()
454 std::ostringstream oss;
455 oss << _dispVar << " = pvs.Show(" << _objVar << ", " << getRenderViewVar() << ");";
456 pushAndExecPyLine(oss.str());
460 MEDPresentation::showScalarBar()
462 std::ostringstream oss;
463 oss << _dispVar << ".SetScalarBarVisibility(" << getRenderViewVar() << ", True);";
464 pushAndExecPyLine(oss.str());
468 MEDPresentation::colorBy()
470 std::ostringstream oss;
471 oss << "pvs.ColorBy(" << _dispVar << ", ('" << _colorByType << "', '" << _fieldName << "'));";
472 pushAndExecPyLine(oss.str());
476 MEDPresentation::rescaleTransferFunction()
478 std::ostringstream oss;
481 case MEDCALC::SCALAR_BAR_ALL_TIMESTEPS:
482 oss << _dispVar << ".RescaleTransferFunctionToDataRangeOverTime();";
484 case MEDCALC::SCALAR_BAR_CURRENT_TIMESTEP:
485 oss << _dispVar << ".RescaleTransferFunctionToDataRange(False);";
488 STDLOG("MEDPresentation::getRescaleCommand(): invalid range!");
489 throw KERNEL::createSalomeException("MEDPresentation::getRescaleCommand(): invalid range!");
491 pushAndExecPyLine(oss.str()); oss.str("");
493 oss << _rangeVar << " = [" << _dispVar << ".LookupTable.RGBPoints[0], " << _dispVar << ".LookupTable.RGBPoints[-4]];";
494 pushAndExecPyLine(oss.str());
496 // Adapt scalar bar title
503 MEDPresentation::GeneratePythonId()
505 static int INIT_ID = 0;
510 MEDPresentation::activateView()
512 MEDPyLockWrapper lock;
514 execPyLine("__alive = " + getRenderViewVar() + " in pvs.GetRenderViews()");
515 PyObject * obj = getPythonObjectFromMain("__alive");
517 if (obj && PyBool_Check(obj))
518 alive = (obj == Py_True);
521 // The view is still there,just activate it:
522 pushAndExecPyLine("pvs.SetActiveView(" + getRenderViewVar() + ");");
525 // The view disappeared, recreate it in a new layout. The transfer of the objects is to be done by the caller.
526 std::ostringstream oss;
527 oss << "pvs.servermanager.misc.ViewLayout(registrationGroup='layouts');";
528 pushAndExecPyLine(oss.str()); oss.str("");
529 oss << getRenderViewVar() << " = pvs.CreateView('RenderView');";
530 pushAndExecPyLine(oss.str()); oss.str("");
536 * Called when the view has been recreated (because the user closed it).
537 * All the objects and set up are re-shown in the new view (which is stored in the same Python variable).
540 MEDPresentation::recreateViewSetup()
546 rescaleTransferFunction();
547 resetCameraAndRender();
551 MEDPresentation::paravisDump() const
555 for (vector<string>::const_iterator it=_pythonCmds.begin(); it != _pythonCmds.end(); ++it)
564 * Query all available component names for the field associated with this presentation.
565 * Fills in all the corresponding string properties:
569 * and the number of components.
572 MEDPresentation::fillAvailableFieldComponents()
574 MEDPyLockWrapper lock; // GIL!
577 if(_pvFieldType == "CELLS") {
580 else if (_pvFieldType == "POINTS") {
584 std::string msg("Unsupported spatial discretisation: " + _pvFieldType);
586 throw KERNEL::createSalomeException(msg.c_str());
589 std::ostringstream oss;
590 oss << "__nbCompo = " << _srcObjVar << "." << typ << ".GetArray('" << _fieldName << "').GetNumberOfComponents();";
591 execPyLine(oss.str());
592 PyObject* p_obj = getPythonObjectFromMain("__nbCompo");
594 if (p_obj && PyLong_Check(p_obj))
595 nbCompo = PyLong_AS_LONG(p_obj);
598 STDLOG("Unexpected Python error");
599 throw KERNEL::createSalomeException("Unexpected Python error");
601 setIntProperty(MEDPresentation::PROP_NB_COMPONENTS, nbCompo);
602 for (long i = 0; i<nbCompo; i++)
604 std::ostringstream oss2;
605 oss2 << "__compo = " << _srcObjVar << "." << typ << ".GetArray('" << _fieldName << "').GetComponentName(" << i << ");";
606 execPyLine(oss2.str());
607 PyObject* p_obj = getPythonObjectFromMain("__compo");
609 if (p_obj && PyUnicode_Check(p_obj))
610 compo = std::string(Py_EncodeLocale(PyUnicode_AS_UNICODE(p_obj), NULL)); // pointing to internal Python memory, so make a copy!!
613 STDLOG("Unexpected Python error");
614 throw KERNEL::createSalomeException("Unexpected Python error");
616 std::ostringstream oss_p;
617 oss_p << MEDPresentation::PROP_COMPONENT << i;
618 setStringProperty(oss_p.str(), compo);
623 * In case where a CELLS field needs to be converted to POINT field.
624 * This updates the source object to become the result of the CellDatatoPointData filter.
627 MEDPresentation::applyCellToPointIfNeeded()
629 if (_pvFieldType == "CELLS")
631 std::ostringstream oss, oss2;
632 // Apply Cell data to point data:
633 oss2 << "__srcObj" << GeneratePythonId();
634 oss << oss2.str() << " = pvs.CellDatatoPointData(Input=" << _srcObjVar << ");";
635 pushAndExecPyLine(oss.str()); oss.str("");
636 // Now the source becomes the result of the CellDatatoPointData:
637 _srcObjVar = oss2.str();
642 // * Convert a vector field into a 3D vector field:
643 // * - if the vector field is already 3D, nothing to do
644 // * - if it is 2D, then add a null component
645 // * - otherwise (tensor field, scalar field) throw
648 //MEDPresentation::convertTo3DVectorField()
650 // std::ostringstream oss, oss1, oss2, oss3;
652 // int nbCompo = getIntProperty(MEDPresentation::PROP_NB_COMPONENTS);
653 // if (nbCompo < 2 || nbCompo > 3)
655 // oss << "The field '" << _fieldName << "' must have 2 or 3 components for this presentation!";
656 // STDLOG(oss.str());
657 // throw KERNEL::createSalomeException(oss.str().c_str());
662 // // Apply calculator:
663 // oss2 << "__srcObj" << GeneratePythonId();
664 // oss << oss2.str() << " = pvs.Calculator(Input=" << _srcObjVar << ");";
665 // pushAndExecPyLine(oss.str()); oss.str("");
666 // // Now the source becomes the result of the CellDatatoPointData:
667 // _srcObjVar = oss2.str();
669 // if(_pvFieldType == "CELLS")
670 // typ = "Cell Data";
671 // else if(_pvFieldType == "POINTS")
672 // typ = "Point Data";
675 // oss3 << "Field '" << _fieldName << "' has invalid field type";
676 // STDLOG(oss3.str());
677 // throw KERNEL::createSalomeException(oss3.str().c_str());
679 // oss << _srcObjVar << ".AttributeMode = '" << typ << "';";
680 // pushAndExecPyLine(oss.str()); oss.str("");
681 // oss << _srcObjVar << ".ResultArrayName = '" << _fieldName << "_CALC';"; // will never be needed I think
682 // pushAndExecPyLine(oss.str()); oss.str("");
683 // oss << _srcObjVar << ".Function = '" << _fieldName << "_0*iHat + " << _fieldName << "_1*jHat + 0.0*zHat';";
684 // pushAndExecPyLine(oss.str()); oss.str("");