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 fieldHandlerId, const std::string& name,
40 const MEDCALC::ViewModeType viewMode,
41 const MEDCALC::ColorMapType colorMap,
42 const MEDCALC::ScalarBarRangeType sbRange)
43 : _fieldHandlerId(fieldHandlerId), _propertiesStr(),
44 //_pipeline(0), _display(0)
45 _selectedComponentIndex(-1),
49 _renderViewPyId(-1), // will be set by getRenderViewCommand()
52 MEDCALC::MEDDataManager_ptr dataManager(MEDFactoryClient::getDataManager());
53 MEDCALC::FieldHandler* fieldHandler = dataManager->getFieldHandler(fieldHandlerId);
54 MEDCALC::MeshHandler* meshHandler = dataManager->getMesh(fieldHandler->meshid);
55 MEDCALC::DatasourceHandler* dataSHandler = dataManager->getDatasourceHandlerFromID(meshHandler->sourceid);
57 _fileName = dataSHandler->uri;
58 _fieldName = fieldHandler->fieldname;
59 _mcFieldType = (MEDCoupling::TypeOfField) fieldHandler->type;
60 _pvFieldType = getPVFieldTypeString(_mcFieldType);
61 _meshName = meshHandler->name;
63 if (_fileName.substr(0, 7) != std::string("file://")) {
64 const char* msg = "MEDPresentation(): Data source is not a file! Can not proceed.";
66 throw MEDPresentationException(msg);
68 _fileName = _fileName.substr(7, _fileName.size());
70 setStringProperty(MEDPresentation::PROP_NAME, name);
72 setIntProperty(MEDPresentation::PROP_NB_COMPONENTS, 0);
73 setIntProperty(MEDPresentation::PROP_SELECTED_COMPONENT, 0);
75 setIntProperty(MEDPresentation::PROP_COLOR_MAP, static_cast<int>(colorMap));
76 setIntProperty(MEDPresentation::PROP_SCALAR_BAR_RANGE, static_cast<int>(sbRange));
79 int id = GeneratePythonId();
80 std::ostringstream oss_o, oss_d, oss_l, oss_s, oss_r;
81 oss_o << "__obj" << id;
82 oss_s << "__srcObj" << id;
83 oss_d << "__disp" << id;
84 oss_l << "__lut" << id;
85 oss_r << "__range" << id;
86 _objVar = oss_o.str();
87 _srcObjVar = oss_s.str();
88 _dispVar = oss_d.str();
89 _lutVar = oss_l.str();
90 _rangeVar = oss_r.str();
93 MEDPresentation::~MEDPresentation()
95 STDLOG("~MEDPresentation(): clear display");
97 MEDPyLockWrapper lock;
98 std::ostringstream oss_v, oss;
99 oss_v << "__view" << _renderViewPyId;
100 oss << "pvs.Hide(" << _objVar << ", view=" << oss_v.str() << ");";
101 oss << "pvs.Render();";
103 PyRun_SimpleString(oss.str().c_str());
108 MEDPresentation::generatePipeline()
110 // Might be more complicated in the future:
112 this->internalGeneratePipeline();
116 //MEDPresentation::pushPyObjects(PyObjectId obj, PyObjectId disp)
118 // _pipeline.push_back(obj);
119 // _display.push_back(disp);
123 MEDPresentation::pushAndExecPyLine(const std::string & lin)
126 _pythonCmds.push_back(lin);
130 MEDPresentation::execPyLine(const std::string & lin)
132 MEDPyLockWrapper lock;
133 // STDLOG("@@@@ MEDPresentation::execPyLine() about to exec >> " << lin);
134 if(PyRun_SimpleString(lin.c_str()))
136 std::ostringstream oss;
137 oss << "MEDPresentation::execPyLine(): following Python command failed!\n";
140 throw KERNEL::createSalomeException(oss.str().c_str());
145 MEDPresentation::setStringProperty(const std::string& propName, const std::string& propValue)
147 _propertiesStr[propName] = propValue;
151 MEDPresentation::getStringProperty(const std::string& propName) const
153 std::map<std::string, std::string>::const_iterator it = _propertiesStr.find(propName);
154 if (it != _propertiesStr.end()) {
158 STDLOG("MEDPresentation::getStringProperty(): no property named " + propName);
159 throw MEDPresentationException("MEDPresentation::getStringProperty(): no property named " + propName);
164 MEDPresentation::setIntProperty(const std::string& propName, const int propValue)
166 _propertiesInt[propName] = propValue;
170 MEDPresentation::getIntProperty(const std::string& propName) const
172 std::map<std::string, int>::const_iterator it = _propertiesInt.find(propName);
173 if (it != _propertiesInt.end()) {
177 STDLOG("MEDPresentation::getIntProperty(): no property named " + propName);
178 throw MEDPresentationException("MEDPresentation::getIntProperty(): no property named " + propName);
183 MEDPresentation::dumpIntProperties() const
185 std::map<std::string, int>::const_iterator it = _propertiesInt.begin();
186 STDLOG("@@@ Dumping INT properties");
187 for(; it != _propertiesInt.end(); ++it)
189 std::ostringstream oss;
190 oss << (*it).first << " -> " << (*it).second;
196 MEDPresentation::dumpStringProperties() const
198 std::map<std::string, std::string>::const_iterator it = _propertiesStr.begin();
199 STDLOG("@@@ Dumping STR properties");
200 for(; it != _propertiesStr.end(); ++it)
202 std::ostringstream oss;
203 oss << (*it).first << " -> " << (*it).second;
209 MEDPresentation::internalGeneratePipeline()
211 MEDPyLockWrapper lock;
212 pushAndExecPyLine( "import pvsimple as pvs;");
213 pushAndExecPyLine( "import medcalc");
218 * @return a borrowed reference. Do not DECRREF!
221 MEDPresentation::getPythonObjectFromMain(const char* python_var) const
225 // All the calls below returns *borrowed* references
226 PyObject* main_module = PyImport_AddModule((char*)"__main__");
227 _globalDict = PyModule_GetDict(main_module);
229 return PyDict_GetItemString(_globalDict, python_var);
233 MEDPresentation::getPVFieldTypeString(MEDCoupling::TypeOfField fieldType) const
237 case MEDCoupling::ON_CELLS:
239 case MEDCoupling::ON_NODES:
241 case MEDCoupling::ON_GAUSS_PT:
242 return "POINTS"; // because internally after application of the ELGA filter, the field will appear as a POINT field
244 STDLOG("MEDPresentation::getPVFieldTypeString() -- Not implemented ! ELNO field?");
250 MEDPresentation::getRenderViewVar() const
252 std::ostringstream oss;
253 oss << "__view" << _renderViewPyId;
258 * Creates the MEDReader source in the pipeline, and potentially apply GAUSS/ELNO filters.
261 MEDPresentation::createSource()
264 switch(_mcFieldType) {
265 case MEDCoupling::ON_CELLS: typ = "P0"; break;
266 case MEDCoupling::ON_NODES: typ = "P1"; break;
267 case MEDCoupling::ON_GAUSS_PT: typ = "GAUSS"; break;
269 const char * msg ="MEDPresentation::createSource(): field type not impl. yet!";
271 throw KERNEL::createSalomeException(msg);
274 std::ostringstream oss;
275 oss << _srcObjVar << " = pvs.MEDReader(FileName='" << _fileName << "');";
276 pushAndExecPyLine(oss.str()); oss.str("");
277 oss << "medcalc.SelectSourceField(" << _srcObjVar << ", '" << _meshName << "', '"
278 << _fieldName << "', '" << typ << "');";
279 pushAndExecPyLine(oss.str()); oss.str("");
280 oss << _srcObjVar << ".GenerateVectors = 1;";
281 pushAndExecPyLine(oss.str()); oss.str("");
283 // Deal with GAUSS fields:
284 if(_mcFieldType == MEDCoupling::ON_GAUSS_PT)
286 std::ostringstream oss, oss2;
287 oss2 << "__srcObj" << GeneratePythonId();
288 oss << oss2.str() << " = pvs.GaussPoints(Input=" << _srcObjVar << ");";
289 pushAndExecPyLine(oss.str()); oss.str("");
290 // Now the source becomes the result of the CellDatatoPointData:
291 _srcObjVar = oss2.str();
292 oss << _srcObjVar << ".SelectSourceArray = ['CELLS', 'ELGA@0'];";
293 pushAndExecPyLine(oss.str()); oss.str("");
295 if(_mcFieldType == MEDCoupling::ON_GAUSS_NE)
297 const char * msg ="MEDPresentation::createSource(): ELNO field never tested!";
299 throw KERNEL::createSalomeException(msg);
301 std::ostringstream oss, oss2;
302 oss2 << "__srcObj" << GeneratePythonId();
303 oss << oss2.str() << " = pvs.ELNOMesh(Input=" << _srcObjVar << ");";
304 pushAndExecPyLine(oss.str()); oss.str("");
305 // Now the source becomes the result of the CellDatatoPointData:
306 _srcObjVar = oss2.str();
307 // oss << _srcObjVar << ".SelectSourceArray = ['CELLS', 'ELNO@0'];";
308 // pushAndExecPyLine(oss.str()); oss.str("");
313 MEDPresentation::setOrCreateRenderView()
315 std::ostringstream oss2;
317 std::string view(getRenderViewVar());
318 oss2 << "pvs._DisableFirstRenderCameraReset();";
319 pushAndExecPyLine(oss2.str()); oss2.str("");
320 if (_viewMode == MEDCALC::VIEW_MODE_OVERLAP) {
321 // this might potentially re-assign to an existing view variable, but this is OK, we
322 // normally reassign exaclty the same RenderView object.
323 oss2 << view << " = pvs.GetActiveViewOrCreate('RenderView');";
324 pushAndExecPyLine(oss2.str()); oss2.str("");
325 } else if (_viewMode == MEDCALC::VIEW_MODE_REPLACE) {
327 oss2 << view << " = pvs.GetActiveViewOrCreate('RenderView');";
328 pushAndExecPyLine(oss2.str()); oss2.str("");
329 oss2 << "pvs.active_objects.source and pvs.Hide(view=" << view << ");";
330 pushAndExecPyLine(oss2.str()); oss2.str("");
331 oss2 << "pvs.Render();";
332 pushAndExecPyLine(oss2.str()); oss2.str("");
333 } else if (_viewMode == MEDCALC::VIEW_MODE_NEW_LAYOUT) {
334 oss2 << "__layout1 = pvs.servermanager.misc.ViewLayout(registrationGroup='layouts');";
335 pushAndExecPyLine(oss2.str()); oss2.str("");
336 oss2 << view << " = pvs.CreateView('RenderView');";
337 pushAndExecPyLine(oss2.str()); oss2.str("");
338 } else if (_viewMode == MEDCALC::VIEW_MODE_SPLIT_VIEW) {
339 oss2 << view << " = pvs.CreateView('RenderView');";
340 pushAndExecPyLine(oss2.str()); oss2.str("");
345 MEDPresentation::resetCameraAndRender()
347 pushAndExecPyLine(getRenderViewVar() + ".ResetCamera();");
348 pushAndExecPyLine("pvs.Render();");
352 MEDPresentation::selectFieldComponent()
354 std::ostringstream oss, oss_l;
357 if (_selectedComponentIndex != -1)
359 oss << _lutVar << ".VectorMode = 'Component';";
360 pushAndExecPyLine(oss.str()); oss.str("");
361 oss << _lutVar << ".VectorComponent = " << _selectedComponentIndex << ";";
362 pushAndExecPyLine(oss.str()); oss.str("");
364 else // Euclidean norm
366 oss << _lutVar << ".VectorMode = 'Magnitude';";
367 pushAndExecPyLine(oss.str()); oss.str("");
372 * Needs the LUT, so to be called after selectColorMap for the first time.
375 MEDPresentation::scalarBarTitle()
377 // get selected component name:
378 std::string compoName;
379 if (_selectedComponentIndex != -1)
381 std::ostringstream oss1;
382 oss1 << MEDPresentation::PROP_COMPONENT << _selectedComponentIndex;
383 compoName = getStringProperty(oss1.str());
387 if (getIntProperty(MEDPresentation::PROP_NB_COMPONENTS) == 1)
390 compoName = "Magnitude";
392 std::ostringstream oss;
393 oss << "pvs.GetScalarBar(" << _lutVar << ").ComponentTitle = '" << compoName << "';";
394 pushAndExecPyLine(oss.str()); oss.str("");
398 MEDPresentation::selectColorMap()
400 std::ostringstream oss, oss2;
402 oss2 << _lutVar << " = pvs.GetColorTransferFunction('" << _fieldName << "');";
403 pushAndExecPyLine(oss2.str());
406 case MEDCALC::COLOR_MAP_BLUE_TO_RED_RAINBOW:
407 oss << _lutVar << ".ApplyPreset('Blue to Red Rainbow',True);";
409 case MEDCALC::COLOR_MAP_COOL_TO_WARM:
410 oss << _lutVar << ".ApplyPreset('Cool to Warm',True);";
413 STDLOG("MEDPresentation::getColorMapCommand(): invalid colormap!");
414 throw KERNEL::createSalomeException("MEDPresentation::getColorMapCommand(): invalid colormap!");
416 pushAndExecPyLine(oss.str());
418 selectFieldComponent(); // somehow PV keeps the LUT parameters of the previous presentation, so better reset this.
422 MEDPresentation::showObject()
424 std::ostringstream oss;
425 oss << _dispVar << " = pvs.Show(" << _objVar << ", " << getRenderViewVar() << ");";
426 pushAndExecPyLine(oss.str());
430 MEDPresentation::showScalarBar()
432 std::ostringstream oss;
433 oss << _dispVar << ".SetScalarBarVisibility(" << getRenderViewVar() << ", True);";
434 pushAndExecPyLine(oss.str());
438 MEDPresentation::colorBy(const std::string & fieldType)
440 std::ostringstream oss;
441 oss << "pvs.ColorBy(" << _dispVar << ", ('" << fieldType << "', '" << _fieldName << "'));";
442 pushAndExecPyLine(oss.str());
446 MEDPresentation::rescaleTransferFunction()
448 std::ostringstream oss;
451 case MEDCALC::SCALAR_BAR_ALL_TIMESTEPS:
452 oss << _dispVar << ".RescaleTransferFunctionToDataRangeOverTime();";
454 case MEDCALC::SCALAR_BAR_CURRENT_TIMESTEP:
455 oss << _dispVar << ".RescaleTransferFunctionToDataRange(False);";
458 STDLOG("MEDPresentation::getRescaleCommand(): invalid range!");
459 throw KERNEL::createSalomeException("MEDPresentation::getRescaleCommand(): invalid range!");
461 pushAndExecPyLine(oss.str()); oss.str("");
463 oss << _rangeVar << " = [" << _dispVar << ".LookupTable.RGBPoints[0], " << _dispVar << ".LookupTable.RGBPoints[-4]];";
464 pushAndExecPyLine(oss.str());
466 // Adapt scalar bar title
473 MEDPresentation::GeneratePythonId()
475 static int INIT_ID = 0;
480 MEDPresentation::activateView()
482 MEDPyLockWrapper lock;
483 pushAndExecPyLine("pvs.SetActiveView(" + getRenderViewVar() + ");");
488 MEDPresentation::paravisDump() const
492 for (vector<string>::const_iterator it=_pythonCmds.begin(); it != _pythonCmds.end(); ++it)
501 * Query all available component names for the field associated with this presentation.
502 * Fills in all the corresponding string properties:
506 * and the number of components.
509 MEDPresentation::fillAvailableFieldComponents()
511 MEDPyLockWrapper lock; // GIL!
514 if(_pvFieldType == "CELLS") {
517 else if (_pvFieldType == "POINTS") {
521 std::string msg("Unsupported spatial discretisation: " + _pvFieldType);
523 throw KERNEL::createSalomeException(msg.c_str());
526 std::ostringstream oss;
527 oss << "__nbCompo = " << _srcObjVar << "." << typ << ".GetArray('" << _fieldName << "').GetNumberOfComponents();";
528 execPyLine(oss.str());
529 PyObject* p_obj = getPythonObjectFromMain("__nbCompo");
531 if (p_obj && PyInt_Check(p_obj))
532 nbCompo = PyInt_AS_LONG(p_obj);
535 STDLOG("Unexpected Python error");
536 throw KERNEL::createSalomeException("Unexpected Python error");
538 setIntProperty(MEDPresentation::PROP_NB_COMPONENTS, nbCompo);
539 for (long i = 0; i<nbCompo; i++)
541 std::ostringstream oss2;
542 oss2 << "__compo = " << _srcObjVar << "." << typ << ".GetArray('" << _fieldName << "').GetComponentName(" << i << ");";
543 execPyLine(oss2.str());
544 PyObject* p_obj = getPythonObjectFromMain("__compo");
546 if (p_obj && PyString_Check(p_obj))
547 compo = std::string(PyString_AsString(p_obj)); // pointing to internal Python memory, so make a copy!!
550 STDLOG("Unexpected Python error");
551 throw KERNEL::createSalomeException("Unexpected Python error");
553 std::ostringstream oss_p;
554 oss_p << MEDPresentation::PROP_COMPONENT << i;
555 setStringProperty(oss_p.str(), compo);
560 * In case where a CELLS field needs to be converted to POINT field.
561 * This updates the source object to become the result of the CellDatatoPointData filter.
564 MEDPresentation::applyCellToPointIfNeeded()
566 if (_pvFieldType == "CELLS")
568 std::ostringstream oss, oss2;
569 // Apply Cell data to point data:
570 oss2 << "__srcObj" << GeneratePythonId();
571 oss << oss2.str() << " = pvs.CellDatatoPointData(Input=" << _srcObjVar << ");";
572 pushAndExecPyLine(oss.str()); oss.str("");
573 // Now the source becomes the result of the CellDatatoPointData:
574 _srcObjVar = oss2.str();
579 // * Convert a vector field into a 3D vector field:
580 // * - if the vector field is already 3D, nothing to do
581 // * - if it is 2D, then add a null component
582 // * - otherwise (tensor field, scalar field) throw
585 //MEDPresentation::convertTo3DVectorField()
587 // std::ostringstream oss, oss1, oss2, oss3;
589 // int nbCompo = getIntProperty(MEDPresentation::PROP_NB_COMPONENTS);
590 // if (nbCompo < 2 || nbCompo > 3)
592 // oss << "The field '" << _fieldName << "' must have 2 or 3 components for this presentation!";
593 // STDLOG(oss.str());
594 // throw KERNEL::createSalomeException(oss.str().c_str());
599 // // Apply calculator:
600 // oss2 << "__srcObj" << GeneratePythonId();
601 // oss << oss2.str() << " = pvs.Calculator(Input=" << _srcObjVar << ");";
602 // pushAndExecPyLine(oss.str()); oss.str("");
603 // // Now the source becomes the result of the CellDatatoPointData:
604 // _srcObjVar = oss2.str();
606 // if(_pvFieldType == "CELLS")
607 // typ = "Cell Data";
608 // else if(_pvFieldType == "POINTS")
609 // typ = "Point Data";
612 // oss3 << "Field '" << _fieldName << "' has invalid field type";
613 // STDLOG(oss3.str());
614 // throw KERNEL::createSalomeException(oss3.str().c_str());
616 // oss << _srcObjVar << ".AttributeMode = '" << typ << "';";
617 // pushAndExecPyLine(oss.str()); oss.str("");
618 // oss << _srcObjVar << ".ResultArrayName = '" << _fieldName << "_CALC';"; // will never be needed I think
619 // pushAndExecPyLine(oss.str()); oss.str("");
620 // oss << _srcObjVar << ".Function = '" << _fieldName << "_0*iHat + " << _fieldName << "_1*jHat + 0.0*zHat';";
621 // pushAndExecPyLine(oss.str()); oss.str("");