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 execPyLine(getRenderViewVar() + ".ResetCamera();");
120 execPyLine("pvs.Render();");
125 MEDPresentation::generatePipeline()
127 // Might be more complicated in the future:
129 this->internalGeneratePipeline();
133 //MEDPresentation::pushPyObjects(PyObjectId obj, PyObjectId disp)
135 // _pipeline.push_back(obj);
136 // _display.push_back(disp);
140 MEDPresentation::pushAndExecPyLine(const std::string & lin)
143 _pythonCmds.push_back(lin);
147 MEDPresentation::execPyLine(const std::string & lin)
149 MEDPyLockWrapper lock;
150 STDLOG("@@@@ MEDPresentation::execPyLine() about to exec >> " << lin);
151 if(PyRun_SimpleString(lin.c_str()))
153 std::ostringstream oss;
154 oss << "MEDPresentation::execPyLine(): following Python command failed!\n";
157 throw KERNEL::createSalomeException(oss.str().c_str());
162 MEDPresentation::setStringProperty(const std::string& propName, const std::string& propValue)
164 _propertiesStr[propName] = propValue;
168 MEDPresentation::getStringProperty(const std::string& propName) const
170 std::map<std::string, std::string>::const_iterator it = _propertiesStr.find(propName);
171 if (it != _propertiesStr.end()) {
175 STDLOG("MEDPresentation::getStringProperty(): no property named " + propName);
176 throw MEDPresentationException("MEDPresentation::getStringProperty(): no property named " + propName);
181 MEDPresentation::setIntProperty(const std::string& propName, const int propValue)
183 _propertiesInt[propName] = propValue;
187 MEDPresentation::getIntProperty(const std::string& propName) const
189 std::map<std::string, int>::const_iterator it = _propertiesInt.find(propName);
190 if (it != _propertiesInt.end()) {
194 STDLOG("MEDPresentation::getIntProperty(): no property named " + propName);
195 throw MEDPresentationException("MEDPresentation::getIntProperty(): no property named " + propName);
200 MEDPresentation::dumpIntProperties() const
202 std::map<std::string, int>::const_iterator it = _propertiesInt.begin();
203 STDLOG("@@@ Dumping INT properties");
204 for(; it != _propertiesInt.end(); ++it)
206 std::ostringstream oss;
207 oss << (*it).first << " -> " << (*it).second;
213 MEDPresentation::dumpStringProperties() const
215 std::map<std::string, std::string>::const_iterator it = _propertiesStr.begin();
216 STDLOG("@@@ Dumping STR properties");
217 for(; it != _propertiesStr.end(); ++it)
219 std::ostringstream oss;
220 oss << (*it).first << " -> " << (*it).second;
226 MEDPresentation::internalGeneratePipeline()
228 MEDPyLockWrapper lock;
229 pushAndExecPyLine( "import pvsimple as pvs;");
230 pushAndExecPyLine( "import medcalc");
235 * @return a borrowed reference. Do not DECRREF!
238 MEDPresentation::getPythonObjectFromMain(const char* python_var) const
242 // All the calls below returns *borrowed* references
243 PyObject* main_module = PyImport_AddModule((char*)"__main__");
244 _globalDict = PyModule_GetDict(main_module);
246 return PyDict_GetItemString(_globalDict, python_var);
250 MEDPresentation::getPVFieldTypeString(MEDCoupling::TypeOfField fieldType) const
254 case MEDCoupling::ON_CELLS:
256 case MEDCoupling::ON_NODES:
258 case MEDCoupling::ON_GAUSS_PT:
259 return "POINTS"; // because internally after application of the ELGA filter, the field will appear as a POINT field
260 case MEDCoupling::ON_GAUSS_NE:
261 return "POINTS"; // because internally after application of the ELNO mesh filter, the field will appear as a POINT field
263 STDLOG("MEDPresentation::getPVFieldTypeString() -- Not implemented ! ELNO field?");
269 MEDPresentation::getRenderViewVar() const
271 std::ostringstream oss;
272 oss << "__view" << _renderViewPyId;
277 * Creates the MEDReader source in the pipeline, and potentially apply GAUSS/ELNO filters.
280 MEDPresentation::createSource()
283 switch(_mcFieldType) {
284 case MEDCoupling::ON_CELLS: typ = "P0"; break;
285 case MEDCoupling::ON_NODES: typ = "P1"; break;
286 case MEDCoupling::ON_GAUSS_PT: typ = "GAUSS"; break;
287 case MEDCoupling::ON_GAUSS_NE: typ = "GSSNE"; break;
289 const char * msg ="MEDPresentation::createSource(): field type not impl. yet!";
291 throw KERNEL::createSalomeException(msg);
294 std::ostringstream oss;
295 oss << _srcObjVar << " = pvs.MEDReader(FileName='" << _fileName << "');";
296 pushAndExecPyLine(oss.str()); oss.str("");
297 oss << "medcalc.SelectSourceField(" << _srcObjVar << ", '" << _meshName << "', '"
298 << _fieldName << "', '" << typ << "');";
299 pushAndExecPyLine(oss.str()); oss.str("");
300 // Generate complete vector fields: fields with 2 components will copied into <name>_vector and
301 // have a third null component added.
302 oss << _srcObjVar << ".GenerateVectors = 1;";
303 pushAndExecPyLine(oss.str()); oss.str("");
305 // Make sure this is set so we stick to time steps:
306 pushAndExecPyLine("pvs.GetAnimationScene().PlayMode = 'Snap To TimeSteps'");
308 // Deal with GAUSS fields:
309 if(_mcFieldType == MEDCoupling::ON_GAUSS_PT)
311 std::ostringstream oss, oss2;
312 oss2 << "__srcObj" << GeneratePythonId();
313 oss << oss2.str() << " = pvs.GaussPoints(Input=" << _srcObjVar << ");";
314 pushAndExecPyLine(oss.str()); oss.str("");
315 // Now the source becomes the result of the CellDatatoPointData:
316 _srcObjVar = oss2.str();
317 oss << _srcObjVar << ".SelectSourceArray = ['CELLS', 'ELGA@0'];";
318 pushAndExecPyLine(oss.str()); oss.str("");
320 if(_mcFieldType == MEDCoupling::ON_GAUSS_NE)
322 std::ostringstream oss, oss2;
323 oss2 << "__srcObj" << GeneratePythonId();
324 oss << oss2.str() << " = pvs.ELNOMesh(Input=" << _srcObjVar << ");";
325 pushAndExecPyLine(oss.str()); oss.str("");
326 // Now the source becomes the result of the CellDatatoPointData:
327 _srcObjVar = oss2.str();
332 MEDPresentation::setOrCreateRenderView()
334 std::ostringstream oss2;
336 std::string view(getRenderViewVar());
337 oss2 << "pvs._DisableFirstRenderCameraReset();";
338 pushAndExecPyLine(oss2.str()); oss2.str("");
339 if (_viewMode == MEDCALC::VIEW_MODE_OVERLAP) {
340 // this might potentially re-assign to an existing view variable, but this is OK, we
341 // normally reassign exactly the same RenderView object.
342 oss2 << view << " = pvs.GetActiveViewOrCreate('RenderView');";
343 pushAndExecPyLine(oss2.str()); oss2.str("");
344 } else if (_viewMode == MEDCALC::VIEW_MODE_REPLACE) {
346 oss2 << view << " = pvs.GetActiveViewOrCreate('RenderView');";
347 pushAndExecPyLine(oss2.str()); oss2.str("");
348 oss2 << "pvs.active_objects.source and pvs.Hide(view=" << view << ");";
349 pushAndExecPyLine(oss2.str()); oss2.str("");
350 oss2 << "pvs.Render();";
351 pushAndExecPyLine(oss2.str()); oss2.str("");
352 } else if (_viewMode == MEDCALC::VIEW_MODE_NEW_LAYOUT) {
353 oss2 << "__layout1 = pvs.servermanager.misc.ViewLayout(registrationGroup='layouts');";
354 pushAndExecPyLine(oss2.str()); oss2.str("");
355 oss2 << view << " = pvs.CreateView('RenderView');";
356 pushAndExecPyLine(oss2.str()); oss2.str("");
357 } else if (_viewMode == MEDCALC::VIEW_MODE_SPLIT_VIEW) {
358 oss2 << view << " = pvs.CreateView('RenderView');";
359 pushAndExecPyLine(oss2.str()); oss2.str("");
364 MEDPresentation::resetCameraAndRender()
366 pushAndExecPyLine(getRenderViewVar() + ".ResetCamera();");
367 pushAndExecPyLine("pvs.Render();");
371 MEDPresentation::selectFieldComponent()
373 std::ostringstream oss, oss_l;
376 if (_selectedComponentIndex != -1)
378 oss << _lutVar << ".VectorMode = 'Component';";
379 pushAndExecPyLine(oss.str()); oss.str("");
380 oss << _lutVar << ".VectorComponent = " << _selectedComponentIndex << ";";
381 pushAndExecPyLine(oss.str()); oss.str("");
383 else // Euclidean norm
385 oss << _lutVar << ".VectorMode = 'Magnitude';";
386 pushAndExecPyLine(oss.str()); oss.str("");
391 * Needs the LUT, so to be called after selectColorMap for the first time.
394 MEDPresentation::scalarBarTitle()
396 // get selected component name:
397 std::string compoName;
398 if (_selectedComponentIndex != -1)
400 std::ostringstream oss1;
401 oss1 << MEDPresentation::PROP_COMPONENT << _selectedComponentIndex;
402 compoName = getStringProperty(oss1.str());
406 if (getIntProperty(MEDPresentation::PROP_NB_COMPONENTS) == 1)
409 compoName = "Magnitude";
411 std::ostringstream oss;
412 oss << "pvs.GetScalarBar(" << _lutVar << ").ComponentTitle = '" << compoName << "';";
413 pushAndExecPyLine(oss.str()); oss.str("");
417 MEDPresentation::selectColorMap()
419 std::ostringstream oss, oss2;
421 oss2 << _lutVar << " = pvs.GetColorTransferFunction('" << _fieldName << "');";
422 pushAndExecPyLine(oss2.str());
425 case MEDCALC::COLOR_MAP_BLUE_TO_RED_RAINBOW:
426 oss << _lutVar << ".ApplyPreset('Blue to Red Rainbow',True);";
428 case MEDCALC::COLOR_MAP_COOL_TO_WARM:
429 oss << _lutVar << ".ApplyPreset('Cool to Warm',True);";
432 STDLOG("MEDPresentation::getColorMapCommand(): invalid colormap!");
433 throw KERNEL::createSalomeException("MEDPresentation::getColorMapCommand(): invalid colormap!");
435 pushAndExecPyLine(oss.str());
437 selectFieldComponent(); // somehow PV keeps the LUT parameters of the previous presentation, so better reset this.
441 MEDPresentation::showObject()
443 std::ostringstream oss;
444 oss << _dispVar << " = pvs.Show(" << _objVar << ", " << getRenderViewVar() << ");";
445 pushAndExecPyLine(oss.str());
449 MEDPresentation::showScalarBar()
451 std::ostringstream oss;
452 oss << _dispVar << ".SetScalarBarVisibility(" << getRenderViewVar() << ", True);";
453 pushAndExecPyLine(oss.str());
457 MEDPresentation::colorBy()
459 std::ostringstream oss;
460 oss << "pvs.ColorBy(" << _dispVar << ", ('" << _colorByType << "', '" << _fieldName << "'));";
461 pushAndExecPyLine(oss.str());
465 MEDPresentation::rescaleTransferFunction()
467 std::ostringstream oss;
470 case MEDCALC::SCALAR_BAR_ALL_TIMESTEPS:
471 oss << _dispVar << ".RescaleTransferFunctionToDataRangeOverTime();";
473 case MEDCALC::SCALAR_BAR_CURRENT_TIMESTEP:
474 oss << _dispVar << ".RescaleTransferFunctionToDataRange(False);";
477 STDLOG("MEDPresentation::getRescaleCommand(): invalid range!");
478 throw KERNEL::createSalomeException("MEDPresentation::getRescaleCommand(): invalid range!");
480 pushAndExecPyLine(oss.str()); oss.str("");
482 oss << _rangeVar << " = [" << _dispVar << ".LookupTable.RGBPoints[0], " << _dispVar << ".LookupTable.RGBPoints[-4]];";
483 pushAndExecPyLine(oss.str());
485 // Adapt scalar bar title
492 MEDPresentation::GeneratePythonId()
494 static int INIT_ID = 0;
499 MEDPresentation::activateView()
501 MEDPyLockWrapper lock;
503 execPyLine("__alive = " + getRenderViewVar() + " in pvs.GetRenderViews()");
504 PyObject * obj = getPythonObjectFromMain("__alive");
506 if (obj && PyBool_Check(obj))
507 alive = (obj == Py_True);
510 // The view is still there,just activate it:
511 pushAndExecPyLine("pvs.SetActiveView(" + getRenderViewVar() + ");");
514 // The view disappeared, recreate it in a new layout. The transfer of the objects is to be done by the caller.
515 std::ostringstream oss;
516 oss << "pvs.servermanager.misc.ViewLayout(registrationGroup='layouts');";
517 pushAndExecPyLine(oss.str()); oss.str("");
518 oss << getRenderViewVar() << " = pvs.CreateView('RenderView');";
519 pushAndExecPyLine(oss.str()); oss.str("");
525 * Called when the view has been recreated (because the user closed it).
526 * All the objects and set up are re-shown in the new view (which is stored in the same Python variable).
529 MEDPresentation::recreateViewSetup()
535 rescaleTransferFunction();
536 resetCameraAndRender();
540 MEDPresentation::paravisDump() const
544 for (vector<string>::const_iterator it=_pythonCmds.begin(); it != _pythonCmds.end(); ++it)
553 * Query all available component names for the field associated with this presentation.
554 * Fills in all the corresponding string properties:
558 * and the number of components.
561 MEDPresentation::fillAvailableFieldComponents()
563 MEDPyLockWrapper lock; // GIL!
566 if(_pvFieldType == "CELLS") {
569 else if (_pvFieldType == "POINTS") {
573 std::string msg("Unsupported spatial discretisation: " + _pvFieldType);
575 throw KERNEL::createSalomeException(msg.c_str());
578 std::ostringstream oss;
579 oss << "__nbCompo = " << _srcObjVar << "." << typ << ".GetArray('" << _fieldName << "').GetNumberOfComponents();";
580 execPyLine(oss.str());
581 PyObject* p_obj = getPythonObjectFromMain("__nbCompo");
583 if (p_obj && PyInt_Check(p_obj))
584 nbCompo = PyInt_AS_LONG(p_obj);
587 STDLOG("Unexpected Python error");
588 throw KERNEL::createSalomeException("Unexpected Python error");
590 setIntProperty(MEDPresentation::PROP_NB_COMPONENTS, nbCompo);
591 for (long i = 0; i<nbCompo; i++)
593 std::ostringstream oss2;
594 oss2 << "__compo = " << _srcObjVar << "." << typ << ".GetArray('" << _fieldName << "').GetComponentName(" << i << ");";
595 execPyLine(oss2.str());
596 PyObject* p_obj = getPythonObjectFromMain("__compo");
598 if (p_obj && PyString_Check(p_obj))
599 compo = std::string(PyString_AsString(p_obj)); // pointing to internal Python memory, so make a copy!!
602 STDLOG("Unexpected Python error");
603 throw KERNEL::createSalomeException("Unexpected Python error");
605 std::ostringstream oss_p;
606 oss_p << MEDPresentation::PROP_COMPONENT << i;
607 setStringProperty(oss_p.str(), compo);
612 * In case where a CELLS field needs to be converted to POINT field.
613 * This updates the source object to become the result of the CellDatatoPointData filter.
616 MEDPresentation::applyCellToPointIfNeeded()
618 if (_pvFieldType == "CELLS")
620 std::ostringstream oss, oss2;
621 // Apply Cell data to point data:
622 oss2 << "__srcObj" << GeneratePythonId();
623 oss << oss2.str() << " = pvs.CellDatatoPointData(Input=" << _srcObjVar << ");";
624 pushAndExecPyLine(oss.str()); oss.str("");
625 // Now the source becomes the result of the CellDatatoPointData:
626 _srcObjVar = oss2.str();
631 // * Convert a vector field into a 3D vector field:
632 // * - if the vector field is already 3D, nothing to do
633 // * - if it is 2D, then add a null component
634 // * - otherwise (tensor field, scalar field) throw
637 //MEDPresentation::convertTo3DVectorField()
639 // std::ostringstream oss, oss1, oss2, oss3;
641 // int nbCompo = getIntProperty(MEDPresentation::PROP_NB_COMPONENTS);
642 // if (nbCompo < 2 || nbCompo > 3)
644 // oss << "The field '" << _fieldName << "' must have 2 or 3 components for this presentation!";
645 // STDLOG(oss.str());
646 // throw KERNEL::createSalomeException(oss.str().c_str());
651 // // Apply calculator:
652 // oss2 << "__srcObj" << GeneratePythonId();
653 // oss << oss2.str() << " = pvs.Calculator(Input=" << _srcObjVar << ");";
654 // pushAndExecPyLine(oss.str()); oss.str("");
655 // // Now the source becomes the result of the CellDatatoPointData:
656 // _srcObjVar = oss2.str();
658 // if(_pvFieldType == "CELLS")
659 // typ = "Cell Data";
660 // else if(_pvFieldType == "POINTS")
661 // typ = "Point Data";
664 // oss3 << "Field '" << _fieldName << "' has invalid field type";
665 // STDLOG(oss3.str());
666 // throw KERNEL::createSalomeException(oss3.str().c_str());
668 // oss << _srcObjVar << ".AttributeMode = '" << typ << "';";
669 // pushAndExecPyLine(oss.str()); oss.str("");
670 // oss << _srcObjVar << ".ResultArrayName = '" << _fieldName << "_CALC';"; // will never be needed I think
671 // pushAndExecPyLine(oss.str()); oss.str("");
672 // oss << _srcObjVar << ".Function = '" << _fieldName << "_0*iHat + " << _fieldName << "_1*jHat + 0.0*zHat';";
673 // pushAndExecPyLine(oss.str()); oss.str("");