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 const std::string MEDPresentation::PROP_NAME = "name";
33 const std::string MEDPresentation::PROP_NB_COMPONENTS = "nbComponents";
34 const std::string MEDPresentation::PROP_SELECTED_COMPONENT = "selectedComponent";
35 const std::string MEDPresentation::PROP_COMPONENT = "component_";
36 const std::string MEDPresentation::PROP_COLOR_MAP = "colorMap";
37 const std::string MEDPresentation::PROP_SCALAR_BAR_RANGE = "scalarBarRange";
39 MEDPresentation::MEDPresentation(MEDPresentation::TypeID handlerId, const std::string& name,
40 const MEDCALC::ViewModeType viewMode,
41 const MEDCALC::ColorMapType colorMap,
42 const MEDCALC::ScalarBarRangeType sbRange)
43 : _handlerId(handlerId), _propertiesStr(),
44 _mcFieldType(MEDCoupling::ON_CELLS),
45 _pvFieldType(""), _meshName(""), _fieldName(""), _fileName(""),
46 _selectedComponentIndex(-1),
50 _renderViewPyId(-1), // will be set by MEDPresentationManager_i::_makePresentation()
53 setStringProperty(MEDPresentation::PROP_NAME, name);
55 setIntProperty(MEDPresentation::PROP_NB_COMPONENTS, 0);
56 setIntProperty(MEDPresentation::PROP_SELECTED_COMPONENT, 0);
58 setIntProperty(MEDPresentation::PROP_COLOR_MAP, static_cast<int>(colorMap));
59 setIntProperty(MEDPresentation::PROP_SCALAR_BAR_RANGE, static_cast<int>(sbRange));
62 int id = GeneratePythonId();
63 std::ostringstream oss_o, oss_d, oss_l, oss_s, oss_r;
64 oss_o << "__obj" << id;
65 oss_s << "__srcObj" << id;
66 oss_d << "__disp" << id;
67 oss_l << "__lut" << id;
68 oss_r << "__range" << id;
69 _objVar = oss_o.str();
70 _srcObjVar = oss_s.str();
71 _dispVar = oss_d.str();
72 _lutVar = oss_l.str();
73 _rangeVar = oss_r.str();
77 * For most of the presentations the field name etc is required.
78 * For the MEDPresentationMeshView however, the handler ID is a mesh handler ID, not a field, and the
79 * treatment is specific.
82 MEDPresentation::initFieldMeshInfos()
84 MEDCALC::MEDDataManager_ptr dataManager(MEDFactoryClient::getDataManager());
85 MEDCALC::FieldHandler* fieldHandler = dataManager->getFieldHandler(_handlerId);
86 MEDCALC::MeshHandler* meshHandler = dataManager->getMeshHandler(fieldHandler->meshid);
87 MEDCALC::DatasourceHandler* dataSHandler = dataManager->getDatasourceHandlerFromID(meshHandler->sourceid);
89 extractFileName(std::string(dataSHandler->uri));
91 _fieldName = fieldHandler->fieldname;
92 _mcFieldType = (MEDCoupling::TypeOfField) fieldHandler->type;
93 _pvFieldType = getPVFieldTypeString(_mcFieldType);
94 _colorByType = _pvFieldType; // by default the same; overridden in DeflectionShape, VectorField, PointSprite and Contour
95 _meshName = meshHandler->name;
99 MEDPresentation::extractFileName(const std::string& name)
102 if (_fileName.substr(0, 7) != std::string("file://")) {
103 const char* msg = "MEDPresentation(): Data source is not a file! Can not proceed.";
105 throw MEDPresentationException(msg);
107 _fileName = _fileName.substr(7, _fileName.size());
110 MEDPresentation::~MEDPresentation()
112 STDLOG("~MEDPresentation(): clear display");
114 MEDPyLockWrapper lock;
115 std::ostringstream oss;
117 oss << "pvs.Hide(" << _objVar << ", view=" << getRenderViewVar() << ");";
118 execPyLine(oss.str());
119 // :TRICKY: The two following lines raise an exception when closing MED module
120 // after sequence: MED - load file - PARAVIS - MED - close SALOME
121 // (see Mantis #23461)
122 //execPyLine(getRenderViewVar() + ".ResetCamera();");
123 //execPyLine("pvs.Render();");
128 MEDPresentation::generatePipeline()
130 // Might be more complicated in the future:
132 this->internalGeneratePipeline();
136 //MEDPresentation::pushPyObjects(PyObjectId obj, PyObjectId disp)
138 // _pipeline.push_back(obj);
139 // _display.push_back(disp);
143 MEDPresentation::pushAndExecPyLine(const std::string & lin)
146 _pythonCmds.push_back(lin);
150 MEDPresentation::execPyLine(const std::string & lin)
152 MEDPyLockWrapper lock;
153 STDLOG("@@@@ MEDPresentation::execPyLine() about to exec >> " << lin);
154 if(PyRun_SimpleString(lin.c_str()))
156 std::ostringstream oss;
157 oss << "MEDPresentation::execPyLine(): following Python command failed!\n";
160 throw KERNEL::createSalomeException(oss.str().c_str());
165 MEDPresentation::setStringProperty(const std::string& propName, const std::string& propValue)
167 _propertiesStr[propName] = propValue;
171 MEDPresentation::getStringProperty(const std::string& propName) const
173 std::map<std::string, std::string>::const_iterator it = _propertiesStr.find(propName);
174 if (it != _propertiesStr.end()) {
178 STDLOG("MEDPresentation::getStringProperty(): no property named " + propName);
179 throw MEDPresentationException("MEDPresentation::getStringProperty(): no property named " + propName);
184 MEDPresentation::setIntProperty(const std::string& propName, const int propValue)
186 _propertiesInt[propName] = propValue;
190 MEDPresentation::getIntProperty(const std::string& propName) const
192 std::map<std::string, int>::const_iterator it = _propertiesInt.find(propName);
193 if (it != _propertiesInt.end()) {
197 STDLOG("MEDPresentation::getIntProperty(): no property named " + propName);
198 throw MEDPresentationException("MEDPresentation::getIntProperty(): no property named " + propName);
203 MEDPresentation::dumpIntProperties() const
205 std::map<std::string, int>::const_iterator it = _propertiesInt.begin();
206 STDLOG("@@@ Dumping INT properties");
207 for(; it != _propertiesInt.end(); ++it)
209 std::ostringstream oss;
210 oss << (*it).first << " -> " << (*it).second;
216 MEDPresentation::dumpStringProperties() const
218 std::map<std::string, std::string>::const_iterator it = _propertiesStr.begin();
219 STDLOG("@@@ Dumping STR properties");
220 for(; it != _propertiesStr.end(); ++it)
222 std::ostringstream oss;
223 oss << (*it).first << " -> " << (*it).second;
229 MEDPresentation::internalGeneratePipeline()
231 MEDPyLockWrapper lock;
232 pushAndExecPyLine( "import pvsimple as pvs;");
233 pushAndExecPyLine( "import medcalc");
238 * @return a borrowed reference. Do not DECRREF!
241 MEDPresentation::getPythonObjectFromMain(const char* python_var) const
245 // All the calls below returns *borrowed* references
246 PyObject* main_module = PyImport_AddModule((char*)"__main__");
247 _globalDict = PyModule_GetDict(main_module);
249 return PyDict_GetItemString(_globalDict, python_var);
253 MEDPresentation::getPVFieldTypeString(MEDCoupling::TypeOfField fieldType) const
257 case MEDCoupling::ON_CELLS:
259 case MEDCoupling::ON_NODES:
261 case MEDCoupling::ON_GAUSS_PT:
262 return "POINTS"; // because internally after application of the ELGA filter, the field will appear as a POINT field
263 case MEDCoupling::ON_GAUSS_NE:
264 return "POINTS"; // because internally after application of the ELNO mesh filter, the field will appear as a POINT field
266 STDLOG("MEDPresentation::getPVFieldTypeString() -- Not implemented ! ELNO field?");
272 MEDPresentation::getRenderViewVar() const
274 std::ostringstream oss;
275 oss << "__view" << _renderViewPyId;
280 * Creates the MEDReader source in the pipeline, and potentially apply GAUSS/ELNO filters.
283 MEDPresentation::createSource()
286 switch(_mcFieldType) {
287 case MEDCoupling::ON_CELLS: typ = "P0"; break;
288 case MEDCoupling::ON_NODES: typ = "P1"; break;
289 case MEDCoupling::ON_GAUSS_PT: typ = "GAUSS"; break;
290 case MEDCoupling::ON_GAUSS_NE: typ = "GSSNE"; break;
292 const char * msg ="MEDPresentation::createSource(): field type not impl. yet!";
294 throw KERNEL::createSalomeException(msg);
297 std::ostringstream oss;
298 oss << _srcObjVar << " = pvs.MEDReader(FileName='" << _fileName << "');";
299 pushAndExecPyLine(oss.str()); oss.str("");
300 oss << "medcalc.SelectSourceField(" << _srcObjVar << ", '" << _meshName << "', '"
301 << _fieldName << "', '" << typ << "');";
302 pushAndExecPyLine(oss.str()); oss.str("");
303 // Generate complete vector fields: fields with 2 components will copied into <name>_vector and
304 // have a third null component added.
305 oss << _srcObjVar << ".GenerateVectors = 1;";
306 pushAndExecPyLine(oss.str()); oss.str("");
308 // Make sure this is set so we stick to time steps:
309 pushAndExecPyLine("pvs.GetAnimationScene().PlayMode = 'Snap To TimeSteps'");
311 // Deal with GAUSS fields:
312 if(_mcFieldType == MEDCoupling::ON_GAUSS_PT)
314 std::ostringstream oss, oss2;
315 oss2 << "__srcObj" << GeneratePythonId();
316 oss << oss2.str() << " = pvs.GaussPoints(Input=" << _srcObjVar << ");";
317 pushAndExecPyLine(oss.str()); oss.str("");
318 // Now the source becomes the result of the CellDatatoPointData:
319 _srcObjVar = oss2.str();
320 oss << _srcObjVar << ".SelectSourceArray = ['CELLS', 'ELGA@0'];";
321 pushAndExecPyLine(oss.str()); oss.str("");
323 if(_mcFieldType == MEDCoupling::ON_GAUSS_NE)
325 std::ostringstream oss, oss2;
326 oss2 << "__srcObj" << GeneratePythonId();
327 oss << oss2.str() << " = pvs.ELNOMesh(Input=" << _srcObjVar << ");";
328 pushAndExecPyLine(oss.str()); oss.str("");
329 // Now the source becomes the result of the CellDatatoPointData:
330 _srcObjVar = oss2.str();
335 MEDPresentation::setOrCreateRenderView()
337 std::ostringstream oss2;
339 std::string view(getRenderViewVar());
340 oss2 << "pvs._DisableFirstRenderCameraReset();";
341 pushAndExecPyLine(oss2.str()); oss2.str("");
342 if (_viewMode == MEDCALC::VIEW_MODE_OVERLAP) {
343 // this might potentially re-assign to an existing view variable, but this is OK, we
344 // normally reassign exactly the same RenderView object.
345 oss2 << view << " = pvs.GetActiveViewOrCreate('RenderView');";
346 pushAndExecPyLine(oss2.str()); oss2.str("");
347 } else if (_viewMode == MEDCALC::VIEW_MODE_REPLACE) {
349 oss2 << view << " = pvs.GetActiveViewOrCreate('RenderView');";
350 pushAndExecPyLine(oss2.str()); oss2.str("");
351 oss2 << "pvs.active_objects.source and pvs.Hide(view=" << view << ");";
352 pushAndExecPyLine(oss2.str()); oss2.str("");
353 oss2 << "pvs.Render();";
354 pushAndExecPyLine(oss2.str()); oss2.str("");
355 } else if (_viewMode == MEDCALC::VIEW_MODE_NEW_LAYOUT) {
356 oss2 << "__layout1 = pvs.servermanager.misc.ViewLayout(registrationGroup='layouts');";
357 pushAndExecPyLine(oss2.str()); oss2.str("");
358 oss2 << view << " = pvs.CreateView('RenderView');";
359 pushAndExecPyLine(oss2.str()); oss2.str("");
360 } else if (_viewMode == MEDCALC::VIEW_MODE_SPLIT_VIEW) {
361 oss2 << view << " = pvs.CreateView('RenderView');";
362 pushAndExecPyLine(oss2.str()); oss2.str("");
367 MEDPresentation::resetCameraAndRender()
369 pushAndExecPyLine(getRenderViewVar() + ".ResetCamera();");
370 pushAndExecPyLine("pvs.Render();");
374 MEDPresentation::selectFieldComponent()
376 std::ostringstream oss, oss_l;
379 if (_selectedComponentIndex != -1)
381 oss << _lutVar << ".VectorMode = 'Component';";
382 pushAndExecPyLine(oss.str()); oss.str("");
383 oss << _lutVar << ".VectorComponent = " << _selectedComponentIndex << ";";
384 pushAndExecPyLine(oss.str()); oss.str("");
386 else // Euclidean norm
388 oss << _lutVar << ".VectorMode = 'Magnitude';";
389 pushAndExecPyLine(oss.str()); oss.str("");
394 * Needs the LUT, so to be called after selectColorMap for the first time.
397 MEDPresentation::scalarBarTitle()
399 // get selected component name:
400 std::string compoName;
401 if (_selectedComponentIndex != -1)
403 std::ostringstream oss1;
404 oss1 << MEDPresentation::PROP_COMPONENT << _selectedComponentIndex;
405 compoName = getStringProperty(oss1.str());
409 if (getIntProperty(MEDPresentation::PROP_NB_COMPONENTS) == 1)
412 compoName = "Magnitude";
414 std::ostringstream oss;
415 oss << "pvs.GetScalarBar(" << _lutVar << ").ComponentTitle = '" << compoName << "';";
416 pushAndExecPyLine(oss.str()); oss.str("");
420 MEDPresentation::selectColorMap()
422 std::ostringstream oss, oss2;
424 oss2 << _lutVar << " = pvs.GetColorTransferFunction('" << _fieldName << "');";
425 pushAndExecPyLine(oss2.str());
428 case MEDCALC::COLOR_MAP_BLUE_TO_RED_RAINBOW:
429 oss << _lutVar << ".ApplyPreset('Blue to Red Rainbow',True);";
431 case MEDCALC::COLOR_MAP_COOL_TO_WARM:
432 oss << _lutVar << ".ApplyPreset('Cool to Warm',True);";
435 STDLOG("MEDPresentation::getColorMapCommand(): invalid colormap!");
436 throw KERNEL::createSalomeException("MEDPresentation::getColorMapCommand(): invalid colormap!");
438 pushAndExecPyLine(oss.str());
440 selectFieldComponent(); // somehow PV keeps the LUT parameters of the previous presentation, so better reset this.
444 MEDPresentation::showObject()
446 std::ostringstream oss;
447 oss << _dispVar << " = pvs.Show(" << _objVar << ", " << getRenderViewVar() << ");";
448 pushAndExecPyLine(oss.str());
452 MEDPresentation::showScalarBar()
454 std::ostringstream oss;
455 oss << _dispVar << ".SetScalarBarVisibility(" << getRenderViewVar() << ", True);";
456 pushAndExecPyLine(oss.str());
460 MEDPresentation::colorBy()
462 std::ostringstream oss;
463 oss << "pvs.ColorBy(" << _dispVar << ", ('" << _colorByType << "', '" << _fieldName << "'));";
464 pushAndExecPyLine(oss.str());
468 MEDPresentation::rescaleTransferFunction()
470 std::ostringstream oss;
473 case MEDCALC::SCALAR_BAR_ALL_TIMESTEPS:
474 oss << _dispVar << ".RescaleTransferFunctionToDataRangeOverTime();";
476 case MEDCALC::SCALAR_BAR_CURRENT_TIMESTEP:
477 oss << _dispVar << ".RescaleTransferFunctionToDataRange(False);";
480 STDLOG("MEDPresentation::getRescaleCommand(): invalid range!");
481 throw KERNEL::createSalomeException("MEDPresentation::getRescaleCommand(): invalid range!");
483 pushAndExecPyLine(oss.str()); oss.str("");
485 oss << _rangeVar << " = [" << _dispVar << ".LookupTable.RGBPoints[0], " << _dispVar << ".LookupTable.RGBPoints[-4]];";
486 pushAndExecPyLine(oss.str());
488 // Adapt scalar bar title
495 MEDPresentation::GeneratePythonId()
497 static int INIT_ID = 0;
502 MEDPresentation::activateView()
504 MEDPyLockWrapper lock;
506 execPyLine("__alive = " + getRenderViewVar() + " in pvs.GetRenderViews()");
507 PyObject * obj = getPythonObjectFromMain("__alive");
509 if (obj && PyBool_Check(obj))
510 alive = (obj == Py_True);
513 // The view is still there,just activate it:
514 pushAndExecPyLine("pvs.SetActiveView(" + getRenderViewVar() + ");");
517 // The view disappeared, recreate it in a new layout. The transfer of the objects is to be done by the caller.
518 std::ostringstream oss;
519 oss << "pvs.servermanager.misc.ViewLayout(registrationGroup='layouts');";
520 pushAndExecPyLine(oss.str()); oss.str("");
521 oss << getRenderViewVar() << " = pvs.CreateView('RenderView');";
522 pushAndExecPyLine(oss.str()); oss.str("");
528 * Called when the view has been recreated (because the user closed it).
529 * All the objects and set up are re-shown in the new view (which is stored in the same Python variable).
532 MEDPresentation::recreateViewSetup()
538 rescaleTransferFunction();
539 resetCameraAndRender();
543 MEDPresentation::paravisDump() const
547 for (vector<string>::const_iterator it=_pythonCmds.begin(); it != _pythonCmds.end(); ++it)
556 * Query all available component names for the field associated with this presentation.
557 * Fills in all the corresponding string properties:
561 * and the number of components.
564 MEDPresentation::fillAvailableFieldComponents()
566 MEDPyLockWrapper lock; // GIL!
569 if(_pvFieldType == "CELLS") {
572 else if (_pvFieldType == "POINTS") {
576 std::string msg("Unsupported spatial discretisation: " + _pvFieldType);
578 throw KERNEL::createSalomeException(msg.c_str());
581 std::ostringstream oss;
582 oss << "__nbCompo = " << _srcObjVar << "." << typ << ".GetArray('" << _fieldName << "').GetNumberOfComponents();";
583 execPyLine(oss.str());
584 PyObject* p_obj = getPythonObjectFromMain("__nbCompo");
586 if (p_obj && PyInt_Check(p_obj))
587 nbCompo = PyInt_AS_LONG(p_obj);
590 STDLOG("Unexpected Python error");
591 throw KERNEL::createSalomeException("Unexpected Python error");
593 setIntProperty(MEDPresentation::PROP_NB_COMPONENTS, nbCompo);
594 for (long i = 0; i<nbCompo; i++)
596 std::ostringstream oss2;
597 oss2 << "__compo = " << _srcObjVar << "." << typ << ".GetArray('" << _fieldName << "').GetComponentName(" << i << ");";
598 execPyLine(oss2.str());
599 PyObject* p_obj = getPythonObjectFromMain("__compo");
601 if (p_obj && PyString_Check(p_obj))
602 compo = std::string(PyString_AsString(p_obj)); // pointing to internal Python memory, so make a copy!!
605 STDLOG("Unexpected Python error");
606 throw KERNEL::createSalomeException("Unexpected Python error");
608 std::ostringstream oss_p;
609 oss_p << MEDPresentation::PROP_COMPONENT << i;
610 setStringProperty(oss_p.str(), compo);
615 * In case where a CELLS field needs to be converted to POINT field.
616 * This updates the source object to become the result of the CellDatatoPointData filter.
619 MEDPresentation::applyCellToPointIfNeeded()
621 if (_pvFieldType == "CELLS")
623 std::ostringstream oss, oss2;
624 // Apply Cell data to point data:
625 oss2 << "__srcObj" << GeneratePythonId();
626 oss << oss2.str() << " = pvs.CellDatatoPointData(Input=" << _srcObjVar << ");";
627 pushAndExecPyLine(oss.str()); oss.str("");
628 // Now the source becomes the result of the CellDatatoPointData:
629 _srcObjVar = oss2.str();
634 // * Convert a vector field into a 3D vector field:
635 // * - if the vector field is already 3D, nothing to do
636 // * - if it is 2D, then add a null component
637 // * - otherwise (tensor field, scalar field) throw
640 //MEDPresentation::convertTo3DVectorField()
642 // std::ostringstream oss, oss1, oss2, oss3;
644 // int nbCompo = getIntProperty(MEDPresentation::PROP_NB_COMPONENTS);
645 // if (nbCompo < 2 || nbCompo > 3)
647 // oss << "The field '" << _fieldName << "' must have 2 or 3 components for this presentation!";
648 // STDLOG(oss.str());
649 // throw KERNEL::createSalomeException(oss.str().c_str());
654 // // Apply calculator:
655 // oss2 << "__srcObj" << GeneratePythonId();
656 // oss << oss2.str() << " = pvs.Calculator(Input=" << _srcObjVar << ");";
657 // pushAndExecPyLine(oss.str()); oss.str("");
658 // // Now the source becomes the result of the CellDatatoPointData:
659 // _srcObjVar = oss2.str();
661 // if(_pvFieldType == "CELLS")
662 // typ = "Cell Data";
663 // else if(_pvFieldType == "POINTS")
664 // typ = "Point Data";
667 // oss3 << "Field '" << _fieldName << "' has invalid field type";
668 // STDLOG(oss3.str());
669 // throw KERNEL::createSalomeException(oss3.str().c_str());
671 // oss << _srcObjVar << ".AttributeMode = '" << typ << "';";
672 // pushAndExecPyLine(oss.str()); oss.str("");
673 // oss << _srcObjVar << ".ResultArrayName = '" << _fieldName << "_CALC';"; // will never be needed I think
674 // pushAndExecPyLine(oss.str()); oss.str("");
675 // oss << _srcObjVar << ".Function = '" << _fieldName << "_0*iHat + " << _fieldName << "_1*jHat + 0.0*zHat';";
676 // pushAndExecPyLine(oss.str()); oss.str("");