1 // Copyright (C) 2011-2016 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 execPyLine(getRenderViewVar() + ".ResetCamera();");
128 execPyLine("pvs.Render();");
133 MEDPresentation::generatePipeline()
135 // Might be more complicated in the future:
137 this->internalGeneratePipeline();
141 //MEDPresentation::pushPyObjects(PyObjectId obj, PyObjectId disp)
143 // _pipeline.push_back(obj);
144 // _display.push_back(disp);
148 MEDPresentation::pushAndExecPyLine(const std::string & lin)
151 _pythonCmds.push_back(lin);
155 MEDPresentation::execPyLine(const std::string & lin)
157 MEDPyLockWrapper lock;
158 STDLOG("@@@@ MEDPresentation::execPyLine() about to exec >> " << lin);
159 if(PyRun_SimpleString(lin.c_str()))
161 std::ostringstream oss;
162 oss << "MEDPresentation::execPyLine(): following Python command failed!\n";
165 throw KERNEL::createSalomeException(oss.str().c_str());
170 MEDPresentation::setStringProperty(const std::string& propName, const std::string& propValue)
172 _propertiesStr[propName] = propValue;
176 MEDPresentation::getStringProperty(const std::string& propName) const
178 std::map<std::string, std::string>::const_iterator it = _propertiesStr.find(propName);
179 if (it != _propertiesStr.end()) {
183 STDLOG("MEDPresentation::getStringProperty(): no property named " + propName);
184 throw MEDPresentationException("MEDPresentation::getStringProperty(): no property named " + propName);
189 MEDPresentation::setIntProperty(const std::string& propName, const int propValue)
191 _propertiesInt[propName] = propValue;
195 MEDPresentation::getIntProperty(const std::string& propName) const
197 std::map<std::string, int>::const_iterator it = _propertiesInt.find(propName);
198 if (it != _propertiesInt.end()) {
202 STDLOG("MEDPresentation::getIntProperty(): no property named " + propName);
203 throw MEDPresentationException("MEDPresentation::getIntProperty(): no property named " + propName);
208 MEDPresentation::dumpIntProperties() const
210 std::map<std::string, int>::const_iterator it = _propertiesInt.begin();
211 STDLOG("@@@ Dumping INT properties");
212 for(; it != _propertiesInt.end(); ++it)
214 std::ostringstream oss;
215 oss << (*it).first << " -> " << (*it).second;
221 MEDPresentation::dumpStringProperties() const
223 std::map<std::string, std::string>::const_iterator it = _propertiesStr.begin();
224 STDLOG("@@@ Dumping STR properties");
225 for(; it != _propertiesStr.end(); ++it)
227 std::ostringstream oss;
228 oss << (*it).first << " -> " << (*it).second;
234 MEDPresentation::internalGeneratePipeline()
236 MEDPyLockWrapper lock;
237 pushAndExecPyLine( "import pvsimple as pvs;");
238 pushAndExecPyLine( "import medcalc");
243 * @return a borrowed reference. Do not DECRREF!
246 MEDPresentation::getPythonObjectFromMain(const char* python_var) const
250 // All the calls below returns *borrowed* references
251 PyObject* main_module = PyImport_AddModule((char*)"__main__");
252 _globalDict = PyModule_GetDict(main_module);
254 return PyDict_GetItemString(_globalDict, python_var);
258 MEDPresentation::getPVFieldTypeString(MEDCoupling::TypeOfField fieldType) const
262 case MEDCoupling::ON_CELLS:
264 case MEDCoupling::ON_NODES:
266 case MEDCoupling::ON_GAUSS_PT:
267 return "POINTS"; // because internally after application of the ELGA filter, the field will appear as a POINT field
268 case MEDCoupling::ON_GAUSS_NE:
269 return "POINTS"; // because internally after application of the ELNO mesh filter, the field will appear as a POINT field
271 STDLOG("MEDPresentation::getPVFieldTypeString() -- Not implemented ! ELNO field?");
277 MEDPresentation::getRenderViewVar() const
279 std::ostringstream oss;
280 oss << "__view" << _renderViewPyId;
285 * Creates the MEDReader source in the pipeline, and potentially apply GAUSS/ELNO filters.
288 MEDPresentation::createSource()
291 switch(_mcFieldType) {
292 case MEDCoupling::ON_CELLS: typ = "P0"; break;
293 case MEDCoupling::ON_NODES: typ = "P1"; break;
294 case MEDCoupling::ON_GAUSS_PT: typ = "GAUSS"; break;
295 case MEDCoupling::ON_GAUSS_NE: typ = "GSSNE"; break;
297 const char * msg ="MEDPresentation::createSource(): field type not impl. yet!";
299 throw KERNEL::createSalomeException(msg);
302 std::ostringstream oss;
303 oss << _srcObjVar << " = pvs.MEDReader(FileName='" << _fileName << "');";
304 pushAndExecPyLine(oss.str()); oss.str("");
305 oss << "medcalc.SelectSourceField(" << _srcObjVar << ", '" << _meshName << "', '"
306 << _fieldName << "', '" << typ << "');";
307 pushAndExecPyLine(oss.str()); oss.str("");
308 // Generate complete vector fields: fields with 2 components will copied into <name>_vector and
309 // have a third null component added.
310 oss << _srcObjVar << ".GenerateVectors = 1;";
311 pushAndExecPyLine(oss.str()); oss.str("");
313 // Make sure this is set so we stick to time steps:
314 pushAndExecPyLine("pvs.GetAnimationScene().PlayMode = 'Snap To TimeSteps'");
316 // Deal with GAUSS fields:
317 if(_mcFieldType == MEDCoupling::ON_GAUSS_PT)
319 std::ostringstream oss, oss2;
320 oss2 << "__srcObj" << GeneratePythonId();
321 oss << oss2.str() << " = pvs.GaussPoints(Input=" << _srcObjVar << ");";
322 pushAndExecPyLine(oss.str()); oss.str("");
323 // Now the source becomes the result of the CellDatatoPointData:
324 _srcObjVar = oss2.str();
325 oss << _srcObjVar << ".SelectSourceArray = ['CELLS', 'ELGA@0'];";
326 pushAndExecPyLine(oss.str()); oss.str("");
328 if(_mcFieldType == MEDCoupling::ON_GAUSS_NE)
330 std::ostringstream oss, oss2;
331 oss2 << "__srcObj" << GeneratePythonId();
332 oss << oss2.str() << " = pvs.ELNOMesh(Input=" << _srcObjVar << ");";
333 pushAndExecPyLine(oss.str()); oss.str("");
334 // Now the source becomes the result of the CellDatatoPointData:
335 _srcObjVar = oss2.str();
340 MEDPresentation::setOrCreateRenderView()
342 std::ostringstream oss2;
344 std::string view(getRenderViewVar());
345 oss2 << "pvs._DisableFirstRenderCameraReset();";
346 pushAndExecPyLine(oss2.str()); oss2.str("");
347 if (_viewMode == MEDCALC::VIEW_MODE_OVERLAP) {
348 // this might potentially re-assign to an existing view variable, but this is OK, we
349 // normally reassign exactly the same RenderView object.
350 oss2 << view << " = pvs.GetActiveViewOrCreate('RenderView');";
351 pushAndExecPyLine(oss2.str()); oss2.str("");
352 } else if (_viewMode == MEDCALC::VIEW_MODE_REPLACE) {
354 oss2 << view << " = pvs.GetActiveViewOrCreate('RenderView');";
355 pushAndExecPyLine(oss2.str()); oss2.str("");
356 oss2 << "pvs.active_objects.source and pvs.Hide(view=" << view << ");";
357 pushAndExecPyLine(oss2.str()); oss2.str("");
358 oss2 << "pvs.Render();";
359 pushAndExecPyLine(oss2.str()); oss2.str("");
360 } else if (_viewMode == MEDCALC::VIEW_MODE_NEW_LAYOUT) {
361 oss2 << "__layout1 = pvs.servermanager.misc.ViewLayout(registrationGroup='layouts');";
362 pushAndExecPyLine(oss2.str()); oss2.str("");
363 oss2 << view << " = pvs.CreateView('RenderView');";
364 pushAndExecPyLine(oss2.str()); oss2.str("");
365 } else if (_viewMode == MEDCALC::VIEW_MODE_SPLIT_VIEW) {
366 oss2 << view << " = pvs.CreateView('RenderView');";
367 pushAndExecPyLine(oss2.str()); oss2.str("");
372 MEDPresentation::resetCameraAndRender()
374 pushAndExecPyLine(getRenderViewVar() + ".ResetCamera();");
375 pushAndExecPyLine("pvs.Render();");
379 MEDPresentation::selectFieldComponent()
381 std::ostringstream oss, oss_l;
384 if (_selectedComponentIndex != -1)
386 oss << _lutVar << ".VectorMode = 'Component';";
387 pushAndExecPyLine(oss.str()); oss.str("");
388 oss << _lutVar << ".VectorComponent = " << _selectedComponentIndex << ";";
389 pushAndExecPyLine(oss.str()); oss.str("");
391 else // Euclidean norm
393 oss << _lutVar << ".VectorMode = 'Magnitude';";
394 pushAndExecPyLine(oss.str()); oss.str("");
399 * Needs the LUT, so to be called after selectColorMap for the first time.
402 MEDPresentation::scalarBarTitle()
404 // get selected component name:
405 std::string compoName;
406 if (_selectedComponentIndex != -1)
408 std::ostringstream oss1;
409 oss1 << MEDPresentation::PROP_COMPONENT << _selectedComponentIndex;
410 compoName = getStringProperty(oss1.str());
414 if (getIntProperty(MEDPresentation::PROP_NB_COMPONENTS) == 1)
417 compoName = "Magnitude";
419 std::ostringstream oss;
420 oss << "pvs.GetScalarBar(" << _lutVar << ").ComponentTitle = '" << compoName << "';";
421 pushAndExecPyLine(oss.str()); oss.str("");
425 MEDPresentation::selectColorMap()
427 std::ostringstream oss, oss2;
429 oss2 << _lutVar << " = pvs.GetColorTransferFunction('" << _fieldName << "');";
430 pushAndExecPyLine(oss2.str());
433 case MEDCALC::COLOR_MAP_BLUE_TO_RED_RAINBOW:
434 oss << _lutVar << ".ApplyPreset('Blue to Red Rainbow',True);";
436 case MEDCALC::COLOR_MAP_COOL_TO_WARM:
437 oss << _lutVar << ".ApplyPreset('Cool to Warm',True);";
440 STDLOG("MEDPresentation::getColorMapCommand(): invalid colormap!");
441 throw KERNEL::createSalomeException("MEDPresentation::getColorMapCommand(): invalid colormap!");
443 pushAndExecPyLine(oss.str());
445 selectFieldComponent(); // somehow PV keeps the LUT parameters of the previous presentation, so better reset this.
449 MEDPresentation::showObject()
451 std::ostringstream oss;
452 oss << _dispVar << " = pvs.Show(" << _objVar << ", " << getRenderViewVar() << ");";
453 pushAndExecPyLine(oss.str());
457 MEDPresentation::showScalarBar()
459 std::ostringstream oss;
460 oss << _dispVar << ".SetScalarBarVisibility(" << getRenderViewVar() << ", True);";
461 pushAndExecPyLine(oss.str());
465 MEDPresentation::colorBy()
467 std::ostringstream oss;
468 oss << "pvs.ColorBy(" << _dispVar << ", ('" << _colorByType << "', '" << _fieldName << "'));";
469 pushAndExecPyLine(oss.str());
473 MEDPresentation::rescaleTransferFunction()
475 std::ostringstream oss;
478 case MEDCALC::SCALAR_BAR_ALL_TIMESTEPS:
479 oss << _dispVar << ".RescaleTransferFunctionToDataRangeOverTime();";
481 case MEDCALC::SCALAR_BAR_CURRENT_TIMESTEP:
482 oss << _dispVar << ".RescaleTransferFunctionToDataRange(False);";
485 STDLOG("MEDPresentation::getRescaleCommand(): invalid range!");
486 throw KERNEL::createSalomeException("MEDPresentation::getRescaleCommand(): invalid range!");
488 pushAndExecPyLine(oss.str()); oss.str("");
490 oss << _rangeVar << " = [" << _dispVar << ".LookupTable.RGBPoints[0], " << _dispVar << ".LookupTable.RGBPoints[-4]];";
491 pushAndExecPyLine(oss.str());
493 // Adapt scalar bar title
500 MEDPresentation::GeneratePythonId()
502 static int INIT_ID = 0;
507 MEDPresentation::activateView()
509 MEDPyLockWrapper lock;
511 execPyLine("__alive = " + getRenderViewVar() + " in pvs.GetRenderViews()");
512 PyObject * obj = getPythonObjectFromMain("__alive");
514 if (obj && PyBool_Check(obj))
515 alive = (obj == Py_True);
518 // The view is still there,just activate it:
519 pushAndExecPyLine("pvs.SetActiveView(" + getRenderViewVar() + ");");
522 // The view disappeared, recreate it in a new layout. The transfer of the objects is to be done by the caller.
523 std::ostringstream oss;
524 oss << "pvs.servermanager.misc.ViewLayout(registrationGroup='layouts');";
525 pushAndExecPyLine(oss.str()); oss.str("");
526 oss << getRenderViewVar() << " = pvs.CreateView('RenderView');";
527 pushAndExecPyLine(oss.str()); oss.str("");
533 * Called when the view has been recreated (because the user closed it).
534 * All the objects and set up are re-shown in the new view (which is stored in the same Python variable).
537 MEDPresentation::recreateViewSetup()
543 rescaleTransferFunction();
544 resetCameraAndRender();
548 MEDPresentation::paravisDump() const
552 for (vector<string>::const_iterator it=_pythonCmds.begin(); it != _pythonCmds.end(); ++it)
561 * Query all available component names for the field associated with this presentation.
562 * Fills in all the corresponding string properties:
566 * and the number of components.
569 MEDPresentation::fillAvailableFieldComponents()
571 MEDPyLockWrapper lock; // GIL!
574 if(_pvFieldType == "CELLS") {
577 else if (_pvFieldType == "POINTS") {
581 std::string msg("Unsupported spatial discretisation: " + _pvFieldType);
583 throw KERNEL::createSalomeException(msg.c_str());
586 std::ostringstream oss;
587 oss << "__nbCompo = " << _srcObjVar << "." << typ << ".GetArray('" << _fieldName << "').GetNumberOfComponents();";
588 execPyLine(oss.str());
589 PyObject* p_obj = getPythonObjectFromMain("__nbCompo");
591 if (p_obj && PyLong_Check(p_obj))
592 nbCompo = PyLong_AS_LONG(p_obj);
595 STDLOG("Unexpected Python error");
596 throw KERNEL::createSalomeException("Unexpected Python error");
598 setIntProperty(MEDPresentation::PROP_NB_COMPONENTS, nbCompo);
599 for (long i = 0; i<nbCompo; i++)
601 std::ostringstream oss2;
602 oss2 << "__compo = " << _srcObjVar << "." << typ << ".GetArray('" << _fieldName << "').GetComponentName(" << i << ");";
603 execPyLine(oss2.str());
604 PyObject* p_obj = getPythonObjectFromMain("__compo");
606 if (p_obj && PyUnicode_Check(p_obj))
607 compo = std::string(Py_EncodeLocale(PyUnicode_AS_UNICODE(p_obj), NULL)); // pointing to internal Python memory, so make a copy!!
610 STDLOG("Unexpected Python error");
611 throw KERNEL::createSalomeException("Unexpected Python error");
613 std::ostringstream oss_p;
614 oss_p << MEDPresentation::PROP_COMPONENT << i;
615 setStringProperty(oss_p.str(), compo);
620 * In case where a CELLS field needs to be converted to POINT field.
621 * This updates the source object to become the result of the CellDatatoPointData filter.
624 MEDPresentation::applyCellToPointIfNeeded()
626 if (_pvFieldType == "CELLS")
628 std::ostringstream oss, oss2;
629 // Apply Cell data to point data:
630 oss2 << "__srcObj" << GeneratePythonId();
631 oss << oss2.str() << " = pvs.CellDatatoPointData(Input=" << _srcObjVar << ");";
632 pushAndExecPyLine(oss.str()); oss.str("");
633 // Now the source becomes the result of the CellDatatoPointData:
634 _srcObjVar = oss2.str();
639 // * Convert a vector field into a 3D vector field:
640 // * - if the vector field is already 3D, nothing to do
641 // * - if it is 2D, then add a null component
642 // * - otherwise (tensor field, scalar field) throw
645 //MEDPresentation::convertTo3DVectorField()
647 // std::ostringstream oss, oss1, oss2, oss3;
649 // int nbCompo = getIntProperty(MEDPresentation::PROP_NB_COMPONENTS);
650 // if (nbCompo < 2 || nbCompo > 3)
652 // oss << "The field '" << _fieldName << "' must have 2 or 3 components for this presentation!";
653 // STDLOG(oss.str());
654 // throw KERNEL::createSalomeException(oss.str().c_str());
659 // // Apply calculator:
660 // oss2 << "__srcObj" << GeneratePythonId();
661 // oss << oss2.str() << " = pvs.Calculator(Input=" << _srcObjVar << ");";
662 // pushAndExecPyLine(oss.str()); oss.str("");
663 // // Now the source becomes the result of the CellDatatoPointData:
664 // _srcObjVar = oss2.str();
666 // if(_pvFieldType == "CELLS")
667 // typ = "Cell Data";
668 // else if(_pvFieldType == "POINTS")
669 // typ = "Point Data";
672 // oss3 << "Field '" << _fieldName << "' has invalid field type";
673 // STDLOG(oss3.str());
674 // throw KERNEL::createSalomeException(oss3.str().c_str());
676 // oss << _srcObjVar << ".AttributeMode = '" << typ << "';";
677 // pushAndExecPyLine(oss.str()); oss.str("");
678 // oss << _srcObjVar << ".ResultArrayName = '" << _fieldName << "_CALC';"; // will never be needed I think
679 // pushAndExecPyLine(oss.str()); oss.str("");
680 // oss << _srcObjVar << ".Function = '" << _fieldName << "_0*iHat + " << _fieldName << "_1*jHat + 0.0*zHat';";
681 // pushAndExecPyLine(oss.str()); oss.str("");