From: Cédric Aguerre Date: Tue, 1 Dec 2015 16:02:11 +0000 (+0100) Subject: fix conflict X-Git-Tag: V8_0_0a1~5^2~12 X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=7d5fb5a50f6d091af34805871047f2fe72bdf293;p=modules%2Fmed.git fix conflict --- 7d5fb5a50f6d091af34805871047f2fe72bdf293 diff --cc medtool/src/MEDCoupling/MEDCouplingField.cxx index 463a44bbb,000000000..cb69a6de7 mode 100644,000000..100644 --- a/medtool/src/MEDCoupling/MEDCouplingField.cxx +++ b/medtool/src/MEDCoupling/MEDCouplingField.cxx @@@ -1,635 -1,0 +1,635 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#include "MEDCouplingField.hxx" +#include "MEDCouplingMesh.hxx" +#include "MEDCouplingFieldDiscretization.hxx" + +#include + +using namespace ParaMEDMEM; + +bool MEDCouplingField::isEqualIfNotWhy(const MEDCouplingField *other, double meshPrec, double valsPrec, std::string& reason) const +{ + if(!other) + throw INTERP_KERNEL::Exception("MEDCouplingField::isEqualIfNotWhy : other instance is NULL !"); + std::ostringstream oss; oss.precision(15); + if(_name!=other->_name) + { + oss << "Field names differ : this name = \"" << _name << "\" and other name = \"" << other->_name << "\" !"; + reason=oss.str(); + return false; + } + if(_desc!=other->_desc) + { + oss << "Field descriptions differ : this description = \"" << _desc << "\" and other description = \"" << other->_desc << "\" !"; + reason=oss.str(); + return false; + } + if(_nature!=other->_nature) + { + oss << "Field nature differ : this nature = \"" << MEDCouplingNatureOfField::GetRepr(_nature) << "\" and other nature = \"" << MEDCouplingNatureOfField::GetRepr(other->_nature) << "\" !"; + reason=oss.str(); + return false; + } + if(!_type->isEqualIfNotWhy(other->_type,valsPrec,reason)) + { + reason.insert(0,"Spatial discretizations differ :"); + return false; + } + if(_mesh==0 && other->_mesh==0) + return true; + if(_mesh==0 || other->_mesh==0) + { + reason="Only one field between the two this and other has its underlying mesh defined !"; + return false; + } + if(_mesh==other->_mesh) + return true; + bool ret=_mesh->isEqualIfNotWhy(other->_mesh,meshPrec,reason); + if(!ret) + reason.insert(0,"Underlying meshes of fields differ for the following reason : "); + return ret; +} + +/*! + * Checks if \a this and another MEDCouplingField are fully equal. + * \param [in] other - the field to compare with \a this one. + * \param [in] meshPrec - precision used to compare node coordinates of the underlying mesh. + * \param [in] valsPrec - precision used to compare field values. + * \return bool - \c true if the two fields are equal, \c false else. + * \throw If \a other is NULL. + */ +bool MEDCouplingField::isEqual(const MEDCouplingField *other, double meshPrec, double valsPrec) const +{ + std::string tmp; + return isEqualIfNotWhy(other,meshPrec,valsPrec,tmp); +} + +/*! + * Checks if \a this and another MEDCouplingField are equal. The textual + * information like names etc. is not considered. + * \param [in] other - the field to compare with \a this one. + * \param [in] meshPrec - precision used to compare node coordinates of the underlying mesh. + * \param [in] valsPrec - precision used to compare field values. + * \return bool - \c true if the two fields are equal, \c false else. + * \throw If \a other is NULL. + * \throw If the spatial discretization of \a this field is NULL. + */ +bool MEDCouplingField::isEqualWithoutConsideringStr(const MEDCouplingField *other, double meshPrec, double valsPrec) const +{ + if(!other) + throw INTERP_KERNEL::Exception("MEDCouplingField::isEqualWithoutConsideringStr : input field is NULL !"); + if(!_type) + throw INTERP_KERNEL::Exception("MEDCouplingField::isEqualWithoutConsideringStr : spatial discretization of this is NULL !"); + if(!_type->isEqualWithoutConsideringStr(other->_type,valsPrec)) + return false; + if(_nature!=other->_nature) + return false; + if(_mesh==0 && other->_mesh==0) + return true; + if(_mesh==0 || other->_mesh==0) + return false; + if(_mesh==other->_mesh) + return true; + return _mesh->isEqualWithoutConsideringStr(other->_mesh,meshPrec); +} + +/*! + * This method states if 'this' and 'other' are compatibles each other before performing any treatment. + * This method is good for methods like : mergeFields. + * This method is not very demanding compared to areStrictlyCompatible that is better for operation on fields. + */ +bool MEDCouplingField::areCompatibleForMerge(const MEDCouplingField *other) const +{ + if(!other) + throw INTERP_KERNEL::Exception("MEDCouplingField::areCompatibleForMerge : input field is NULL !"); + if(!_type->isEqual(other->_type,1.)) + return false; + if(_nature!=other->_nature) + return false; + if(_mesh==other->_mesh) + return true; + return _mesh->areCompatibleForMerge(other->_mesh); +} + +/*! + * This method is more strict than MEDCouplingField::areCompatibleForMerge method. + * This method is used for operation on fields to operate a first check before attempting operation. + */ +bool MEDCouplingField::areStrictlyCompatible(const MEDCouplingField *other) const +{ + if(!other) + throw INTERP_KERNEL::Exception("MEDCouplingField::areStrictlyCompatible : input field is NULL !"); + if(!_type->isEqual(other->_type,1.e-12)) + return false; + if(_nature!=other->_nature) + return false; + return _mesh==other->_mesh; +} + +/*! + * This method is less strict than MEDCouplingField::areStrictlyCompatible method. + * The difference is that the nature is not checked. + * This method is used for multiplication and division on fields to operate a first check before attempting operation. + */ +bool MEDCouplingField::areStrictlyCompatibleForMulDiv(const MEDCouplingField *other) const +{ + if(!other) + throw INTERP_KERNEL::Exception("MEDCouplingField::areStrictlyCompatible : input field is NULL !"); + if(!_type->isEqual(other->_type,1.e-12)) + return false; + return _mesh==other->_mesh; +} + + +void MEDCouplingField::updateTime() const +{ + if(_mesh) + updateTimeWith(*_mesh); + if(_type) + updateTimeWith(*_type); +} + +std::size_t MEDCouplingField::getHeapMemorySizeWithoutChildren() const +{ + std::size_t ret=0; + ret+=_name.capacity(); + ret+=_desc.capacity(); + return ret; +} + +std::vector MEDCouplingField::getDirectChildrenWithNull() const +{ + std::vector ret; + ret.push_back(_mesh); + ret.push_back((const MEDCouplingFieldDiscretization *)_type); + return ret; +} + +/*! + * Returns a type of \ref MEDCouplingSpatialDisc "spatial discretization" of \a this + * field in terms of enum ParaMEDMEM::TypeOfField. + * \return ParaMEDMEM::TypeOfField - the type of \a this field. + * \throw If the geometric type is empty. + */ +TypeOfField MEDCouplingField::getTypeOfField() const +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("MEDCouplingField::getTypeOfField : spatial discretization is null !"); + return _type->getEnum(); +} + +/*! + * Returns the nature of \a this field. This information is very important during + * interpolation process using ParaMEDMEM::MEDCouplingRemapper or ParaMEDMEM::InterpKernelDEC. + * In other context than the two mentioned above, this attribute is unimportant. This + * attribute is not stored in the MED file. + * For more information of the semantics and the influence of this attribute to the + * result of interpolation, see + * - \ref NatureOfField + * - \ref TableNatureOfField "How interpolation coefficients depend on Field Nature" + */ +NatureOfField MEDCouplingField::getNature() const +{ + return _nature; +} + +/*! + * Sets the nature of \a this field. This information is very important during + * interpolation process using ParaMEDMEM::MEDCouplingRemapper or ParaMEDMEM::InterpKernelDEC. + * In other context than the two mentioned above, this attribute is unimportant. This + * attribute is not stored in the MED file. + * For more information of the semantics and the influence of this attribute to the + * result of interpolation, see + * - \ref NatureOfField + * - \ref TableNatureOfField "How interpolation coefficients depend on Field Nature" + * + * \param [in] nat - the nature of \a this field. + * \throw If \a nat has an invalid value. + */ +void MEDCouplingField::setNature(NatureOfField nat) +{ + MEDCouplingNatureOfField::GetRepr(nat);//generate a throw if nat not recognized + _nature=nat; +} + +/*! + * Returns coordinates of field location points that depend on + * \ref MEDCouplingSpatialDisc "spatial discretization" of \a this field. + * - For a field on nodes, returns coordinates of nodes. + * - For a field on cells, returns barycenters of cells. + * - For a field on gauss points, returns coordinates of gauss points. + * + * \return DataArrayDouble * - a new instance of DataArrayDouble. The caller is to + * delete this array using decrRef() as it is no more needed. + * \throw If the spatial discretization of \a this field is NULL. + * \throw If the mesh is not set. + */ +DataArrayDouble *MEDCouplingField::getLocalizationOfDiscr() const +{ + if(!_mesh) + throw INTERP_KERNEL::Exception("MEDCouplingField::getLocalizationOfDiscr : No mesh set !"); + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("MEDCouplingField::getLocalizationOfDiscr : No spatial discretization set !"); + return _type->getLocalizationOfDiscValues(_mesh); +} + +/*! + * Returns a new MEDCouplingFieldDouble containing volumes of cells of a dual mesh whose + * cells are constructed around field location points (getLocalizationOfDiscr()) of \a this + * field. (In case of a field on cells, the dual mesh coincides with the underlying mesh).
+ * For 1D cells, the returned field contains lengths.
+ * For 2D cells, the returned field contains areas.
+ * For 3D cells, the returned field contains volumes. + * \param [in] isAbs - if \c true, the computed cell volume does not reflect cell + * orientation, i.e. the volume is always positive. + * \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble. + * The caller is to delete this array using decrRef() as + * it is no more needed. + * \throw If the mesh is not set. + * \throw If the spatial discretization of \a this field is NULL. + * \throw If the spatial discretization of \a this field is not well defined. + */ + +MEDCouplingFieldDouble *MEDCouplingField::buildMeasureField(bool isAbs) const +{ + if(!_mesh) + throw INTERP_KERNEL::Exception("MEDCouplingField::buildMeasureField : no mesh defined !"); + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("MEDCouplingField::buildMeasureField : No spatial discretization set !"); + return _type->getMeasureField(_mesh,isAbs); +} + +/*! + * Sets the underlying mesh of \a this field. + * For examples of field construction, see \ref MEDCouplingFirstSteps3. + * \param [in] mesh - the new underlying mesh. + */ +void MEDCouplingField::setMesh(const MEDCouplingMesh *mesh) +{ + if(mesh!=_mesh) + { + if(_mesh) + _mesh->decrRef(); + _mesh=mesh; + declareAsNew(); + if(_mesh) + { + _mesh->incrRef(); + updateTimeWith(*_mesh); + } + } +} + +/*! + * Sets localization of Gauss points for a given geometric type of cell. + * \param [in] type - the geometric type of cell for which the Gauss localization is set. + * \param [in] refCoo - coordinates of points of the reference cell. Size of this vector + * must be \c nbOfNodesPerCell * \c dimOfType. + * \param [in] gsCoo - coordinates of Gauss points on the reference cell. Size of this vector + * must be _wg_.size() * \c dimOfType. + * \param [in] wg - the weights of Gauss points. + * \throw If \a this field is not on Gauss points. + * \throw If the spatial discretization of \a this field is NULL. + * \throw If the mesh is not set. + * \throw If size of any vector do not match the \a type. + */ +void MEDCouplingField::setGaussLocalizationOnType(INTERP_KERNEL::NormalizedCellType type, const std::vector& refCoo, + const std::vector& gsCoo, const std::vector& wg) +{ + if(!_mesh) + throw INTERP_KERNEL::Exception("Mesh has to be set before calling setGaussLocalizationOnType method !"); + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call setGaussLocalizationOnType method !"); + _type->setGaussLocalizationOnType(_mesh,type,refCoo,gsCoo,wg); +} + +/*! + * Sets localization of Gauss points for given cells specified by their ids. + * \param [in] begin - an array of cell ids of interest. + * \param [in] end - the end of \a begin, i.e. a pointer to its (last+1)-th element. + * \param [in] refCoo - coordinates of points of the reference cell. Size of this vector + * must be \c nbOfNodesPerCell * \c dimOfType. + * \param [in] gsCoo - coordinates of Gauss points on the reference cell. Size of this vector + * must be _wg_.size() * \c dimOfType. + * \param [in] wg - the weights of Gauss points. + * \throw If \a this field is not on Gauss points. + * \throw If the spatial discretization of \a this field is NULL. + * \throw If the mesh is not set. + * \throw If size of any vector do not match the type of cell # \a begin[0]. + * \throw If type of any cell in \a begin differs from that of cell # \a begin[0]. + * \throw If the range [_begin_,_end_) is empty. + */ +void MEDCouplingField::setGaussLocalizationOnCells(const int *begin, const int *end, const std::vector& refCoo, + const std::vector& gsCoo, const std::vector& wg) +{ + if(!_mesh) + throw INTERP_KERNEL::Exception("Mesh has to be set before calling setGaussLocalizationOnCells method !"); + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call setGaussLocalizationOnCells method !"); + _type->setGaussLocalizationOnCells(_mesh,begin,end,refCoo,gsCoo,wg); +} + +/*! + * Clears data on Gauss points localization. + * \throw If \a this field is not on Gauss points. + * \throw If the spatial discretization of \a this field is NULL. + */ +void MEDCouplingField::clearGaussLocalizations() +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call clearGaussLocalizations method !"); + _type->clearGaussLocalizations(); +} + +/*! + * Returns a reference to the Gauss localization object by its id. + * \warning This method is not const, so the returned object can be modified without any + * problem. + * \param [in] locId - the id of the Gauss localization object of interest. + * It must be in range 0 <= locId < getNbOfGaussLocalization() . + * \return \ref ParaMEDMEM::MEDCouplingGaussLocalization "MEDCouplingGaussLocalization" & - the + * Gauss localization object. + * \throw If \a this field is not on Gauss points. + * \throw If \a locId is not within the valid range. + * \throw If the spatial discretization of \a this field is NULL. + */ +MEDCouplingGaussLocalization& MEDCouplingField::getGaussLocalization(int locId) +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call getGaussLocalization method !"); + return _type->getGaussLocalization(locId); +} + +/*! + * Returns an id of the Gauss localization object corresponding to a given cell type. + * \param [in] type - the cell type of interest. + * \return int - the id of the Gauss localization object. + * \throw If \a this field is not on Gauss points. + * \throw If the spatial discretization of \a this field is NULL. + * \throw If no Gauss localization object found for the given cell \a type. + * \throw If more than one Gauss localization object found for the given cell \a type. + */ +int MEDCouplingField::getGaussLocalizationIdOfOneType(INTERP_KERNEL::NormalizedCellType type) const +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call getGaussLocalizationIdOfOneType method !"); + return _type->getGaussLocalizationIdOfOneType(type); +} + +/*! + * Returns ids of Gauss localization objects corresponding to a given cell type. + * \param [in] type - the cell type of interest. + * \return std::set - ids of the Gauss localization object. + * \throw If \a this field is not on Gauss points. + * \throw If the spatial discretization of \a this field is NULL + */ +std::set MEDCouplingField::getGaussLocalizationIdsOfOneType(INTERP_KERNEL::NormalizedCellType type) const +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call getGaussLocalizationIdsOfOneType method !"); + return _type->getGaussLocalizationIdsOfOneType(type); +} + +/*! + * Returns number of Gauss localization objects available. Implicitly all ids in + * [0,getNbOfGaussLocalization()) are valid Gauss localization ids. + * \return int - the number of available Gauss localization objects. + * \throw If \a this field is not on Gauss points. + * \throw If the spatial discretization of \a this field is NULL. + */ +int MEDCouplingField::getNbOfGaussLocalization() const +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call getNbOfGaussLocalization method !"); + return _type->getNbOfGaussLocalization(); +} + +/*! + * Returns an id of the Gauss localization object corresponding to a type of a given cell. + * \param [in] cellId - an id of the cell of interest. + * \return int - the id of the Gauss localization object. + * \throw If \a this field is not on Gauss points. + * \throw If the spatial discretization of \a this field is NULL. + * \throw If no Gauss localization object found for the given cell. + */ +int MEDCouplingField::getGaussLocalizationIdOfOneCell(int cellId) const +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call getGaussLocalizationIdOfOneCell method !"); + return _type->getGaussLocalizationIdOfOneCell(cellId); +} + +/*! + * Returns ids of cells that share the same Gauss localization given by its id. + * \param [in] locId - the id of the Gauss localization object of interest. + * It must be in range 0 <= locId < getNbOfGaussLocalization() . + * \param [in,out] cellIds - a vector returning ids of found cells. It is cleared before + * filling in. It remains empty if no cells found. + * \throw If \a this field is not on Gauss points. + * \throw If \a locId is not within the valid range. + * \throw If the spatial discretization of \a this field is NULL. + */ +void MEDCouplingField::getCellIdsHavingGaussLocalization(int locId, std::vector& cellIds) const +{ + cellIds.clear(); + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call getCellIdsHavingGaussLocalization method !"); + _type->getCellIdsHavingGaussLocalization(locId,cellIds); +} + +/*! + * Returns a reference to the Gauss localization object by its id. + * \warning This method is const, so the returned object is not apt for modification. + * \param [in] locId - the id of the Gauss localization object of interest. + * It must be in range 0 <= locId < getNbOfGaussLocalization() . + * \return const \ref MEDCouplingGaussLocalization & - the Gauss localization object. + * \throw If \a this field is not on Gauss points. + * \throw If \a locId is not within the valid range. + * \throw If the spatial discretization of \a this field is NULL. + */ +const MEDCouplingGaussLocalization& MEDCouplingField::getGaussLocalization(int locId) const +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call getGaussLocalization method !"); + return _type->getGaussLocalization(locId); +} + +MEDCouplingField::~MEDCouplingField() +{ + if(_mesh) + _mesh->decrRef(); +} + +MEDCouplingField::MEDCouplingField(MEDCouplingFieldDiscretization *type, NatureOfField nature):_nature(nature),_mesh(0),_type(type) +{ +} + +MEDCouplingField::MEDCouplingField(TypeOfField type):_nature(NoNature),_mesh(0),_type(MEDCouplingFieldDiscretization::New(type)) +{ +} + +MEDCouplingField::MEDCouplingField(const MEDCouplingField& other, bool deepCopy):RefCountObject(other),_name(other._name),_desc(other._desc),_nature(other._nature), + _mesh(0),_type(0) +{ + if(other._mesh) + { + _mesh=other._mesh; + _mesh->incrRef(); + } + if(deepCopy) + _type=other._type->clone(); + else + _type=other._type; +} + +/*! + * Returns a new MEDCouplingMesh constituted by some cells of the underlying mesh of \a - * this filed, and returns ids of entities (nodes, cells, Gauss points) lying on the ++ * this field, and returns ids of entities (nodes, cells, Gauss points) lying on the + * specified cells. The cells to include to the result mesh are specified by an array of + * cell ids. The new mesh shares the coordinates array with the underlying mesh. + * \param [in] start - an array of cell ids to include to the result mesh. + * \param [in] end - specifies the end of the array \a start, so that + * the last value of \a start is \a end[ -1 ]. + * \param [out] di - a new instance of DataArrayInt holding the ids of entities (nodes, + * cells, Gauss points). The caller is to delete this array using decrRef() as it + * is no more needed. + * \return MEDCouplingMesh * - a new instance of MEDCouplingMesh. The caller is to + * delete this mesh using decrRef() as it is no more needed. + * \throw If the spatial discretization of \a this field is NULL. + * \throw If the mesh is not set. + * \sa buildSubMeshDataRange() + */ +MEDCouplingMesh *MEDCouplingField::buildSubMeshData(const int *start, const int *end, DataArrayInt *&di) const +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call buildSubMeshData method !"); + return _type->buildSubMeshData(_mesh,start,end,di); +} + +/*! + * This method returns a submesh of 'mesh' instance constituting cell ids defined by a range given by the 3 following inputs \a begin, \a end and \a step. + * + * \param [out] beginOut Valid only if \a di is NULL + * \param [out] endOut Valid only if \a di is NULL + * \param [out] stepOut Valid only if \a di is NULL + * \param [out] di is an array returned that specifies entity ids (nodes, cells, Gauss points... ) in array if no output range is foundable. + * + * \sa MEDCouplingField::buildSubMeshData + */ +MEDCouplingMesh *MEDCouplingField::buildSubMeshDataRange(int begin, int end, int step, int& beginOut, int& endOut, int& stepOut, DataArrayInt *&di) const +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call buildSubMeshDataRange method !"); + return _type->buildSubMeshDataRange(_mesh,begin,end,step,beginOut,endOut,stepOut,di); +} + +/*! + * This method returns tuples ids implied by the mesh selection of the cell ids contained in array defined as an interval [start;end). + * \return a newly allocated DataArrayInt instance containing tuples ids. + */ +DataArrayInt *MEDCouplingField::computeTupleIdsToSelectFromCellIds(const int *startCellIds, const int *endCellIds) const +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call computeTupleIdsToSelectFromCellIds method !"); + return _type->computeTupleIdsToSelectFromCellIds(_mesh,startCellIds,endCellIds); +} + +/*! + * Returns number of tuples expected regarding the spatial discretization of \a this + * field and number of entities in the underlying mesh. This method behaves exactly as MEDCouplingFieldDouble::getNumberOfTuples. + * \return int - the number of expected tuples. + * \throw If the spatial discretization of \a this field is NULL. + * \throw If the mesh is not set. + */ +int MEDCouplingField::getNumberOfTuplesExpected() const +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call getNumberOfTuplesExpected method !"); + if(_mesh) + return _type->getNumberOfTuples(_mesh); + else + throw INTERP_KERNEL::Exception("MEDCouplingField::getNumberOfTuplesExpected : Empty mesh !"); +} + +void MEDCouplingField::setDiscretization(MEDCouplingFieldDiscretization *newDisc) +{ + bool needUpdate=(const MEDCouplingFieldDiscretization *)_type!=newDisc; + _type=newDisc; + if(newDisc) + newDisc->incrRef(); + if(needUpdate) + declareAsNew(); +} + +/*! + * Returns number of mesh entities in the underlying mesh of \a this field regarding the + * spatial discretization. + * \return int - the number of mesh entities porting the field values. + * \throw If the spatial discretization of \a this field is NULL. + * \throw If the mesh is not set. + */ +int MEDCouplingField::getNumberOfMeshPlacesExpected() const +{ + if(!((const MEDCouplingFieldDiscretization *)_type)) + throw INTERP_KERNEL::Exception("Spatial discretization not set ! Impossible to call getNumberOfMeshPlacesExpected method !"); + if(_mesh) + return _type->getNumberOfMeshPlaces(_mesh); + else + throw INTERP_KERNEL::Exception("MEDCouplingField::getNumberOfMeshPlacesExpected : Empty mesh !"); +} + +/*! + * Copy tiny info (component names, name, description) but warning the underlying mesh is not renamed (for safety reason). + */ +void MEDCouplingField::copyTinyStringsFrom(const MEDCouplingField *other) +{ + if(other) + { + setName(other->_name); + setDescription(other->_desc); + } +} + +/*! + * This method computes the number of tuples a DataArrayDouble instance should have to build a correct MEDCouplingFieldDouble instance starting from a + * submesh of a virtual mesh on which a substraction per type had been applied regarding the spatial discretization in \a this. + * + * For spatial discretization \b not equal to ON_GAUSS_NE this method will make the hypothesis that any positive entity id in \a code \a idsPerType is valid. + * So in those cases attribute \a _mesh of \a this is ignored. + * + * For spatial discretization equal to ON_GAUSS_NE \a _mesh attribute will be taken into account. + * + * The input code is those implemented in MEDCouplingUMesh::splitProfilePerType. + * + * \param [in] code - a code with format described above. + * \param [in] idsPerType - a list of subparts + * \throw If \a this has no spatial discretization set. + * \throw If input code point to invalid zones in spatial discretization. + * \throw If spatial discretization in \a this requires a mesh and those mesh is invalid (null,...) + */ +int MEDCouplingField::getNumberOfTuplesExpectedRegardingCode(const std::vector& code, const std::vector& idsPerType) const +{ + const MEDCouplingFieldDiscretization *t(_type); + if(!t) + throw INTERP_KERNEL::Exception("MEDCouplingField::getNumberOfTuplesExpectedRegardingCode : no spatial discretization set !"); + return t->getNumberOfTuplesExpectedRegardingCode(code,idsPerType); +} diff --cc medtool/src/MEDCoupling/MEDCouplingMemArray.cxx index 751741283,000000000..998ac654e mode 100644,000000..100644 --- a/medtool/src/MEDCoupling/MEDCouplingMemArray.cxx +++ b/medtool/src/MEDCoupling/MEDCouplingMemArray.cxx @@@ -1,11860 -1,0 +1,11865 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#include "MEDCouplingMemArray.txx" +#include "MEDCouplingAutoRefCountObjectPtr.hxx" + +#include "BBTree.txx" +#include "GenMathFormulae.hxx" +#include "InterpKernelAutoPtr.hxx" +#include "InterpKernelExprParser.hxx" + +#include +#include +#include +#include +#include +#include + +typedef double (*MYFUNCPTR)(double); + +using namespace ParaMEDMEM; + +template +void DataArrayDouble::findCommonTuplesAlg(const double *bbox, int nbNodes, int limitNodeId, double prec, DataArrayInt *c, DataArrayInt *cI) const +{ + const double *coordsPtr=getConstPointer(); + BBTreePts myTree(bbox,0,0,nbNodes,prec); + std::vector isDone(nbNodes); + for(int i=0;i intersectingElems; + myTree.getElementsAroundPoint(coordsPtr+i*SPACEDIM,intersectingElems); + if(intersectingElems.size()>1) + { + std::vector commonNodes; + for(std::vector::const_iterator it=intersectingElems.begin();it!=intersectingElems.end();it++) + if(*it!=i) + if(*it>=limitNodeId) + { + commonNodes.push_back(*it); + isDone[*it]=true; + } + if(!commonNodes.empty()) + { + cI->pushBackSilent(cI->back()+(int)commonNodes.size()+1); + c->pushBackSilent(i); + c->insertAtTheEnd(commonNodes.begin(),commonNodes.end()); + } + } + } + } +} + +template +void DataArrayDouble::FindTupleIdsNearTuplesAlg(const BBTreePts& myTree, const double *pos, int nbOfTuples, double eps, + DataArrayInt *c, DataArrayInt *cI) +{ + for(int i=0;i intersectingElems; + myTree.getElementsAroundPoint(pos+i*SPACEDIM,intersectingElems); + std::vector commonNodes; + for(std::vector::const_iterator it=intersectingElems.begin();it!=intersectingElems.end();it++) + commonNodes.push_back(*it); + cI->pushBackSilent(cI->back()+(int)commonNodes.size()); + c->insertAtTheEnd(commonNodes.begin(),commonNodes.end()); + } +} + +template +void DataArrayDouble::FindClosestTupleIdAlg(const BBTreePts& myTree, double dist, const double *pos, int nbOfTuples, const double *thisPt, int thisNbOfTuples, int *res) +{ + double distOpt(dist); + const double *p(pos); + int *r(res); + for(int i=0;i::max()) + { + distOpt=std::max(ret,1e-4); + *r=elem; + break; + } + else + { distOpt=2*distOpt; continue; } + } + } +} + +std::size_t DataArray::getHeapMemorySizeWithoutChildren() const +{ + std::size_t sz1=_name.capacity(); + std::size_t sz2=_info_on_compo.capacity(); + std::size_t sz3=0; + for(std::vector::const_iterator it=_info_on_compo.begin();it!=_info_on_compo.end();it++) + sz3+=(*it).capacity(); + return sz1+sz2+sz3; +} + +std::vector DataArray::getDirectChildrenWithNull() const +{ + return std::vector(); +} + +/*! + * Sets the attribute \a _name of \a this array. + * See \ref MEDCouplingArrayBasicsName "DataArrays infos" for more information. + * \param [in] name - new array name + */ +void DataArray::setName(const std::string& name) +{ + _name=name; +} + +/*! + * Copies textual data from an \a other DataArray. The copied data are + * - the name attribute, + * - the information of components. + * + * For more information on these data see \ref MEDCouplingArrayBasicsName "DataArrays infos". + * + * \param [in] other - another instance of DataArray to copy the textual data from. + * \throw If number of components of \a this array differs from that of the \a other. + */ +void DataArray::copyStringInfoFrom(const DataArray& other) +{ + if(_info_on_compo.size()!=other._info_on_compo.size()) + throw INTERP_KERNEL::Exception("Size of arrays mismatches on copyStringInfoFrom !"); + _name=other._name; + _info_on_compo=other._info_on_compo; +} + +void DataArray::copyPartOfStringInfoFrom(const DataArray& other, const std::vector& compoIds) +{ + int nbOfCompoOth=other.getNumberOfComponents(); + std::size_t newNbOfCompo=compoIds.size(); + for(std::size_t i=0;i=nbOfCompoOth || compoIds[i]<0) + { + std::ostringstream oss; oss << "Specified component id is out of range (" << compoIds[i] << ") compared with nb of actual components (" << nbOfCompoOth << ")"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + for(std::size_t i=0;i& compoIds, const DataArray& other) +{ + int nbOfCompo=getNumberOfComponents(); + std::size_t partOfCompoToSet=compoIds.size(); + if((int)partOfCompoToSet!=other.getNumberOfComponents()) + throw INTERP_KERNEL::Exception("Given compoIds has not the same size as number of components of given array !"); + for(std::size_t i=0;i=nbOfCompo || compoIds[i]<0) + { + std::ostringstream oss; oss << "Specified component id is out of range (" << compoIds[i] << ") compared with nb of actual components (" << nbOfCompo << ")"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + for(std::size_t i=0;i::const_iterator iter=_info_on_compo.begin();iter!=_info_on_compo.end();iter++) + stream << "\"" << *iter << "\" "; + stream << "\n"; +} + +std::string DataArray::cppRepr(const std::string& varName) const +{ + std::ostringstream ret; + reprCppStream(varName,ret); + return ret.str(); +} + +/*! + * Sets information on all components. To know more on format of this information + * see \ref MEDCouplingArrayBasicsCompoName "DataArrays infos". + * \param [in] info - a vector of strings. + * \throw If size of \a info differs from the number of components of \a this. + */ +void DataArray::setInfoOnComponents(const std::vector& info) +{ + if(getNumberOfComponents()!=(int)info.size()) + { + std::ostringstream oss; oss << "DataArray::setInfoOnComponents : input is of size " << info.size() << " whereas number of components is equal to " << getNumberOfComponents() << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + _info_on_compo=info; +} + +/*! + * This method is only a dispatcher towards DataArrayDouble::setPartOfValues3, DataArrayInt::setPartOfValues3, DataArrayChar::setPartOfValues3 depending on the true + * type of \a this and \a aBase. + * + * \throw If \a aBase and \a this do not have the same type. + * + * \sa DataArrayDouble::setPartOfValues3, DataArrayInt::setPartOfValues3, DataArrayChar::setPartOfValues3. + */ +void DataArray::setPartOfValuesBase3(const DataArray *aBase, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare) +{ + if(!aBase) + throw INTERP_KERNEL::Exception("DataArray::setPartOfValuesBase3 : input aBase object is NULL !"); + DataArrayDouble *this1(dynamic_cast(this)); + DataArrayInt *this2(dynamic_cast(this)); + DataArrayChar *this3(dynamic_cast(this)); + const DataArrayDouble *a1(dynamic_cast(aBase)); + const DataArrayInt *a2(dynamic_cast(aBase)); + const DataArrayChar *a3(dynamic_cast(aBase)); + if(this1 && a1) + { + this1->setPartOfValues3(a1,bgTuples,endTuples,bgComp,endComp,stepComp,strictCompoCompare); + return ; + } + if(this2 && a2) + { + this2->setPartOfValues3(a2,bgTuples,endTuples,bgComp,endComp,stepComp,strictCompoCompare); + return ; + } + if(this3 && a3) + { + this3->setPartOfValues3(a3,bgTuples,endTuples,bgComp,endComp,stepComp,strictCompoCompare); + return ; + } + throw INTERP_KERNEL::Exception("DataArray::setPartOfValuesBase3 : input aBase object and this do not have the same type !"); +} + +std::vector DataArray::getVarsOnComponent() const +{ + int nbOfCompo=(int)_info_on_compo.size(); + std::vector ret(nbOfCompo); + for(int i=0;i DataArray::getUnitsOnComponent() const +{ + int nbOfCompo=(int)_info_on_compo.size(); + std::vector ret(nbOfCompo); + for(int i=0;i=0) + return _info_on_compo[i]; + else + { + std::ostringstream oss; oss << "DataArray::getInfoOnComponent : Specified component id is out of range (" << i << ") compared with nb of actual components (" << (int) _info_on_compo.size(); + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +/*! + * Returns the var part of the full information of the \a i-th component. + * For example, if \c getInfoOnComponent(0) returns "SIGXY [N/m^2]", then + * \c getVarOnComponent(0) returns "SIGXY". + * If a unit part of information is not detected by presence of + * two square brackets, then the full information is returned. + * To read more about the component information format, see + * \ref MEDCouplingArrayBasicsCompoName "DataArrays infos". + * \param [in] i - the index (zero based) of the component of interest. + * \return std::string - a string containing the var information, or the full info. + * \throw If \a i is not a valid component index. + */ +std::string DataArray::getVarOnComponent(int i) const +{ + if(i<(int)_info_on_compo.size() && i>=0) + { + return GetVarNameFromInfo(_info_on_compo[i]); + } + else + { + std::ostringstream oss; oss << "DataArray::getVarOnComponent : Specified component id is out of range (" << i << ") compared with nb of actual components (" << (int) _info_on_compo.size(); + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +/*! + * Returns the unit part of the full information of the \a i-th component. + * For example, if \c getInfoOnComponent(0) returns "SIGXY [ N/m^2]", then + * \c getUnitOnComponent(0) returns " N/m^2". + * If a unit part of information is not detected by presence of + * two square brackets, then an empty string is returned. + * To read more about the component information format, see + * \ref MEDCouplingArrayBasicsCompoName "DataArrays infos". + * \param [in] i - the index (zero based) of the component of interest. + * \return std::string - a string containing the unit information, if any, or "". + * \throw If \a i is not a valid component index. + */ +std::string DataArray::getUnitOnComponent(int i) const +{ + if(i<(int)_info_on_compo.size() && i>=0) + { + return GetUnitFromInfo(_info_on_compo[i]); + } + else + { + std::ostringstream oss; oss << "DataArray::getUnitOnComponent : Specified component id is out of range (" << i << ") compared with nb of actual components (" << (int) _info_on_compo.size(); + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +/*! + * Returns the var part of the full component information. + * For example, if \a info == "SIGXY [N/m^2]", then this method returns "SIGXY". + * If a unit part of information is not detected by presence of + * two square brackets, then the whole \a info is returned. + * To read more about the component information format, see + * \ref MEDCouplingArrayBasicsCompoName "DataArrays infos". + * \param [in] info - the full component information. + * \return std::string - a string containing only var information, or the \a info. + */ +std::string DataArray::GetVarNameFromInfo(const std::string& info) +{ + std::size_t p1=info.find_last_of('['); + std::size_t p2=info.find_last_of(']'); + if(p1==std::string::npos || p2==std::string::npos) + return info; + if(p1>p2) + return info; + if(p1==0) + return std::string(); + std::size_t p3=info.find_last_not_of(' ',p1-1); + return info.substr(0,p3+1); +} + +/*! + * Returns the unit part of the full component information. + * For example, if \a info == "SIGXY [ N/m^2]", then this method returns " N/m^2". + * If a unit part of information is not detected by presence of + * two square brackets, then an empty string is returned. + * To read more about the component information format, see + * \ref MEDCouplingArrayBasicsCompoName "DataArrays infos". + * \param [in] info - the full component information. + * \return std::string - a string containing only unit information, if any, or "". + */ +std::string DataArray::GetUnitFromInfo(const std::string& info) +{ + std::size_t p1=info.find_last_of('['); + std::size_t p2=info.find_last_of(']'); + if(p1==std::string::npos || p2==std::string::npos) + return std::string(); + if(p1>p2) + return std::string(); + return info.substr(p1+1,p2-p1-1); +} + +/*! + * This method put in info format the result of the merge of \a var and \a unit. + * The standard format for that is "var [unit]". + * Inversely you can retrieve the var part or the unit part of info string using resp. GetVarNameFromInfo and GetUnitFromInfo. + */ +std::string DataArray::BuildInfoFromVarAndUnit(const std::string& var, const std::string& unit) +{ + std::ostringstream oss; + oss << var << " [" << unit << "]"; + return oss.str(); +} + +/*! + * Returns a new DataArray by concatenating all given arrays, so that (1) the number + * of tuples in the result array is a sum of the number of tuples of given arrays and (2) + * the number of component in the result array is same as that of each of given arrays. + * Info on components is copied from the first of the given arrays. Number of components + * in the given arrays must be the same. + * \param [in] arrs - a sequence of arrays to include in the result array. All arrays must have the same type. + * \return DataArray * - the new instance of DataArray (that can be either DataArrayInt, DataArrayDouble, DataArrayChar). + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If all arrays within \a arrs are NULL. + * \throw If all not null arrays in \a arrs have not the same type. + * \throw If getNumberOfComponents() of arrays within \a arrs. + */ +DataArray *DataArray::Aggregate(const std::vector& arrs) +{ + std::vector arr2; + for(std::vector::const_iterator it=arrs.begin();it!=arrs.end();it++) + if(*it) + arr2.push_back(*it); + if(arr2.empty()) + throw INTERP_KERNEL::Exception("DataArray::Aggregate : only null instance in input vector !"); + std::vector arrd; + std::vector arri; + std::vector arrc; + for(std::vector::const_iterator it=arr2.begin();it!=arr2.end();it++) + { + const DataArrayDouble *a=dynamic_cast(*it); + if(a) + { arrd.push_back(a); continue; } + const DataArrayInt *b=dynamic_cast(*it); + if(b) + { arri.push_back(b); continue; } + const DataArrayChar *c=dynamic_cast(*it); + if(c) + { arrc.push_back(c); continue; } + throw INTERP_KERNEL::Exception("DataArray::Aggregate : presence of not null instance in inuput that is not in [DataArrayDouble, DataArrayInt, DataArrayChar] !"); + } + if(arr2.size()==arrd.size()) + return DataArrayDouble::Aggregate(arrd); + if(arr2.size()==arri.size()) + return DataArrayInt::Aggregate(arri); + if(arr2.size()==arrc.size()) + return DataArrayChar::Aggregate(arrc); + throw INTERP_KERNEL::Exception("DataArray::Aggregate : all input arrays must have the same type !"); +} + +/*! + * Sets information on a component specified by an index. + * To know more on format of this information + * see \ref MEDCouplingArrayBasicsCompoName "DataArrays infos". + * \warning Don't pass NULL as \a info! + * \param [in] i - the index (zero based) of the component of interest. + * \param [in] info - the string containing the information. + * \throw If \a i is not a valid component index. + */ +void DataArray::setInfoOnComponent(int i, const std::string& info) +{ + if(i<(int)_info_on_compo.size() && i>=0) + _info_on_compo[i]=info; + else + { + std::ostringstream oss; oss << "DataArray::setInfoOnComponent : Specified component id is out of range (" << i << ") compared with nb of actual components (" << (int) _info_on_compo.size(); + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +/*! + * Sets information on all components. This method can change number of components + * at certain conditions; if the conditions are not respected, an exception is thrown. + * The number of components can be changed in \a this only if \a this is not allocated. + * The condition of number of components must not be changed. + * + * To know more on format of the component information see + * \ref MEDCouplingArrayBasicsCompoName "DataArrays infos". + * \param [in] info - a vector of component infos. + * \throw If \a this->getNumberOfComponents() != \a info.size() && \a this->isAllocated() + */ +void DataArray::setInfoAndChangeNbOfCompo(const std::vector& info) +{ + if(getNumberOfComponents()!=(int)info.size()) + { + if(!isAllocated()) + _info_on_compo=info; + else + { + std::ostringstream oss; oss << "DataArray::setInfoAndChangeNbOfCompo : input is of size " << info.size() << " whereas number of components is equal to " << getNumberOfComponents() << " and this is already allocated !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + else + _info_on_compo=info; +} + +void DataArray::checkNbOfTuples(int nbOfTuples, const std::string& msg) const +{ + if(getNumberOfTuples()!=nbOfTuples) + { + std::ostringstream oss; oss << msg << " : mismatch number of tuples : expected " << nbOfTuples << " having " << getNumberOfTuples() << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +void DataArray::checkNbOfComps(int nbOfCompo, const std::string& msg) const +{ + if(getNumberOfComponents()!=nbOfCompo) + { + std::ostringstream oss; oss << msg << " : mismatch number of components : expected " << nbOfCompo << " having " << getNumberOfComponents() << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +void DataArray::checkNbOfElems(std::size_t nbOfElems, const std::string& msg) const +{ + if(getNbOfElems()!=nbOfElems) + { + std::ostringstream oss; oss << msg << " : mismatch number of elems : Expected " << nbOfElems << " having " << getNbOfElems() << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +void DataArray::checkNbOfTuplesAndComp(const DataArray& other, const std::string& msg) const +{ + if(getNumberOfTuples()!=other.getNumberOfTuples()) + { + std::ostringstream oss; oss << msg << " : mismatch number of tuples : expected " << other.getNumberOfTuples() << " having " << getNumberOfTuples() << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if(getNumberOfComponents()!=other.getNumberOfComponents()) + { + std::ostringstream oss; oss << msg << " : mismatch number of components : expected " << other.getNumberOfComponents() << " having " << getNumberOfComponents() << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +void DataArray::checkNbOfTuplesAndComp(int nbOfTuples, int nbOfCompo, const std::string& msg) const +{ + checkNbOfTuples(nbOfTuples,msg); + checkNbOfComps(nbOfCompo,msg); +} + +/*! + * Simply this method checks that \b value is in [0,\b ref). + */ +void DataArray::CheckValueInRange(int ref, int value, const std::string& msg) +{ + if(value<0 || value>=ref) + { + std::ostringstream oss; oss << "DataArray::CheckValueInRange : " << msg << " ! Expected in range [0," << ref << "[ having " << value << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +/*! + * This method checks that [\b start, \b end) is compliant with ref length \b value. + * typicaly start in [0,\b value) and end in [0,\b value). If value==start and start==end, it is supported. + */ +void DataArray::CheckValueInRangeEx(int value, int start, int end, const std::string& msg) +{ + if(start<0 || start>=value) + { + if(value!=start || end!=start) + { + std::ostringstream oss; oss << "DataArray::CheckValueInRangeEx : " << msg << " ! Expected start " << start << " of input range, in [0," << value << "[ !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + if(end<0 || end>value) + { + std::ostringstream oss; oss << "DataArray::CheckValueInRangeEx : " << msg << " ! Expected end " << end << " of input range, in [0," << value << "] !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +void DataArray::CheckClosingParInRange(int ref, int value, const std::string& msg) +{ + if(value<0 || value>ref) + { + std::ostringstream oss; oss << "DataArray::CheckClosingParInRange : " << msg << " ! Expected input range in [0," << ref << "] having closing open parenthesis " << value << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +/*! + * This method is useful to slice work among a pool of threads or processes. \a begin, \a end \a step is the input whole slice of work to perform, + * typically it is a whole slice of tuples of DataArray or cells, nodes of a mesh... + * + * The input \a sliceId should be an id in [0, \a nbOfSlices) that specifies the slice of work. + * + * \param [in] start - the start of the input slice of the whole work to perform splitted into slices. + * \param [in] stop - the stop of the input slice of the whole work to perform splitted into slices. + * \param [in] step - the step (that can be <0) of the input slice of the whole work to perform splitted into slices. + * \param [in] sliceId - the slice id considered + * \param [in] nbOfSlices - the number of slices (typically the number of cores on which the work is expected to be sliced) + * \param [out] startSlice - the start of the slice considered + * \param [out] stopSlice - the stop of the slice consided + * + * \throw If \a step == 0 + * \throw If \a nbOfSlices not > 0 + * \throw If \a sliceId not in [0,nbOfSlices) + */ +void DataArray::GetSlice(int start, int stop, int step, int sliceId, int nbOfSlices, int& startSlice, int& stopSlice) +{ + if(nbOfSlices<=0) + { + std::ostringstream oss; oss << "DataArray::GetSlice : nbOfSlices (" << nbOfSlices << ") must be > 0 !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if(sliceId<0 || sliceId>=nbOfSlices) + { + std::ostringstream oss; oss << "DataArray::GetSlice : sliceId (" << nbOfSlices << ") must be in [0 , nbOfSlices (" << nbOfSlices << ") ) !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + int nbElems=GetNumberOfItemGivenBESRelative(start,stop,step,"DataArray::GetSlice"); + int minNbOfElemsPerSlice=nbElems/nbOfSlices; + startSlice=start+minNbOfElemsPerSlice*step*sliceId; + if(sliceId 0 !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + return (end-1-begin)/step+1; +} + +int DataArray::GetNumberOfItemGivenBESRelative(int begin, int end, int step, const std::string& msg) +{ + if(step==0) + throw INTERP_KERNEL::Exception("DataArray::GetNumberOfItemGivenBES : step=0 is not allowed !"); + if(end0) + { + std::ostringstream oss; oss << msg << " : end before begin whereas step is positive !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if(begin 0 !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if(begin!=end) + return (std::max(begin,end)-1-std::min(begin,end))/std::abs(step)+1; + else + return 0; +} + +int DataArray::GetPosOfItemGivenBESRelativeNoThrow(int value, int begin, int end, int step) +{ + if(step!=0) + { + if(step>0) + { + if(begin<=value && value=value && value>end) + { + if((begin-value)%(-step)==0) + return (begin-value)/(-step); + else + return -1; + } + else + return -1; + } + } + else + return -1; +} + +/*! + * Returns a new instance of DataArrayDouble. The caller is to delete this array + * using decrRef() as it is no more needed. + */ +DataArrayDouble *DataArrayDouble::New() +{ + return new DataArrayDouble; +} + +/*! + * Checks if raw data is allocated. Read more on the raw data + * in \ref MEDCouplingArrayBasicsTuplesAndCompo "DataArrays infos" for more information. + * \return bool - \a true if the raw data is allocated, \a false else. + */ +bool DataArrayDouble::isAllocated() const +{ + return getConstPointer()!=0; +} + +/*! + * Checks if raw data is allocated and throws an exception if it is not the case. + * \throw If the raw data is not allocated. + */ +void DataArrayDouble::checkAllocated() const +{ + if(!isAllocated()) + throw INTERP_KERNEL::Exception("DataArrayDouble::checkAllocated : Array is defined but not allocated ! Call alloc or setValues method first !"); +} + +/*! + * This method desallocated \a this without modification of informations relative to the components. + * After call of this method, DataArrayDouble::isAllocated will return false. + * If \a this is already not allocated, \a this is let unchanged. + */ +void DataArrayDouble::desallocate() +{ + _mem.destroy(); +} + +std::size_t DataArrayDouble::getHeapMemorySizeWithoutChildren() const +{ + std::size_t sz(_mem.getNbOfElemAllocated()); + sz*=sizeof(double); + return DataArray::getHeapMemorySizeWithoutChildren()+sz; +} + +/*! + * Returns the only one value in \a this, if and only if number of elements + * (nb of tuples * nb of components) is equal to 1, and that \a this is allocated. + * \return double - the sole value stored in \a this array. + * \throw If at least one of conditions stated above is not fulfilled. + */ +double DataArrayDouble::doubleValue() const +{ + if(isAllocated()) + { + if(getNbOfElems()==1) + { + return *getConstPointer(); + } + else + throw INTERP_KERNEL::Exception("DataArrayDouble::doubleValue : DataArrayDouble instance is allocated but number of elements is not equal to 1 !"); + } + else + throw INTERP_KERNEL::Exception("DataArrayDouble::doubleValue : DataArrayDouble instance is not allocated !"); +} + +/*! + * Checks the number of tuples. + * \return bool - \a true if getNumberOfTuples() == 0, \a false else. + * \throw If \a this is not allocated. + */ +bool DataArrayDouble::empty() const +{ + checkAllocated(); + return getNumberOfTuples()==0; +} + +/*! + * Returns a full copy of \a this. For more info on copying data arrays see + * \ref MEDCouplingArrayBasicsCopyDeep. + * \return DataArrayDouble * - a new instance of DataArrayDouble. The caller is to + * delete this array using decrRef() as it is no more needed. + */ +DataArrayDouble *DataArrayDouble::deepCpy() const +{ + return new DataArrayDouble(*this); +} + +/*! + * Returns either a \a deep or \a shallow copy of this array. For more info see + * \ref MEDCouplingArrayBasicsCopyDeep and \ref MEDCouplingArrayBasicsCopyShallow. + * \param [in] dCpy - if \a true, a deep copy is returned, else, a shallow one. + * \return DataArrayDouble * - either a new instance of DataArrayDouble (if \a dCpy + * == \a true) or \a this instance (if \a dCpy == \a false). + */ +DataArrayDouble *DataArrayDouble::performCpy(bool dCpy) const +{ + if(dCpy) + return deepCpy(); + else + { + incrRef(); + return const_cast(this); + } +} + +/*! + * Copies all the data from another DataArrayDouble. For more info see + * \ref MEDCouplingArrayBasicsCopyDeepAssign. + * \param [in] other - another instance of DataArrayDouble to copy data from. + * \throw If the \a other is not allocated. + */ +void DataArrayDouble::cpyFrom(const DataArrayDouble& other) +{ + other.checkAllocated(); + int nbOfTuples=other.getNumberOfTuples(); + int nbOfComp=other.getNumberOfComponents(); + allocIfNecessary(nbOfTuples,nbOfComp); + std::size_t nbOfElems=(std::size_t)nbOfTuples*nbOfComp; + double *pt=getPointer(); + const double *ptI=other.getConstPointer(); + for(std::size_t i=0;igetNumberOfComponents() != 1 + * \throw If \a this is not allocated. + */ +void DataArrayDouble::iota(double init) +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::iota : works only for arrays with only one component, you can call 'rearrange' method before !"); + double *ptr=getPointer(); + int ntuples=getNumberOfTuples(); + for(int i=0;igetNumberOfComponents() != 1 + * \throw If \a this is not allocated. + */ +bool DataArrayDouble::isUniform(double val, double eps) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::isUniform : must be applied on DataArrayDouble with only one component, you can call 'rearrange' method before !"); + int nbOfTuples=getNumberOfTuples(); + const double *w=getConstPointer(); + const double *end2=w+nbOfTuples; + const double vmin=val-eps; + const double vmax=val+eps; + for(;w!=end2;w++) + if(*wvmax) + return false; + return true; +} + +/*! + * Sorts values of the array. + * \param [in] asc - \a true means ascending order, \a false, descending. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + */ +void DataArrayDouble::sort(bool asc) +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::sort : only supported with 'this' array with ONE component !"); + _mem.sort(asc); + declareAsNew(); +} + +/*! + * Reverse the array values. + * \throw If \a this->getNumberOfComponents() < 1. + * \throw If \a this is not allocated. + */ +void DataArrayDouble::reverse() +{ + checkAllocated(); + _mem.reverse(getNumberOfComponents()); + declareAsNew(); +} + +/*! + * Checks that \a this array is consistently **increasing** or **decreasing** in value, + * with at least absolute difference value of |\a eps| at each step. + * If not an exception is thrown. + * \param [in] increasing - if \a true, the array values should be increasing. + * \param [in] eps - minimal absolute difference between the neighbor values at which + * the values are considered different. + * \throw If sequence of values is not strictly monotonic in agreement with \a + * increasing arg. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a this is not allocated. + */ +void DataArrayDouble::checkMonotonic(bool increasing, double eps) const +{ + if(!isMonotonic(increasing,eps)) + { + if (increasing) + throw INTERP_KERNEL::Exception("DataArrayDouble::checkMonotonic : 'this' is not INCREASING monotonic !"); + else + throw INTERP_KERNEL::Exception("DataArrayDouble::checkMonotonic : 'this' is not DECREASING monotonic !"); + } +} + +/*! + * Checks that \a this array is consistently **increasing** or **decreasing** in value, + * with at least absolute difference value of |\a eps| at each step. + * \param [in] increasing - if \a true, array values should be increasing. + * \param [in] eps - minimal absolute difference between the neighbor values at which + * the values are considered different. + * \return bool - \a true if values change in accordance with \a increasing arg. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a this is not allocated. + */ +bool DataArrayDouble::isMonotonic(bool increasing, double eps) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::isMonotonic : only supported with 'this' array with ONE component !"); + int nbOfElements=getNumberOfTuples(); + const double *ptr=getConstPointer(); + if(nbOfElements==0) + return true; + double ref=ptr[0]; + double absEps=fabs(eps); + if(increasing) + { + for(int i=1;i(ref-absEps)) + return false; + ref=ptr[i]; + } + return true; + } +} + +/*! + * Returns a textual and human readable representation of \a this instance of + * DataArrayDouble. This text is shown when a DataArrayDouble is printed in Python. + * \return std::string - text describing \a this DataArrayDouble. + * + * \sa reprNotTooLong, reprZip + */ +std::string DataArrayDouble::repr() const +{ + std::ostringstream ret; + reprStream(ret); + return ret.str(); +} + +std::string DataArrayDouble::reprZip() const +{ + std::ostringstream ret; + reprZipStream(ret); + return ret.str(); +} + +/*! + * This method is close to repr method except that when \a this has more than 1000 tuples, all tuples are not + * printed out to avoid to consume too much space in interpretor. + * \sa repr + */ +std::string DataArrayDouble::reprNotTooLong() const +{ + std::ostringstream ret; + reprNotTooLongStream(ret); + return ret.str(); +} + +void DataArrayDouble::writeVTK(std::ostream& ofs, int indent, const std::string& nameInFile, DataArrayByte *byteArr) const +{ + static const char SPACE[4]={' ',' ',' ',' '}; + checkAllocated(); + std::string idt(indent,' '); + ofs.precision(17); + ofs << idt << "::const_iterator it=_info_on_compo.begin();it!=_info_on_compo.end();it++) + if(!(*it).empty()) + areAllEmpty=false; + if(!areAllEmpty) + for(std::size_t i=0;i<_info_on_compo.size();i++) + ofs << " ComponentName" << i << "=\"" << _info_on_compo[i] << "\""; + // + if(byteArr) + { + ofs << " format=\"appended\" offset=\"" << byteArr->getNumberOfTuples() << "\">"; + INTERP_KERNEL::AutoPtr tmp(new float[getNbOfElems()]); + float *pt(tmp); + // to make Visual C++ happy : instead of std::copy(begin(),end(),(float *)tmp); + for(const double *src=begin();src!=end();src++,pt++) + *pt=float(*src); + const char *data(reinterpret_cast((float *)tmp)); + std::size_t sz(getNbOfElems()*sizeof(float)); + byteArr->insertAtTheEnd(data,data+sz); + byteArr->insertAtTheEnd(SPACE,SPACE+4); + } + else + { + ofs << " RangeMin=\"" << getMinValueInArray() << "\" RangeMax=\"" << getMaxValueInArray() << "\" format=\"ascii\">\n" << idt; + std::copy(begin(),end(),std::ostream_iterator(ofs," ")); + } + ofs << std::endl << idt << "\n"; +} + +void DataArrayDouble::reprStream(std::ostream& stream) const +{ + stream << "Name of double array : \"" << _name << "\"\n"; + reprWithoutNameStream(stream); +} + +void DataArrayDouble::reprZipStream(std::ostream& stream) const +{ + stream << "Name of double array : \"" << _name << "\"\n"; + reprZipWithoutNameStream(stream); +} + +void DataArrayDouble::reprNotTooLongStream(std::ostream& stream) const +{ + stream << "Name of double array : \"" << _name << "\"\n"; + reprNotTooLongWithoutNameStream(stream); +} + +void DataArrayDouble::reprWithoutNameStream(std::ostream& stream) const +{ + DataArray::reprWithoutNameStream(stream); + stream.precision(17); + _mem.repr(getNumberOfComponents(),stream); +} + +void DataArrayDouble::reprZipWithoutNameStream(std::ostream& stream) const +{ + DataArray::reprWithoutNameStream(stream); + stream.precision(17); + _mem.reprZip(getNumberOfComponents(),stream); +} + +void DataArrayDouble::reprNotTooLongWithoutNameStream(std::ostream& stream) const +{ + DataArray::reprWithoutNameStream(stream); + stream.precision(17); + _mem.reprNotTooLong(getNumberOfComponents(),stream); +} + +void DataArrayDouble::reprCppStream(const std::string& varName, std::ostream& stream) const +{ + int nbTuples=getNumberOfTuples(),nbComp=getNumberOfComponents(); + const double *data=getConstPointer(); + stream.precision(17); + stream << "DataArrayDouble *" << varName << "=DataArrayDouble::New();" << std::endl; + if(nbTuples*nbComp>=1) + { + stream << "const double " << varName << "Data[" << nbTuples*nbComp << "]={"; + std::copy(data,data+nbTuples*nbComp-1,std::ostream_iterator(stream,",")); + stream << data[nbTuples*nbComp-1] << "};" << std::endl; + stream << varName << "->useArray(" << varName << "Data,false,CPP_DEALLOC," << nbTuples << "," << nbComp << ");" << std::endl; + } + else + stream << varName << "->alloc(" << nbTuples << "," << nbComp << ");" << std::endl; + stream << varName << "->setName(\"" << getName() << "\");" << std::endl; +} + +/*! + * Method that gives a quick overvien of \a this for python. + */ +void DataArrayDouble::reprQuickOverview(std::ostream& stream) const +{ + static const std::size_t MAX_NB_OF_BYTE_IN_REPR=300; + stream << "DataArrayDouble C++ instance at " << this << ". "; + if(isAllocated()) + { + int nbOfCompo=(int)_info_on_compo.size(); + if(nbOfCompo>=1) + { + int nbOfTuples=getNumberOfTuples(); + stream << "Number of tuples : " << nbOfTuples << ". Number of components : " << nbOfCompo << "." << std::endl; + reprQuickOverviewData(stream,MAX_NB_OF_BYTE_IN_REPR); + } + else + stream << "Number of components : 0."; + } + else + stream << "*** No data allocated ****"; +} + +void DataArrayDouble::reprQuickOverviewData(std::ostream& stream, std::size_t maxNbOfByteInRepr) const +{ + const double *data=begin(); + int nbOfTuples=getNumberOfTuples(); + int nbOfCompo=(int)_info_on_compo.size(); + std::ostringstream oss2; oss2 << "["; + oss2.precision(17); + std::string oss2Str(oss2.str()); + bool isFinished=true; + for(int i=0;i1) + { + oss2 << "("; + for(int j=0;j=0 !"); + checkAllocated(); + _mem.reAlloc(getNumberOfComponents()*(std::size_t)nbOfTuples); + declareAsNew(); +} + +/*! + * Creates a new DataArrayInt and assigns all (textual and numerical) data of \a this + * array to the new one. + * \return DataArrayInt * - the new instance of DataArrayInt. + */ +DataArrayInt *DataArrayDouble::convertToIntArr() const +{ + DataArrayInt *ret=DataArrayInt::New(); + ret->alloc(getNumberOfTuples(),getNumberOfComponents()); + int *dest=ret->getPointer(); + // to make Visual C++ happy : instead of std::size_t nbOfVals=getNbOfElems(); std::copy(src,src+nbOfVals,dest); + for(const double *src=begin();src!=end();src++,dest++) + *dest=(int)*src; + ret->copyStringInfoFrom(*this); + return ret; +} + +/*! + * Returns a new DataArrayDouble holding the same values as \a this array but differently + * arranged in memory. If \a this array holds 2 components of 3 values: + * \f$ x_0,x_1,x_2,y_0,y_1,y_2 \f$, then the result array holds these values arranged + * as follows: \f$ x_0,y_0,x_1,y_1,x_2,y_2 \f$. + * \warning Do not confuse this method with transpose()! + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + */ +DataArrayDouble *DataArrayDouble::fromNoInterlace() const +{ + if(_mem.isNull()) + throw INTERP_KERNEL::Exception("DataArrayDouble::fromNoInterlace : Not defined array !"); + double *tab=_mem.fromNoInterlace(getNumberOfComponents()); + DataArrayDouble *ret=DataArrayDouble::New(); + ret->useArray(tab,true,C_DEALLOC,getNumberOfTuples(),getNumberOfComponents()); + return ret; +} + +/*! + * Returns a new DataArrayDouble holding the same values as \a this array but differently + * arranged in memory. If \a this array holds 2 components of 3 values: + * \f$ x_0,y_0,x_1,y_1,x_2,y_2 \f$, then the result array holds these values arranged + * as follows: \f$ x_0,x_1,x_2,y_0,y_1,y_2 \f$. + * \warning Do not confuse this method with transpose()! + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + */ +DataArrayDouble *DataArrayDouble::toNoInterlace() const +{ + if(_mem.isNull()) + throw INTERP_KERNEL::Exception("DataArrayDouble::toNoInterlace : Not defined array !"); + double *tab=_mem.toNoInterlace(getNumberOfComponents()); + DataArrayDouble *ret=DataArrayDouble::New(); + ret->useArray(tab,true,C_DEALLOC,getNumberOfTuples(),getNumberOfComponents()); + return ret; +} + +/*! + * Permutes values of \a this array as required by \a old2New array. The values are + * permuted so that \c new[ \a old2New[ i ]] = \c old[ i ]. Number of tuples remains + * the same as in \c this one. + * If a permutation reduction is needed, substr() or selectByTupleId() should be used. + * For more info on renumbering see \ref numbering. + * \param [in] old2New - C array of length equal to \a this->getNumberOfTuples() + * giving a new position for i-th old value. + */ +void DataArrayDouble::renumberInPlace(const int *old2New) +{ + checkAllocated(); + int nbTuples=getNumberOfTuples(); + int nbOfCompo=getNumberOfComponents(); + double *tmp=new double[nbTuples*nbOfCompo]; + const double *iptr=getConstPointer(); + for(int i=0;i=0 && vgetNumberOfTuples() + * giving a previous position of i-th new value. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + */ +void DataArrayDouble::renumberInPlaceR(const int *new2Old) +{ + checkAllocated(); + int nbTuples=getNumberOfTuples(); + int nbOfCompo=getNumberOfComponents(); + double *tmp=new double[nbTuples*nbOfCompo]; + const double *iptr=getConstPointer(); + for(int i=0;i=0 && vgetNumberOfTuples() + * giving a new position for i-th old value. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + */ +DataArrayDouble *DataArrayDouble::renumber(const int *old2New) const +{ + checkAllocated(); + int nbTuples=getNumberOfTuples(); + int nbOfCompo=getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(nbTuples,nbOfCompo); + ret->copyStringInfoFrom(*this); + const double *iptr=getConstPointer(); + double *optr=ret->getPointer(); + for(int i=0;icopyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a copy of \a this array with values permuted as required by \a new2Old array. + * The values are permuted so that \c new[ i ] = \c old[ \a new2Old[ i ]]. Number of + * tuples in the result array remains the same as in \c this one. + * If a permutation reduction is needed, substr() or selectByTupleId() should be used. + * For more info on renumbering see \ref numbering. + * \param [in] new2Old - C array of length equal to \a this->getNumberOfTuples() + * giving a previous position of i-th new value. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + */ +DataArrayDouble *DataArrayDouble::renumberR(const int *new2Old) const +{ + checkAllocated(); + int nbTuples=getNumberOfTuples(); + int nbOfCompo=getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(nbTuples,nbOfCompo); + ret->copyStringInfoFrom(*this); + const double *iptr=getConstPointer(); + double *optr=ret->getPointer(); + for(int i=0;icopyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a shorten and permuted copy of \a this array. The new DataArrayDouble is + * of size \a newNbOfTuple and it's values are permuted as required by \a old2New array. + * The values are permuted so that \c new[ \a old2New[ i ]] = \c old[ i ] for all + * \a old2New[ i ] >= 0. In other words every i-th tuple in \a this array, for which + * \a old2New[ i ] is negative, is missing from the result array. + * For more info on renumbering see \ref numbering. + * \param [in] old2New - C array of length equal to \a this->getNumberOfTuples() + * giving a new position for i-th old tuple and giving negative position for + * for i-th old tuple that should be omitted. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + */ +DataArrayDouble *DataArrayDouble::renumberAndReduce(const int *old2New, int newNbOfTuple) const +{ + checkAllocated(); + int nbTuples=getNumberOfTuples(); + int nbOfCompo=getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(newNbOfTuple,nbOfCompo); + const double *iptr=getConstPointer(); + double *optr=ret->getPointer(); + for(int i=0;i=0) + std::copy(iptr+i*nbOfCompo,iptr+(i+1)*nbOfCompo,optr+w*nbOfCompo); + } + ret->copyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a shorten and permuted copy of \a this array. The new DataArrayDouble is + * of size \a new2OldEnd - \a new2OldBg and it's values are permuted as required by + * \a new2OldBg array. + * The values are permuted so that \c new[ i ] = \c old[ \a new2OldBg[ i ]]. + * This method is equivalent to renumberAndReduce() except that convention in input is + * \c new2old and \b not \c old2new. + * For more info on renumbering see \ref numbering. + * \param [in] new2OldBg - pointer to the beginning of a permutation array that gives a + * tuple index in \a this array to fill the i-th tuple in the new array. + * \param [in] new2OldEnd - specifies the end of the permutation array that starts at + * \a new2OldBg, so that pointer to a tuple index (\a pi) varies as this: + * \a new2OldBg <= \a pi < \a new2OldEnd. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + */ +DataArrayDouble *DataArrayDouble::selectByTupleId(const int *new2OldBg, const int *new2OldEnd) const +{ + checkAllocated(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + int nbComp=getNumberOfComponents(); + ret->alloc((int)std::distance(new2OldBg,new2OldEnd),nbComp); + ret->copyStringInfoFrom(*this); + double *pt=ret->getPointer(); + const double *srcPt=getConstPointer(); + int i=0; + for(const int *w=new2OldBg;w!=new2OldEnd;w++,i++) + std::copy(srcPt+(*w)*nbComp,srcPt+((*w)+1)*nbComp,pt+i*nbComp); + ret->copyStringInfoFrom(*this); + return ret.retn(); +} + ++DataArrayDouble *DataArrayDouble::selectByTupleId(const DataArrayInt & di) const ++{ ++ return selectByTupleId(di.getConstPointer(), di.getConstPointer()+di.getNumberOfTuples()); ++} ++ +/*! + * Returns a shorten and permuted copy of \a this array. The new DataArrayDouble is + * of size \a new2OldEnd - \a new2OldBg and it's values are permuted as required by + * \a new2OldBg array. + * The values are permuted so that \c new[ i ] = \c old[ \a new2OldBg[ i ]]. + * This method is equivalent to renumberAndReduce() except that convention in input is + * \c new2old and \b not \c old2new. + * This method is equivalent to selectByTupleId() except that it prevents coping data + * from behind the end of \a this array. + * For more info on renumbering see \ref numbering. + * \param [in] new2OldBg - pointer to the beginning of a permutation array that gives a + * tuple index in \a this array to fill the i-th tuple in the new array. + * \param [in] new2OldEnd - specifies the end of the permutation array that starts at + * \a new2OldBg, so that pointer to a tuple index (\a pi) varies as this: + * \a new2OldBg <= \a pi < \a new2OldEnd. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a new2OldEnd - \a new2OldBg > \a this->getNumberOfTuples(). + */ +DataArrayDouble *DataArrayDouble::selectByTupleIdSafe(const int *new2OldBg, const int *new2OldEnd) const +{ + checkAllocated(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + int nbComp=getNumberOfComponents(); + int oldNbOfTuples=getNumberOfTuples(); + ret->alloc((int)std::distance(new2OldBg,new2OldEnd),nbComp); + ret->copyStringInfoFrom(*this); + double *pt=ret->getPointer(); + const double *srcPt=getConstPointer(); + int i=0; + for(const int *w=new2OldBg;w!=new2OldEnd;w++,i++) + if(*w>=0 && *wgetNumberOfTuples) !"); + ret->copyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a shorten copy of \a this array. The new DataArrayDouble contains every + * (\a bg + \c i * \a step)-th tuple of \a this array located before the \a end2-th + * tuple. Indices of the selected tuples are the same as ones returned by the Python + * command \c range( \a bg, \a end2, \a step ). + * This method is equivalent to selectByTupleIdSafe() except that the input array is + * not constructed explicitly. + * For more info on renumbering see \ref numbering. + * \param [in] bg - index of the first tuple to copy from \a this array. + * \param [in] end2 - index of the tuple before which the tuples to copy are located. + * \param [in] step - index increment to get index of the next tuple to copy. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + * \sa DataArrayDouble::substr. + */ +DataArrayDouble *DataArrayDouble::selectByTupleId2(int bg, int end2, int step) const +{ + checkAllocated(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + int nbComp=getNumberOfComponents(); + int newNbOfTuples=GetNumberOfItemGivenBESRelative(bg,end2,step,"DataArrayDouble::selectByTupleId2 : "); + ret->alloc(newNbOfTuples,nbComp); + double *pt=ret->getPointer(); + const double *srcPt=getConstPointer()+bg*nbComp; + for(int i=0;icopyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a shorten copy of \a this array. The new DataArrayDouble contains ranges + * of tuples specified by \a ranges parameter. + * For more info on renumbering see \ref numbering. + * \param [in] ranges - std::vector of std::pair's each of which defines a range + * of tuples in [\c begin,\c end) format. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a end < \a begin. + * \throw If \a end > \a this->getNumberOfTuples(). + * \throw If \a this is not allocated. + */ +DataArray *DataArrayDouble::selectByTupleRanges(const std::vector >& ranges) const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + int nbOfTuplesThis=getNumberOfTuples(); + if(ranges.empty()) + { + DataArrayDouble *ret=DataArrayDouble::New(); + ret->alloc(0,nbOfComp); + ret->copyStringInfoFrom(*this); + return ret; + } + int ref=ranges.front().first; + int nbOfTuples=0; + bool isIncreasing=true; + for(std::vector >::const_iterator it=ranges.begin();it!=ranges.end();it++) + { + if((*it).first<=(*it).second) + { + if((*it).first>=0 && (*it).second<=nbOfTuplesThis) + { + nbOfTuples+=(*it).second-(*it).first; + if(isIncreasing) + isIncreasing=ref<=(*it).first; + ref=(*it).second; + } + else + { + std::ostringstream oss; oss << "DataArrayDouble::selectByTupleRanges : on range #" << std::distance(ranges.begin(),it); + oss << " (" << (*it).first << "," << (*it).second << ") is greater than number of tuples of this :" << nbOfTuples << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + else + { + std::ostringstream oss; oss << "DataArrayDouble::selectByTupleRanges : on range #" << std::distance(ranges.begin(),it); + oss << " (" << (*it).first << "," << (*it).second << ") end is before begin !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + if(isIncreasing && nbOfTuplesThis==nbOfTuples) + return deepCpy(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(nbOfTuples,nbOfComp); + ret->copyStringInfoFrom(*this); + const double *src=getConstPointer(); + double *work=ret->getPointer(); + for(std::vector >::const_iterator it=ranges.begin();it!=ranges.end();it++) + work=std::copy(src+(*it).first*nbOfComp,src+(*it).second*nbOfComp,work); + return ret.retn(); +} + +/*! + * Returns a shorten copy of \a this array. The new DataArrayDouble contains all + * tuples starting from the \a tupleIdBg-th tuple and including all tuples located before + * the \a tupleIdEnd-th one. This methods has a similar behavior as std::string::substr(). + * This method is a specialization of selectByTupleId2(). + * \param [in] tupleIdBg - index of the first tuple to copy from \a this array. + * \param [in] tupleIdEnd - index of the tuple before which the tuples to copy are located. + * If \a tupleIdEnd == -1, all the tuples till the end of \a this array are copied. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a tupleIdBg < 0. + * \throw If \a tupleIdBg > \a this->getNumberOfTuples(). + \throw If \a tupleIdEnd != -1 && \a tupleIdEnd < \a this->getNumberOfTuples(). + * \sa DataArrayDouble::selectByTupleId2 + */ +DataArrayDouble *DataArrayDouble::substr(int tupleIdBg, int tupleIdEnd) const +{ + checkAllocated(); + int nbt=getNumberOfTuples(); + if(tupleIdBg<0) + throw INTERP_KERNEL::Exception("DataArrayDouble::substr : The tupleIdBg parameter must be greater than 0 !"); + if(tupleIdBg>nbt) + throw INTERP_KERNEL::Exception("DataArrayDouble::substr : The tupleIdBg parameter is greater than number of tuples !"); + int trueEnd=tupleIdEnd; + if(tupleIdEnd!=-1) + { + if(tupleIdEnd>nbt) + throw INTERP_KERNEL::Exception("DataArrayDouble::substr : The tupleIdBg parameter is greater or equal than number of tuples !"); + } + else + trueEnd=nbt; + int nbComp=getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(trueEnd-tupleIdBg,nbComp); + ret->copyStringInfoFrom(*this); + std::copy(getConstPointer()+tupleIdBg*nbComp,getConstPointer()+trueEnd*nbComp,ret->getPointer()); + return ret.retn(); +} + +/*! + * Returns a shorten or extended copy of \a this array. If \a newNbOfComp is less + * than \a this->getNumberOfComponents() then the result array is shorten as each tuple + * is truncated to have \a newNbOfComp components, keeping first components. If \a + * newNbOfComp is more than \a this->getNumberOfComponents() then the result array is + * expanded as each tuple is populated with \a dftValue to have \a newNbOfComp + * components. + * \param [in] newNbOfComp - number of components for the new array to have. + * \param [in] dftValue - value assigned to new values added to the new array. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + */ +DataArrayDouble *DataArrayDouble::changeNbOfComponents(int newNbOfComp, double dftValue) const +{ + checkAllocated(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(getNumberOfTuples(),newNbOfComp); + const double *oldc=getConstPointer(); + double *nc=ret->getPointer(); + int nbOfTuples=getNumberOfTuples(); + int oldNbOfComp=getNumberOfComponents(); + int dim=std::min(oldNbOfComp,newNbOfComp); + for(int i=0;isetName(getName()); + for(int i=0;isetInfoOnComponent(i,getInfoOnComponent(i)); + ret->setName(getName()); + return ret.retn(); +} + +/*! + * Changes the number of components within \a this array so that its raw data **does + * not** change, instead splitting this data into tuples changes. + * \warning This method erases all (name and unit) component info set before! + * \param [in] newNbOfComp - number of components for \a this array to have. + * \throw If \a this is not allocated + * \throw If getNbOfElems() % \a newNbOfCompo != 0. + * \throw If \a newNbOfCompo is lower than 1. + * \throw If the rearrange method would lead to a number of tuples higher than 2147483647 (maximal capacity of int32 !). + * \warning This method erases all (name and unit) component info set before! + */ +void DataArrayDouble::rearrange(int newNbOfCompo) +{ + checkAllocated(); + if(newNbOfCompo<1) + throw INTERP_KERNEL::Exception("DataArrayDouble::rearrange : input newNbOfCompo must be > 0 !"); + std::size_t nbOfElems=getNbOfElems(); + if(nbOfElems%newNbOfCompo!=0) + throw INTERP_KERNEL::Exception("DataArrayDouble::rearrange : nbOfElems%newNbOfCompo!=0 !"); + if(nbOfElems/newNbOfCompo>(std::size_t)std::numeric_limits::max()) + throw INTERP_KERNEL::Exception("DataArrayDouble::rearrange : the rearrangement leads to too high number of tuples (> 2147483647) !"); + _info_on_compo.clear(); + _info_on_compo.resize(newNbOfCompo); + declareAsNew(); +} + +/*! + * Changes the number of components within \a this array to be equal to its number + * of tuples, and inversely its number of tuples to become equal to its number of + * components. So that its raw data **does not** change, instead splitting this + * data into tuples changes. + * \warning This method erases all (name and unit) component info set before! + * \warning Do not confuse this method with fromNoInterlace() and toNoInterlace()! + * \throw If \a this is not allocated. + * \sa rearrange() + */ +void DataArrayDouble::transpose() +{ + checkAllocated(); + int nbOfTuples=getNumberOfTuples(); + rearrange(nbOfTuples); +} + +/*! + * Returns a copy of \a this array composed of selected components. + * The new DataArrayDouble has the same number of tuples but includes components + * specified by \a compoIds parameter. So that getNbOfElems() of the result array + * can be either less, same or more than \a this->getNbOfElems(). + * \param [in] compoIds - sequence of zero based indices of components to include + * into the new array. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + * \throw If a component index (\a i) is not valid: + * \a i < 0 || \a i >= \a this->getNumberOfComponents(). + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarraydouble_KeepSelectedComponents "Here is a Python example". + * \endif + */ +DataArrayDouble *DataArrayDouble::keepSelectedComponents(const std::vector& compoIds) const +{ + checkAllocated(); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayDouble::New()); + std::size_t newNbOfCompo=compoIds.size(); + int oldNbOfCompo=getNumberOfComponents(); + for(std::vector::const_iterator it=compoIds.begin();it!=compoIds.end();it++) + if((*it)<0 || (*it)>=oldNbOfCompo) + { + std::ostringstream oss; oss << "DataArrayDouble::keepSelectedComponents : invalid requested component : " << *it << " whereas it should be in [0," << oldNbOfCompo << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + int nbOfTuples=getNumberOfTuples(); + ret->alloc(nbOfTuples,(int)newNbOfCompo); + ret->copyPartOfStringInfoFrom(*this,compoIds); + const double *oldc=getConstPointer(); + double *nc=ret->getPointer(); + for(int i=0;icheckAllocated(); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples!=other->getNumberOfTuples()) + throw INTERP_KERNEL::Exception("DataArrayDouble::meldWith : mismatch of number of tuples !"); + int nbOfComp1=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + double *newArr=(double *)malloc((nbOfTuples*(nbOfComp1+nbOfComp2))*sizeof(double)); + double *w=newArr; + const double *inp1=getConstPointer(); + const double *inp2=other->getConstPointer(); + for(int i=0;i compIds(nbOfComp2); + for(int i=0;igetNumberOfTuples() ) tuple #i in \a other is equal ( regarding input precision \a prec ) to tuple tupleIds[i] in \a this. + * + * \param [in] other - the array having the same number of components than \a this. + * \param [out] tupleIds - the tuple ids containing the same number of tuples than \a other has. + * \sa DataArrayDouble::findCommonTuples + */ +bool DataArrayDouble::areIncludedInMe(const DataArrayDouble *other, double prec, DataArrayInt *&tupleIds) const +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayDouble::areIncludedInMe : input array is NULL !"); + checkAllocated(); other->checkAllocated(); + if(getNumberOfComponents()!=other->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("DataArrayDouble::areIncludedInMe : the number of components does not match !"); + MEDCouplingAutoRefCountObjectPtr a=DataArrayDouble::Aggregate(this,other); + DataArrayInt *c=0,*ci=0; + a->findCommonTuples(prec,getNumberOfTuples(),c,ci); + MEDCouplingAutoRefCountObjectPtr cSafe(c),ciSafe(ci); + int newNbOfTuples=-1; + MEDCouplingAutoRefCountObjectPtr ids=DataArrayInt::BuildOld2NewArrayFromSurjectiveFormat2(a->getNumberOfTuples(),c->begin(),ci->begin(),ci->end(),newNbOfTuples); + MEDCouplingAutoRefCountObjectPtr ret1=ids->selectByTupleId2(getNumberOfTuples(),a->getNumberOfTuples(),1); + tupleIds=ret1.retn(); + return newNbOfTuples==getNumberOfTuples(); +} + +/*! + * Searches for tuples coincident within \a prec tolerance. Each tuple is considered + * as coordinates of a point in getNumberOfComponents()-dimensional space. The + * distance separating two points is computed with the infinite norm. + * + * Indices of coincident tuples are stored in output arrays. + * A pair of arrays (\a comm, \a commIndex) is called "Surjective Format 2". + * + * This method is typically used by MEDCouplingPointSet::findCommonNodes() and + * MEDCouplingUMesh::mergeNodes(). + * \param [in] prec - minimal absolute distance between two tuples (infinite norm) at which they are + * considered not coincident. + * \param [in] limitTupleId - limit tuple id. If all tuples within a group of coincident + * tuples have id strictly lower than \a limitTupleId then they are not returned. + * \param [out] comm - the array holding ids (== indices) of coincident tuples. + * \a comm->getNumberOfComponents() == 1. + * \a comm->getNumberOfTuples() == \a commIndex->back(). + * \param [out] commIndex - the array dividing all indices stored in \a comm into + * groups of (indices of) coincident tuples. Its every value is a tuple + * index where a next group of tuples begins. For example the second + * group of tuples in \a comm is described by following range of indices: + * [ \a commIndex[1], \a commIndex[2] ). \a commIndex->getNumberOfTuples()-1 + * gives the number of groups of coincident tuples. + * \throw If \a this is not allocated. + * \throw If the number of components is not in [1,2,3,4]. + * + * \if ENABLE_EXAMPLES + * \ref cpp_mcdataarraydouble_findcommontuples "Here is a C++ example". + * + * \ref py_mcdataarraydouble_findcommontuples "Here is a Python example". + * \endif + * \sa DataArrayInt::BuildOld2NewArrayFromSurjectiveFormat2(), DataArrayDouble::areIncludedInMe + */ +void DataArrayDouble::findCommonTuples(double prec, int limitTupleId, DataArrayInt *&comm, DataArrayInt *&commIndex) const +{ + checkAllocated(); + int nbOfCompo=getNumberOfComponents(); + if ((nbOfCompo<1) || (nbOfCompo>4)) //test before work + throw INTERP_KERNEL::Exception("DataArrayDouble::findCommonTuples : Unexpected spacedim of coords. Must be 1, 2, 3 or 4."); + + int nbOfTuples=getNumberOfTuples(); + // + MEDCouplingAutoRefCountObjectPtr c(DataArrayInt::New()),cI(DataArrayInt::New()); c->alloc(0,1); cI->pushBackSilent(0); + switch(nbOfCompo) + { + case 4: + findCommonTuplesAlg<4>(begin(),nbOfTuples,limitTupleId,prec,c,cI); + break; + case 3: + findCommonTuplesAlg<3>(begin(),nbOfTuples,limitTupleId,prec,c,cI); + break; + case 2: + findCommonTuplesAlg<2>(begin(),nbOfTuples,limitTupleId,prec,c,cI); + break; + case 1: + findCommonTuplesAlg<1>(begin(),nbOfTuples,limitTupleId,prec,c,cI); + break; + default: + throw INTERP_KERNEL::Exception("DataArrayDouble::findCommonTuples : nb of components managed are 1,2,3 and 4 ! not implemented for other number of components !"); + } + comm=c.retn(); + commIndex=cI.retn(); +} + +/*! + * + * \param [in] nbTimes specifies the nb of times each tuples in \a this will be duplicated contiguouly in returned DataArrayDouble instance. + * \a nbTimes should be at least equal to 1. + * \return a newly allocated DataArrayDouble having one component and number of tuples equal to \a nbTimes * \c this->getNumberOfTuples. + * \throw if \a this is not allocated or if \a this has not number of components set to one or if \a nbTimes is lower than 1. + */ +DataArrayDouble *DataArrayDouble::duplicateEachTupleNTimes(int nbTimes) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::duplicateEachTupleNTimes : this should have only one component !"); + if(nbTimes<1) + throw INTERP_KERNEL::Exception("DataArrayDouble::duplicateEachTupleNTimes : nb times should be >= 1 !"); + int nbTuples=getNumberOfTuples(); + const double *inPtr=getConstPointer(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); ret->alloc(nbTimes*nbTuples,1); + double *retPtr=ret->getPointer(); + for(int i=0;icopyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * This methods returns the minimal distance between the two set of points \a this and \a other. + * So \a this and \a other have to have the same number of components. If not an INTERP_KERNEL::Exception will be thrown. + * This method works only if number of components of \a this (equal to those of \a other) is in 1, 2 or 3. + * + * \param [out] thisTupleId the tuple id in \a this corresponding to the returned minimal distance + * \param [out] otherTupleId the tuple id in \a other corresponding to the returned minimal distance + * \return the minimal distance between the two set of points \a this and \a other. + * \sa DataArrayDouble::findClosestTupleId + */ +double DataArrayDouble::minimalDistanceTo(const DataArrayDouble *other, int& thisTupleId, int& otherTupleId) const +{ + MEDCouplingAutoRefCountObjectPtr part1=findClosestTupleId(other); + int nbOfCompo(getNumberOfComponents()); + int otherNbTuples(other->getNumberOfTuples()); + const double *thisPt(begin()),*otherPt(other->begin()); + const int *part1Pt(part1->begin()); + double ret=std::numeric_limits::max(); + for(int i=0;igetNumberOfTuples() tuples and one components. + * \sa DataArrayDouble::minimalDistanceTo + */ +DataArrayInt *DataArrayDouble::findClosestTupleId(const DataArrayDouble *other) const +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayDouble::findClosestTupleId : other instance is NULL !"); + checkAllocated(); other->checkAllocated(); + int nbOfCompo=getNumberOfComponents(); + if(nbOfCompo!=other->getNumberOfComponents()) + { + std::ostringstream oss; oss << "DataArrayDouble::findClosestTupleId : number of components in this is " << nbOfCompo; + oss << ", whereas number of components in other is " << other->getNumberOfComponents() << "! Should be equal !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + int nbOfTuples=other->getNumberOfTuples(); + int thisNbOfTuples=getNumberOfTuples(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); ret->alloc(nbOfTuples,1); + double bounds[6]; + getMinMaxPerComponent(bounds); + switch(nbOfCompo) + { + case 3: + { + double xDelta(fabs(bounds[1]-bounds[0])),yDelta(fabs(bounds[3]-bounds[2])),zDelta(fabs(bounds[5]-bounds[4])); + double delta=std::max(xDelta,yDelta); delta=std::max(delta,zDelta); + double characSize=pow((delta*delta*delta)/((double)thisNbOfTuples),1./3.); + BBTreePts<3,int> myTree(begin(),0,0,getNumberOfTuples(),characSize*1e-12); + FindClosestTupleIdAlg<3>(myTree,3.*characSize*characSize,other->begin(),nbOfTuples,begin(),thisNbOfTuples,ret->getPointer()); + break; + } + case 2: + { + double xDelta(fabs(bounds[1]-bounds[0])),yDelta(fabs(bounds[3]-bounds[2])); + double delta=std::max(xDelta,yDelta); + double characSize=sqrt(delta/(double)thisNbOfTuples); + BBTreePts<2,int> myTree(begin(),0,0,getNumberOfTuples(),characSize*1e-12); + FindClosestTupleIdAlg<2>(myTree,2.*characSize*characSize,other->begin(),nbOfTuples,begin(),thisNbOfTuples,ret->getPointer()); + break; + } + case 1: + { + double characSize=fabs(bounds[1]-bounds[0])/thisNbOfTuples; + BBTreePts<1,int> myTree(begin(),0,0,getNumberOfTuples(),characSize*1e-12); + FindClosestTupleIdAlg<1>(myTree,1.*characSize*characSize,other->begin(),nbOfTuples,begin(),thisNbOfTuples,ret->getPointer()); + break; + } + default: + throw INTERP_KERNEL::Exception("Unexpected spacedim of coords for findClosestTupleId. Must be 1, 2 or 3."); + } + return ret.retn(); +} + +/*! + * This method expects that \a this and \a otherBBoxFrmt arrays are bounding box arrays ( as the output of MEDCouplingPointSet::getBoundingBoxForBBTree method ). + * This method will return a DataArrayInt array having the same number of tuples than \a this. This returned array tells for each cell in \a this + * how many bounding boxes in \a otherBBoxFrmt. + * So, this method expects that \a this and \a otherBBoxFrmt have the same number of components. + * + * \param [in] otherBBoxFrmt - It is an array . + * \param [in] eps - the absolute precision of the detection. when eps < 0 the bboxes are enlarged so more interactions are detected. Inversely when > 0 the bboxes are stretched. + * \sa MEDCouplingPointSet::getBoundingBoxForBBTree + * \throw If \a this and \a otherBBoxFrmt have not the same number of components. + * \throw If \a this and \a otherBBoxFrmt number of components is not even (BBox format). + */ +DataArrayInt *DataArrayDouble::computeNbOfInteractionsWith(const DataArrayDouble *otherBBoxFrmt, double eps) const +{ + if(!otherBBoxFrmt) + throw INTERP_KERNEL::Exception("DataArrayDouble::computeNbOfInteractionsWith : input array is NULL !"); + if(!isAllocated() || !otherBBoxFrmt->isAllocated()) + throw INTERP_KERNEL::Exception("DataArrayDouble::computeNbOfInteractionsWith : this and input array must be allocated !"); + int nbOfComp(getNumberOfComponents()),nbOfTuples(getNumberOfTuples()); + if(nbOfComp!=otherBBoxFrmt->getNumberOfComponents()) + { + std::ostringstream oss; oss << "DataArrayDouble::computeNbOfInteractionsWith : this number of components (" << nbOfComp << ") must be equal to the number of components of input array (" << otherBBoxFrmt->getNumberOfComponents() << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if(nbOfComp%2!=0) + { + std::ostringstream oss; oss << "DataArrayDouble::computeNbOfInteractionsWith : Number of components (" << nbOfComp << ") is not even ! It should be to be compatible with bbox format !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(nbOfTuples,1); + const double *thisBBPtr(begin()); + int *retPtr(ret->getPointer()); + switch(nbOfComp/2) + { + case 3: + { + BBTree<3,int> bbt(otherBBoxFrmt->begin(),0,0,otherBBoxFrmt->getNumberOfTuples(),eps); + for(int i=0;i bbt(otherBBoxFrmt->begin(),0,0,otherBBoxFrmt->getNumberOfTuples(),eps); + for(int i=0;i bbt(otherBBoxFrmt->begin(),0,0,otherBBoxFrmt->getNumberOfTuples(),eps); + for(int i=0;i c(c0),cI(cI0); + int newNbOfTuples=-1; + MEDCouplingAutoRefCountObjectPtr o2n=DataArrayInt::BuildOld2NewArrayFromSurjectiveFormat2(getNumberOfTuples(),c0->begin(),cI0->begin(),cI0->end(),newNbOfTuples); + return renumberAndReduce(o2n->getConstPointer(),newNbOfTuples); +} + +/*! + * Copy all components in a specified order from another DataArrayDouble. + * Both numerical and textual data is copied. The number of tuples in \a this and + * the other array can be different. + * \param [in] a - the array to copy data from. + * \param [in] compoIds - sequence of zero based indices of components, data of which is + * to be copied. + * \throw If \a a is NULL. + * \throw If \a compoIds.size() != \a a->getNumberOfComponents(). + * \throw If \a compoIds[i] < 0 or \a compoIds[i] > \a this->getNumberOfComponents(). + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarraydouble_setselectedcomponents "Here is a Python example". + * \endif + */ +void DataArrayDouble::setSelectedComponents(const DataArrayDouble *a, const std::vector& compoIds) +{ + if(!a) + throw INTERP_KERNEL::Exception("DataArrayDouble::setSelectedComponents : input DataArrayDouble is NULL !"); + checkAllocated(); + copyPartOfStringInfoFrom2(compoIds,*a); + std::size_t partOfCompoSz=compoIds.size(); + int nbOfCompo=getNumberOfComponents(); + int nbOfTuples=std::min(getNumberOfTuples(),a->getNumberOfTuples()); + const double *ac=a->getConstPointer(); + double *nc=getPointer(); + for(int i=0;igetNumberOfComponents() + * must be equal to the number of columns to assign to, else an + * exception is thrown; if \a false, then it is only required that \a + * a->getNbOfElems() equals to number of values to assign to (this condition + * must be respected even if \a strictCompoCompare is \a true). The number of + * values to assign to is given by following Python expression: + * \a nbTargetValues = + * \c len(\c range(\a bgTuples,\a endTuples,\a stepTuples)) * + * \c len(\c range(\a bgComp,\a endComp,\a stepComp)). + * \throw If \a a is NULL. + * \throw If \a a is not allocated. + * \throw If \a this is not allocated. + * \throw If parameters specifying tuples and components to assign to do not give a + * non-empty range of increasing indices. + * \throw If \a a->getNbOfElems() != \a nbTargetValues. + * \throw If \a strictCompoCompare == \a true && \a a->getNumberOfComponents() != + * \c len(\c range(\a bgComp,\a endComp,\a stepComp)). + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarraydouble_setpartofvalues1 "Here is a Python example". + * \endif + */ +void DataArrayDouble::setPartOfValues1(const DataArrayDouble *a, int bgTuples, int endTuples, int stepTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare) +{ + if(!a) + throw INTERP_KERNEL::Exception("DataArrayDouble::setPartOfValues1 : input DataArrayDouble is NULL !"); + const char msg[]="DataArrayDouble::setPartOfValues1"; + checkAllocated(); + a->checkAllocated(); + int newNbOfTuples=DataArray::GetNumberOfItemGivenBES(bgTuples,endTuples,stepTuples,msg); + int newNbOfComp=DataArray::GetNumberOfItemGivenBES(bgComp,endComp,stepComp,msg); + int nbComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + DataArray::CheckValueInRangeEx(nbOfTuples,bgTuples,endTuples,"invalid tuple value"); + DataArray::CheckValueInRangeEx(nbComp,bgComp,endComp,"invalid component value"); + bool assignTech=true; + if(a->getNbOfElems()==(std::size_t)newNbOfTuples*newNbOfComp) + { + if(strictCompoCompare) + a->checkNbOfTuplesAndComp(newNbOfTuples,newNbOfComp,msg); + } + else + { + a->checkNbOfTuplesAndComp(1,newNbOfComp,msg); + assignTech=false; + } + const double *srcPt=a->getConstPointer(); + double *pt=getPointer()+bgTuples*nbComp+bgComp; + if(assignTech) + { + for(int i=0;igetNbOfElems() equals to number of values to assign to, then every value + * of \a a is assigned to its own location within \a this array. + * - If \a a includes one tuple, then all values of \a a are assigned to the specified + * components of every specified tuple of \a this array. In this mode it is required + * that \a a->getNumberOfComponents() equals to the number of specified components. + * + * \param [in] a - the array to copy values from. + * \param [in] bgTuples - pointer to an array of tuple indices of \a this array to + * assign values of \a a to. + * \param [in] endTuples - specifies the end of the array \a bgTuples, so that + * pointer to a tuple index (pi) varies as this: + * \a bgTuples <= \a pi < \a endTuples. + * \param [in] bgComp - pointer to an array of component indices of \a this array to + * assign values of \a a to. + * \param [in] endComp - specifies the end of the array \a bgTuples, so that + * pointer to a component index (pi) varies as this: + * \a bgComp <= \a pi < \a endComp. + * \param [in] strictCompoCompare - this parameter is checked only if the + * *mode of usage* is the first; if it is \a true (default), + * then \a a->getNumberOfComponents() must be equal + * to the number of specified columns, else this is not required. + * \throw If \a a is NULL. + * \throw If \a a is not allocated. + * \throw If \a this is not allocated. + * \throw If any index of tuple/component given by bgTuples / bgComp is + * out of a valid range for \a this array. + * \throw In the first *mode of usage*, if strictCompoCompare == true and + * if a->getNumberOfComponents() != (endComp - bgComp) . + * \throw In the second *mode of usage*, if \a a->getNumberOfTuples() != 1 or + * a->getNumberOfComponents() != (endComp - bgComp). + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarraydouble_setpartofvalues2 "Here is a Python example". + * \endif + */ +void DataArrayDouble::setPartOfValues2(const DataArrayDouble *a, const int *bgTuples, const int *endTuples, const int *bgComp, const int *endComp, bool strictCompoCompare) +{ + if(!a) + throw INTERP_KERNEL::Exception("DataArrayDouble::setPartOfValues2 : input DataArrayDouble is NULL !"); + const char msg[]="DataArrayDouble::setPartOfValues2"; + checkAllocated(); + a->checkAllocated(); + int nbComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + for(const int *z=bgComp;z!=endComp;z++) + DataArray::CheckValueInRange(nbComp,*z,"invalid component id"); + int newNbOfTuples=(int)std::distance(bgTuples,endTuples); + int newNbOfComp=(int)std::distance(bgComp,endComp); + bool assignTech=true; + if(a->getNbOfElems()==(std::size_t)newNbOfTuples*newNbOfComp) + { + if(strictCompoCompare) + a->checkNbOfTuplesAndComp(newNbOfTuples,newNbOfComp,msg); + } + else + { + a->checkNbOfTuplesAndComp(1,newNbOfComp,msg); + assignTech=false; + } + double *pt=getPointer(); + const double *srcPt=a->getConstPointer(); + if(assignTech) + { + for(const int *w=bgTuples;w!=endTuples;w++) + { + DataArray::CheckValueInRange(nbOfTuples,*w,"invalid tuple id"); + for(const int *z=bgComp;z!=endComp;z++,srcPt++) + { + pt[(std::size_t)(*w)*nbComp+(*z)]=*srcPt; + } + } + } + else + { + for(const int *w=bgTuples;w!=endTuples;w++) + { + const double *srcPt2=srcPt; + DataArray::CheckValueInRange(nbOfTuples,*w,"invalid tuple id"); + for(const int *z=bgComp;z!=endComp;z++,srcPt2++) + { + pt[(std::size_t)(*w)*nbComp+(*z)]=*srcPt2; + } + } + } +} + +/*! + * Assign a given value to values at specified tuples and components of \a this array. + * The tuples and components to assign to are defined by C arrays of indices. + * \param [in] a - the value to assign. + * \param [in] bgTuples - pointer to an array of tuple indices of \a this array to + * assign \a a to. + * \param [in] endTuples - specifies the end of the array \a bgTuples, so that + * pointer to a tuple index (\a pi) varies as this: + * \a bgTuples <= \a pi < \a endTuples. + * \param [in] bgComp - pointer to an array of component indices of \a this array to + * assign \a a to. + * \param [in] endComp - specifies the end of the array \a bgTuples, so that + * pointer to a component index (\a pi) varies as this: + * \a bgComp <= \a pi < \a endComp. + * \throw If \a this is not allocated. + * \throw If any index of tuple/component given by bgTuples / bgComp is + * out of a valid range for \a this array. + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarraydouble_setpartofvaluessimple2 "Here is a Python example". + * \endif + */ +void DataArrayDouble::setPartOfValuesSimple2(double a, const int *bgTuples, const int *endTuples, const int *bgComp, const int *endComp) +{ + checkAllocated(); + int nbComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + for(const int *z=bgComp;z!=endComp;z++) + DataArray::CheckValueInRange(nbComp,*z,"invalid component id"); + double *pt=getPointer(); + for(const int *w=bgTuples;w!=endTuples;w++) + for(const int *z=bgComp;z!=endComp;z++) + { + DataArray::CheckValueInRange(nbOfTuples,*w,"invalid tuple id"); + pt[(std::size_t)(*w)*nbComp+(*z)]=a; + } +} + +/*! + * Copy all values from another DataArrayDouble (\a a) into specified tuples and + * components of \a this array. Textual data is not copied. + * The tuples to assign to are defined by a C array of indices. + * The components to assign to are defined by three values similar to parameters of + * the Python function \c range(\c start,\c stop,\c step). + * There are two *modes of usage*: + * - If \a a->getNbOfElems() equals to number of values to assign to, then every value + * of \a a is assigned to its own location within \a this array. + * - If \a a includes one tuple, then all values of \a a are assigned to the specified + * components of every specified tuple of \a this array. In this mode it is required + * that \a a->getNumberOfComponents() equals to the number of specified components. + * + * \param [in] a - the array to copy values from. + * \param [in] bgTuples - pointer to an array of tuple indices of \a this array to + * assign values of \a a to. + * \param [in] endTuples - specifies the end of the array \a bgTuples, so that + * pointer to a tuple index (pi) varies as this: + * \a bgTuples <= \a pi < \a endTuples. + * \param [in] bgComp - index of the first component of \a this array to assign to. + * \param [in] endComp - index of the component before which the components to assign + * to are located. + * \param [in] stepComp - index increment to get index of the next component to assign to. + * \param [in] strictCompoCompare - this parameter is checked only in the first + * *mode of usage*; if \a strictCompoCompare is \a true (default), + * then \a a->getNumberOfComponents() must be equal + * to the number of specified columns, else this is not required. + * \throw If \a a is NULL. + * \throw If \a a is not allocated. + * \throw If \a this is not allocated. + * \throw If any index of tuple given by \a bgTuples is out of a valid range for + * \a this array. + * \throw In the first *mode of usage*, if strictCompoCompare == true and + * if a->getNumberOfComponents() is unequal to the number of components + * defined by (bgComp,endComp,stepComp). + * \throw In the second *mode of usage*, if \a a->getNumberOfTuples() != 1 or + * a->getNumberOfComponents() is unequal to the number of components + * defined by (bgComp,endComp,stepComp). + * \throw If parameters specifying components to assign to, do not give a + * non-empty range of increasing indices or indices are out of a valid range + * for \c this array. + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarraydouble_setpartofvalues3 "Here is a Python example". + * \endif + */ +void DataArrayDouble::setPartOfValues3(const DataArrayDouble *a, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare) +{ + if(!a) + throw INTERP_KERNEL::Exception("DataArrayDouble::setPartOfValues3 : input DataArrayDouble is NULL !"); + const char msg[]="DataArrayDouble::setPartOfValues3"; + checkAllocated(); + a->checkAllocated(); + int newNbOfComp=DataArray::GetNumberOfItemGivenBES(bgComp,endComp,stepComp,msg); + int nbComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + DataArray::CheckValueInRangeEx(nbComp,bgComp,endComp,"invalid component value"); + int newNbOfTuples=(int)std::distance(bgTuples,endTuples); + bool assignTech=true; + if(a->getNbOfElems()==(std::size_t)newNbOfTuples*newNbOfComp) + { + if(strictCompoCompare) + a->checkNbOfTuplesAndComp(newNbOfTuples,newNbOfComp,msg); + } + else + { + a->checkNbOfTuplesAndComp(1,newNbOfComp,msg); + assignTech=false; + } + double *pt=getPointer()+bgComp; + const double *srcPt=a->getConstPointer(); + if(assignTech) + { + for(const int *w=bgTuples;w!=endTuples;w++) + for(int j=0;j(pi) varies as this: + * \a bgTuples <= \a pi < \a endTuples. + * \param [in] bgComp - index of the first component of \a this array to assign to. + * \param [in] endComp - index of the component before which the components to assign + * to are located. + * \param [in] stepComp - index increment to get index of the next component to assign to. + * \throw If \a this is not allocated. + * \throw If any index of tuple given by \a bgTuples is out of a valid range for + * \a this array. + * \throw If parameters specifying components to assign to, do not give a + * non-empty range of increasing indices or indices are out of a valid range + * for \c this array. + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarraydouble_setpartofvaluessimple3 "Here is a Python example". + * \endif + */ +void DataArrayDouble::setPartOfValuesSimple3(double a, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp) +{ + const char msg[]="DataArrayDouble::setPartOfValuesSimple3"; + checkAllocated(); + int newNbOfComp=DataArray::GetNumberOfItemGivenBES(bgComp,endComp,stepComp,msg); + int nbComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + DataArray::CheckValueInRangeEx(nbComp,bgComp,endComp,"invalid component value"); + double *pt=getPointer()+bgComp; + for(const int *w=bgTuples;w!=endTuples;w++) + for(int j=0;jgetNumberOfComponents() + * must be equal to the number of columns to assign to, else an + * exception is thrown; if \a false, then it is only required that \a + * a->getNbOfElems() equals to number of values to assign to (this condition + * must be respected even if \a strictCompoCompare is \a true). The number of + * values to assign to is given by following Python expression: + * \a nbTargetValues = + * \c len(\c range(\a bgTuples,\a endTuples,\a stepTuples)) * + * \c len(\c range(\a bgComp,\a endComp,\a stepComp)). + * \throw If \a a is NULL. + * \throw If \a a is not allocated. + * \throw If \a this is not allocated. + * \throw If parameters specifying tuples and components to assign to do not give a + * non-empty range of increasing indices. + * \throw If \a a->getNbOfElems() != \a nbTargetValues. + * \throw If \a strictCompoCompare == \a true && \a a->getNumberOfComponents() != + * \c len(\c range(\a bgComp,\a endComp,\a stepComp)). + * + */ +void DataArrayDouble::setPartOfValues4(const DataArrayDouble *a, int bgTuples, int endTuples, int stepTuples, const int *bgComp, const int *endComp, bool strictCompoCompare) +{ + if(!a) + throw INTERP_KERNEL::Exception("DataArrayDouble::setPartOfValues4 : input DataArrayDouble is NULL !"); + const char msg[]="DataArrayDouble::setPartOfValues4"; + checkAllocated(); + a->checkAllocated(); + int newNbOfTuples=DataArray::GetNumberOfItemGivenBES(bgTuples,endTuples,stepTuples,msg); + int newNbOfComp=(int)std::distance(bgComp,endComp); + int nbComp=getNumberOfComponents(); + for(const int *z=bgComp;z!=endComp;z++) + DataArray::CheckValueInRange(nbComp,*z,"invalid component id"); + int nbOfTuples=getNumberOfTuples(); + DataArray::CheckValueInRangeEx(nbOfTuples,bgTuples,endTuples,"invalid tuple value"); + bool assignTech=true; + if(a->getNbOfElems()==(std::size_t)newNbOfTuples*newNbOfComp) + { + if(strictCompoCompare) + a->checkNbOfTuplesAndComp(newNbOfTuples,newNbOfComp,msg); + } + else + { + a->checkNbOfTuplesAndComp(1,newNbOfComp,msg); + assignTech=false; + } + const double *srcPt=a->getConstPointer(); + double *pt=getPointer()+bgTuples*nbComp; + if(assignTech) + { + for(int i=0;ithis->getNumberOfComponents() != a->getNumberOfComponents(). + * \throw If \a tuplesSelec->getNumberOfComponents() != 2. + * \throw If any tuple index given by \a tuplesSelec is out of a valid range for + * the corresponding (\a this or \a a) array. + */ +void DataArrayDouble::setPartOfValuesAdv(const DataArrayDouble *a, const DataArrayInt *tuplesSelec) +{ + if(!a || !tuplesSelec) + throw INTERP_KERNEL::Exception("DataArrayDouble::setPartOfValuesAdv : input DataArrayDouble is NULL !"); + checkAllocated(); + a->checkAllocated(); + tuplesSelec->checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=a->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("DataArrayDouble::setPartOfValuesAdv : This and a do not have the same number of components !"); + if(tuplesSelec->getNumberOfComponents()!=2) + throw INTERP_KERNEL::Exception("DataArrayDouble::setPartOfValuesAdv : Expecting to have a tuple selector DataArrayInt instance with exactly 2 components !"); + int thisNt=getNumberOfTuples(); + int aNt=a->getNumberOfTuples(); + double *valsToSet=getPointer(); + const double *valsSrc=a->getConstPointer(); + for(const int *tuple=tuplesSelec->begin();tuple!=tuplesSelec->end();tuple+=2) + { + if(tuple[1]>=0 && tuple[1]=0 && tuple[0]begin(),tuple)/2; + oss << " of 'tuplesSelec' request of tuple id #" << tuple[0] << " in 'this' ! It should be in [0," << thisNt << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + else + { + std::ostringstream oss; oss << "DataArrayDouble::setPartOfValuesAdv : Tuple #" << std::distance(tuplesSelec->begin(),tuple)/2; + oss << " of 'tuplesSelec' request of tuple id #" << tuple[1] << " in 'a' ! It should be in [0," << aNt << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } +} + +/*! + * Copy some tuples from another DataArrayDouble (\a aBase) into contiguous tuples + * of \a this array. Textual data is not copied. Both arrays must have equal number of + * components. + * The tuples to assign to are defined by index of the first tuple, and + * their number is defined by \a tuplesSelec->getNumberOfTuples(). + * The tuples to copy are defined by values of a DataArrayInt. + * All components of selected tuples are copied. + * \param [in] tupleIdStart - index of the first tuple of \a this array to assign + * values to. + * \param [in] aBase - the array to copy values from. + * \param [in] tuplesSelec - the array specifying tuples of \a a to copy. + * \throw If \a this is not allocated. + * \throw If \a aBase is NULL. + * \throw If \a aBase is not allocated. + * \throw If \a tuplesSelec is NULL. + * \throw If \a tuplesSelec is not allocated. + * \throw If this->getNumberOfComponents() != aBase->getNumberOfComponents(). + * \throw If \a tuplesSelec->getNumberOfComponents() != 1. + * \throw If tupleIdStart + tuplesSelec->getNumberOfTuples() > this->getNumberOfTuples(). + * \throw If any tuple index given by \a tuplesSelec is out of a valid range for + * \a aBase array. + */ +void DataArrayDouble::setContigPartOfSelectedValues(int tupleIdStart, const DataArray *aBase, const DataArrayInt *tuplesSelec) +{ + if(!aBase || !tuplesSelec) + throw INTERP_KERNEL::Exception("DataArrayDouble::setContigPartOfSelectedValues : input DataArray is NULL !"); + const DataArrayDouble *a=dynamic_cast(aBase); + if(!a) + throw INTERP_KERNEL::Exception("DataArrayDouble::setContigPartOfSelectedValues : input DataArray aBase is not a DataArrayDouble !"); + checkAllocated(); + a->checkAllocated(); + tuplesSelec->checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=a->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("DataArrayDouble::setContigPartOfSelectedValues : This and a do not have the same number of components !"); + if(tuplesSelec->getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::setContigPartOfSelectedValues : Expecting to have a tuple selector DataArrayInt instance with exactly 1 component !"); + int thisNt=getNumberOfTuples(); + int aNt=a->getNumberOfTuples(); + int nbOfTupleToWrite=tuplesSelec->getNumberOfTuples(); + double *valsToSet=getPointer()+tupleIdStart*nbOfComp; + if(tupleIdStart+nbOfTupleToWrite>thisNt) + throw INTERP_KERNEL::Exception("DataArrayDouble::setContigPartOfSelectedValues : invalid number range of values to write !"); + const double *valsSrc=a->getConstPointer(); + for(const int *tuple=tuplesSelec->begin();tuple!=tuplesSelec->end();tuple++,valsToSet+=nbOfComp) + { + if(*tuple>=0 && *tuplebegin(),tuple); + oss << " of 'tuplesSelec' request of tuple id #" << *tuple << " in 'a' ! It should be in [0," << aNt << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } +} + +/*! + * Copy some tuples from another DataArrayDouble (\a aBase) into contiguous tuples + * of \a this array. Textual data is not copied. Both arrays must have equal number of + * components. + * The tuples to copy are defined by three values similar to parameters of + * the Python function \c range(\c start,\c stop,\c step). + * The tuples to assign to are defined by index of the first tuple, and + * their number is defined by number of tuples to copy. + * All components of selected tuples are copied. + * \param [in] tupleIdStart - index of the first tuple of \a this array to assign + * values to. + * \param [in] aBase - the array to copy values from. + * \param [in] bg - index of the first tuple to copy of the array \a aBase. + * \param [in] end2 - index of the tuple of \a aBase before which the tuples to copy + * are located. + * \param [in] step - index increment to get index of the next tuple to copy. + * \throw If \a this is not allocated. + * \throw If \a aBase is NULL. + * \throw If \a aBase is not allocated. + * \throw If this->getNumberOfComponents() != aBase->getNumberOfComponents(). + * \throw If tupleIdStart + len(range(bg,end2,step)) > this->getNumberOfTuples(). + * \throw If parameters specifying tuples to copy, do not give a + * non-empty range of increasing indices or indices are out of a valid range + * for the array \a aBase. + */ +void DataArrayDouble::setContigPartOfSelectedValues2(int tupleIdStart, const DataArray *aBase, int bg, int end2, int step) +{ + if(!aBase) + throw INTERP_KERNEL::Exception("DataArrayDouble::setContigPartOfSelectedValues2 : input DataArray is NULL !"); + const DataArrayDouble *a=dynamic_cast(aBase); + if(!a) + throw INTERP_KERNEL::Exception("DataArrayDouble::setContigPartOfSelectedValues2 : input DataArray aBase is not a DataArrayDouble !"); + checkAllocated(); + a->checkAllocated(); + int nbOfComp=getNumberOfComponents(); + const char msg[]="DataArrayDouble::setContigPartOfSelectedValues2"; + int nbOfTupleToWrite=DataArray::GetNumberOfItemGivenBES(bg,end2,step,msg); + if(nbOfComp!=a->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("DataArrayDouble::setContigPartOfSelectedValues2 : This and a do not have the same number of components !"); + int thisNt=getNumberOfTuples(); + int aNt=a->getNumberOfTuples(); + double *valsToSet=getPointer()+tupleIdStart*nbOfComp; + if(tupleIdStart+nbOfTupleToWrite>thisNt) + throw INTERP_KERNEL::Exception("DataArrayDouble::setContigPartOfSelectedValues2 : invalid number range of values to write !"); + if(end2>aNt) + throw INTERP_KERNEL::Exception("DataArrayDouble::setContigPartOfSelectedValues2 : invalid range of values to read !"); + const double *valsSrc=a->getConstPointer()+bg*nbOfComp; + for(int i=0;i( 0 <= tupleId < this->getNumberOfTuples() ) is violated. + * \throw If condition ( 0 <= compoId < this->getNumberOfComponents() ) is violated. + */ +double DataArrayDouble::getIJSafe(int tupleId, int compoId) const +{ + checkAllocated(); + if(tupleId<0 || tupleId>=getNumberOfTuples()) + { + std::ostringstream oss; oss << "DataArrayDouble::getIJSafe : request for tupleId " << tupleId << " should be in [0," << getNumberOfTuples() << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if(compoId<0 || compoId>=getNumberOfComponents()) + { + std::ostringstream oss; oss << "DataArrayDouble::getIJSafe : request for compoId " << compoId << " should be in [0," << getNumberOfComponents() << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + return _mem[tupleId*_info_on_compo.size()+compoId]; +} + +/*! + * Returns the first value of \a this. + * \return double - the last value of \a this array. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a this->getNumberOfTuples() < 1. + */ +double DataArrayDouble::front() const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::front : number of components not equal to one !"); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples<1) + throw INTERP_KERNEL::Exception("DataArrayDouble::front : number of tuples must be >= 1 !"); + return *(getConstPointer()); +} + +/*! + * Returns the last value of \a this. + * \return double - the last value of \a this array. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a this->getNumberOfTuples() < 1. + */ +double DataArrayDouble::back() const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::back : number of components not equal to one !"); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples<1) + throw INTERP_KERNEL::Exception("DataArrayDouble::back : number of tuples must be >= 1 !"); + return *(getConstPointer()+nbOfTuples-1); +} + +void DataArrayDouble::SetArrayIn(DataArrayDouble *newArray, DataArrayDouble* &arrayToSet) +{ + if(newArray!=arrayToSet) + { + if(arrayToSet) + arrayToSet->decrRef(); + arrayToSet=newArray; + if(arrayToSet) + arrayToSet->incrRef(); + } +} + +/*! + * Sets a C array to be used as raw data of \a this. The previously set info + * of components is retained and re-sized. + * For more info see \ref MEDCouplingArraySteps1. + * \param [in] array - the C array to be used as raw data of \a this. + * \param [in] ownership - if \a true, \a array will be deallocated at destruction of \a this. + * \param [in] type - specifies how to deallocate \a array. If \a type == ParaMEDMEM::CPP_DEALLOC, + * \c delete [] \c array; will be called. If \a type == ParaMEDMEM::C_DEALLOC, + * \c free(\c array ) will be called. + * \param [in] nbOfTuple - new number of tuples in \a this. + * \param [in] nbOfCompo - new number of components in \a this. + */ +void DataArrayDouble::useArray(const double *array, bool ownership, DeallocType type, int nbOfTuple, int nbOfCompo) +{ + _info_on_compo.resize(nbOfCompo); + _mem.useArray(array,ownership,type,(std::size_t)nbOfTuple*nbOfCompo); + declareAsNew(); +} + +void DataArrayDouble::useExternalArrayWithRWAccess(const double *array, int nbOfTuple, int nbOfCompo) +{ + _info_on_compo.resize(nbOfCompo); + _mem.useExternalArrayWithRWAccess(array,(std::size_t)nbOfTuple*nbOfCompo); + declareAsNew(); +} + +/*! + * Checks if 0.0 value is present in \a this array. If it is the case, an exception + * is thrown. + * \throw If zero is found in \a this array. + */ +void DataArrayDouble::checkNoNullValues() const +{ + const double *tmp=getConstPointer(); + std::size_t nbOfElems=getNbOfElems(); + const double *where=std::find(tmp,tmp+nbOfElems,0.); + if(where!=tmp+nbOfElems) + throw INTERP_KERNEL::Exception("A value 0.0 have been detected !"); +} + +/*! + * Computes minimal and maximal value in each component. An output array is filled + * with \c 2 * \a this->getNumberOfComponents() values, so the caller is to allocate + * enough memory before calling this method. + * \param [out] bounds - array of size at least 2 *\a this->getNumberOfComponents(). + * It is filled as follows:
+ * \a bounds[0] = \c min_of_component_0
+ * \a bounds[1] = \c max_of_component_0
+ * \a bounds[2] = \c min_of_component_1
+ * \a bounds[3] = \c max_of_component_1
+ * ... + */ +void DataArrayDouble::getMinMaxPerComponent(double *bounds) const +{ + checkAllocated(); + int dim=getNumberOfComponents(); + for (int idim=0; idim::max(); + bounds[idim*2+1]=-std::numeric_limits::max(); + } + const double *ptr=getConstPointer(); + int nbOfTuples=getNumberOfTuples(); + for(int i=0;iptr[i*dim+idim]) + { + bounds[idim*2]=ptr[i*dim+idim]; + } + if(bounds[idim*2+1]getNumberOfTuples() tuples and 2 * \c this->getNumberOfComponent() components + * + * \throw If \a this is not allocated yet. + */ +DataArrayDouble *DataArrayDouble::computeBBoxPerTuple(double epsilon) const +{ + checkAllocated(); + const double *dataPtr=getConstPointer(); + int nbOfCompo=getNumberOfComponents(); + int nbTuples=getNumberOfTuples(); + MEDCouplingAutoRefCountObjectPtr bbox=DataArrayDouble::New(); + bbox->alloc(nbTuples,2*nbOfCompo); + double *bboxPtr=bbox->getPointer(); + for(int i=0;icheckAllocated(); + int nbOfCompo=getNumberOfComponents(); + int otherNbOfCompo=other->getNumberOfComponents(); + if(nbOfCompo!=otherNbOfCompo) + throw INTERP_KERNEL::Exception("DataArrayDouble::computeTupleIdsNearTuples : number of components should be equal between this and other !"); + int nbOfTuplesOther=other->getNumberOfTuples(); + MEDCouplingAutoRefCountObjectPtr cArr(DataArrayInt::New()),cIArr(DataArrayInt::New()); cArr->alloc(0,1); cIArr->pushBackSilent(0); + switch(nbOfCompo) + { + case 3: + { + BBTreePts<3,int> myTree(begin(),0,0,getNumberOfTuples(),eps); + FindTupleIdsNearTuplesAlg<3>(myTree,other->getConstPointer(),nbOfTuplesOther,eps,cArr,cIArr); + break; + } + case 2: + { + BBTreePts<2,int> myTree(begin(),0,0,getNumberOfTuples(),eps); + FindTupleIdsNearTuplesAlg<2>(myTree,other->getConstPointer(),nbOfTuplesOther,eps,cArr,cIArr); + break; + } + case 1: + { + BBTreePts<1,int> myTree(begin(),0,0,getNumberOfTuples(),eps); + FindTupleIdsNearTuplesAlg<1>(myTree,other->getConstPointer(),nbOfTuplesOther,eps,cArr,cIArr); + break; + } + default: + throw INTERP_KERNEL::Exception("Unexpected spacedim of coords for computeTupleIdsNearTuples. Must be 1, 2 or 3."); + } + c=cArr.retn(); cI=cIArr.retn(); +} + +/*! + * This method recenter tuples in \b this in order to be centered at the origin to benefit about the advantages of maximal precision to be around the box + * around origin of 'radius' 1. + * + * \param [in] eps absolute epsilon. under that value of delta between max and min no scale is performed. + */ +void DataArrayDouble::recenterForMaxPrecision(double eps) +{ + checkAllocated(); + int dim=getNumberOfComponents(); + std::vector bounds(2*dim); + getMinMaxPerComponent(&bounds[0]); + for(int i=0;ieps) + applyLin(1./delta,-offset/delta,i); + else + applyLin(1.,-offset,i); + } +} + +/*! + * Returns the maximal value and its location within \a this one-dimensional array. + * \param [out] tupleId - index of the tuple holding the maximal value. + * \return double - the maximal value among all values of \a this array. + * \throw If \a this->getNumberOfComponents() != 1 + * \throw If \a this->getNumberOfTuples() < 1 + */ +double DataArrayDouble::getMaxValue(int& tupleId) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::getMaxValue : must be applied on DataArrayDouble with only one component, you can call 'rearrange' method before or call 'getMaxValueInArray' method !"); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples<=0) + throw INTERP_KERNEL::Exception("DataArrayDouble::getMaxValue : array exists but number of tuples must be > 0 !"); + const double *vals=getConstPointer(); + const double *loc=std::max_element(vals,vals+nbOfTuples); + tupleId=(int)std::distance(vals,loc); + return *loc; +} + +/*! + * Returns the maximal value within \a this array that is allowed to have more than + * one component. + * \return double - the maximal value among all values of \a this array. + * \throw If \a this is not allocated. + */ +double DataArrayDouble::getMaxValueInArray() const +{ + checkAllocated(); + const double *loc=std::max_element(begin(),end()); + return *loc; +} + +/*! + * Returns the maximal value and all its locations within \a this one-dimensional array. + * \param [out] tupleIds - a new instance of DataArrayInt containg indices of + * tuples holding the maximal value. The caller is to delete it using + * decrRef() as it is no more needed. + * \return double - the maximal value among all values of \a this array. + * \throw If \a this->getNumberOfComponents() != 1 + * \throw If \a this->getNumberOfTuples() < 1 + */ +double DataArrayDouble::getMaxValue2(DataArrayInt*& tupleIds) const +{ + int tmp; + tupleIds=0; + double ret=getMaxValue(tmp); + tupleIds=getIdsInRange(ret,ret); + return ret; +} + +/*! + * Returns the minimal value and its location within \a this one-dimensional array. + * \param [out] tupleId - index of the tuple holding the minimal value. + * \return double - the minimal value among all values of \a this array. + * \throw If \a this->getNumberOfComponents() != 1 + * \throw If \a this->getNumberOfTuples() < 1 + */ +double DataArrayDouble::getMinValue(int& tupleId) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::getMinValue : must be applied on DataArrayDouble with only one component, you can call 'rearrange' method before call 'getMinValueInArray' method !"); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples<=0) + throw INTERP_KERNEL::Exception("DataArrayDouble::getMinValue : array exists but number of tuples must be > 0 !"); + const double *vals=getConstPointer(); + const double *loc=std::min_element(vals,vals+nbOfTuples); + tupleId=(int)std::distance(vals,loc); + return *loc; +} + +/*! + * Returns the minimal value within \a this array that is allowed to have more than + * one component. + * \return double - the minimal value among all values of \a this array. + * \throw If \a this is not allocated. + */ +double DataArrayDouble::getMinValueInArray() const +{ + checkAllocated(); + const double *loc=std::min_element(begin(),end()); + return *loc; +} + +/*! + * Returns the minimal value and all its locations within \a this one-dimensional array. + * \param [out] tupleIds - a new instance of DataArrayInt containg indices of + * tuples holding the minimal value. The caller is to delete it using + * decrRef() as it is no more needed. + * \return double - the minimal value among all values of \a this array. + * \throw If \a this->getNumberOfComponents() != 1 + * \throw If \a this->getNumberOfTuples() < 1 + */ +double DataArrayDouble::getMinValue2(DataArrayInt*& tupleIds) const +{ + int tmp; + tupleIds=0; + double ret=getMinValue(tmp); + tupleIds=getIdsInRange(ret,ret); + return ret; +} + +/*! + * This method returns the number of values in \a this that are equals ( within an absolute precision of \a eps ) to input parameter \a value. + * This method only works for single component array. + * + * \return a value in [ 0, \c this->getNumberOfTuples() ) + * + * \throw If \a this is not allocated + * + */ +int DataArrayDouble::count(double value, double eps) const +{ + int ret=0; + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::count : must be applied on DataArrayDouble with only one component, you can call 'rearrange' method before !"); + const double *vals=begin(); + int nbOfTuples=getNumberOfTuples(); + for(int i=0;igetNumberOfComponents() != 1 + * \throw If \a this->getNumberOfTuples() < 1 + */ +double DataArrayDouble::getAverageValue() const +{ + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::getAverageValue : must be applied on DataArrayDouble with only one component, you can call 'rearrange' method before !"); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples<=0) + throw INTERP_KERNEL::Exception("DataArrayDouble::getAverageValue : array exists but number of tuples must be > 0 !"); + const double *vals=getConstPointer(); + double ret=std::accumulate(vals,vals+nbOfTuples,0.); + return ret/nbOfTuples; +} + +/*! + * Returns the Euclidean norm of the vector defined by \a this array. + * \return double - the value of the Euclidean norm, i.e. + * the square root of the inner product of vector. + * \throw If \a this is not allocated. + */ +double DataArrayDouble::norm2() const +{ + checkAllocated(); + double ret=0.; + std::size_t nbOfElems=getNbOfElems(); + const double *pt=getConstPointer(); + for(std::size_t i=0;iret) + ret=val; + } + return ret; +} + +/*! + * Returns the minimum norm (absolute value) of the vector defined by \a this array. + * This method works even if the number of components is diferent from one. + * If the number of elements in \a this is 0, std::numeric_limits::max() is returned. + * \return double - the value of the minimum norm, i.e. + * the minimal absolute value among values of \a this array (whatever its number of components). + * \throw If \a this is not allocated. + */ +double DataArrayDouble::normMin() const +{ + checkAllocated(); + double ret(std::numeric_limits::max()); + std::size_t nbOfElems(getNbOfElems()); + const double *pt(getConstPointer()); + for(std::size_t i=0;igetNumberOfComponents(), allocated + * by the caller, that is filled by this method with sum value for each + * component. + * \throw If \a this is not allocated. + */ +void DataArrayDouble::accumulate(double *res) const +{ + checkAllocated(); + const double *ptr=getConstPointer(); + int nbTuple=getNumberOfTuples(); + int nbComps=getNumberOfComponents(); + std::fill(res,res+nbComps,0.); + for(int i=0;i()); +} + +/*! + * This method returns the min distance from an external tuple defined by [ \a tupleBg , \a tupleEnd ) to \a this and + * the first tuple in \a this that matches the returned distance. If there is no tuples in \a this an exception will be thrown. + * + * + * \a this is expected to be allocated and expected to have a number of components equal to the distance from \a tupleBg to + * \a tupleEnd. If not an exception will be thrown. + * + * \param [in] tupleBg start pointer (included) of input external tuple + * \param [in] tupleEnd end pointer (not included) of input external tuple + * \param [out] tupleId the tuple id in \a this that matches the min of distance between \a this and input external tuple + * \return the min distance. + * \sa MEDCouplingUMesh::distanceToPoint + */ +double DataArrayDouble::distanceToTuple(const double *tupleBg, const double *tupleEnd, int& tupleId) const +{ + checkAllocated(); + int nbTuple=getNumberOfTuples(); + int nbComps=getNumberOfComponents(); + if(nbComps!=(int)std::distance(tupleBg,tupleEnd)) + { std::ostringstream oss; oss << "DataArrayDouble::distanceToTuple : size of input tuple is " << std::distance(tupleBg,tupleEnd) << " should be equal to the number of components in this : " << nbComps << " !"; throw INTERP_KERNEL::Exception(oss.str().c_str()); } + if(nbTuple==0) + throw INTERP_KERNEL::Exception("DataArrayDouble::distanceToTuple : no tuple in this ! No distance to compute !"); + double ret0=std::numeric_limits::max(); + tupleId=-1; + const double *work=getConstPointer(); + for(int i=0;i=ret0) + continue; + else + { ret0=val; tupleId=i; } + } + return sqrt(ret0); +} + +/*! + * Accumulate values of the given component of \a this array. + * \param [in] compId - the index of the component of interest. + * \return double - a sum value of \a compId-th component. + * \throw If \a this is not allocated. + * \throw If \a the condition ( 0 <= \a compId < \a this->getNumberOfComponents() ) is + * not respected. + */ +double DataArrayDouble::accumulate(int compId) const +{ + checkAllocated(); + const double *ptr=getConstPointer(); + int nbTuple=getNumberOfTuples(); + int nbComps=getNumberOfComponents(); + if(compId<0 || compId>=nbComps) + throw INTERP_KERNEL::Exception("DataArrayDouble::accumulate : Invalid compId specified : No such nb of components !"); + double ret=0.; + for(int i=0;igetNumberOfTuples). + * This method is quite useful for users that need to put a field on cells to field on nodes on the same mesh without a need of conservation. + * + * \param [in] bgOfIndex - begin (included) of the input index array. + * \param [in] endOfIndex - end (excluded) of the input index array. + * \return DataArrayDouble * - the new instance having the same number of components than \a this. + * + * \throw If bgOfIndex or end is NULL. + * \throw If input index array is not ascendingly sorted. + * \throw If there is an id in [ \a bgOfIndex, \a endOfIndex ) not in [0, \c this->getNumberOfTuples). + * \throw If std::distance(bgOfIndex,endOfIndex)==0. + */ +DataArrayDouble *DataArrayDouble::accumulatePerChunck(const int *bgOfIndex, const int *endOfIndex) const +{ + if(!bgOfIndex || !endOfIndex) + throw INTERP_KERNEL::Exception("DataArrayDouble::accumulatePerChunck : input pointer NULL !"); + checkAllocated(); + int nbCompo=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + int sz=(int)std::distance(bgOfIndex,endOfIndex); + if(sz<1) + throw INTERP_KERNEL::Exception("DataArrayDouble::accumulatePerChunck : invalid size of input index array !"); + sz--; + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); ret->alloc(sz,nbCompo); + const int *w=bgOfIndex; + if(*w<0 || *w>=nbOfTuples) + throw INTERP_KERNEL::Exception("DataArrayDouble::accumulatePerChunck : The first element of the input index not in [0,nbOfTuples) !"); + const double *srcPt=begin()+(*w)*nbCompo; + double *tmp=ret->getPointer(); + for(int i=0;i=w[0]) + { + for(int j=w[0];j=0 && j()); + else + { + std::ostringstream oss; oss << "DataArrayDouble::accumulatePerChunck : At rank #" << i << " the input index array points to id " << j << " should be in [0," << nbOfTuples << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + } + else + { + std::ostringstream oss; oss << "DataArrayDouble::accumulatePerChunck : At rank #" << i << " the input index array is not in ascendingly sorted."; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + ret->copyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Converts each 2D point defined by the tuple of \a this array from the Polar to the + * Cartesian coordinate system. The two components of the tuple of \a this array are + * considered to contain (1) radius and (2) angle of the point in the Polar CS. + * \return DataArrayDouble * - the new instance of DataArrayDouble, whose each tuple + * contains X and Y coordinates of the point in the Cartesian CS. The caller + * is to delete this array using decrRef() as it is no more needed. The array + * does not contain any textual info on components. + * \throw If \a this->getNumberOfComponents() != 2. + */ +DataArrayDouble *DataArrayDouble::fromPolarToCart() const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=2) + throw INTERP_KERNEL::Exception("DataArrayDouble::fromPolarToCart : must be an array with exactly 2 components !"); + int nbOfTuple=getNumberOfTuples(); + DataArrayDouble *ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple,2); + double *w=ret->getPointer(); + const double *wIn=getConstPointer(); + for(int i=0;igetNumberOfComponents() != 3. + */ +DataArrayDouble *DataArrayDouble::fromCylToCart() const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=3) + throw INTERP_KERNEL::Exception("DataArrayDouble::fromCylToCart : must be an array with exactly 3 components !"); + int nbOfTuple=getNumberOfTuples(); + DataArrayDouble *ret=DataArrayDouble::New(); + ret->alloc(getNumberOfTuples(),3); + double *w=ret->getPointer(); + const double *wIn=getConstPointer(); + for(int i=0;isetInfoOnComponent(2,getInfoOnComponent(2)); + return ret; +} + +/*! + * Converts each 3D point defined by the tuple of \a this array from the Spherical to + * the Cartesian coordinate system. The three components of the tuple of \a this array + * are considered to contain (1) radius, (2) polar angle and (3) azimuthal angle of the + * point in the Cylindrical CS. + * \return DataArrayDouble * - the new instance of DataArrayDouble, whose each tuple + * contains X, Y and Z coordinates of the point in the Cartesian CS. The info + * on the third component is copied from \a this array. The caller + * is to delete this array using decrRef() as it is no more needed. + * \throw If \a this->getNumberOfComponents() != 3. + */ +DataArrayDouble *DataArrayDouble::fromSpherToCart() const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=3) + throw INTERP_KERNEL::Exception("DataArrayDouble::fromSpherToCart : must be an array with exactly 3 components !"); + int nbOfTuple=getNumberOfTuples(); + DataArrayDouble *ret=DataArrayDouble::New(); + ret->alloc(getNumberOfTuples(),3); + double *w=ret->getPointer(); + const double *wIn=getConstPointer(); + for(int i=0;i(t) of \a this array as follows: + * \f$ t[0]^2+t[1]^2+t[2]^2+2*t[3]^2+2*t[4]^2+2*t[5]^2\f$. + * The caller is to delete this result array using decrRef() as it is no more needed. + * \throw If \a this->getNumberOfComponents() != 6. + */ +DataArrayDouble *DataArrayDouble::doublyContractedProduct() const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=6) + throw INTERP_KERNEL::Exception("DataArrayDouble::doublyContractedProduct : must be an array with exactly 6 components !"); + DataArrayDouble *ret=DataArrayDouble::New(); + int nbOfTuple=getNumberOfTuples(); + ret->alloc(nbOfTuple,1); + const double *src=getConstPointer(); + double *dest=ret->getPointer(); + for(int i=0;igetNumberOfComponents() is not in [4,6,9]. + */ +DataArrayDouble *DataArrayDouble::determinant() const +{ + checkAllocated(); + DataArrayDouble *ret=DataArrayDouble::New(); + int nbOfTuple=getNumberOfTuples(); + ret->alloc(nbOfTuple,1); + const double *src=getConstPointer(); + double *dest=ret->getPointer(); + switch(getNumberOfComponents()) + { + case 6: + for(int i=0;idecrRef(); + throw INTERP_KERNEL::Exception("DataArrayDouble::determinant : Invalid number of components ! must be in 4,6,9 !"); + } +} + +/*! + * Computes 3 eigenvalues of every upper triangular matrix defined by the tuple of + * \a this array, which contains 6 components. + * \return DataArrayDouble * - the new instance of DataArrayDouble containing 3 + * components, whose each tuple contains the eigenvalues of the matrix of + * corresponding tuple of \a this array. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If \a this->getNumberOfComponents() != 6. + */ +DataArrayDouble *DataArrayDouble::eigenValues() const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=6) + throw INTERP_KERNEL::Exception("DataArrayDouble::eigenValues : must be an array with exactly 6 components !"); + DataArrayDouble *ret=DataArrayDouble::New(); + int nbOfTuple=getNumberOfTuples(); + ret->alloc(nbOfTuple,3); + const double *src=getConstPointer(); + double *dest=ret->getPointer(); + for(int i=0;igetNumberOfComponents() != 6. + */ +DataArrayDouble *DataArrayDouble::eigenVectors() const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=6) + throw INTERP_KERNEL::Exception("DataArrayDouble::eigenVectors : must be an array with exactly 6 components !"); + DataArrayDouble *ret=DataArrayDouble::New(); + int nbOfTuple=getNumberOfTuples(); + ret->alloc(nbOfTuple,9); + const double *src=getConstPointer(); + double *dest=ret->getPointer(); + for(int i=0;igetNumberOfComponents() is not in [4,6,9]. + */ +DataArrayDouble *DataArrayDouble::inverse() const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=6 && nbOfComp!=9 && nbOfComp!=4) + throw INTERP_KERNEL::Exception("DataArrayDouble::inversion : must be an array with 4,6 or 9 components !"); + DataArrayDouble *ret=DataArrayDouble::New(); + int nbOfTuple=getNumberOfTuples(); + ret->alloc(nbOfTuple,nbOfComp); + const double *src=getConstPointer(); + double *dest=ret->getPointer(); + if(nbOfComp==6) + for(int i=0;igetNumberOfComponents() is not in [4,6,9]. + */ +DataArrayDouble *DataArrayDouble::trace() const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=6 && nbOfComp!=9 && nbOfComp!=4) + throw INTERP_KERNEL::Exception("DataArrayDouble::trace : must be an array with 4,6 or 9 components !"); + DataArrayDouble *ret=DataArrayDouble::New(); + int nbOfTuple=getNumberOfTuples(); + ret->alloc(nbOfTuple,1); + const double *src=getConstPointer(); + double *dest=ret->getPointer(); + if(nbOfComp==6) + for(int i=0;igetNumberOfComponents() != 6. + */ +DataArrayDouble *DataArrayDouble::deviator() const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=6) + throw INTERP_KERNEL::Exception("DataArrayDouble::deviator : must be an array with exactly 6 components !"); + DataArrayDouble *ret=DataArrayDouble::New(); + int nbOfTuple=getNumberOfTuples(); + ret->alloc(nbOfTuple,6); + const double *src=getConstPointer(); + double *dest=ret->getPointer(); + for(int i=0;ialloc(nbOfTuple,1); + const double *src=getConstPointer(); + double *dest=ret->getPointer(); + for(int i=0;i ret(DataArrayDouble::New()); + ret->alloc(nbOfTuple,1); + const double *src(getConstPointer()); + double *dest(ret->getPointer()); + for(int i=0;i ret=DataArrayDouble::New(); + int nbOfTuple=getNumberOfTuples(); + ret->alloc(nbOfTuple,1); + const double *src=getConstPointer(); + double *dest=ret->getPointer(); + for(int i=0;i ret0=DataArrayDouble::New(); + MEDCouplingAutoRefCountObjectPtr ret1=DataArrayInt::New(); + int nbOfTuple=getNumberOfTuples(); + ret0->alloc(nbOfTuple,1); ret1->alloc(nbOfTuple,1); + const double *src=getConstPointer(); + double *dest=ret0->getPointer(); int *dest1=ret1->getPointer(); + for(int i=0;igetNumberOfTuples() * \c this->getNumberOfTuples() tuples. + * \n This returned array contains the euclidian distance for each tuple in \a this. + * \n So the returned array can be seen as a dense symmetrical matrix whose diagonal elements are equal to 0. + * \n The returned array has only one component (and **not** \c this->getNumberOfTuples() components to avoid the useless memory consumption due to components info in returned DataArrayDouble) + * + * \warning use this method with care because it can leads to big amount of consumed memory ! + * + * \return A newly allocated (huge) ParaMEDMEM::DataArrayDouble instance that the caller should deal with. + * + * \throw If \a this is not allocated. + * + * \sa DataArrayDouble::buildEuclidianDistanceDenseMatrixWith + */ +DataArrayDouble *DataArrayDouble::buildEuclidianDistanceDenseMatrix() const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + const double *inData=getConstPointer(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(nbOfTuples*nbOfTuples,1); + double *outData=ret->getPointer(); + for(int i=0;igetNumberOfTuples() * \c other->getNumberOfTuples() tuples. + * \n This returned array contains the euclidian distance for each tuple in \a other with each tuple in \a this. + * \n So the returned array can be seen as a dense rectangular matrix with \c other->getNumberOfTuples() rows and \c this->getNumberOfTuples() columns. + * \n Output rectangular matrix is sorted along rows. + * \n The returned array has only one component (and **not** \c this->getNumberOfTuples() components to avoid the useless memory consumption due to components info in returned DataArrayDouble) + * + * \warning use this method with care because it can leads to big amount of consumed memory ! + * + * \param [in] other DataArrayDouble instance having same number of components than \a this. + * \return A newly allocated (huge) ParaMEDMEM::DataArrayDouble instance that the caller should deal with. + * + * \throw If \a this is not allocated, or if \a other is null or if \a other is not allocated, or if number of components of \a other and \a this differs. + * + * \sa DataArrayDouble::buildEuclidianDistanceDenseMatrix + */ +DataArrayDouble *DataArrayDouble::buildEuclidianDistanceDenseMatrixWith(const DataArrayDouble *other) const +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayDouble::buildEuclidianDistanceDenseMatrixWith : input parameter is null !"); + checkAllocated(); + other->checkAllocated(); + int nbOfComp=getNumberOfComponents(); + int otherNbOfComp=other->getNumberOfComponents(); + if(nbOfComp!=otherNbOfComp) + { + std::ostringstream oss; oss << "DataArrayDouble::buildEuclidianDistanceDenseMatrixWith : this nb of compo=" << nbOfComp << " and other nb of compo=" << otherNbOfComp << ". It should match !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + int nbOfTuples=getNumberOfTuples(); + int otherNbOfTuples=other->getNumberOfTuples(); + const double *inData=getConstPointer(); + const double *inDataOther=other->getConstPointer(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(otherNbOfTuples*nbOfTuples,1); + double *outData=ret->getPointer(); + for(int i=0;i()); + declareAsNew(); +} + +/*! + * Converts every value of \a this array to its absolute value. + * \b WARNING this method is non const. If a new DataArrayDouble instance should be built containing the result of abs DataArrayDouble::computeAbs + * should be called instead. + * + * \throw If \a this is not allocated. + * \sa DataArrayDouble::computeAbs + */ +void DataArrayDouble::abs() +{ + checkAllocated(); + double *ptr(getPointer()); + std::size_t nbOfElems(getNbOfElems()); + std::transform(ptr,ptr+nbOfElems,ptr,std::ptr_fun(fabs)); + declareAsNew(); +} + +/*! + * This method builds a new instance of \a this object containing the result of std::abs applied of all elements in \a this. + * This method is a const method (that do not change any values in \a this) contrary to DataArrayDouble::abs method. + * + * \return DataArrayDouble * - the new instance of DataArrayDouble containing the + * same number of tuples and component as \a this array. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If \a this is not allocated. + * \sa DataArrayDouble::abs + */ +DataArrayDouble *DataArrayDouble::computeAbs() const +{ + checkAllocated(); + DataArrayDouble *newArr(DataArrayDouble::New()); + int nbOfTuples(getNumberOfTuples()); + int nbOfComp(getNumberOfComponents()); + newArr->alloc(nbOfTuples,nbOfComp); + std::transform(begin(),end(),newArr->getPointer(),std::ptr_fun(fabs)); + newArr->copyStringInfoFrom(*this); + return newArr; +} + +/*! + * Apply a linear function to a given component of \a this array, so that + * an array element (x) becomes \f$ a * x + b \f$. + * \param [in] a - the first coefficient of the function. + * \param [in] b - the second coefficient of the function. + * \param [in] compoId - the index of component to modify. + * \throw If \a this is not allocated, or \a compoId is not in [0,\c this->getNumberOfComponents() ). + */ +void DataArrayDouble::applyLin(double a, double b, int compoId) +{ + checkAllocated(); + double *ptr(getPointer()+compoId); + int nbOfComp(getNumberOfComponents()),nbOfTuple(getNumberOfTuples()); + if(compoId<0 || compoId>=nbOfComp) + { + std::ostringstream oss; oss << "DataArrayDouble::applyLin : The compoId requested (" << compoId << ") is not valid ! Must be in [0," << nbOfComp << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + for(int i=0;istd::numeric_limits::min()) + { + *ptr=numerator/(*ptr); + } + else + { + std::ostringstream oss; oss << "DataArrayDouble::applyInv : presence of null value in tuple #" << i/getNumberOfComponents() << " component #" << i%getNumberOfComponents(); + oss << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + declareAsNew(); +} + +/*! + * Returns a full copy of \a this array except that sign of all elements is reversed. + * \return DataArrayDouble * - the new instance of DataArrayDouble containing the + * same number of tuples and component as \a this array. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If \a this is not allocated. + */ +DataArrayDouble *DataArrayDouble::negate() const +{ + checkAllocated(); + DataArrayDouble *newArr=DataArrayDouble::New(); + int nbOfTuples=getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + newArr->alloc(nbOfTuples,nbOfComp); + const double *cptr=getConstPointer(); + std::transform(cptr,cptr+nbOfTuples*nbOfComp,newArr->getPointer(),std::negate()); + newArr->copyStringInfoFrom(*this); + return newArr; +} + +/*! + * Modify all elements of \a this array, so that + * an element _x_ becomes val ^ x . Contrary to DataArrayInt::applyPow + * all values in \a this have to be >= 0 if val is \b not integer. + * \param [in] val - the value used to apply pow on all array elements. + * \throw If \a this is not allocated. + * \warning If an exception is thrown because of presence of 0 element in \a this + * array and \a val is \b not integer, all elements processed before detection of the zero element remain + * modified. + */ +void DataArrayDouble::applyPow(double val) +{ + checkAllocated(); + double *ptr=getPointer(); + std::size_t nbOfElems=getNbOfElems(); + int val2=(int)val; + bool isInt=((double)val2)==val; + if(!isInt) + { + for(std::size_t i=0;i=0) + *ptr=pow(*ptr,val); + else + { + std::ostringstream oss; oss << "DataArrayDouble::applyPow (double) : At elem # " << i << " value is " << *ptr << " ! must be >=0. !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + } + else + { + for(std::size_t i=0;i= 0 !"); + double *ptr=getPointer(); + std::size_t nbOfElems=getNbOfElems(); + for(std::size_t i=0;ialloc(nbOfTuples,nbOfComp); + const double *ptr=getConstPointer(); + double *ptrToFill=newArr->getPointer(); + for(int i=0;i(oss,", ")); + oss << ") : Evaluation of function failed !"; + newArr->decrRef(); + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + return newArr; +} + +/*! + * Returns a new DataArrayDouble created from \a this one by applying a function to every + * tuple of \a this array. Textual data is not copied. + * For more info see \ref MEDCouplingArrayApplyFunc1. + * \param [in] nbOfComp - number of components in the result array. + * \param [in] func - the expression defining how to transform a tuple of \a this array. + * Supported expressions are described \ref MEDCouplingArrayApplyFuncExpr "here". + * \param [in] isSafe - By default true. If true invalid operation (division by 0. acos of value > 1. ...) leads to a throw of an exception. + * If false the computation is carried on without any notification. When false the evaluation is a little faster. + * \return DataArrayDouble * - the new instance of DataArrayDouble containing the + * same number of tuples as \a this array and \a nbOfComp components. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If \a this is not allocated. + * \throw If computing \a func fails. + */ +DataArrayDouble *DataArrayDouble::applyFunc(int nbOfComp, const std::string& func, bool isSafe) const +{ + INTERP_KERNEL::ExprParser expr(func); + expr.parse(); + std::set vars; + expr.getTrueSetOfVars(vars); + std::vector varsV(vars.begin(),vars.end()); + return applyFunc3(nbOfComp,varsV,func,isSafe); +} + +/*! + * Returns a new DataArrayDouble created from \a this one by applying a function to every + * tuple of \a this array. Textual data is not copied. This method works by tuples (whatever its size). + * If \a this is a one component array, call applyFuncOnThis instead that performs the same work faster. + * + * For more info see \ref MEDCouplingArrayApplyFunc0. + * \param [in] func - the expression defining how to transform a tuple of \a this array. + * Supported expressions are described \ref MEDCouplingArrayApplyFuncExpr "here". + * \param [in] isSafe - By default true. If true invalid operation (division by 0. acos of value > 1. ...) leads to a throw of an exception. + * If false the computation is carried on without any notification. When false the evaluation is a little faster. + * \return DataArrayDouble * - the new instance of DataArrayDouble containing the + * same number of tuples and components as \a this array. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \sa applyFuncOnThis + * \throw If \a this is not allocated. + * \throw If computing \a func fails. + */ +DataArrayDouble *DataArrayDouble::applyFunc(const std::string& func, bool isSafe) const +{ + int nbOfComp(getNumberOfComponents()); + if(nbOfComp<=0) + throw INTERP_KERNEL::Exception("DataArrayDouble::applyFunc : output number of component must be > 0 !"); + checkAllocated(); + int nbOfTuples(getNumberOfTuples()); + MEDCouplingAutoRefCountObjectPtr newArr(DataArrayDouble::New()); + newArr->alloc(nbOfTuples,nbOfComp); + INTERP_KERNEL::ExprParser expr(func); + expr.parse(); + std::set vars; + expr.getTrueSetOfVars(vars); + if((int)vars.size()>1) + { + std::ostringstream oss; oss << "DataArrayDouble::applyFunc : this method works only with at most one var func expression ! If you need to map comps on variables please use applyFunc2 or applyFunc3 instead ! Vars in expr are : "; + std::copy(vars.begin(),vars.end(),std::ostream_iterator(oss," ")); + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if(vars.empty()) + { + expr.prepareFastEvaluator(); + newArr->rearrange(1); + newArr->fillWithValue(expr.evaluateDouble()); + newArr->rearrange(nbOfComp); + return newArr.retn(); + } + std::vector vars2(vars.begin(),vars.end()); + double buff,*ptrToFill(newArr->getPointer()); + const double *ptr(begin()); + std::vector stck; + expr.prepareExprEvaluationDouble(vars2,1,1,0,&buff,&buff+1); + expr.prepareFastEvaluator(); + if(!isSafe) + { + for(int i=0;i 1. ...) leads to a throw of an exception. + * If false the computation is carried on without any notification. When false the evaluation is a little faster. + * + * \sa applyFunc + */ +void DataArrayDouble::applyFuncOnThis(const std::string& func, bool isSafe) +{ + int nbOfComp(getNumberOfComponents()); + if(nbOfComp<=0) + throw INTERP_KERNEL::Exception("DataArrayDouble::applyFuncOnThis : output number of component must be > 0 !"); + checkAllocated(); + int nbOfTuples(getNumberOfTuples()); + INTERP_KERNEL::ExprParser expr(func); + expr.parse(); + std::set vars; + expr.getTrueSetOfVars(vars); + if((int)vars.size()>1) + { + std::ostringstream oss; oss << "DataArrayDouble::applyFuncOnThis : this method works only with at most one var func expression ! If you need to map comps on variables please use applyFunc2 or applyFunc3 instead ! Vars in expr are : "; + std::copy(vars.begin(),vars.end(),std::ostream_iterator(oss," ")); + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if(vars.empty()) + { + expr.prepareFastEvaluator(); + std::vector compInfo(getInfoOnComponents()); + rearrange(1); + fillWithValue(expr.evaluateDouble()); + rearrange(nbOfComp); + setInfoOnComponents(compInfo); + return ; + } + std::vector vars2(vars.begin(),vars.end()); + double buff,*ptrToFill(getPointer()); + const double *ptr(begin()); + std::vector stck; + expr.prepareExprEvaluationDouble(vars2,1,1,0,&buff,&buff+1); + expr.prepareFastEvaluator(); + if(!isSafe) + { + for(int i=0;i 1. ...) leads to a throw of an exception. + * If false the computation is carried on without any notification. When false the evaluation is a little faster. + * \return DataArrayDouble * - the new instance of DataArrayDouble containing the + * same number of tuples as \a this array. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If \a this is not allocated. + * \throw If \a func contains vars that are not in \a this->getInfoOnComponent(). + * \throw If computing \a func fails. + */ +DataArrayDouble *DataArrayDouble::applyFunc2(int nbOfComp, const std::string& func, bool isSafe) const +{ + return applyFunc3(nbOfComp,getVarsOnComponent(),func,isSafe); +} + +/*! + * Returns a new DataArrayDouble created from \a this one by applying a function to every + * tuple of \a this array. Textual data is not copied. + * For more info see \ref MEDCouplingArrayApplyFunc3. + * \param [in] nbOfComp - number of components in the result array. + * \param [in] varsOrder - sequence of vars defining their order. + * \param [in] func - the expression defining how to transform a tuple of \a this array. + * Supported expressions are described \ref MEDCouplingArrayApplyFuncExpr "here". + * \param [in] isSafe - By default true. If true invalid operation (division by 0. acos of value > 1. ...) leads to a throw of an exception. + * If false the computation is carried on without any notification. When false the evaluation is a little faster. + * \return DataArrayDouble * - the new instance of DataArrayDouble containing the + * same number of tuples as \a this array. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If \a this is not allocated. + * \throw If \a func contains vars not in \a varsOrder. + * \throw If computing \a func fails. + */ +DataArrayDouble *DataArrayDouble::applyFunc3(int nbOfComp, const std::vector& varsOrder, const std::string& func, bool isSafe) const +{ + if(nbOfComp<=0) + throw INTERP_KERNEL::Exception("DataArrayDouble::applyFunc3 : output number of component must be > 0 !"); + std::vector varsOrder2(varsOrder); + int oldNbOfComp(getNumberOfComponents()); + for(int i=(int)varsOrder.size();i vars; + expr.getTrueSetOfVars(vars); + if((int)vars.size()>oldNbOfComp) + { + std::ostringstream oss; oss << "The field has " << oldNbOfComp << " components and there are "; + oss << vars.size() << " variables : "; + std::copy(vars.begin(),vars.end(),std::ostream_iterator(oss," ")); + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + MEDCouplingAutoRefCountObjectPtr newArr(DataArrayDouble::New()); + newArr->alloc(nbOfTuples,nbOfComp); + INTERP_KERNEL::AutoPtr buff(new double[oldNbOfComp]); + double *buffPtr(buff),*ptrToFill; + std::vector stck; + for(int iComp=0;iCompgetPointer()+iComp; + if(!isSafe) + { + for(int i=0;i(oss,", ")); + oss << ") : Evaluation of function failed !" << e.what(); + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + } + } + return newArr.retn(); +} + +void DataArrayDouble::applyFuncFast32(const std::string& func) +{ + checkAllocated(); + INTERP_KERNEL::ExprParser expr(func); + expr.parse(); + char *funcStr=expr.compileX86(); + MYFUNCPTR funcPtr; + *((void **)&funcPtr)=funcStr;//he he... + // + double *ptr=getPointer(); + int nbOfComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + int nbOfElems=nbOfTuples*nbOfComp; + for(int i=0;igetNumberOfComponents() != 1. + * + * \sa DataArrayDouble::getIdsNotInRange + * + * \if ENABLE_EXAMPLES + * \ref cpp_mcdataarraydouble_getidsinrange "Here is a C++ example".
+ * \ref py_mcdataarraydouble_getidsinrange "Here is a Python example". + * \endif + */ +DataArrayInt *DataArrayDouble::getIdsInRange(double vmin, double vmax) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::getIdsInRange : this must have exactly one component !"); + const double *cptr(begin()); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + int nbOfTuples(getNumberOfTuples()); + for(int i=0;i=vmin && *cptr<=vmax) + ret->pushBackSilent(i); + return ret.retn(); +} + +/*! + * Returns a new DataArrayInt contating indices of tuples of \a this one-dimensional + * array whose values are not within a given range. Textual data is not copied. + * \param [in] vmin - a lowest not acceptable value (excluded). + * \param [in] vmax - a greatest not acceptable value (excluded). + * \return DataArrayInt * - the new instance of DataArrayInt. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If \a this->getNumberOfComponents() != 1. + * + * \sa DataArrayDouble::getIdsInRange + */ +DataArrayInt *DataArrayDouble::getIdsNotInRange(double vmin, double vmax) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::getIdsNotInRange : this must have exactly one component !"); + const double *cptr(begin()); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + int nbOfTuples(getNumberOfTuples()); + for(int i=0;ivmax) + ret->pushBackSilent(i); + return ret.retn(); +} + +/*! + * Returns a new DataArrayDouble by concatenating two given arrays, so that (1) the number + * of tuples in the result array is a sum of the number of tuples of given arrays and (2) + * the number of component in the result array is same as that of each of given arrays. + * Info on components is copied from the first of the given arrays. Number of components + * in the given arrays must be the same. + * \param [in] a1 - an array to include in the result array. + * \param [in] a2 - another array to include in the result array. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If both \a a1 and \a a2 are NULL. + * \throw If \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents(). + */ +DataArrayDouble *DataArrayDouble::Aggregate(const DataArrayDouble *a1, const DataArrayDouble *a2) +{ + std::vector tmp(2); + tmp[0]=a1; tmp[1]=a2; + return Aggregate(tmp); +} + +/*! + * Returns a new DataArrayDouble by concatenating all given arrays, so that (1) the number + * of tuples in the result array is a sum of the number of tuples of given arrays and (2) + * the number of component in the result array is same as that of each of given arrays. + * Info on components is copied from the first of the given arrays. Number of components + * in the given arrays must be the same. + * If the number of non null of elements in \a arr is equal to one the returned object is a copy of it + * not the object itself. + * \param [in] arr - a sequence of arrays to include in the result array. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If all arrays within \a arr are NULL. + * \throw If getNumberOfComponents() of arrays within \a arr. + */ +DataArrayDouble *DataArrayDouble::Aggregate(const std::vector& arr) +{ + std::vector a; + for(std::vector::const_iterator it4=arr.begin();it4!=arr.end();it4++) + if(*it4) + a.push_back(*it4); + if(a.empty()) + throw INTERP_KERNEL::Exception("DataArrayDouble::Aggregate : input list must contain at least one NON EMPTY DataArrayDouble !"); + std::vector::const_iterator it=a.begin(); + int nbOfComp=(*it)->getNumberOfComponents(); + int nbt=(*it++)->getNumberOfTuples(); + for(int i=1;it!=a.end();it++,i++) + { + if((*it)->getNumberOfComponents()!=nbOfComp) + throw INTERP_KERNEL::Exception("DataArrayDouble::Aggregate : Nb of components mismatch for array aggregation !"); + nbt+=(*it)->getNumberOfTuples(); + } + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(nbt,nbOfComp); + double *pt=ret->getPointer(); + for(it=a.begin();it!=a.end();it++) + pt=std::copy((*it)->getConstPointer(),(*it)->getConstPointer()+(*it)->getNbOfElems(),pt); + ret->copyStringInfoFrom(*(a[0])); + return ret.retn(); +} + +/*! + * Returns a new DataArrayDouble by aggregating two given arrays, so that (1) the number + * of components in the result array is a sum of the number of components of given arrays + * and (2) the number of tuples in the result array is same as that of each of given + * arrays. In other words the i-th tuple of result array includes all components of + * i-th tuples of all given arrays. + * Number of tuples in the given arrays must be the same. + * \param [in] a1 - an array to include in the result array. + * \param [in] a2 - another array to include in the result array. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If both \a a1 and \a a2 are NULL. + * \throw If any given array is not allocated. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() + */ +DataArrayDouble *DataArrayDouble::Meld(const DataArrayDouble *a1, const DataArrayDouble *a2) +{ + std::vector arr(2); + arr[0]=a1; arr[1]=a2; + return Meld(arr); +} + +/*! + * Returns a new DataArrayDouble by aggregating all given arrays, so that (1) the number + * of components in the result array is a sum of the number of components of given arrays + * and (2) the number of tuples in the result array is same as that of each of given + * arrays. In other words the i-th tuple of result array includes all components of + * i-th tuples of all given arrays. + * Number of tuples in the given arrays must be the same. + * \param [in] arr - a sequence of arrays to include in the result array. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If all arrays within \a arr are NULL. + * \throw If any given array is not allocated. + * \throw If getNumberOfTuples() of arrays within \a arr is different. + */ +DataArrayDouble *DataArrayDouble::Meld(const std::vector& arr) +{ + std::vector a; + for(std::vector::const_iterator it4=arr.begin();it4!=arr.end();it4++) + if(*it4) + a.push_back(*it4); + if(a.empty()) + throw INTERP_KERNEL::Exception("DataArrayDouble::Meld : input list must contain at least one NON EMPTY DataArrayDouble !"); + std::vector::const_iterator it; + for(it=a.begin();it!=a.end();it++) + (*it)->checkAllocated(); + it=a.begin(); + int nbOfTuples=(*it)->getNumberOfTuples(); + std::vector nbc(a.size()); + std::vector pts(a.size()); + nbc[0]=(*it)->getNumberOfComponents(); + pts[0]=(*it++)->getConstPointer(); + for(int i=1;it!=a.end();it++,i++) + { + if(nbOfTuples!=(*it)->getNumberOfTuples()) + throw INTERP_KERNEL::Exception("DataArrayDouble::Meld : mismatch of number of tuples !"); + nbc[i]=(*it)->getNumberOfComponents(); + pts[i]=(*it)->getConstPointer(); + } + int totalNbOfComp=std::accumulate(nbc.begin(),nbc.end(),0); + DataArrayDouble *ret=DataArrayDouble::New(); + ret->alloc(nbOfTuples,totalNbOfComp); + double *retPtr=ret->getPointer(); + for(int i=0;isetInfoOnComponent(k,a[i]->getInfoOnComponent(j)); + return ret; +} + +/*! + * Returns a new DataArrayDouble containing a dot product of two given arrays, so that + * the i-th tuple of the result array is a sum of products of j-th components of i-th + * tuples of given arrays (\f$ a_i = \sum_{j=1}^n a1_j * a2_j \f$). + * Info on components and name is copied from the first of the given arrays. + * Number of tuples and components in the given arrays must be the same. + * \param [in] a1 - a given array. + * \param [in] a2 - another given array. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If any given array is not allocated. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() + * \throw If \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() + */ +DataArrayDouble *DataArrayDouble::Dot(const DataArrayDouble *a1, const DataArrayDouble *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayDouble::Dot : input DataArrayDouble instance is NULL !"); + a1->checkAllocated(); + a2->checkAllocated(); + int nbOfComp=a1->getNumberOfComponents(); + if(nbOfComp!=a2->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("Nb of components mismatch for array Dot !"); + int nbOfTuple=a1->getNumberOfTuples(); + if(nbOfTuple!=a2->getNumberOfTuples()) + throw INTERP_KERNEL::Exception("Nb of tuples mismatch for array Dot !"); + DataArrayDouble *ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple,1); + double *retPtr=ret->getPointer(); + const double *a1Ptr=a1->getConstPointer(); + const double *a2Ptr=a2->getConstPointer(); + for(int i=0;isetInfoOnComponent(0,a1->getInfoOnComponent(0)); + ret->setName(a1->getName()); + return ret; +} + +/*! + * Returns a new DataArrayDouble containing a cross product of two given arrays, so that + * the i-th tuple of the result array contains 3 components of a vector which is a cross + * product of two vectors defined by the i-th tuples of given arrays. + * Info on components is copied from the first of the given arrays. + * Number of tuples in the given arrays must be the same. + * Number of components in the given arrays must be 3. + * \param [in] a1 - a given array. + * \param [in] a2 - another given array. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() + * \throw If \a a1->getNumberOfComponents() != 3 + * \throw If \a a2->getNumberOfComponents() != 3 + */ +DataArrayDouble *DataArrayDouble::CrossProduct(const DataArrayDouble *a1, const DataArrayDouble *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayDouble::CrossProduct : input DataArrayDouble instance is NULL !"); + int nbOfComp=a1->getNumberOfComponents(); + if(nbOfComp!=a2->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("Nb of components mismatch for array crossProduct !"); + if(nbOfComp!=3) + throw INTERP_KERNEL::Exception("Nb of components must be equal to 3 for array crossProduct !"); + int nbOfTuple=a1->getNumberOfTuples(); + if(nbOfTuple!=a2->getNumberOfTuples()) + throw INTERP_KERNEL::Exception("Nb of tuples mismatch for array crossProduct !"); + DataArrayDouble *ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple,3); + double *retPtr=ret->getPointer(); + const double *a1Ptr=a1->getConstPointer(); + const double *a2Ptr=a2->getConstPointer(); + for(int i=0;icopyStringInfoFrom(*a1); + return ret; +} + +/*! + * Returns a new DataArrayDouble containing maximal values of two given arrays. + * Info on components is copied from the first of the given arrays. + * Number of tuples and components in the given arrays must be the same. + * \param [in] a1 - an array to compare values with another one. + * \param [in] a2 - another array to compare values with the first one. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() + * \throw If \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() + */ +DataArrayDouble *DataArrayDouble::Max(const DataArrayDouble *a1, const DataArrayDouble *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayDouble::Max : input DataArrayDouble instance is NULL !"); + int nbOfComp=a1->getNumberOfComponents(); + if(nbOfComp!=a2->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("Nb of components mismatch for array Max !"); + int nbOfTuple=a1->getNumberOfTuples(); + if(nbOfTuple!=a2->getNumberOfTuples()) + throw INTERP_KERNEL::Exception("Nb of tuples mismatch for array Max !"); + DataArrayDouble *ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple,nbOfComp); + double *retPtr=ret->getPointer(); + const double *a1Ptr=a1->getConstPointer(); + const double *a2Ptr=a2->getConstPointer(); + int nbElem=nbOfTuple*nbOfComp; + for(int i=0;icopyStringInfoFrom(*a1); + return ret; +} + +/*! + * Returns a new DataArrayDouble containing minimal values of two given arrays. + * Info on components is copied from the first of the given arrays. + * Number of tuples and components in the given arrays must be the same. + * \param [in] a1 - an array to compare values with another one. + * \param [in] a2 - another array to compare values with the first one. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() + * \throw If \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() + */ +DataArrayDouble *DataArrayDouble::Min(const DataArrayDouble *a1, const DataArrayDouble *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayDouble::Min : input DataArrayDouble instance is NULL !"); + int nbOfComp=a1->getNumberOfComponents(); + if(nbOfComp!=a2->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("Nb of components mismatch for array min !"); + int nbOfTuple=a1->getNumberOfTuples(); + if(nbOfTuple!=a2->getNumberOfTuples()) + throw INTERP_KERNEL::Exception("Nb of tuples mismatch for array min !"); + DataArrayDouble *ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple,nbOfComp); + double *retPtr=ret->getPointer(); + const double *a1Ptr=a1->getConstPointer(); + const double *a2Ptr=a2->getConstPointer(); + int nbElem=nbOfTuple*nbOfComp; + for(int i=0;icopyStringInfoFrom(*a1); + return ret; +} + +/*! + * Returns a new DataArrayDouble that is a sum of two given arrays. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * the result array (_a_) is a sum of the corresponding values of \a a1 and \a a2, + * i.e.: _a_ [ i, j ] = _a1_ [ i, j ] + _a2_ [ i, j ]. + * 2. The arrays have same number of tuples and one array, say _a2_, has one + * component. Then + * _a_ [ i, j ] = _a1_ [ i, j ] + _a2_ [ i, 0 ]. + * 3. The arrays have same number of components and one array, say _a2_, has one + * tuple. Then + * _a_ [ i, j ] = _a1_ [ i, j ] + _a2_ [ 0, j ]. + * + * Info on components is copied either from the first array (in the first case) or from + * the array with maximal number of elements (getNbOfElems()). + * \param [in] a1 - an array to sum up. + * \param [in] a2 - another array to sum up. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() and + * \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() and + * none of them has number of tuples or components equal to 1. + */ +DataArrayDouble *DataArrayDouble::Add(const DataArrayDouble *a1, const DataArrayDouble *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayDouble::Add : input DataArrayDouble instance is NULL !"); + int nbOfTuple=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + int nbOfComp=a1->getNumberOfComponents(); + int nbOfComp2=a2->getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=0; + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple,nbOfComp); + std::transform(a1->begin(),a1->end(),a2->begin(),ret->getPointer(),std::plus()); + ret->copyStringInfoFrom(*a1); + } + else + { + int nbOfCompMin,nbOfCompMax; + const DataArrayDouble *aMin, *aMax; + if(nbOfComp>nbOfComp2) + { + nbOfCompMin=nbOfComp2; nbOfCompMax=nbOfComp; + aMin=a2; aMax=a1; + } + else + { + nbOfCompMin=nbOfComp; nbOfCompMax=nbOfComp2; + aMin=a1; aMax=a2; + } + if(nbOfCompMin==1) + { + ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple,nbOfCompMax); + const double *aMinPtr=aMin->getConstPointer(); + const double *aMaxPtr=aMax->getConstPointer(); + double *res=ret->getPointer(); + for(int i=0;i(),aMinPtr[i])); + ret->copyStringInfoFrom(*aMax); + } + else + throw INTERP_KERNEL::Exception("Nb of components mismatch for array Add !"); + } + } + else if((nbOfTuple==1 && nbOfTuple2>1) || (nbOfTuple>1 && nbOfTuple2==1)) + { + if(nbOfComp==nbOfComp2) + { + int nbOfTupleMax=std::max(nbOfTuple,nbOfTuple2); + const DataArrayDouble *aMin=nbOfTuple>nbOfTuple2?a2:a1; + const DataArrayDouble *aMax=nbOfTuple>nbOfTuple2?a1:a2; + const double *aMinPtr=aMin->getConstPointer(),*aMaxPtr=aMax->getConstPointer(); + ret=DataArrayDouble::New(); + ret->alloc(nbOfTupleMax,nbOfComp); + double *res=ret->getPointer(); + for(int i=0;i()); + ret->copyStringInfoFrom(*aMax); + } + else + throw INTERP_KERNEL::Exception("Nb of components mismatch for array Add !"); + } + else + throw INTERP_KERNEL::Exception("Nb of tuples mismatch for array Add !"); + return ret.retn(); +} + +/*! + * Adds values of another DataArrayDouble to values of \a this one. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * \a other array is added to the corresponding value of \a this array, i.e.: + * _a_ [ i, j ] += _other_ [ i, j ]. + * 2. The arrays have same number of tuples and \a other array has one component. Then + * _a_ [ i, j ] += _other_ [ i, 0 ]. + * 3. The arrays have same number of components and \a other array has one tuple. Then + * _a_ [ i, j ] += _a2_ [ 0, j ]. + * + * \param [in] other - an array to add to \a this one. + * \throw If \a other is NULL. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples() and + * \a this->getNumberOfComponents() != \a other->getNumberOfComponents() and + * \a other has number of both tuples and components not equal to 1. + */ +void DataArrayDouble::addEqual(const DataArrayDouble *other) +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayDouble::addEqual : input DataArrayDouble instance is NULL !"); + const char *msg="Nb of tuples mismatch for DataArrayDouble::addEqual !"; + checkAllocated(); + other->checkAllocated(); + int nbOfTuple=getNumberOfTuples(); + int nbOfTuple2=other->getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + std::transform(begin(),end(),other->begin(),getPointer(),std::plus()); + } + else if(nbOfComp2==1) + { + double *ptr=getPointer(); + const double *ptrc=other->getConstPointer(); + for(int i=0;i(),*ptrc++)); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else if(nbOfTuple2==1) + { + if(nbOfComp2==nbOfComp) + { + double *ptr=getPointer(); + const double *ptrc=other->getConstPointer(); + for(int i=0;i()); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else + throw INTERP_KERNEL::Exception(msg); + declareAsNew(); +} + +/*! + * Returns a new DataArrayDouble that is a subtraction of two given arrays. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * the result array (_a_) is a subtraction of the corresponding values of \a a1 and + * \a a2, i.e.: _a_ [ i, j ] = _a1_ [ i, j ] - _a2_ [ i, j ]. + * 2. The arrays have same number of tuples and one array, say _a2_, has one + * component. Then + * _a_ [ i, j ] = _a1_ [ i, j ] - _a2_ [ i, 0 ]. + * 3. The arrays have same number of components and one array, say _a2_, has one + * tuple. Then + * _a_ [ i, j ] = _a1_ [ i, j ] - _a2_ [ 0, j ]. + * + * Info on components is copied either from the first array (in the first case) or from + * the array with maximal number of elements (getNbOfElems()). + * \param [in] a1 - an array to subtract from. + * \param [in] a2 - an array to subtract. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() and + * \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() and + * none of them has number of tuples or components equal to 1. + */ +DataArrayDouble *DataArrayDouble::Substract(const DataArrayDouble *a1, const DataArrayDouble *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayDouble::Substract : input DataArrayDouble instance is NULL !"); + int nbOfTuple1=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + int nbOfComp1=a1->getNumberOfComponents(); + int nbOfComp2=a2->getNumberOfComponents(); + if(nbOfTuple2==nbOfTuple1) + { + if(nbOfComp1==nbOfComp2) + { + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple2,nbOfComp1); + std::transform(a1->begin(),a1->end(),a2->begin(),ret->getPointer(),std::minus()); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else if(nbOfComp2==1) + { + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple1,nbOfComp1); + const double *a2Ptr=a2->getConstPointer(); + const double *a1Ptr=a1->getConstPointer(); + double *res=ret->getPointer(); + for(int i=0;i(),a2Ptr[i])); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else + { + a1->checkNbOfComps(nbOfComp2,"Nb of components mismatch for array Substract !"); + return 0; + } + } + else if(nbOfTuple2==1) + { + a1->checkNbOfComps(nbOfComp2,"Nb of components mismatch for array Substract !"); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple1,nbOfComp1); + const double *a1ptr=a1->getConstPointer(),*a2ptr=a2->getConstPointer(); + double *pt=ret->getPointer(); + for(int i=0;i()); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else + { + a1->checkNbOfTuples(nbOfTuple2,"Nb of tuples mismatch for array Substract !");//will always throw an exception + return 0; + } +} + +/*! + * Subtract values of another DataArrayDouble from values of \a this one. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * \a other array is subtracted from the corresponding value of \a this array, i.e.: + * _a_ [ i, j ] -= _other_ [ i, j ]. + * 2. The arrays have same number of tuples and \a other array has one component. Then + * _a_ [ i, j ] -= _other_ [ i, 0 ]. + * 3. The arrays have same number of components and \a other array has one tuple. Then + * _a_ [ i, j ] -= _a2_ [ 0, j ]. + * + * \param [in] other - an array to subtract from \a this one. + * \throw If \a other is NULL. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples() and + * \a this->getNumberOfComponents() != \a other->getNumberOfComponents() and + * \a other has number of both tuples and components not equal to 1. + */ +void DataArrayDouble::substractEqual(const DataArrayDouble *other) +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayDouble::substractEqual : input DataArrayDouble instance is NULL !"); + const char *msg="Nb of tuples mismatch for DataArrayDouble::substractEqual !"; + checkAllocated(); + other->checkAllocated(); + int nbOfTuple=getNumberOfTuples(); + int nbOfTuple2=other->getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + std::transform(begin(),end(),other->begin(),getPointer(),std::minus()); + } + else if(nbOfComp2==1) + { + double *ptr=getPointer(); + const double *ptrc=other->getConstPointer(); + for(int i=0;i(),*ptrc++)); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else if(nbOfTuple2==1) + { + if(nbOfComp2==nbOfComp) + { + double *ptr=getPointer(); + const double *ptrc=other->getConstPointer(); + for(int i=0;i()); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else + throw INTERP_KERNEL::Exception(msg); + declareAsNew(); +} + +/*! + * Returns a new DataArrayDouble that is a product of two given arrays. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * the result array (_a_) is a product of the corresponding values of \a a1 and + * \a a2, i.e. _a_ [ i, j ] = _a1_ [ i, j ] * _a2_ [ i, j ]. + * 2. The arrays have same number of tuples and one array, say _a2_, has one + * component. Then + * _a_ [ i, j ] = _a1_ [ i, j ] * _a2_ [ i, 0 ]. + * 3. The arrays have same number of components and one array, say _a2_, has one + * tuple. Then + * _a_ [ i, j ] = _a1_ [ i, j ] * _a2_ [ 0, j ]. + * + * Info on components is copied either from the first array (in the first case) or from + * the array with maximal number of elements (getNbOfElems()). + * \param [in] a1 - a factor array. + * \param [in] a2 - another factor array. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() and + * \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() and + * none of them has number of tuples or components equal to 1. + */ +DataArrayDouble *DataArrayDouble::Multiply(const DataArrayDouble *a1, const DataArrayDouble *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayDouble::Multiply : input DataArrayDouble instance is NULL !"); + int nbOfTuple=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + int nbOfComp=a1->getNumberOfComponents(); + int nbOfComp2=a2->getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=0; + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple,nbOfComp); + std::transform(a1->begin(),a1->end(),a2->begin(),ret->getPointer(),std::multiplies()); + ret->copyStringInfoFrom(*a1); + } + else + { + int nbOfCompMin,nbOfCompMax; + const DataArrayDouble *aMin, *aMax; + if(nbOfComp>nbOfComp2) + { + nbOfCompMin=nbOfComp2; nbOfCompMax=nbOfComp; + aMin=a2; aMax=a1; + } + else + { + nbOfCompMin=nbOfComp; nbOfCompMax=nbOfComp2; + aMin=a1; aMax=a2; + } + if(nbOfCompMin==1) + { + ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple,nbOfCompMax); + const double *aMinPtr=aMin->getConstPointer(); + const double *aMaxPtr=aMax->getConstPointer(); + double *res=ret->getPointer(); + for(int i=0;i(),aMinPtr[i])); + ret->copyStringInfoFrom(*aMax); + } + else + throw INTERP_KERNEL::Exception("Nb of components mismatch for array Multiply !"); + } + } + else if((nbOfTuple==1 && nbOfTuple2>1) || (nbOfTuple>1 && nbOfTuple2==1)) + { + if(nbOfComp==nbOfComp2) + { + int nbOfTupleMax=std::max(nbOfTuple,nbOfTuple2); + const DataArrayDouble *aMin=nbOfTuple>nbOfTuple2?a2:a1; + const DataArrayDouble *aMax=nbOfTuple>nbOfTuple2?a1:a2; + const double *aMinPtr=aMin->getConstPointer(),*aMaxPtr=aMax->getConstPointer(); + ret=DataArrayDouble::New(); + ret->alloc(nbOfTupleMax,nbOfComp); + double *res=ret->getPointer(); + for(int i=0;i()); + ret->copyStringInfoFrom(*aMax); + } + else + throw INTERP_KERNEL::Exception("Nb of components mismatch for array Multiply !"); + } + else + throw INTERP_KERNEL::Exception("Nb of tuples mismatch for array Multiply !"); + return ret.retn(); +} + +/*! + * Multiply values of another DataArrayDouble to values of \a this one. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * \a other array is multiplied to the corresponding value of \a this array, i.e. + * _this_ [ i, j ] *= _other_ [ i, j ]. + * 2. The arrays have same number of tuples and \a other array has one component. Then + * _this_ [ i, j ] *= _other_ [ i, 0 ]. + * 3. The arrays have same number of components and \a other array has one tuple. Then + * _this_ [ i, j ] *= _a2_ [ 0, j ]. + * + * \param [in] other - an array to multiply to \a this one. + * \throw If \a other is NULL. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples() and + * \a this->getNumberOfComponents() != \a other->getNumberOfComponents() and + * \a other has number of both tuples and components not equal to 1. + */ +void DataArrayDouble::multiplyEqual(const DataArrayDouble *other) +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayDouble::multiplyEqual : input DataArrayDouble instance is NULL !"); + const char *msg="Nb of tuples mismatch for DataArrayDouble::multiplyEqual !"; + checkAllocated(); + other->checkAllocated(); + int nbOfTuple=getNumberOfTuples(); + int nbOfTuple2=other->getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + std::transform(begin(),end(),other->begin(),getPointer(),std::multiplies()); + } + else if(nbOfComp2==1) + { + double *ptr=getPointer(); + const double *ptrc=other->getConstPointer(); + for(int i=0;i(),*ptrc++)); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else if(nbOfTuple2==1) + { + if(nbOfComp2==nbOfComp) + { + double *ptr=getPointer(); + const double *ptrc=other->getConstPointer(); + for(int i=0;i()); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else + throw INTERP_KERNEL::Exception(msg); + declareAsNew(); +} + +/*! + * Returns a new DataArrayDouble that is a division of two given arrays. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * the result array (_a_) is a division of the corresponding values of \a a1 and + * \a a2, i.e.: _a_ [ i, j ] = _a1_ [ i, j ] / _a2_ [ i, j ]. + * 2. The arrays have same number of tuples and one array, say _a2_, has one + * component. Then + * _a_ [ i, j ] = _a1_ [ i, j ] / _a2_ [ i, 0 ]. + * 3. The arrays have same number of components and one array, say _a2_, has one + * tuple. Then + * _a_ [ i, j ] = _a1_ [ i, j ] / _a2_ [ 0, j ]. + * + * Info on components is copied either from the first array (in the first case) or from + * the array with maximal number of elements (getNbOfElems()). + * \warning No check of division by zero is performed! + * \param [in] a1 - a numerator array. + * \param [in] a2 - a denominator array. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() and + * \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() and + * none of them has number of tuples or components equal to 1. + */ +DataArrayDouble *DataArrayDouble::Divide(const DataArrayDouble *a1, const DataArrayDouble *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayDouble::Divide : input DataArrayDouble instance is NULL !"); + int nbOfTuple1=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + int nbOfComp1=a1->getNumberOfComponents(); + int nbOfComp2=a2->getNumberOfComponents(); + if(nbOfTuple2==nbOfTuple1) + { + if(nbOfComp1==nbOfComp2) + { + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple2,nbOfComp1); + std::transform(a1->begin(),a1->end(),a2->begin(),ret->getPointer(),std::divides()); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else if(nbOfComp2==1) + { + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple1,nbOfComp1); + const double *a2Ptr=a2->getConstPointer(); + const double *a1Ptr=a1->getConstPointer(); + double *res=ret->getPointer(); + for(int i=0;i(),a2Ptr[i])); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else + { + a1->checkNbOfComps(nbOfComp2,"Nb of components mismatch for array Divide !"); + return 0; + } + } + else if(nbOfTuple2==1) + { + a1->checkNbOfComps(nbOfComp2,"Nb of components mismatch for array Divide !"); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); + ret->alloc(nbOfTuple1,nbOfComp1); + const double *a1ptr=a1->getConstPointer(),*a2ptr=a2->getConstPointer(); + double *pt=ret->getPointer(); + for(int i=0;i()); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else + { + a1->checkNbOfTuples(nbOfTuple2,"Nb of tuples mismatch for array Divide !");//will always throw an exception + return 0; + } +} + +/*! + * Divide values of \a this array by values of another DataArrayDouble. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * \a this array is divided by the corresponding value of \a other one, i.e.: + * _a_ [ i, j ] /= _other_ [ i, j ]. + * 2. The arrays have same number of tuples and \a other array has one component. Then + * _a_ [ i, j ] /= _other_ [ i, 0 ]. + * 3. The arrays have same number of components and \a other array has one tuple. Then + * _a_ [ i, j ] /= _a2_ [ 0, j ]. + * + * \warning No check of division by zero is performed! + * \param [in] other - an array to divide \a this one by. + * \throw If \a other is NULL. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples() and + * \a this->getNumberOfComponents() != \a other->getNumberOfComponents() and + * \a other has number of both tuples and components not equal to 1. + */ +void DataArrayDouble::divideEqual(const DataArrayDouble *other) +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayDouble::divideEqual : input DataArrayDouble instance is NULL !"); + const char *msg="Nb of tuples mismatch for DataArrayDouble::divideEqual !"; + checkAllocated(); + other->checkAllocated(); + int nbOfTuple=getNumberOfTuples(); + int nbOfTuple2=other->getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + std::transform(begin(),end(),other->begin(),getPointer(),std::divides()); + } + else if(nbOfComp2==1) + { + double *ptr=getPointer(); + const double *ptrc=other->getConstPointer(); + for(int i=0;i(),*ptrc++)); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else if(nbOfTuple2==1) + { + if(nbOfComp2==nbOfComp) + { + double *ptr=getPointer(); + const double *ptrc=other->getConstPointer(); + for(int i=0;i()); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else + throw INTERP_KERNEL::Exception(msg); + declareAsNew(); +} + +/*! + * Returns a new DataArrayDouble that is the result of pow of two given arrays. There are 3 + * valid cases. + * + * \param [in] a1 - an array to pow up. + * \param [in] a2 - another array to sum up. + * \return DataArrayDouble * - the new instance of DataArrayDouble. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() + * \throw If \a a1->getNumberOfComponents() != 1 or \a a2->getNumberOfComponents() != 1. + * \throw If there is a negative value in \a a1. + */ +DataArrayDouble *DataArrayDouble::Pow(const DataArrayDouble *a1, const DataArrayDouble *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayDouble::Pow : at least one of input instances is null !"); + int nbOfTuple=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + int nbOfComp=a1->getNumberOfComponents(); + int nbOfComp2=a2->getNumberOfComponents(); + if(nbOfTuple!=nbOfTuple2) + throw INTERP_KERNEL::Exception("DataArrayDouble::Pow : number of tuples mismatches !"); + if(nbOfComp!=1 || nbOfComp2!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::Pow : number of components of both arrays must be equal to 1 !"); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayDouble::New(); ret->alloc(nbOfTuple,1); + const double *ptr1(a1->begin()),*ptr2(a2->begin()); + double *ptr=ret->getPointer(); + for(int i=0;i=0) + { + *ptr=pow(*ptr1,*ptr2); + } + else + { + std::ostringstream oss; oss << "DataArrayDouble::Pow : on tuple #" << i << " of a1 value is < 0 (" << *ptr1 << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + return ret.retn(); +} + +/*! + * Apply pow on values of another DataArrayDouble to values of \a this one. + * + * \param [in] other - an array to pow to \a this one. + * \throw If \a other is NULL. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples() + * \throw If \a this->getNumberOfComponents() != 1 or \a other->getNumberOfComponents() != 1 + * \throw If there is a negative value in \a this. + */ +void DataArrayDouble::powEqual(const DataArrayDouble *other) +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayDouble::powEqual : input instance is null !"); + int nbOfTuple=getNumberOfTuples(); + int nbOfTuple2=other->getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + if(nbOfTuple!=nbOfTuple2) + throw INTERP_KERNEL::Exception("DataArrayDouble::powEqual : number of tuples mismatches !"); + if(nbOfComp!=1 || nbOfComp2!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::powEqual : number of components of both arrays must be equal to 1 !"); + double *ptr=getPointer(); + const double *ptrc=other->begin(); + for(int i=0;i=0) + *ptr=pow(*ptr,*ptrc); + else + { + std::ostringstream oss; oss << "DataArrayDouble::powEqual : on tuple #" << i << " of this value is < 0 (" << *ptr << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + declareAsNew(); +} + +/*! + * This method is \b NOT wrapped into python because it can be useful only for performance reasons in C++ context. + * All values in \a this must be 0. or 1. within eps error. 0 means false, 1 means true. + * If an another value than 0 or 1 appear (within eps precision) an INTERP_KERNEL::Exception will be thrown. + * + * \throw if \a this is not allocated. + * \throw if \a this has not exactly one component. + */ +std::vector DataArrayDouble::toVectorOfBool(double eps) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayDouble::toVectorOfBool : must be applied on single component array !"); + int nbt(getNumberOfTuples()); + std::vector ret(nbt); + const double *pt(begin()); + for(int i=0;i& tinyInfo) const +{ + tinyInfo.resize(2); + if(isAllocated()) + { + tinyInfo[0]=getNumberOfTuples(); + tinyInfo[1]=getNumberOfComponents(); + } + else + { + tinyInfo[0]=-1; + tinyInfo[1]=-1; + } +} + +/*! + * Useless method for end user. Only for MPI/Corba/File serialsation for multi arrays class. + * Server side. + */ +void DataArrayDouble::getTinySerializationStrInformation(std::vector& tinyInfo) const +{ + if(isAllocated()) + { + int nbOfCompo=getNumberOfComponents(); + tinyInfo.resize(nbOfCompo+1); + tinyInfo[0]=getName(); + for(int i=0;i& tinyInfoI) +{ + int nbOfTuple=tinyInfoI[0]; + int nbOfComp=tinyInfoI[1]; + if(nbOfTuple!=-1 || nbOfComp!=-1) + { + alloc(nbOfTuple,nbOfComp); + return true; + } + return false; +} + +/*! + * Useless method for end user. Only for MPI/Corba/File serialsation for multi arrays class. + */ +void DataArrayDouble::finishUnserialization(const std::vector& tinyInfoI, const std::vector& tinyInfoS) +{ + setName(tinyInfoS[0]); + if(isAllocated()) + { + int nbOfCompo=getNumberOfComponents(); + for(int i=0;iincrRef(); + if(_da->isAllocated()) + { + _nb_comp=da->getNumberOfComponents(); + _nb_tuple=da->getNumberOfTuples(); + _pt=da->getPointer(); + } + } +} + +DataArrayDoubleIterator::~DataArrayDoubleIterator() +{ + if(_da) + _da->decrRef(); +} + +DataArrayDoubleTuple *DataArrayDoubleIterator::nextt() +{ + if(_tuple_id<_nb_tuple) + { + _tuple_id++; + DataArrayDoubleTuple *ret=new DataArrayDoubleTuple(_pt,_nb_comp); + _pt+=_nb_comp; + return ret; + } + else + return 0; +} + +DataArrayDoubleTuple::DataArrayDoubleTuple(double *pt, int nbOfComp):_pt(pt),_nb_of_compo(nbOfComp) +{ +} + + +std::string DataArrayDoubleTuple::repr() const +{ + std::ostringstream oss; oss.precision(17); oss << "("; + for(int i=0;i<_nb_of_compo-1;i++) + oss << _pt[i] << ", "; + oss << _pt[_nb_of_compo-1] << ")"; + return oss.str(); +} + +double DataArrayDoubleTuple::doubleValue() const +{ + if(_nb_of_compo==1) + return *_pt; + throw INTERP_KERNEL::Exception("DataArrayDoubleTuple::doubleValue : DataArrayDoubleTuple instance has not exactly 1 component -> Not possible to convert it into a double precision float !"); +} + +/*! + * This method returns a newly allocated instance the caller should dealed with by a ParaMEDMEM::DataArrayDouble::decrRef. + * This method performs \b no copy of data. The content is only referenced using ParaMEDMEM::DataArrayDouble::useArray with ownership set to \b false. + * This method throws an INTERP_KERNEL::Exception is it is impossible to match sizes of \b this that is too say \b nbOfCompo=this->_nb_of_elem and \bnbOfTuples==1 or + * \b nbOfCompo=1 and \bnbOfTuples==this->_nb_of_elem. + */ +DataArrayDouble *DataArrayDoubleTuple::buildDADouble(int nbOfTuples, int nbOfCompo) const +{ + if((_nb_of_compo==nbOfCompo && nbOfTuples==1) || (_nb_of_compo==nbOfTuples && nbOfCompo==1)) + { + DataArrayDouble *ret=DataArrayDouble::New(); + ret->useExternalArrayWithRWAccess(_pt,nbOfTuples,nbOfCompo); + return ret; + } + else + { + std::ostringstream oss; oss << "DataArrayDoubleTuple::buildDADouble : unable to build a requested DataArrayDouble instance with nbofTuple=" << nbOfTuples << " and nbOfCompo=" << nbOfCompo; + oss << ".\nBecause the number of elements in this is " << _nb_of_compo << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} + +/*! + * Returns a new instance of DataArrayInt. The caller is to delete this array + * using decrRef() as it is no more needed. + */ +DataArrayInt *DataArrayInt::New() +{ + return new DataArrayInt; +} + +/*! + * Checks if raw data is allocated. Read more on the raw data + * in \ref MEDCouplingArrayBasicsTuplesAndCompo "DataArrays infos" for more information. + * \return bool - \a true if the raw data is allocated, \a false else. + */ +bool DataArrayInt::isAllocated() const +{ + return getConstPointer()!=0; +} + +/*! + * Checks if raw data is allocated and throws an exception if it is not the case. + * \throw If the raw data is not allocated. + */ +void DataArrayInt::checkAllocated() const +{ + if(!isAllocated()) + throw INTERP_KERNEL::Exception("DataArrayInt::checkAllocated : Array is defined but not allocated ! Call alloc or setValues method first !"); +} + +/*! + * This method desallocated \a this without modification of informations relative to the components. + * After call of this method, DataArrayInt::isAllocated will return false. + * If \a this is already not allocated, \a this is let unchanged. + */ +void DataArrayInt::desallocate() +{ + _mem.destroy(); +} + +std::size_t DataArrayInt::getHeapMemorySizeWithoutChildren() const +{ + std::size_t sz(_mem.getNbOfElemAllocated()); + sz*=sizeof(int); + return DataArray::getHeapMemorySizeWithoutChildren()+sz; +} + +/*! + * Returns the only one value in \a this, if and only if number of elements + * (nb of tuples * nb of components) is equal to 1, and that \a this is allocated. + * \return double - the sole value stored in \a this array. + * \throw If at least one of conditions stated above is not fulfilled. + */ +int DataArrayInt::intValue() const +{ + if(isAllocated()) + { + if(getNbOfElems()==1) + { + return *getConstPointer(); + } + else + throw INTERP_KERNEL::Exception("DataArrayInt::intValue : DataArrayInt instance is allocated but number of elements is not equal to 1 !"); + } + else + throw INTERP_KERNEL::Exception("DataArrayInt::intValue : DataArrayInt instance is not allocated !"); +} + +/*! + * Returns an integer value characterizing \a this array, which is useful for a quick + * comparison of many instances of DataArrayInt. + * \return int - the hash value. + * \throw If \a this is not allocated. + */ +int DataArrayInt::getHashCode() const +{ + checkAllocated(); + std::size_t nbOfElems=getNbOfElems(); + int ret=nbOfElems*65536; + int delta=3; + if(nbOfElems>48) + delta=nbOfElems/8; + int ret0=0; + const int *pt=begin(); + for(std::size_t i=0;i(this); + } +} + +/*! + * Copies all the data from another DataArrayInt. For more info see + * \ref MEDCouplingArrayBasicsCopyDeepAssign. + * \param [in] other - another instance of DataArrayInt to copy data from. + * \throw If the \a other is not allocated. + */ +void DataArrayInt::cpyFrom(const DataArrayInt& other) +{ + other.checkAllocated(); + int nbOfTuples=other.getNumberOfTuples(); + int nbOfComp=other.getNumberOfComponents(); + allocIfNecessary(nbOfTuples,nbOfComp); + std::size_t nbOfElems=(std::size_t)nbOfTuples*nbOfComp; + int *pt=getPointer(); + const int *ptI=other.getConstPointer(); + for(std::size_t i=0;igetNumberOfComponents() != 1 + * \throw If \a this is not allocated. + */ +void DataArrayInt::iota(int init) +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::iota : works only for arrays with only one component, you can call 'rearrange' method before !"); + int *ptr=getPointer(); + int ntuples=getNumberOfTuples(); + for(int i=0;igetNumberOfTuples() << "\">"; + if(std::string(type)=="Int32") + { + const char *data(reinterpret_cast(begin())); + std::size_t sz(getNbOfElems()*sizeof(int)); + byteArr->insertAtTheEnd(data,data+sz); + byteArr->insertAtTheEnd(SPACE,SPACE+4); + } + else if(std::string(type)=="Int8") + { + INTERP_KERNEL::AutoPtr tmp(new char[getNbOfElems()]); + std::copy(begin(),end(),(char *)tmp); + byteArr->insertAtTheEnd((char *)tmp,(char *)tmp+getNbOfElems()); + byteArr->insertAtTheEnd(SPACE,SPACE+4); + } + else if(std::string(type)=="UInt8") + { + INTERP_KERNEL::AutoPtr tmp(new unsigned char[getNbOfElems()]); + std::copy(begin(),end(),(unsigned char *)tmp); + byteArr->insertAtTheEnd((unsigned char *)tmp,(unsigned char *)tmp+getNbOfElems()); + byteArr->insertAtTheEnd(SPACE,SPACE+4); + } + else + throw INTERP_KERNEL::Exception("DataArrayInt::writeVTK : Only Int32, Int8 and UInt8 supported !"); + } + else + { + ofs << " RangeMin=\"" << getMinValueInArray() << "\" RangeMax=\"" << getMaxValueInArray() << "\" format=\"ascii\">\n" << idt; + std::copy(begin(),end(),std::ostream_iterator(ofs," ")); + } + ofs << std::endl << idt << "\n"; +} + +void DataArrayInt::reprStream(std::ostream& stream) const +{ + stream << "Name of int array : \"" << _name << "\"\n"; + reprWithoutNameStream(stream); +} + +void DataArrayInt::reprZipStream(std::ostream& stream) const +{ + stream << "Name of int array : \"" << _name << "\"\n"; + reprZipWithoutNameStream(stream); +} + +void DataArrayInt::reprNotTooLongStream(std::ostream& stream) const +{ + stream << "Name of int array : \"" << _name << "\"\n"; + reprNotTooLongWithoutNameStream(stream); +} + +void DataArrayInt::reprWithoutNameStream(std::ostream& stream) const +{ + DataArray::reprWithoutNameStream(stream); + _mem.repr(getNumberOfComponents(),stream); +} + +void DataArrayInt::reprZipWithoutNameStream(std::ostream& stream) const +{ + DataArray::reprWithoutNameStream(stream); + _mem.reprZip(getNumberOfComponents(),stream); +} + +void DataArrayInt::reprNotTooLongWithoutNameStream(std::ostream& stream) const +{ + DataArray::reprWithoutNameStream(stream); + stream.precision(17); + _mem.reprNotTooLong(getNumberOfComponents(),stream); +} + +void DataArrayInt::reprCppStream(const std::string& varName, std::ostream& stream) const +{ + int nbTuples=getNumberOfTuples(),nbComp=getNumberOfComponents(); + const int *data=getConstPointer(); + stream << "DataArrayInt *" << varName << "=DataArrayInt::New();" << std::endl; + if(nbTuples*nbComp>=1) + { + stream << "const int " << varName << "Data[" << nbTuples*nbComp << "]={"; + std::copy(data,data+nbTuples*nbComp-1,std::ostream_iterator(stream,",")); + stream << data[nbTuples*nbComp-1] << "};" << std::endl; + stream << varName << "->useArray(" << varName << "Data,false,CPP_DEALLOC," << nbTuples << "," << nbComp << ");" << std::endl; + } + else + stream << varName << "->alloc(" << nbTuples << "," << nbComp << ");" << std::endl; + stream << varName << "->setName(\"" << getName() << "\");" << std::endl; +} + +/*! + * Method that gives a quick overvien of \a this for python. + */ +void DataArrayInt::reprQuickOverview(std::ostream& stream) const +{ + static const std::size_t MAX_NB_OF_BYTE_IN_REPR=300; + stream << "DataArrayInt C++ instance at " << this << ". "; + if(isAllocated()) + { + int nbOfCompo=(int)_info_on_compo.size(); + if(nbOfCompo>=1) + { + int nbOfTuples=getNumberOfTuples(); + stream << "Number of tuples : " << nbOfTuples << ". Number of components : " << nbOfCompo << "." << std::endl; + reprQuickOverviewData(stream,MAX_NB_OF_BYTE_IN_REPR); + } + else + stream << "Number of components : 0."; + } + else + stream << "*** No data allocated ****"; +} + +void DataArrayInt::reprQuickOverviewData(std::ostream& stream, std::size_t maxNbOfByteInRepr) const +{ + const int *data=begin(); + int nbOfTuples=getNumberOfTuples(); + int nbOfCompo=(int)_info_on_compo.size(); + std::ostringstream oss2; oss2 << "["; + std::string oss2Str(oss2.str()); + bool isFinished=true; + for(int i=0;i1) + { + oss2 << "("; + for(int j=0;jgetNumberOfComponents() != 1 + * \throw If any value of \a this can't be used as a valid index for + * [\a indArrBg, \a indArrEnd). + * + * \sa replaceOneValByInThis + */ +void DataArrayInt::transformWithIndArr(const int *indArrBg, const int *indArrEnd) +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("Call transformWithIndArr method on DataArrayInt with only one component, you can call 'rearrange' method before !"); + int nbElemsIn((int)std::distance(indArrBg,indArrEnd)),nbOfTuples(getNumberOfTuples()),*pt(getPointer()); + for(int i=0;i=0 && *ptgetNumberOfComponents() != 1. + * \throw If \a arrEnd - arrBg < 2. + * \throw If any value of \a this is not less than \a arrEnd[-1]. + */ +void DataArrayInt::splitByValueRange(const int *arrBg, const int *arrEnd, + DataArrayInt *& castArr, DataArrayInt *& rankInsideCast, DataArrayInt *& castsPresent) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("Call splitByValueRange method on DataArrayInt with only one component, you can call 'rearrange' method before !"); + int nbOfTuples=getNumberOfTuples(); + std::size_t nbOfCast=std::distance(arrBg,arrEnd); + if(nbOfCast<2) + throw INTERP_KERNEL::Exception("DataArrayInt::splitByValueRange : The input array giving the cast range values should be of size >=2 !"); + nbOfCast--; + const int *work=getConstPointer(); + typedef std::reverse_iterator rintstart; + rintstart bg(arrEnd);//OK no problem because size of 'arr' is greater or equal 2 + rintstart end2(arrBg); + MEDCouplingAutoRefCountObjectPtr ret1=DataArrayInt::New(); + MEDCouplingAutoRefCountObjectPtr ret2=DataArrayInt::New(); + MEDCouplingAutoRefCountObjectPtr ret3=DataArrayInt::New(); + ret1->alloc(nbOfTuples,1); + ret2->alloc(nbOfTuples,1); + int *ret1Ptr=ret1->getPointer(); + int *ret2Ptr=ret2->getPointer(); + std::set castsDetected; + for(int i=0;i(), work[i])); + std::size_t pos=std::distance(bg,res); + std::size_t pos2=nbOfCast-pos; + if(pos2alloc((int)castsDetected.size(),1); + std::copy(castsDetected.begin(),castsDetected.end(),ret3->getPointer()); + castArr=ret1.retn(); + rankInsideCast=ret2.retn(); + castsPresent=ret3.retn(); +} + +/*! + * This method look at \a this if it can be considered as a range defined by the 3-tuple ( \a strt , \a sttoopp , \a stteepp ). + * If false is returned the tuple must be ignored. If true is returned \a this can be considered by a range( \a strt , \a sttoopp , \a stteepp ). + * This method works only if \a this is allocated and single component. If not an exception will be thrown. + * + * \param [out] strt - the start of the range (included) if true is returned. + * \param [out] sttoopp - the end of the range (not included) if true is returned. + * \param [out] stteepp - the step of the range if true is returned. + * \return the verdict of the check. + * + * \sa DataArray::GetNumberOfItemGivenBES + */ +bool DataArrayInt::isRange(int& strt, int& sttoopp, int& stteepp) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::isRange : this must be single component array !"); + int nbTuples(getNumberOfTuples()); + if(nbTuples==0) + { strt=0; sttoopp=0; stteepp=1; return true; } + const int *pt(begin()); + strt=*pt; + if(nbTuples==1) + { sttoopp=strt+1; stteepp=1; return true; } + strt=*pt; sttoopp=pt[nbTuples-1]; + if(strt==sttoopp) + return false; + if(sttoopp>strt) + { + sttoopp++; + int a(sttoopp-1-strt),tmp(strt); + if(a%(nbTuples-1)!=0) + return false; + stteepp=a/(nbTuples-1); + for(int i=0;igetNumberOfComponents() != 1. + * \throw If any value of \a this array is not a valid index for \a indArrBg array. + * \throw If any value of \a indArrBg is not a valid index for \a this array. + */ +DataArrayInt *DataArrayInt::transformWithIndArrR(const int *indArrBg, const int *indArrEnd) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("Call transformWithIndArrR method on DataArrayInt with only one component, you can call 'rearrange' method before !"); + int nbElemsIn=(int)std::distance(indArrBg,indArrEnd); + int nbOfTuples=getNumberOfTuples(); + const int *pt=getConstPointer(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuples,1); + ret->fillWithValue(-1); + int *tmp=ret->getPointer(); + for(int i=0;i=0 && *pt=0 && pos + * \ref py_mcdataarrayint_invertarrayo2n2n2o "Here is a Python example". + * \endif + */ +DataArrayInt *DataArrayInt::invertArrayO2N2N2O(int newNbOfElem) const +{ + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(newNbOfElem,1); + int nbOfOldNodes=getNumberOfTuples(); + const int *old2New=getConstPointer(); + int *pt=ret->getPointer(); + for(int i=0;i!=nbOfOldNodes;i++) + { + int newp(old2New[i]); + if(newp!=-1) + { + if(newp>=0 && newp ret=DataArrayInt::New(); + ret->alloc(newNbOfElem,1); + int nbOfOldNodes=getNumberOfTuples(); + const int *old2New=getConstPointer(); + int *pt=ret->getPointer(); + for(int i=nbOfOldNodes-1;i>=0;i--) + { + int newp(old2New[i]); + if(newp!=-1) + { + if(newp>=0 && newp ret=DataArrayInt::New(); + ret->alloc(oldNbOfElem,1); + const int *new2Old=getConstPointer(); + int *pt=ret->getPointer(); + std::fill(pt,pt+oldNbOfElem,-1); + int nbOfNewElems=getNumberOfTuples(); + for(int i=0;i=0 && v a=deepCpy(); + MEDCouplingAutoRefCountObjectPtr b=other.deepCpy(); + a->sort(); + b->sort(); + return a->isEqualWithoutConsideringStr(*b); +} + +/*! + * This method compares content of input vector \a v and \a this. + * If for each id in \a this v[id]==True and for all other ids id2 not in \a this v[id2]==False, true is returned. + * For performance reasons \a this is expected to be sorted ascendingly. If not an exception will be thrown. + * + * \param [in] v - the vector of 'flags' to be compared with \a this. + * + * \throw If \a this is not sorted ascendingly. + * \throw If \a this has not exactly one component. + * \throw If \a this is not allocated. + */ +bool DataArrayInt::isFittingWith(const std::vector& v) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::isFittingWith : number of components of this should be equal to one !"); + const int *w(begin()),*end2(end()); + int refVal=-std::numeric_limits::max(); + int i=0; + std::vector::const_iterator it(v.begin()); + for(;it!=v.end();it++,i++) + { + if(*it) + { + if(w!=end2) + { + if(*w++==i) + { + if(i>refVal) + refVal=i; + else + { + std::ostringstream oss; oss << "DataArrayInt::isFittingWith : At pos #" << std::distance(begin(),w-1) << " this is not sorted ascendingly !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + else + return false; + } + else + return false; + } + } + return w==end2; +} + +/*! + * This method assumes that \a this has one component and is allocated. This method scans all tuples in \a this and for all tuple equal to \a val + * put True to the corresponding entry in \a vec. + * \a vec is expected to be with the same size than the number of tuples of \a this. + */ +void DataArrayInt::switchOnTupleEqualTo(int val, std::vector& vec) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::switchOnTupleEqualTo : number of components of this should be equal to one !"); + int nbOfTuples(getNumberOfTuples()); + if(nbOfTuples!=(int)vec.size()) + throw INTERP_KERNEL::Exception("DataArrayInt::switchOnTupleEqualTo : number of tuples of this should be equal to size of input vector of bool !"); + const int *pt(begin()); + for(int i=0;igetNumberOfComponents() != 1. + */ +void DataArrayInt::sort(bool asc) +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::sort : only supported with 'this' array with ONE component !"); + _mem.sort(asc); + declareAsNew(); +} + +/*! + * Computes for each tuple the sum of number of components values in the tuple and return it. + * + * \return DataArrayInt * - the new instance of DataArrayInt containing the + * same number of tuples as \a this array and one component. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If \a this is not allocated. + */ +DataArrayInt *DataArrayInt::sumPerTuple() const +{ + checkAllocated(); + int nbOfComp(getNumberOfComponents()),nbOfTuple(getNumberOfTuples()); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); + ret->alloc(nbOfTuple,1); + const int *src(getConstPointer()); + int *dest(ret->getPointer()); + for(int i=0;igetNumberOfComponents() < 1. + * \throw If \a this is not allocated. + */ +void DataArrayInt::reverse() +{ + checkAllocated(); + _mem.reverse(getNumberOfComponents()); + declareAsNew(); +} + +/*! + * Checks that \a this array is consistently **increasing** or **decreasing** in value. + * If not an exception is thrown. + * \param [in] increasing - if \a true, the array values should be increasing. + * \throw If sequence of values is not strictly monotonic in agreement with \a + * increasing arg. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a this is not allocated. + */ +void DataArrayInt::checkMonotonic(bool increasing) const +{ + if(!isMonotonic(increasing)) + { + if (increasing) + throw INTERP_KERNEL::Exception("DataArrayInt::checkMonotonic : 'this' is not INCREASING monotonic !"); + else + throw INTERP_KERNEL::Exception("DataArrayInt::checkMonotonic : 'this' is not DECREASING monotonic !"); + } +} + +/*! + * Checks that \a this array is consistently **increasing** or **decreasing** in value. + * \param [in] increasing - if \a true, array values should be increasing. + * \return bool - \a true if values change in accordance with \a increasing arg. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a this is not allocated. + */ +bool DataArrayInt::isMonotonic(bool increasing) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::isMonotonic : only supported with 'this' array with ONE component !"); + int nbOfElements=getNumberOfTuples(); + const int *ptr=getConstPointer(); + if(nbOfElements==0) + return true; + int ref=ptr[0]; + if(increasing) + { + for(int i=1;i=ref) + ref=ptr[i]; + else + return false; + } + } + else + { + for(int i=1;iref) + ref=ptr[i]; + else + return false; + } + } + else + { + for(int i=1;i other.getIJ(i,0) == this->getIJ(ret->getIJ(i),0). If such a permutation is + * not possible because some element in \a other is not in \a this, an exception is thrown. + * \param [in] other - an array to compute permutation to. + * \return DataArrayInt * - a new instance of DataArrayInt, which is a permutation array + * from \a this to \a other. The caller is to delete this array using decrRef() as it is + * no more needed. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a other->getNumberOfComponents() != 1. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples(). + * \throw If \a other includes a value which is not in \a this array. + * + * \if ENABLE_EXAMPLES + * \ref cpp_mcdataarrayint_buildpermutationarr "Here is a C++ example". + * + * \ref py_mcdataarrayint_buildpermutationarr "Here is a Python example". + * \endif + */ +DataArrayInt *DataArrayInt::buildPermutationArr(const DataArrayInt& other) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1 || other.getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::buildPermutationArr : 'this' and 'other' have to have exactly ONE component !"); + int nbTuple=getNumberOfTuples(); + other.checkAllocated(); + if(nbTuple!=other.getNumberOfTuples()) + throw INTERP_KERNEL::Exception("DataArrayInt::buildPermutationArr : 'this' and 'other' must have the same number of tuple !"); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbTuple,1); + ret->fillWithValue(-1); + const int *pt=getConstPointer(); + std::map mm; + for(int i=0;igetPointer(); + for(int i=0;i::const_iterator it=mm.find(pt[i]); + if(it==mm.end()) + { + std::ostringstream oss; oss << "DataArrayInt::buildPermutationArr : Arrays mismatch : element (" << pt[i] << ") in 'other' not findable in 'this' !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + retToFill[i]=(*it).second; + } + return ret.retn(); +} + +/*! + * Sets a C array to be used as raw data of \a this. The previously set info + * of components is retained and re-sized. + * For more info see \ref MEDCouplingArraySteps1. + * \param [in] array - the C array to be used as raw data of \a this. + * \param [in] ownership - if \a true, \a array will be deallocated at destruction of \a this. + * \param [in] type - specifies how to deallocate \a array. If \a type == ParaMEDMEM::CPP_DEALLOC, + * \c delete [] \c array; will be called. If \a type == ParaMEDMEM::C_DEALLOC, + * \c free(\c array ) will be called. + * \param [in] nbOfTuple - new number of tuples in \a this. + * \param [in] nbOfCompo - new number of components in \a this. + */ +void DataArrayInt::useArray(const int *array, bool ownership, DeallocType type, int nbOfTuple, int nbOfCompo) +{ + _info_on_compo.resize(nbOfCompo); + _mem.useArray(array,ownership,type,nbOfTuple*nbOfCompo); + declareAsNew(); +} + +void DataArrayInt::useExternalArrayWithRWAccess(const int *array, int nbOfTuple, int nbOfCompo) +{ + _info_on_compo.resize(nbOfCompo); + _mem.useExternalArrayWithRWAccess(array,nbOfTuple*nbOfCompo); + declareAsNew(); +} + +/*! + * Returns a new DataArrayInt holding the same values as \a this array but differently + * arranged in memory. If \a this array holds 2 components of 3 values: + * \f$ x_0,x_1,x_2,y_0,y_1,y_2 \f$, then the result array holds these values arranged + * as follows: \f$ x_0,y_0,x_1,y_1,x_2,y_2 \f$. + * \warning Do not confuse this method with transpose()! + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + */ +DataArrayInt *DataArrayInt::fromNoInterlace() const +{ + checkAllocated(); + if(_mem.isNull()) + throw INTERP_KERNEL::Exception("DataArrayInt::fromNoInterlace : Not defined array !"); + int *tab=_mem.fromNoInterlace(getNumberOfComponents()); + DataArrayInt *ret=DataArrayInt::New(); + ret->useArray(tab,true,C_DEALLOC,getNumberOfTuples(),getNumberOfComponents()); + return ret; +} + +/*! + * Returns a new DataArrayInt holding the same values as \a this array but differently + * arranged in memory. If \a this array holds 2 components of 3 values: + * \f$ x_0,y_0,x_1,y_1,x_2,y_2 \f$, then the result array holds these values arranged + * as follows: \f$ x_0,x_1,x_2,y_0,y_1,y_2 \f$. + * \warning Do not confuse this method with transpose()! + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + */ +DataArrayInt *DataArrayInt::toNoInterlace() const +{ + checkAllocated(); + if(_mem.isNull()) + throw INTERP_KERNEL::Exception("DataArrayInt::toNoInterlace : Not defined array !"); + int *tab=_mem.toNoInterlace(getNumberOfComponents()); + DataArrayInt *ret=DataArrayInt::New(); + ret->useArray(tab,true,C_DEALLOC,getNumberOfTuples(),getNumberOfComponents()); + return ret; +} + +/*! + * Permutes values of \a this array as required by \a old2New array. The values are + * permuted so that \c new[ \a old2New[ i ]] = \c old[ i ]. Number of tuples remains + * the same as in \c this one. + * If a permutation reduction is needed, substr() or selectByTupleId() should be used. + * For more info on renumbering see \ref numbering. + * \param [in] old2New - C array of length equal to \a this->getNumberOfTuples() + * giving a new position for i-th old value. + */ +void DataArrayInt::renumberInPlace(const int *old2New) +{ + checkAllocated(); + int nbTuples=getNumberOfTuples(); + int nbOfCompo=getNumberOfComponents(); + int *tmp=new int[nbTuples*nbOfCompo]; + const int *iptr=getConstPointer(); + for(int i=0;i=0 && vgetNumberOfTuples() + * giving a previous position of i-th new value. + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + */ +void DataArrayInt::renumberInPlaceR(const int *new2Old) +{ + checkAllocated(); + int nbTuples=getNumberOfTuples(); + int nbOfCompo=getNumberOfComponents(); + int *tmp=new int[nbTuples*nbOfCompo]; + const int *iptr=getConstPointer(); + for(int i=0;i=0 && vgetNumberOfTuples() + * giving a new position for i-th old value. + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + */ +DataArrayInt *DataArrayInt::renumber(const int *old2New) const +{ + checkAllocated(); + int nbTuples=getNumberOfTuples(); + int nbOfCompo=getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbTuples,nbOfCompo); + ret->copyStringInfoFrom(*this); + const int *iptr=getConstPointer(); + int *optr=ret->getPointer(); + for(int i=0;icopyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a copy of \a this array with values permuted as required by \a new2Old array. + * The values are permuted so that \c new[ i ] = \c old[ \a new2Old[ i ]]. Number of + * tuples in the result array remains the same as in \c this one. + * If a permutation reduction is needed, substr() or selectByTupleId() should be used. + * For more info on renumbering see \ref numbering. + * \param [in] new2Old - C array of length equal to \a this->getNumberOfTuples() + * giving a previous position of i-th new value. + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + */ +DataArrayInt *DataArrayInt::renumberR(const int *new2Old) const +{ + checkAllocated(); + int nbTuples=getNumberOfTuples(); + int nbOfCompo=getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbTuples,nbOfCompo); + ret->copyStringInfoFrom(*this); + const int *iptr=getConstPointer(); + int *optr=ret->getPointer(); + for(int i=0;icopyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a shorten and permuted copy of \a this array. The new DataArrayInt is + * of size \a newNbOfTuple and it's values are permuted as required by \a old2New array. + * The values are permuted so that \c new[ \a old2New[ i ]] = \c old[ i ] for all + * \a old2New[ i ] >= 0. In other words every i-th tuple in \a this array, for which + * \a old2New[ i ] is negative, is missing from the result array. + * For more info on renumbering see \ref numbering. + * \param [in] old2New - C array of length equal to \a this->getNumberOfTuples() + * giving a new position for i-th old tuple and giving negative position for + * for i-th old tuple that should be omitted. + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + */ +DataArrayInt *DataArrayInt::renumberAndReduce(const int *old2New, int newNbOfTuple) const +{ + checkAllocated(); + int nbTuples=getNumberOfTuples(); + int nbOfCompo=getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(newNbOfTuple,nbOfCompo); + const int *iptr=getConstPointer(); + int *optr=ret->getPointer(); + for(int i=0;i=0) + std::copy(iptr+i*nbOfCompo,iptr+(i+1)*nbOfCompo,optr+w*nbOfCompo); + } + ret->copyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a shorten and permuted copy of \a this array. The new DataArrayInt is + * of size \a new2OldEnd - \a new2OldBg and it's values are permuted as required by + * \a new2OldBg array. + * The values are permuted so that \c new[ i ] = \c old[ \a new2OldBg[ i ]]. + * This method is equivalent to renumberAndReduce() except that convention in input is + * \c new2old and \b not \c old2new. + * For more info on renumbering see \ref numbering. + * \param [in] new2OldBg - pointer to the beginning of a permutation array that gives a + * tuple index in \a this array to fill the i-th tuple in the new array. + * \param [in] new2OldEnd - specifies the end of the permutation array that starts at + * \a new2OldBg, so that pointer to a tuple index (\a pi) varies as this: + * \a new2OldBg <= \a pi < \a new2OldEnd. + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + */ +DataArrayInt *DataArrayInt::selectByTupleId(const int *new2OldBg, const int *new2OldEnd) const +{ + checkAllocated(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + int nbComp=getNumberOfComponents(); + ret->alloc((int)std::distance(new2OldBg,new2OldEnd),nbComp); + ret->copyStringInfoFrom(*this); + int *pt=ret->getPointer(); + const int *srcPt=getConstPointer(); + int i=0; + for(const int *w=new2OldBg;w!=new2OldEnd;w++,i++) + std::copy(srcPt+(*w)*nbComp,srcPt+((*w)+1)*nbComp,pt+i*nbComp); + ret->copyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a shorten and permuted copy of \a this array. The new DataArrayInt is + * of size \a new2OldEnd - \a new2OldBg and it's values are permuted as required by + * \a new2OldBg array. + * The values are permuted so that \c new[ i ] = \c old[ \a new2OldBg[ i ]]. + * This method is equivalent to renumberAndReduce() except that convention in input is + * \c new2old and \b not \c old2new. + * This method is equivalent to selectByTupleId() except that it prevents coping data + * from behind the end of \a this array. + * For more info on renumbering see \ref numbering. + * \param [in] new2OldBg - pointer to the beginning of a permutation array that gives a + * tuple index in \a this array to fill the i-th tuple in the new array. + * \param [in] new2OldEnd - specifies the end of the permutation array that starts at + * \a new2OldBg, so that pointer to a tuple index (\a pi) varies as this: + * \a new2OldBg <= \a pi < \a new2OldEnd. + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a new2OldEnd - \a new2OldBg > \a this->getNumberOfTuples(). + */ +DataArrayInt *DataArrayInt::selectByTupleIdSafe(const int *new2OldBg, const int *new2OldEnd) const +{ + checkAllocated(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + int nbComp=getNumberOfComponents(); + int oldNbOfTuples=getNumberOfTuples(); + ret->alloc((int)std::distance(new2OldBg,new2OldEnd),nbComp); + ret->copyStringInfoFrom(*this); + int *pt=ret->getPointer(); + const int *srcPt=getConstPointer(); + int i=0; + for(const int *w=new2OldBg;w!=new2OldEnd;w++,i++) + if(*w>=0 && *wgetNumberOfTuples) !"); + ret->copyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a shorten copy of \a this array. The new DataArrayInt contains every + * (\a bg + \c i * \a step)-th tuple of \a this array located before the \a end2-th + * tuple. Indices of the selected tuples are the same as ones returned by the Python + * command \c range( \a bg, \a end2, \a step ). + * This method is equivalent to selectByTupleIdSafe() except that the input array is + * not constructed explicitly. + * For more info on renumbering see \ref numbering. + * \param [in] bg - index of the first tuple to copy from \a this array. + * \param [in] end2 - index of the tuple before which the tuples to copy are located. + * \param [in] step - index increment to get index of the next tuple to copy. + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + * \sa DataArrayInt::substr. + */ +DataArrayInt *DataArrayInt::selectByTupleId2(int bg, int end2, int step) const +{ + checkAllocated(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + int nbComp=getNumberOfComponents(); + int newNbOfTuples=GetNumberOfItemGivenBESRelative(bg,end2,step,"DataArrayInt::selectByTupleId2 : "); + ret->alloc(newNbOfTuples,nbComp); + int *pt=ret->getPointer(); + const int *srcPt=getConstPointer()+bg*nbComp; + for(int i=0;icopyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a shorten copy of \a this array. The new DataArrayInt contains ranges + * of tuples specified by \a ranges parameter. + * For more info on renumbering see \ref numbering. + * \param [in] ranges - std::vector of std::pair's each of which defines a range + * of tuples in [\c begin,\c end) format. + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a end < \a begin. + * \throw If \a end > \a this->getNumberOfTuples(). + * \throw If \a this is not allocated. + */ +DataArray *DataArrayInt::selectByTupleRanges(const std::vector >& ranges) const +{ + checkAllocated(); + int nbOfComp=getNumberOfComponents(); + int nbOfTuplesThis=getNumberOfTuples(); + if(ranges.empty()) + { + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(0,nbOfComp); + ret->copyStringInfoFrom(*this); + return ret.retn(); + } + int ref=ranges.front().first; + int nbOfTuples=0; + bool isIncreasing=true; + for(std::vector >::const_iterator it=ranges.begin();it!=ranges.end();it++) + { + if((*it).first<=(*it).second) + { + if((*it).first>=0 && (*it).second<=nbOfTuplesThis) + { + nbOfTuples+=(*it).second-(*it).first; + if(isIncreasing) + isIncreasing=ref<=(*it).first; + ref=(*it).second; + } + else + { + std::ostringstream oss; oss << "DataArrayInt::selectByTupleRanges : on range #" << std::distance(ranges.begin(),it); + oss << " (" << (*it).first << "," << (*it).second << ") is greater than number of tuples of this :" << nbOfTuples << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + else + { + std::ostringstream oss; oss << "DataArrayInt::selectByTupleRanges : on range #" << std::distance(ranges.begin(),it); + oss << " (" << (*it).first << "," << (*it).second << ") end is before begin !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + if(isIncreasing && nbOfTuplesThis==nbOfTuples) + return deepCpy(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuples,nbOfComp); + ret->copyStringInfoFrom(*this); + const int *src=getConstPointer(); + int *work=ret->getPointer(); + for(std::vector >::const_iterator it=ranges.begin();it!=ranges.end();it++) + work=std::copy(src+(*it).first*nbOfComp,src+(*it).second*nbOfComp,work); + return ret.retn(); +} + +/*! + * Returns a new DataArrayInt containing a renumbering map in "Old to New" mode. + * This map, if applied to \a this array, would make it sorted. For example, if + * \a this array contents are [9,10,0,6,4,11,3,7] then the contents of the result array + * are [5,6,0,3,2,7,1,4]; if this result array (\a res) is used as an argument in call + * \a this->renumber(\a res) then the returned array contains [0,3,4,6,7,9,10,11]. + * This method is useful for renumbering (in MED file for example). For more info + * on renumbering see \ref numbering. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If there are equal values in \a this array. + */ +DataArrayInt *DataArrayInt::checkAndPreparePermutation() const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::checkAndPreparePermutation : number of components must == 1 !"); + int nbTuples=getNumberOfTuples(); + const int *pt=getConstPointer(); + int *pt2=CheckAndPreparePermutation(pt,pt+nbTuples); + DataArrayInt *ret=DataArrayInt::New(); + ret->useArray(pt2,true,C_DEALLOC,nbTuples,1); + return ret; +} + +/*! + * This method tries to find the permutation to apply to the first input \a ids1 to obtain the same array (without considering strings informations) the second + * input array \a ids2. + * \a ids1 and \a ids2 are expected to be both a list of ids (both with number of components equal to one) not sorted and with values that can be negative. + * This method will throw an exception is no such permutation array can be obtained. It is typically the case if there is some ids in \a ids1 not in \a ids2 or + * inversely. + * In case of success (no throw) : \c ids1->renumber(ret)->isEqual(ids2) where \a ret is the return of this method. + * + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If either ids1 or ids2 is null not allocated or not with one components. + * + */ +DataArrayInt *DataArrayInt::FindPermutationFromFirstToSecond(const DataArrayInt *ids1, const DataArrayInt *ids2) +{ + if(!ids1 || !ids2) + throw INTERP_KERNEL::Exception("DataArrayInt::FindPermutationFromFirstToSecond : the two input arrays must be not null !"); + if(!ids1->isAllocated() || !ids2->isAllocated()) + throw INTERP_KERNEL::Exception("DataArrayInt::FindPermutationFromFirstToSecond : the two input arrays must be allocated !"); + if(ids1->getNumberOfComponents()!=1 || ids2->getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::FindPermutationFromFirstToSecond : the two input arrays have exactly one component !"); + if(ids1->getNumberOfTuples()!=ids2->getNumberOfTuples()) + { + std::ostringstream oss; oss << "DataArrayInt::FindPermutationFromFirstToSecond : first array has " << ids1->getNumberOfTuples() << " tuples and the second one " << ids2->getNumberOfTuples() << " tuples ! No chance to find a permutation between the 2 arrays !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + MEDCouplingAutoRefCountObjectPtr p1(ids1->deepCpy()); + MEDCouplingAutoRefCountObjectPtr p2(ids2->deepCpy()); + p1->sort(true); p2->sort(true); + if(!p1->isEqualWithoutConsideringStr(*p2)) + throw INTERP_KERNEL::Exception("DataArrayInt::FindPermutationFromFirstToSecond : the two arrays are not lying on same ids ! Impossible to find a permutation between the 2 arrays !"); + p1=ids1->checkAndPreparePermutation(); + p2=ids2->checkAndPreparePermutation(); + p2=p2->invertArrayO2N2N2O(p2->getNumberOfTuples()); + p2=p2->selectByTupleIdSafe(p1->begin(),p1->end()); + return p2.retn(); +} + +/*! + * Returns two arrays describing a surjective mapping from \a this set of values (\a A) + * onto a set of values of size \a targetNb (\a B). The surjective function is + * \a B[ \a A[ i ]] = i. That is to say that for each \a id in [0,\a targetNb), where \a + * targetNb < \a this->getNumberOfTuples(), there exists at least one tupleId (\a tid) so + * that this->getIJ( tid, 0 ) == id.
+ * The first of out arrays returns indices of elements of \a this array, grouped by their + * place in the set \a B. The second out array is the index of the first one; it shows how + * many elements of \a A are mapped into each element of \a B.
+ * For more info on + * mapping and its usage in renumbering see \ref numbering.
+ * \b Example: + * - \a this: [0,3,2,3,2,2,1,2] + * - \a targetNb: 4 + * - \a arr: [0, 6, 2,4,5,7, 1,3] + * - \a arrI: [0,1,2,6,8] + * + * This result means:
+ * the element of \a B 0 encounters within \a A once (\a arrI[ 0+1 ] - \a arrI[ 0 ]) and + * its index within \a A is 0 ( \a arr[ 0:1 ] == \a arr[ \a arrI[ 0 ] : \a arrI[ 0+1 ]]);
+ * the element of \a B 2 encounters within \a A 4 times (\a arrI[ 2+1 ] - \a arrI[ 2 ]) and + * its indices within \a A are [2,4,5,7] ( \a arr[ 2:6 ] == \a arr[ \a arrI[ 2 ] : + * \a arrI[ 2+1 ]]);
etc. + * \param [in] targetNb - the size of the set \a B. \a targetNb must be equal or more + * than the maximal value of \a A. + * \param [out] arr - a new instance of DataArrayInt returning indices of + * elements of \a this, grouped by their place in the set \a B. The caller is to delete + * this array using decrRef() as it is no more needed. + * \param [out] arrI - a new instance of DataArrayInt returning size of groups of equal + * elements of \a this. The caller is to delete this array using decrRef() as it + * is no more needed. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If any value in \a this is more or equal to \a targetNb. + */ +void DataArrayInt::changeSurjectiveFormat(int targetNb, DataArrayInt *&arr, DataArrayInt *&arrI) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::changeSurjectiveFormat : number of components must == 1 !"); + int nbOfTuples=getNumberOfTuples(); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); + MEDCouplingAutoRefCountObjectPtr retI(DataArrayInt::New()); + retI->alloc(targetNb+1,1); + const int *input=getConstPointer(); + std::vector< std::vector > tmp(targetNb); + for(int i=0;i=0 && tmp2getPointer(); + *retIPtr=0; + for(std::vector< std::vector >::const_iterator it1=tmp.begin();it1!=tmp.end();it1++,retIPtr++) + retIPtr[1]=retIPtr[0]+(int)((*it1).size()); + if(nbOfTuples!=retI->getIJ(targetNb,0)) + throw INTERP_KERNEL::Exception("DataArrayInt::changeSurjectiveFormat : big problem should never happen !"); + ret->alloc(nbOfTuples,1); + int *retPtr=ret->getPointer(); + for(std::vector< std::vector >::const_iterator it1=tmp.begin();it1!=tmp.end();it1++) + retPtr=std::copy((*it1).begin(),(*it1).end(),retPtr); + arr=ret.retn(); + arrI=retI.retn(); +} + + +/*! + * Returns a new DataArrayInt containing a renumbering map in "Old to New" mode computed + * from a zip representation of a surjective format (returned e.g. by + * \ref ParaMEDMEM::DataArrayDouble::findCommonTuples() "DataArrayDouble::findCommonTuples()" + * for example). The result array minimizes the permutation.
+ * For more info on renumbering see \ref numbering.
+ * \b Example:
+ * - \a nbOfOldTuples: 10 + * - \a arr : [0,3, 5,7,9] + * - \a arrIBg : [0,2,5] + * - \a newNbOfTuples: 7 + * - result array : [0,1,2,0,3,4,5,4,6,4] + * + * \param [in] nbOfOldTuples - number of tuples in the initial array \a arr. + * \param [in] arr - the array of tuple indices grouped by \a arrIBg array. + * \param [in] arrIBg - the array dividing all indices stored in \a arr into groups of + * (indices of) equal values. Its every element (except the last one) points to + * the first element of a group of equal values. + * \param [in] arrIEnd - specifies the end of \a arrIBg, so that the last element of \a + * arrIBg is \a arrIEnd[ -1 ]. + * \param [out] newNbOfTuples - number of tuples after surjection application. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If any value of \a arr breaks condition ( 0 <= \a arr[ i ] < \a nbOfOldTuples ). + */ +DataArrayInt *DataArrayInt::BuildOld2NewArrayFromSurjectiveFormat2(int nbOfOldTuples, const int *arr, const int *arrIBg, const int *arrIEnd, int &newNbOfTuples) +{ + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfOldTuples,1); + int *pt=ret->getPointer(); + std::fill(pt,pt+nbOfOldTuples,-1); + int nbOfGrps=((int)std::distance(arrIBg,arrIEnd))-1; + const int *cIPtr=arrIBg; + for(int i=0;i=0 && arr[j] + * \b Example:
+ * - \a this: [2,0,1,1,0,1,2,0,1,1,0,0] + * - result: [10,0,5,6,1,7,11,2,8,9,3,4] + * - after applying result to \a this: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2] + * + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + */ +DataArrayInt *DataArrayInt::buildPermArrPerLevel() const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::buildPermArrPerLevel : number of components must == 1 !"); + int nbOfTuples=getNumberOfTuples(); + const int *pt=getConstPointer(); + std::map m; + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuples,1); + int *opt=ret->getPointer(); + for(int i=0;i::iterator it=m.find(val); + if(it!=m.end()) + { + *opt=(*it).second; + (*it).second++; + } + else + { + *opt=0; + m.insert(std::pair(val,1)); + } + } + int sum=0; + for(std::map::iterator it=m.begin();it!=m.end();it++) + { + int vt=(*it).second; + (*it).second=sum; + sum+=vt; + } + pt=getConstPointer(); + opt=ret->getPointer(); + for(int i=0;igetNumberOfTuples()) + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \sa isIdentity2 + */ +bool DataArrayInt::isIdentity() const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + return false; + int nbOfTuples(getNumberOfTuples()); + const int *pt=getConstPointer(); + for(int i=0;igetNumberOfTuples()) and if \a this has \a sizeExpected tuples in it. + * + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \sa isIdentity + */ +bool DataArrayInt::isIdentity2(int sizeExpected) const +{ + bool ret0(isIdentity()); + if(!ret0) + return false; + return getNumberOfTuples()==sizeExpected; +} + +/*! + * Checks if all values in \a this array are equal to \a val. + * \param [in] val - value to check equality of array values to. + * \return bool - \a true if all values are \a val. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1 + */ +bool DataArrayInt::isUniform(int val) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::isUniform : must be applied on DataArrayInt with only one component, you can call 'rearrange' method before !"); + int nbOfTuples=getNumberOfTuples(); + const int *w=getConstPointer(); + const int *end2=w+nbOfTuples; + for(;w!=end2;w++) + if(*w!=val) + return false; + return true; +} + +/*! + * Creates a new DataArrayDouble and assigns all (textual and numerical) data of \a this + * array to the new one. + * \return DataArrayDouble * - the new instance of DataArrayInt. + */ +DataArrayDouble *DataArrayInt::convertToDblArr() const +{ + checkAllocated(); + DataArrayDouble *ret=DataArrayDouble::New(); + ret->alloc(getNumberOfTuples(),getNumberOfComponents()); + std::size_t nbOfVals=getNbOfElems(); + const int *src=getConstPointer(); + double *dest=ret->getPointer(); + std::copy(src,src+nbOfVals,dest); + ret->copyStringInfoFrom(*this); + return ret; +} + +/*! + * Returns a shorten copy of \a this array. The new DataArrayInt contains all + * tuples starting from the \a tupleIdBg-th tuple and including all tuples located before + * the \a tupleIdEnd-th one. This methods has a similar behavior as std::string::substr(). + * This method is a specialization of selectByTupleId2(). + * \param [in] tupleIdBg - index of the first tuple to copy from \a this array. + * \param [in] tupleIdEnd - index of the tuple before which the tuples to copy are located. + * If \a tupleIdEnd == -1, all the tuples till the end of \a this array are copied. + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a tupleIdBg < 0. + * \throw If \a tupleIdBg > \a this->getNumberOfTuples(). + \throw If \a tupleIdEnd != -1 && \a tupleIdEnd < \a this->getNumberOfTuples(). + * \sa DataArrayInt::selectByTupleId2 + */ +DataArrayInt *DataArrayInt::substr(int tupleIdBg, int tupleIdEnd) const +{ + checkAllocated(); + int nbt=getNumberOfTuples(); + if(tupleIdBg<0) + throw INTERP_KERNEL::Exception("DataArrayInt::substr : The tupleIdBg parameter must be greater than 0 !"); + if(tupleIdBg>nbt) + throw INTERP_KERNEL::Exception("DataArrayInt::substr : The tupleIdBg parameter is greater than number of tuples !"); + int trueEnd=tupleIdEnd; + if(tupleIdEnd!=-1) + { + if(tupleIdEnd>nbt) + throw INTERP_KERNEL::Exception("DataArrayInt::substr : The tupleIdBg parameter is greater or equal than number of tuples !"); + } + else + trueEnd=nbt; + int nbComp=getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(trueEnd-tupleIdBg,nbComp); + ret->copyStringInfoFrom(*this); + std::copy(getConstPointer()+tupleIdBg*nbComp,getConstPointer()+trueEnd*nbComp,ret->getPointer()); + return ret.retn(); +} + +/*! + * Changes the number of components within \a this array so that its raw data **does + * not** change, instead splitting this data into tuples changes. + * \warning This method erases all (name and unit) component info set before! + * \param [in] newNbOfComp - number of components for \a this array to have. + * \throw If \a this is not allocated + * \throw If getNbOfElems() % \a newNbOfCompo != 0. + * \throw If \a newNbOfCompo is lower than 1. + * \throw If the rearrange method would lead to a number of tuples higher than 2147483647 (maximal capacity of int32 !). + * \warning This method erases all (name and unit) component info set before! + */ +void DataArrayInt::rearrange(int newNbOfCompo) +{ + checkAllocated(); + if(newNbOfCompo<1) + throw INTERP_KERNEL::Exception("DataArrayInt::rearrange : input newNbOfCompo must be > 0 !"); + std::size_t nbOfElems=getNbOfElems(); + if(nbOfElems%newNbOfCompo!=0) + throw INTERP_KERNEL::Exception("DataArrayInt::rearrange : nbOfElems%newNbOfCompo!=0 !"); + if(nbOfElems/newNbOfCompo>(std::size_t)std::numeric_limits::max()) + throw INTERP_KERNEL::Exception("DataArrayInt::rearrange : the rearrangement leads to too high number of tuples (> 2147483647) !"); + _info_on_compo.clear(); + _info_on_compo.resize(newNbOfCompo); + declareAsNew(); +} + +/*! + * Changes the number of components within \a this array to be equal to its number + * of tuples, and inversely its number of tuples to become equal to its number of + * components. So that its raw data **does not** change, instead splitting this + * data into tuples changes. + * \warning This method erases all (name and unit) component info set before! + * \warning Do not confuse this method with fromNoInterlace() and toNoInterlace()! + * \throw If \a this is not allocated. + * \sa rearrange() + */ +void DataArrayInt::transpose() +{ + checkAllocated(); + int nbOfTuples=getNumberOfTuples(); + rearrange(nbOfTuples); +} + +/*! + * Returns a shorten or extended copy of \a this array. If \a newNbOfComp is less + * than \a this->getNumberOfComponents() then the result array is shorten as each tuple + * is truncated to have \a newNbOfComp components, keeping first components. If \a + * newNbOfComp is more than \a this->getNumberOfComponents() then the result array is + * expanded as each tuple is populated with \a dftValue to have \a newNbOfComp + * components. + * \param [in] newNbOfComp - number of components for the new array to have. + * \param [in] dftValue - value assigned to new values added to the new array. + * \return DataArrayDouble * - the new instance of DataArrayDouble that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + */ +DataArrayInt *DataArrayInt::changeNbOfComponents(int newNbOfComp, int dftValue) const +{ + checkAllocated(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(getNumberOfTuples(),newNbOfComp); + const int *oldc=getConstPointer(); + int *nc=ret->getPointer(); + int nbOfTuples=getNumberOfTuples(); + int oldNbOfComp=getNumberOfComponents(); + int dim=std::min(oldNbOfComp,newNbOfComp); + for(int i=0;isetName(getName()); + for(int i=0;isetInfoOnComponent(i,getInfoOnComponent(i)); + ret->setName(getName()); + return ret.retn(); +} + +/*! + * Changes number of tuples in the array. If the new number of tuples is smaller + * than the current number the array is truncated, otherwise the array is extended. + * \param [in] nbOfTuples - new number of tuples. + * \throw If \a this is not allocated. + * \throw If \a nbOfTuples is negative. + */ +void DataArrayInt::reAlloc(int nbOfTuples) +{ + if(nbOfTuples<0) + throw INTERP_KERNEL::Exception("DataArrayInt::reAlloc : input new number of tuples should be >=0 !"); + checkAllocated(); + _mem.reAlloc(getNumberOfComponents()*(std::size_t)nbOfTuples); + declareAsNew(); +} + + +/*! + * Returns a copy of \a this array composed of selected components. + * The new DataArrayInt has the same number of tuples but includes components + * specified by \a compoIds parameter. So that getNbOfElems() of the result array + * can be either less, same or more than \a this->getNbOfElems(). + * \param [in] compoIds - sequence of zero based indices of components to include + * into the new array. + * \return DataArrayInt * - the new instance of DataArrayInt that the caller + * is to delete using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + * \throw If a component index (\a i) is not valid: + * \a i < 0 || \a i >= \a this->getNumberOfComponents(). + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarrayint_keepselectedcomponents "Here is a Python example". + * \endif + */ +DataArrayInt *DataArrayInt::keepSelectedComponents(const std::vector& compoIds) const +{ + checkAllocated(); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); + int newNbOfCompo=(int)compoIds.size(); + int oldNbOfCompo=getNumberOfComponents(); + for(std::vector::const_iterator it=compoIds.begin();it!=compoIds.end();it++) + DataArray::CheckValueInRange(oldNbOfCompo,(*it),"keepSelectedComponents invalid requested component"); + int nbOfTuples=getNumberOfTuples(); + ret->alloc(nbOfTuples,newNbOfCompo); + ret->copyPartOfStringInfoFrom(*this,compoIds); + const int *oldc=getConstPointer(); + int *nc=ret->getPointer(); + for(int i=0;icheckAllocated(); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples!=other->getNumberOfTuples()) + throw INTERP_KERNEL::Exception("DataArrayInt::meldWith : mismatch of number of tuples !"); + int nbOfComp1=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + int *newArr=(int *)malloc(nbOfTuples*(nbOfComp1+nbOfComp2)*sizeof(int)); + int *w=newArr; + const int *inp1=getConstPointer(); + const int *inp2=other->getConstPointer(); + for(int i=0;i compIds(nbOfComp2); + for(int i=0;igetNumberOfComponents(). + * \throw If \a compoIds[i] < 0 or \a compoIds[i] > \a this->getNumberOfComponents(). + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarrayint_setselectedcomponents "Here is a Python example". + * \endif + */ +void DataArrayInt::setSelectedComponents(const DataArrayInt *a, const std::vector& compoIds) +{ + if(!a) + throw INTERP_KERNEL::Exception("DataArrayInt::setSelectedComponents : input DataArrayInt is NULL !"); + checkAllocated(); + a->checkAllocated(); + copyPartOfStringInfoFrom2(compoIds,*a); + std::size_t partOfCompoSz=compoIds.size(); + int nbOfCompo=getNumberOfComponents(); + int nbOfTuples=std::min(getNumberOfTuples(),a->getNumberOfTuples()); + const int *ac=a->getConstPointer(); + int *nc=getPointer(); + for(int i=0;igetNumberOfComponents() + * must be equal to the number of columns to assign to, else an + * exception is thrown; if \a false, then it is only required that \a + * a->getNbOfElems() equals to number of values to assign to (this condition + * must be respected even if \a strictCompoCompare is \a true). The number of + * values to assign to is given by following Python expression: + * \a nbTargetValues = + * \c len(\c range(\a bgTuples,\a endTuples,\a stepTuples)) * + * \c len(\c range(\a bgComp,\a endComp,\a stepComp)). + * \throw If \a a is NULL. + * \throw If \a a is not allocated. + * \throw If \a this is not allocated. + * \throw If parameters specifying tuples and components to assign to do not give a + * non-empty range of increasing indices. + * \throw If \a a->getNbOfElems() != \a nbTargetValues. + * \throw If \a strictCompoCompare == \a true && \a a->getNumberOfComponents() != + * \c len(\c range(\a bgComp,\a endComp,\a stepComp)). + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarrayint_setpartofvalues1 "Here is a Python example". + * \endif + */ +void DataArrayInt::setPartOfValues1(const DataArrayInt *a, int bgTuples, int endTuples, int stepTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare) +{ + if(!a) + throw INTERP_KERNEL::Exception("DataArrayInt::setPartOfValues1 : DataArrayInt pointer in input is NULL !"); + const char msg[]="DataArrayInt::setPartOfValues1"; + checkAllocated(); + a->checkAllocated(); + int newNbOfTuples=DataArray::GetNumberOfItemGivenBES(bgTuples,endTuples,stepTuples,msg); + int newNbOfComp=DataArray::GetNumberOfItemGivenBES(bgComp,endComp,stepComp,msg); + int nbComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + DataArray::CheckValueInRangeEx(nbOfTuples,bgTuples,endTuples,"invalid tuple value"); + DataArray::CheckValueInRangeEx(nbComp,bgComp,endComp,"invalid component value"); + bool assignTech=true; + if(a->getNbOfElems()==(std::size_t)newNbOfTuples*newNbOfComp) + { + if(strictCompoCompare) + a->checkNbOfTuplesAndComp(newNbOfTuples,newNbOfComp,msg); + } + else + { + a->checkNbOfTuplesAndComp(1,newNbOfComp,msg); + assignTech=false; + } + int *pt=getPointer()+bgTuples*nbComp+bgComp; + const int *srcPt=a->getConstPointer(); + if(assignTech) + { + for(int i=0;igetNbOfElems() equals to number of values to assign to, then every value + * of \a a is assigned to its own location within \a this array. + * - If \a a includes one tuple, then all values of \a a are assigned to the specified + * components of every specified tuple of \a this array. In this mode it is required + * that \a a->getNumberOfComponents() equals to the number of specified components. + * + * \param [in] a - the array to copy values from. + * \param [in] bgTuples - pointer to an array of tuple indices of \a this array to + * assign values of \a a to. + * \param [in] endTuples - specifies the end of the array \a bgTuples, so that + * pointer to a tuple index (pi) varies as this: + * \a bgTuples <= \a pi < \a endTuples. + * \param [in] bgComp - pointer to an array of component indices of \a this array to + * assign values of \a a to. + * \param [in] endComp - specifies the end of the array \a bgTuples, so that + * pointer to a component index (pi) varies as this: + * \a bgComp <= \a pi < \a endComp. + * \param [in] strictCompoCompare - this parameter is checked only if the + * *mode of usage* is the first; if it is \a true (default), + * then \a a->getNumberOfComponents() must be equal + * to the number of specified columns, else this is not required. + * \throw If \a a is NULL. + * \throw If \a a is not allocated. + * \throw If \a this is not allocated. + * \throw If any index of tuple/component given by bgTuples / bgComp is + * out of a valid range for \a this array. + * \throw In the first *mode of usage*, if strictCompoCompare == true and + * if a->getNumberOfComponents() != (endComp - bgComp) . + * \throw In the second *mode of usage*, if \a a->getNumberOfTuples() != 1 or + * a->getNumberOfComponents() != (endComp - bgComp). + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarrayint_setpartofvalues2 "Here is a Python example". + * \endif + */ +void DataArrayInt::setPartOfValues2(const DataArrayInt *a, const int *bgTuples, const int *endTuples, const int *bgComp, const int *endComp, bool strictCompoCompare) +{ + if(!a) + throw INTERP_KERNEL::Exception("DataArrayInt::setPartOfValues2 : DataArrayInt pointer in input is NULL !"); + const char msg[]="DataArrayInt::setPartOfValues2"; + checkAllocated(); + a->checkAllocated(); + int nbComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + for(const int *z=bgComp;z!=endComp;z++) + DataArray::CheckValueInRange(nbComp,*z,"invalid component id"); + int newNbOfTuples=(int)std::distance(bgTuples,endTuples); + int newNbOfComp=(int)std::distance(bgComp,endComp); + bool assignTech=true; + if(a->getNbOfElems()==(std::size_t)newNbOfTuples*newNbOfComp) + { + if(strictCompoCompare) + a->checkNbOfTuplesAndComp(newNbOfTuples,newNbOfComp,msg); + } + else + { + a->checkNbOfTuplesAndComp(1,newNbOfComp,msg); + assignTech=false; + } + int *pt=getPointer(); + const int *srcPt=a->getConstPointer(); + if(assignTech) + { + for(const int *w=bgTuples;w!=endTuples;w++) + { + DataArray::CheckValueInRange(nbOfTuples,*w,"invalid tuple id"); + for(const int *z=bgComp;z!=endComp;z++,srcPt++) + { + pt[(std::size_t)(*w)*nbComp+(*z)]=*srcPt; + } + } + } + else + { + for(const int *w=bgTuples;w!=endTuples;w++) + { + const int *srcPt2=srcPt; + DataArray::CheckValueInRange(nbOfTuples,*w,"invalid tuple id"); + for(const int *z=bgComp;z!=endComp;z++,srcPt2++) + { + pt[(std::size_t)(*w)*nbComp+(*z)]=*srcPt2; + } + } + } +} + +/*! + * Assign a given value to values at specified tuples and components of \a this array. + * The tuples and components to assign to are defined by C arrays of indices. + * \param [in] a - the value to assign. + * \param [in] bgTuples - pointer to an array of tuple indices of \a this array to + * assign \a a to. + * \param [in] endTuples - specifies the end of the array \a bgTuples, so that + * pointer to a tuple index (\a pi) varies as this: + * \a bgTuples <= \a pi < \a endTuples. + * \param [in] bgComp - pointer to an array of component indices of \a this array to + * assign \a a to. + * \param [in] endComp - specifies the end of the array \a bgTuples, so that + * pointer to a component index (\a pi) varies as this: + * \a bgComp <= \a pi < \a endComp. + * \throw If \a this is not allocated. + * \throw If any index of tuple/component given by bgTuples / bgComp is + * out of a valid range for \a this array. + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarrayint_setpartofvaluessimple2 "Here is a Python example". + * \endif + */ +void DataArrayInt::setPartOfValuesSimple2(int a, const int *bgTuples, const int *endTuples, const int *bgComp, const int *endComp) +{ + checkAllocated(); + int nbComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + for(const int *z=bgComp;z!=endComp;z++) + DataArray::CheckValueInRange(nbComp,*z,"invalid component id"); + int *pt=getPointer(); + for(const int *w=bgTuples;w!=endTuples;w++) + for(const int *z=bgComp;z!=endComp;z++) + { + DataArray::CheckValueInRange(nbOfTuples,*w,"invalid tuple id"); + pt[(std::size_t)(*w)*nbComp+(*z)]=a; + } +} + +/*! + * Copy all values from another DataArrayInt (\a a) into specified tuples and + * components of \a this array. Textual data is not copied. + * The tuples to assign to are defined by a C array of indices. + * The components to assign to are defined by three values similar to parameters of + * the Python function \c range(\c start,\c stop,\c step). + * There are two *modes of usage*: + * - If \a a->getNbOfElems() equals to number of values to assign to, then every value + * of \a a is assigned to its own location within \a this array. + * - If \a a includes one tuple, then all values of \a a are assigned to the specified + * components of every specified tuple of \a this array. In this mode it is required + * that \a a->getNumberOfComponents() equals to the number of specified components. + * + * \param [in] a - the array to copy values from. + * \param [in] bgTuples - pointer to an array of tuple indices of \a this array to + * assign values of \a a to. + * \param [in] endTuples - specifies the end of the array \a bgTuples, so that + * pointer to a tuple index (pi) varies as this: + * \a bgTuples <= \a pi < \a endTuples. + * \param [in] bgComp - index of the first component of \a this array to assign to. + * \param [in] endComp - index of the component before which the components to assign + * to are located. + * \param [in] stepComp - index increment to get index of the next component to assign to. + * \param [in] strictCompoCompare - this parameter is checked only in the first + * *mode of usage*; if \a strictCompoCompare is \a true (default), + * then \a a->getNumberOfComponents() must be equal + * to the number of specified columns, else this is not required. + * \throw If \a a is NULL. + * \throw If \a a is not allocated. + * \throw If \a this is not allocated. + * \throw If any index of tuple given by \a bgTuples is out of a valid range for + * \a this array. + * \throw In the first *mode of usage*, if strictCompoCompare == true and + * if a->getNumberOfComponents() is unequal to the number of components + * defined by (bgComp,endComp,stepComp). + * \throw In the second *mode of usage*, if \a a->getNumberOfTuples() != 1 or + * a->getNumberOfComponents() is unequal to the number of components + * defined by (bgComp,endComp,stepComp). + * \throw If parameters specifying components to assign to, do not give a + * non-empty range of increasing indices or indices are out of a valid range + * for \c this array. + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarrayint_setpartofvalues3 "Here is a Python example". + * \endif + */ +void DataArrayInt::setPartOfValues3(const DataArrayInt *a, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare) +{ + if(!a) + throw INTERP_KERNEL::Exception("DataArrayInt::setPartOfValues3 : DataArrayInt pointer in input is NULL !"); + const char msg[]="DataArrayInt::setPartOfValues3"; + checkAllocated(); + a->checkAllocated(); + int newNbOfComp=DataArray::GetNumberOfItemGivenBES(bgComp,endComp,stepComp,msg); + int nbComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + DataArray::CheckValueInRangeEx(nbComp,bgComp,endComp,"invalid component value"); + int newNbOfTuples=(int)std::distance(bgTuples,endTuples); + bool assignTech=true; + if(a->getNbOfElems()==(std::size_t)newNbOfTuples*newNbOfComp) + { + if(strictCompoCompare) + a->checkNbOfTuplesAndComp(newNbOfTuples,newNbOfComp,msg); + } + else + { + a->checkNbOfTuplesAndComp(1,newNbOfComp,msg); + assignTech=false; + } + int *pt=getPointer()+bgComp; + const int *srcPt=a->getConstPointer(); + if(assignTech) + { + for(const int *w=bgTuples;w!=endTuples;w++) + for(int j=0;j(pi) varies as this: + * \a bgTuples <= \a pi < \a endTuples. + * \param [in] bgComp - index of the first component of \a this array to assign to. + * \param [in] endComp - index of the component before which the components to assign + * to are located. + * \param [in] stepComp - index increment to get index of the next component to assign to. + * \throw If \a this is not allocated. + * \throw If any index of tuple given by \a bgTuples is out of a valid range for + * \a this array. + * \throw If parameters specifying components to assign to, do not give a + * non-empty range of increasing indices or indices are out of a valid range + * for \c this array. + * + * \if ENABLE_EXAMPLES + * \ref py_mcdataarrayint_setpartofvaluessimple3 "Here is a Python example". + * \endif + */ +void DataArrayInt::setPartOfValuesSimple3(int a, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp) +{ + const char msg[]="DataArrayInt::setPartOfValuesSimple3"; + checkAllocated(); + int newNbOfComp=DataArray::GetNumberOfItemGivenBES(bgComp,endComp,stepComp,msg); + int nbComp=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + DataArray::CheckValueInRangeEx(nbComp,bgComp,endComp,"invalid component value"); + int *pt=getPointer()+bgComp; + for(const int *w=bgTuples;w!=endTuples;w++) + for(int j=0;jcheckAllocated(); + int newNbOfTuples=DataArray::GetNumberOfItemGivenBES(bgTuples,endTuples,stepTuples,msg); + int newNbOfComp=(int)std::distance(bgComp,endComp); + int nbComp=getNumberOfComponents(); + for(const int *z=bgComp;z!=endComp;z++) + DataArray::CheckValueInRange(nbComp,*z,"invalid component id"); + int nbOfTuples=getNumberOfTuples(); + DataArray::CheckValueInRangeEx(nbOfTuples,bgTuples,endTuples,"invalid tuple value"); + bool assignTech=true; + if(a->getNbOfElems()==(std::size_t)newNbOfTuples*newNbOfComp) + { + if(strictCompoCompare) + a->checkNbOfTuplesAndComp(newNbOfTuples,newNbOfComp,msg); + } + else + { + a->checkNbOfTuplesAndComp(1,newNbOfComp,msg); + assignTech=false; + } + const int *srcPt=a->getConstPointer(); + int *pt=getPointer()+bgTuples*nbComp; + if(assignTech) + { + for(int i=0;ithis->getNumberOfComponents() != a->getNumberOfComponents(). + * \throw If \a tuplesSelec->getNumberOfComponents() != 2. + * \throw If any tuple index given by \a tuplesSelec is out of a valid range for + * the corresponding (\a this or \a a) array. + */ +void DataArrayInt::setPartOfValuesAdv(const DataArrayInt *a, const DataArrayInt *tuplesSelec) +{ + if(!a || !tuplesSelec) + throw INTERP_KERNEL::Exception("DataArrayInt::setPartOfValuesAdv : DataArrayInt pointer in input is NULL !"); + checkAllocated(); + a->checkAllocated(); + tuplesSelec->checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=a->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("DataArrayInt::setPartOfValuesAdv : This and a do not have the same number of components !"); + if(tuplesSelec->getNumberOfComponents()!=2) + throw INTERP_KERNEL::Exception("DataArrayInt::setPartOfValuesAdv : Expecting to have a tuple selector DataArrayInt instance with exactly 2 components !"); + int thisNt=getNumberOfTuples(); + int aNt=a->getNumberOfTuples(); + int *valsToSet=getPointer(); + const int *valsSrc=a->getConstPointer(); + for(const int *tuple=tuplesSelec->begin();tuple!=tuplesSelec->end();tuple+=2) + { + if(tuple[1]>=0 && tuple[1]=0 && tuple[0]begin(),tuple)/2; + oss << " of 'tuplesSelec' request of tuple id #" << tuple[0] << " in 'this' ! It should be in [0," << thisNt << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + else + { + std::ostringstream oss; oss << "DataArrayInt::setPartOfValuesAdv : Tuple #" << std::distance(tuplesSelec->begin(),tuple)/2; + oss << " of 'tuplesSelec' request of tuple id #" << tuple[1] << " in 'a' ! It should be in [0," << aNt << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } +} + +/*! + * Copy some tuples from another DataArrayInt (\a aBase) into contiguous tuples + * of \a this array. Textual data is not copied. Both arrays must have equal number of + * components. + * The tuples to assign to are defined by index of the first tuple, and + * their number is defined by \a tuplesSelec->getNumberOfTuples(). + * The tuples to copy are defined by values of a DataArrayInt. + * All components of selected tuples are copied. + * \param [in] tupleIdStart - index of the first tuple of \a this array to assign + * values to. + * \param [in] aBase - the array to copy values from. + * \param [in] tuplesSelec - the array specifying tuples of \a aBase to copy. + * \throw If \a this is not allocated. + * \throw If \a aBase is NULL. + * \throw If \a aBase is not allocated. + * \throw If \a tuplesSelec is NULL. + * \throw If \a tuplesSelec is not allocated. + * \throw If this->getNumberOfComponents() != a->getNumberOfComponents(). + * \throw If \a tuplesSelec->getNumberOfComponents() != 1. + * \throw If tupleIdStart + tuplesSelec->getNumberOfTuples() > this->getNumberOfTuples(). + * \throw If any tuple index given by \a tuplesSelec is out of a valid range for + * \a aBase array. + */ +void DataArrayInt::setContigPartOfSelectedValues(int tupleIdStart, const DataArray *aBase, const DataArrayInt *tuplesSelec) +{ + if(!aBase || !tuplesSelec) + throw INTERP_KERNEL::Exception("DataArrayInt::setContigPartOfSelectedValues : input DataArray is NULL !"); + const DataArrayInt *a=dynamic_cast(aBase); + if(!a) + throw INTERP_KERNEL::Exception("DataArrayInt::setContigPartOfSelectedValues : input DataArray aBase is not a DataArrayInt !"); + checkAllocated(); + a->checkAllocated(); + tuplesSelec->checkAllocated(); + int nbOfComp=getNumberOfComponents(); + if(nbOfComp!=a->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("DataArrayInt::setContigPartOfSelectedValues : This and a do not have the same number of components !"); + if(tuplesSelec->getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::setContigPartOfSelectedValues : Expecting to have a tuple selector DataArrayInt instance with exactly 1 component !"); + int thisNt=getNumberOfTuples(); + int aNt=a->getNumberOfTuples(); + int nbOfTupleToWrite=tuplesSelec->getNumberOfTuples(); + int *valsToSet=getPointer()+tupleIdStart*nbOfComp; + if(tupleIdStart+nbOfTupleToWrite>thisNt) + throw INTERP_KERNEL::Exception("DataArrayInt::setContigPartOfSelectedValues : invalid number range of values to write !"); + const int *valsSrc=a->getConstPointer(); + for(const int *tuple=tuplesSelec->begin();tuple!=tuplesSelec->end();tuple++,valsToSet+=nbOfComp) + { + if(*tuple>=0 && *tuplebegin(),tuple); + oss << " of 'tuplesSelec' request of tuple id #" << *tuple << " in 'a' ! It should be in [0," << aNt << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } +} + +/*! + * Copy some tuples from another DataArrayInt (\a aBase) into contiguous tuples + * of \a this array. Textual data is not copied. Both arrays must have equal number of + * components. + * The tuples to copy are defined by three values similar to parameters of + * the Python function \c range(\c start,\c stop,\c step). + * The tuples to assign to are defined by index of the first tuple, and + * their number is defined by number of tuples to copy. + * All components of selected tuples are copied. + * \param [in] tupleIdStart - index of the first tuple of \a this array to assign + * values to. + * \param [in] aBase - the array to copy values from. + * \param [in] bg - index of the first tuple to copy of the array \a aBase. + * \param [in] end2 - index of the tuple of \a aBase before which the tuples to copy + * are located. + * \param [in] step - index increment to get index of the next tuple to copy. + * \throw If \a this is not allocated. + * \throw If \a aBase is NULL. + * \throw If \a aBase is not allocated. + * \throw If this->getNumberOfComponents() != aBase->getNumberOfComponents(). + * \throw If tupleIdStart + len(range(bg,end2,step)) > this->getNumberOfTuples(). + * \throw If parameters specifying tuples to copy, do not give a + * non-empty range of increasing indices or indices are out of a valid range + * for the array \a aBase. + */ +void DataArrayInt::setContigPartOfSelectedValues2(int tupleIdStart, const DataArray *aBase, int bg, int end2, int step) +{ + if(!aBase) + throw INTERP_KERNEL::Exception("DataArrayInt::setContigPartOfSelectedValues2 : input DataArray is NULL !"); + const DataArrayInt *a=dynamic_cast(aBase); + if(!a) + throw INTERP_KERNEL::Exception("DataArrayInt::setContigPartOfSelectedValues2 : input DataArray aBase is not a DataArrayInt !"); + checkAllocated(); + a->checkAllocated(); + int nbOfComp=getNumberOfComponents(); + const char msg[]="DataArrayInt::setContigPartOfSelectedValues2"; + int nbOfTupleToWrite=DataArray::GetNumberOfItemGivenBES(bg,end2,step,msg); + if(nbOfComp!=a->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("DataArrayInt::setContigPartOfSelectedValues2 : This and a do not have the same number of components !"); + int thisNt=getNumberOfTuples(); + int aNt=a->getNumberOfTuples(); + int *valsToSet=getPointer()+tupleIdStart*nbOfComp; + if(tupleIdStart+nbOfTupleToWrite>thisNt) + throw INTERP_KERNEL::Exception("DataArrayInt::setContigPartOfSelectedValues2 : invalid number range of values to write !"); + if(end2>aNt) + throw INTERP_KERNEL::Exception("DataArrayInt::setContigPartOfSelectedValues2 : invalid range of values to read !"); + const int *valsSrc=a->getConstPointer()+bg*nbOfComp; + for(int i=0;i( 0 <= tupleId < this->getNumberOfTuples() ) is violated. + * \throw If condition ( 0 <= compoId < this->getNumberOfComponents() ) is violated. + */ +int DataArrayInt::getIJSafe(int tupleId, int compoId) const +{ + checkAllocated(); + if(tupleId<0 || tupleId>=getNumberOfTuples()) + { + std::ostringstream oss; oss << "DataArrayInt::getIJSafe : request for tupleId " << tupleId << " should be in [0," << getNumberOfTuples() << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if(compoId<0 || compoId>=getNumberOfComponents()) + { + std::ostringstream oss; oss << "DataArrayInt::getIJSafe : request for compoId " << compoId << " should be in [0," << getNumberOfComponents() << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + return _mem[tupleId*_info_on_compo.size()+compoId]; +} + +/*! + * Returns the first value of \a this. + * \return int - the last value of \a this array. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a this->getNumberOfTuples() < 1. + */ +int DataArrayInt::front() const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::front : number of components not equal to one !"); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples<1) + throw INTERP_KERNEL::Exception("DataArrayInt::front : number of tuples must be >= 1 !"); + return *(getConstPointer()); +} + +/*! + * Returns the last value of \a this. + * \return int - the last value of \a this array. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a this->getNumberOfTuples() < 1. + */ +int DataArrayInt::back() const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::back : number of components not equal to one !"); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples<1) + throw INTERP_KERNEL::Exception("DataArrayInt::back : number of tuples must be >= 1 !"); + return *(getConstPointer()+nbOfTuples-1); +} + +/*! + * Assign pointer to one array to a pointer to another appay. Reference counter of + * \a arrayToSet is incremented / decremented. + * \param [in] newArray - the pointer to array to assign to \a arrayToSet. + * \param [in,out] arrayToSet - the pointer to array to assign to. + */ +void DataArrayInt::SetArrayIn(DataArrayInt *newArray, DataArrayInt* &arrayToSet) +{ + if(newArray!=arrayToSet) + { + if(arrayToSet) + arrayToSet->decrRef(); + arrayToSet=newArray; + if(arrayToSet) + arrayToSet->incrRef(); + } +} + +DataArrayIntIterator *DataArrayInt::iterator() +{ + return new DataArrayIntIterator(this); +} + +/*! + * Creates a new DataArrayInt containing IDs (indices) of tuples holding value equal to a + * given one. The ids are sorted in the ascending order. + * \param [in] val - the value to find within \a this. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \sa DataArrayInt::getIdsEqualTuple + */ +DataArrayInt *DataArrayInt::getIdsEqual(int val) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::getIdsEqual : the array must have only one component, you can call 'rearrange' method before !"); + const int *cptr(getConstPointer()); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + int nbOfTuples=getNumberOfTuples(); + for(int i=0;ipushBackSilent(i); + return ret.retn(); +} + +/*! + * Creates a new DataArrayInt containing IDs (indices) of tuples holding value \b not + * equal to a given one. + * \param [in] val - the value to ignore within \a this. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + */ +DataArrayInt *DataArrayInt::getIdsNotEqual(int val) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::getIdsNotEqual : the array must have only one component, you can call 'rearrange' method before !"); + const int *cptr(getConstPointer()); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + int nbOfTuples=getNumberOfTuples(); + for(int i=0;ipushBackSilent(i); + return ret.retn(); +} + +/*! + * Creates a new DataArrayInt containing IDs (indices) of tuples holding tuple equal to those defined by [ \a tupleBg , \a tupleEnd ) + * This method is an extension of DataArrayInt::getIdsEqual method. + * + * \param [in] tupleBg - the begin (included) of the input tuple to find within \a this. + * \param [in] tupleEnd - the end (excluded) of the input tuple to find within \a this. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != std::distance(tupleBg,tupleEnd). + * \throw If \a this->getNumberOfComponents() is equal to 0. + * \sa DataArrayInt::getIdsEqual + */ +DataArrayInt *DataArrayInt::getIdsEqualTuple(const int *tupleBg, const int *tupleEnd) const +{ + std::size_t nbOfCompoExp(std::distance(tupleBg,tupleEnd)); + checkAllocated(); + if(getNumberOfComponents()!=(int)nbOfCompoExp) + { + std::ostringstream oss; oss << "DataArrayInt::getIdsEqualTuple : mismatch of number of components. Input tuple has " << nbOfCompoExp << " whereas this array has " << getNumberOfComponents() << " components !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if(nbOfCompoExp==0) + throw INTERP_KERNEL::Exception("DataArrayInt::getIdsEqualTuple : number of components should be > 0 !"); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + const int *bg(begin()),*end2(end()),*work(begin()); + while(work!=end2) + { + work=std::search(work,end2,tupleBg,tupleEnd); + if(work!=end2) + { + std::size_t pos(std::distance(bg,work)); + if(pos%nbOfCompoExp==0) + ret->pushBackSilent(pos/nbOfCompoExp); + work++; + } + } + return ret.retn(); +} + +/*! + * Assigns \a newValue to all elements holding \a oldValue within \a this + * one-dimensional array. + * \param [in] oldValue - the value to replace. + * \param [in] newValue - the value to assign. + * \return int - number of replacements performed. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + */ +int DataArrayInt::changeValue(int oldValue, int newValue) +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::changeValue : the array must have only one component, you can call 'rearrange' method before !"); + int *start=getPointer(); + int *end2=start+getNbOfElems(); + int ret=0; + for(int *val=start;val!=end2;val++) + { + if(*val==oldValue) + { + *val=newValue; + ret++; + } + } + return ret; +} + +/*! + * Creates a new DataArrayInt containing IDs (indices) of tuples holding value equal to + * one of given values. + * \param [in] valsBg - an array of values to find within \a this array. + * \param [in] valsEnd - specifies the end of the array \a valsBg, so that + * the last value of \a valsBg is \a valsEnd[ -1 ]. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If \a this->getNumberOfComponents() != 1. + */ +DataArrayInt *DataArrayInt::getIdsEqualList(const int *valsBg, const int *valsEnd) const +{ + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::getIdsEqualList : the array must have only one component, you can call 'rearrange' method before !"); + std::set vals2(valsBg,valsEnd); + const int *cptr=getConstPointer(); + std::vector res; + int nbOfTuples=getNumberOfTuples(); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + for(int i=0;ipushBackSilent(i); + return ret.retn(); +} + +/*! + * Creates a new DataArrayInt containing IDs (indices) of tuples holding values \b not + * equal to any of given values. + * \param [in] valsBg - an array of values to ignore within \a this array. + * \param [in] valsEnd - specifies the end of the array \a valsBg, so that + * the last value of \a valsBg is \a valsEnd[ -1 ]. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If \a this->getNumberOfComponents() != 1. + */ +DataArrayInt *DataArrayInt::getIdsNotEqualList(const int *valsBg, const int *valsEnd) const +{ + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::getIdsNotEqualList : the array must have only one component, you can call 'rearrange' method before !"); + std::set vals2(valsBg,valsEnd); + const int *cptr=getConstPointer(); + std::vector res; + int nbOfTuples=getNumberOfTuples(); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + for(int i=0;ipushBackSilent(i); + return ret.retn(); +} + +/*! + * This method is an extension of DataArrayInt::locateValue method because this method works for DataArrayInt with + * any number of components excepted 0 (an INTERP_KERNEL::Exception is thrown in this case). + * This method searches in \b this is there is a tuple that matched the input parameter \b tupl. + * If any the tuple id is returned. If not -1 is returned. + * + * This method throws an INTERP_KERNEL::Exception if the number of components in \b this mismatches with the size of + * the input vector. An INTERP_KERNEL::Exception is thrown too if \b this is not allocated. + * + * \return tuple id where \b tupl is. -1 if no such tuple exists in \b this. + * \sa DataArrayInt::search, DataArrayInt::presenceOfTuple. + */ +int DataArrayInt::locateTuple(const std::vector& tupl) const +{ + checkAllocated(); + int nbOfCompo=getNumberOfComponents(); + if(nbOfCompo==0) + throw INTERP_KERNEL::Exception("DataArrayInt::locateTuple : 0 components in 'this' !"); + if(nbOfCompo!=(int)tupl.size()) + { + std::ostringstream oss; oss << "DataArrayInt::locateTuple : 'this' contains " << nbOfCompo << " components and searching for a tuple of length " << tupl.size() << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + const int *cptr=getConstPointer(); + std::size_t nbOfVals=getNbOfElems(); + for(const int *work=cptr;work!=cptr+nbOfVals;) + { + work=std::search(work,cptr+nbOfVals,tupl.begin(),tupl.end()); + if(work!=cptr+nbOfVals) + { + if(std::distance(cptr,work)%nbOfCompo!=0) + work++; + else + return std::distance(cptr,work)/nbOfCompo; + } + } + return -1; +} + +/*! + * This method searches the sequence specified in input parameter \b vals in \b this. + * This works only for DataArrayInt having number of components equal to one (if not an INTERP_KERNEL::Exception will be thrown). + * This method differs from DataArrayInt::locateTuple in that the position is internal raw data is not considered here contrary to DataArrayInt::locateTuple. + * \sa DataArrayInt::locateTuple + */ +int DataArrayInt::search(const std::vector& vals) const +{ + checkAllocated(); + int nbOfCompo=getNumberOfComponents(); + if(nbOfCompo!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::search : works only for DataArrayInt instance with one component !"); + const int *cptr=getConstPointer(); + std::size_t nbOfVals=getNbOfElems(); + const int *loc=std::search(cptr,cptr+nbOfVals,vals.begin(),vals.end()); + if(loc!=cptr+nbOfVals) + return std::distance(cptr,loc); + return -1; +} + +/*! + * This method expects to be called when number of components of this is equal to one. + * This method returns the tuple id, if it exists, of the first tuple equal to \b value. + * If not any tuple contains \b value -1 is returned. + * \sa DataArrayInt::presenceOfValue + */ +int DataArrayInt::locateValue(int value) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::presenceOfValue : the array must have only one component, you can call 'rearrange' method before !"); + const int *cptr=getConstPointer(); + int nbOfTuples=getNumberOfTuples(); + const int *ret=std::find(cptr,cptr+nbOfTuples,value); + if(ret!=cptr+nbOfTuples) + return std::distance(cptr,ret); + return -1; +} + +/*! + * This method expects to be called when number of components of this is equal to one. + * This method returns the tuple id, if it exists, of the first tuple so that the value is contained in \b vals. + * If not any tuple contains one of the values contained in 'vals' false is returned. + * \sa DataArrayInt::presenceOfValue + */ +int DataArrayInt::locateValue(const std::vector& vals) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::presenceOfValue : the array must have only one component, you can call 'rearrange' method before !"); + std::set vals2(vals.begin(),vals.end()); + const int *cptr=getConstPointer(); + int nbOfTuples=getNumberOfTuples(); + for(const int *w=cptr;w!=cptr+nbOfTuples;w++) + if(vals2.find(*w)!=vals2.end()) + return std::distance(cptr,w); + return -1; +} + +/*! + * This method returns the number of values in \a this that are equals to input parameter \a value. + * This method only works for single component array. + * + * \return a value in [ 0, \c this->getNumberOfTuples() ) + * + * \throw If \a this is not allocated + * + */ +int DataArrayInt::count(int value) const +{ + int ret=0; + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::count : must be applied on DataArrayInt with only one component, you can call 'rearrange' method before !"); + const int *vals=begin(); + int nbOfTuples=getNumberOfTuples(); + for(int i=0;i& tupl) const +{ + return locateTuple(tupl)!=-1; +} + + +/*! + * Returns \a true if a given value is present within \a this one-dimensional array. + * \param [in] value - the value to find within \a this array. + * \return bool - \a true in case if \a value is present within \a this array. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \sa locateValue() + */ +bool DataArrayInt::presenceOfValue(int value) const +{ + return locateValue(value)!=-1; +} + +/*! + * This method expects to be called when number of components of this is equal to one. + * This method returns true if it exists a tuple so that the value is contained in \b vals. + * If not any tuple contains one of the values contained in 'vals' false is returned. + * \sa DataArrayInt::locateValue + */ +bool DataArrayInt::presenceOfValue(const std::vector& vals) const +{ + return locateValue(vals)!=-1; +} + +/*! + * Accumulates values of each component of \a this array. + * \param [out] res - an array of length \a this->getNumberOfComponents(), allocated + * by the caller, that is filled by this method with sum value for each + * component. + * \throw If \a this is not allocated. + */ +void DataArrayInt::accumulate(int *res) const +{ + checkAllocated(); + const int *ptr=getConstPointer(); + int nbTuple=getNumberOfTuples(); + int nbComps=getNumberOfComponents(); + std::fill(res,res+nbComps,0); + for(int i=0;i()); +} + +int DataArrayInt::accumulate(int compId) const +{ + checkAllocated(); + const int *ptr=getConstPointer(); + int nbTuple=getNumberOfTuples(); + int nbComps=getNumberOfComponents(); + if(compId<0 || compId>=nbComps) + throw INTERP_KERNEL::Exception("DataArrayInt::accumulate : Invalid compId specified : No such nb of components !"); + int ret=0; + for(int i=0;igetNumberOfTuples). + * + * \param [in] bgOfIndex - begin (included) of the input index array. + * \param [in] endOfIndex - end (excluded) of the input index array. + * \return DataArrayInt * - the new instance having the same number of components than \a this. + * + * \throw If bgOfIndex or end is NULL. + * \throw If input index array is not ascendingly sorted. + * \throw If there is an id in [ \a bgOfIndex, \a endOfIndex ) not in [0, \c this->getNumberOfTuples). + * \throw If std::distance(bgOfIndex,endOfIndex)==0. + */ +DataArrayInt *DataArrayInt::accumulatePerChunck(const int *bgOfIndex, const int *endOfIndex) const +{ + if(!bgOfIndex || !endOfIndex) + throw INTERP_KERNEL::Exception("DataArrayInt::accumulatePerChunck : input pointer NULL !"); + checkAllocated(); + int nbCompo=getNumberOfComponents(); + int nbOfTuples=getNumberOfTuples(); + int sz=(int)std::distance(bgOfIndex,endOfIndex); + if(sz<1) + throw INTERP_KERNEL::Exception("DataArrayInt::accumulatePerChunck : invalid size of input index array !"); + sz--; + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); ret->alloc(sz,nbCompo); + const int *w=bgOfIndex; + if(*w<0 || *w>=nbOfTuples) + throw INTERP_KERNEL::Exception("DataArrayInt::accumulatePerChunck : The first element of the input index not in [0,nbOfTuples) !"); + const int *srcPt=begin()+(*w)*nbCompo; + int *tmp=ret->getPointer(); + for(int i=0;i=w[0]) + { + for(int j=w[0];j=0 && j()); + else + { + std::ostringstream oss; oss << "DataArrayInt::accumulatePerChunck : At rank #" << i << " the input index array points to id " << j << " should be in [0," << nbOfTuples << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + } + else + { + std::ostringstream oss; oss << "DataArrayInt::accumulatePerChunck : At rank #" << i << " the input index array is not in ascendingly sorted."; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + ret->copyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a new DataArrayInt by concatenating two given arrays, so that (1) the number + * of tuples in the result array is a1->getNumberOfTuples() + a2->getNumberOfTuples() - + * offsetA2 and (2) + * the number of component in the result array is same as that of each of given arrays. + * First \a offsetA2 tuples of \a a2 are skipped and thus are missing from the result array. + * Info on components is copied from the first of the given arrays. Number of components + * in the given arrays must be the same. + * \param [in] a1 - an array to include in the result array. + * \param [in] a2 - another array to include in the result array. + * \param [in] offsetA2 - number of tuples of \a a2 to skip. + * \return DataArrayInt * - the new instance of DataArrayInt. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents(). + */ +DataArrayInt *DataArrayInt::Aggregate(const DataArrayInt *a1, const DataArrayInt *a2, int offsetA2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayInt::Aggregate : input DataArrayInt instance is NULL !"); + int nbOfComp=a1->getNumberOfComponents(); + if(nbOfComp!=a2->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("Nb of components mismatch for array Aggregation !"); + int nbOfTuple1=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + DataArrayInt *ret=DataArrayInt::New(); + ret->alloc(nbOfTuple1+nbOfTuple2-offsetA2,nbOfComp); + int *pt=std::copy(a1->getConstPointer(),a1->getConstPointer()+nbOfTuple1*nbOfComp,ret->getPointer()); + std::copy(a2->getConstPointer()+offsetA2*nbOfComp,a2->getConstPointer()+nbOfTuple2*nbOfComp,pt); + ret->copyStringInfoFrom(*a1); + return ret; +} + +/*! + * Returns a new DataArrayInt by concatenating all given arrays, so that (1) the number + * of tuples in the result array is a sum of the number of tuples of given arrays and (2) + * the number of component in the result array is same as that of each of given arrays. + * Info on components is copied from the first of the given arrays. Number of components + * in the given arrays must be the same. + * If the number of non null of elements in \a arr is equal to one the returned object is a copy of it + * not the object itself. + * \param [in] arr - a sequence of arrays to include in the result array. + * \return DataArrayInt * - the new instance of DataArrayInt. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If all arrays within \a arr are NULL. + * \throw If getNumberOfComponents() of arrays within \a arr. + */ +DataArrayInt *DataArrayInt::Aggregate(const std::vector& arr) +{ + std::vector a; + for(std::vector::const_iterator it4=arr.begin();it4!=arr.end();it4++) + if(*it4) + a.push_back(*it4); + if(a.empty()) + throw INTERP_KERNEL::Exception("DataArrayInt::Aggregate : input list must be NON EMPTY !"); + std::vector::const_iterator it=a.begin(); + int nbOfComp=(*it)->getNumberOfComponents(); + int nbt=(*it++)->getNumberOfTuples(); + for(int i=1;it!=a.end();it++,i++) + { + if((*it)->getNumberOfComponents()!=nbOfComp) + throw INTERP_KERNEL::Exception("DataArrayInt::Aggregate : Nb of components mismatch for array aggregation !"); + nbt+=(*it)->getNumberOfTuples(); + } + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbt,nbOfComp); + int *pt=ret->getPointer(); + for(it=a.begin();it!=a.end();it++) + pt=std::copy((*it)->getConstPointer(),(*it)->getConstPointer()+(*it)->getNbOfElems(),pt); + ret->copyStringInfoFrom(*(a[0])); + return ret.retn(); +} + +/*! + * This method takes as input a list of DataArrayInt instances \a arrs that represent each a packed index arrays. + * A packed index array is an allocated array with one component, and at least one tuple. The first element + * of each array in \a arrs must be 0. Each array in \a arrs is expected to be increasingly monotonic. + * This method is useful for users that want to aggregate a pair of DataArrayInt representing an indexed data (typically nodal connectivity index in unstructured meshes. + * + * \return DataArrayInt * - a new object to be managed by the caller. + */ +DataArrayInt *DataArrayInt::AggregateIndexes(const std::vector& arrs) +{ + int retSz=1; + for(std::vector::const_iterator it4=arrs.begin();it4!=arrs.end();it4++) + { + if(*it4) + { + (*it4)->checkAllocated(); + if((*it4)->getNumberOfComponents()!=1) + { + std::ostringstream oss; oss << "DataArrayInt::AggregateIndexes : presence of a DataArrayInt instance with nb of compo != 1 at pos " << std::distance(arrs.begin(),it4) << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + int nbTupl=(*it4)->getNumberOfTuples(); + if(nbTupl<1) + { + std::ostringstream oss; oss << "DataArrayInt::AggregateIndexes : presence of a DataArrayInt instance with nb of tuples < 1 at pos " << std::distance(arrs.begin(),it4) << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if((*it4)->front()!=0) + { + std::ostringstream oss; oss << "DataArrayInt::AggregateIndexes : presence of a DataArrayInt instance with front value != 0 at pos " << std::distance(arrs.begin(),it4) << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + retSz+=nbTupl-1; + } + else + { + std::ostringstream oss; oss << "DataArrayInt::AggregateIndexes : presence of a null instance at pos " << std::distance(arrs.begin(),it4) << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + if(arrs.empty()) + throw INTERP_KERNEL::Exception("DataArrayInt::AggregateIndexes : input list must be NON EMPTY !"); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(retSz,1); + int *pt=ret->getPointer(); *pt++=0; + for(std::vector::const_iterator it=arrs.begin();it!=arrs.end();it++) + pt=std::transform((*it)->begin()+1,(*it)->end(),pt,std::bind2nd(std::plus(),pt[-1])); + ret->copyStringInfoFrom(*(arrs[0])); + return ret.retn(); +} + +/*! + * Returns the maximal value and its location within \a this one-dimensional array. + * \param [out] tupleId - index of the tuple holding the maximal value. + * \return int - the maximal value among all values of \a this array. + * \throw If \a this->getNumberOfComponents() != 1 + * \throw If \a this->getNumberOfTuples() < 1 + */ +int DataArrayInt::getMaxValue(int& tupleId) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::getMaxValue : must be applied on DataArrayInt with only one component !"); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples<=0) + throw INTERP_KERNEL::Exception("DataArrayInt::getMaxValue : array exists but number of tuples must be > 0 !"); + const int *vals=getConstPointer(); + const int *loc=std::max_element(vals,vals+nbOfTuples); + tupleId=(int)std::distance(vals,loc); + return *loc; +} + +/*! + * Returns the maximal value within \a this array that is allowed to have more than + * one component. + * \return int - the maximal value among all values of \a this array. + * \throw If \a this is not allocated. + */ +int DataArrayInt::getMaxValueInArray() const +{ + checkAllocated(); + const int *loc=std::max_element(begin(),end()); + return *loc; +} + +/*! + * Returns the minimal value and its location within \a this one-dimensional array. + * \param [out] tupleId - index of the tuple holding the minimal value. + * \return int - the minimal value among all values of \a this array. + * \throw If \a this->getNumberOfComponents() != 1 + * \throw If \a this->getNumberOfTuples() < 1 + */ +int DataArrayInt::getMinValue(int& tupleId) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::getMaxValue : must be applied on DataArrayInt with only one component !"); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples<=0) + throw INTERP_KERNEL::Exception("DataArrayInt::getMaxValue : array exists but number of tuples must be > 0 !"); + const int *vals=getConstPointer(); + const int *loc=std::min_element(vals,vals+nbOfTuples); + tupleId=(int)std::distance(vals,loc); + return *loc; +} + +/*! + * Returns the minimal value within \a this array that is allowed to have more than + * one component. + * \return int - the minimal value among all values of \a this array. + * \throw If \a this is not allocated. + */ +int DataArrayInt::getMinValueInArray() const +{ + checkAllocated(); + const int *loc=std::min_element(begin(),end()); + return *loc; +} + +/*! + * Returns in a single walk in \a this the min value and the max value in \a this. + * \a this is expected to be single component array. + * + * \param [out] minValue - the min value in \a this. + * \param [out] maxValue - the max value in \a this. + * + * \sa getMinValueInArray, getMinValue, getMaxValueInArray, getMaxValue + */ +void DataArrayInt::getMinMaxValues(int& minValue, int& maxValue) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::getMinMaxValues : must be applied on DataArrayInt with only one component !"); + int nbTuples(getNumberOfTuples()); + const int *pt(begin()); + minValue=std::numeric_limits::max(); maxValue=-std::numeric_limits::max(); + for(int i=0;imaxValue) + maxValue=*pt; + } +} + +/*! + * Converts every value of \a this array to its absolute value. + * \b WARNING this method is non const. If a new DataArrayInt instance should be built containing the result of abs DataArrayInt::computeAbs + * should be called instead. + * + * \throw If \a this is not allocated. + * \sa DataArrayInt::computeAbs + */ +void DataArrayInt::abs() +{ + checkAllocated(); + int *ptr(getPointer()); + std::size_t nbOfElems(getNbOfElems()); + std::transform(ptr,ptr+nbOfElems,ptr,std::ptr_fun(std::abs)); + declareAsNew(); +} + +/*! + * This method builds a new instance of \a this object containing the result of std::abs applied of all elements in \a this. + * This method is a const method (that do not change any values in \a this) contrary to DataArrayInt::abs method. + * + * \return DataArrayInt * - the new instance of DataArrayInt containing the + * same number of tuples and component as \a this array. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If \a this is not allocated. + * \sa DataArrayInt::abs + */ +DataArrayInt *DataArrayInt::computeAbs() const +{ + checkAllocated(); + DataArrayInt *newArr(DataArrayInt::New()); + int nbOfTuples(getNumberOfTuples()); + int nbOfComp(getNumberOfComponents()); + newArr->alloc(nbOfTuples,nbOfComp); + std::transform(begin(),end(),newArr->getPointer(),std::ptr_fun(std::abs)); + newArr->copyStringInfoFrom(*this); + return newArr; +} + +/*! + * Apply a liner function to a given component of \a this array, so that + * an array element (x) becomes \f$ a * x + b \f$. + * \param [in] a - the first coefficient of the function. + * \param [in] b - the second coefficient of the function. + * \param [in] compoId - the index of component to modify. + * \throw If \a this is not allocated. + */ +void DataArrayInt::applyLin(int a, int b, int compoId) +{ + checkAllocated(); + int *ptr=getPointer()+compoId; + int nbOfComp=getNumberOfComponents(); + int nbOfTuple=getNumberOfTuples(); + for(int i=0;ialloc(nbOfTuples,nbOfComp); + const int *cptr=getConstPointer(); + std::transform(cptr,cptr+nbOfTuples*nbOfComp,newArr->getPointer(),std::negate()); + newArr->copyStringInfoFrom(*this); + return newArr; +} + +/*! + * Modify all elements of \a this array, so that + * an element _x_ becomes \f$ numerator / x \f$. + * \warning If an exception is thrown because of presence of 0 element in \a this + * array, all elements processed before detection of the zero element remain + * modified. + * \param [in] numerator - the numerator used to modify array elements. + * \throw If \a this is not allocated. + * \throw If there is an element equal to 0 in \a this array. + */ +void DataArrayInt::applyInv(int numerator) +{ + checkAllocated(); + int *ptr=getPointer(); + std::size_t nbOfElems=getNbOfElems(); + for(std::size_t i=0;i(),val)); + declareAsNew(); +} + +/*! + * Modify all elements of \a this array, so that + * an element _x_ becomes x % val . + * \param [in] val - the divisor used to modify array elements. + * \throw If \a this is not allocated. + * \throw If \a val <= 0. + */ +void DataArrayInt::applyModulus(int val) +{ + if(val<=0) + throw INTERP_KERNEL::Exception("DataArrayInt::applyDivideBy : Trying to operate modulus on value <= 0 !"); + checkAllocated(); + int *ptr=getPointer(); + std::size_t nbOfElems=getNbOfElems(); + std::transform(ptr,ptr+nbOfElems,ptr,std::bind2nd(std::modulus(),val)); + declareAsNew(); +} + +/*! + * This method works only on data array with one component. + * This method returns a newly allocated array storing stored ascendantly tuple ids in \b this so that + * this[*id] in [\b vmin,\b vmax) + * + * \param [in] vmin begin of range. This value is included in range (included). + * \param [in] vmax end of range. This value is \b not included in range (excluded). + * \return a newly allocated data array that the caller should deal with. + * + * \sa DataArrayInt::getIdsNotInRange , DataArrayInt::getIdsStrictlyNegative + */ +DataArrayInt *DataArrayInt::getIdsInRange(int vmin, int vmax) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::getIdsInRange : this must have exactly one component !"); + const int *cptr(begin()); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + int nbOfTuples(getNumberOfTuples()); + for(int i=0;i=vmin && *cptrpushBackSilent(i); + return ret.retn(); +} + +/*! + * This method works only on data array with one component. + * This method returns a newly allocated array storing stored ascendantly tuple ids in \b this so that + * this[*id] \b not in [\b vmin,\b vmax) + * + * \param [in] vmin begin of range. This value is \b not included in range (excluded). + * \param [in] vmax end of range. This value is included in range (included). + * \return a newly allocated data array that the caller should deal with. + * + * \sa DataArrayInt::getIdsInRange , DataArrayInt::getIdsStrictlyNegative + */ +DataArrayInt *DataArrayInt::getIdsNotInRange(int vmin, int vmax) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::getIdsNotInRange : this must have exactly one component !"); + const int *cptr(getConstPointer()); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + int nbOfTuples(getNumberOfTuples()); + for(int i=0;i=vmax) + ret->pushBackSilent(i); + return ret.retn(); +} + +/*! + * This method works only on data array with one component. This method returns a newly allocated array storing stored ascendantly of tuple ids in \a this so that this[id]<0. + * + * \return a newly allocated data array that the caller should deal with. + * \sa DataArrayInt::getIdsInRange + */ +DataArrayInt *DataArrayInt::getIdsStrictlyNegative() const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::getIdsStrictlyNegative : this must have exactly one component !"); + const int *cptr(getConstPointer()); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + int nbOfTuples(getNumberOfTuples()); + for(int i=0;ipushBackSilent(i); + return ret.retn(); +} + +/*! + * This method works only on data array with one component. + * This method checks that all ids in \b this are in [ \b vmin, \b vmax ). If there is at least one element in \a this not in [ \b vmin, \b vmax ) an exception will be thrown. + * + * \param [in] vmin begin of range. This value is included in range (included). + * \param [in] vmax end of range. This value is \b not included in range (excluded). + * \return if all ids in \a this are so that (*this)[i]==i for all i in [ 0, \c this->getNumberOfTuples() ). */ +bool DataArrayInt::checkAllIdsInRange(int vmin, int vmax) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::checkAllIdsInRange : this must have exactly one component !"); + int nbOfTuples=getNumberOfTuples(); + bool ret=true; + const int *cptr=getConstPointer(); + for(int i=0;i=vmin && *cptr val % x . + * \warning If an exception is thrown because of presence of an element <= 0 in \a this + * array, all elements processed before detection of the zero element remain + * modified. + * \param [in] val - the divident used to modify array elements. + * \throw If \a this is not allocated. + * \throw If there is an element equal to or less than 0 in \a this array. + */ +void DataArrayInt::applyRModulus(int val) +{ + checkAllocated(); + int *ptr=getPointer(); + std::size_t nbOfElems=getNbOfElems(); + for(std::size_t i=0;i0) + { + *ptr=val%(*ptr); + } + else + { + std::ostringstream oss; oss << "DataArrayInt::applyRModulus : presence of value <=0 in tuple #" << i/getNumberOfComponents() << " component #" << i%getNumberOfComponents(); + oss << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + declareAsNew(); +} + +/*! + * Modify all elements of \a this array, so that + * an element _x_ becomes val ^ x . + * \param [in] val - the value used to apply pow on all array elements. + * \throw If \a this is not allocated. + * \throw If \a val < 0. + */ +void DataArrayInt::applyPow(int val) +{ + checkAllocated(); + if(val<0) + throw INTERP_KERNEL::Exception("DataArrayInt::applyPow : input pow in < 0 !"); + int *ptr=getPointer(); + std::size_t nbOfElems=getNbOfElems(); + if(val==0) + { + std::fill(ptr,ptr+nbOfElems,1); + return ; + } + for(std::size_t i=0;i=0) + { + int tmp=1; + for(int j=0;j<*ptr;j++) + tmp*=val; + *ptr=tmp; + } + else + { + std::ostringstream oss; oss << "DataArrayInt::applyRPow : presence of negative value in tuple #" << i/getNumberOfComponents() << " component #" << i%getNumberOfComponents(); + oss << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + declareAsNew(); +} + +/*! + * Returns a new DataArrayInt by aggregating two given arrays, so that (1) the number + * of components in the result array is a sum of the number of components of given arrays + * and (2) the number of tuples in the result array is same as that of each of given + * arrays. In other words the i-th tuple of result array includes all components of + * i-th tuples of all given arrays. + * Number of tuples in the given arrays must be the same. + * \param [in] a1 - an array to include in the result array. + * \param [in] a2 - another array to include in the result array. + * \return DataArrayInt * - the new instance of DataArrayInt. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If both \a a1 and \a a2 are NULL. + * \throw If any given array is not allocated. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() + */ +DataArrayInt *DataArrayInt::Meld(const DataArrayInt *a1, const DataArrayInt *a2) +{ + std::vector arr(2); + arr[0]=a1; arr[1]=a2; + return Meld(arr); +} + +/*! + * Returns a new DataArrayInt by aggregating all given arrays, so that (1) the number + * of components in the result array is a sum of the number of components of given arrays + * and (2) the number of tuples in the result array is same as that of each of given + * arrays. In other words the i-th tuple of result array includes all components of + * i-th tuples of all given arrays. + * Number of tuples in the given arrays must be the same. + * \param [in] arr - a sequence of arrays to include in the result array. + * \return DataArrayInt * - the new instance of DataArrayInt. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If all arrays within \a arr are NULL. + * \throw If any given array is not allocated. + * \throw If getNumberOfTuples() of arrays within \a arr is different. + */ +DataArrayInt *DataArrayInt::Meld(const std::vector& arr) +{ + std::vector a; + for(std::vector::const_iterator it4=arr.begin();it4!=arr.end();it4++) + if(*it4) + a.push_back(*it4); + if(a.empty()) + throw INTERP_KERNEL::Exception("DataArrayInt::Meld : array must be NON empty !"); + std::vector::const_iterator it; + for(it=a.begin();it!=a.end();it++) + (*it)->checkAllocated(); + it=a.begin(); + int nbOfTuples=(*it)->getNumberOfTuples(); + std::vector nbc(a.size()); + std::vector pts(a.size()); + nbc[0]=(*it)->getNumberOfComponents(); + pts[0]=(*it++)->getConstPointer(); + for(int i=1;it!=a.end();it++,i++) + { + if(nbOfTuples!=(*it)->getNumberOfTuples()) + throw INTERP_KERNEL::Exception("DataArrayInt::meld : mismatch of number of tuples !"); + nbc[i]=(*it)->getNumberOfComponents(); + pts[i]=(*it)->getConstPointer(); + } + int totalNbOfComp=std::accumulate(nbc.begin(),nbc.end(),0); + DataArrayInt *ret=DataArrayInt::New(); + ret->alloc(nbOfTuples,totalNbOfComp); + int *retPtr=ret->getPointer(); + for(int i=0;isetInfoOnComponent(k,a[i]->getInfoOnComponent(j)); + return ret; +} + +/*! + * Returns a new DataArrayInt which is a minimal partition of elements of \a groups. + * The i-th item of the result array is an ID of a set of elements belonging to a + * unique set of groups, which the i-th element is a part of. This set of elements + * belonging to a unique set of groups is called \a family, so the result array contains + * IDs of families each element belongs to. + * + * \b Example: if we have two groups of elements: \a group1 [0,4] and \a group2 [ 0,1,2 ], + * then there are 3 families: + * - \a family1 (with ID 1) contains element [0] belonging to ( \a group1 + \a group2 ), + * - \a family2 (with ID 2) contains elements [4] belonging to ( \a group1 ), + * - \a family3 (with ID 3) contains element [1,2] belonging to ( \a group2 ),
+ * and the result array contains IDs of families [ 1,3,3,0,2 ].
Note a family ID 0 which + * stands for the element #3 which is in none of groups. + * + * \param [in] groups - sequence of groups of element IDs. + * \param [in] newNb - total number of elements; it must be more than max ID of element + * in \a groups. + * \param [out] fidsOfGroups - IDs of families the elements of each group belong to. + * \return DataArrayInt * - a new instance of DataArrayInt containing IDs of families + * each element with ID from range [0, \a newNb ) belongs to. The caller is to + * delete this array using decrRef() as it is no more needed. + * \throw If any element ID in \a groups violates condition ( 0 <= ID < \a newNb ). + */ +DataArrayInt *DataArrayInt::MakePartition(const std::vector& groups, int newNb, std::vector< std::vector >& fidsOfGroups) +{ + std::vector groups2; + for(std::vector::const_iterator it4=groups.begin();it4!=groups.end();it4++) + if(*it4) + groups2.push_back(*it4); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(newNb,1); + int *retPtr=ret->getPointer(); + std::fill(retPtr,retPtr+newNb,0); + int fid=1; + for(std::vector::const_iterator iter=groups2.begin();iter!=groups2.end();iter++) + { + const int *ptr=(*iter)->getConstPointer(); + std::size_t nbOfElem=(*iter)->getNbOfElems(); + int sfid=fid; + for(int j=0;j=0 && ptr[i]getName() << "\" in tuple #" << i << " value = " << ptr[i] << " ! Should be in [0," << newNb; + oss << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + if(found) + fid++; + } + } + fidsOfGroups.clear(); + fidsOfGroups.resize(groups2.size()); + int grId=0; + for(std::vector::const_iterator iter=groups2.begin();iter!=groups2.end();iter++,grId++) + { + std::set tmp; + const int *ptr=(*iter)->getConstPointer(); + std::size_t nbOfElem=(*iter)->getNbOfElems(); + for(const int *p=ptr;p!=ptr+nbOfElem;p++) + tmp.insert(retPtr[*p]); + fidsOfGroups[grId].insert(fidsOfGroups[grId].end(),tmp.begin(),tmp.end()); + } + return ret.retn(); +} + +/*! + * Returns a new DataArrayInt which contains all elements of given one-dimensional + * arrays. The result array does not contain any duplicates and its values + * are sorted in ascending order. + * \param [in] arr - sequence of DataArrayInt's to unite. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If any \a arr[i] is not allocated. + * \throw If \a arr[i]->getNumberOfComponents() != 1. + */ +DataArrayInt *DataArrayInt::BuildUnion(const std::vector& arr) +{ + std::vector a; + for(std::vector::const_iterator it4=arr.begin();it4!=arr.end();it4++) + if(*it4) + a.push_back(*it4); + for(std::vector::const_iterator it=a.begin();it!=a.end();it++) + { + (*it)->checkAllocated(); + if((*it)->getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::BuildUnion : only single component allowed !"); + } + // + std::set r; + for(std::vector::const_iterator it=a.begin();it!=a.end();it++) + { + const int *pt=(*it)->getConstPointer(); + int nbOfTuples=(*it)->getNumberOfTuples(); + r.insert(pt,pt+nbOfTuples); + } + DataArrayInt *ret=DataArrayInt::New(); + ret->alloc((int)r.size(),1); + std::copy(r.begin(),r.end(),ret->getPointer()); + return ret; +} + +/*! + * Returns a new DataArrayInt which contains elements present in each of given one-dimensional + * arrays. The result array does not contain any duplicates and its values + * are sorted in ascending order. + * \param [in] arr - sequence of DataArrayInt's to intersect. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If any \a arr[i] is not allocated. + * \throw If \a arr[i]->getNumberOfComponents() != 1. + */ +DataArrayInt *DataArrayInt::BuildIntersection(const std::vector& arr) +{ + std::vector a; + for(std::vector::const_iterator it4=arr.begin();it4!=arr.end();it4++) + if(*it4) + a.push_back(*it4); + for(std::vector::const_iterator it=a.begin();it!=a.end();it++) + { + (*it)->checkAllocated(); + if((*it)->getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::BuildIntersection : only single component allowed !"); + } + // + std::set r; + for(std::vector::const_iterator it=a.begin();it!=a.end();it++) + { + const int *pt=(*it)->getConstPointer(); + int nbOfTuples=(*it)->getNumberOfTuples(); + std::set s1(pt,pt+nbOfTuples); + if(it!=a.begin()) + { + std::set r2; + std::set_intersection(r.begin(),r.end(),s1.begin(),s1.end(),inserter(r2,r2.end())); + r=r2; + } + else + r=s1; + } + DataArrayInt *ret(DataArrayInt::New()); + ret->alloc((int)r.size(),1); + std::copy(r.begin(),r.end(),ret->getPointer()); + return ret; +} + +/// @cond INTERNAL +namespace ParaMEDMEMImpl +{ + class OpSwitchedOn + { + public: + OpSwitchedOn(int *pt):_pt(pt),_cnt(0) { } + void operator()(const bool& b) { if(b) *_pt++=_cnt; _cnt++; } + private: + int *_pt; + int _cnt; + }; + + class OpSwitchedOff + { + public: + OpSwitchedOff(int *pt):_pt(pt),_cnt(0) { } + void operator()(const bool& b) { if(!b) *_pt++=_cnt; _cnt++; } + private: + int *_pt; + int _cnt; + }; +} +/// @endcond + +/*! + * This method returns the list of ids in ascending mode so that v[id]==true. + */ +DataArrayInt *DataArrayInt::BuildListOfSwitchedOn(const std::vector& v) +{ + int sz((int)std::count(v.begin(),v.end(),true)); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(sz,1); + std::for_each(v.begin(),v.end(),ParaMEDMEMImpl::OpSwitchedOn(ret->getPointer())); + return ret.retn(); +} + +/*! + * This method returns the list of ids in ascending mode so that v[id]==false. + */ +DataArrayInt *DataArrayInt::BuildListOfSwitchedOff(const std::vector& v) +{ + int sz((int)std::count(v.begin(),v.end(),false)); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(sz,1); + std::for_each(v.begin(),v.end(),ParaMEDMEMImpl::OpSwitchedOff(ret->getPointer())); + return ret.retn(); +} + +/*! + * This method allows to put a vector of vector of integer into a more compact data stucture (skyline). + * This method is not available into python because no available optimized data structure available to map std::vector< std::vector >. + * + * \param [in] v the input data structure to be translate into skyline format. + * \param [out] data the first element of the skyline format. The user is expected to deal with newly allocated array. + * \param [out] dataIndex the second element of the skyline format. + */ +void DataArrayInt::PutIntoToSkylineFrmt(const std::vector< std::vector >& v, DataArrayInt *& data, DataArrayInt *& dataIndex) +{ + int sz((int)v.size()); + MEDCouplingAutoRefCountObjectPtr ret0(DataArrayInt::New()),ret1(DataArrayInt::New()); + ret1->alloc(sz+1,1); + int *pt(ret1->getPointer()); *pt=0; + for(int i=0;ialloc(ret1->back(),1); + pt=ret0->getPointer(); + for(int i=0;igetNumberOfComponents() != 1. + * \throw If any element \a x of \a this array violates condition ( 0 <= \a x < \a + * nbOfElement ). + */ +DataArrayInt *DataArrayInt::buildComplement(int nbOfElement) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::buildComplement : only single component allowed !"); + std::vector tmp(nbOfElement); + const int *pt=getConstPointer(); + int nbOfTuples=getNumberOfTuples(); + for(const int *w=pt;w!=pt+nbOfTuples;w++) + if(*w>=0 && *walloc(nbOfRetVal,1); + int j=0; + int *retPtr=ret->getPointer(); + for(int i=0;igetNumberOfComponents() != 1. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \sa DataArrayInt::buildSubstractionOptimized() + */ +DataArrayInt *DataArrayInt::buildSubstraction(const DataArrayInt *other) const +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayInt::buildSubstraction : DataArrayInt pointer in input is NULL !"); + checkAllocated(); + other->checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::buildSubstraction : only single component allowed !"); + if(other->getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::buildSubstraction : only single component allowed for other type !"); + const int *pt=getConstPointer(); + int nbOfTuples=getNumberOfTuples(); + std::set s1(pt,pt+nbOfTuples); + pt=other->getConstPointer(); + nbOfTuples=other->getNumberOfTuples(); + std::set s2(pt,pt+nbOfTuples); + std::vector r; + std::set_difference(s1.begin(),s1.end(),s2.begin(),s2.end(),std::back_insert_iterator< std::vector >(r)); + DataArrayInt *ret=DataArrayInt::New(); + ret->alloc((int)r.size(),1); + std::copy(r.begin(),r.end(),ret->getPointer()); + return ret; +} + +/*! + * \a this is expected to have one component and to be sorted ascendingly (as for \a other). + * \a other is expected to be a part of \a this. If not DataArrayInt::buildSubstraction should be called instead. + * + * \param [in] other an array with one component and expected to be sorted ascendingly. + * \ret list of ids in \a this but not in \a other. + * \sa DataArrayInt::buildSubstraction + */ +DataArrayInt *DataArrayInt::buildSubstractionOptimized(const DataArrayInt *other) const +{ + static const char *MSG="DataArrayInt::buildSubstractionOptimized : only single component allowed !"; + if(!other) throw INTERP_KERNEL::Exception("DataArrayInt::buildSubstractionOptimized : NULL input array !"); + checkAllocated(); other->checkAllocated(); + if(getNumberOfComponents()!=1) throw INTERP_KERNEL::Exception(MSG); + if(other->getNumberOfComponents()!=1) throw INTERP_KERNEL::Exception(MSG); + const int *pt1Bg(begin()),*pt1End(end()),*pt2Bg(other->begin()),*pt2End(other->end()); + const int *work1(pt1Bg),*work2(pt2Bg); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + for(;work1!=pt1End;work1++) + { + if(work2!=pt2End && *work1==*work2) + work2++; + else + ret->pushBackSilent(*work1); + } + return ret.retn(); +} + + +/*! + * Returns a new DataArrayInt which contains all elements of \a this and a given + * one-dimensional arrays. The result array does not contain any duplicates + * and its values are sorted in ascending order. + * \param [in] other - an array to unite with \a this one. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If \a this or \a other is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a other->getNumberOfComponents() != 1. + */ +DataArrayInt *DataArrayInt::buildUnion(const DataArrayInt *other) const +{ + std::vectorarrs(2); + arrs[0]=this; arrs[1]=other; + return BuildUnion(arrs); +} + + +/*! + * Returns a new DataArrayInt which contains elements present in both \a this and a given + * one-dimensional arrays. The result array does not contain any duplicates + * and its values are sorted in ascending order. + * \param [in] other - an array to intersect with \a this one. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If \a this or \a other is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a other->getNumberOfComponents() != 1. + */ +DataArrayInt *DataArrayInt::buildIntersection(const DataArrayInt *other) const +{ + std::vectorarrs(2); + arrs[0]=this; arrs[1]=other; + return BuildIntersection(arrs); +} + +/*! + * This method can be applied on allocated with one component DataArrayInt instance. + * This method is typically relevant for sorted arrays. All consecutive duplicated items in \a this will appear only once in returned DataArrayInt instance. + * Example : if \a this contains [1,2,2,3,3,3,3,4,5,5,7,7,7,19] the returned array will contain [1,2,3,4,5,7,19] + * + * \return a newly allocated array that contain the result of the unique operation applied on \a this. + * \throw if \a this is not allocated or if \a this has not exactly one component. + * \sa DataArrayInt::buildUniqueNotSorted + */ +DataArrayInt *DataArrayInt::buildUnique() const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::buildUnique : only single component allowed !"); + int nbOfTuples=getNumberOfTuples(); + MEDCouplingAutoRefCountObjectPtr tmp=deepCpy(); + int *data=tmp->getPointer(); + int *last=std::unique(data,data+nbOfTuples); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(std::distance(data,last),1); + std::copy(data,last,ret->getPointer()); + return ret.retn(); +} + +/*! + * This method can be applied on allocated with one component DataArrayInt instance. + * This method keep elements only once by keeping the same order in \a this that is not expected to be sorted. + * + * \return a newly allocated array that contain the result of the unique operation applied on \a this. + * + * \throw if \a this is not allocated or if \a this has not exactly one component. + * + * \sa DataArrayInt::buildUnique + */ +DataArrayInt *DataArrayInt::buildUniqueNotSorted() const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::buildUniqueNotSorted : only single component allowed !"); + int minVal,maxVal; + getMinMaxValues(minVal,maxVal); + std::vector b(maxVal-minVal+1,false); + const int *ptBg(begin()),*endBg(end()); + MEDCouplingAutoRefCountObjectPtr ret(DataArrayInt::New()); ret->alloc(0,1); + for(const int *pt=ptBg;pt!=endBg;pt++) + { + if(!b[*pt-minVal]) + { + ret->pushBackSilent(*pt); + b[*pt-minVal]=true; + } + } + ret->copyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * Returns a new DataArrayInt which contains size of every of groups described by \a this + * "index" array. Such "index" array is returned for example by + * \ref ParaMEDMEM::MEDCouplingUMesh::buildDescendingConnectivity + * "MEDCouplingUMesh::buildDescendingConnectivity" and + * \ref ParaMEDMEM::MEDCouplingUMesh::getNodalConnectivityIndex + * "MEDCouplingUMesh::getNodalConnectivityIndex" etc. + * This method preforms the reverse operation of DataArrayInt::computeOffsets2. + * \return DataArrayInt * - a new instance of DataArrayInt, whose number of tuples + * equals to \a this->getNumberOfComponents() - 1, and number of components is 1. + * The caller is to delete this array using decrRef() as it is no more needed. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If \a this->getNumberOfTuples() < 2. + * + * \b Example:
+ * - this contains [1,3,6,7,7,9,15] + * - result array contains [2,3,1,0,2,6], + * where 2 = 3 - 1, 3 = 6 - 3, 1 = 7 - 6 etc. + * + * \sa DataArrayInt::computeOffsets2 + */ +DataArrayInt *DataArrayInt::deltaShiftIndex() const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::deltaShiftIndex : only single component allowed !"); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples<2) + throw INTERP_KERNEL::Exception("DataArrayInt::deltaShiftIndex : 1 tuple at least must be present in 'this' !"); + const int *ptr=getConstPointer(); + DataArrayInt *ret=DataArrayInt::New(); + ret->alloc(nbOfTuples-1,1); + int *out=ret->getPointer(); + std::transform(ptr+1,ptr+nbOfTuples,ptr,out,std::minus()); + return ret; +} + +/*! + * Modifies \a this one-dimensional array so that value of each element \a x + * of \a this array (\a a) is computed as \f$ x_i = \sum_{j=0}^{i-1} a[ j ] \f$. + * Or: for each i>0 new[i]=new[i-1]+old[i-1] for i==0 new[i]=0. Number of tuples + * and components remains the same.
+ * This method is useful for allToAllV in MPI with contiguous policy. This method + * differs from computeOffsets2() in that the number of tuples is \b not changed by + * this one. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * + * \b Example:
+ * - Before \a this contains [3,5,1,2,0,8] + * - After \a this contains [0,3,8,9,11,11]
+ * Note that the last element 19 = 11 + 8 is missing because size of \a this + * array is retained and thus there is no space to store the last element. + */ +void DataArrayInt::computeOffsets() +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::computeOffsets : only single component allowed !"); + int nbOfTuples=getNumberOfTuples(); + if(nbOfTuples==0) + return ; + int *work=getPointer(); + int tmp=work[0]; + work[0]=0; + for(int i=1;i0 new[i]=new[i-1]+old[i-1] for i==0 new[i]=0. Number + * components remains the same and number of tuples is inceamented by one.
+ * This method is useful for allToAllV in MPI with contiguous policy. This method + * differs from computeOffsets() in that the number of tuples is changed by this one. + * This method preforms the reverse operation of DataArrayInt::deltaShiftIndex. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * + * \b Example:
+ * - Before \a this contains [3,5,1,2,0,8] + * - After \a this contains [0,3,8,9,11,11,19]
+ * \sa DataArrayInt::deltaShiftIndex + */ +void DataArrayInt::computeOffsets2() +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::computeOffsets2 : only single component allowed !"); + int nbOfTuples=getNumberOfTuples(); + int *ret=(int *)malloc((nbOfTuples+1)*sizeof(int)); + if(nbOfTuples==0) + return ; + const int *work=getConstPointer(); + ret[0]=0; + for(int i=0;igetNumberOfComponents() ranges, all ids in \a listOfIds + * filling completely one of the ranges in \a this. + * + * \param [in] listOfIds a list of ids that has to be sorted ascendingly. + * \param [out] rangeIdsFetched the range ids fetched + * \param [out] idsInInputListThatFetch contains the list of ids in \a listOfIds that are \b fully included in a range in \a this. So + * \a idsInInputListThatFetch is a part of input \a listOfIds. + * + * \sa DataArrayInt::computeOffsets2 + * + * \b Example:
+ * - \a this : [0,3,7,9,15,18] + * - \a listOfIds contains [0,1,2,3,7,8,15,16,17] + * - \a rangeIdsFetched result array: [0,2,4] + * - \a idsInInputListThatFetch result array: [0,1,2,7,8,15,16,17] + * In this example id 3 in input \a listOfIds is alone so it do not appear in output \a idsInInputListThatFetch. + *
+ */ +void DataArrayInt::searchRangesInListOfIds(const DataArrayInt *listOfIds, DataArrayInt *& rangeIdsFetched, DataArrayInt *& idsInInputListThatFetch) const +{ + if(!listOfIds) + throw INTERP_KERNEL::Exception("DataArrayInt::searchRangesInListOfIds : input list of ids is null !"); + listOfIds->checkAllocated(); checkAllocated(); + if(listOfIds->getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::searchRangesInListOfIds : input list of ids must have exactly one component !"); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::searchRangesInListOfIds : this must have exactly one component !"); + MEDCouplingAutoRefCountObjectPtr ret0=DataArrayInt::New(); ret0->alloc(0,1); + MEDCouplingAutoRefCountObjectPtr ret1=DataArrayInt::New(); ret1->alloc(0,1); + const int *tupEnd(listOfIds->end()),*offBg(begin()),*offEnd(end()-1); + const int *tupPtr(listOfIds->begin()),*offPtr(offBg); + while(tupPtr!=tupEnd && offPtr!=offEnd) + { + if(*tupPtr==*offPtr) + { + int i=offPtr[0]; + while(ipushBackSilent((int)std::distance(offBg,offPtr)); + ret1->pushBackValsSilent(tupPtr-(offPtr[1]-offPtr[0]),tupPtr); + offPtr++; + } + } + else + { if(*tupPtr<*offPtr) tupPtr++; else offPtr++; } + } + rangeIdsFetched=ret0.retn(); + idsInInputListThatFetch=ret1.retn(); +} + +/*! + * Returns a new DataArrayInt whose contents is computed from that of \a this and \a + * offsets arrays as follows. \a offsets is a one-dimensional array considered as an + * "index" array of a "iota" array, thus, whose each element gives an index of a group + * beginning within the "iota" array. And \a this is a one-dimensional array + * considered as a selector of groups described by \a offsets to include into the result array. + * \throw If \a offsets is NULL. + * \throw If \a offsets is not allocated. + * \throw If \a offsets->getNumberOfComponents() != 1. + * \throw If \a offsets is not monotonically increasing. + * \throw If \a this is not allocated. + * \throw If \a this->getNumberOfComponents() != 1. + * \throw If any element of \a this is not a valid index for \a offsets array. + * + * \b Example:
+ * - \a this: [0,2,3] + * - \a offsets: [0,3,6,10,14,20] + * - result array: [0,1,2,6,7,8,9,10,11,12,13] ==
+ * \c range(0,3) + \c range(6,10) + \c range(10,14) ==
+ * \c range( \a offsets[ \a this[0] ], offsets[ \a this[0]+1 ]) + + * \c range( \a offsets[ \a this[1] ], offsets[ \a this[1]+1 ]) + + * \c range( \a offsets[ \a this[2] ], offsets[ \a this[2]+1 ]) + */ +DataArrayInt *DataArrayInt::buildExplicitArrByRanges(const DataArrayInt *offsets) const +{ + if(!offsets) + throw INTERP_KERNEL::Exception("DataArrayInt::buildExplicitArrByRanges : DataArrayInt pointer in input is NULL !"); + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::buildExplicitArrByRanges : only single component allowed !"); + offsets->checkAllocated(); + if(offsets->getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::buildExplicitArrByRanges : input array should have only single component !"); + int othNbTuples=offsets->getNumberOfTuples()-1; + int nbOfTuples=getNumberOfTuples(); + int retNbOftuples=0; + const int *work=getConstPointer(); + const int *offPtr=offsets->getConstPointer(); + for(int i=0;i=0 && val=0) + retNbOftuples+=delta; + else + { + std::ostringstream oss; oss << "DataArrayInt::buildExplicitArrByRanges : Tuple #" << val << " of offset array has a delta < 0 !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + else + { + std::ostringstream oss; oss << "DataArrayInt::buildExplicitArrByRanges : Tuple #" << i << " in this contains " << val; + oss << " whereas offsets array is of size " << othNbTuples+1 << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(retNbOftuples,1); + int *retPtr=ret->getPointer(); + for(int i=0;igetNumberOfComponents() != 1. + * \throw If \a this->getNumberOfTuples() == 0. + * \throw If \a this is not monotonically increasing. + * \throw If any element of ids in ( \a bg \a stop \a step ) points outside the scale in \a this. + * + * \b Example:
+ * - \a bg , \a stop and \a step : (0,5,2) + * - \a this: [0,3,6,10,14,20] + * - result array: [0,0,0, 2,2,2,2, 4,4,4,4,4,4] ==
+ */ +DataArrayInt *DataArrayInt::buildExplicitArrOfSliceOnScaledArr(int bg, int stop, int step) const +{ + if(!isAllocated()) + throw INTERP_KERNEL::Exception("DataArrayInt::buildExplicitArrOfSliceOnScaledArr : not allocated array !"); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::buildExplicitArrOfSliceOnScaledArr : number of components is expected to be equal to one !"); + int nbOfTuples(getNumberOfTuples()); + if(nbOfTuples==0) + throw INTERP_KERNEL::Exception("DataArrayInt::buildExplicitArrOfSliceOnScaledArr : number of tuples must be != 0 !"); + const int *ids(begin()); + int nbOfEltsInSlc(GetNumberOfItemGivenBESRelative(bg,stop,step,"DataArrayInt::buildExplicitArrOfSliceOnScaledArr")),sz(0),pos(bg); + for(int i=0;i=0 && pos ret(DataArrayInt::New()); ret->alloc(sz,1); + int *retPtr(ret->getPointer()); + pos=bg; + for(int i=0;igetIJ(i,0) and put the result + * in tuple **i** of returned DataArrayInt. + * If ranges overlapped (in theory it should not) this method do not detect it and always returns the first range. + * + * For example if \a this contains : [1,24,7,8,10,17] and \a ranges contains [(0,3),(3,8),(8,15),(15,22),(22,30)] + * The return DataArrayInt will contain : **[0,4,1,2,2,3]** + * + * \param [in] ranges typically come from output of MEDCouplingUMesh::ComputeRangesFromTypeDistribution. Each range is specified like this : 1st component is + * for lower value included and 2nd component is the upper value of corresponding range **excluded**. + * \throw If offsets is a null pointer or does not have 2 components or if \a this is not allocated or \a this do not have exactly one component. To finish an exception + * is thrown if no ranges in \a ranges contains value in \a this. + * + * \sa DataArrayInt::findIdInRangeForEachTuple + */ +DataArrayInt *DataArrayInt::findRangeIdForEachTuple(const DataArrayInt *ranges) const +{ + if(!ranges) + throw INTERP_KERNEL::Exception("DataArrayInt::findRangeIdForEachTuple : null input pointer !"); + if(ranges->getNumberOfComponents()!=2) + throw INTERP_KERNEL::Exception("DataArrayInt::findRangeIdForEachTuple : input DataArrayInt instance should have 2 components !"); + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::findRangeIdForEachTuple : this should have only one component !"); + int nbTuples=getNumberOfTuples(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); ret->alloc(nbTuples,1); + int nbOfRanges=ranges->getNumberOfTuples(); + const int *rangesPtr=ranges->getConstPointer(); + int *retPtr=ret->getPointer(); + const int *inPtr=getConstPointer(); + for(int i=0;i=rangesPtr[2*j] && valgetIJ(i,0) and put the result + * in tuple **i** of returned DataArrayInt. + * If ranges overlapped (in theory it should not) this method do not detect it and always returns the sub position of the first range. + * + * For example if \a this contains : [1,24,7,8,10,17] and \a ranges contains [(0,3),(3,8),(8,15),(15,22),(22,30)] + * The return DataArrayInt will contain : **[1,2,4,0,2,2]** + * This method is often called in pair with DataArrayInt::findRangeIdForEachTuple method. + * + * \param [in] ranges typically come from output of MEDCouplingUMesh::ComputeRangesFromTypeDistribution. Each range is specified like this : 1st component is + * for lower value included and 2nd component is the upper value of corresponding range **excluded**. + * \throw If offsets is a null pointer or does not have 2 components or if \a this is not allocated or \a this do not have exactly one component. To finish an exception + * is thrown if no ranges in \a ranges contains value in \a this. + * \sa DataArrayInt::findRangeIdForEachTuple + */ +DataArrayInt *DataArrayInt::findIdInRangeForEachTuple(const DataArrayInt *ranges) const +{ + if(!ranges) + throw INTERP_KERNEL::Exception("DataArrayInt::findIdInRangeForEachTuple : null input pointer !"); + if(ranges->getNumberOfComponents()!=2) + throw INTERP_KERNEL::Exception("DataArrayInt::findIdInRangeForEachTuple : input DataArrayInt instance should have 2 components !"); + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::findIdInRangeForEachTuple : this should have only one component !"); + int nbTuples=getNumberOfTuples(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); ret->alloc(nbTuples,1); + int nbOfRanges=ranges->getNumberOfTuples(); + const int *rangesPtr=ranges->getConstPointer(); + int *retPtr=ret->getPointer(); + const int *inPtr=getConstPointer(); + for(int i=0;i=rangesPtr[2*j] && valgetIJ(tid,0)==this->getIJ(tid-1,1) and \c this->getIJ(tid,1)==this->getIJ(tid+1,0). + * If it is impossible to reach such condition an exception will be thrown ! \b WARNING In case of throw \a this can be partially modified ! + * If this method has correctly worked, \a this will be able to be considered as a linked list. + * This method does nothing if number of tuples is lower of equal to 1. + * + * This method is useful for users having an unstructured mesh having only SEG2 to rearrange internaly the connectibity without any coordinates consideration. + * + * \sa MEDCouplingUMesh::orderConsecutiveCells1D + */ +void DataArrayInt::sortEachPairToMakeALinkedList() +{ + checkAllocated(); + if(getNumberOfComponents()!=2) + throw INTERP_KERNEL::Exception("DataArrayInt::sortEachPairToMakeALinkedList : Only works on DataArrayInt instance with nb of components equal to 2 !"); + int nbOfTuples(getNumberOfTuples()); + if(nbOfTuples<=1) + return ; + int *conn(getPointer()); + for(int i=1;i1) + { + if(conn[2]==conn[3]) + { + std::ostringstream oss; oss << "DataArrayInt::sortEachPairToMakeALinkedList : In the tuple #" << i << " presence of a pair filled with same ids !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + if(conn[2]!=conn[1] && conn[3]==conn[1] && conn[2]!=conn[0]) + std::swap(conn[2],conn[3]); + //not(conn[2]==conn[1] && conn[3]!=conn[1] && conn[3]!=conn[0]) + if(conn[2]!=conn[1] || conn[3]==conn[1] || conn[3]==conn[0]) + { + std::ostringstream oss; oss << "DataArrayInt::sortEachPairToMakeALinkedList : In the tuple #" << i << " something is invalid !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + else + { + if(conn[0]==conn[1] || conn[2]==conn[3]) + throw INTERP_KERNEL::Exception("DataArrayInt::sortEachPairToMakeALinkedList : In the 2 first tuples presence of a pair filled with same ids !"); + int tmp[4]; + std::set s; + s.insert(conn,conn+4); + if(s.size()!=3) + throw INTERP_KERNEL::Exception("DataArrayInt::sortEachPairToMakeALinkedList : This can't be considered as a linked list regarding 2 first tuples !"); + if(std::count(conn,conn+4,conn[0])==2) + { + tmp[0]=conn[1]; + tmp[1]=conn[0]; + tmp[2]=conn[0]; + if(conn[2]==conn[0]) + { tmp[3]=conn[3]; } + else + { tmp[3]=conn[2];} + std::copy(tmp,tmp+4,conn); + } + } + } +} + +/*! + * + * \param [in] nbTimes specifies the nb of times each tuples in \a this will be duplicated contiguouly in returned DataArrayInt instance. + * \a nbTimes should be at least equal to 1. + * \return a newly allocated DataArrayInt having one component and number of tuples equal to \a nbTimes * \c this->getNumberOfTuples. + * \throw if \a this is not allocated or if \a this has not number of components set to one or if \a nbTimes is lower than 1. + */ +DataArrayInt *DataArrayInt::duplicateEachTupleNTimes(int nbTimes) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::duplicateEachTupleNTimes : this should have only one component !"); + if(nbTimes<1) + throw INTERP_KERNEL::Exception("DataArrayInt::duplicateEachTupleNTimes : nb times should be >= 1 !"); + int nbTuples=getNumberOfTuples(); + const int *inPtr=getConstPointer(); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); ret->alloc(nbTimes*nbTuples,1); + int *retPtr=ret->getPointer(); + for(int i=0;icopyStringInfoFrom(*this); + return ret.retn(); +} + +/*! + * This method returns all different values found in \a this. This method throws if \a this has not been allocated. + * But the number of components can be different from one. + * \return a newly allocated array (that should be dealt by the caller) containing different values in \a this. + */ +DataArrayInt *DataArrayInt::getDifferentValues() const +{ + checkAllocated(); + std::set ret; + ret.insert(begin(),end()); + MEDCouplingAutoRefCountObjectPtr ret2=DataArrayInt::New(); ret2->alloc((int)ret.size(),1); + std::copy(ret.begin(),ret.end(),ret2->getPointer()); + return ret2.retn(); +} + +/*! + * This method is a refinement of DataArrayInt::getDifferentValues because it returns not only different values in \a this but also, for each of + * them it tells which tuple id have this id. + * This method works only on arrays with one component (if it is not the case call DataArrayInt::rearrange(1) ). + * This method returns two arrays having same size. + * The instances of DataArrayInt in the returned vector have be specially allocated and computed by this method. Each of them should be dealt by the caller of this method. + * Example : if this is equal to [1,0,1,2,0,2,2,-3,2] -> differentIds=[-3,0,1,2] and returned array will be equal to [[7],[1,4],[0,2],[3,5,6,8]] + */ +std::vector DataArrayInt::partitionByDifferentValues(std::vector& differentIds) const +{ + checkAllocated(); + if(getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::partitionByDifferentValues : this should have only one component !"); + int id=0; + std::map m,m2,m3; + for(const int *w=begin();w!=end();w++) + m[*w]++; + differentIds.resize(m.size()); + std::vector ret(m.size()); + std::vector retPtr(m.size()); + for(std::map::const_iterator it=m.begin();it!=m.end();it++,id++) + { + m2[(*it).first]=id; + ret[id]=DataArrayInt::New(); + ret[id]->alloc((*it).second,1); + retPtr[id]=ret[id]->getPointer(); + differentIds[id]=(*it).first; + } + id=0; + for(const int *w=begin();w!=end();w++,id++) + { + retPtr[m2[*w]][m3[*w]++]=id; + } + return ret; +} + +/*! + * This method split ids in [0, \c this->getNumberOfTuples() ) using \a this array as a field of weight (>=0 each). + * The aim of this method is to return a set of \a nbOfSlices chunk of contiguous ids as balanced as possible. + * + * \param [in] nbOfSlices - number of slices expected. + * \return - a vector having a size equal to \a nbOfSlices giving the start (included) and the stop (excluded) of each chunks. + * + * \sa DataArray::GetSlice + * \throw If \a this is not allocated or not with exactly one component. + * \throw If an element in \a this if < 0. + */ +std::vector< std::pair > DataArrayInt::splitInBalancedSlices(int nbOfSlices) const +{ + if(!isAllocated() || getNumberOfComponents()!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::splitInBalancedSlices : this array should have number of components equal to one and must be allocated !"); + if(nbOfSlices<=0) + throw INTERP_KERNEL::Exception("DataArrayInt::splitInBalancedSlices : number of slices must be >= 1 !"); + int sum(accumulate(0)),nbOfTuples(getNumberOfTuples()); + int sumPerSlc(sum/nbOfSlices),pos(0); + const int *w(begin()); + std::vector< std::pair > ret(nbOfSlices); + for(int i=0;i p(pos,-1); + int locSum(0); + while(locSumgetNumberOfTuples() != \a a2->getNumberOfTuples() and + * \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() and + * none of them has number of tuples or components equal to 1. + */ +DataArrayInt *DataArrayInt::Add(const DataArrayInt *a1, const DataArrayInt *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayInt::Add : input DataArrayInt instance is NULL !"); + int nbOfTuple=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + int nbOfComp=a1->getNumberOfComponents(); + int nbOfComp2=a2->getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=0; + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + ret=DataArrayInt::New(); + ret->alloc(nbOfTuple,nbOfComp); + std::transform(a1->begin(),a1->end(),a2->begin(),ret->getPointer(),std::plus()); + ret->copyStringInfoFrom(*a1); + } + else + { + int nbOfCompMin,nbOfCompMax; + const DataArrayInt *aMin, *aMax; + if(nbOfComp>nbOfComp2) + { + nbOfCompMin=nbOfComp2; nbOfCompMax=nbOfComp; + aMin=a2; aMax=a1; + } + else + { + nbOfCompMin=nbOfComp; nbOfCompMax=nbOfComp2; + aMin=a1; aMax=a2; + } + if(nbOfCompMin==1) + { + ret=DataArrayInt::New(); + ret->alloc(nbOfTuple,nbOfCompMax); + const int *aMinPtr=aMin->getConstPointer(); + const int *aMaxPtr=aMax->getConstPointer(); + int *res=ret->getPointer(); + for(int i=0;i(),aMinPtr[i])); + ret->copyStringInfoFrom(*aMax); + } + else + throw INTERP_KERNEL::Exception("Nb of components mismatch for array Add !"); + } + } + else if((nbOfTuple==1 && nbOfTuple2>1) || (nbOfTuple>1 && nbOfTuple2==1)) + { + if(nbOfComp==nbOfComp2) + { + int nbOfTupleMax=std::max(nbOfTuple,nbOfTuple2); + const DataArrayInt *aMin=nbOfTuple>nbOfTuple2?a2:a1; + const DataArrayInt *aMax=nbOfTuple>nbOfTuple2?a1:a2; + const int *aMinPtr=aMin->getConstPointer(),*aMaxPtr=aMax->getConstPointer(); + ret=DataArrayInt::New(); + ret->alloc(nbOfTupleMax,nbOfComp); + int *res=ret->getPointer(); + for(int i=0;i()); + ret->copyStringInfoFrom(*aMax); + } + else + throw INTERP_KERNEL::Exception("Nb of components mismatch for array Add !"); + } + else + throw INTERP_KERNEL::Exception("Nb of tuples mismatch for array Add !"); + return ret.retn(); +} + +/*! + * Adds values of another DataArrayInt to values of \a this one. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * \a other array is added to the corresponding value of \a this array, i.e.: + * _a_ [ i, j ] += _other_ [ i, j ]. + * 2. The arrays have same number of tuples and \a other array has one component. Then + * _a_ [ i, j ] += _other_ [ i, 0 ]. + * 3. The arrays have same number of components and \a other array has one tuple. Then + * _a_ [ i, j ] += _a2_ [ 0, j ]. + * + * \param [in] other - an array to add to \a this one. + * \throw If \a other is NULL. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples() and + * \a this->getNumberOfComponents() != \a other->getNumberOfComponents() and + * \a other has number of both tuples and components not equal to 1. + */ +void DataArrayInt::addEqual(const DataArrayInt *other) +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayInt::addEqual : input DataArrayInt instance is NULL !"); + const char *msg="Nb of tuples mismatch for DataArrayInt::addEqual !"; + checkAllocated(); other->checkAllocated(); + int nbOfTuple=getNumberOfTuples(); + int nbOfTuple2=other->getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + std::transform(begin(),end(),other->begin(),getPointer(),std::plus()); + } + else if(nbOfComp2==1) + { + int *ptr=getPointer(); + const int *ptrc=other->getConstPointer(); + for(int i=0;i(),*ptrc++)); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else if(nbOfTuple2==1) + { + if(nbOfComp2==nbOfComp) + { + int *ptr=getPointer(); + const int *ptrc=other->getConstPointer(); + for(int i=0;i()); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else + throw INTERP_KERNEL::Exception(msg); + declareAsNew(); +} + +/*! + * Returns a new DataArrayInt that is a subtraction of two given arrays. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * the result array (_a_) is a subtraction of the corresponding values of \a a1 and + * \a a2, i.e.: _a_ [ i, j ] = _a1_ [ i, j ] - _a2_ [ i, j ]. + * 2. The arrays have same number of tuples and one array, say _a2_, has one + * component. Then + * _a_ [ i, j ] = _a1_ [ i, j ] - _a2_ [ i, 0 ]. + * 3. The arrays have same number of components and one array, say _a2_, has one + * tuple. Then + * _a_ [ i, j ] = _a1_ [ i, j ] - _a2_ [ 0, j ]. + * + * Info on components is copied either from the first array (in the first case) or from + * the array with maximal number of elements (getNbOfElems()). + * \param [in] a1 - an array to subtract from. + * \param [in] a2 - an array to subtract. + * \return DataArrayInt * - the new instance of DataArrayInt. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() and + * \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() and + * none of them has number of tuples or components equal to 1. + */ +DataArrayInt *DataArrayInt::Substract(const DataArrayInt *a1, const DataArrayInt *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayInt::Substract : input DataArrayInt instance is NULL !"); + int nbOfTuple1=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + int nbOfComp1=a1->getNumberOfComponents(); + int nbOfComp2=a2->getNumberOfComponents(); + if(nbOfTuple2==nbOfTuple1) + { + if(nbOfComp1==nbOfComp2) + { + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuple2,nbOfComp1); + std::transform(a1->begin(),a1->end(),a2->begin(),ret->getPointer(),std::minus()); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else if(nbOfComp2==1) + { + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuple1,nbOfComp1); + const int *a2Ptr=a2->getConstPointer(); + const int *a1Ptr=a1->getConstPointer(); + int *res=ret->getPointer(); + for(int i=0;i(),a2Ptr[i])); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else + { + a1->checkNbOfComps(nbOfComp2,"Nb of components mismatch for array Substract !"); + return 0; + } + } + else if(nbOfTuple2==1) + { + a1->checkNbOfComps(nbOfComp2,"Nb of components mismatch for array Substract !"); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuple1,nbOfComp1); + const int *a1ptr=a1->getConstPointer(),*a2ptr=a2->getConstPointer(); + int *pt=ret->getPointer(); + for(int i=0;i()); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else + { + a1->checkNbOfTuples(nbOfTuple2,"Nb of tuples mismatch for array Substract !");//will always throw an exception + return 0; + } +} + +/*! + * Subtract values of another DataArrayInt from values of \a this one. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * \a other array is subtracted from the corresponding value of \a this array, i.e.: + * _a_ [ i, j ] -= _other_ [ i, j ]. + * 2. The arrays have same number of tuples and \a other array has one component. Then + * _a_ [ i, j ] -= _other_ [ i, 0 ]. + * 3. The arrays have same number of components and \a other array has one tuple. Then + * _a_ [ i, j ] -= _a2_ [ 0, j ]. + * + * \param [in] other - an array to subtract from \a this one. + * \throw If \a other is NULL. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples() and + * \a this->getNumberOfComponents() != \a other->getNumberOfComponents() and + * \a other has number of both tuples and components not equal to 1. + */ +void DataArrayInt::substractEqual(const DataArrayInt *other) +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayInt::substractEqual : input DataArrayInt instance is NULL !"); + const char *msg="Nb of tuples mismatch for DataArrayInt::substractEqual !"; + checkAllocated(); other->checkAllocated(); + int nbOfTuple=getNumberOfTuples(); + int nbOfTuple2=other->getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + std::transform(begin(),end(),other->begin(),getPointer(),std::minus()); + } + else if(nbOfComp2==1) + { + int *ptr=getPointer(); + const int *ptrc=other->getConstPointer(); + for(int i=0;i(),*ptrc++)); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else if(nbOfTuple2==1) + { + int *ptr=getPointer(); + const int *ptrc=other->getConstPointer(); + for(int i=0;i()); + } + else + throw INTERP_KERNEL::Exception(msg); + declareAsNew(); +} + +/*! + * Returns a new DataArrayInt that is a product of two given arrays. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * the result array (_a_) is a product of the corresponding values of \a a1 and + * \a a2, i.e.: _a_ [ i, j ] = _a1_ [ i, j ] * _a2_ [ i, j ]. + * 2. The arrays have same number of tuples and one array, say _a2_, has one + * component. Then + * _a_ [ i, j ] = _a1_ [ i, j ] * _a2_ [ i, 0 ]. + * 3. The arrays have same number of components and one array, say _a2_, has one + * tuple. Then + * _a_ [ i, j ] = _a1_ [ i, j ] * _a2_ [ 0, j ]. + * + * Info on components is copied either from the first array (in the first case) or from + * the array with maximal number of elements (getNbOfElems()). + * \param [in] a1 - a factor array. + * \param [in] a2 - another factor array. + * \return DataArrayInt * - the new instance of DataArrayInt. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() and + * \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() and + * none of them has number of tuples or components equal to 1. + */ +DataArrayInt *DataArrayInt::Multiply(const DataArrayInt *a1, const DataArrayInt *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayInt::Multiply : input DataArrayInt instance is NULL !"); + int nbOfTuple=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + int nbOfComp=a1->getNumberOfComponents(); + int nbOfComp2=a2->getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr ret=0; + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + ret=DataArrayInt::New(); + ret->alloc(nbOfTuple,nbOfComp); + std::transform(a1->begin(),a1->end(),a2->begin(),ret->getPointer(),std::multiplies()); + ret->copyStringInfoFrom(*a1); + } + else + { + int nbOfCompMin,nbOfCompMax; + const DataArrayInt *aMin, *aMax; + if(nbOfComp>nbOfComp2) + { + nbOfCompMin=nbOfComp2; nbOfCompMax=nbOfComp; + aMin=a2; aMax=a1; + } + else + { + nbOfCompMin=nbOfComp; nbOfCompMax=nbOfComp2; + aMin=a1; aMax=a2; + } + if(nbOfCompMin==1) + { + ret=DataArrayInt::New(); + ret->alloc(nbOfTuple,nbOfCompMax); + const int *aMinPtr=aMin->getConstPointer(); + const int *aMaxPtr=aMax->getConstPointer(); + int *res=ret->getPointer(); + for(int i=0;i(),aMinPtr[i])); + ret->copyStringInfoFrom(*aMax); + } + else + throw INTERP_KERNEL::Exception("Nb of components mismatch for array Multiply !"); + } + } + else if((nbOfTuple==1 && nbOfTuple2>1) || (nbOfTuple>1 && nbOfTuple2==1)) + { + if(nbOfComp==nbOfComp2) + { + int nbOfTupleMax=std::max(nbOfTuple,nbOfTuple2); + const DataArrayInt *aMin=nbOfTuple>nbOfTuple2?a2:a1; + const DataArrayInt *aMax=nbOfTuple>nbOfTuple2?a1:a2; + const int *aMinPtr=aMin->getConstPointer(),*aMaxPtr=aMax->getConstPointer(); + ret=DataArrayInt::New(); + ret->alloc(nbOfTupleMax,nbOfComp); + int *res=ret->getPointer(); + for(int i=0;i()); + ret->copyStringInfoFrom(*aMax); + } + else + throw INTERP_KERNEL::Exception("Nb of components mismatch for array Multiply !"); + } + else + throw INTERP_KERNEL::Exception("Nb of tuples mismatch for array Multiply !"); + return ret.retn(); +} + + +/*! + * Multiply values of another DataArrayInt to values of \a this one. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * \a other array is multiplied to the corresponding value of \a this array, i.e.: + * _a_ [ i, j ] *= _other_ [ i, j ]. + * 2. The arrays have same number of tuples and \a other array has one component. Then + * _a_ [ i, j ] *= _other_ [ i, 0 ]. + * 3. The arrays have same number of components and \a other array has one tuple. Then + * _a_ [ i, j ] *= _a2_ [ 0, j ]. + * + * \param [in] other - an array to multiply to \a this one. + * \throw If \a other is NULL. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples() and + * \a this->getNumberOfComponents() != \a other->getNumberOfComponents() and + * \a other has number of both tuples and components not equal to 1. + */ +void DataArrayInt::multiplyEqual(const DataArrayInt *other) +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayInt::multiplyEqual : input DataArrayInt instance is NULL !"); + const char *msg="Nb of tuples mismatch for DataArrayInt::multiplyEqual !"; + checkAllocated(); other->checkAllocated(); + int nbOfTuple=getNumberOfTuples(); + int nbOfTuple2=other->getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + std::transform(begin(),end(),other->begin(),getPointer(),std::multiplies()); + } + else if(nbOfComp2==1) + { + int *ptr=getPointer(); + const int *ptrc=other->getConstPointer(); + for(int i=0;i(),*ptrc++)); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else if(nbOfTuple2==1) + { + if(nbOfComp2==nbOfComp) + { + int *ptr=getPointer(); + const int *ptrc=other->getConstPointer(); + for(int i=0;i()); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else + throw INTERP_KERNEL::Exception(msg); + declareAsNew(); +} + + +/*! + * Returns a new DataArrayInt that is a division of two given arrays. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * the result array (_a_) is a division of the corresponding values of \a a1 and + * \a a2, i.e.: _a_ [ i, j ] = _a1_ [ i, j ] / _a2_ [ i, j ]. + * 2. The arrays have same number of tuples and one array, say _a2_, has one + * component. Then + * _a_ [ i, j ] = _a1_ [ i, j ] / _a2_ [ i, 0 ]. + * 3. The arrays have same number of components and one array, say _a2_, has one + * tuple. Then + * _a_ [ i, j ] = _a1_ [ i, j ] / _a2_ [ 0, j ]. + * + * Info on components is copied either from the first array (in the first case) or from + * the array with maximal number of elements (getNbOfElems()). + * \warning No check of division by zero is performed! + * \param [in] a1 - a numerator array. + * \param [in] a2 - a denominator array. + * \return DataArrayInt * - the new instance of DataArrayInt. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() and + * \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() and + * none of them has number of tuples or components equal to 1. + */ +DataArrayInt *DataArrayInt::Divide(const DataArrayInt *a1, const DataArrayInt *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayInt::Divide : input DataArrayInt instance is NULL !"); + int nbOfTuple1=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + int nbOfComp1=a1->getNumberOfComponents(); + int nbOfComp2=a2->getNumberOfComponents(); + if(nbOfTuple2==nbOfTuple1) + { + if(nbOfComp1==nbOfComp2) + { + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuple2,nbOfComp1); + std::transform(a1->begin(),a1->end(),a2->begin(),ret->getPointer(),std::divides()); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else if(nbOfComp2==1) + { + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuple1,nbOfComp1); + const int *a2Ptr=a2->getConstPointer(); + const int *a1Ptr=a1->getConstPointer(); + int *res=ret->getPointer(); + for(int i=0;i(),a2Ptr[i])); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else + { + a1->checkNbOfComps(nbOfComp2,"Nb of components mismatch for array Divide !"); + return 0; + } + } + else if(nbOfTuple2==1) + { + a1->checkNbOfComps(nbOfComp2,"Nb of components mismatch for array Divide !"); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuple1,nbOfComp1); + const int *a1ptr=a1->getConstPointer(),*a2ptr=a2->getConstPointer(); + int *pt=ret->getPointer(); + for(int i=0;i()); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else + { + a1->checkNbOfTuples(nbOfTuple2,"Nb of tuples mismatch for array Divide !");//will always throw an exception + return 0; + } +} + +/*! + * Divide values of \a this array by values of another DataArrayInt. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * \a this array is divided by the corresponding value of \a other one, i.e.: + * _a_ [ i, j ] /= _other_ [ i, j ]. + * 2. The arrays have same number of tuples and \a other array has one component. Then + * _a_ [ i, j ] /= _other_ [ i, 0 ]. + * 3. The arrays have same number of components and \a other array has one tuple. Then + * _a_ [ i, j ] /= _a2_ [ 0, j ]. + * + * \warning No check of division by zero is performed! + * \param [in] other - an array to divide \a this one by. + * \throw If \a other is NULL. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples() and + * \a this->getNumberOfComponents() != \a other->getNumberOfComponents() and + * \a other has number of both tuples and components not equal to 1. + */ +void DataArrayInt::divideEqual(const DataArrayInt *other) +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayInt::divideEqual : input DataArrayInt instance is NULL !"); + const char *msg="Nb of tuples mismatch for DataArrayInt::divideEqual !"; + checkAllocated(); other->checkAllocated(); + int nbOfTuple=getNumberOfTuples(); + int nbOfTuple2=other->getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + std::transform(begin(),end(),other->begin(),getPointer(),std::divides()); + } + else if(nbOfComp2==1) + { + int *ptr=getPointer(); + const int *ptrc=other->getConstPointer(); + for(int i=0;i(),*ptrc++)); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else if(nbOfTuple2==1) + { + if(nbOfComp2==nbOfComp) + { + int *ptr=getPointer(); + const int *ptrc=other->getConstPointer(); + for(int i=0;i()); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else + throw INTERP_KERNEL::Exception(msg); + declareAsNew(); +} + + +/*! + * Returns a new DataArrayInt that is a modulus of two given arrays. There are 3 + * valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * the result array (_a_) is a division of the corresponding values of \a a1 and + * \a a2, i.e.: _a_ [ i, j ] = _a1_ [ i, j ] % _a2_ [ i, j ]. + * 2. The arrays have same number of tuples and one array, say _a2_, has one + * component. Then + * _a_ [ i, j ] = _a1_ [ i, j ] % _a2_ [ i, 0 ]. + * 3. The arrays have same number of components and one array, say _a2_, has one + * tuple. Then + * _a_ [ i, j ] = _a1_ [ i, j ] % _a2_ [ 0, j ]. + * + * Info on components is copied either from the first array (in the first case) or from + * the array with maximal number of elements (getNbOfElems()). + * \warning No check of division by zero is performed! + * \param [in] a1 - a dividend array. + * \param [in] a2 - a divisor array. + * \return DataArrayInt * - the new instance of DataArrayInt. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() and + * \a a1->getNumberOfComponents() != \a a2->getNumberOfComponents() and + * none of them has number of tuples or components equal to 1. + */ +DataArrayInt *DataArrayInt::Modulus(const DataArrayInt *a1, const DataArrayInt *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayInt::Modulus : input DataArrayInt instance is NULL !"); + int nbOfTuple1=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + int nbOfComp1=a1->getNumberOfComponents(); + int nbOfComp2=a2->getNumberOfComponents(); + if(nbOfTuple2==nbOfTuple1) + { + if(nbOfComp1==nbOfComp2) + { + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuple2,nbOfComp1); + std::transform(a1->begin(),a1->end(),a2->begin(),ret->getPointer(),std::modulus()); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else if(nbOfComp2==1) + { + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuple1,nbOfComp1); + const int *a2Ptr=a2->getConstPointer(); + const int *a1Ptr=a1->getConstPointer(); + int *res=ret->getPointer(); + for(int i=0;i(),a2Ptr[i])); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else + { + a1->checkNbOfComps(nbOfComp2,"Nb of components mismatch for array Modulus !"); + return 0; + } + } + else if(nbOfTuple2==1) + { + a1->checkNbOfComps(nbOfComp2,"Nb of components mismatch for array Modulus !"); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuple1,nbOfComp1); + const int *a1ptr=a1->getConstPointer(),*a2ptr=a2->getConstPointer(); + int *pt=ret->getPointer(); + for(int i=0;i()); + ret->copyStringInfoFrom(*a1); + return ret.retn(); + } + else + { + a1->checkNbOfTuples(nbOfTuple2,"Nb of tuples mismatch for array Modulus !");//will always throw an exception + return 0; + } +} + +/*! + * Modify \a this array so that each value becomes a modulus of division of this value by + * a value of another DataArrayInt. There are 3 valid cases. + * 1. The arrays have same number of tuples and components. Then each value of + * \a this array is divided by the corresponding value of \a other one, i.e.: + * _a_ [ i, j ] %= _other_ [ i, j ]. + * 2. The arrays have same number of tuples and \a other array has one component. Then + * _a_ [ i, j ] %= _other_ [ i, 0 ]. + * 3. The arrays have same number of components and \a other array has one tuple. Then + * _a_ [ i, j ] %= _a2_ [ 0, j ]. + * + * \warning No check of division by zero is performed! + * \param [in] other - a divisor array. + * \throw If \a other is NULL. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples() and + * \a this->getNumberOfComponents() != \a other->getNumberOfComponents() and + * \a other has number of both tuples and components not equal to 1. + */ +void DataArrayInt::modulusEqual(const DataArrayInt *other) +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayInt::modulusEqual : input DataArrayInt instance is NULL !"); + const char *msg="Nb of tuples mismatch for DataArrayInt::modulusEqual !"; + checkAllocated(); other->checkAllocated(); + int nbOfTuple=getNumberOfTuples(); + int nbOfTuple2=other->getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + if(nbOfTuple==nbOfTuple2) + { + if(nbOfComp==nbOfComp2) + { + std::transform(begin(),end(),other->begin(),getPointer(),std::modulus()); + } + else if(nbOfComp2==1) + { + if(nbOfComp2==nbOfComp) + { + int *ptr=getPointer(); + const int *ptrc=other->getConstPointer(); + for(int i=0;i(),*ptrc++)); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else + throw INTERP_KERNEL::Exception(msg); + } + else if(nbOfTuple2==1) + { + int *ptr=getPointer(); + const int *ptrc=other->getConstPointer(); + for(int i=0;i()); + } + else + throw INTERP_KERNEL::Exception(msg); + declareAsNew(); +} + +/*! + * Returns a new DataArrayInt that is the result of pow of two given arrays. There are 3 + * valid cases. + * + * \param [in] a1 - an array to pow up. + * \param [in] a2 - another array to sum up. + * \return DataArrayInt * - the new instance of DataArrayInt. + * The caller is to delete this result array using decrRef() as it is no more + * needed. + * \throw If either \a a1 or \a a2 is NULL. + * \throw If \a a1->getNumberOfTuples() != \a a2->getNumberOfTuples() + * \throw If \a a1->getNumberOfComponents() != 1 or \a a2->getNumberOfComponents() != 1. + * \throw If there is a negative value in \a a2. + */ +DataArrayInt *DataArrayInt::Pow(const DataArrayInt *a1, const DataArrayInt *a2) +{ + if(!a1 || !a2) + throw INTERP_KERNEL::Exception("DataArrayInt::Pow : at least one of input instances is null !"); + int nbOfTuple=a1->getNumberOfTuples(); + int nbOfTuple2=a2->getNumberOfTuples(); + int nbOfComp=a1->getNumberOfComponents(); + int nbOfComp2=a2->getNumberOfComponents(); + if(nbOfTuple!=nbOfTuple2) + throw INTERP_KERNEL::Exception("DataArrayInt::Pow : number of tuples mismatches !"); + if(nbOfComp!=1 || nbOfComp2!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::Pow : number of components of both arrays must be equal to 1 !"); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); ret->alloc(nbOfTuple,1); + const int *ptr1(a1->begin()),*ptr2(a2->begin()); + int *ptr=ret->getPointer(); + for(int i=0;i=0) + { + int tmp=1; + for(int j=0;j<*ptr2;j++) + tmp*=*ptr1; + *ptr=tmp; + } + else + { + std::ostringstream oss; oss << "DataArrayInt::Pow : on tuple #" << i << " of a2 value is < 0 (" << *ptr2 << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + return ret.retn(); +} + +/*! + * Apply pow on values of another DataArrayInt to values of \a this one. + * + * \param [in] other - an array to pow to \a this one. + * \throw If \a other is NULL. + * \throw If \a this->getNumberOfTuples() != \a other->getNumberOfTuples() + * \throw If \a this->getNumberOfComponents() != 1 or \a other->getNumberOfComponents() != 1 + * \throw If there is a negative value in \a other. + */ +void DataArrayInt::powEqual(const DataArrayInt *other) +{ + if(!other) + throw INTERP_KERNEL::Exception("DataArrayInt::powEqual : input instance is null !"); + int nbOfTuple=getNumberOfTuples(); + int nbOfTuple2=other->getNumberOfTuples(); + int nbOfComp=getNumberOfComponents(); + int nbOfComp2=other->getNumberOfComponents(); + if(nbOfTuple!=nbOfTuple2) + throw INTERP_KERNEL::Exception("DataArrayInt::powEqual : number of tuples mismatches !"); + if(nbOfComp!=1 || nbOfComp2!=1) + throw INTERP_KERNEL::Exception("DataArrayInt::powEqual : number of components of both arrays must be equal to 1 !"); + int *ptr=getPointer(); + const int *ptrc=other->begin(); + for(int i=0;i=0) + { + int tmp=1; + for(int j=0;j<*ptrc;j++) + tmp*=*ptr; + *ptr=tmp; + } + else + { + std::ostringstream oss; oss << "DataArrayInt::powEqual : on tuple #" << i << " of other value is < 0 (" << *ptrc << ") !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } + declareAsNew(); +} + +/*! + * Returns a C array which is a renumbering map in "Old to New" mode for the input array. + * This map, if applied to \a start array, would make it sorted. For example, if + * \a start array contents are [9,10,0,6,4,11,3,7] then the contents of the result array is + * [5,6,0,3,2,7,1,4]. + * \param [in] start - pointer to the first element of the array for which the + * permutation map is computed. + * \param [in] end - pointer specifying the end of the array \a start, so that + * the last value of \a start is \a end[ -1 ]. + * \return int * - the result permutation array that the caller is to delete as it is no + * more needed. + * \throw If there are equal values in the input array. + */ +int *DataArrayInt::CheckAndPreparePermutation(const int *start, const int *end) +{ + std::size_t sz=std::distance(start,end); + int *ret=(int *)malloc(sz*sizeof(int)); + int *work=new int[sz]; + std::copy(start,end,work); + std::sort(work,work+sz); + if(std::unique(work,work+sz)!=work+sz) + { + delete [] work; + free(ret); + throw INTERP_KERNEL::Exception("Some elements are equals in the specified array !"); + } + std::map m; + for(int *workPt=work;workPt!=work+sz;workPt++) + m[*workPt]=(int)std::distance(work,workPt); + int *iter2=ret; + for(const int *iter=start;iter!=end;iter++,iter2++) + *iter2=m[*iter]; + delete [] work; + return ret; +} + +/*! + * Returns a new DataArrayInt containing an arithmetic progression + * that is equal to the sequence returned by Python \c range(\a begin,\a end,\a step ) + * function. + * \param [in] begin - the start value of the result sequence. + * \param [in] end - limiting value, so that every value of the result array is less than + * \a end. + * \param [in] step - specifies the increment or decrement. + * \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete this + * array using decrRef() as it is no more needed. + * \throw If \a step == 0. + * \throw If \a end < \a begin && \a step > 0. + * \throw If \a end > \a begin && \a step < 0. + */ +DataArrayInt *DataArrayInt::Range(int begin, int end, int step) +{ + int nbOfTuples=GetNumberOfItemGivenBESRelative(begin,end,step,"DataArrayInt::Range"); + MEDCouplingAutoRefCountObjectPtr ret=DataArrayInt::New(); + ret->alloc(nbOfTuples,1); + int *ptr=ret->getPointer(); + if(step>0) + { + for(int i=begin;iend;i+=step,ptr++) + *ptr=i; + } + return ret.retn(); +} + +/*! + * Useless method for end user. Only for MPI/Corba/File serialsation for multi arrays class. + * Server side. + */ +void DataArrayInt::getTinySerializationIntInformation(std::vector& tinyInfo) const +{ + tinyInfo.resize(2); + if(isAllocated()) + { + tinyInfo[0]=getNumberOfTuples(); + tinyInfo[1]=getNumberOfComponents(); + } + else + { + tinyInfo[0]=-1; + tinyInfo[1]=-1; + } +} + +/*! + * Useless method for end user. Only for MPI/Corba/File serialsation for multi arrays class. + * Server side. + */ +void DataArrayInt::getTinySerializationStrInformation(std::vector& tinyInfo) const +{ + if(isAllocated()) + { + int nbOfCompo=getNumberOfComponents(); + tinyInfo.resize(nbOfCompo+1); + tinyInfo[0]=getName(); + for(int i=0;i& tinyInfoI) +{ + int nbOfTuple=tinyInfoI[0]; + int nbOfComp=tinyInfoI[1]; + if(nbOfTuple!=-1 || nbOfComp!=-1) + { + alloc(nbOfTuple,nbOfComp); + return true; + } + return false; +} + +/*! + * Useless method for end user. Only for MPI/Corba/File serialsation for multi arrays class. + * This method returns if a feeding is needed. + */ +void DataArrayInt::finishUnserialization(const std::vector& tinyInfoI, const std::vector& tinyInfoS) +{ + setName(tinyInfoS[0]); + if(isAllocated()) + { + int nbOfCompo=tinyInfoI[1]; + for(int i=0;iincrRef(); + if(_da->isAllocated()) + { + _nb_comp=da->getNumberOfComponents(); + _nb_tuple=da->getNumberOfTuples(); + _pt=da->getPointer(); + } + } +} + +DataArrayIntIterator::~DataArrayIntIterator() +{ + if(_da) + _da->decrRef(); +} + +DataArrayIntTuple *DataArrayIntIterator::nextt() +{ + if(_tuple_id<_nb_tuple) + { + _tuple_id++; + DataArrayIntTuple *ret=new DataArrayIntTuple(_pt,_nb_comp); + _pt+=_nb_comp; + return ret; + } + else + return 0; +} + +DataArrayIntTuple::DataArrayIntTuple(int *pt, int nbOfComp):_pt(pt),_nb_of_compo(nbOfComp) +{ +} + +std::string DataArrayIntTuple::repr() const +{ + std::ostringstream oss; oss << "("; + for(int i=0;i<_nb_of_compo-1;i++) + oss << _pt[i] << ", "; + oss << _pt[_nb_of_compo-1] << ")"; + return oss.str(); +} + +int DataArrayIntTuple::intValue() const +{ + if(_nb_of_compo==1) + return *_pt; + throw INTERP_KERNEL::Exception("DataArrayIntTuple::intValue : DataArrayIntTuple instance has not exactly 1 component -> Not possible to convert it into an integer !"); +} + +/*! + * This method returns a newly allocated instance the caller should dealed with by a ParaMEDMEM::DataArrayInt::decrRef. + * This method performs \b no copy of data. The content is only referenced using ParaMEDMEM::DataArrayInt::useArray with ownership set to \b false. + * This method throws an INTERP_KERNEL::Exception is it is impossible to match sizes of \b this that is too say \b nbOfCompo=this->_nb_of_elem and \bnbOfTuples==1 or + * \b nbOfCompo=1 and \bnbOfTuples==this->_nb_of_elem. + */ +DataArrayInt *DataArrayIntTuple::buildDAInt(int nbOfTuples, int nbOfCompo) const +{ + if((_nb_of_compo==nbOfCompo && nbOfTuples==1) || (_nb_of_compo==nbOfTuples && nbOfCompo==1)) + { + DataArrayInt *ret=DataArrayInt::New(); + ret->useExternalArrayWithRWAccess(_pt,nbOfTuples,nbOfCompo); + return ret; + } + else + { + std::ostringstream oss; oss << "DataArrayIntTuple::buildDAInt : unable to build a requested DataArrayInt instance with nbofTuple=" << nbOfTuples << " and nbOfCompo=" << nbOfCompo; + oss << ".\nBecause the number of elements in this is " << _nb_of_compo << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } +} diff --cc medtool/src/MEDCoupling/MEDCouplingMemArray.hxx index 1fc39204c,000000000..201b7601e mode 100644,000000..100644 --- a/medtool/src/MEDCoupling/MEDCouplingMemArray.hxx +++ b/medtool/src/MEDCoupling/MEDCouplingMemArray.hxx @@@ -1,946 -1,0 +1,947 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#ifndef __PARAMEDMEM_MEDCOUPLINGMEMARRAY_HXX__ +#define __PARAMEDMEM_MEDCOUPLINGMEMARRAY_HXX__ + +#include "MEDCoupling.hxx" +#include "MEDCouplingTimeLabel.hxx" +#include "MEDCouplingRefCountObject.hxx" +#include "InterpKernelException.hxx" +#include "BBTreePts.txx" + +#include +#include +#include + +namespace ParaMEDMEM +{ + template + class MEDCouplingPointer + { + public: + MEDCouplingPointer():_internal(0),_external(0) { } + void null() { _internal=0; _external=0; } + bool isNull() const { return _internal==0 && _external==0; } + void setInternal(T *pointer); + void setExternal(const T *pointer); + const T *getConstPointer() const { if(_internal) return _internal; else return _external; } + const T *getConstPointerLoc(std::size_t offset) const { if(_internal) return _internal+offset; else return _external+offset; } + T *getPointer() { if(_internal) return _internal; if(_external) throw INTERP_KERNEL::Exception("Trying to write on an external pointer."); else return 0; } + private: + T *_internal; + const T *_external; + }; + + template + class MemArray + { + public: + typedef void (*Deallocator)(void *,void *); + public: + MemArray():_nb_of_elem(0),_nb_of_elem_alloc(0),_ownership(false),_dealloc(0),_param_for_deallocator(0) { } + MemArray(const MemArray& other); + bool isNull() const { return _pointer.isNull(); } + const T *getConstPointerLoc(std::size_t offset) const { return _pointer.getConstPointerLoc(offset); } + const T *getConstPointer() const { return _pointer.getConstPointer(); } + std::size_t getNbOfElem() const { return _nb_of_elem; } + std::size_t getNbOfElemAllocated() const { return _nb_of_elem_alloc; } + T *getPointer() { return _pointer.getPointer(); } + MemArray &operator=(const MemArray& other); + T operator[](std::size_t id) const { return _pointer.getConstPointer()[id]; } + T& operator[](std::size_t id) { return _pointer.getPointer()[id]; } + bool isEqual(const MemArray& other, T prec, std::string& reason) const; + void repr(int sl, std::ostream& stream) const; + bool reprHeader(int sl, std::ostream& stream) const; + void reprZip(int sl, std::ostream& stream) const; + void reprNotTooLong(int sl, std::ostream& stream) const; + void fillWithValue(const T& val); + T *fromNoInterlace(int nbOfComp) const; + T *toNoInterlace(int nbOfComp) const; + void sort(bool asc); + void reverse(int nbOfComp); + void alloc(std::size_t nbOfElements); + void reserve(std::size_t newNbOfElements); + void reAlloc(std::size_t newNbOfElements); + void useArray(const T *array, bool ownership, DeallocType type, std::size_t nbOfElem); + void useExternalArrayWithRWAccess(const T *array, std::size_t nbOfElem); + void writeOnPlace(std::size_t id, T element0, const T *others, std::size_t sizeOfOthers); + template + void insertAtTheEnd(InputIterator first, InputIterator last); + void pushBack(T elem); + T popBack(); + void pack() const; + bool isDeallocatorCalled() const { return _ownership; } + Deallocator getDeallocator() const { return _dealloc; } + void setSpecificDeallocator(Deallocator dealloc) { _dealloc=dealloc; } + void setParameterForDeallocator(void *param) { _param_for_deallocator=param; } + void *getParameterForDeallocator() const { return _param_for_deallocator; } + void destroy(); + ~MemArray() { destroy(); } + public: + static void CPPDeallocator(void *pt, void *param); + static void CDeallocator(void *pt, void *param); + private: + static void DestroyPointer(T *pt, Deallocator dealloc, void *param); + static Deallocator BuildFromType(DeallocType type); + private: + std::size_t _nb_of_elem; + std::size_t _nb_of_elem_alloc; + bool _ownership; + MEDCouplingPointer _pointer; + Deallocator _dealloc; + void *_param_for_deallocator; + }; + + class DataArrayInt; + class DataArrayByte; + + class DataArray : public RefCountObject, public TimeLabel + { + public: + MEDCOUPLING_EXPORT std::size_t getHeapMemorySizeWithoutChildren() const; + MEDCOUPLING_EXPORT std::vector getDirectChildrenWithNull() const; + MEDCOUPLING_EXPORT void setName(const std::string& name); + MEDCOUPLING_EXPORT void copyStringInfoFrom(const DataArray& other); + MEDCOUPLING_EXPORT void copyPartOfStringInfoFrom(const DataArray& other, const std::vector& compoIds); + MEDCOUPLING_EXPORT void copyPartOfStringInfoFrom2(const std::vector& compoIds, const DataArray& other); + MEDCOUPLING_EXPORT bool areInfoEqualsIfNotWhy(const DataArray& other, std::string& reason) const; + MEDCOUPLING_EXPORT bool areInfoEquals(const DataArray& other) const; + MEDCOUPLING_EXPORT std::string cppRepr(const std::string& varName) const; + MEDCOUPLING_EXPORT std::string getName() const { return _name; } + MEDCOUPLING_EXPORT const std::vector &getInfoOnComponents() const { return _info_on_compo; } + MEDCOUPLING_EXPORT std::vector &getInfoOnComponents() { return _info_on_compo; } + MEDCOUPLING_EXPORT void setInfoOnComponents(const std::vector& info); + MEDCOUPLING_EXPORT void setInfoAndChangeNbOfCompo(const std::vector& info); + MEDCOUPLING_EXPORT std::vector getVarsOnComponent() const; + MEDCOUPLING_EXPORT std::vector getUnitsOnComponent() const; + MEDCOUPLING_EXPORT std::string getInfoOnComponent(int i) const; + MEDCOUPLING_EXPORT std::string getVarOnComponent(int i) const; + MEDCOUPLING_EXPORT std::string getUnitOnComponent(int i) const; + MEDCOUPLING_EXPORT void setInfoOnComponent(int i, const std::string& info); + MEDCOUPLING_EXPORT int getNumberOfComponents() const { return (int)_info_on_compo.size(); } + MEDCOUPLING_EXPORT void setPartOfValuesBase3(const DataArray *aBase, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT virtual DataArray *deepCpy() const = 0; + MEDCOUPLING_EXPORT virtual bool isAllocated() const = 0; + MEDCOUPLING_EXPORT virtual void checkAllocated() const = 0; + MEDCOUPLING_EXPORT virtual void desallocate() = 0; + MEDCOUPLING_EXPORT virtual int getNumberOfTuples() const = 0; + MEDCOUPLING_EXPORT virtual std::size_t getNbOfElems() const = 0; + MEDCOUPLING_EXPORT virtual std::size_t getNbOfElemAllocated() const = 0; + MEDCOUPLING_EXPORT virtual void alloc(int nbOfTuple, int nbOfCompo=1) = 0; + MEDCOUPLING_EXPORT virtual void reAlloc(int newNbOfTuple) = 0; + MEDCOUPLING_EXPORT virtual void renumberInPlace(const int *old2New) = 0; + MEDCOUPLING_EXPORT virtual void renumberInPlaceR(const int *new2Old) = 0; + MEDCOUPLING_EXPORT virtual void setContigPartOfSelectedValues(int tupleIdStart, const DataArray *aBase, const DataArrayInt *tuplesSelec) = 0; + MEDCOUPLING_EXPORT virtual void setContigPartOfSelectedValues2(int tupleIdStart, const DataArray *aBase, int bg, int end2, int step) = 0; + MEDCOUPLING_EXPORT virtual DataArray *selectByTupleRanges(const std::vector >& ranges) const = 0; + MEDCOUPLING_EXPORT virtual DataArray *keepSelectedComponents(const std::vector& compoIds) const = 0; + MEDCOUPLING_EXPORT virtual DataArray *selectByTupleId(const int *new2OldBg, const int *new2OldEnd) const = 0; + MEDCOUPLING_EXPORT virtual DataArray *selectByTupleIdSafe(const int *new2OldBg, const int *new2OldEnd) const = 0; + MEDCOUPLING_EXPORT virtual DataArray *selectByTupleId2(int bg, int end2, int step) const = 0; + MEDCOUPLING_EXPORT virtual void rearrange(int newNbOfCompo) = 0; + MEDCOUPLING_EXPORT void checkNbOfTuples(int nbOfTuples, const std::string& msg) const; + MEDCOUPLING_EXPORT void checkNbOfComps(int nbOfCompo, const std::string& msg) const; + MEDCOUPLING_EXPORT void checkNbOfTuplesAndComp(const DataArray& other, const std::string& msg) const; + MEDCOUPLING_EXPORT void checkNbOfTuplesAndComp(int nbOfTuples, int nbOfCompo, const std::string& msg) const; + MEDCOUPLING_EXPORT void checkNbOfElems(std::size_t nbOfElems, const std::string& msg) const; + MEDCOUPLING_EXPORT static void GetSlice(int start, int stop, int step, int sliceId, int nbOfSlices, int& startSlice, int& stopSlice); + MEDCOUPLING_EXPORT static int GetNumberOfItemGivenBES(int begin, int end, int step, const std::string& msg); + MEDCOUPLING_EXPORT static int GetNumberOfItemGivenBESRelative(int begin, int end, int step, const std::string& msg); + MEDCOUPLING_EXPORT static int GetPosOfItemGivenBESRelativeNoThrow(int value, int begin, int end, int step); + MEDCOUPLING_EXPORT static std::string GetVarNameFromInfo(const std::string& info); + MEDCOUPLING_EXPORT static std::string GetUnitFromInfo(const std::string& info); + MEDCOUPLING_EXPORT static std::string BuildInfoFromVarAndUnit(const std::string& var, const std::string& unit); + MEDCOUPLING_EXPORT static DataArray *Aggregate(const std::vector& arrs); + MEDCOUPLING_EXPORT virtual void reprStream(std::ostream& stream) const = 0; + MEDCOUPLING_EXPORT virtual void reprZipStream(std::ostream& stream) const = 0; + MEDCOUPLING_EXPORT virtual void reprWithoutNameStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT virtual void reprZipWithoutNameStream(std::ostream& stream) const = 0; + MEDCOUPLING_EXPORT virtual void reprCppStream(const std::string& varName, std::ostream& stream) const = 0; + MEDCOUPLING_EXPORT virtual void reprQuickOverview(std::ostream& stream) const = 0; + MEDCOUPLING_EXPORT virtual void reprQuickOverviewData(std::ostream& stream, std::size_t maxNbOfByteInRepr) const = 0; + protected: + DataArray() { } + ~DataArray() { } + protected: + static void CheckValueInRange(int ref, int value, const std::string& msg); + static void CheckValueInRangeEx(int value, int start, int end, const std::string& msg); + static void CheckClosingParInRange(int ref, int value, const std::string& msg); + protected: + std::string _name; + std::vector _info_on_compo; + }; +} + +#include "MEDCouplingMemArray.txx" + +namespace ParaMEDMEM +{ + class DataArrayInt; + class DataArrayDoubleIterator; + class DataArrayDouble : public DataArray + { + public: + MEDCOUPLING_EXPORT static DataArrayDouble *New(); + MEDCOUPLING_EXPORT bool isAllocated() const; + MEDCOUPLING_EXPORT void checkAllocated() const; + MEDCOUPLING_EXPORT void desallocate(); + MEDCOUPLING_EXPORT int getNumberOfTuples() const { return _info_on_compo.empty()?0:_mem.getNbOfElem()/getNumberOfComponents(); } + MEDCOUPLING_EXPORT std::size_t getNbOfElems() const { return _mem.getNbOfElem(); } + MEDCOUPLING_EXPORT std::size_t getHeapMemorySizeWithoutChildren() const; + MEDCOUPLING_EXPORT double doubleValue() const; + MEDCOUPLING_EXPORT bool empty() const; + MEDCOUPLING_EXPORT DataArrayDouble *deepCpy() const; + MEDCOUPLING_EXPORT DataArrayDouble *performCpy(bool deepCpy) const; + MEDCOUPLING_EXPORT void cpyFrom(const DataArrayDouble& other); + MEDCOUPLING_EXPORT void reserve(std::size_t nbOfElems); + MEDCOUPLING_EXPORT void pushBackSilent(double val); + MEDCOUPLING_EXPORT void pushBackValsSilent(const double *valsBg, const double *valsEnd); + MEDCOUPLING_EXPORT double popBackSilent(); + MEDCOUPLING_EXPORT void pack() const; + MEDCOUPLING_EXPORT std::size_t getNbOfElemAllocated() const { return _mem.getNbOfElemAllocated(); } + MEDCOUPLING_EXPORT void alloc(int nbOfTuple, int nbOfCompo=1); + MEDCOUPLING_EXPORT void allocIfNecessary(int nbOfTuple, int nbOfCompo); + MEDCOUPLING_EXPORT void fillWithZero(); + MEDCOUPLING_EXPORT void fillWithValue(double val); + MEDCOUPLING_EXPORT void iota(double init=0.); + MEDCOUPLING_EXPORT bool isUniform(double val, double eps) const; + MEDCOUPLING_EXPORT void sort(bool asc=true); + MEDCOUPLING_EXPORT void reverse(); + MEDCOUPLING_EXPORT void checkMonotonic(bool increasing, double eps) const; + MEDCOUPLING_EXPORT bool isMonotonic(bool increasing, double eps) const; + MEDCOUPLING_EXPORT std::string repr() const; + MEDCOUPLING_EXPORT std::string reprZip() const; + MEDCOUPLING_EXPORT std::string reprNotTooLong() const; + MEDCOUPLING_EXPORT void writeVTK(std::ostream& ofs, int indent, const std::string& nameInFile, DataArrayByte *byteArr) const; + MEDCOUPLING_EXPORT void reprStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprZipStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprNotTooLongStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprWithoutNameStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprZipWithoutNameStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprNotTooLongWithoutNameStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprCppStream(const std::string& varName, std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprQuickOverview(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprQuickOverviewData(std::ostream& stream, std::size_t maxNbOfByteInRepr) const; + MEDCOUPLING_EXPORT bool isEqual(const DataArrayDouble& other, double prec) const; + MEDCOUPLING_EXPORT bool isEqualIfNotWhy(const DataArrayDouble& other, double prec, std::string& reason) const; + MEDCOUPLING_EXPORT bool isEqualWithoutConsideringStr(const DataArrayDouble& other, double prec) const; + MEDCOUPLING_EXPORT void reAlloc(int nbOfTuples); + MEDCOUPLING_EXPORT DataArrayInt *convertToIntArr() const; + MEDCOUPLING_EXPORT DataArrayDouble *fromNoInterlace() const; + MEDCOUPLING_EXPORT DataArrayDouble *toNoInterlace() const; + MEDCOUPLING_EXPORT void renumberInPlace(const int *old2New); + MEDCOUPLING_EXPORT void renumberInPlaceR(const int *new2Old); + MEDCOUPLING_EXPORT DataArrayDouble *renumber(const int *old2New) const; + MEDCOUPLING_EXPORT DataArrayDouble *renumberR(const int *new2Old) const; + MEDCOUPLING_EXPORT DataArrayDouble *renumberAndReduce(const int *old2New, int newNbOfTuple) const; + MEDCOUPLING_EXPORT DataArrayDouble *selectByTupleId(const int *new2OldBg, const int *new2OldEnd) const; ++ MEDCOUPLING_EXPORT DataArrayDouble *selectByTupleId(const DataArrayInt & di) const; + MEDCOUPLING_EXPORT DataArrayDouble *selectByTupleIdSafe(const int *new2OldBg, const int *new2OldEnd) const; + MEDCOUPLING_EXPORT DataArrayDouble *selectByTupleId2(int bg, int end2, int step) const; + MEDCOUPLING_EXPORT DataArray *selectByTupleRanges(const std::vector >& ranges) const; + MEDCOUPLING_EXPORT DataArrayDouble *substr(int tupleIdBg, int tupleIdEnd=-1) const; + MEDCOUPLING_EXPORT void rearrange(int newNbOfCompo); + MEDCOUPLING_EXPORT void transpose(); + MEDCOUPLING_EXPORT DataArrayDouble *changeNbOfComponents(int newNbOfComp, double dftValue) const; + MEDCOUPLING_EXPORT DataArrayDouble *keepSelectedComponents(const std::vector& compoIds) const; + MEDCOUPLING_EXPORT void meldWith(const DataArrayDouble *other); + MEDCOUPLING_EXPORT bool areIncludedInMe(const DataArrayDouble *other, double prec, DataArrayInt *&tupleIds) const; + MEDCOUPLING_EXPORT void findCommonTuples(double prec, int limitTupleId, DataArrayInt *&comm, DataArrayInt *&commIndex) const; + MEDCOUPLING_EXPORT double minimalDistanceTo(const DataArrayDouble *other, int& thisTupleId, int& otherTupleId) const; + MEDCOUPLING_EXPORT DataArrayDouble *duplicateEachTupleNTimes(int nbTimes) const; + MEDCOUPLING_EXPORT DataArrayDouble *getDifferentValues(double prec, int limitTupleId=-1) const; + MEDCOUPLING_EXPORT DataArrayInt *findClosestTupleId(const DataArrayDouble *other) const; + MEDCOUPLING_EXPORT DataArrayInt *computeNbOfInteractionsWith(const DataArrayDouble *otherBBoxFrmt, double eps) const; + MEDCOUPLING_EXPORT void setSelectedComponents(const DataArrayDouble *a, const std::vector& compoIds); + MEDCOUPLING_EXPORT void setPartOfValues1(const DataArrayDouble *a, int bgTuples, int endTuples, int stepTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple1(double a, int bgTuples, int endTuples, int stepTuples, int bgComp, int endComp, int stepComp); + MEDCOUPLING_EXPORT void setPartOfValues2(const DataArrayDouble *a, const int *bgTuples, const int *endTuples, const int *bgComp, const int *endComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple2(double a, const int *bgTuples, const int *endTuples, const int *bgComp, const int *endComp); + MEDCOUPLING_EXPORT void setPartOfValues3(const DataArrayDouble *a, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple3(double a, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp); + MEDCOUPLING_EXPORT void setPartOfValues4(const DataArrayDouble *a, int bgTuples, int endTuples, int stepTuples, const int *bgComp, const int *endComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple4(double a, int bgTuples, int endTuples, int stepTuples, const int *bgComp, const int *endComp); + MEDCOUPLING_EXPORT void setPartOfValuesAdv(const DataArrayDouble *a, const DataArrayInt *tuplesSelec); + MEDCOUPLING_EXPORT void setContigPartOfSelectedValues(int tupleIdStart, const DataArray *aBase, const DataArrayInt *tuplesSelec); + MEDCOUPLING_EXPORT void setContigPartOfSelectedValues2(int tupleIdStart, const DataArray *aBase, int bg, int end2, int step); + MEDCOUPLING_EXPORT void getTuple(int tupleId, double *res) const { std::copy(_mem.getConstPointerLoc(tupleId*_info_on_compo.size()),_mem.getConstPointerLoc((tupleId+1)*_info_on_compo.size()),res); } + MEDCOUPLING_EXPORT double getIJ(int tupleId, int compoId) const { return _mem[tupleId*_info_on_compo.size()+compoId]; } + MEDCOUPLING_EXPORT double front() const; + MEDCOUPLING_EXPORT double back() const; + MEDCOUPLING_EXPORT double getIJSafe(int tupleId, int compoId) const; + MEDCOUPLING_EXPORT void setIJ(int tupleId, int compoId, double newVal) { _mem[tupleId*_info_on_compo.size()+compoId]=newVal; declareAsNew(); } + MEDCOUPLING_EXPORT void setIJSilent(int tupleId, int compoId, double newVal) { _mem[tupleId*_info_on_compo.size()+compoId]=newVal; } + MEDCOUPLING_EXPORT double *getPointer() { return _mem.getPointer(); declareAsNew(); } + MEDCOUPLING_EXPORT static void SetArrayIn(DataArrayDouble *newArray, DataArrayDouble* &arrayToSet); + MEDCOUPLING_EXPORT const double *getConstPointer() const { return _mem.getConstPointer(); } + MEDCOUPLING_EXPORT DataArrayDoubleIterator *iterator(); + MEDCOUPLING_EXPORT const double *begin() const { return getConstPointer(); } + MEDCOUPLING_EXPORT const double *end() const { return getConstPointer()+getNbOfElems(); } + MEDCOUPLING_EXPORT void useArray(const double *array, bool ownership, DeallocType type, int nbOfTuple, int nbOfCompo); + MEDCOUPLING_EXPORT void useExternalArrayWithRWAccess(const double *array, int nbOfTuple, int nbOfCompo); + template + void insertAtTheEnd(InputIterator first, InputIterator last); + MEDCOUPLING_EXPORT void writeOnPlace(std::size_t id, double element0, const double *others, int sizeOfOthers) { _mem.writeOnPlace(id,element0,others,sizeOfOthers); } + MEDCOUPLING_EXPORT void checkNoNullValues() const; + MEDCOUPLING_EXPORT void getMinMaxPerComponent(double *bounds) const; + MEDCOUPLING_EXPORT DataArrayDouble *computeBBoxPerTuple(double epsilon=0.0) const; + MEDCOUPLING_EXPORT void computeTupleIdsNearTuples(const DataArrayDouble *other, double eps, DataArrayInt *& c, DataArrayInt *& cI) const; + MEDCOUPLING_EXPORT void recenterForMaxPrecision(double eps); + MEDCOUPLING_EXPORT double getMaxValue(int& tupleId) const; + MEDCOUPLING_EXPORT double getMaxValueInArray() const; + MEDCOUPLING_EXPORT double getMinValue(int& tupleId) const; + MEDCOUPLING_EXPORT double getMinValueInArray() const; + MEDCOUPLING_EXPORT double getMaxValue2(DataArrayInt*& tupleIds) const; + MEDCOUPLING_EXPORT double getMinValue2(DataArrayInt*& tupleIds) const; + MEDCOUPLING_EXPORT int count(double value, double eps) const; + MEDCOUPLING_EXPORT double getAverageValue() const; + MEDCOUPLING_EXPORT double norm2() const; + MEDCOUPLING_EXPORT double normMax() const; + MEDCOUPLING_EXPORT double normMin() const; + MEDCOUPLING_EXPORT void accumulate(double *res) const; + MEDCOUPLING_EXPORT double accumulate(int compId) const; + MEDCOUPLING_EXPORT DataArrayDouble *accumulatePerChunck(const int *bgOfIndex, const int *endOfIndex) const; + MEDCOUPLING_EXPORT double distanceToTuple(const double *tupleBg, const double *tupleEnd, int& tupleId) const; + MEDCOUPLING_EXPORT DataArrayDouble *fromPolarToCart() const; + MEDCOUPLING_EXPORT DataArrayDouble *fromCylToCart() const; + MEDCOUPLING_EXPORT DataArrayDouble *fromSpherToCart() const; + MEDCOUPLING_EXPORT DataArrayDouble *doublyContractedProduct() const; + MEDCOUPLING_EXPORT DataArrayDouble *determinant() const; + MEDCOUPLING_EXPORT DataArrayDouble *eigenValues() const; + MEDCOUPLING_EXPORT DataArrayDouble *eigenVectors() const; + MEDCOUPLING_EXPORT DataArrayDouble *inverse() const; + MEDCOUPLING_EXPORT DataArrayDouble *trace() const; + MEDCOUPLING_EXPORT DataArrayDouble *deviator() const; + MEDCOUPLING_EXPORT DataArrayDouble *magnitude() const; + MEDCOUPLING_EXPORT DataArrayDouble *sumPerTuple() const; + MEDCOUPLING_EXPORT DataArrayDouble *maxPerTuple() const; + MEDCOUPLING_EXPORT DataArrayDouble *maxPerTupleWithCompoId(DataArrayInt* &compoIdOfMaxPerTuple) const; + MEDCOUPLING_EXPORT DataArrayDouble *buildEuclidianDistanceDenseMatrix() const; + MEDCOUPLING_EXPORT DataArrayDouble *buildEuclidianDistanceDenseMatrixWith(const DataArrayDouble *other) const; + MEDCOUPLING_EXPORT void sortPerTuple(bool asc); + MEDCOUPLING_EXPORT void abs(); + MEDCOUPLING_EXPORT DataArrayDouble *computeAbs() const; + MEDCOUPLING_EXPORT void applyLin(double a, double b, int compoId); + MEDCOUPLING_EXPORT void applyLin(double a, double b); + MEDCOUPLING_EXPORT void applyInv(double numerator); + MEDCOUPLING_EXPORT void applyPow(double val); + MEDCOUPLING_EXPORT void applyRPow(double val); + MEDCOUPLING_EXPORT DataArrayDouble *negate() const; + MEDCOUPLING_EXPORT DataArrayDouble *applyFunc(int nbOfComp, FunctionToEvaluate func) const; + MEDCOUPLING_EXPORT DataArrayDouble *applyFunc(int nbOfComp, const std::string& func, bool isSafe=true) const; + MEDCOUPLING_EXPORT DataArrayDouble *applyFunc(const std::string& func, bool isSafe=true) const; + MEDCOUPLING_EXPORT void applyFuncOnThis(const std::string& func, bool isSafe=true); + MEDCOUPLING_EXPORT DataArrayDouble *applyFunc2(int nbOfComp, const std::string& func, bool isSafe=true) const; + MEDCOUPLING_EXPORT DataArrayDouble *applyFunc3(int nbOfComp, const std::vector& varsOrder, const std::string& func, bool isSafe=true) const; + MEDCOUPLING_EXPORT void applyFuncFast32(const std::string& func); + MEDCOUPLING_EXPORT void applyFuncFast64(const std::string& func); + MEDCOUPLING_EXPORT DataArrayInt *getIdsInRange(double vmin, double vmax) const; + MEDCOUPLING_EXPORT DataArrayInt *getIdsNotInRange(double vmin, double vmax) const; + MEDCOUPLING_EXPORT static DataArrayDouble *Aggregate(const DataArrayDouble *a1, const DataArrayDouble *a2); + MEDCOUPLING_EXPORT static DataArrayDouble *Aggregate(const std::vector& arr); + MEDCOUPLING_EXPORT static DataArrayDouble *Meld(const DataArrayDouble *a1, const DataArrayDouble *a2); + MEDCOUPLING_EXPORT static DataArrayDouble *Meld(const std::vector& arr); + MEDCOUPLING_EXPORT static DataArrayDouble *Dot(const DataArrayDouble *a1, const DataArrayDouble *a2); + MEDCOUPLING_EXPORT static DataArrayDouble *CrossProduct(const DataArrayDouble *a1, const DataArrayDouble *a2); + MEDCOUPLING_EXPORT static DataArrayDouble *Max(const DataArrayDouble *a1, const DataArrayDouble *a2); + MEDCOUPLING_EXPORT static DataArrayDouble *Min(const DataArrayDouble *a1, const DataArrayDouble *a2); + MEDCOUPLING_EXPORT static DataArrayDouble *Add(const DataArrayDouble *a1, const DataArrayDouble *a2); + MEDCOUPLING_EXPORT void addEqual(const DataArrayDouble *other); + MEDCOUPLING_EXPORT static DataArrayDouble *Substract(const DataArrayDouble *a1, const DataArrayDouble *a2); + MEDCOUPLING_EXPORT void substractEqual(const DataArrayDouble *other); + MEDCOUPLING_EXPORT static DataArrayDouble *Multiply(const DataArrayDouble *a1, const DataArrayDouble *a2); + MEDCOUPLING_EXPORT void multiplyEqual(const DataArrayDouble *other); + MEDCOUPLING_EXPORT static DataArrayDouble *Divide(const DataArrayDouble *a1, const DataArrayDouble *a2); + MEDCOUPLING_EXPORT void divideEqual(const DataArrayDouble *other); + MEDCOUPLING_EXPORT static DataArrayDouble *Pow(const DataArrayDouble *a1, const DataArrayDouble *a2); + MEDCOUPLING_EXPORT void powEqual(const DataArrayDouble *other); + MEDCOUPLING_EXPORT void updateTime() const { } + MEDCOUPLING_EXPORT MemArray& accessToMemArray() { return _mem; } + MEDCOUPLING_EXPORT const MemArray& accessToMemArray() const { return _mem; } + MEDCOUPLING_EXPORT std::vector toVectorOfBool(double eps) const; + public: + MEDCOUPLING_EXPORT void getTinySerializationIntInformation(std::vector& tinyInfo) const; + MEDCOUPLING_EXPORT void getTinySerializationStrInformation(std::vector& tinyInfo) const; + MEDCOUPLING_EXPORT bool resizeForUnserialization(const std::vector& tinyInfoI); + MEDCOUPLING_EXPORT void finishUnserialization(const std::vector& tinyInfoI, const std::vector& tinyInfoS); + public: + template + void findCommonTuplesAlg(const double *bbox, int nbNodes, int limitNodeId, double prec, DataArrayInt *c, DataArrayInt *cI) const; + template + static void FindClosestTupleIdAlg(const BBTreePts& myTree, double dist, const double *pos, int nbOfTuples, const double *thisPt, int thisNbOfTuples, int *res); + template + static void FindTupleIdsNearTuplesAlg(const BBTreePts& myTree, const double *pos, int nbOfTuples, double eps, + DataArrayInt *c, DataArrayInt *cI); + private: + ~DataArrayDouble() { } + DataArrayDouble() { } + private: + MemArray _mem; + }; + + class DataArrayDoubleTuple; + + class DataArrayDoubleIterator + { + public: + MEDCOUPLING_EXPORT DataArrayDoubleIterator(DataArrayDouble *da); + MEDCOUPLING_EXPORT ~DataArrayDoubleIterator(); + MEDCOUPLING_EXPORT DataArrayDoubleTuple *nextt(); + private: + DataArrayDouble *_da; + double *_pt; + int _tuple_id; + int _nb_comp; + int _nb_tuple; + }; + + class DataArrayDoubleTuple + { + public: + MEDCOUPLING_EXPORT DataArrayDoubleTuple(double *pt, int nbOfComp); + MEDCOUPLING_EXPORT std::string repr() const; + MEDCOUPLING_EXPORT int getNumberOfCompo() const { return _nb_of_compo; } + MEDCOUPLING_EXPORT const double *getConstPointer() const { return _pt; } + MEDCOUPLING_EXPORT double *getPointer() { return _pt; } + MEDCOUPLING_EXPORT double doubleValue() const; + MEDCOUPLING_EXPORT DataArrayDouble *buildDADouble(int nbOfTuples, int nbOfCompo) const; + private: + double *_pt; + int _nb_of_compo; + }; + + class DataArrayIntIterator; + + class DataArrayInt : public DataArray + { + public: + MEDCOUPLING_EXPORT static DataArrayInt *New(); + MEDCOUPLING_EXPORT bool isAllocated() const; + MEDCOUPLING_EXPORT void checkAllocated() const; + MEDCOUPLING_EXPORT void desallocate(); + MEDCOUPLING_EXPORT int getNumberOfTuples() const { return _info_on_compo.empty()?0:_mem.getNbOfElem()/getNumberOfComponents(); } + MEDCOUPLING_EXPORT std::size_t getNbOfElems() const { return _mem.getNbOfElem(); } + MEDCOUPLING_EXPORT std::size_t getHeapMemorySizeWithoutChildren() const; + MEDCOUPLING_EXPORT int intValue() const; + MEDCOUPLING_EXPORT int getHashCode() const; + MEDCOUPLING_EXPORT bool empty() const; + MEDCOUPLING_EXPORT DataArrayInt *deepCpy() const; + MEDCOUPLING_EXPORT DataArrayInt *performCpy(bool deepCpy) const; + MEDCOUPLING_EXPORT void cpyFrom(const DataArrayInt& other); + MEDCOUPLING_EXPORT void reserve(std::size_t nbOfElems); + MEDCOUPLING_EXPORT void pushBackSilent(int val); + MEDCOUPLING_EXPORT void pushBackValsSilent(const int *valsBg, const int *valsEnd); + MEDCOUPLING_EXPORT int popBackSilent(); + MEDCOUPLING_EXPORT void pack() const; + MEDCOUPLING_EXPORT std::size_t getNbOfElemAllocated() const { return _mem.getNbOfElemAllocated(); } + MEDCOUPLING_EXPORT void alloc(int nbOfTuple, int nbOfCompo=1); + MEDCOUPLING_EXPORT void allocIfNecessary(int nbOfTuple, int nbOfCompo); + MEDCOUPLING_EXPORT bool isEqual(const DataArrayInt& other) const; + MEDCOUPLING_EXPORT bool isEqualIfNotWhy(const DataArrayInt& other, std::string& reason) const; + MEDCOUPLING_EXPORT bool isEqualWithoutConsideringStr(const DataArrayInt& other) const; + MEDCOUPLING_EXPORT bool isEqualWithoutConsideringStrAndOrder(const DataArrayInt& other) const; + MEDCOUPLING_EXPORT bool isFittingWith(const std::vector& v) const; + MEDCOUPLING_EXPORT void switchOnTupleEqualTo(int val, std::vector& vec) const; + MEDCOUPLING_EXPORT DataArrayInt *buildPermutationArr(const DataArrayInt& other) const; + MEDCOUPLING_EXPORT DataArrayInt *sumPerTuple() const; + MEDCOUPLING_EXPORT void sort(bool asc=true); + MEDCOUPLING_EXPORT void reverse(); + MEDCOUPLING_EXPORT void checkMonotonic(bool increasing) const; + MEDCOUPLING_EXPORT bool isMonotonic(bool increasing) const; + MEDCOUPLING_EXPORT void checkStrictlyMonotonic(bool increasing) const; + MEDCOUPLING_EXPORT bool isStrictlyMonotonic(bool increasing) const; + MEDCOUPLING_EXPORT void fillWithZero(); + MEDCOUPLING_EXPORT void fillWithValue(int val); + MEDCOUPLING_EXPORT void iota(int init=0); + MEDCOUPLING_EXPORT std::string repr() const; + MEDCOUPLING_EXPORT std::string reprZip() const; + MEDCOUPLING_EXPORT std::string reprNotTooLong() const; + MEDCOUPLING_EXPORT void writeVTK(std::ostream& ofs, int indent, const std::string& type, const std::string& nameInFile, DataArrayByte *byteArr) const; + MEDCOUPLING_EXPORT void reprStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprZipStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprNotTooLongStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprWithoutNameStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprZipWithoutNameStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprNotTooLongWithoutNameStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprCppStream(const std::string& varName, std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprQuickOverview(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprQuickOverviewData(std::ostream& stream, std::size_t maxNbOfByteInRepr) const; + MEDCOUPLING_EXPORT void transformWithIndArr(const int *indArrBg, const int *indArrEnd); + MEDCOUPLING_EXPORT void replaceOneValByInThis(int valToBeReplaced, int replacedBy); + MEDCOUPLING_EXPORT DataArrayInt *transformWithIndArrR(const int *indArrBg, const int *indArrEnd) const; + MEDCOUPLING_EXPORT void splitByValueRange(const int *arrBg, const int *arrEnd, + DataArrayInt *& castArr, DataArrayInt *& rankInsideCast, DataArrayInt *& castsPresent) const; + MEDCOUPLING_EXPORT bool isRange(int& strt, int& sttoopp, int& stteepp) const; + MEDCOUPLING_EXPORT DataArrayInt *invertArrayO2N2N2O(int newNbOfElem) const; + MEDCOUPLING_EXPORT DataArrayInt *invertArrayN2O2O2N(int oldNbOfElem) const; + MEDCOUPLING_EXPORT DataArrayInt *invertArrayO2N2N2OBis(int newNbOfElem) const; + MEDCOUPLING_EXPORT void reAlloc(int nbOfTuples); + MEDCOUPLING_EXPORT DataArrayDouble *convertToDblArr() const; + MEDCOUPLING_EXPORT DataArrayInt *fromNoInterlace() const; + MEDCOUPLING_EXPORT DataArrayInt *toNoInterlace() const; + MEDCOUPLING_EXPORT void renumberInPlace(const int *old2New); + MEDCOUPLING_EXPORT void renumberInPlaceR(const int *new2Old); + MEDCOUPLING_EXPORT DataArrayInt *renumber(const int *old2New) const; + MEDCOUPLING_EXPORT DataArrayInt *renumberR(const int *new2Old) const; + MEDCOUPLING_EXPORT DataArrayInt *renumberAndReduce(const int *old2NewBg, int newNbOfTuple) const; + MEDCOUPLING_EXPORT DataArrayInt *selectByTupleId(const int *new2OldBg, const int *new2OldEnd) const; + MEDCOUPLING_EXPORT DataArrayInt *selectByTupleIdSafe(const int *new2OldBg, const int *new2OldEnd) const; + MEDCOUPLING_EXPORT DataArrayInt *selectByTupleId2(int bg, int end, int step) const; + MEDCOUPLING_EXPORT DataArray *selectByTupleRanges(const std::vector >& ranges) const; + MEDCOUPLING_EXPORT DataArrayInt *checkAndPreparePermutation() const; + MEDCOUPLING_EXPORT static DataArrayInt *FindPermutationFromFirstToSecond(const DataArrayInt *ids1, const DataArrayInt *ids2); + MEDCOUPLING_EXPORT void changeSurjectiveFormat(int targetNb, DataArrayInt *&arr, DataArrayInt *&arrI) const; + MEDCOUPLING_EXPORT static DataArrayInt *BuildOld2NewArrayFromSurjectiveFormat2(int nbOfOldTuples, const int *arr, const int *arrIBg, const int *arrIEnd, int &newNbOfTuples); + MEDCOUPLING_EXPORT DataArrayInt *buildPermArrPerLevel() const; + MEDCOUPLING_EXPORT bool isIdentity() const; + MEDCOUPLING_EXPORT bool isIdentity2(int sizeExpected) const; + MEDCOUPLING_EXPORT bool isUniform(int val) const; + MEDCOUPLING_EXPORT DataArrayInt *substr(int tupleIdBg, int tupleIdEnd=-1) const; + MEDCOUPLING_EXPORT void rearrange(int newNbOfCompo); + MEDCOUPLING_EXPORT void transpose(); + MEDCOUPLING_EXPORT DataArrayInt *changeNbOfComponents(int newNbOfComp, int dftValue) const; + MEDCOUPLING_EXPORT DataArrayInt *keepSelectedComponents(const std::vector& compoIds) const; + MEDCOUPLING_EXPORT void meldWith(const DataArrayInt *other); + MEDCOUPLING_EXPORT void setSelectedComponents(const DataArrayInt *a, const std::vector& compoIds); + MEDCOUPLING_EXPORT void setPartOfValues1(const DataArrayInt *a, int bgTuples, int endTuples, int stepTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple1(int a, int bgTuples, int endTuples, int stepTuples, int bgComp, int endComp, int stepComp); + MEDCOUPLING_EXPORT void setPartOfValues2(const DataArrayInt *a, const int *bgTuples, const int *endTuples, const int *bgComp, const int *endComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple2(int a, const int *bgTuples, const int *endTuples, const int *bgComp, const int *endComp); + MEDCOUPLING_EXPORT void setPartOfValues3(const DataArrayInt *a, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple3(int a, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp); + MEDCOUPLING_EXPORT void setPartOfValues4(const DataArrayInt *a, int bgTuples, int endTuples, int stepTuples, const int *bgComp, const int *endComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple4(int a, int bgTuples, int endTuples, int stepTuples, const int *bgComp, const int *endComp); + MEDCOUPLING_EXPORT void setPartOfValuesAdv(const DataArrayInt *a, const DataArrayInt *tuplesSelec); + MEDCOUPLING_EXPORT void setContigPartOfSelectedValues(int tupleIdStart, const DataArray *aBase, const DataArrayInt *tuplesSelec); + MEDCOUPLING_EXPORT void setContigPartOfSelectedValues2(int tupleIdStart, const DataArray *aBase, int bg, int end2, int step); + MEDCOUPLING_EXPORT void getTuple(int tupleId, int *res) const { std::copy(_mem.getConstPointerLoc(tupleId*_info_on_compo.size()),_mem.getConstPointerLoc((tupleId+1)*_info_on_compo.size()),res); } + MEDCOUPLING_EXPORT int getIJ(int tupleId, int compoId) const { return _mem[tupleId*_info_on_compo.size()+compoId]; } + MEDCOUPLING_EXPORT int getIJSafe(int tupleId, int compoId) const; + MEDCOUPLING_EXPORT int front() const; + MEDCOUPLING_EXPORT int back() const; + MEDCOUPLING_EXPORT void setIJ(int tupleId, int compoId, int newVal) { _mem[tupleId*_info_on_compo.size()+compoId]=newVal; declareAsNew(); } + MEDCOUPLING_EXPORT void setIJSilent(int tupleId, int compoId, int newVal) { _mem[tupleId*_info_on_compo.size()+compoId]=newVal; } + MEDCOUPLING_EXPORT int *getPointer() { return _mem.getPointer(); declareAsNew(); } + MEDCOUPLING_EXPORT static void SetArrayIn(DataArrayInt *newArray, DataArrayInt* &arrayToSet); + MEDCOUPLING_EXPORT const int *getConstPointer() const { return _mem.getConstPointer(); } + MEDCOUPLING_EXPORT DataArrayIntIterator *iterator(); + MEDCOUPLING_EXPORT const int *begin() const { return getConstPointer(); } + MEDCOUPLING_EXPORT const int *end() const { return getConstPointer()+getNbOfElems(); } + MEDCOUPLING_EXPORT DataArrayInt *getIdsEqual(int val) const; + MEDCOUPLING_EXPORT DataArrayInt *getIdsNotEqual(int val) const; + MEDCOUPLING_EXPORT DataArrayInt *getIdsEqualList(const int *valsBg, const int *valsEnd) const; + MEDCOUPLING_EXPORT DataArrayInt *getIdsNotEqualList(const int *valsBg, const int *valsEnd) const; + MEDCOUPLING_EXPORT DataArrayInt *getIdsEqualTuple(const int *tupleBg, const int *tupleEnd) const; + MEDCOUPLING_EXPORT int changeValue(int oldValue, int newValue); + MEDCOUPLING_EXPORT int locateTuple(const std::vector& tupl) const; + MEDCOUPLING_EXPORT int locateValue(int value) const; + MEDCOUPLING_EXPORT int locateValue(const std::vector& vals) const; + MEDCOUPLING_EXPORT int search(const std::vector& vals) const; + MEDCOUPLING_EXPORT bool presenceOfTuple(const std::vector& tupl) const; + MEDCOUPLING_EXPORT bool presenceOfValue(int value) const; + MEDCOUPLING_EXPORT bool presenceOfValue(const std::vector& vals) const; + MEDCOUPLING_EXPORT int count(int value) const; + MEDCOUPLING_EXPORT void accumulate(int *res) const; + MEDCOUPLING_EXPORT int accumulate(int compId) const; + MEDCOUPLING_EXPORT DataArrayInt *accumulatePerChunck(const int *bgOfIndex, const int *endOfIndex) const; + MEDCOUPLING_EXPORT int getMaxValue(int& tupleId) const; + MEDCOUPLING_EXPORT int getMaxValueInArray() const; + MEDCOUPLING_EXPORT int getMinValue(int& tupleId) const; + MEDCOUPLING_EXPORT int getMinValueInArray() const; + MEDCOUPLING_EXPORT void getMinMaxValues(int& minValue, int& maxValue) const; + MEDCOUPLING_EXPORT void abs(); + MEDCOUPLING_EXPORT DataArrayInt *computeAbs() const; + MEDCOUPLING_EXPORT void applyLin(int a, int b, int compoId); + MEDCOUPLING_EXPORT void applyLin(int a, int b); + MEDCOUPLING_EXPORT void applyInv(int numerator); + MEDCOUPLING_EXPORT DataArrayInt *negate() const; + MEDCOUPLING_EXPORT void applyDivideBy(int val); + MEDCOUPLING_EXPORT void applyModulus(int val); + MEDCOUPLING_EXPORT void applyRModulus(int val); + MEDCOUPLING_EXPORT void applyPow(int val); + MEDCOUPLING_EXPORT void applyRPow(int val); + MEDCOUPLING_EXPORT DataArrayInt *getIdsInRange(int vmin, int vmax) const; + MEDCOUPLING_EXPORT DataArrayInt *getIdsNotInRange(int vmin, int vmax) const; + MEDCOUPLING_EXPORT DataArrayInt *getIdsStrictlyNegative() const; + MEDCOUPLING_EXPORT bool checkAllIdsInRange(int vmin, int vmax) const; + MEDCOUPLING_EXPORT static DataArrayInt *Aggregate(const DataArrayInt *a1, const DataArrayInt *a2, int offsetA2); + MEDCOUPLING_EXPORT static DataArrayInt *Aggregate(const std::vector& arr); + MEDCOUPLING_EXPORT static DataArrayInt *AggregateIndexes(const std::vector& arrs); + MEDCOUPLING_EXPORT static DataArrayInt *Meld(const DataArrayInt *a1, const DataArrayInt *a2); + MEDCOUPLING_EXPORT static DataArrayInt *Meld(const std::vector& arr); + MEDCOUPLING_EXPORT static DataArrayInt *MakePartition(const std::vector& groups, int newNb, std::vector< std::vector >& fidsOfGroups); + MEDCOUPLING_EXPORT static DataArrayInt *BuildUnion(const std::vector& arr); + MEDCOUPLING_EXPORT static DataArrayInt *BuildIntersection(const std::vector& arr); + MEDCOUPLING_EXPORT static DataArrayInt *BuildListOfSwitchedOn(const std::vector& v); + MEDCOUPLING_EXPORT static DataArrayInt *BuildListOfSwitchedOff(const std::vector& v); + MEDCOUPLING_EXPORT static void PutIntoToSkylineFrmt(const std::vector< std::vector >& v, DataArrayInt *& data, DataArrayInt *& dataIndex); + MEDCOUPLING_EXPORT DataArrayInt *buildComplement(int nbOfElement) const; + MEDCOUPLING_EXPORT DataArrayInt *buildSubstraction(const DataArrayInt *other) const; + MEDCOUPLING_EXPORT DataArrayInt *buildSubstractionOptimized(const DataArrayInt *other) const; + MEDCOUPLING_EXPORT DataArrayInt *buildUnion(const DataArrayInt *other) const; + MEDCOUPLING_EXPORT DataArrayInt *buildIntersection(const DataArrayInt *other) const; + MEDCOUPLING_EXPORT DataArrayInt *buildUnique() const; + MEDCOUPLING_EXPORT DataArrayInt *buildUniqueNotSorted() const; + MEDCOUPLING_EXPORT DataArrayInt *deltaShiftIndex() const; + MEDCOUPLING_EXPORT void computeOffsets(); + MEDCOUPLING_EXPORT void computeOffsets2(); + MEDCOUPLING_EXPORT void searchRangesInListOfIds(const DataArrayInt *listOfIds, DataArrayInt *& rangeIdsFetched, DataArrayInt *& idsInInputListThatFetch) const; + MEDCOUPLING_EXPORT DataArrayInt *buildExplicitArrByRanges(const DataArrayInt *offsets) const; + MEDCOUPLING_EXPORT DataArrayInt *buildExplicitArrOfSliceOnScaledArr(int begin, int stop, int step) const; + MEDCOUPLING_EXPORT DataArrayInt *findRangeIdForEachTuple(const DataArrayInt *ranges) const; + MEDCOUPLING_EXPORT DataArrayInt *findIdInRangeForEachTuple(const DataArrayInt *ranges) const; + MEDCOUPLING_EXPORT void sortEachPairToMakeALinkedList(); + MEDCOUPLING_EXPORT DataArrayInt *duplicateEachTupleNTimes(int nbTimes) const; + MEDCOUPLING_EXPORT DataArrayInt *getDifferentValues() const; + MEDCOUPLING_EXPORT std::vector partitionByDifferentValues(std::vector& differentIds) const; + MEDCOUPLING_EXPORT std::vector< std::pair > splitInBalancedSlices(int nbOfSlices) const; + MEDCOUPLING_EXPORT void useArray(const int *array, bool ownership, DeallocType type, int nbOfTuple, int nbOfCompo); + MEDCOUPLING_EXPORT void useExternalArrayWithRWAccess(const int *array, int nbOfTuple, int nbOfCompo); + template + void insertAtTheEnd(InputIterator first, InputIterator last); + MEDCOUPLING_EXPORT void writeOnPlace(std::size_t id, int element0, const int *others, int sizeOfOthers) { _mem.writeOnPlace(id,element0,others,sizeOfOthers); } + MEDCOUPLING_EXPORT static DataArrayInt *Add(const DataArrayInt *a1, const DataArrayInt *a2); + MEDCOUPLING_EXPORT void addEqual(const DataArrayInt *other); + MEDCOUPLING_EXPORT static DataArrayInt *Substract(const DataArrayInt *a1, const DataArrayInt *a2); + MEDCOUPLING_EXPORT void substractEqual(const DataArrayInt *other); + MEDCOUPLING_EXPORT static DataArrayInt *Multiply(const DataArrayInt *a1, const DataArrayInt *a2); + MEDCOUPLING_EXPORT void multiplyEqual(const DataArrayInt *other); + MEDCOUPLING_EXPORT static DataArrayInt *Divide(const DataArrayInt *a1, const DataArrayInt *a2); + MEDCOUPLING_EXPORT void divideEqual(const DataArrayInt *other); + MEDCOUPLING_EXPORT static DataArrayInt *Modulus(const DataArrayInt *a1, const DataArrayInt *a2); + MEDCOUPLING_EXPORT void modulusEqual(const DataArrayInt *other); + MEDCOUPLING_EXPORT static DataArrayInt *Pow(const DataArrayInt *a1, const DataArrayInt *a2); + MEDCOUPLING_EXPORT void powEqual(const DataArrayInt *other); + MEDCOUPLING_EXPORT void updateTime() const { } + MEDCOUPLING_EXPORT MemArray& accessToMemArray() { return _mem; } + MEDCOUPLING_EXPORT const MemArray& accessToMemArray() const { return _mem; } + public: + MEDCOUPLING_EXPORT static int *CheckAndPreparePermutation(const int *start, const int *end); + MEDCOUPLING_EXPORT static DataArrayInt *Range(int begin, int end, int step); + public: + MEDCOUPLING_EXPORT void getTinySerializationIntInformation(std::vector& tinyInfo) const; + MEDCOUPLING_EXPORT void getTinySerializationStrInformation(std::vector& tinyInfo) const; + MEDCOUPLING_EXPORT bool resizeForUnserialization(const std::vector& tinyInfoI); + MEDCOUPLING_EXPORT void finishUnserialization(const std::vector& tinyInfoI, const std::vector& tinyInfoS); + private: + ~DataArrayInt() { } + DataArrayInt() { } + private: + MemArray _mem; + }; + + class DataArrayIntTuple; + + class DataArrayIntIterator + { + public: + MEDCOUPLING_EXPORT DataArrayIntIterator(DataArrayInt *da); + MEDCOUPLING_EXPORT ~DataArrayIntIterator(); + MEDCOUPLING_EXPORT DataArrayIntTuple *nextt(); + private: + DataArrayInt *_da; + int *_pt; + int _tuple_id; + int _nb_comp; + int _nb_tuple; + }; + + class DataArrayIntTuple + { + public: + MEDCOUPLING_EXPORT DataArrayIntTuple(int *pt, int nbOfComp); + MEDCOUPLING_EXPORT std::string repr() const; + MEDCOUPLING_EXPORT int getNumberOfCompo() const { return _nb_of_compo; } + MEDCOUPLING_EXPORT const int *getConstPointer() const { return _pt; } + MEDCOUPLING_EXPORT int *getPointer() { return _pt; } + MEDCOUPLING_EXPORT int intValue() const; + MEDCOUPLING_EXPORT DataArrayInt *buildDAInt(int nbOfTuples, int nbOfCompo) const; + private: + int *_pt; + int _nb_of_compo; + }; + + class DataArrayChar : public DataArray + { + public: + MEDCOUPLING_EXPORT virtual DataArrayChar *buildEmptySpecializedDAChar() const = 0; + MEDCOUPLING_EXPORT bool isAllocated() const; + MEDCOUPLING_EXPORT void checkAllocated() const; + MEDCOUPLING_EXPORT void desallocate(); + MEDCOUPLING_EXPORT int getNumberOfTuples() const { return _info_on_compo.empty()?0:_mem.getNbOfElem()/getNumberOfComponents(); } + MEDCOUPLING_EXPORT std::size_t getNbOfElems() const { return _mem.getNbOfElem(); } + MEDCOUPLING_EXPORT std::size_t getHeapMemorySizeWithoutChildren() const; + MEDCOUPLING_EXPORT int getHashCode() const; + MEDCOUPLING_EXPORT bool empty() const; + MEDCOUPLING_EXPORT void cpyFrom(const DataArrayChar& other); + MEDCOUPLING_EXPORT void reserve(std::size_t nbOfElems); + MEDCOUPLING_EXPORT void pushBackSilent(char val); + MEDCOUPLING_EXPORT void pushBackValsSilent(const char *valsBg, const char *valsEnd); + MEDCOUPLING_EXPORT char popBackSilent(); + MEDCOUPLING_EXPORT void pack() const; + MEDCOUPLING_EXPORT std::size_t getNbOfElemAllocated() const { return _mem.getNbOfElemAllocated(); } + MEDCOUPLING_EXPORT void alloc(int nbOfTuple, int nbOfCompo=1); + MEDCOUPLING_EXPORT void allocIfNecessary(int nbOfTuple, int nbOfCompo); + MEDCOUPLING_EXPORT bool isEqual(const DataArrayChar& other) const; + MEDCOUPLING_EXPORT virtual bool isEqualIfNotWhy(const DataArrayChar& other, std::string& reason) const; + MEDCOUPLING_EXPORT bool isEqualWithoutConsideringStr(const DataArrayChar& other) const; + MEDCOUPLING_EXPORT void reverse(); + MEDCOUPLING_EXPORT void fillWithZero(); + MEDCOUPLING_EXPORT void fillWithValue(char val); + MEDCOUPLING_EXPORT std::string repr() const; + MEDCOUPLING_EXPORT std::string reprZip() const; + MEDCOUPLING_EXPORT void reAlloc(int nbOfTuples); + MEDCOUPLING_EXPORT DataArrayInt *convertToIntArr() const; + MEDCOUPLING_EXPORT void renumberInPlace(const int *old2New); + MEDCOUPLING_EXPORT void renumberInPlaceR(const int *new2Old); + MEDCOUPLING_EXPORT DataArrayChar *renumber(const int *old2New) const; + MEDCOUPLING_EXPORT DataArrayChar *renumberR(const int *new2Old) const; + MEDCOUPLING_EXPORT DataArrayChar *renumberAndReduce(const int *old2NewBg, int newNbOfTuple) const; + MEDCOUPLING_EXPORT DataArrayChar *selectByTupleId(const int *new2OldBg, const int *new2OldEnd) const; + MEDCOUPLING_EXPORT DataArrayChar *selectByTupleIdSafe(const int *new2OldBg, const int *new2OldEnd) const; + MEDCOUPLING_EXPORT DataArrayChar *selectByTupleId2(int bg, int end, int step) const; + MEDCOUPLING_EXPORT bool isUniform(char val) const; + MEDCOUPLING_EXPORT void rearrange(int newNbOfCompo); + MEDCOUPLING_EXPORT DataArrayChar *substr(int tupleIdBg, int tupleIdEnd=-1) const; + MEDCOUPLING_EXPORT DataArrayChar *changeNbOfComponents(int newNbOfComp, char dftValue) const; + MEDCOUPLING_EXPORT DataArrayChar *keepSelectedComponents(const std::vector& compoIds) const; + MEDCOUPLING_EXPORT void meldWith(const DataArrayChar *other); + MEDCOUPLING_EXPORT void setPartOfValues1(const DataArrayChar *a, int bgTuples, int endTuples, int stepTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple1(char a, int bgTuples, int endTuples, int stepTuples, int bgComp, int endComp, int stepComp); + MEDCOUPLING_EXPORT void setPartOfValues2(const DataArrayChar *a, const int *bgTuples, const int *endTuples, const int *bgComp, const int *endComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple2(char a, const int *bgTuples, const int *endTuples, const int *bgComp, const int *endComp); + MEDCOUPLING_EXPORT void setPartOfValues3(const DataArrayChar *a, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple3(char a, const int *bgTuples, const int *endTuples, int bgComp, int endComp, int stepComp); + MEDCOUPLING_EXPORT void setPartOfValues4(const DataArrayChar *a, int bgTuples, int endTuples, int stepTuples, const int *bgComp, const int *endComp, bool strictCompoCompare=true); + MEDCOUPLING_EXPORT void setPartOfValuesSimple4(char a, int bgTuples, int endTuples, int stepTuples, const int *bgComp, const int *endComp); + MEDCOUPLING_EXPORT void setPartOfValuesAdv(const DataArrayChar *a, const DataArrayChar *tuplesSelec); + MEDCOUPLING_EXPORT void setContigPartOfSelectedValues(int tupleIdStart, const DataArray *aBase, const DataArrayInt *tuplesSelec); + MEDCOUPLING_EXPORT void setContigPartOfSelectedValues2(int tupleIdStart, const DataArray *aBase, int bg, int end2, int step); + MEDCOUPLING_EXPORT DataArray *selectByTupleRanges(const std::vector >& ranges) const; + MEDCOUPLING_EXPORT void getTuple(int tupleId, char *res) const { std::copy(_mem.getConstPointerLoc(tupleId*_info_on_compo.size()),_mem.getConstPointerLoc((tupleId+1)*_info_on_compo.size()),res); } + MEDCOUPLING_EXPORT char getIJ(int tupleId, int compoId) const { return _mem[tupleId*_info_on_compo.size()+compoId]; } + MEDCOUPLING_EXPORT char getIJSafe(int tupleId, int compoId) const; + MEDCOUPLING_EXPORT char front() const; + MEDCOUPLING_EXPORT char back() const; + MEDCOUPLING_EXPORT void setIJ(int tupleId, int compoId, char newVal) { _mem[tupleId*_info_on_compo.size()+compoId]=newVal; declareAsNew(); } + MEDCOUPLING_EXPORT void setIJSilent(int tupleId, int compoId, char newVal) { _mem[tupleId*_info_on_compo.size()+compoId]=newVal; } + MEDCOUPLING_EXPORT char *getPointer() { return _mem.getPointer(); declareAsNew(); } + MEDCOUPLING_EXPORT const char *getConstPointer() const { return _mem.getConstPointer(); } + MEDCOUPLING_EXPORT const char *begin() const { return getConstPointer(); } + MEDCOUPLING_EXPORT const char *end() const { return getConstPointer()+getNbOfElems(); } + MEDCOUPLING_EXPORT DataArrayInt *getIdsEqual(char val) const; + MEDCOUPLING_EXPORT DataArrayInt *getIdsNotEqual(char val) const; + MEDCOUPLING_EXPORT int search(const std::vector& vals) const; + MEDCOUPLING_EXPORT int locateTuple(const std::vector& tupl) const; + MEDCOUPLING_EXPORT int locateValue(char value) const; + MEDCOUPLING_EXPORT int locateValue(const std::vector& vals) const; + MEDCOUPLING_EXPORT bool presenceOfTuple(const std::vector& tupl) const; + MEDCOUPLING_EXPORT bool presenceOfValue(char value) const; + MEDCOUPLING_EXPORT bool presenceOfValue(const std::vector& vals) const; + MEDCOUPLING_EXPORT char getMaxValue(int& tupleId) const; + MEDCOUPLING_EXPORT char getMaxValueInArray() const; + MEDCOUPLING_EXPORT char getMinValue(int& tupleId) const; + MEDCOUPLING_EXPORT char getMinValueInArray() const; + MEDCOUPLING_EXPORT DataArrayInt *getIdsInRange(char vmin, char vmax) const; + MEDCOUPLING_EXPORT static DataArrayChar *Aggregate(const DataArrayChar *a1, const DataArrayChar *a2); + MEDCOUPLING_EXPORT static DataArrayChar *Aggregate(const std::vector& arr); + MEDCOUPLING_EXPORT static DataArrayChar *Meld(const DataArrayChar *a1, const DataArrayChar *a2); + MEDCOUPLING_EXPORT static DataArrayChar *Meld(const std::vector& arr); + MEDCOUPLING_EXPORT void useArray(const char *array, bool ownership, DeallocType type, int nbOfTuple, int nbOfCompo); + template + void insertAtTheEnd(InputIterator first, InputIterator last); + MEDCOUPLING_EXPORT void useExternalArrayWithRWAccess(const char *array, int nbOfTuple, int nbOfCompo); + MEDCOUPLING_EXPORT void updateTime() const { } + MEDCOUPLING_EXPORT MemArray& accessToMemArray() { return _mem; } + MEDCOUPLING_EXPORT const MemArray& accessToMemArray() const { return _mem; } + public: + //MEDCOUPLING_EXPORT void getTinySerializationIntInformation(std::vector& tinyInfo) const; + //MEDCOUPLING_EXPORT void getTinySerializationStrInformation(std::vector& tinyInfo) const; + //MEDCOUPLING_EXPORT bool resizeForUnserialization(const std::vector& tinyInfoI); + //MEDCOUPLING_EXPORT void finishUnserialization(const std::vector& tinyInfoI, const std::vector& tinyInfoS); + protected: + DataArrayChar() { } + protected: + MemArray _mem; + }; + + class DataArrayByteIterator; + + class DataArrayByte : public DataArrayChar + { + public: + MEDCOUPLING_EXPORT static DataArrayByte *New(); + MEDCOUPLING_EXPORT DataArrayChar *buildEmptySpecializedDAChar() const; + MEDCOUPLING_EXPORT DataArrayByteIterator *iterator(); + MEDCOUPLING_EXPORT DataArrayByte *deepCpy() const; + MEDCOUPLING_EXPORT DataArrayByte *performCpy(bool deepCpy) const; + MEDCOUPLING_EXPORT char byteValue() const; + MEDCOUPLING_EXPORT void reprStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprZipStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprWithoutNameStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprZipWithoutNameStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprCppStream(const std::string& varName, std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprQuickOverview(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprQuickOverviewData(std::ostream& stream, std::size_t maxNbOfByteInRepr) const; + MEDCOUPLING_EXPORT bool isEqualIfNotWhy(const DataArrayChar& other, std::string& reason) const; + MEDCOUPLING_EXPORT std::vector toVectorOfBool() const; + private: + ~DataArrayByte() { } + DataArrayByte() { } + }; + + class DataArrayByteTuple; + + class DataArrayByteIterator + { + public: + MEDCOUPLING_EXPORT DataArrayByteIterator(DataArrayByte *da); + MEDCOUPLING_EXPORT ~DataArrayByteIterator(); + MEDCOUPLING_EXPORT DataArrayByteTuple *nextt(); + private: + DataArrayByte *_da; + char *_pt; + int _tuple_id; + int _nb_comp; + int _nb_tuple; + }; + + class DataArrayByteTuple + { + public: + MEDCOUPLING_EXPORT DataArrayByteTuple(char *pt, int nbOfComp); + MEDCOUPLING_EXPORT std::string repr() const; + MEDCOUPLING_EXPORT int getNumberOfCompo() const { return _nb_of_compo; } + MEDCOUPLING_EXPORT const char *getConstPointer() const { return _pt; } + MEDCOUPLING_EXPORT char *getPointer() { return _pt; } + MEDCOUPLING_EXPORT char byteValue() const; + MEDCOUPLING_EXPORT DataArrayByte *buildDAByte(int nbOfTuples, int nbOfCompo) const; + private: + char *_pt; + int _nb_of_compo; + }; + + class DataArrayAsciiCharIterator; + + class DataArrayAsciiChar : public DataArrayChar + { + public: + MEDCOUPLING_EXPORT static DataArrayAsciiChar *New(); + MEDCOUPLING_EXPORT static DataArrayAsciiChar *New(const std::string& st); + MEDCOUPLING_EXPORT static DataArrayAsciiChar *New(const std::vector& vst, char defaultChar); + MEDCOUPLING_EXPORT DataArrayChar *buildEmptySpecializedDAChar() const; + MEDCOUPLING_EXPORT DataArrayAsciiCharIterator *iterator(); + MEDCOUPLING_EXPORT DataArrayAsciiChar *deepCpy() const; + MEDCOUPLING_EXPORT DataArrayAsciiChar *performCpy(bool deepCpy) const; + MEDCOUPLING_EXPORT char asciiCharValue() const; + MEDCOUPLING_EXPORT void reprStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprZipStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprWithoutNameStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprZipWithoutNameStream(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprCppStream(const std::string& varName, std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprQuickOverview(std::ostream& stream) const; + MEDCOUPLING_EXPORT void reprQuickOverviewData(std::ostream& stream, std::size_t maxNbOfByteInRepr) const; + MEDCOUPLING_EXPORT bool isEqualIfNotWhy(const DataArrayChar& other, std::string& reason) const; + private: + ~DataArrayAsciiChar() { } + DataArrayAsciiChar() { } + DataArrayAsciiChar(const std::string& st); + DataArrayAsciiChar(const std::vector& vst, char defaultChar); + }; + + class DataArrayAsciiCharTuple; + + class DataArrayAsciiCharIterator + { + public: + MEDCOUPLING_EXPORT DataArrayAsciiCharIterator(DataArrayAsciiChar *da); + MEDCOUPLING_EXPORT ~DataArrayAsciiCharIterator(); + MEDCOUPLING_EXPORT DataArrayAsciiCharTuple *nextt(); + private: + DataArrayAsciiChar *_da; + char *_pt; + int _tuple_id; + int _nb_comp; + int _nb_tuple; + }; + + class DataArrayAsciiCharTuple + { + public: + MEDCOUPLING_EXPORT DataArrayAsciiCharTuple(char *pt, int nbOfComp); + MEDCOUPLING_EXPORT std::string repr() const; + MEDCOUPLING_EXPORT int getNumberOfCompo() const { return _nb_of_compo; } + MEDCOUPLING_EXPORT const char *getConstPointer() const { return _pt; } + MEDCOUPLING_EXPORT char *getPointer() { return _pt; } + MEDCOUPLING_EXPORT char asciiCharValue() const; + MEDCOUPLING_EXPORT DataArrayAsciiChar *buildDAAsciiChar(int nbOfTuples, int nbOfCompo) const; + private: + char *_pt; + int _nb_of_compo; + }; + + template + void DataArrayDouble::insertAtTheEnd(InputIterator first, InputIterator last) + { + int nbCompo(getNumberOfComponents()); + if(nbCompo==1) + _mem.insertAtTheEnd(first,last); + else if(nbCompo==0) + { + _info_on_compo.resize(1); + _mem.insertAtTheEnd(first,last); + } + else + throw INTERP_KERNEL::Exception("DataArrayDouble::insertAtTheEnd : not available for DataArrayDouble with number of components different than 1 !"); + } + + template + void DataArrayInt::insertAtTheEnd(InputIterator first, InputIterator last) + { + int nbCompo(getNumberOfComponents()); + if(nbCompo==1) + _mem.insertAtTheEnd(first,last); + else if(nbCompo==0) + { + _info_on_compo.resize(1); + _mem.insertAtTheEnd(first,last); + } + else + throw INTERP_KERNEL::Exception("DataArrayInt::insertAtTheEnd : not available for DataArrayInt with number of components different than 1 !"); + } + + template + void DataArrayChar::insertAtTheEnd(InputIterator first, InputIterator last) + { + int nbCompo(getNumberOfComponents()); + if(nbCompo==1) + _mem.insertAtTheEnd(first,last); + else if(nbCompo==0) + { + _info_on_compo.resize(1); + _mem.insertAtTheEnd(first,last); + } + else + throw INTERP_KERNEL::Exception("DataArrayChar::insertAtTheEnd : not available for DataArrayChar with number of components different than 1 !"); + } +} + +#endif diff --cc medtool/src/MEDCoupling/MEDCouplingRemapper.cxx index 18741778f,000000000..8dad02890 mode 100644,000000..100644 --- a/medtool/src/MEDCoupling/MEDCouplingRemapper.cxx +++ b/medtool/src/MEDCoupling/MEDCouplingRemapper.cxx @@@ -1,1312 -1,0 +1,1324 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#include "MEDCouplingRemapper.hxx" +#include "MEDCouplingMemArray.hxx" +#include "MEDCouplingFieldDouble.hxx" +#include "MEDCouplingFieldTemplate.hxx" +#include "MEDCouplingFieldDiscretization.hxx" +#include "MEDCouplingExtrudedMesh.hxx" +#include "MEDCouplingCMesh.hxx" +#include "MEDCouplingNormalizedUnstructuredMesh.txx" +#include "MEDCouplingNormalizedCartesianMesh.txx" + +#include "Interpolation1D.txx" +#include "Interpolation2DCurve.hxx" +#include "Interpolation2D.txx" +#include "Interpolation3D.txx" +#include "Interpolation3DSurf.hxx" +#include "Interpolation2D1D.txx" +#include "Interpolation3D2D.txx" +#include "InterpolationCU.txx" +#include "InterpolationCC.txx" + +using namespace ParaMEDMEM; + +MEDCouplingRemapper::MEDCouplingRemapper():_src_ft(0),_target_ft(0),_interp_matrix_pol(IK_ONLY_PREFERED),_nature_of_deno(NoNature),_time_deno_update(0) +{ +} + +MEDCouplingRemapper::~MEDCouplingRemapper() +{ + releaseData(false); +} + +/*! + * This method is the second step of the remapping process. The remapping process works in three phases : + * + * - Set remapping options appropriately + * - The computation of remapping matrix + * - Apply the matrix vector multiply to obtain the result of the remapping + * + * This method performs the second step (computation of remapping matrix) which may be CPU-time consuming. This phase is also the most critical (where the most tricky algorithm) in the remapping process. + * Strictly speaking to perform the computation of the remapping matrix the field templates source-side and target-side is required (which is the case of MEDCouplingRemapper::prepareEx). + * So this method is less precise but a more user friendly way to compute a remapping matrix. + * + * \param [in] srcMesh the source mesh + * \param [in] targetMesh the target mesh + * \param [in] method A string obtained by aggregation of the spatial discretisation string representation of source field and target field. The string representation is those returned by MEDCouplingFieldDiscretization::getStringRepr. + * Example : "P0" is for cell discretization. "P1" is for node discretization. So "P0P1" for \a method parameter means from a source cell field (lying on \a srcMesh) to a target node field (lying on \a targetMesh). + * + * \sa MEDCouplingRemapper::prepareEx + */ +int MEDCouplingRemapper::prepare(const MEDCouplingMesh *srcMesh, const MEDCouplingMesh *targetMesh, const std::string& method) +{ + if(!srcMesh || !targetMesh) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepare : presence of NULL input pointer !"); + std::string srcMethod,targetMethod; + INTERP_KERNEL::Interpolation::CheckAndSplitInterpolationMethod(method,srcMethod,targetMethod); + MEDCouplingAutoRefCountObjectPtr src=MEDCouplingFieldTemplate::New(MEDCouplingFieldDiscretization::GetTypeOfFieldFromStringRepr(srcMethod)); + src->setMesh(srcMesh); + MEDCouplingAutoRefCountObjectPtr target=MEDCouplingFieldTemplate::New(MEDCouplingFieldDiscretization::GetTypeOfFieldFromStringRepr(targetMethod)); + target->setMesh(targetMesh); + return prepareEx(src,target); +} + +/*! + * This method is the generalization of MEDCouplingRemapper::prepare. Indeed, MEDCouplingFieldTemplate instances gives all required information to compute the remapping matrix. + * This method must be used instead of MEDCouplingRemapper::prepare if Gauss point to Gauss point must be applied. + * + * \param [in] src is the field template source side. + * \param [in] target is the field template target side. + * + * \sa MEDCouplingRemapper::prepare + */ +int MEDCouplingRemapper::prepareEx(const MEDCouplingFieldTemplate *src, const MEDCouplingFieldTemplate *target) +{ + if(!src || !target) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareEx : presence of NULL input pointer !"); + if(!src->getMesh() || !target->getMesh()) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareEx : presence of NULL mesh pointer in given field template !"); + releaseData(true); + _src_ft=const_cast(src); _src_ft->incrRef(); + _target_ft=const_cast(target); _target_ft->incrRef(); + if(isInterpKernelOnlyOrNotOnly()) + return prepareInterpKernelOnly(); + else + return prepareNotInterpKernelOnly(); +} + +int MEDCouplingRemapper::prepareInterpKernelOnly() +{ + int meshInterpType=((int)_src_ft->getMesh()->getType()*16)+(int)_target_ft->getMesh()->getType(); ++ // *** Remember: ++// typedef enum ++// { ++// UNSTRUCTURED = 5, ++// CARTESIAN = 7, ++// EXTRUDED = 8, ++// CURVE_LINEAR = 9, ++// SINGLE_STATIC_GEO_TYPE_UNSTRUCTURED = 10, ++// SINGLE_DYNAMIC_GEO_TYPE_UNSTRUCTURED = 11, ++// IMAGE_GRID = 12 ++// } MEDCouplingMeshType; ++ + switch(meshInterpType) + { - case 90: - case 91: - case 165: - case 181: - case 170: - case 171: - case 186: - case 187: - case 85://Unstructured-Unstructured ++ case 90: // UNSTRUCTURED - SINGLE_STATIC_GEO_TYPE_UNSTRUCTURED ++ case 91: // UNSTRUCTURED - SINGLE_DYNAMIC_GEO_TYPE_UNSTRUCTURED ++ case 165: // SINGLE_STATIC_GEO_TYPE_UNSTRUCTURED - UNSTRUCTURED ++ case 181: // SINGLE_DYNAMIC_GEO_TYPE_UNSTRUCTURED - UNSTRUCTURED ++ case 170: // SINGLE_STATIC_GEO_TYPE_UNSTRUCTURED - SINGLE_STATIC_GEO_TYPE_UNSTRUCTURED ++ case 171: // SINGLE_STATIC_GEO_TYPE_UNSTRUCTURED - SINGLE_DYNAMIC_GEO_TYPE_UNSTRUCTURED ++ case 186: // SINGLE_DYNAMIC_GEO_TYPE_UNSTRUCTURED - SINGLE_STATIC_GEO_TYPE_UNSTRUCTURED ++ case 187: // SINGLE_DYNAMIC_GEO_TYPE_UNSTRUCTURED - SINGLE_DYNAMIC_GEO_TYPE_UNSTRUCTURED ++ case 85: // UNSTRUCTURED - UNSTRUCTURED + return prepareInterpKernelOnlyUU(); - case 167: - case 183: - case 87://Unstructured-Cartesian ++ case 167: // SINGLE_STATIC_GEO_TYPE_UNSTRUCTURED - CARTESIAN ++ case 183: // SINGLE_DYNAMIC_GEO_TYPE_UNSTRUCTURED - CARTESIAN ++ case 87: // UNSTRUCTURED - CARTESIAN + return prepareInterpKernelOnlyUC(); - case 122: - case 123: - case 117://Cartesian-Unstructured ++ case 122: // CARTESIAN - SINGLE_STATIC_GEO_TYPE_UNSTRUCTURED ++ case 123: // CARTESIAN - SINGLE_DYNAMIC_GEO_TYPE_UNSTRUCTURED ++ case 117: // CARTESIAN - UNSTRUCTURED + return prepareInterpKernelOnlyCU(); - case 119://Cartesian-Cartesian ++ case 119: // CARTESIAN - CARTESIAN + return prepareInterpKernelOnlyCC(); - case 136://Extruded-Extruded ++ case 136: // EXTRUDED - EXTRUDED + return prepareInterpKernelOnlyEE(); + default: + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareInterpKernelOnly : Not managed type of meshes ! Dealt meshes type are : Unstructured<->Unstructured, Unstructured<->Cartesian, Cartesian<->Cartesian, Extruded<->Extruded !"); + } +} + +int MEDCouplingRemapper::prepareNotInterpKernelOnly() +{ + std::string srcm,trgm,method; + method=checkAndGiveInterpolationMethodStr(srcm,trgm); + switch(CheckInterpolationMethodManageableByNotOnlyInterpKernel(method)) + { + case 0: + return prepareNotInterpKernelOnlyGaussGauss(); + default: + { + std::ostringstream oss; oss << "MEDCouplingRemapper::prepareNotInterpKernelOnly : INTERNAL ERROR ! the method \"" << method << "\" declared as managed bu not implemented !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + } +} + +/*! + * This method performs the operation source to target using matrix computed in ParaMEDMEM::MEDCouplingRemapper::prepare method. + * If meshes of \b srcField and \b targetField do not match exactly those given into \ref ParaMEDMEM::MEDCouplingRemapper::prepare "prepare method" an exception will be thrown. + * + * \param [in] srcField is the source field from which the interpolation will be done. The mesh into \b srcField should be the same than those specified on ParaMEDMEM::MEDCouplingRemapper::prepare. + * \param [in/out] targetField the destination field with the allocated array in which all tuples will be overwritten. + * \param [in] dftValue is the value that will be assigned in the targetField to each entity of target mesh (entity depending on the method selected on prepare invocation) that is not intercepted by any entity of source mesh. + * For example in "P0P0" case (cell-cell) if a cell in target mesh is not overlapped by any source cell the \a dftValue value will be attached on that cell in the returned \a targetField. In some cases a target + * cell not intercepted by any source cell is a bug so in this case it is advised to set a huge value (1e300 for example) to \a dftValue to quickly point to the problem. But for users doing parallelism a target cell can + * be intercepted by a source cell on a different process. In this case 0. assigned to \a dftValue is more appropriate. + * + * \sa transferField + */ +void MEDCouplingRemapper::transfer(const MEDCouplingFieldDouble *srcField, MEDCouplingFieldDouble *targetField, double dftValue) +{ + if(!srcField || !targetField) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::transfer : input field must be both not NULL !"); + transferUnderground(srcField,targetField,true,dftValue); +} + +/*! + * This method is equivalent to ParaMEDMEM::MEDCouplingRemapper::transfer except that here \b targetField is a in/out parameter. + * If an entity (cell for example) in targetField is not fetched by any entity (cell for example) of \b srcField, the value in targetField is + * let unchanged. + * This method requires that \b targetField was fully defined and allocated. If the array is not allocated an exception will be thrown. + * + * \param [in] srcField is the source field from which the interpolation will be done. The mesh into \b srcField should be the same than those specified on ParaMEDMEM::MEDCouplingRemapper::prepare. + * \param [in,out] targetField the destination field with the allocated array in which only tuples whose entities are fetched by interpolation will be overwritten only. + */ +void MEDCouplingRemapper::partialTransfer(const MEDCouplingFieldDouble *srcField, MEDCouplingFieldDouble *targetField) +{ + if(!srcField || !targetField) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::partialTransfer : input field must be both not NULL !"); + transferUnderground(srcField,targetField,false,std::numeric_limits::max()); +} + +void MEDCouplingRemapper::reverseTransfer(MEDCouplingFieldDouble *srcField, const MEDCouplingFieldDouble *targetField, double dftValue) +{ + if(!srcField || !targetField) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::reverseTransfer : input fields must be both not NULL !"); + checkPrepare(); + targetField->checkCoherency(); + if(_src_ft->getDiscretization()->getStringRepr()!=srcField->getDiscretization()->getStringRepr()) + throw INTERP_KERNEL::Exception("Incoherency with prepare call for source field"); + if(_target_ft->getDiscretization()->getStringRepr()!=targetField->getDiscretization()->getStringRepr()) + throw INTERP_KERNEL::Exception("Incoherency with prepare call for target field"); + if(srcField->getNature()!=targetField->getNature()) + throw INTERP_KERNEL::Exception("Natures of fields mismatch !"); + if(targetField->getNumberOfTuplesExpected()!=_target_ft->getNumberOfTuplesExpected()) + { + std::ostringstream oss; + oss << "MEDCouplingRemapper::reverseTransfer : in given source field the number of tuples required is " << _target_ft->getNumberOfTuplesExpected() << " (on prepare) and number of tuples in given target field is " << targetField->getNumberOfTuplesExpected(); + oss << " ! It appears that the target support is not the same between the prepare and the transfer !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + DataArrayDouble *array(srcField->getArray()); + int trgNbOfCompo=targetField->getNumberOfComponents(); + if(array) + { + srcField->checkCoherency(); + if(trgNbOfCompo!=srcField->getNumberOfTuplesExpected()) + throw INTERP_KERNEL::Exception("Number of components mismatch !"); + } + else + { + MEDCouplingAutoRefCountObjectPtr tmp(DataArrayDouble::New()); + tmp->alloc(srcField->getNumberOfTuplesExpected(),trgNbOfCompo); + srcField->setArray(tmp); + } + computeDeno(srcField->getNature(),srcField,targetField); + double *resPointer(srcField->getArray()->getPointer()); + const double *inputPointer=targetField->getArray()->getConstPointer(); + computeReverseProduct(inputPointer,trgNbOfCompo,dftValue,resPointer); +} + +/*! + * This method performs the operation source to target using matrix computed in ParaMEDMEM::MEDCouplingRemapper::prepare method. + * If mesh of \b srcField does not match exactly those given into \ref ParaMEDMEM::MEDCouplingRemapper::prepare "prepare method" an exception will be thrown. + * + * \param [in] srcField is the source field from which the interpolation will be done. The mesh into \b srcField should be the same than those specified on ParaMEDMEM::MEDCouplingRemapper::prepare. + * \param [in] dftValue is the value that will be assigned in the targetField to each entity of target mesh (entity depending on the method selected on prepare invocation) that is not intercepted by any entity of source mesh. + * For example in "P0P0" case (cell-cell) if a cell in target mesh is not overlapped by any source cell the \a dftValue value will be attached on that cell in the returned \a targetField. In some cases a target + * cell not intercepted by any source cell is a bug so in this case it is advised to set a huge value (1e300 for example) to \a dftValue to quickly point to the problem. But for users doing parallelism a target cell can + * be intercepted by a source cell on a different process. In this case 0. assigned to \a dftValue is more appropriate. + * \return destination field to be deallocated by the caller. + * + * \sa transfer + */ +MEDCouplingFieldDouble *MEDCouplingRemapper::transferField(const MEDCouplingFieldDouble *srcField, double dftValue) +{ + checkPrepare(); + if(!srcField) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::transferField : input srcField is NULL !"); + srcField->checkCoherency(); + if(_src_ft->getDiscretization()->getStringRepr()!=srcField->getDiscretization()->getStringRepr()) + throw INTERP_KERNEL::Exception("Incoherency with prepare call for source field"); + MEDCouplingFieldDouble *ret=MEDCouplingFieldDouble::New(*_target_ft,srcField->getTimeDiscretization()); + ret->setNature(srcField->getNature()); + transfer(srcField,ret,dftValue); + ret->copyAllTinyAttrFrom(srcField);//perform copy of tiny strings after and not before transfer because the array will be created on transfer + return ret; +} + +MEDCouplingFieldDouble *MEDCouplingRemapper::reverseTransferField(const MEDCouplingFieldDouble *targetField, double dftValue) +{ + if(!targetField) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::transferField : input targetField is NULL !"); + targetField->checkCoherency(); + checkPrepare(); + if(_target_ft->getDiscretization()->getStringRepr()!=targetField->getDiscretization()->getStringRepr()) + throw INTERP_KERNEL::Exception("Incoherency with prepare call for target field"); + MEDCouplingFieldDouble *ret=MEDCouplingFieldDouble::New(*_src_ft,targetField->getTimeDiscretization()); + ret->setNature(targetField->getNature()); + reverseTransfer(ret,targetField,dftValue); + ret->copyAllTinyAttrFrom(targetField);//perform copy of tiny strings after and not before reverseTransfer because the array will be created on reverseTransfer + return ret; +} + +/*! + * This method does nothing more than inherited INTERP_KERNEL::InterpolationOptions::setOptionInt method. This method + * is here only for automatic CORBA generators. + */ +bool MEDCouplingRemapper::setOptionInt(const std::string& key, int value) +{ + return INTERP_KERNEL::InterpolationOptions::setOptionInt(key,value); +} + +/*! + * This method does nothing more than inherited INTERP_KERNEL::InterpolationOptions::setOptionInt method. This method + * is here only for automatic CORBA generators. + */ +bool MEDCouplingRemapper::setOptionDouble(const std::string& key, double value) +{ + return INTERP_KERNEL::InterpolationOptions::setOptionDouble(key,value); +} + +/*! + * This method does nothing more than inherited INTERP_KERNEL::InterpolationOptions::setOptionInt method. This method + * is here only for automatic CORBA generators. + */ +bool MEDCouplingRemapper::setOptionString(const std::string& key, const std::string& value) +{ + return INTERP_KERNEL::InterpolationOptions::setOptionString(key,value); +} + +/*! + * This method returns the interpolation matrix policy. This policy specifies which interpolation matrix method to keep or prefered. + * If interpolation matrix policy is : + * + * - set to IK_ONLY_PREFERED (0) (the default) : the INTERP_KERNEL only method is prefered. That is to say, if it is possible to treat the case + * regarding spatial discretization of source and target with INTERP_KERNEL only method, INTERP_KERNEL only method will be performed. + * If not, the \b not only INTERP_KERNEL method will be attempt. + * + * - set to NOT_IK_ONLY_PREFERED (1) : the \b NOT only INTERP_KERNEL method is prefered. That is to say, if it is possible to treat the case + * regarding spatial discretization of source and target with \b NOT only INTERP_KERNEL method, \b NOT only INTERP_KERNEL method, will be performed. + * If not, the INTERP_KERNEL only method will be attempt. + * + * - IK_ONLY_FORCED (2) : Only INTERP_KERNEL only method will be launched. + * + * - NOT_IK_ONLY_FORCED (3) : Only \b NOT INTERP_KERNEL only method will be launched. + * + * \sa MEDCouplingRemapper::setInterpolationMatrixPolicy + */ +int MEDCouplingRemapper::getInterpolationMatrixPolicy() const +{ + return _interp_matrix_pol; +} + +/*! + * This method sets a new interpolation matrix policy. The default one is IK_PREFERED (0). The input is of type \c int to be dealt by standard Salome + * CORBA component generators. This method throws an INTERP_KERNEL::Exception if a the input integer is not in the available possibilities, that is to say not in + * [0 (IK_PREFERED) , 1 (NOT_IK_PREFERED), 2 (IK_ONLY_FORCED), 3 (NOT_IK_ONLY_FORCED)]. + * + * If interpolation matrix policy is : + * + * - set to IK_ONLY_PREFERED (0) (the default) : the INTERP_KERNEL only method is prefered. That is to say, if it is possible to treat the case + * regarding spatial discretization of source and target with INTERP_KERNEL only method, INTERP_KERNEL only method will be performed. + * If not, the \b not only INTERP_KERNEL method will be attempt. + * + * - set to NOT_IK_ONLY_PREFERED (1) : the \b NOT only INTERP_KERNEL method is prefered. That is to say, if it is possible to treat the case + * regarding spatial discretization of source and target with \b NOT only INTERP_KERNEL method, \b NOT only INTERP_KERNEL method, will be performed. + * If not, the INTERP_KERNEL only method will be attempt. + * + * - IK_ONLY_FORCED (2) : Only INTERP_KERNEL only method will be launched. + * + * - NOT_IK_ONLY_FORCED (3) : Only \b NOT INTERP_KERNEL only method will be launched. + * + * \input newInterpMatPol the new interpolation matrix method policy. This parameter is of type \c int and not of type \c ParaMEDMEM::InterpolationMatrixPolicy + * for automatic generation of CORBA component. + * + * \sa MEDCouplingRemapper::getInterpolationMatrixPolicy + */ +void MEDCouplingRemapper::setInterpolationMatrixPolicy(int newInterpMatPol) +{ + switch(newInterpMatPol) + { + case 0: + _interp_matrix_pol=IK_ONLY_PREFERED; + break; + case 1: + _interp_matrix_pol=NOT_IK_ONLY_PREFERED; + break; + case 2: + _interp_matrix_pol=IK_ONLY_FORCED; + break; + case 3: + _interp_matrix_pol=NOT_IK_ONLY_FORCED; + break; + default: + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::setInterpolationMatrixPolicy : invalid input integer value ! Should be in [0 (IK_PREFERED) , 1 (NOT_IK_PREFERED), 2 (IK_ONLY_FORCED), 3 (NOT_IK_ONLY_FORCED)] ! For information, the default is IK_PREFERED=0 !"); + } +} + +int MEDCouplingRemapper::prepareInterpKernelOnlyUU() +{ + const MEDCouplingPointSet *src_mesh=static_cast(_src_ft->getMesh()); + const MEDCouplingPointSet *target_mesh=static_cast(_target_ft->getMesh()); + std::string srcMeth,trgMeth; + std::string method(checkAndGiveInterpolationMethodStr(srcMeth,trgMeth)); + const int srcMeshDim=src_mesh->getMeshDimension(); + int srcSpaceDim=-1; + if(srcMeshDim!=-1) + srcSpaceDim=src_mesh->getSpaceDimension(); + const int trgMeshDim=target_mesh->getMeshDimension(); + int trgSpaceDim=-1; + if(trgMeshDim!=-1) + trgSpaceDim=target_mesh->getSpaceDimension(); + if(trgSpaceDim!=srcSpaceDim) + if(trgSpaceDim!=-1 && srcSpaceDim!=-1) + throw INTERP_KERNEL::Exception("Incoherent space dimension detected between target and source."); + int nbCols; + if(srcMeshDim==1 && trgMeshDim==1 && srcSpaceDim==1) + { + MEDCouplingNormalizedUnstructuredMesh<1,1> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<1,1> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation1D interpolation(*this); + nbCols=interpolation.interpolateMeshes(source_mesh_wrapper,target_mesh_wrapper,_matrix,method); + } + else if(srcMeshDim==1 && trgMeshDim==1 && srcSpaceDim==2) + { + MEDCouplingNormalizedUnstructuredMesh<2,1> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<2,1> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation2DCurve interpolation(*this); + nbCols=interpolation.interpolateMeshes(source_mesh_wrapper,target_mesh_wrapper,_matrix,method); + } + else if(srcMeshDim==2 && trgMeshDim==2 && srcSpaceDim==2) + { + MEDCouplingNormalizedUnstructuredMesh<2,2> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<2,2> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation2D interpolation(*this); + nbCols=interpolation.interpolateMeshes(source_mesh_wrapper,target_mesh_wrapper,_matrix,method); + } + else if(srcMeshDim==3 && trgMeshDim==3 && srcSpaceDim==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,3> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<3,3> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation3D interpolation(*this); + nbCols=interpolation.interpolateMeshes(source_mesh_wrapper,target_mesh_wrapper,_matrix,method); + } + else if(srcMeshDim==2 && trgMeshDim==2 && srcSpaceDim==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,2> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<3,2> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation3DSurf interpolation(*this); + nbCols=interpolation.interpolateMeshes(source_mesh_wrapper,target_mesh_wrapper,_matrix,method); + } + else if(srcMeshDim==3 && trgMeshDim==1 && srcSpaceDim==3) + { + if(getIntersectionType()!=INTERP_KERNEL::PointLocator) + throw INTERP_KERNEL::Exception("Invalid interpolation requested between 3D and 1D ! Select PointLocator as intersection type !"); + MEDCouplingNormalizedUnstructuredMesh<3,3> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<3,3> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation3D interpolation(*this); + nbCols=interpolation.interpolateMeshes(source_mesh_wrapper,target_mesh_wrapper,_matrix,method); + } + else if(srcMeshDim==1 && trgMeshDim==3 && srcSpaceDim==3) + { + if(getIntersectionType()!=INTERP_KERNEL::PointLocator) + throw INTERP_KERNEL::Exception("Invalid interpolation requested between 3D and 1D ! Select PointLocator as intersection type !"); + MEDCouplingNormalizedUnstructuredMesh<3,3> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<3,3> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation3D interpolation(*this); + std::vector > matrixTmp; + std::string revMethod(BuildMethodFrom(trgMeth,srcMeth)); + nbCols=interpolation.interpolateMeshes(target_mesh_wrapper,source_mesh_wrapper,matrixTmp,revMethod); + ReverseMatrix(matrixTmp,nbCols,_matrix); + nbCols=matrixTmp.size(); + } + else if(srcMeshDim==2 && trgMeshDim==1 && srcSpaceDim==2) + { + if(getIntersectionType()==INTERP_KERNEL::PointLocator) + { + MEDCouplingNormalizedUnstructuredMesh<2,2> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<2,2> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation2D interpolation(*this); + nbCols=interpolation.interpolateMeshes(source_mesh_wrapper,target_mesh_wrapper,_matrix,method); + } + else + { + MEDCouplingNormalizedUnstructuredMesh<2,2> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<2,2> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation2D1D interpolation(*this); + std::vector > matrixTmp; + std::string revMethod(BuildMethodFrom(trgMeth,srcMeth)); + nbCols=interpolation.interpolateMeshes(target_mesh_wrapper,source_mesh_wrapper,matrixTmp,revMethod); + ReverseMatrix(matrixTmp,nbCols,_matrix); + nbCols=matrixTmp.size(); + INTERP_KERNEL::Interpolation2D1D::DuplicateFacesType duplicateFaces=interpolation.retrieveDuplicateFaces(); + if(!duplicateFaces.empty()) + { - std::ostringstream oss; oss << "An unexpected situation happend ! For the following 1D Cells are part of edges shared by 2D cells :\n"; ++ std::ostringstream oss; oss << "An unexpected situation happened ! For the following 1D Cells are part of edges shared by 2D cells :\n"; + for(std::map >::const_iterator it=duplicateFaces.begin();it!=duplicateFaces.end();it++) + { + oss << "1D Cell #" << (*it).first << " is part of common edge of following 2D cells ids : "; + std::copy((*it).second.begin(),(*it).second.end(),std::ostream_iterator(oss," ")); + oss << std::endl; + } + } + } + } + else if(srcMeshDim==1 && trgMeshDim==2 && srcSpaceDim==2) + { + if(getIntersectionType()==INTERP_KERNEL::PointLocator) + { + MEDCouplingNormalizedUnstructuredMesh<2,2> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<2,2> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation2D interpolation(*this); + std::vector > matrixTmp; + std::string revMethod(BuildMethodFrom(trgMeth,srcMeth)); + nbCols=interpolation.interpolateMeshes(target_mesh_wrapper,source_mesh_wrapper,matrixTmp,revMethod); + ReverseMatrix(matrixTmp,nbCols,_matrix); + nbCols=matrixTmp.size(); + } + else + { + MEDCouplingNormalizedUnstructuredMesh<2,2> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<2,2> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation2D1D interpolation(*this); + nbCols=interpolation.interpolateMeshes(source_mesh_wrapper,target_mesh_wrapper,_matrix,method); + INTERP_KERNEL::Interpolation2D1D::DuplicateFacesType duplicateFaces=interpolation.retrieveDuplicateFaces(); + if(!duplicateFaces.empty()) + { + std::ostringstream oss; oss << "An unexpected situation happend ! For the following 1D Cells are part of edges shared by 2D cells :\n"; + for(std::map >::const_iterator it=duplicateFaces.begin();it!=duplicateFaces.end();it++) + { + oss << "1D Cell #" << (*it).first << " is part of common edge of following 2D cells ids : "; + std::copy((*it).second.begin(),(*it).second.end(),std::ostream_iterator(oss," ")); + oss << std::endl; + } + } + } + } + else if(srcMeshDim==2 && trgMeshDim==3 && srcSpaceDim==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,3> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<3,3> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation3D2D interpolation(*this); + nbCols=interpolation.interpolateMeshes(source_mesh_wrapper,target_mesh_wrapper,_matrix,method); + INTERP_KERNEL::Interpolation3D2D::DuplicateFacesType duplicateFaces=interpolation.retrieveDuplicateFaces(); + if(!duplicateFaces.empty()) + { + std::ostringstream oss; oss << "An unexpected situation happend ! For the following 2D Cells are part of edges shared by 3D cells :\n"; + for(std::map >::const_iterator it=duplicateFaces.begin();it!=duplicateFaces.end();it++) + { + oss << "2D Cell #" << (*it).first << " is part of common face of following 3D cells ids : "; + std::copy((*it).second.begin(),(*it).second.end(),std::ostream_iterator(oss," ")); + oss << std::endl; + } + } + } + else if(srcMeshDim==3 && trgMeshDim==2 && srcSpaceDim==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,3> source_mesh_wrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<3,3> target_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation3D2D interpolation(*this); + std::vector > matrixTmp; + std::string revMethod(BuildMethodFrom(trgMeth,srcMeth)); + nbCols=interpolation.interpolateMeshes(target_mesh_wrapper,source_mesh_wrapper,matrixTmp,revMethod); + ReverseMatrix(matrixTmp,nbCols,_matrix); + nbCols=matrixTmp.size(); + INTERP_KERNEL::Interpolation3D2D::DuplicateFacesType duplicateFaces=interpolation.retrieveDuplicateFaces(); + if(!duplicateFaces.empty()) + { + std::ostringstream oss; oss << "An unexpected situation happend ! For the following 2D Cells are part of edges shared by 3D cells :\n"; + for(std::map >::const_iterator it=duplicateFaces.begin();it!=duplicateFaces.end();it++) + { + oss << "2D Cell #" << (*it).first << " is part of common face of following 3D cells ids : "; + std::copy((*it).second.begin(),(*it).second.end(),std::ostream_iterator(oss," ")); + oss << std::endl; + } + } + } + else if(trgMeshDim==-1) + { + if(srcMeshDim==2 && srcSpaceDim==2) + { + MEDCouplingNormalizedUnstructuredMesh<2,2> source_mesh_wrapper(src_mesh); + INTERP_KERNEL::Interpolation2D interpolation(*this); + nbCols=interpolation.toIntegralUniform(source_mesh_wrapper,_matrix,srcMeth); + } + else if(srcMeshDim==3 && srcSpaceDim==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,3> source_mesh_wrapper(src_mesh); + INTERP_KERNEL::Interpolation3D interpolation(*this); + nbCols=interpolation.toIntegralUniform(source_mesh_wrapper,_matrix,srcMeth); + } + else if(srcMeshDim==2 && srcSpaceDim==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,2> source_mesh_wrapper(src_mesh); + INTERP_KERNEL::Interpolation3DSurf interpolation(*this); + nbCols=interpolation.toIntegralUniform(source_mesh_wrapper,_matrix,srcMeth); + } + else + throw INTERP_KERNEL::Exception("No interpolation available for the given mesh and space dimension of source mesh to -1D targetMesh"); + } + else if(srcMeshDim==-1) + { + if(trgMeshDim==2 && trgSpaceDim==2) + { + MEDCouplingNormalizedUnstructuredMesh<2,2> source_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation2D interpolation(*this); + nbCols=interpolation.fromIntegralUniform(source_mesh_wrapper,_matrix,trgMeth); + } + else if(trgMeshDim==3 && trgSpaceDim==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,3> source_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation3D interpolation(*this); + nbCols=interpolation.fromIntegralUniform(source_mesh_wrapper,_matrix,trgMeth); + } + else if(trgMeshDim==2 && trgSpaceDim==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,2> source_mesh_wrapper(target_mesh); + INTERP_KERNEL::Interpolation3DSurf interpolation(*this); + nbCols=interpolation.fromIntegralUniform(source_mesh_wrapper,_matrix,trgMeth); + } + else + throw INTERP_KERNEL::Exception("No interpolation available for the given mesh and space dimension of source mesh from -1D sourceMesh"); + } + else + throw INTERP_KERNEL::Exception("No interpolation available for the given mesh and space dimension"); + _deno_multiply.clear(); + _deno_multiply.resize(_matrix.size()); + _deno_reverse_multiply.clear(); + _deno_reverse_multiply.resize(nbCols); + declareAsNew(); + return 1; +} + +int MEDCouplingRemapper::prepareInterpKernelOnlyEE() +{ + std::string srcMeth,trgMeth; + std::string methC=checkAndGiveInterpolationMethodStr(srcMeth,trgMeth); + const MEDCouplingExtrudedMesh *src_mesh=static_cast(_src_ft->getMesh()); + const MEDCouplingExtrudedMesh *target_mesh=static_cast(_target_ft->getMesh()); + if(methC!="P0P0") + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareInterpKernelOnlyEE : Only P0P0 method implemented for Extruded/Extruded meshes !"); + MEDCouplingNormalizedUnstructuredMesh<3,2> source_mesh_wrapper(src_mesh->getMesh2D()); + MEDCouplingNormalizedUnstructuredMesh<3,2> target_mesh_wrapper(target_mesh->getMesh2D()); + INTERP_KERNEL::Interpolation3DSurf interpolation2D(*this); + std::vector > matrix2D; + int nbCols2D=interpolation2D.interpolateMeshes(source_mesh_wrapper,target_mesh_wrapper,matrix2D,methC); + MEDCouplingUMesh *s1D,*t1D; + double v[3]; + MEDCouplingExtrudedMesh::Project1DMeshes(src_mesh->getMesh1D(),target_mesh->getMesh1D(),getPrecision(),s1D,t1D,v); + MEDCouplingNormalizedUnstructuredMesh<1,1> s1DWrapper(s1D); + MEDCouplingNormalizedUnstructuredMesh<1,1> t1DWrapper(t1D); + std::vector > matrix1D; + INTERP_KERNEL::Interpolation1D interpolation1D(*this); + int nbCols1D=interpolation1D.interpolateMeshes(s1DWrapper,t1DWrapper,matrix1D,methC); + s1D->decrRef(); + t1D->decrRef(); + buildFinalInterpolationMatrixByConvolution(matrix1D,matrix2D,src_mesh->getMesh3DIds()->getConstPointer(),nbCols2D,nbCols1D, + target_mesh->getMesh3DIds()->getConstPointer()); + // + _deno_multiply.clear(); + _deno_multiply.resize(_matrix.size()); + _deno_reverse_multiply.clear(); + _deno_reverse_multiply.resize(nbCols2D*nbCols1D); + declareAsNew(); + return 1; +} + +int MEDCouplingRemapper::prepareInterpKernelOnlyUC() +{ + std::string srcMeth,trgMeth; + std::string methodCpp=checkAndGiveInterpolationMethodStr(srcMeth,trgMeth); + if(methodCpp!="P0P0") + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareInterpKernelOnlyUC : only P0P0 interpolation supported for the moment !"); + const MEDCouplingUMesh *src_mesh=static_cast(_src_ft->getMesh()); + const MEDCouplingCMesh *target_mesh=static_cast(_target_ft->getMesh()); + const int srcMeshDim=src_mesh->getMeshDimension(); + const int srcSpceDim=src_mesh->getSpaceDimension(); + const int trgMeshDim=target_mesh->getMeshDimension(); + if(srcMeshDim!=srcSpceDim || srcMeshDim!=trgMeshDim) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareInterpKernelOnlyUC : space dim of src unstructured should be equal to mesh dim of src unstructured and should be equal also equal to trg cartesian dimension !"); + std::vector > res; + switch(srcMeshDim) + { + case 1: + { + MEDCouplingNormalizedCartesianMesh<1> targetWrapper(target_mesh); + MEDCouplingNormalizedUnstructuredMesh<1,1> sourceWrapper(src_mesh); + INTERP_KERNEL::InterpolationCU myInterpolator(*this); + myInterpolator.interpolateMeshes(targetWrapper,sourceWrapper,res,"P0P0"); + break; + } + case 2: + { + MEDCouplingNormalizedCartesianMesh<2> targetWrapper(target_mesh); + MEDCouplingNormalizedUnstructuredMesh<2,2> sourceWrapper(src_mesh); + INTERP_KERNEL::InterpolationCU myInterpolator(*this); + myInterpolator.interpolateMeshes(targetWrapper,sourceWrapper,res,"P0P0"); + break; + } + case 3: + { + MEDCouplingNormalizedCartesianMesh<3> targetWrapper(target_mesh); + MEDCouplingNormalizedUnstructuredMesh<3,3> sourceWrapper(src_mesh); + INTERP_KERNEL::InterpolationCU myInterpolator(*this); + myInterpolator.interpolateMeshes(targetWrapper,sourceWrapper,res,"P0P0"); + break; + } + default: + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareInterpKernelOnlyUC : only dimension 1 2 or 3 supported !"); + } + ReverseMatrix(res,target_mesh->getNumberOfCells(),_matrix); + nullifiedTinyCoeffInCrudeMatrixAbs(0.); + // + _deno_multiply.clear(); + _deno_multiply.resize(_matrix.size()); + _deno_reverse_multiply.clear(); + _deno_reverse_multiply.resize(src_mesh->getNumberOfCells()); + declareAsNew(); + return 1; +} + +int MEDCouplingRemapper::prepareInterpKernelOnlyCU() +{ + std::string srcMeth,trgMeth; + std::string methodCpp=checkAndGiveInterpolationMethodStr(srcMeth,trgMeth); + if(methodCpp!="P0P0") + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareInterpKernelOnlyCU : only P0P0 interpolation supported for the moment !"); + const MEDCouplingCMesh *src_mesh=static_cast(_src_ft->getMesh()); + const MEDCouplingUMesh *target_mesh=static_cast(_target_ft->getMesh()); + const int srcMeshDim=src_mesh->getMeshDimension(); + const int trgMeshDim=target_mesh->getMeshDimension(); + const int trgSpceDim=target_mesh->getSpaceDimension(); + if(trgMeshDim!=trgSpceDim || trgMeshDim!=srcMeshDim) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareInterpKernelOnlyCU : space dim of target unstructured should be equal to mesh dim of target unstructured and should be equal also equal to source cartesian dimension !"); + switch(srcMeshDim) + { + case 1: + { + MEDCouplingNormalizedCartesianMesh<1> sourceWrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<1,1> targetWrapper(target_mesh); + INTERP_KERNEL::InterpolationCU myInterpolator(*this); + myInterpolator.interpolateMeshes(sourceWrapper,targetWrapper,_matrix,"P0P0"); + break; + } + case 2: + { + MEDCouplingNormalizedCartesianMesh<2> sourceWrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<2,2> targetWrapper(target_mesh); + INTERP_KERNEL::InterpolationCU myInterpolator(*this); + myInterpolator.interpolateMeshes(sourceWrapper,targetWrapper,_matrix,"P0P0"); + break; + } + case 3: + { + MEDCouplingNormalizedCartesianMesh<3> sourceWrapper(src_mesh); + MEDCouplingNormalizedUnstructuredMesh<3,3> targetWrapper(target_mesh); + INTERP_KERNEL::InterpolationCU myInterpolator(*this); + myInterpolator.interpolateMeshes(sourceWrapper,targetWrapper,_matrix,"P0P0"); + break; + } + default: + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareInterpKernelOnlyCU : only dimension 1 2 or 3 supported !"); + } + nullifiedTinyCoeffInCrudeMatrixAbs(0.); + // + _deno_multiply.clear(); + _deno_multiply.resize(_matrix.size()); + _deno_reverse_multiply.clear(); + _deno_reverse_multiply.resize(src_mesh->getNumberOfCells()); + declareAsNew(); + return 1; +} + +int MEDCouplingRemapper::prepareInterpKernelOnlyCC() +{ + std::string srcMeth,trgMeth; + std::string methodCpp=checkAndGiveInterpolationMethodStr(srcMeth,trgMeth); + if(methodCpp!="P0P0") + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareInterpKernelOnlyCC : only P0P0 interpolation supported for the moment !"); + const MEDCouplingCMesh *src_mesh=static_cast(_src_ft->getMesh()); + const MEDCouplingCMesh *target_mesh=static_cast(_target_ft->getMesh()); + const int srcMeshDim=src_mesh->getMeshDimension(); + const int trgMeshDim=target_mesh->getMeshDimension(); + if(trgMeshDim!=srcMeshDim) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareInterpKernelOnlyCC : dim of target cartesian should be equal to dim of source cartesian dimension !"); + switch(srcMeshDim) + { + case 1: + { + MEDCouplingNormalizedCartesianMesh<1> sourceWrapper(src_mesh); + MEDCouplingNormalizedCartesianMesh<1> targetWrapper(target_mesh); + INTERP_KERNEL::InterpolationCC myInterpolator(*this); + myInterpolator.interpolateMeshes(sourceWrapper,targetWrapper,_matrix,"P0P0"); + break; + } + case 2: + { + MEDCouplingNormalizedCartesianMesh<2> sourceWrapper(src_mesh); + MEDCouplingNormalizedCartesianMesh<2> targetWrapper(target_mesh); + INTERP_KERNEL::InterpolationCC myInterpolator(*this); + myInterpolator.interpolateMeshes(sourceWrapper,targetWrapper,_matrix,"P0P0"); + break; + } + case 3: + { + MEDCouplingNormalizedCartesianMesh<3> sourceWrapper(src_mesh); + MEDCouplingNormalizedCartesianMesh<3> targetWrapper(target_mesh); + INTERP_KERNEL::InterpolationCC myInterpolator(*this); + myInterpolator.interpolateMeshes(sourceWrapper,targetWrapper,_matrix,"P0P0"); + break; + } + default: + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareInterpKernelOnlyCC : only dimension 1 2 or 3 supported !"); + } + nullifiedTinyCoeffInCrudeMatrixAbs(0.); + // + _deno_multiply.clear(); + _deno_multiply.resize(_matrix.size()); + _deno_reverse_multiply.clear(); + _deno_reverse_multiply.resize(src_mesh->getNumberOfCells()); + declareAsNew(); + return 1; +} + +int MEDCouplingRemapper::prepareNotInterpKernelOnlyGaussGauss() +{ + if(getIntersectionType()!=INTERP_KERNEL::PointLocator) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::prepareNotInterpKernelOnlyGaussGauss : The intersection type is not supported ! Only PointLocator is supported for Gauss->Gauss interpolation ! Please invoke setIntersectionType(PointLocator) on the MEDCouplingRemapper instance !"); + MEDCouplingAutoRefCountObjectPtr trgLoc=_target_ft->getLocalizationOfDiscr(); + const double *trgLocPtr=trgLoc->begin(); + int trgSpaceDim=trgLoc->getNumberOfComponents(); + MEDCouplingAutoRefCountObjectPtr srcOffsetArr=_src_ft->getDiscretization()->getOffsetArr(_src_ft->getMesh()); + if(trgSpaceDim!=_src_ft->getMesh()->getSpaceDimension()) + { + std::ostringstream oss; oss << "MEDCouplingRemapper::prepareNotInterpKernelOnlyGaussGauss : space dimensions mismatch between source and target !"; + oss << " Target discretization localization has dimension " << trgSpaceDim << ", whereas the space dimension of source is equal to "; + oss << _src_ft->getMesh()->getSpaceDimension() << " !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + const int *srcOffsetArrPtr=srcOffsetArr->begin(); + MEDCouplingAutoRefCountObjectPtr srcLoc=_src_ft->getLocalizationOfDiscr(); + const double *srcLocPtr=srcLoc->begin(); + MEDCouplingAutoRefCountObjectPtr eltsArr,eltsIndexArr; + int trgNbOfGaussPts=trgLoc->getNumberOfTuples(); + _matrix.resize(trgNbOfGaussPts); + _src_ft->getMesh()->getCellsContainingPoints(trgLoc->begin(),trgNbOfGaussPts,getPrecision(),eltsArr,eltsIndexArr); + const int *elts(eltsArr->begin()),*eltsIndex(eltsIndexArr->begin()); + MEDCouplingAutoRefCountObjectPtr nbOfSrcCellsShTrgPts(eltsIndexArr->deltaShiftIndex()); + MEDCouplingAutoRefCountObjectPtr ids0=nbOfSrcCellsShTrgPts->getIdsNotEqual(0); + for(const int *trgId=ids0->begin();trgId!=ids0->end();trgId++) + { + const double *ptTrg=trgLocPtr+trgSpaceDim*(*trgId); + int srcCellId=elts[eltsIndex[*trgId]]; + double dist=std::numeric_limits::max(); + int srcEntry=-1; + for(int srcId=srcOffsetArrPtr[srcCellId];srcIdgetNumberOfTuples()!=trgNbOfGaussPts) + { + MEDCouplingAutoRefCountObjectPtr orphanTrgIds=nbOfSrcCellsShTrgPts->getIdsEqual(0); + MEDCouplingAutoRefCountObjectPtr orphanTrg=trgLoc->selectByTupleId(orphanTrgIds->begin(),orphanTrgIds->end()); + MEDCouplingAutoRefCountObjectPtr srcIdPerTrg=srcLoc->findClosestTupleId(orphanTrg); + const int *srcIdPerTrgPtr=srcIdPerTrg->begin(); + for(const int *orphanTrgId=orphanTrgIds->begin();orphanTrgId!=orphanTrgIds->end();orphanTrgId++,srcIdPerTrgPtr++) + _matrix[*orphanTrgId][*srcIdPerTrgPtr]=2.; + } + _deno_multiply.clear(); + _deno_multiply.resize(_matrix.size()); + _deno_reverse_multiply.clear(); + _deno_reverse_multiply.resize(srcLoc->getNumberOfTuples()); + declareAsNew(); + return 1; +} + +/*! + * This method checks that the input interpolation \a method is managed by not INTERP_KERNEL only methods. + * If no an INTERP_KERNEL::Exception will be thrown. If yes, a magic number will be returned to switch in the MEDCouplingRemapper::prepareNotInterpKernelOnly method. + */ +int MEDCouplingRemapper::CheckInterpolationMethodManageableByNotOnlyInterpKernel(const std::string& method) +{ + if(method=="GAUSSGAUSS") + return 0; + std::ostringstream oss; oss << "MEDCouplingRemapper::CheckInterpolationMethodManageableByNotOnlyInterpKernel : "; + oss << "The method \"" << method << "\" is not manageable by not INTERP_KERNEL only method."; + oss << " Not only INTERP_KERNEL methods dealed are : GAUSSGAUSS !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); +} + +/*! + * This method determines regarding \c _interp_matrix_pol attribute ( set by MEDCouplingRemapper::setInterpolationMatrixPolicy and by default equal - * to IK_ONLY_PREFERED = 0 ) , which method will be applied. If \c true is returned the INTERP_KERNEL only method should be applied to \c false the \b not ++ * to IK_ONLY_PREFERED, which method will be applied. If \c true is returned the INTERP_KERNEL only method should be applied to \c false the \b not + * only INTERP_KERNEL method should be applied. + */ +bool MEDCouplingRemapper::isInterpKernelOnlyOrNotOnly() const +{ + std::string srcm,trgm,method; + method=checkAndGiveInterpolationMethodStr(srcm,trgm); + switch(_interp_matrix_pol) + { + case IK_ONLY_PREFERED: + { + try + { + std::string tmp1,tmp2; + INTERP_KERNEL::Interpolation::CheckAndSplitInterpolationMethod(method,tmp1,tmp2); + return true; + } + catch(INTERP_KERNEL::Exception& /*e*/) + { + return false; + } + } + case NOT_IK_ONLY_PREFERED: + { + try + { + CheckInterpolationMethodManageableByNotOnlyInterpKernel(method); + return false; + } + catch(INTERP_KERNEL::Exception& /*e*/) + { + return true; + } + } + case IK_ONLY_FORCED: + return true; + case NOT_IK_ONLY_FORCED: + return false; + default: + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::isInterpKernelOnlyOrNotOnly : internal error ! The interpolation matrix policy is not managed ! Try to change it using MEDCouplingRemapper::setInterpolationMatrixPolicy !"); + } +} + +void MEDCouplingRemapper::updateTime() const +{ +} + +void MEDCouplingRemapper::checkPrepare() const +{ + const MEDCouplingFieldTemplate *s(_src_ft),*t(_target_ft); + if(!s || !t) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::checkPrepare : it appears that MEDCouplingRemapper::prepare(Ex) has not been called !"); + if(!s->getMesh() || !t->getMesh()) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::checkPrepare : it appears that no all field templates have their mesh set !"); +} + +/*! + * This method builds a code considering already set field discretization int \a this : \a _src_ft and \a _target_ft. + * This method returns 3 informations (2 in ouput parameters and 1 in return). + * + * \param [out] srcMeth the string code of the discretization of source field template + * \param [out] trgMeth the string code of the discretization of target field template + * \return the standardized string code (compatible with INTERP_KERNEL) for matrix of numerators (in \a _matrix) + */ +std::string MEDCouplingRemapper::checkAndGiveInterpolationMethodStr(std::string& srcMeth, std::string& trgMeth) const +{ + const MEDCouplingFieldTemplate *s(_src_ft),*t(_target_ft); + if(!s || !t) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::checkAndGiveInterpolationMethodStr : it appears that no all field templates have been set !"); + if(!s->getMesh() || !t->getMesh()) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::checkAndGiveInterpolationMethodStr : it appears that no all field templates have their mesh set !"); + srcMeth=_src_ft->getDiscretization()->getRepr(); + trgMeth=_target_ft->getDiscretization()->getRepr(); + return BuildMethodFrom(srcMeth,trgMeth); +} + +std::string MEDCouplingRemapper::BuildMethodFrom(const std::string& meth1, const std::string& meth2) +{ + std::string method(meth1); method+=meth2; + return method; +} + +void MEDCouplingRemapper::releaseData(bool matrixSuppression) +{ + _src_ft=0; + _target_ft=0; + if(matrixSuppression) + { + _matrix.clear(); + _deno_multiply.clear(); + _deno_reverse_multiply.clear(); + } +} + +void MEDCouplingRemapper::transferUnderground(const MEDCouplingFieldDouble *srcField, MEDCouplingFieldDouble *targetField, bool isDftVal, double dftValue) +{ + if(!srcField || !targetField) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::transferUnderground : srcField or targetField is NULL !"); + srcField->checkCoherency(); + checkPrepare(); + if(_src_ft->getDiscretization()->getStringRepr()!=srcField->getDiscretization()->getStringRepr()) + throw INTERP_KERNEL::Exception("Incoherency with prepare call for source field"); + if(_target_ft->getDiscretization()->getStringRepr()!=targetField->getDiscretization()->getStringRepr()) + throw INTERP_KERNEL::Exception("Incoherency with prepare call for target field"); + if(srcField->getNature()!=targetField->getNature()) + throw INTERP_KERNEL::Exception("Natures of fields mismatch !"); + if(srcField->getNumberOfTuplesExpected()!=_src_ft->getNumberOfTuplesExpected()) + { + std::ostringstream oss; + oss << "MEDCouplingRemapper::transferUnderground : in given source field the number of tuples required is " << _src_ft->getNumberOfTuplesExpected() << " (on prepare) and number of tuples in given source field is " << srcField->getNumberOfTuplesExpected(); + oss << " ! It appears that the source support is not the same between the prepare and the transfer !"; + throw INTERP_KERNEL::Exception(oss.str().c_str()); + } + DataArrayDouble *array(targetField->getArray()); + int srcNbOfCompo(srcField->getNumberOfComponents()); + if(array) + { + targetField->checkCoherency(); + if(srcNbOfCompo!=targetField->getNumberOfComponents()) + throw INTERP_KERNEL::Exception("Number of components mismatch !"); + } + else + { + if(!isDftVal) + throw INTERP_KERNEL::Exception("MEDCouplingRemapper::partialTransfer : This method requires that the array of target field exists ! Allocate it or call MEDCouplingRemapper::transfer instead !"); + MEDCouplingAutoRefCountObjectPtr tmp(DataArrayDouble::New()); + tmp->alloc(targetField->getNumberOfTuples(),srcNbOfCompo); + targetField->setArray(tmp); + } + computeDeno(srcField->getNature(),srcField,targetField); + double *resPointer(targetField->getArray()->getPointer()); + const double *inputPointer(srcField->getArray()->getConstPointer()); + computeProduct(inputPointer,srcNbOfCompo,isDftVal,dftValue,resPointer); +} + +void MEDCouplingRemapper::computeDeno(NatureOfField nat, const MEDCouplingFieldDouble *srcField, const MEDCouplingFieldDouble *trgField) +{ + if(nat==NoNature) + return computeDenoFromScratch(nat,srcField,trgField); + else if(nat!=_nature_of_deno) + return computeDenoFromScratch(nat,srcField,trgField); + else if(nat==_nature_of_deno && _time_deno_update!=getTimeOfThis()) + return computeDenoFromScratch(nat,srcField,trgField); +} + +void MEDCouplingRemapper::computeDenoFromScratch(NatureOfField nat, const MEDCouplingFieldDouble *srcField, const MEDCouplingFieldDouble *trgField) +{ + _nature_of_deno=nat; + _time_deno_update=getTimeOfThis(); + switch(_nature_of_deno) + { + case ConservativeVolumic: + { + ComputeRowSumAndColSum(_matrix,_deno_multiply,_deno_reverse_multiply); + break; + } + case Integral: + { + MEDCouplingFieldDouble *deno=srcField->getDiscretization()->getMeasureField(srcField->getMesh(),getMeasureAbsStatus()); + MEDCouplingFieldDouble *denoR=trgField->getDiscretization()->getMeasureField(trgField->getMesh(),getMeasureAbsStatus()); + const double *denoPtr=deno->getArray()->getConstPointer(); + const double *denoRPtr=denoR->getArray()->getConstPointer(); + if(trgField->getMesh()->getMeshDimension()==-1) + { + double *denoRPtr2=denoR->getArray()->getPointer(); + denoRPtr2[0]=std::accumulate(denoPtr,denoPtr+deno->getNumberOfTuples(),0.); + } + if(srcField->getMesh()->getMeshDimension()==-1) + { + double *denoPtr2=deno->getArray()->getPointer(); + denoPtr2[0]=std::accumulate(denoRPtr,denoRPtr+denoR->getNumberOfTuples(),0.); + } + int idx=0; + for(std::vector >::const_iterator iter1=_matrix.begin();iter1!=_matrix.end();iter1++,idx++) + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + { + _deno_multiply[idx][(*iter2).first]=denoPtr[(*iter2).first]; + _deno_reverse_multiply[(*iter2).first][idx]=denoRPtr[idx]; + } + deno->decrRef(); + denoR->decrRef(); + break; + } + case IntegralGlobConstraint: + { + ComputeColSumAndRowSum(_matrix,_deno_multiply,_deno_reverse_multiply); + break; + } + case RevIntegral: + { + MEDCouplingFieldDouble *deno=trgField->getDiscretization()->getMeasureField(trgField->getMesh(),getMeasureAbsStatus()); + MEDCouplingFieldDouble *denoR=srcField->getDiscretization()->getMeasureField(srcField->getMesh(),getMeasureAbsStatus()); + const double *denoPtr=deno->getArray()->getConstPointer(); + const double *denoRPtr=denoR->getArray()->getConstPointer(); + if(trgField->getMesh()->getMeshDimension()==-1) + { + double *denoRPtr2=denoR->getArray()->getPointer(); + denoRPtr2[0]=std::accumulate(denoPtr,denoPtr+deno->getNumberOfTuples(),0.); + } + if(srcField->getMesh()->getMeshDimension()==-1) + { + double *denoPtr2=deno->getArray()->getPointer(); + denoPtr2[0]=std::accumulate(denoRPtr,denoRPtr+denoR->getNumberOfTuples(),0.); + } + int idx=0; + for(std::vector >::const_iterator iter1=_matrix.begin();iter1!=_matrix.end();iter1++,idx++) + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + { + _deno_multiply[idx][(*iter2).first]=denoPtr[idx]; + _deno_reverse_multiply[(*iter2).first][idx]=denoRPtr[(*iter2).first]; + } + deno->decrRef(); + denoR->decrRef(); + break; + } + case NoNature: + throw INTERP_KERNEL::Exception("No nature specified ! Select one !"); + } +} + +void MEDCouplingRemapper::computeProduct(const double *inputPointer, int inputNbOfCompo, bool isDftVal, double dftValue, double *resPointer) +{ + int idx=0; + double *tmp=new double[inputNbOfCompo]; + for(std::vector >::const_iterator iter1=_matrix.begin();iter1!=_matrix.end();iter1++,idx++) + { + if((*iter1).empty()) + { + if(isDftVal) + std::fill(resPointer+idx*inputNbOfCompo,resPointer+(idx+1)*inputNbOfCompo,dftValue); + continue; + } + else + std::fill(resPointer+idx*inputNbOfCompo,resPointer+(idx+1)*inputNbOfCompo,0.); + std::map::const_iterator iter3=_deno_multiply[idx].begin(); + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++,iter3++) + { + std::transform(inputPointer+(*iter2).first*inputNbOfCompo,inputPointer+((*iter2).first+1)*inputNbOfCompo,tmp,std::bind2nd(std::multiplies(),(*iter2).second/(*iter3).second)); + std::transform(tmp,tmp+inputNbOfCompo,resPointer+idx*inputNbOfCompo,resPointer+idx*inputNbOfCompo,std::plus()); + } + } + delete [] tmp; +} + +void MEDCouplingRemapper::computeReverseProduct(const double *inputPointer, int inputNbOfCompo, double dftValue, double *resPointer) +{ + std::vector isReached(_deno_reverse_multiply.size(),false); + int idx=0; + double *tmp=new double[inputNbOfCompo]; + std::fill(resPointer,resPointer+inputNbOfCompo*_deno_reverse_multiply.size(),0.); + for(std::vector >::const_iterator iter1=_matrix.begin();iter1!=_matrix.end();iter1++,idx++) + { + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + { + isReached[(*iter2).first]=true; + std::transform(inputPointer+idx*inputNbOfCompo,inputPointer+(idx+1)*inputNbOfCompo,tmp,std::bind2nd(std::multiplies(),(*iter2).second/_deno_reverse_multiply[(*iter2).first][idx])); + std::transform(tmp,tmp+inputNbOfCompo,resPointer+((*iter2).first)*inputNbOfCompo,resPointer+((*iter2).first)*inputNbOfCompo,std::plus()); + } + } + delete [] tmp; + idx=0; + for(std::vector::const_iterator iter3=isReached.begin();iter3!=isReached.end();iter3++,idx++) + if(!*iter3) + std::fill(resPointer+idx*inputNbOfCompo,resPointer+(idx+1)*inputNbOfCompo,dftValue); +} + +void MEDCouplingRemapper::ReverseMatrix(const std::vector >& matIn, int nbColsMatIn, std::vector >& matOut) +{ + matOut.resize(nbColsMatIn); + int id=0; + for(std::vector >::const_iterator iter1=matIn.begin();iter1!=matIn.end();iter1++,id++) + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + matOut[(*iter2).first][id]=(*iter2).second; +} + +void MEDCouplingRemapper::ComputeRowSumAndColSum(const std::vector >& matrixDeno, + std::vector >& deno, std::vector >& denoReverse) +{ + std::map values; + int idx=0; + for(std::vector >::const_iterator iter1=matrixDeno.begin();iter1!=matrixDeno.end();iter1++,idx++) + { + double sum=0.; + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + { + sum+=(*iter2).second; + values[(*iter2).first]+=(*iter2).second; + } + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + deno[idx][(*iter2).first]=sum; + } + idx=0; + for(std::vector >::const_iterator iter1=matrixDeno.begin();iter1!=matrixDeno.end();iter1++,idx++) + { + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + denoReverse[(*iter2).first][idx]=values[(*iter2).first]; + } +} + +void MEDCouplingRemapper::ComputeColSumAndRowSum(const std::vector >& matrixDeno, + std::vector >& deno, std::vector >& denoReverse) +{ + std::map values; + int idx=0; + for(std::vector >::const_iterator iter1=matrixDeno.begin();iter1!=matrixDeno.end();iter1++,idx++) + { + double sum=0.; + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + { + sum+=(*iter2).second; + values[(*iter2).first]+=(*iter2).second; + } + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + denoReverse[(*iter2).first][idx]=sum; + } + idx=0; + for(std::vector >::const_iterator iter1=matrixDeno.begin();iter1!=matrixDeno.end();iter1++,idx++) + { + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + deno[idx][(*iter2).first]=values[(*iter2).first]; + } +} + +void MEDCouplingRemapper::buildFinalInterpolationMatrixByConvolution(const std::vector< std::map >& m1D, + const std::vector< std::map >& m2D, + const int *corrCellIdSrc, int nbOf2DCellsSrc, int nbOf1DCellsSrc, + const int *corrCellIdTrg) +{ + int nbOf2DCellsTrg=m2D.size(); + int nbOf1DCellsTrg=m1D.size(); + int nbOf3DCellsTrg=nbOf2DCellsTrg*nbOf1DCellsTrg; + _matrix.resize(nbOf3DCellsTrg); + int id2R=0; + for(std::vector< std::map >::const_iterator iter2R=m2D.begin();iter2R!=m2D.end();iter2R++,id2R++) + { + for(std::map::const_iterator iter2C=(*iter2R).begin();iter2C!=(*iter2R).end();iter2C++) + { + int id1R=0; + for(std::vector< std::map >::const_iterator iter1R=m1D.begin();iter1R!=m1D.end();iter1R++,id1R++) + { + for(std::map::const_iterator iter1C=(*iter1R).begin();iter1C!=(*iter1R).end();iter1C++) + { + _matrix[corrCellIdTrg[id1R*nbOf2DCellsTrg+id2R]][corrCellIdSrc[(*iter1C).first*nbOf2DCellsSrc+(*iter2C).first]]=(*iter1C).second*((*iter2C).second); + } + } + } + } +} + +void MEDCouplingRemapper::PrintMatrix(const std::vector >& m) +{ + int id=0; + for(std::vector >::const_iterator iter1=m.begin();iter1!=m.end();iter1++,id++) + { + std::cout << "Target Cell # " << id << " : "; + for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + std::cout << "(" << (*iter2).first << "," << (*iter2).second << "), "; + std::cout << std::endl; + } +} + +const std::vector >& MEDCouplingRemapper::getCrudeMatrix() const +{ + return _matrix; +} + +/*! + * Returns the number of columns of matrix returned by MEDCouplingRemapper::getCrudeMatrix method. + */ +int MEDCouplingRemapper::getNumberOfColsOfMatrix() const +{ + return (int)_deno_reverse_multiply.size(); +} + +/*! + * This method is supposed to be called , if needed, right after MEDCouplingRemapper::prepare or MEDCouplingRemapper::prepareEx. + * If not the behaviour is unpredictable. + * This method works on precomputed \a this->_matrix. All coefficients in the matrix is lower than \a maxValAbs this coefficient is + * set to 0. That is to say that its entry disappear from the map storing the corresponding row in the data storage of sparse crude matrix. + * This method is useful to correct at a high level some problems linked to precision. Indeed, with some \ref NatureOfField "natures of field" some threshold effect + * can occur. + * + * \param [in] maxValAbs is a limit behind which a coefficient is set to 0. \a maxValAbs is expected to be positive, if not this method do nothing. + * \return a positive value that tells the number of coefficients put to 0. The 0 returned value means that the matrix has remained unchanged. + * \sa MEDCouplingRemapper::nullifiedTinyCoeffInCrudeMatrix + */ +int MEDCouplingRemapper::nullifiedTinyCoeffInCrudeMatrixAbs(double maxValAbs) +{ + int ret=0; + std::vector > matrixNew(_matrix.size()); + int i=0; + for(std::vector >::const_iterator it1=_matrix.begin();it1!=_matrix.end();it1++,i++) + { + std::map& rowNew=matrixNew[i]; + for(std::map::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + { + if(fabs((*it2).second)>maxValAbs) + rowNew[(*it2).first]=(*it2).second; + else + ret++; + } + } + if(ret>0) + _matrix=matrixNew; + return ret; +} + +/*! + * This method is supposed to be called , if needed, right after MEDCouplingRemapper::prepare or MEDCouplingRemapper::prepareEx. + * If not the behaviour is unpredictable. + * This method works on precomputed \a this->_matrix. All coefficients in the matrix is lower than delta multiplied by \a scaleFactor this coefficient is + * set to 0. That is to say that its entry disappear from the map storing the corresponding row in the data storage of sparse crude matrix. + * delta is the value returned by MEDCouplingRemapper::getMaxValueInCrudeMatrix method. + * This method is useful to correct at a high level some problems linked to precision. Indeed, with some \ref NatureOfField "natures of field" some threshold effect + * can occur. + * + * \param [in] scaleFactor is the scale factor from which coefficients lower than \a scaleFactor times range width of coefficients are set to zero. + * \return a positive value that tells the number of coefficients put to 0. The 0 returned value means that the matrix has remained unchanged. If -1 is returned it means + * that all coefficients are null. + * \sa MEDCouplingRemapper::nullifiedTinyCoeffInCrudeMatrixAbs + */ +int MEDCouplingRemapper::nullifiedTinyCoeffInCrudeMatrix(double scaleFactor) +{ + double maxVal=getMaxValueInCrudeMatrix(); + if(maxVal==0.) + return -1; + return nullifiedTinyCoeffInCrudeMatrixAbs(scaleFactor*maxVal); +} + +/*! + * This method is supposed to be called , if needed, right after MEDCouplingRemapper::prepare or MEDCouplingRemapper::prepareEx. + * If not the behaviour is unpredictable. + * This method returns the maximum of the absolute values of coefficients into the sparse crude matrix. + * The returned value is positive. + */ +double MEDCouplingRemapper::getMaxValueInCrudeMatrix() const +{ + double ret=0.; + for(std::vector >::const_iterator it1=_matrix.begin();it1!=_matrix.end();it1++) + for(std::map::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + if(fabs((*it2).second)>ret) + ret=fabs((*it2).second); + return ret; +} diff --cc medtool/src/ParaMEDMEM/ElementLocator.cxx index 74e27545a,000000000..1374387ee mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEM/ElementLocator.cxx +++ b/medtool/src/ParaMEDMEM/ElementLocator.cxx @@@ -1,720 -1,0 +1,720 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include +#include "CommInterface.hxx" +#include "ElementLocator.hxx" +#include "Topology.hxx" +#include "BlockTopology.hxx" +#include "ParaFIELD.hxx" +#include "ParaMESH.hxx" +#include "ProcessorGroup.hxx" +#include "MPIProcessorGroup.hxx" +#include "MEDCouplingFieldDouble.hxx" +#include "MEDCouplingAutoRefCountObjectPtr.hxx" +#include "DirectedBoundingBox.hxx" + +#include +#include +#include + +using namespace std; + +//#define USE_DIRECTED_BB + +namespace ParaMEDMEM +{ + ElementLocator::ElementLocator(const ParaFIELD& sourceField, + const ProcessorGroup& distant_group, + const ProcessorGroup& local_group) + : _local_para_field(sourceField), + _local_cell_mesh(sourceField.getSupport()->getCellMesh()), + _local_face_mesh(sourceField.getSupport()->getFaceMesh()), + _distant_group(distant_group), + _local_group(local_group) + { + _union_group = _local_group.fuse(distant_group); + _computeBoundingBoxes(); + _comm=getCommunicator(); + } + + ElementLocator::~ElementLocator() + { + delete _union_group; + delete [] _domain_bounding_boxes; + } + + const MPI_Comm *ElementLocator::getCommunicator() const + { + MPIProcessorGroup* group=static_cast (_union_group); + return group->getComm(); + } + + NatureOfField ElementLocator::getLocalNature() const + { + return _local_para_field.getField()->getNature(); + } + + + /*! Procedure for exchanging a mesh between a distant proc and a local processor + \param idistantrank proc id on distant group + \param distant_mesh on return , points to a local reconstruction of + the distant mesh + \param distant_ids on return, contains a vector defining a correspondence + between the distant ids and the ids of the local reconstruction + */ + void ElementLocator::exchangeMesh(int idistantrank, + MEDCouplingPointSet*& distant_mesh, + int*& distant_ids) + { + int rank = _union_group->translateRank(&_distant_group,idistantrank); + + if (find(_distant_proc_ids.begin(), _distant_proc_ids.end(),rank)==_distant_proc_ids.end()) + return; + + MEDCouplingAutoRefCountObjectPtr elems; +#ifdef USE_DIRECTED_BB + INTERP_KERNEL::DirectedBoundingBox dbb; + double* distant_bb = _domain_bounding_boxes+rank*dbb.dataSize(_local_cell_mesh_space_dim); + dbb.setData(distant_bb); + elems=_local_cell_mesh->getCellsInBoundingBox(dbb,getBoundingBoxAdjustment()); +#else + double* distant_bb = _domain_bounding_boxes+rank*2*_local_cell_mesh_space_dim; + elems=_local_cell_mesh->getCellsInBoundingBox(distant_bb,getBoundingBoxAdjustment()); +#endif + + DataArrayInt *distant_ids_send; + MEDCouplingPointSet *send_mesh = (MEDCouplingPointSet *)_local_para_field.getField()->buildSubMeshData(elems->begin(),elems->end(),distant_ids_send); + _exchangeMesh(send_mesh, distant_mesh, idistantrank, distant_ids_send, distant_ids); + distant_ids_send->decrRef(); + + if(send_mesh) + send_mesh->decrRef(); + } + + void ElementLocator::exchangeMethod(const std::string& sourceMeth, int idistantrank, std::string& targetMeth) + { + CommInterface comm_interface=_union_group->getCommInterface(); + MPIProcessorGroup* group=static_cast (_union_group); + const MPI_Comm* comm=(group->getComm()); + MPI_Status status; + // it must be converted to union numbering before communication + int idistRankInUnion = group->translateRank(&_distant_group,idistantrank); + char *recv_buffer=new char[4]; + std::vector send_buffer(4); + std::copy(sourceMeth.begin(),sourceMeth.end(),send_buffer.begin()); + comm_interface.sendRecv(&send_buffer[0], 4, MPI_CHAR,idistRankInUnion, 1112, + recv_buffer, 4, MPI_CHAR,idistRankInUnion, 1112, + *comm, &status); + targetMeth=recv_buffer; + delete [] recv_buffer; + } + + + + /*! + Compute bounding boxes + */ + void ElementLocator::_computeBoundingBoxes() + { + CommInterface comm_interface =_union_group->getCommInterface(); + MPIProcessorGroup* group=static_cast (_union_group); + const MPI_Comm* comm = group->getComm(); + _local_cell_mesh_space_dim = -1; + if(_local_cell_mesh->getMeshDimension() != -1) + _local_cell_mesh_space_dim=_local_cell_mesh->getSpaceDimension(); + int *spaceDimForAll=new int[_union_group->size()]; + comm_interface.allGather(&_local_cell_mesh_space_dim, 1, MPI_INT, + spaceDimForAll,1, MPI_INT, + *comm); + _local_cell_mesh_space_dim=*std::max_element(spaceDimForAll,spaceDimForAll+_union_group->size()); + _is_m1d_corr=((*std::min_element(spaceDimForAll,spaceDimForAll+_union_group->size()))==-1); + for(int i=0;i<_union_group->size();i++) + if(spaceDimForAll[i]!=_local_cell_mesh_space_dim && spaceDimForAll[i]!=-1) + throw INTERP_KERNEL::Exception("Spacedim not matches !"); + delete [] spaceDimForAll; +#ifdef USE_DIRECTED_BB + INTERP_KERNEL::DirectedBoundingBox dbb; + int bbSize = dbb.dataSize(_local_cell_mesh_space_dim); + _domain_bounding_boxes = new double[bbSize*_union_group->size()]; + if(_local_cell_mesh->getMeshDimension() != -1) + dbb = INTERP_KERNEL::DirectedBoundingBox(_local_cell_mesh->getCoords()->getPointer(), + _local_cell_mesh->getNumberOfNodes(), + _local_cell_mesh_space_dim); + std::vector dbbData = dbb.getData(); + if ( dbbData.size() < bbSize ) dbbData.resize(bbSize,0); + double * minmax= &dbbData[0]; +#else + int bbSize = 2*_local_cell_mesh_space_dim; + _domain_bounding_boxes = new double[bbSize*_union_group->size()]; + double * minmax=new double [bbSize]; + if(_local_cell_mesh->getMeshDimension() != -1) + _local_cell_mesh->getBoundingBox(minmax); + else + for(int i=0;i<_local_cell_mesh_space_dim;i++) + { + minmax[i*2]=-std::numeric_limits::max(); + minmax[i*2+1]=std::numeric_limits::max(); + } +#endif + + comm_interface.allGather(minmax, bbSize, MPI_DOUBLE, + _domain_bounding_boxes,bbSize, MPI_DOUBLE, + *comm); + + for (int i=0; i< _distant_group.size(); i++) + { + int rank=_union_group->translateRank(&_distant_group,i); + + if (_intersectsBoundingBox(rank)) + { + _distant_proc_ids.push_back(rank); + } + } +#ifdef USE_DIRECTED_BB +#else + delete [] minmax; +#endif + } + + + + /*! + * Intersect local bounding box with a given distant bounding box on "irank" + */ + bool ElementLocator::_intersectsBoundingBox(int irank) + { +#ifdef USE_DIRECTED_BB + INTERP_KERNEL::DirectedBoundingBox local_dbb, distant_dbb; + local_dbb.setData( _domain_bounding_boxes+_union_group->myRank()*local_dbb.dataSize( _local_cell_mesh_space_dim )); + distant_dbb.setData( _domain_bounding_boxes+irank*distant_dbb.dataSize( _local_cell_mesh_space_dim )); + return !local_dbb.isDisjointWith( distant_dbb ); +#else + double* local_bb = _domain_bounding_boxes+_union_group->myRank()*2*_local_cell_mesh_space_dim; + double* distant_bb = _domain_bounding_boxes+irank*2*_local_cell_mesh_space_dim; + ++ const double eps = 1e-12; + for (int idim=0; idim < _local_cell_mesh_space_dim; idim++) + { - const double eps = 1e-12; + bool intersects = (distant_bb[idim*2]getCommInterface(); + + // First stage : exchanging sizes + // ------------------------------ + vector tinyInfoLocalD,tinyInfoDistantD(1);//not used for the moment + vector tinyInfoLocal,tinyInfoDistant; + vector tinyInfoLocalS; + //Getting tiny info of local mesh to allow the distant proc to initialize and allocate + //the transmitted mesh. + local_mesh->getTinySerializationInformation(tinyInfoLocalD,tinyInfoLocal,tinyInfoLocalS); + tinyInfoLocal.push_back(distant_ids_send->getNumberOfTuples()); + tinyInfoDistant.resize(tinyInfoLocal.size()); + std::fill(tinyInfoDistant.begin(),tinyInfoDistant.end(),0); + MPIProcessorGroup* group=static_cast (_union_group); + const MPI_Comm* comm=group->getComm(); + MPI_Status status; + + // iproc_distant is the number of proc in distant group + // it must be converted to union numbering before communication + int iprocdistant_in_union = group->translateRank(&_distant_group, + iproc_distant); + + comm_interface.sendRecv(&tinyInfoLocal[0], tinyInfoLocal.size(), MPI_INT, iprocdistant_in_union, 1112, + &tinyInfoDistant[0], tinyInfoDistant.size(), MPI_INT,iprocdistant_in_union,1112, + *comm, &status); + DataArrayInt *v1Local=0; + DataArrayDouble *v2Local=0; + DataArrayInt *v1Distant=DataArrayInt::New(); + DataArrayDouble *v2Distant=DataArrayDouble::New(); + //serialization of local mesh to send data to distant proc. + local_mesh->serialize(v1Local,v2Local); + //Building the right instance of copy of distant mesh. + MEDCouplingPointSet *distant_mesh_tmp=MEDCouplingPointSet::BuildInstanceFromMeshType((MEDCouplingMeshType)tinyInfoDistant[0]); + std::vector unusedTinyDistantSts; + distant_mesh_tmp->resizeForUnserialization(tinyInfoDistant,v1Distant,v2Distant,unusedTinyDistantSts); + int nbLocalElems=0; + int nbDistElem=0; + int *ptLocal=0; + int *ptDist=0; + if(v1Local) + { + nbLocalElems=v1Local->getNbOfElems(); + ptLocal=v1Local->getPointer(); + } + if(v1Distant) + { + nbDistElem=v1Distant->getNbOfElems(); + ptDist=v1Distant->getPointer(); + } + comm_interface.sendRecv(ptLocal, nbLocalElems, MPI_INT, + iprocdistant_in_union, 1111, + ptDist, nbDistElem, MPI_INT, + iprocdistant_in_union,1111, + *comm, &status); + nbLocalElems=0; + double *ptLocal2=0; + double *ptDist2=0; + if(v2Local) + { + nbLocalElems=v2Local->getNbOfElems(); + ptLocal2=v2Local->getPointer(); + } + nbDistElem=0; + if(v2Distant) + { + nbDistElem=v2Distant->getNbOfElems(); + ptDist2=v2Distant->getPointer(); + } + comm_interface.sendRecv(ptLocal2, nbLocalElems, MPI_DOUBLE, + iprocdistant_in_union, 1112, + ptDist2, nbDistElem, MPI_DOUBLE, + iprocdistant_in_union, 1112, + *comm, &status); + // + distant_mesh=distant_mesh_tmp; + //finish unserialization + distant_mesh->unserialization(tinyInfoDistantD,tinyInfoDistant,v1Distant,v2Distant,unusedTinyDistantSts); + // + distant_ids_recv=new int[tinyInfoDistant.back()]; + comm_interface.sendRecv(const_cast(reinterpret_cast(distant_ids_send->getConstPointer())),tinyInfoLocal.back(), MPI_INT, + iprocdistant_in_union, 1113, + distant_ids_recv,tinyInfoDistant.back(), MPI_INT, + iprocdistant_in_union,1113, + *comm, &status); + if(v1Local) + v1Local->decrRef(); + if(v2Local) + v2Local->decrRef(); + if(v1Distant) + v1Distant->decrRef(); + if(v2Distant) + v2Distant->decrRef(); + } + + /*! + * connected with ElementLocator::sendPolicyToWorkingSideL + */ + void ElementLocator::recvPolicyFromLazySideW(std::vector& policy) + { + policy.resize(_distant_proc_ids.size()); + int procId=0; + CommInterface comm; + MPI_Status status; + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + int toRecv; + comm.recv((void *)&toRecv,1,MPI_INT,*iter,1120,*_comm,&status); + policy[procId]=toRecv; + } + } + + /*! + * connected with ElementLocator::recvFromWorkingSideL + */ + void ElementLocator::sendSumToLazySideW(const std::vector< std::vector >& distantLocEltIds, const std::vector< std::vector >& partialSumRelToDistantIds) + { + int procId=0; + CommInterface comm; + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + const vector& eltIds=distantLocEltIds[procId]; + const vector& valued=partialSumRelToDistantIds[procId]; + int lgth=eltIds.size(); + comm.send(&lgth,1,MPI_INT,*iter,1114,*_comm); + comm.send(const_cast(reinterpret_cast(&eltIds[0])),lgth,MPI_INT,*iter,1115,*_comm); + comm.send(const_cast(reinterpret_cast(&valued[0])),lgth,MPI_DOUBLE,*iter,1116,*_comm); + } + } + + /*! + * connected with ElementLocator::sendToWorkingSideL + */ + void ElementLocator::recvSumFromLazySideW(std::vector< std::vector >& globalSumRelToDistantIds) + { + int procId=0; + CommInterface comm; + MPI_Status status; + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + std::vector& vec=globalSumRelToDistantIds[procId]; + comm.recv(&vec[0],vec.size(),MPI_DOUBLE,*iter,1117,*_comm,&status); + } + } + + /*! + * connected with ElementLocator::recvLocalIdsFromWorkingSideL + */ + void ElementLocator::sendLocalIdsToLazyProcsW(const std::vector< std::vector >& distantLocEltIds) + { + int procId=0; + CommInterface comm; + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + const vector& eltIds=distantLocEltIds[procId]; + int lgth=eltIds.size(); + comm.send(&lgth,1,MPI_INT,*iter,1121,*_comm); + comm.send(const_cast(reinterpret_cast(&eltIds[0])),lgth,MPI_INT,*iter,1122,*_comm); + } + } + + /*! + * connected with ElementLocator::sendGlobalIdsToWorkingSideL + */ + void ElementLocator::recvGlobalIdsFromLazyProcsW(const std::vector< std::vector >& distantLocEltIds, std::vector< std::vector >& globalIds) + { + int procId=0; + CommInterface comm; + MPI_Status status; + globalIds.resize(_distant_proc_ids.size()); + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + const std::vector& vec=distantLocEltIds[procId]; + std::vector& global=globalIds[procId]; + global.resize(vec.size()); + comm.recv(&global[0],vec.size(),MPI_INT,*iter,1123,*_comm,&status); + } + } + + /*! + * connected with ElementLocator::sendCandidatesGlobalIdsToWorkingSideL + */ + void ElementLocator::recvCandidatesGlobalIdsFromLazyProcsW(std::vector< std::vector >& globalIds) + { + int procId=0; + CommInterface comm; + MPI_Status status; + globalIds.resize(_distant_proc_ids.size()); + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + std::vector& global=globalIds[procId]; + int lgth; + comm.recv(&lgth,1,MPI_INT,*iter,1132,*_comm,&status); + global.resize(lgth); + comm.recv(&global[0],lgth,MPI_INT,*iter,1133,*_comm,&status); + } + } + + /*! + * connected with ElementLocator::recvSumFromWorkingSideL + */ + void ElementLocator::sendPartialSumToLazyProcsW(const std::vector& distantGlobIds, const std::vector& sum) + { + int procId=0; + CommInterface comm; + int lgth=distantGlobIds.size(); + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + comm.send(&lgth,1,MPI_INT,*iter,1124,*_comm); + comm.send(const_cast(reinterpret_cast(&distantGlobIds[0])),lgth,MPI_INT,*iter,1125,*_comm); + comm.send(const_cast(reinterpret_cast(&sum[0])),lgth,MPI_DOUBLE,*iter,1126,*_comm); + } + } + + /*! + * connected with ElementLocator::recvCandidatesForAddElementsL + */ + void ElementLocator::sendCandidatesForAddElementsW(const std::vector& distantGlobIds) + { + int procId=0; + CommInterface comm; + int lgth=distantGlobIds.size(); + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + comm.send(const_cast(reinterpret_cast(&lgth)),1,MPI_INT,*iter,1128,*_comm); + comm.send(const_cast(reinterpret_cast(&distantGlobIds[0])),lgth,MPI_INT,*iter,1129,*_comm); + } + } + + /*! + * connected with ElementLocator::sendAddElementsToWorkingSideL + */ + void ElementLocator::recvAddElementsFromLazyProcsW(std::vector >& elementsToAdd) + { + int procId=0; + CommInterface comm; + MPI_Status status; + int lgth=_distant_proc_ids.size(); + elementsToAdd.resize(lgth); + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + int locLgth; + std::vector& eltToFeed=elementsToAdd[procId]; + comm.recv(&locLgth,1,MPI_INT,*iter,1130,*_comm,&status); + eltToFeed.resize(locLgth); + comm.recv(&eltToFeed[0],locLgth,MPI_INT,*iter,1131,*_comm,&status); + } + } + + /*! + * connected with ElementLocator::recvPolicyFromLazySideW + */ + int ElementLocator::sendPolicyToWorkingSideL() + { + CommInterface comm; + int toSend; + DataArrayInt *isCumulative=_local_para_field.returnCumulativeGlobalNumbering(); + if(isCumulative) + { + toSend=CUMULATIVE_POLICY; + isCumulative->decrRef(); + } + else + toSend=NO_POST_TREATMENT_POLICY; + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++) + comm.send(&toSend,1,MPI_INT,*iter,1120,*_comm); + return toSend; + } + + /*! + * connected with ElementLocator::sendSumToLazySideW + */ + void ElementLocator::recvFromWorkingSideL() + { + _values_added.resize(_local_para_field.getField()->getNumberOfTuples()); + int procId=0; + CommInterface comm; + _ids_per_working_proc.resize(_distant_proc_ids.size()); + MPI_Status status; + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + int lgth; + comm.recv(&lgth,1,MPI_INT,*iter,1114,*_comm,&status); + vector& ids=_ids_per_working_proc[procId]; + ids.resize(lgth); + vector values(lgth); + comm.recv(&ids[0],lgth,MPI_INT,*iter,1115,*_comm,&status); + comm.recv(&values[0],lgth,MPI_DOUBLE,*iter,1116,*_comm,&status); + for(int i=0;i::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + vector& ids=_ids_per_working_proc[procId]; + vector valsToSend(ids.size()); + vector::iterator iter3=valsToSend.begin(); + for(vector::const_iterator iter2=ids.begin();iter2!=ids.end();iter2++,iter3++) + *iter3=_values_added[*iter2]; + comm.send(&valsToSend[0],ids.size(),MPI_DOUBLE,*iter,1117,*_comm); + //ids.clear(); + } + //_ids_per_working_proc.clear(); + } + + /*! + * connected with ElementLocator::sendLocalIdsToLazyProcsW + */ + void ElementLocator::recvLocalIdsFromWorkingSideL() + { + int procId=0; + CommInterface comm; + _ids_per_working_proc.resize(_distant_proc_ids.size()); + MPI_Status status; + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + int lgth; + vector& ids=_ids_per_working_proc[procId]; + comm.recv(&lgth,1,MPI_INT,*iter,1121,*_comm,&status); + ids.resize(lgth); + comm.recv(&ids[0],lgth,MPI_INT,*iter,1122,*_comm,&status); + } + } + + /*! + * connected with ElementLocator::recvGlobalIdsFromLazyProcsW + */ + void ElementLocator::sendGlobalIdsToWorkingSideL() + { + int procId=0; + CommInterface comm; + DataArrayInt *globalIds=_local_para_field.returnGlobalNumbering(); + const int *globalIdsC=globalIds->getConstPointer(); + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + const vector& ids=_ids_per_working_proc[procId]; + vector valsToSend(ids.size()); + vector::iterator iter1=valsToSend.begin(); + for(vector::const_iterator iter2=ids.begin();iter2!=ids.end();iter2++,iter1++) + *iter1=globalIdsC[*iter2]; + comm.send(&valsToSend[0],ids.size(),MPI_INT,*iter,1123,*_comm); + } + if(globalIds) + globalIds->decrRef(); + } + + /*! + * connected with ElementLocator::sendPartialSumToLazyProcsW + */ + void ElementLocator::recvSumFromWorkingSideL() + { + int procId=0; + int wProcSize=_distant_proc_ids.size(); + CommInterface comm; + _ids_per_working_proc.resize(wProcSize); + _values_per_working_proc.resize(wProcSize); + MPI_Status status; + std::map sums; + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + int lgth; + comm.recv(&lgth,1,MPI_INT,*iter,1124,*_comm,&status); + vector& ids=_ids_per_working_proc[procId]; + vector& vals=_values_per_working_proc[procId]; + ids.resize(lgth); + vals.resize(lgth); + comm.recv(&ids[0],lgth,MPI_INT,*iter,1125,*_comm,&status); + comm.recv(&vals[0],lgth,MPI_DOUBLE,*iter,1126,*_comm,&status); + vector::const_iterator iter1=ids.begin(); + vector::const_iterator iter2=vals.begin(); + for(;iter1!=ids.end();iter1++,iter2++) + sums[*iter1]+=*iter2; + } + //assign sum to prepare sending to working side + for(procId=0;procId& ids=_ids_per_working_proc[procId]; + vector& vals=_values_per_working_proc[procId]; + vector::const_iterator iter1=ids.begin(); + vector::iterator iter2=vals.begin(); + for(;iter1!=ids.end();iter1++,iter2++) + *iter2=sums[*iter1]; + ids.clear(); + } + } + + /*! + * Foreach working procs Wi compute and push it in _ids_per_working_proc3, + * if it exist, local id of nodes that are in interaction with an another lazy proc than this + * and that exists in this \b but with no interaction with this. + * The computation is performed here. sendAddElementsToWorkingSideL is only in charge to send + * precomputed _ids_per_working_proc3 attribute. + * connected with ElementLocator::sendCandidatesForAddElementsW + */ + void ElementLocator::recvCandidatesForAddElementsL() + { + int procId=0; + int wProcSize=_distant_proc_ids.size(); + CommInterface comm; + _ids_per_working_proc3.resize(wProcSize); + MPI_Status status; + std::map sums; + DataArrayInt *globalIds=_local_para_field.returnGlobalNumbering(); + const int *globalIdsC=globalIds->getConstPointer(); + int nbElts=globalIds->getNumberOfTuples(); + std::set globalIdsS(globalIdsC,globalIdsC+nbElts); + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + const std::vector& ids0=_ids_per_working_proc[procId]; + int lgth0=ids0.size(); + std::set elts0; + for(int i=0;i ids(lgth); + comm.recv(&ids[0],lgth,MPI_INT,*iter,1129,*_comm,&status); + set ids1(ids.begin(),ids.end()); + ids.clear(); + set tmp5,tmp6; + set_intersection(globalIdsS.begin(),globalIdsS.end(),ids1.begin(),ids1.end(),inserter(tmp5,tmp5.begin())); + set_difference(tmp5.begin(),tmp5.end(),elts0.begin(),elts0.end(),inserter(tmp6,tmp6.begin())); + std::vector& ids2=_ids_per_working_proc3[procId]; + ids2.resize(tmp6.size()); + std::copy(tmp6.begin(),tmp6.end(),ids2.begin()); + //global->local + for(std::vector::iterator iter2=ids2.begin();iter2!=ids2.end();iter2++) + *iter2=std::find(globalIdsC,globalIdsC+nbElts,*iter2)-globalIdsC; + } + if(globalIds) + globalIds->decrRef(); + } + + /*! + * connected with ElementLocator::recvAddElementsFromLazyProcsW + */ + void ElementLocator::sendAddElementsToWorkingSideL() + { + int procId=0; + CommInterface comm; + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + const std::vector& vals=_ids_per_working_proc3[procId]; + int size=vals.size(); + comm.send(const_cast(reinterpret_cast(&size)),1,MPI_INT,*iter,1130,*_comm); + comm.send(const_cast(reinterpret_cast(&vals[0])),size,MPI_INT,*iter,1131,*_comm); + } + } + + /*! + * This method sends to working side Wi only nodes in interaction with Wi \b and located on boundary, to reduce number. + * connected with ElementLocator::recvCandidatesGlobalIdsFromLazyProcsW + */ + void ElementLocator::sendCandidatesGlobalIdsToWorkingSideL() + { + int procId=0; + CommInterface comm; + DataArrayInt *globalIds=_local_para_field.returnGlobalNumbering(); + const int *globalIdsC=globalIds->getConstPointer(); + MEDCouplingAutoRefCountObjectPtr candidates=_local_para_field.getSupport()->getCellMesh()->findBoundaryNodes(); + for(int *iter1=candidates->getPointer();iter1!=candidates->getPointer()+candidates->getNumberOfTuples();iter1++) + (*iter1)=globalIdsC[*iter1]; + std::set candidatesS(candidates->begin(),candidates->end()); + for(vector::const_iterator iter=_distant_proc_ids.begin();iter!=_distant_proc_ids.end();iter++,procId++) + { + const vector& ids=_ids_per_working_proc[procId]; + vector valsToSend(ids.size()); + vector::iterator iter1=valsToSend.begin(); + for(vector::const_iterator iter2=ids.begin();iter2!=ids.end();iter2++,iter1++) + *iter1=globalIdsC[*iter2]; + std::set tmp2(valsToSend.begin(),valsToSend.end()); + std::vector tmp3; + set_intersection(candidatesS.begin(),candidatesS.end(),tmp2.begin(),tmp2.end(),std::back_insert_iterator< std::vector >(tmp3)); + int lgth=tmp3.size(); + comm.send(&lgth,1,MPI_INT,*iter,1132,*_comm); + comm.send(&tmp3[0],lgth,MPI_INT,*iter,1133,*_comm); + } + if(globalIds) + globalIds->decrRef(); + } +} diff --cc medtool/src/ParaMEDMEM/OverlapDEC.cxx index 09253d350,000000000..af842fb9d mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEM/OverlapDEC.cxx +++ b/medtool/src/ParaMEDMEM/OverlapDEC.cxx @@@ -1,323 -1,0 +1,362 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#include "OverlapDEC.hxx" +#include "CommInterface.hxx" ++#include "ParaMESH.hxx" +#include "ParaFIELD.hxx" +#include "MPIProcessorGroup.hxx" +#include "OverlapElementLocator.hxx" +#include "OverlapInterpolationMatrix.hxx" + +namespace ParaMEDMEM +{ +/*! + \anchor OverlapDEC-det + \class OverlapDEC + + \section OverlapDEC-over Overview + + The \c OverlapDEC enables the \ref InterpKerRemapGlobal "conservative remapping" of fields between + two parallel codes. This remapping is based on the computation of intersection volumes on + a \b single \b processor \b group. On this processor group are defined two field-templates called A + and B. The computation is possible for 3D meshes, 2D meshes, 3D-surface meshes, 1D meshes and + 2D-curve meshes. Dimensions must be similar for the distribution templates A and B. + + The main difference with \ref InterpKernelDEC-det "InterpKernelDEC" is that this + \ref para-dec "DEC" works with a *single* processor group, in which processors will share the work. + Consequently each processor manages two \ref MEDCouplingFieldTemplatesPage "field templates" (A and B) + called source and target. + Furthermore all processors in the processor group cooperate in the global interpolation matrix + computation. In this respect \c InterpKernelDEC is a specialization of \c OverlapDEC. + + \section ParaMEDMEMOverlapDECAlgorithmDescription Algorithm description + + Let's consider the following use case that is ran in ParaMEDMEMTest_OverlapDEC.cxx to describes + the different steps of the computation. The processor group contains 3 processors. + \anchor ParaMEDMEMOverlapDECImgTest1 + \image html OverlapDEC1.png "Example split of the source and target mesh among the 3 procs" + - \subsection ParaMEDMEMOverlapDECAlgoStep1 Step 1 : Bounding box exchange and global interaction - between procs computation. ++ \subsection ParaMEDMEMOverlapDECAlgoStep1 Step 1 : Bounding box exchange and global interaction between procs computation. + + In order to reduce as much as possible the amount of communications between distant processors, + every processor computes a bounding box for A and B. Then a AllToAll communication is performed + so that + every processor can compute the \b global interactions between processor. + This computation leads every processor to compute the same global TODO list expressed as a list + of pair. A pair ( x, y ) means that proc \b x fieldtemplate A can interact with fieltemplate B of + proc \b y because the two bounding boxes interact. + In the \ref ParaMEDMEMOverlapDECImgTest1 "example above" this computation leads to the following + a \b global TODO list : + + \b (0,0),(0,1),(1,0),(1,2),(2,0),(2,1),(2,2) + + Here the pair (0,2) does not appear because the bounding box of fieldtemplateA of proc#2 does + not intersect that of fieldtemplate B on proc#0. + + Stage performed by ParaMEDMEM::OverlapElementLocator::computeBoundingBoxes. + + \subsection ParaMEDMEMOverlapDECAlgoStep2 Step 2 : Computation of local TODO list + + Starting from the global interaction previously computed in \ref ParaMEDMEMOverlapDECAlgoStep1 + "Step 1", each proc computes the TODO list per proc. + The following rules is chosen : a pair (x,y) can be treated by either proc \#x or proc \#y, + in order to reduce the amount of data transfert among + processors. The algorithm chosen for load balancing is the following : Each processor has + an empty \b local TODO list at the beginning. Then for each pair (k,m) in + \b global TODO list, if proc\#k has less temporary local list than proc\#m pair, (k,m) is added + to temparary local TODO list of proc\#k. + If proc\#m has less temporary local TODO list than proc\#k pair, (k,m) is added to temporary + local TODO list of proc\#m. + If proc\#k and proc\#m have the same amount of temporary local TODO list pair, (k,m) is added to + temporary local TODO list of proc\#k. + + In the \ref ParaMEDMEMOverlapDECImgTest1 "example above" this computation leads to the following + local TODO list : + + - proc\#0 : (0,0) + - proc\#1 : (0,1),(1,0) + - proc\#2 : (1,2),(2,0),(2,1),(2,2) + + The algorithm described here is not perfect for this use case, we hope to enhance it soon. + + At this stage each proc knows precisely its \b local TODO list (with regard to interpolation). + The \b local TODO list of other procs than local + is kept for future computations. + + \subsection ParaMEDMEMOverlapDECAlgoStep3 Step 3 : Matrix echange between procs + + Knowing the \b local TODO list, the aim now is to exchange field-templates between procs. + Each proc computes knowing TODO list per + proc computed in \ref ParaMEDMEMOverlapDECAlgoStep2 "Step 2" the exchange TODO list : + + In the \ref ParaMEDMEMOverlapDECImgTest1 "example above" the exchange TODO list gives the + following results : + + Sending TODO list per proc : + + - proc \#0 : Send fieldtemplate A to Proc\#1, Send fieldtemplate B to Proc\#1, Send fieldtemplate + B to Proc\#2 + - Proc \#1 : Send fieldtemplate A to Proc\#2, Send fieldtemplate B to Proc\#2 + - Proc \#2 : No send. + + Receiving TODO list per proc : + + - proc \#0 : No receiving + - proc \#1 : receiving fieldtemplate A from Proc\#0, receiving fieldtemplate B from Proc\#0 + - proc \#2 : receiving fieldtemplate B from Proc\#0, receiving fieldtemplate A from Proc\#1, + receiving fieldtemplate B from Proc\#1 + + To avoid as much as possible large volumes of transfers between procs, only relevant parts of + meshes are sent. In order for proc\#k to send fieldtemplate A to fieldtemplate B + of proc \#m., proc\#k computes the part of mesh A contained in the boundingbox B of proc\#m. It + implies that the corresponding cellIds or nodeIds of the + corresponding part are sent to proc \#m too. + + Let's consider the couple (k,m) in the TODO list. This couple is treated by either k or m as + seen in \ref ParaMEDMEMOverlapDECAlgoStep2 "here in Step2". + + As will be dealt in Step 6, for final matrix-vector computations, the resulting matrix of the + couple (k,m) whereever it is computed (proc \#k or proc \#m) + will be stored in \b proc\#m. + + - If proc \#k is in charge (performs the matrix computation) for this couple (k,m), target ids + (cells or nodes) of the mesh in proc \#m are renumbered, because proc \#m has seelected a sub mesh + of the target mesh to avoid large amounts of data to transfer. In this case as proc \#m is ultimately + in charge of the matrix, proc \#k must keep preciously the + source ids needed to be sent to proc\#m. No problem will appear for matrix assembling in proc m + for source ids because no restriction was done. + Concerning source ids to be sent for the matrix-vector computation, proc k will know precisely + which source ids field values to send to proc \#m. + This is embodied by OverlapMapping::keepTracksOfTargetIds in proc m. + + - If proc \#m is in charge (performs matrix computation) for this couple (k,m), source ids (cells + or nodes) of the mesh in proc \#k are renumbered, because proc \#k has selected a sub mesh of the + source mesh to avoid large amounts of data to transfer. In this case as proc \#k is ultimately + in charge of the matrix, proc \#m receives the source ids + from remote proc \#k, and thus the matrix is directly correct, no need for renumbering as + in \ref ParaMEDMEMOverlapDECAlgoStep5 "Step 5". However proc \#k must + keep track of the ids sent to proc \#m for te matrix-vector computation. + This is incarnated by OverlapMapping::keepTracksOfSourceIds in proc k. + + This step is performed in ParaMEDMEM::OverlapElementLocator::exchangeMeshes method. + + \subsection ParaMEDMEMOverlapDECAlgoStep4 Step 4 : Computation of the interpolation matrix + + After mesh exchange in \ref ParaMEDMEMOverlapDECAlgoStep3 "Step3" each processor has all the + required information to treat its \b local TODO list computed in + \ref ParaMEDMEMOverlapDECAlgoStep2 "Step2". This step is potentially CPU costly, which is why + the \b local TODO list per proc is expected to + be as well balanced as possible. + + The interpolation is performed as the \ref ParaMEDMEM::MEDCouplingRemapper "remapper" does. + + This operation is performed by OverlapInterpolationMatrix::addContribution method. + + \subsection ParaMEDMEMOverlapDECAlgoStep5 Step 5 : Global matrix construction. + + After having performed the TODO list at the end of \ref ParaMEDMEMOverlapDECAlgoStep4 "Step4" + we need to assemble the final matrix. + + The final aim is to have a distributed matrix \f$ M_k \f$ on each proc\#k. In order to reduce + data exchange during the matrix product process, + \f$ M_k \f$ is built using sizeof(Proc group) \c std::vector< \c std::map \c >. + + For a proc\#k, it is necessary to fetch info of all matrices built in + \ref ParaMEDMEMOverlapDECAlgoStep4 "Step4" where the first element in pair (i,j) + is equal to k. + + After this step, the matrix repartition is the following after a call to + ParaMEDMEM::OverlapMapping::prepare : + + - proc\#0 : (0,0),(1,0),(2,0) + - proc\#1 : (0,1),(2,1) + - proc\#2 : (1,2),(2,2) + + Tuple (2,1) computed on proc 2 is stored in proc 1 after execution of the function + "prepare". This is an example of item 0 in \ref ParaMEDMEMOverlapDECAlgoStep2 "Step2". + Tuple (0,1) computed on proc 1 is stored in proc 1 too. This is an example of item 1 in \ref ParaMEDMEMOverlapDECAlgoStep2 "Step2". + + In the end ParaMEDMEM::OverlapMapping::_proc_ids_to_send_vector_st will contain : + + - Proc\#0 : 0,1 + - Proc\#1 : 0,2 + - Proc\#2 : 0,1,2 + + In the end ParaMEDMEM::OverlapMapping::_proc_ids_to_recv_vector_st will contain : + + - Proc\#0 : 0,1,2 + - Proc\#1 : 0,2 + - Proc\#2 : 1,2 + + The method in charge to perform this is : ParaMEDMEM::OverlapMapping::prepare. +*/ + OverlapDEC::OverlapDEC(const std::set& procIds, const MPI_Comm& world_comm): - _own_group(true),_interpolation_matrix(0), ++ _load_balancing_algo(1), ++ _own_group(true),_interpolation_matrix(0), _locator(0), + _source_field(0),_own_source_field(false), + _target_field(0),_own_target_field(false), ++ _default_field_value(0.0), + _comm(MPI_COMM_NULL) + { + ParaMEDMEM::CommInterface comm; + int *ranks_world=new int[procIds.size()]; // ranks of sources and targets in world_comm + std::copy(procIds.begin(),procIds.end(),ranks_world); + MPI_Group group,world_group; + comm.commGroup(world_comm,&world_group); + comm.groupIncl(world_group,procIds.size(),ranks_world,&group); + delete [] ranks_world; + comm.commCreate(world_comm,group,&_comm); + comm.groupFree(&group); + comm.groupFree(&world_group); + if(_comm==MPI_COMM_NULL) + { + _group=0; + return ; + } + std::set idsUnion; + for(std::size_t i=0;imultiply(); ++ _interpolation_matrix->multiply(_default_field_value); + } + + void OverlapDEC::recvData() + { + throw INTERP_KERNEL::Exception("Not implemented yet !!!!"); + //_interpolation_matrix->transposeMultiply(); + } + + void OverlapDEC::synchronize() + { + if(!isInGroup()) + return ; ++ // Check number of components of field on both side (for now allowing void field/mesh on one proc is not allowed) ++ if (!_source_field || !_source_field->getField()) ++ throw INTERP_KERNEL::Exception("OverlapDEC::synchronize(): currently, having a void source field on a proc is not allowed!"); ++ if (!_target_field || !_target_field->getField()) ++ throw INTERP_KERNEL::Exception("OverlapDEC::synchronize(): currently, having a void target field on a proc is not allowed!"); ++ if (_target_field->getField()->getNumberOfComponents() != _source_field->getField()->getNumberOfComponents()) ++ throw INTERP_KERNEL::Exception("OverlapDEC::synchronize(): source and target field have different number of components!"); + delete _interpolation_matrix; - _interpolation_matrix=new OverlapInterpolationMatrix(_source_field,_target_field,*_group,*this,*this); - OverlapElementLocator locator(_source_field,_target_field,*_group); - locator.copyOptions(*this); - locator.exchangeMeshes(*_interpolation_matrix); - std::vector< std::pair > jobs=locator.getToDoList(); - std::string srcMeth=locator.getSourceMethod(); - std::string trgMeth=locator.getTargetMethod(); ++ _locator = new OverlapElementLocator(_source_field,_target_field,*_group, getBoundingBoxAdjustmentAbs(), _load_balancing_algo); ++ _interpolation_matrix=new OverlapInterpolationMatrix(_source_field,_target_field,*_group,*this,*this, *_locator); ++ _locator->copyOptions(*this); ++ _locator->exchangeMeshes(*_interpolation_matrix); ++ std::vector< std::pair > jobs=_locator->getToDoList(); ++ std::string srcMeth=_locator->getSourceMethod(); ++ std::string trgMeth=_locator->getTargetMethod(); + for(std::vector< std::pair >::const_iterator it=jobs.begin();it!=jobs.end();it++) + { - const MEDCouplingPointSet *src=locator.getSourceMesh((*it).first); - const DataArrayInt *srcIds=locator.getSourceIds((*it).first); - const MEDCouplingPointSet *trg=locator.getTargetMesh((*it).second); - const DataArrayInt *trgIds=locator.getTargetIds((*it).second); - _interpolation_matrix->addContribution(src,srcIds,srcMeth,(*it).first,trg,trgIds,trgMeth,(*it).second); ++ const MEDCouplingPointSet *src=_locator->getSourceMesh((*it).first); ++ const DataArrayInt *srcIds=_locator->getSourceIds((*it).first); ++ const MEDCouplingPointSet *trg=_locator->getTargetMesh((*it).second); ++ const DataArrayInt *trgIds=_locator->getTargetIds((*it).second); ++ _interpolation_matrix->computeLocalIntersection(src,srcIds,srcMeth,(*it).first,trg,trgIds,trgMeth,(*it).second); + } - _interpolation_matrix->prepare(locator.getProcsInInteraction()); - _interpolation_matrix->computeDeno(); ++ _interpolation_matrix->prepare(_locator->getProcsToSendFieldData()); ++ _interpolation_matrix->computeSurfacesAndDeno(); + } + + void OverlapDEC::attachSourceLocalField(ParaFIELD *field, bool ownPt) + { + if(!isInGroup()) + return ; + if(_own_source_field) + delete _source_field; + _source_field=field; + _own_source_field=ownPt; + } + + void OverlapDEC::attachTargetLocalField(ParaFIELD *field, bool ownPt) + { + if(!isInGroup()) + return ; + if(_own_target_field) + delete _target_field; + _target_field=field; + _own_target_field=ownPt; + } + ++ void OverlapDEC::attachSourceLocalField(MEDCouplingFieldDouble *field) ++ { ++ if(!isInGroup()) ++ return ; ++ ++ ParaMESH *paramesh = new ParaMESH(static_cast(const_cast(field->getMesh())), ++ *_group,field->getMesh()->getName()); ++ ParaFIELD *tmpField=new ParaFIELD(field, paramesh, *_group); ++ tmpField->setOwnSupport(true); ++ attachSourceLocalField(tmpField,true); ++ } ++ ++ void OverlapDEC::attachTargetLocalField(MEDCouplingFieldDouble *field) ++ { ++ if(!isInGroup()) ++ return ; ++ ++ ParaMESH *paramesh = new ParaMESH(static_cast(const_cast(field->getMesh())), ++ *_group,field->getMesh()->getName()); ++ ParaFIELD *tmpField=new ParaFIELD(field, paramesh, *_group); ++ tmpField->setOwnSupport(true); ++ attachTargetLocalField(tmpField,true); ++ } ++ + bool OverlapDEC::isInGroup() const + { + if(!_group) + return false; + return _group->containsMyRank(); + } ++ ++ void OverlapDEC::debugPrintWorkSharing(std::ostream & ostr) const ++ { ++ _locator->debugPrintWorkSharing(ostr); ++ } +} diff --cc medtool/src/ParaMEDMEM/OverlapDEC.hxx index b7b9b8c2f,000000000..2d63789b7 mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEM/OverlapDEC.hxx +++ b/medtool/src/ParaMEDMEM/OverlapDEC.hxx @@@ -1,61 -1,0 +1,76 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#ifndef __OVERLAPDEC_HXX__ +#define __OVERLAPDEC_HXX__ + +#include "DEC.hxx" +#include "InterpolationOptions.hxx" + +#include ++#include + +namespace ParaMEDMEM +{ + class OverlapInterpolationMatrix; ++ class OverlapElementLocator; + class ProcessorGroup; + class ParaFIELD; + + class OverlapDEC : public DEC, public INTERP_KERNEL::InterpolationOptions + { + public: + OverlapDEC(const std::set& procIds,const MPI_Comm& world_comm=MPI_COMM_WORLD); + virtual ~OverlapDEC(); + void sendRecvData(bool way=true); + void sendData(); + void recvData(); + void synchronize(); + void attachSourceLocalField(ParaFIELD *field, bool ownPt=false); + void attachTargetLocalField(ParaFIELD *field, bool ownPt=false); - ProcessorGroup *getGrp() { return _group; } ++ void attachSourceLocalField(MEDCouplingFieldDouble *field); ++ void attachTargetLocalField(MEDCouplingFieldDouble *field); ++ ProcessorGroup *getGroup() { return _group; } + bool isInGroup() const; ++ ++ void setDefaultValue(double val) {_default_field_value = val;} ++ //! 0 means initial algo from Antho, 1 or 2 means Adrien's algo (2 should be better). Make your choice :-)) ++ void setWorkSharingAlgo(int method) { _load_balancing_algo = method; } ++ ++ void debugPrintWorkSharing(std::ostream & ostr) const; + private: ++ int _load_balancing_algo; ++ + bool _own_group; + OverlapInterpolationMatrix* _interpolation_matrix; ++ OverlapElementLocator* _locator; + ProcessorGroup *_group; + ++ double _default_field_value; ++ + ParaFIELD *_source_field; + bool _own_source_field; + ParaFIELD *_target_field; + bool _own_target_field; + MPI_Comm _comm; + }; +} + +#endif diff --cc medtool/src/ParaMEDMEM/OverlapElementLocator.cxx index 51560e145,000000000..81cb987db mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEM/OverlapElementLocator.cxx +++ b/medtool/src/ParaMEDMEM/OverlapElementLocator.cxx @@@ -1,369 -1,0 +1,552 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#include "OverlapElementLocator.hxx" + +#include "CommInterface.hxx" +#include "Topology.hxx" +#include "BlockTopology.hxx" +#include "ParaFIELD.hxx" +#include "ParaMESH.hxx" +#include "ProcessorGroup.hxx" +#include "MPIProcessorGroup.hxx" +#include "OverlapInterpolationMatrix.hxx" +#include "MEDCouplingFieldDouble.hxx" +#include "MEDCouplingFieldDiscretization.hxx" +#include "DirectedBoundingBox.hxx" +#include "InterpKernelAutoPtr.hxx" + +#include + +using namespace std; + +namespace ParaMEDMEM +{ - OverlapElementLocator::OverlapElementLocator(const ParaFIELD *sourceField, const ParaFIELD *targetField, const ProcessorGroup& group) ++ const int OverlapElementLocator::START_TAG_MESH_XCH = 1140; ++ ++ OverlapElementLocator::OverlapElementLocator(const ParaFIELD *sourceField, const ParaFIELD *targetField, ++ const ProcessorGroup& group, double epsAbs, int workSharingAlgo) + : _local_source_field(sourceField), + _local_target_field(targetField), + _local_source_mesh(0), + _local_target_mesh(0), + _domain_bounding_boxes(0), - _group(group) ++ _group(group), ++ _epsAbs(epsAbs) + { + if(_local_source_field) + _local_source_mesh=_local_source_field->getSupport()->getCellMesh(); + if(_local_target_field) + _local_target_mesh=_local_target_field->getSupport()->getCellMesh(); + _comm=getCommunicator(); - computeBoundingBoxes(); ++ ++ computeBoundingBoxesAndInteractionList(); ++ switch(workSharingAlgo) ++ { ++ case 0: ++ computeTodoList_original(); break; ++ case 1: ++ computeTodoList_new(false); break; ++ case 2: ++ computeTodoList_new(true); break; ++ default: ++ throw INTERP_KERNEL::Exception("OverlapElementLocator::OverlapElementLocator(): invalid algorithm selected!"); ++ } ++ ++ fillProcToSend(); + } + + OverlapElementLocator::~OverlapElementLocator() + { + delete [] _domain_bounding_boxes; + } + + const MPI_Comm *OverlapElementLocator::getCommunicator() const + { + const MPIProcessorGroup* group=static_cast(&_group); + return group->getComm(); + } + - void OverlapElementLocator::computeBoundingBoxes() ++ void OverlapElementLocator::computeBoundingBoxesAndInteractionList() + { + CommInterface comm_interface=_group.getCommInterface(); + const MPIProcessorGroup* group=static_cast (&_group); + _local_space_dim=0; + if(_local_source_mesh) + _local_space_dim=_local_source_mesh->getSpaceDimension(); + else + _local_space_dim=_local_target_mesh->getSpaceDimension(); + // + const MPI_Comm* comm = group->getComm(); + int bbSize=2*2*_local_space_dim;//2 (for source/target) 2 (min/max) + _domain_bounding_boxes=new double[bbSize*_group.size()]; + INTERP_KERNEL::AutoPtr minmax=new double[bbSize]; + //Format minmax : Xmin_src,Xmax_src,Ymin_src,Ymax_src,Zmin_src,Zmax_src,Xmin_trg,Xmax_trg,Ymin_trg,Ymax_trg,Zmin_trg,Zmax_trg + if(_local_source_mesh) + _local_source_mesh->getBoundingBox(minmax); + else + { + for(int i=0;i<_local_space_dim;i++) + { + minmax[i*2]=std::numeric_limits::max(); + minmax[i*2+1]=-std::numeric_limits::max(); + } + } + if(_local_target_mesh) + _local_target_mesh->getBoundingBox(minmax+2*_local_space_dim); + else + { + for(int i=0;i<_local_space_dim;i++) + { + minmax[i*2+2*_local_space_dim]=std::numeric_limits::max(); + minmax[i*2+1+2*_local_space_dim]=-std::numeric_limits::max(); + } + } + comm_interface.allGather(minmax, bbSize, MPI_DOUBLE, + _domain_bounding_boxes,bbSize, MPI_DOUBLE, + *comm); + + // Computation of all pairs needing an interpolation pairs are duplicated now ! + + _proc_pairs.clear();//first is source second is target + _proc_pairs.resize(_group.size()); + for(int i=0;i<_group.size();i++) + for(int j=0;j<_group.size();j++) - { - if(intersectsBoundingBox(i,j)) - _proc_pairs[i].push_back(j); - } ++ if(intersectsBoundingBox(i,j)) ++ _proc_pairs[i].push_back(j); ++ } + ++ void OverlapElementLocator::computeTodoList_original() ++ { + // OK now let's assigning as balanced as possible, job to each proc of group - std::vector< std::vector< std::pair > > pairsToBeDonePerProc(_group.size()); ++ _all_todo_lists.resize(_group.size()); + int i=0; + for(std::vector< std::vector< int > >::const_iterator it1=_proc_pairs.begin();it1!=_proc_pairs.end();it1++,i++) + for(std::vector< int >::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + { - if(pairsToBeDonePerProc[i].size()<=pairsToBeDonePerProc[*it2].size())//it includes the fact that i==*it2 - pairsToBeDonePerProc[i].push_back(std::pair(i,*it2)); ++ if(_all_todo_lists[i].size()<=_all_todo_lists[*it2].size())//it includes the fact that i==*it2 ++ _all_todo_lists[i].push_back(ProcCouple(i,*it2)); + else - pairsToBeDonePerProc[*it2].push_back(std::pair(i,*it2)); ++ _all_todo_lists[*it2].push_back(ProcCouple(i,*it2)); + } + //Keeping todo list of current proc. _to_do_list contains a set of pair where at least _group.myRank() appears once. + //This proc will be in charge to perform interpolation of any of element of '_to_do_list' + //If _group.myRank()==myPair.first, current proc should fetch target mesh of myPair.second (if different from _group.myRank()). + //If _group.myRank()==myPair.second, current proc should fetch source mesh of myPair.second. - ++ + int myProcId=_group.myRank(); - _to_do_list=pairsToBeDonePerProc[myProcId]; ++ _to_do_list=_all_todo_lists[myProcId]; + - //Feeding now '_procs_to_send'. A same id can appears twice. The second parameter in pair means what to send true=source, false=target - _procs_to_send.clear(); - for(int i=_group.size()-1;i>=0;i--) - if(i!=myProcId) ++#ifdef DEC_DEBUG ++ std::stringstream scout; ++ scout << "(" << myProcId << ") my TODO list is: "; ++ for (std::vector< ProcCouple >::const_iterator itdbg=_to_do_list.begin(); itdbg!=_to_do_list.end(); itdbg++) ++ scout << "(" << (*itdbg).first << "," << (*itdbg).second << ")"; ++ std::cout << scout.str() << "\n"; ++#endif ++ } ++ ++ /* More efficient (?) work sharing algorithm: a job (i,j) is initially assigned twice: to proc#i and to proc#j. ++ * Then try to reduce as much as possible the variance of the num of jobs per proc by selecting the right duplicate ++ * to remove: ++ * - take the most loaded proc i, ++ * + select the job (i,j) for which proc#j is the less loaded ++ * + remove this job from proc#i, and mark it as 'unremovable' from proc#j ++ * - repeat until no more duplicates are found ++ */ ++ void OverlapElementLocator::computeTodoList_new(bool revertIter) ++ { ++ using namespace std; ++ int infinity = std::numeric_limits::max(); ++ // Initialisation ++ int grp_size = _group.size(); ++ vector < map > full_set(grp_size ); ++ int srcProcID = 0; ++ for(vector< vector< int > >::const_iterator it = _proc_pairs.begin(); it != _proc_pairs.end(); it++, srcProcID++) ++ for (vector< int >::const_iterator it2=(*it).begin(); it2 != (*it).end(); it2++) ++ { ++ // Here a pair of the form (i,i) is added only once! ++ int tgtProcID = *it2; ++ ProcCouple cpl = make_pair(srcProcID, tgtProcID); ++ full_set[srcProcID][cpl] = -1; ++ full_set[tgtProcID][cpl] = -1; ++ } ++ int procID = 0; ++ vector < map > ::iterator itVector; ++ map::iterator itMap; ++ for(itVector = full_set.begin(); itVector != full_set.end(); itVector++, procID++) ++ for (itMap=(*itVector).begin(); itMap != (*itVector).end(); itMap++) + { - const std::vector< std::pair >& anRemoteProcToDoList=pairsToBeDonePerProc[i]; - for(std::vector< std::pair >::const_iterator it=anRemoteProcToDoList.begin();it!=anRemoteProcToDoList.end();it++) ++ const ProcCouple & cpl = (*itMap).first; ++ if (cpl.first == cpl.second) ++ // special case - this couple can not be removed in the future ++ (*itMap).second = infinity; ++ else + { - if((*it).first==myProcId) - _procs_to_send.push_back(std::pair(i,true)); - if((*it).second==myProcId) - _procs_to_send.push_back(std::pair(i,false)); ++ if(cpl.first == procID) ++ (*itMap).second = full_set[cpl.second].size(); ++ else // cpl.second == srcProcID ++ (*itMap).second = full_set[cpl.first].size(); + } + } ++ INTERP_KERNEL::AutoPtr proc_valid = new bool[grp_size]; ++ fill((bool *)proc_valid, proc_valid+grp_size, true); ++ ++ // Now the algo: ++ while (find((bool *)proc_valid, proc_valid+grp_size, true) != proc_valid+grp_size) ++ { ++ // Most loaded proc: ++ int max_sz = -1, max_id = -1; ++ for(itVector = full_set.begin(), procID=0; itVector != full_set.end(); itVector++, procID++) ++ { ++ int sz = (*itVector).size(); ++ if (proc_valid[procID] && sz > max_sz) ++ { ++ max_sz = sz; ++ max_id = procID; ++ } ++ } ++ ++ // Nothing more to do: ++ if (max_sz == -1) ++ break; ++ // For this proc, job with less loaded second proc: ++ int min_sz = infinity; ++ map & max_map = full_set[max_id]; ++ ProcCouple hit_cpl = make_pair(-1,-1); ++ if(revertIter) ++ { ++ // Use a reverse iterator here increases our chances to hit a couple of the form (i, myProcId) ++ // meaning that the final matrix computed won't have to be sent: save some comm. ++ map ::const_reverse_iterator ritMap; ++ for(ritMap=max_map.rbegin(); ritMap != max_map.rend(); ritMap++) ++ if ((*ritMap).second < min_sz) ++ hit_cpl = (*ritMap).first; ++ } ++ else ++ { ++ for(itMap=max_map.begin(); itMap != max_map.end(); itMap++) ++ if ((*itMap).second < min_sz) ++ hit_cpl = (*itMap).first; ++ } ++ if (hit_cpl.first == -1) ++ { ++ // Plouf. Current proc 'max_id' can not be reduced. Invalid it: ++ proc_valid[max_id] = false; ++ continue; ++ } ++ // Remove item from proc 'max_id' ++ full_set[max_id].erase(hit_cpl); ++ // And mark it as not removable on the other side: ++ if (hit_cpl.first == max_id) ++ full_set[hit_cpl.second][hit_cpl] = infinity; ++ else // hit_cpl.second == max_id ++ full_set[hit_cpl.first][hit_cpl] = infinity; ++ ++ // Now update all counts of valid maps: ++ procID = 0; ++ for(itVector = full_set.begin(); itVector != full_set.end(); itVector++, procID++) ++ if(proc_valid[procID] && procID != max_id) ++ for(itMap = (*itVector).begin(); itMap != (*itVector).end(); itMap++) ++ { ++ const ProcCouple & cpl = (*itMap).first; ++ // Unremovable item: ++ if ((*itMap).second == infinity) ++ continue; ++ if (cpl.first == max_id || cpl.second == max_id) ++ (*itMap).second--; ++ } ++ } ++ // Final formatting - extract remaining keys in each map: ++ int myProcId=_group.myRank(); ++ _all_todo_lists.resize(grp_size); ++ procID = 0; ++ for(itVector = full_set.begin(); itVector != full_set.end(); itVector++, procID++) ++ for(itMap = (*itVector).begin(); itMap != (*itVector).end(); itMap++) ++ _all_todo_lists[procID].push_back((*itMap).first); ++ _to_do_list=_all_todo_lists[myProcId]; ++ ++#ifdef DEC_DEBUG ++ std::stringstream scout; ++ scout << "(" << myProcId << ") my TODO list is: "; ++ for (std::vector< ProcCouple >::const_iterator itdbg=_to_do_list.begin(); itdbg!=_to_do_list.end(); itdbg++) ++ scout << "(" << (*itdbg).first << "," << (*itdbg).second << ")"; ++ std::cout << scout.str() << "\n"; ++#endif + } + ++ void OverlapElementLocator::debugPrintWorkSharing(std::ostream & ostr) const ++ { ++ std::vector< std::vector< ProcCouple > >::const_iterator it = _all_todo_lists.begin(); ++ ostr << "TODO list lengths: "; ++ for(; it != _all_todo_lists.end(); ++it) ++ ostr << (*it).size() << " "; ++ ostr << "\n"; ++ } ++ ++ void OverlapElementLocator::fillProcToSend() ++ { ++ // Feeding now '_procs_to_send*'. A same id can appears twice. The second parameter in pair means what ++ // to send true=source, false=target ++ int myProcId=_group.myRank(); ++ _procs_to_send_mesh.clear(); ++ _procs_to_send_field.clear(); ++ for(int i=_group.size()-1;i>=0;i--) ++ { ++ const std::vector< ProcCouple >& anRemoteProcToDoList=_all_todo_lists[i]; ++ for(std::vector< ProcCouple >::const_iterator it=anRemoteProcToDoList.begin();it!=anRemoteProcToDoList.end();it++) ++ { ++ if((*it).first==myProcId) ++ { ++ if(i!=myProcId) ++ _procs_to_send_mesh.push_back(Proc_SrcOrTgt(i,true)); ++ _procs_to_send_field.push_back((*it).second); ++ } ++ if((*it).second==myProcId) ++ if(i!=myProcId) ++ _procs_to_send_mesh.push_back(Proc_SrcOrTgt(i,false)); ++ } ++ } ++ } ++ ++ + /*! + * The aim of this method is to perform the communication to get data corresponding to '_to_do_list' attribute. + * The principle is the following : if proc n1 and n2 need to perform a cross sending with n1 > toDoListForFetchRemaining; - for(std::vector< std::pair >::const_iterator it=_to_do_list.begin();it!=_to_do_list.end();it++) ++ std::vector< ProcCouple > toDoListForFetchRemaining; ++ for(std::vector< ProcCouple >::const_iterator it=_to_do_list.begin();it!=_to_do_list.end();it++) + { - if((*it).first!=(*it).second) ++ int first = (*it).first, second = (*it).second; ++ if(first!=second) + { - if((*it).first==myProcId) ++ if(first==myProcId) + { - if((*it).second((*it).first,(*it).second)); ++ toDoListForFetchRemaining.push_back(ProcCouple(first,second)); + } + else + {//(*it).second==myProcId - if((*it).first((*it).first,(*it).second)); ++ toDoListForFetchRemaining.push_back(ProcCouple(first,second)); + } + } + } + //sending source or target mesh to remote procs - for(std::vector< std::pair >::const_iterator it2=_procs_to_send.begin();it2!=_procs_to_send.end();it2++) ++ for(std::vector< Proc_SrcOrTgt >::const_iterator it2=_procs_to_send_mesh.begin();it2!=_procs_to_send_mesh.end();it2++) + sendLocalMeshTo((*it2).first,(*it2).second,matrix); + //fetching remaining meshes - for(std::vector< std::pair >::const_iterator it=toDoListForFetchRemaining.begin();it!=toDoListForFetchRemaining.end();it++) ++ for(std::vector< ProcCouple >::const_iterator it=toDoListForFetchRemaining.begin();it!=toDoListForFetchRemaining.end();it++) + { + if((*it).first!=(*it).second) + { + if((*it).first==myProcId) - receiveRemoteMesh((*it).second,false); ++ receiveRemoteMeshFrom((*it).second,false); + else//(*it).second==myProcId - receiveRemoteMesh((*it).first,true); ++ receiveRemoteMeshFrom((*it).first,true); + } + } + } + + std::string OverlapElementLocator::getSourceMethod() const + { + return _local_source_field->getField()->getDiscretization()->getStringRepr(); + } + + std::string OverlapElementLocator::getTargetMethod() const + { + return _local_target_field->getField()->getDiscretization()->getStringRepr(); + } + + const MEDCouplingPointSet *OverlapElementLocator::getSourceMesh(int procId) const + { + int myProcId=_group.myRank(); + if(myProcId==procId) + return _local_source_mesh; - std::pair p(procId,true); - std::map, MEDCouplingAutoRefCountObjectPtr< MEDCouplingPointSet > >::const_iterator it=_remote_meshes.find(p); ++ Proc_SrcOrTgt p(procId,true); ++ std::map::const_iterator it=_remote_meshes.find(p); + return (*it).second; + } + + const DataArrayInt *OverlapElementLocator::getSourceIds(int procId) const + { + int myProcId=_group.myRank(); + if(myProcId==procId) + return 0; - std::pair p(procId,true); - std::map, MEDCouplingAutoRefCountObjectPtr< DataArrayInt > >::const_iterator it=_remote_elems.find(p); ++ Proc_SrcOrTgt p(procId,true); ++ std::map::const_iterator it=_remote_elems.find(p); + return (*it).second; + } + + const MEDCouplingPointSet *OverlapElementLocator::getTargetMesh(int procId) const + { + int myProcId=_group.myRank(); + if(myProcId==procId) + return _local_target_mesh; - std::pair p(procId,false); - std::map, MEDCouplingAutoRefCountObjectPtr< MEDCouplingPointSet > >::const_iterator it=_remote_meshes.find(p); ++ Proc_SrcOrTgt p(procId,false); ++ std::map::const_iterator it=_remote_meshes.find(p); + return (*it).second; + } + + const DataArrayInt *OverlapElementLocator::getTargetIds(int procId) const + { + int myProcId=_group.myRank(); + if(myProcId==procId) + return 0; - std::pair p(procId,false); - std::map, MEDCouplingAutoRefCountObjectPtr< DataArrayInt > >::const_iterator it=_remote_elems.find(p); ++ Proc_SrcOrTgt p(procId,false); ++ std::map::const_iterator it=_remote_elems.find(p); + return (*it).second; + } + ++ bool OverlapElementLocator::isInMyTodoList(int i, int j) const ++ { ++ ProcCouple cpl = std::make_pair(i, j); ++ return std::find(_to_do_list.begin(), _to_do_list.end(), cpl)!=_to_do_list.end(); ++ } ++ + bool OverlapElementLocator::intersectsBoundingBox(int isource, int itarget) const + { + const double *source_bb=_domain_bounding_boxes+isource*2*2*_local_space_dim; + const double *target_bb=_domain_bounding_boxes+itarget*2*2*_local_space_dim+2*_local_space_dim; + + for (int idim=0; idim < _local_space_dim; idim++) + { - const double eps = -1e-12;//tony to change - bool intersects = (target_bb[idim*2] elems=local_mesh->getCellsInBoundingBox(distant_bb,getBoundingBoxAdjustment()); - DataArrayInt *idsToSend; - MEDCouplingPointSet *send_mesh=static_cast(field->getField()->buildSubMeshData(elems->begin(),elems->end(),idsToSend)); ++ AutoDAInt elems=local_mesh->getCellsInBoundingBox(distant_bb,getBoundingBoxAdjustment()); ++ DataArrayInt *old2new_map; ++ MEDCouplingPointSet *send_mesh=static_cast(field->getField()->buildSubMeshData(elems->begin(),elems->end(),old2new_map)); + if(sourceOrTarget) - matrix.keepTracksOfSourceIds(procId,idsToSend);//Case#1 in Step2 of main algorithm. ++ matrix.keepTracksOfSourceIds(procId,old2new_map); + else - matrix.keepTracksOfTargetIds(procId,idsToSend);//Case#0 in Step2 of main algorithm. - sendMesh(procId,send_mesh,idsToSend); ++ matrix.keepTracksOfTargetIds(procId,old2new_map); ++ sendMesh(procId,send_mesh,old2new_map); + send_mesh->decrRef(); - idsToSend->decrRef(); ++ old2new_map->decrRef(); + } + + /*! + * This method recieves source remote mesh on proc 'procId' if sourceOrTarget==True + * This method recieves target remote mesh on proc 'procId' if sourceOrTarget==False + */ - void OverlapElementLocator::receiveRemoteMesh(int procId, bool sourceOrTarget) ++ void OverlapElementLocator::receiveRemoteMeshFrom(int procId, bool sourceOrTarget) + { - DataArrayInt *da=0; ++ DataArrayInt *old2new_map=0; + MEDCouplingPointSet *m=0; - receiveMesh(procId,m,da); - std::pair p(procId,sourceOrTarget); ++ receiveMesh(procId,m,old2new_map); ++ Proc_SrcOrTgt p(procId,sourceOrTarget); + _remote_meshes[p]=m; - _remote_elems[p]=da; ++ _remote_elems[p]=old2new_map; + } + + void OverlapElementLocator::sendMesh(int procId, const MEDCouplingPointSet *mesh, const DataArrayInt *idsToSend) const + { + CommInterface comInterface=_group.getCommInterface(); ++ + // First stage : exchanging sizes + vector tinyInfoLocalD;//tinyInfoLocalD not used for the moment + vector tinyInfoLocal; + vector tinyInfoLocalS; + mesh->getTinySerializationInformation(tinyInfoLocalD,tinyInfoLocal,tinyInfoLocalS); + const MPI_Comm *comm=getCommunicator(); + // + int lgth[2]; + lgth[0]=tinyInfoLocal.size(); + lgth[1]=idsToSend->getNbOfElems(); - comInterface.send(&lgth,2,MPI_INT,procId,1140,*_comm); - comInterface.send(&tinyInfoLocal[0],tinyInfoLocal.size(),MPI_INT,procId,1141,*comm); ++ comInterface.send(&lgth,2,MPI_INT,procId,START_TAG_MESH_XCH,*_comm); ++ comInterface.send(&tinyInfoLocal[0],tinyInfoLocal.size(),MPI_INT,procId,START_TAG_MESH_XCH+1,*comm); + // + DataArrayInt *v1Local=0; + DataArrayDouble *v2Local=0; + mesh->serialize(v1Local,v2Local); - comInterface.send(v1Local->getPointer(),v1Local->getNbOfElems(),MPI_INT,procId,1142,*comm); - comInterface.send(v2Local->getPointer(),v2Local->getNbOfElems(),MPI_DOUBLE,procId,1143,*comm); ++ comInterface.send(v1Local->getPointer(),v1Local->getNbOfElems(),MPI_INT,procId,START_TAG_MESH_XCH+2,*comm); ++ comInterface.send(v2Local->getPointer(),v2Local->getNbOfElems(),MPI_DOUBLE,procId,START_TAG_MESH_XCH+3,*comm); + //finished for mesh, ids now - comInterface.send(const_cast(idsToSend->getConstPointer()),lgth[1],MPI_INT,procId,1144,*comm); ++ comInterface.send(const_cast(idsToSend->getConstPointer()),lgth[1],MPI_INT,procId,START_TAG_MESH_XCH+4,*comm); + // + v1Local->decrRef(); + v2Local->decrRef(); + } + + void OverlapElementLocator::receiveMesh(int procId, MEDCouplingPointSet* &mesh, DataArrayInt *&ids) const + { + int lgth[2]; + MPI_Status status; + const MPI_Comm *comm=getCommunicator(); + CommInterface comInterface=_group.getCommInterface(); - comInterface.recv(lgth,2,MPI_INT,procId,1140,*_comm,&status); ++ comInterface.recv(lgth,2,MPI_INT,procId,START_TAG_MESH_XCH,*_comm,&status); + std::vector tinyInfoDistant(lgth[0]); + ids=DataArrayInt::New(); + ids->alloc(lgth[1],1); - comInterface.recv(&tinyInfoDistant[0],lgth[0],MPI_INT,procId,1141,*comm,&status); ++ comInterface.recv(&tinyInfoDistant[0],lgth[0],MPI_INT,procId,START_TAG_MESH_XCH+1,*comm,&status); + mesh=MEDCouplingPointSet::BuildInstanceFromMeshType((MEDCouplingMeshType)tinyInfoDistant[0]); + std::vector unusedTinyDistantSts; + vector tinyInfoDistantD(1);//tinyInfoDistantD not used for the moment + DataArrayInt *v1Distant=DataArrayInt::New(); + DataArrayDouble *v2Distant=DataArrayDouble::New(); + mesh->resizeForUnserialization(tinyInfoDistant,v1Distant,v2Distant,unusedTinyDistantSts); - comInterface.recv(v1Distant->getPointer(),v1Distant->getNbOfElems(),MPI_INT,procId,1142,*comm,&status); - comInterface.recv(v2Distant->getPointer(),v2Distant->getNbOfElems(),MPI_DOUBLE,procId,1143,*comm,&status); ++ comInterface.recv(v1Distant->getPointer(),v1Distant->getNbOfElems(),MPI_INT,procId,START_TAG_MESH_XCH+2,*comm,&status); ++ comInterface.recv(v2Distant->getPointer(),v2Distant->getNbOfElems(),MPI_DOUBLE,procId,START_TAG_MESH_XCH+3,*comm,&status); + mesh->unserialization(tinyInfoDistantD,tinyInfoDistant,v1Distant,v2Distant,unusedTinyDistantSts); + //finished for mesh, ids now + comInterface.recv(ids->getPointer(),lgth[1],MPI_INT,procId,1144,*comm,&status); + // + v1Distant->decrRef(); + v2Distant->decrRef(); + } +} diff --cc medtool/src/ParaMEDMEM/OverlapElementLocator.hxx index 6ce2677f2,000000000..3ffd028db mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEM/OverlapElementLocator.hxx +++ b/medtool/src/ParaMEDMEM/OverlapElementLocator.hxx @@@ -1,91 -1,0 +1,116 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#ifndef __OVERLAPELEMENTLOCATOR_HXX__ +#define __OVERLAPELEMENTLOCATOR_HXX__ + +#include "InterpolationOptions.hxx" +#include "MEDCouplingNatureOfField.hxx" +#include "MEDCouplingPointSet.hxx" +#include "MEDCouplingMemArray.hxx" +#include "MEDCouplingAutoRefCountObjectPtr.hxx" + +#include +#include +#include +#include + ++//#define DEC_DEBUG ++ +namespace ParaMEDMEM +{ + class ParaFIELD; + class ProcessorGroup; + class OverlapInterpolationMatrix; + ++ typedef std::pair ProcCouple; // a couple of proc IDs, typically used to define a exchange betw 2 procs ++ + class OverlapElementLocator : public INTERP_KERNEL::InterpolationOptions + { + public: - OverlapElementLocator(const ParaFIELD *sourceField, const ParaFIELD *targetField, const ProcessorGroup& group); ++ OverlapElementLocator(const ParaFIELD *sourceField, const ParaFIELD *targetField, const ProcessorGroup& group, ++ double epsAbs, int workSharingAlgo); + virtual ~OverlapElementLocator(); + const MPI_Comm *getCommunicator() const; + void exchangeMeshes(OverlapInterpolationMatrix& matrix); + std::vector< std::pair > getToDoList() const { return _to_do_list; } - std::vector< std::vector< int > > getProcsInInteraction() const { return _proc_pairs; } ++ std::vector< int > getProcsToSendFieldData() const { return _procs_to_send_field; } // same set as the set of procs we sent mesh data to + std::string getSourceMethod() const; + std::string getTargetMethod() const; + const MEDCouplingPointSet *getSourceMesh(int procId) const; + const DataArrayInt *getSourceIds(int procId) const; + const MEDCouplingPointSet *getTargetMesh(int procId) const; + const DataArrayInt *getTargetIds(int procId) const; ++ bool isInMyTodoList(int i, int j) const; ++ void debugPrintWorkSharing(std::ostream & ostr) const; + private: - void computeBoundingBoxes(); ++ void computeBoundingBoxesAndInteractionList(); ++ void computeTodoList_original(); ++ void computeTodoList_new(bool revertIter); ++ void fillProcToSend(); + bool intersectsBoundingBox(int i, int j) const; + void sendLocalMeshTo(int procId, bool sourceOrTarget, OverlapInterpolationMatrix& matrix) const; - void receiveRemoteMesh(int procId, bool sourceOrTarget); ++ void receiveRemoteMeshFrom(int procId, bool sourceOrTarget); + void sendMesh(int procId, const MEDCouplingPointSet *mesh, const DataArrayInt *idsToSend) const; + void receiveMesh(int procId, MEDCouplingPointSet* &mesh, DataArrayInt *&ids) const; + private: ++ typedef MEDCouplingAutoRefCountObjectPtr< MEDCouplingPointSet > AutoMCPointSet; ++ typedef MEDCouplingAutoRefCountObjectPtr< DataArrayInt > AutoDAInt; ++ typedef std::pair Proc_SrcOrTgt; // a key indicating a proc ID and whether the data is for source mesh/field or target mesh/field ++ ++ static const int START_TAG_MESH_XCH; ++ + const ParaFIELD *_local_source_field; + const ParaFIELD *_local_target_field; ++ + int _local_space_dim; + MEDCouplingPointSet *_local_source_mesh; + MEDCouplingPointSet *_local_target_mesh; - std::vector _distant_cell_meshes; - std::vector _distant_face_meshes; - //! of size _group.size(). Contains for each source proc i, the ids of proc j the targets interact with. This vector is common for all procs in _group. ++ ++ /*! of size _group.size(). Contains for each source proc i, the ids of proc j the targets interact with. ++ This vector is common for all procs in _group. This is the full list of jobs to do the interp. */ + std::vector< std::vector< int > > _proc_pairs; - //! list of interpolations couple to be done - std::vector< std::pair > _to_do_list; - std::vector< std::pair > _procs_to_send; - std::map, MEDCouplingAutoRefCountObjectPtr< MEDCouplingPointSet > > _remote_meshes; - std::map, MEDCouplingAutoRefCountObjectPtr< DataArrayInt > > _remote_elems; ++ //! todo lists per proc ++ std::vector< std::vector< ProcCouple > > _all_todo_lists; ++ //! list of interpolation couples to be done by this proc only. This is a simple extraction of the member above _all_todo_lists ++ std::vector< ProcCouple > _to_do_list; ++ //! list of procs the local proc will have to send mesh data to: ++ std::vector< Proc_SrcOrTgt > _procs_to_send_mesh; ++// /*! list of procs the local proc will have to send field data to for the final matrix-vector computation: ++// * This can be different from _procs_to_send_mesh (restricted to Source) because interpolation matrix bits are computed on a potentially ++// * different proc than the target one. */ ++ std::vector< int > _procs_to_send_field; ++ //! Set of distant meshes ++ std::map< Proc_SrcOrTgt, AutoMCPointSet > _remote_meshes; ++ //! Set of cell ID mappings for the above distant meshes (because only part of the meshes are exchanged) ++ std::map< Proc_SrcOrTgt, AutoDAInt > _remote_elems; + double* _domain_bounding_boxes; - const ProcessorGroup& _group; ++ //! bounding box absolute adjustment ++ double _epsAbs; ++ + std::vector _distant_proc_ids; ++ ++ const ProcessorGroup& _group; + const MPI_Comm *_comm; - //Attributes only used by lazy side - //std::vector _values_added; - //std::vector< std::vector > _ids_per_working_proc; - //std::vector< std::vector > _ids_per_working_proc3; - //std::vector< std::vector > _values_per_working_proc; + }; + +} + +#endif diff --cc medtool/src/ParaMEDMEM/OverlapInterpolationMatrix.cxx index b57541bb8,000000000..060783833 mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEM/OverlapInterpolationMatrix.cxx +++ b/medtool/src/ParaMEDMEM/OverlapInterpolationMatrix.cxx @@@ -1,315 -1,0 +1,302 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#include "OverlapInterpolationMatrix.hxx" +#include "ParaMESH.hxx" +#include "ParaFIELD.hxx" +#include "ProcessorGroup.hxx" +#include "TranslationRotationMatrix.hxx" +#include "Interpolation.hxx" +#include "Interpolation1D.txx" +#include "Interpolation2DCurve.hxx" +#include "Interpolation2D.txx" +#include "Interpolation3DSurf.hxx" +#include "Interpolation3D.txx" +#include "Interpolation3D2D.txx" +#include "Interpolation2D1D.txx" +#include "MEDCouplingUMesh.hxx" +#include "MEDCouplingNormalizedUnstructuredMesh.txx" +#include "InterpolationOptions.hxx" +#include "NormalizedUnstructuredMesh.hxx" +#include "ElementLocator.hxx" +#include "InterpKernelAutoPtr.hxx" + +#include + +using namespace std; + +namespace ParaMEDMEM +{ + OverlapInterpolationMatrix::OverlapInterpolationMatrix(ParaFIELD *source_field, + ParaFIELD *target_field, + const ProcessorGroup& group, + const DECOptions& dec_options, - const INTERP_KERNEL::InterpolationOptions& i_opt): ++ const INTERP_KERNEL::InterpolationOptions& i_opt, ++ const OverlapElementLocator & locator): + INTERP_KERNEL::InterpolationOptions(i_opt), + DECOptions(dec_options), + _source_field(source_field), + _target_field(target_field), + _source_support(source_field->getSupport()->getCellMesh()), + _target_support(target_field->getSupport()->getCellMesh()), - _mapping(group), ++ _mapping(group, locator), + _group(group) + { - int nbelems = source_field->getField()->getNumberOfTuples(); - _row_offsets.resize(nbelems+1); - _coeffs.resize(nbelems); - _target_volume.resize(nbelems); + } + + void OverlapInterpolationMatrix::keepTracksOfSourceIds(int procId, DataArrayInt *ids) + { + _mapping.keepTracksOfSourceIds(procId,ids); + } + + void OverlapInterpolationMatrix::keepTracksOfTargetIds(int procId, DataArrayInt *ids) + { + _mapping.keepTracksOfTargetIds(procId,ids); + } + + OverlapInterpolationMatrix::~OverlapInterpolationMatrix() + { + } + - void OverlapInterpolationMatrix::addContribution(const MEDCouplingPointSet *src, const DataArrayInt *srcIds, const std::string& srcMeth, int srcProcId, ++ // TODO? Merge with MEDCouplingRemapper::prepareInterpKernelOnlyUU() ? ++ /**! ++ * Local run (on this proc) of the sequential interpolation algorithm. ++ * ++ * @param srcIds is null if the source mesh is on the local proc ++ * @param trgIds is null if the source mesh is on the local proc ++ * ++ * One of the 2 is necessarily null (the two can be null together) ++ */ ++ void OverlapInterpolationMatrix::computeLocalIntersection(const MEDCouplingPointSet *src, const DataArrayInt *srcIds, const std::string& srcMeth, int srcProcId, + const MEDCouplingPointSet *trg, const DataArrayInt *trgIds, const std::string& trgMeth, int trgProcId) + { + std::string interpMethod(srcMeth); + interpMethod+=trgMeth; + //creating the interpolator structure - vector > surfaces; ++ vector sparse_matrix_part; + int colSize=0; + //computation of the intersection volumes between source and target elements + const MEDCouplingUMesh *trgC=dynamic_cast(trg); + const MEDCouplingUMesh *srcC=dynamic_cast(src); + if ( src->getMeshDimension() == -1 ) + { + if(trgC->getMeshDimension()==2 && trgC->getSpaceDimension()==2) + { + MEDCouplingNormalizedUnstructuredMesh<2,2> target_mesh_wrapper(trgC); + INTERP_KERNEL::Interpolation2D interpolation(*this); - colSize=interpolation.fromIntegralUniform(target_mesh_wrapper,surfaces,trgMeth); ++ colSize=interpolation.fromIntegralUniform(target_mesh_wrapper,sparse_matrix_part,trgMeth); + } + else if(trgC->getMeshDimension()==3 && trgC->getSpaceDimension()==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,3> target_mesh_wrapper(trgC); + INTERP_KERNEL::Interpolation3D interpolation(*this); - colSize=interpolation.fromIntegralUniform(target_mesh_wrapper,surfaces,trgMeth); ++ colSize=interpolation.fromIntegralUniform(target_mesh_wrapper,sparse_matrix_part,trgMeth); + } + else if(trgC->getMeshDimension()==2 && trgC->getSpaceDimension()==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,2> target_mesh_wrapper(trgC); + INTERP_KERNEL::Interpolation3DSurf interpolation(*this); - colSize=interpolation.fromIntegralUniform(target_mesh_wrapper,surfaces,trgMeth); ++ colSize=interpolation.fromIntegralUniform(target_mesh_wrapper,sparse_matrix_part,trgMeth); + } + else + throw INTERP_KERNEL::Exception("No para interpolation available for the given mesh and space dimension of source mesh to -1D targetMesh"); + } + else if ( trg->getMeshDimension() == -1 ) + { + if(srcC->getMeshDimension()==2 && srcC->getSpaceDimension()==2) + { + MEDCouplingNormalizedUnstructuredMesh<2,2> local_mesh_wrapper(srcC); + INTERP_KERNEL::Interpolation2D interpolation(*this); - colSize=interpolation.toIntegralUniform(local_mesh_wrapper,surfaces,srcMeth); ++ colSize=interpolation.toIntegralUniform(local_mesh_wrapper,sparse_matrix_part,srcMeth); + } + else if(srcC->getMeshDimension()==3 && srcC->getSpaceDimension()==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,3> local_mesh_wrapper(srcC); + INTERP_KERNEL::Interpolation3D interpolation(*this); - colSize=interpolation.toIntegralUniform(local_mesh_wrapper,surfaces,srcMeth); ++ colSize=interpolation.toIntegralUniform(local_mesh_wrapper,sparse_matrix_part,srcMeth); + } + else if(srcC->getMeshDimension()==2 && srcC->getSpaceDimension()==3) + { + MEDCouplingNormalizedUnstructuredMesh<3,2> local_mesh_wrapper(srcC); + INTERP_KERNEL::Interpolation3DSurf interpolation(*this); - colSize=interpolation.toIntegralUniform(local_mesh_wrapper,surfaces,srcMeth); ++ colSize=interpolation.toIntegralUniform(local_mesh_wrapper,sparse_matrix_part,srcMeth); + } + else + throw INTERP_KERNEL::Exception("No para interpolation available for the given mesh and space dimension of distant mesh to -1D sourceMesh"); + } + else if ( src->getMeshDimension() == 2 && trg->getMeshDimension() == 3 + && trg->getSpaceDimension() == 3 && src->getSpaceDimension() == 3 ) + { + MEDCouplingNormalizedUnstructuredMesh<3,3> target_wrapper(trgC); + MEDCouplingNormalizedUnstructuredMesh<3,3> source_wrapper(srcC); + + INTERP_KERNEL::Interpolation3D2D interpolator (*this); - colSize=interpolator.interpolateMeshes(source_wrapper,target_wrapper,surfaces,interpMethod); - target_wrapper.releaseTempArrays(); - source_wrapper.releaseTempArrays(); ++ colSize=interpolator.interpolateMeshes(source_wrapper,target_wrapper,sparse_matrix_part,interpMethod); + } + else if ( src->getMeshDimension() == 3 && trg->getMeshDimension() == 2 + && trg->getSpaceDimension() == 3 && src->getSpaceDimension() == 3 ) + { + MEDCouplingNormalizedUnstructuredMesh<3,3> target_wrapper(trgC); + MEDCouplingNormalizedUnstructuredMesh<3,3> source_wrapper(srcC); + + INTERP_KERNEL::Interpolation3D2D interpolator (*this); - vector > surfacesTranspose; - colSize=interpolator.interpolateMeshes(target_wrapper,source_wrapper,surfaces,interpMethod);//not a bug target in source. - TransposeMatrix(surfacesTranspose,colSize,surfaces); - colSize=surfacesTranspose.size(); - target_wrapper.releaseTempArrays(); - source_wrapper.releaseTempArrays(); ++ vector matrixTranspose; ++ colSize=interpolator.interpolateMeshes(target_wrapper,source_wrapper,sparse_matrix_part,interpMethod);//not a bug target in source. ++ TransposeMatrix(matrixTranspose,colSize,sparse_matrix_part); ++ colSize=matrixTranspose.size(); + } + else if ( src->getMeshDimension() == 1 && trg->getMeshDimension() == 2 + && trg->getSpaceDimension() == 2 && src->getSpaceDimension() == 2 ) + { + MEDCouplingNormalizedUnstructuredMesh<2,2> target_wrapper(trgC); + MEDCouplingNormalizedUnstructuredMesh<2,2> source_wrapper(srcC); + + INTERP_KERNEL::Interpolation2D1D interpolator (*this); - colSize=interpolator.interpolateMeshes(source_wrapper,target_wrapper,surfaces,interpMethod); - target_wrapper.releaseTempArrays(); - source_wrapper.releaseTempArrays(); ++ colSize=interpolator.interpolateMeshes(source_wrapper,target_wrapper,sparse_matrix_part,interpMethod); + } + else if ( src->getMeshDimension() == 2 && trg->getMeshDimension() == 1 + && trg->getSpaceDimension() == 2 && src->getSpaceDimension() == 2 ) + { + MEDCouplingNormalizedUnstructuredMesh<2,2> target_wrapper(trgC); + MEDCouplingNormalizedUnstructuredMesh<2,2> source_wrapper(srcC); + + INTERP_KERNEL::Interpolation2D1D interpolator (*this); - vector > surfacesTranspose; - colSize=interpolator.interpolateMeshes(target_wrapper,source_wrapper,surfacesTranspose,interpMethod);//not a bug target in source. - TransposeMatrix(surfacesTranspose,colSize,surfaces); - colSize=surfacesTranspose.size(); - target_wrapper.releaseTempArrays(); - source_wrapper.releaseTempArrays(); ++ vector matrixTranspose; ++ colSize=interpolator.interpolateMeshes(target_wrapper,source_wrapper,matrixTranspose,interpMethod);//not a bug target in source. ++ TransposeMatrix(matrixTranspose,colSize,sparse_matrix_part); ++ colSize=matrixTranspose.size(); + } + else if (trg->getMeshDimension() != _source_support->getMeshDimension()) + { + throw INTERP_KERNEL::Exception("local and distant meshes do not have the same space and mesh dimensions"); + } + else if( src->getMeshDimension() == 1 + && src->getSpaceDimension() == 1 ) + { + MEDCouplingNormalizedUnstructuredMesh<1,1> target_wrapper(trgC); + MEDCouplingNormalizedUnstructuredMesh<1,1> source_wrapper(srcC); + + INTERP_KERNEL::Interpolation1D interpolation(*this); - colSize=interpolation.interpolateMeshes(source_wrapper,target_wrapper,surfaces,interpMethod); - target_wrapper.releaseTempArrays(); - source_wrapper.releaseTempArrays(); ++ colSize=interpolation.interpolateMeshes(source_wrapper,target_wrapper,sparse_matrix_part,interpMethod); + } + else if( trg->getMeshDimension() == 1 + && trg->getSpaceDimension() == 2 ) + { + MEDCouplingNormalizedUnstructuredMesh<2,1> target_wrapper(trgC); + MEDCouplingNormalizedUnstructuredMesh<2,1> source_wrapper(srcC); + + INTERP_KERNEL::Interpolation2DCurve interpolation(*this); - colSize=interpolation.interpolateMeshes(source_wrapper,target_wrapper,surfaces,interpMethod); - target_wrapper.releaseTempArrays(); - source_wrapper.releaseTempArrays(); ++ colSize=interpolation.interpolateMeshes(source_wrapper,target_wrapper,sparse_matrix_part,interpMethod); + } + else if ( trg->getMeshDimension() == 2 + && trg->getSpaceDimension() == 3 ) + { + MEDCouplingNormalizedUnstructuredMesh<3,2> target_wrapper(trgC); + MEDCouplingNormalizedUnstructuredMesh<3,2> source_wrapper(srcC); + + INTERP_KERNEL::Interpolation3DSurf interpolator (*this); - colSize=interpolator.interpolateMeshes(source_wrapper,target_wrapper,surfaces,interpMethod); - target_wrapper.releaseTempArrays(); - source_wrapper.releaseTempArrays(); ++ colSize=interpolator.interpolateMeshes(source_wrapper,target_wrapper,sparse_matrix_part,interpMethod); + } + else if ( trg->getMeshDimension() == 2 + && trg->getSpaceDimension() == 2) + { + MEDCouplingNormalizedUnstructuredMesh<2,2> target_wrapper(trgC); + MEDCouplingNormalizedUnstructuredMesh<2,2> source_wrapper(srcC); + + INTERP_KERNEL::Interpolation2D interpolator (*this); - colSize=interpolator.interpolateMeshes(source_wrapper,target_wrapper,surfaces,interpMethod); - target_wrapper.releaseTempArrays(); - source_wrapper.releaseTempArrays(); ++ colSize=interpolator.interpolateMeshes(source_wrapper,target_wrapper,sparse_matrix_part,interpMethod); + } + else if ( trg->getMeshDimension() == 3 + && trg->getSpaceDimension() == 3 ) + { + MEDCouplingNormalizedUnstructuredMesh<3,3> target_wrapper(trgC); + MEDCouplingNormalizedUnstructuredMesh<3,3> source_wrapper(srcC); + + INTERP_KERNEL::Interpolation3D interpolator (*this); - colSize=interpolator.interpolateMeshes(source_wrapper,target_wrapper,surfaces,interpMethod); - target_wrapper.releaseTempArrays(); - source_wrapper.releaseTempArrays(); ++ colSize=interpolator.interpolateMeshes(source_wrapper,target_wrapper,sparse_matrix_part,interpMethod); + } + else + { - throw INTERP_KERNEL::Exception("no interpolator exists for these mesh and space dimensions "); ++ throw INTERP_KERNEL::Exception("No interpolator exists for these mesh and space dimensions!"); + } - bool needSourceSurf=isSurfaceComputationNeeded(srcMeth); - MEDCouplingFieldDouble *source_triangle_surf=0; - if(needSourceSurf) - source_triangle_surf=src->getMeasureField(getMeasureAbsStatus()); - // - fillDistributedMatrix(surfaces,srcIds,srcProcId,trgIds,trgProcId); - // - if(needSourceSurf) - source_triangle_surf->decrRef(); ++ /* Fill distributed matrix: ++ In sparse_matrix_part rows refer to target, and columns (=first param of map in SparseDoubleVec) ++ refer to source. ++ */ ++ _mapping.addContributionST(sparse_matrix_part,srcIds,srcProcId,trgIds,trgProcId); + } + + /*! - * \b res rows refers to target and column (first param of map) to source. ++ * 'procsToSendField' gives the list of procs field data has to be sent to. ++ * See OverlapElementLocator::computeBoundingBoxesAndTodoList() + */ - void OverlapInterpolationMatrix::fillDistributedMatrix(const std::vector< std::map >& res, - const DataArrayInt *srcIds, int srcProc, - const DataArrayInt *trgIds, int trgProc) - { - _mapping.addContributionST(res,srcIds,srcProc,trgIds,trgProc); - } - - /*! - * 'procsInInteraction' gives the global view of interaction between procs. - * In 'procsInInteraction' for a proc with id i, is in interaction with procs listed in procsInInteraction[i] - */ - void OverlapInterpolationMatrix::prepare(const std::vector< std::vector >& procsInInteraction) ++ void OverlapInterpolationMatrix::prepare(const std::vector< int >& procsToSendField) + { + if(_source_support) - _mapping.prepare(procsInInteraction,_target_field->getField()->getNumberOfTuplesExpected()); ++ _mapping.prepare(procsToSendField,_target_field->getField()->getNumberOfTuplesExpected()); + else - _mapping.prepare(procsInInteraction,0); ++ _mapping.prepare(procsToSendField,0); + } + - void OverlapInterpolationMatrix::computeDeno() ++ void OverlapInterpolationMatrix::computeSurfacesAndDeno() + { + if(_target_field->getField()->getNature()==ConservativeVolumic) + _mapping.computeDenoConservativeVolumic(_target_field->getField()->getNumberOfTuplesExpected()); + else - throw INTERP_KERNEL::Exception("Policy Not implemented yet : only ConservativeVolumic defined !"); ++ throw INTERP_KERNEL::Exception("OverlapDEC: Policy not implemented yet: only ConservativeVolumic!"); ++// { ++// if(_target_field->getField()->getNature()==RevIntegral) ++// { ++// MEDCouplingAutoRefCountObjectPtr f; ++// int orient = getOrientation(); // From InterpolationOptions inheritance ++// if(orient == 2) // absolute areas ++// f = _target_support->getMeasureField(true); ++// else ++// if(orient == 0) // relative areas ++// f = _target_support->getMeasureField(false); ++// else ++// throw INTERP_KERNEL::Exception("OverlapDEC: orientation policy not impl. yet!"); ++// _mapping.computeDenoRevIntegral(*f->getArray()); ++// } ++// else ++// throw INTERP_KERNEL::Exception("OverlapDEC: Policy not implemented yet: only ConservativeVolumic and RevIntegral defined!"); ++// } + } + - void OverlapInterpolationMatrix::multiply() ++ void OverlapInterpolationMatrix::multiply(double default_val) + { - _mapping.multiply(_source_field->getField(),_target_field->getField()); ++ _mapping.multiply(_source_field->getField(),_target_field->getField(), default_val); + } + + void OverlapInterpolationMatrix::transposeMultiply() + { + _mapping.transposeMultiply(_target_field->getField(),_source_field->getField()); + } + - bool OverlapInterpolationMatrix::isSurfaceComputationNeeded(const std::string& method) const - { - return method=="P0"; - } - - void OverlapInterpolationMatrix::TransposeMatrix(const std::vector >& matIn, int nbColsMatIn, std::vector >& matOut) ++ void OverlapInterpolationMatrix::TransposeMatrix(const std::vector& matIn, ++ int nbColsMatIn, std::vector& matOut) + { + matOut.resize(nbColsMatIn); + int id=0; - for(std::vector >::const_iterator iter1=matIn.begin();iter1!=matIn.end();iter1++,id++) - for(std::map::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) ++ for(std::vector::const_iterator iter1=matIn.begin();iter1!=matIn.end();iter1++,id++) ++ for(SparseDoubleVec::const_iterator iter2=(*iter1).begin();iter2!=(*iter1).end();iter2++) + matOut[(*iter2).first][id]=(*iter2).second; + } +} diff --cc medtool/src/ParaMEDMEM/OverlapInterpolationMatrix.hxx index 2190e9add,000000000..d652ad024 mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEM/OverlapInterpolationMatrix.hxx +++ b/medtool/src/ParaMEDMEM/OverlapInterpolationMatrix.hxx @@@ -1,131 -1,0 +1,82 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#ifndef __OVERLAPINTERPOLATIONMATRIX_HXX__ +#define __OVERLAPINTERPOLATIONMATRIX_HXX__ + +#include "MPIAccessDEC.hxx" +#include "OverlapMapping.hxx" +#include "InterpolationOptions.hxx" +#include "DECOptions.hxx" + +namespace ParaMEDMEM +{ + class ParaFIELD; + class MEDCouplingPointSet; + + /*! + * Internal class, not part of the public API. + * + * Similar to InterpolationMatrix, but for the OverlapDEC instead of the InterpKernelDEC. + */ + class OverlapInterpolationMatrix : public INTERP_KERNEL::InterpolationOptions, + public DECOptions + { + public: + + OverlapInterpolationMatrix(ParaFIELD *source_field, + ParaFIELD *target_field, + const ProcessorGroup& group, + const DECOptions& dec_opt, - const InterpolationOptions& i_opt); ++ const InterpolationOptions& i_opt, ++ const OverlapElementLocator & loc); + + void keepTracksOfSourceIds(int procId, DataArrayInt *ids); + + void keepTracksOfTargetIds(int procId, DataArrayInt *ids); + - void addContribution(const MEDCouplingPointSet *src, const DataArrayInt *srcIds, const std::string& srcMeth, int srcProcId, ++ void computeLocalIntersection(const MEDCouplingPointSet *src, const DataArrayInt *srcIds, const std::string& srcMeth, int srcProcId, + const MEDCouplingPointSet *trg, const DataArrayInt *trgIds, const std::string& trgMeth, int trgProcId); + - void prepare(const std::vector< std::vector >& procsInInteraction); ++ void prepare(const std::vector< int > & procsToSendField); + - void computeDeno(); ++ void computeSurfacesAndDeno(); + - void multiply(); ++ void multiply(double default_val); + + void transposeMultiply(); + + virtual ~OverlapInterpolationMatrix(); - #if 0 - void addContribution(MEDCouplingPointSet& distant_support, int iproc_distant, - const int* distant_elems, const std::string& srcMeth, const std::string& targetMeth); - void finishContributionW(ElementLocator& elementLocator); - void finishContributionL(ElementLocator& elementLocator); - void multiply(MEDCouplingFieldDouble& field) const; - void transposeMultiply(MEDCouplingFieldDouble& field)const; - void prepare(); - int getNbRows() const { return _row_offsets.size(); } - MPIAccessDEC* getAccessDEC() { return _mapping.getAccessDEC(); } + private: - void computeConservVolDenoW(ElementLocator& elementLocator); - void computeIntegralDenoW(ElementLocator& elementLocator); - void computeRevIntegralDenoW(ElementLocator& elementLocator); - void computeGlobConstraintDenoW(ElementLocator& elementLocator); - void computeConservVolDenoL(ElementLocator& elementLocator); - void computeIntegralDenoL(ElementLocator& elementLocator); - void computeRevIntegralDenoL(ElementLocator& elementLocator); - - void computeLocalColSum(std::vector& res) const; - void computeLocalRowSum(const std::vector& distantProcs, std::vector >& resPerProcI, - std::vector >& resPerProcD) const; - void computeGlobalRowSum(ElementLocator& elementLocator, std::vector >& denoStrorage, std::vector >& denoStrorageInv); - void computeGlobalColSum(std::vector >& denoStrorage); - void resizeGlobalColSum(std::vector >& denoStrorage); - void fillDSFromVM(int iproc_distant, const int* distant_elems, const std::vector< std::map >& values, MEDCouplingFieldDouble *surf); - void serializeMe(std::vector< std::vector< std::map > >& data1, std::vector& data2) const; - void initialize(); - void findAdditionnalElements(ElementLocator& elementLocator, std::vector >& elementsToAdd, - const std::vector >& resPerProcI, const std::vector >& globalIdsPartial); - void addGhostElements(const std::vector& distantProcs, const std::vector >& elementsToAdd); - int mergePolicies(const std::vector& policyPartial); - void mergeRowSum(const std::vector< std::vector >& rowsPartialSumD, const std::vector< std::vector >& globalIdsPartial, - std::vector& globalIdsLazySideInteraction, std::vector& sumCorresponding); - void mergeRowSum2(const std::vector< std::vector >& globalIdsPartial, std::vector< std::vector >& rowsPartialSumD, - const std::vector& globalIdsLazySideInteraction, const std::vector& sumCorresponding); - void mergeRowSum3(const std::vector< std::vector >& globalIdsPartial, std::vector< std::vector >& rowsPartialSumD); - void mergeCoeffs(const std::vector& procsInInteraction, const std::vector< std::vector >& rowsPartialSumI, - const std::vector >& globalIdsPartial, std::vector >& denoStrorageInv); - void divideByGlobalRowSum(const std::vector& distantProcs, const std::vector >& resPerProcI, - const std::vector >& resPerProcD, std::vector >& deno); - #endif - private: - bool isSurfaceComputationNeeded(const std::string& method) const; - void fillDistributedMatrix(const std::vector< std::map >& res, - const DataArrayInt *srcIds, int srcProc, - const DataArrayInt *trgIds, int trgProc); - static void TransposeMatrix(const std::vector >& matIn, int nbColsMatIn, std::vector >& matOut); ++ ++ static void TransposeMatrix(const std::vector& matIn, int nbColsMatIn, ++ std::vector& matOut); + private: - ParaMEDMEM::ParaFIELD *_source_field; - ParaMEDMEM::ParaFIELD *_target_field; - std::vector _row_offsets; - std::map, int > _col_offsets; ++ ParaFIELD *_source_field; ++ ParaFIELD *_target_field; + MEDCouplingPointSet *_source_support; + MEDCouplingPointSet *_target_support; - OverlapMapping _mapping; ++ OverlapMapping _mapping; + + const ProcessorGroup& _group; - std::vector< std::vector > _target_volume; - std::vector > > _coeffs; - std::vector > _deno_multiply; - std::vector > _deno_reverse_multiply; + }; +} + +#endif diff --cc medtool/src/ParaMEDMEM/OverlapMapping.cxx index abb7a1d1b,000000000..f66dee02c mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEM/OverlapMapping.cxx +++ b/medtool/src/ParaMEDMEM/OverlapMapping.cxx @@@ -1,673 -1,0 +1,885 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#include "OverlapMapping.hxx" +#include "MPIProcessorGroup.hxx" + +#include "MEDCouplingFieldDouble.hxx" +#include "MEDCouplingAutoRefCountObjectPtr.hxx" + +#include "InterpKernelAutoPtr.hxx" + +#include +#include + +using namespace ParaMEDMEM; + - OverlapMapping::OverlapMapping(const ProcessorGroup& group):_group(group) ++OverlapMapping::OverlapMapping(const ProcessorGroup& group, const OverlapElementLocator & loc): ++ _group(group),_locator(loc) +{ +} + +/*! - * This method keeps tracks of source ids to know in step 6 of main algorithm, which tuple ids to send away. - * This method incarnates item#1 of step2 algorithm. ++ * Keeps the link between a given a proc holding source mesh data, and the corresponding cell IDs. + */ +void OverlapMapping::keepTracksOfSourceIds(int procId, DataArrayInt *ids) +{ + ids->incrRef(); - _src_ids_st2.push_back(ids); - _src_proc_st2.push_back(procId); ++ _sent_src_ids[procId] = ids; +} + +/*! - * This method keeps tracks of target ids to know in step 6 of main algorithm. - * This method incarnates item#0 of step2 algorithm. - */ ++ * Same as keepTracksOfSourceIds() but for target mesh data. ++*/ +void OverlapMapping::keepTracksOfTargetIds(int procId, DataArrayInt *ids) +{ + ids->incrRef(); - _trg_ids_st2.push_back(ids); - _trg_proc_st2.push_back(procId); ++ _sent_trg_ids[procId] = ids; +} + +/*! - * This method stores from a matrix in format Target(rows)/Source(cols) for a source procId 'srcProcId' and for a target procId 'trgProcId'. - * All ids (source and target) are in format of local ids. ++ * This method stores in the local members the contribution coming from a matrix in format ++ * Target(rows)/Source(cols) for a source procId 'srcProcId' and for a target procId 'trgProcId'. ++ * All IDs received here (source and target) are in the format of local IDs. ++ * ++ * @param srcIds is null if the source mesh is on the local proc ++ * @param trgIds is null if the source mesh is on the local proc ++ * ++ * One of the 2 is necessarily null (the two can be null together) + */ - void OverlapMapping::addContributionST(const std::vector< std::map >& matrixST, const DataArrayInt *srcIds, int srcProcId, const DataArrayInt *trgIds, int trgProcId) ++void OverlapMapping::addContributionST(const std::vector< SparseDoubleVec >& matrixST, const DataArrayInt *srcIds, int srcProcId, const DataArrayInt *trgIds, int trgProcId) +{ + _matrixes_st.push_back(matrixST); + _source_proc_id_st.push_back(srcProcId); + _target_proc_id_st.push_back(trgProcId); - if(srcIds) - {//item#1 of step2 algorithm in proc m. Only to know in advanced nb of recv ids [ (0,1) computed on proc1 and Matrix-Vector on proc1 ] - _nb_of_src_ids_proc_st2.push_back(srcIds->getNumberOfTuples()); - _src_ids_proc_st2.push_back(srcProcId); - } - else - {//item#0 of step2 algorithm in proc k ++ if(srcIds) // source mesh part is remote <=> srcProcId != myRank ++ _nb_of_rcv_src_ids[srcProcId] = srcIds->getNumberOfTuples(); ++ else // source mesh part is local ++ { + std::set s; - for(std::vector< std::map >::const_iterator it1=matrixST.begin();it1!=matrixST.end();it1++) - for(std::map::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) ++ // For all source IDs (=col indices) in the sparse matrix: ++ for(std::vector< SparseDoubleVec >::const_iterator it1=matrixST.begin();it1!=matrixST.end();it1++) ++ for(SparseDoubleVec::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + s.insert((*it2).first); - _src_ids_zip_st2.resize(_src_ids_zip_st2.size()+1); - _src_ids_zip_st2.back().insert(_src_ids_zip_st2.back().end(),s.begin(),s.end()); - _src_ids_zip_proc_st2.push_back(trgProcId); ++ vector v(s.begin(), s.end()); // turn set into vector ++ _src_ids_zip_comp[trgProcId] = v; + } +} + +/*! - * 'procsInInteraction' gives the global view of interaction between procs. - * In 'procsInInteraction' for a proc with id i, is in interaction with procs listed in procsInInteraction[i]. ++ * This method is in charge to send matrices in AlltoAll mode. ++ * ++ * 'procsToSendField' gives the list of procs field data has to be sent to. ++ * See OverlapElementLocator::computeBoundingBoxesAndTodoList() + * - * This method is in charge to send matrixes in AlltoAll mode. - * After the call of this method 'this' contains the matrixST for all source elements of the current proc ++ * After the call of this method, 'this' contains the matrixST for all source cells of the current proc + */ - void OverlapMapping::prepare(const std::vector< std::vector >& procsInInteraction, int nbOfTrgElems) ++void OverlapMapping::prepare(const std::vector< int >& procsToSendField, int nbOfTrgElems) +{ ++#ifdef DEC_DEBUG ++ printMatrixesST(); ++#endif ++ + CommInterface commInterface=_group.getCommInterface(); + const MPIProcessorGroup *group=static_cast(&_group); + const MPI_Comm *comm=group->getComm(); + int grpSize=_group.size(); + INTERP_KERNEL::AutoPtr nbsend=new int[grpSize]; + INTERP_KERNEL::AutoPtr nbsend2=new int[grpSize]; + INTERP_KERNEL::AutoPtr nbsend3=new int[grpSize]; + std::fill(nbsend,nbsend+grpSize,0); + int myProcId=_group.myRank(); - _proc_ids_to_recv_vector_st.clear(); - int curProc=0; - for(std::vector< std::vector >::const_iterator it1=procsInInteraction.begin();it1!=procsInInteraction.end();it1++,curProc++) - if(std::find((*it1).begin(),(*it1).end(),myProcId)!=(*it1).end()) - _proc_ids_to_recv_vector_st.push_back(curProc); - _proc_ids_to_send_vector_st=procsInInteraction[myProcId]; + for(std::size_t i=0;i<_matrixes_st.size();i++) + if(_source_proc_id_st[i]==myProcId) + nbsend[_target_proc_id_st[i]]=_matrixes_st[i].size(); + INTERP_KERNEL::AutoPtr nbrecv=new int[grpSize]; + commInterface.allToAll(nbsend,1,MPI_INT,nbrecv,1,MPI_INT,*comm); + //exchanging matrix + //first exchanging offsets+ids_source + INTERP_KERNEL::AutoPtr nbrecv1=new int[grpSize]; + INTERP_KERNEL::AutoPtr nbrecv2=new int[grpSize]; + // + int *tmp=0; + serializeMatrixStep0ST(nbrecv, + tmp,nbsend2,nbsend3, + nbrecv1,nbrecv2); + INTERP_KERNEL::AutoPtr bigArr=tmp; + INTERP_KERNEL::AutoPtr bigArrRecv=new int[nbrecv2[grpSize-1]+nbrecv1[grpSize-1]]; + commInterface.allToAllV(bigArr,nbsend2,nbsend3,MPI_INT, + bigArrRecv,nbrecv1,nbrecv2,MPI_INT, + *comm);// sending ids of sparse matrix (n+1 elems) + //second phase echange target ids + std::fill(nbsend2,nbsend2+grpSize,0); + INTERP_KERNEL::AutoPtr nbrecv3=new int[grpSize]; + INTERP_KERNEL::AutoPtr nbrecv4=new int[grpSize]; + double *tmp2=0; + int lgthOfArr=serializeMatrixStep1ST(nbrecv,bigArrRecv,nbrecv1,nbrecv2, + tmp,tmp2, + nbsend2,nbsend3,nbrecv3,nbrecv4); + INTERP_KERNEL::AutoPtr bigArr2=tmp; + INTERP_KERNEL::AutoPtr bigArrD2=tmp2; + INTERP_KERNEL::AutoPtr bigArrRecv2=new int[lgthOfArr]; + INTERP_KERNEL::AutoPtr bigArrDRecv2=new double[lgthOfArr]; + commInterface.allToAllV(bigArr2,nbsend2,nbsend3,MPI_INT, + bigArrRecv2,nbrecv3,nbrecv4,MPI_INT, + *comm); + commInterface.allToAllV(bigArrD2,nbsend2,nbsend3,MPI_DOUBLE, + bigArrDRecv2,nbrecv3,nbrecv4,MPI_DOUBLE, + *comm); + //finishing + unserializationST(nbOfTrgElems,nbrecv,bigArrRecv,nbrecv1,nbrecv2, + bigArrRecv2,bigArrDRecv2,nbrecv3,nbrecv4); - //updating _src_ids_zip_st2 and _src_ids_zip_st2 with received matrix. - updateZipSourceIdsForFuture(); - //finish to fill _the_matrix_st with already in place matrix in _matrixes_st ++ ++ //finish to fill _the_matrix_st with already in place matrix in _matrixes_st (local computation) + finishToFillFinalMatrixST(); - //printTheMatrix(); ++ ++ //updating _src_ids_zip_st2 and _src_ids_zip_st2 with received matrix. ++ fillSourceIdsZipReceivedForMultiply(); ++ // Prepare proc list for future field data exchange (mutliply()): ++ _proc_ids_to_send_vector_st = procsToSendField; ++ // Make some space on local proc: ++ _matrixes_st.clear(); ++ ++#ifdef DEC_DEBUG ++ printTheMatrix(); ++#endif +} + - /*! - * Compute denominators. - */ - void OverlapMapping::computeDenoGlobConstraint() ++///*! ++// * Compute denominators for IntegralGlobConstraint interp. ++// * TO BE REVISED: needs another communication since some bits are held non locally ++// */ ++//void OverlapMapping::computeDenoGlobConstraint() ++//{ ++// _the_deno_st.clear(); ++// std::size_t sz1=_the_matrix_st.size(); ++// _the_deno_st.resize(sz1); ++// for(std::size_t i=0;i& mToFill=_the_deno_st[i][j]; - const std::map& m=_the_matrix_st[i][j]; - for(std::map::const_iterator it=m.begin();it!=m.end();it++) - sum+=(*it).second; - for(std::map::const_iterator it=m.begin();it!=m.end();it++) - mToFill[(*it).first]=sum; ++ SparseDoubleVec& mToFill=_the_deno_st[i][j]; ++ SparseDoubleVec& mToIterate=_the_matrix_st[i][j]; ++ for(SparseDoubleVec::const_iterator it=mToIterate.begin();it!=mToIterate.end();it++) ++ mToFill[(*it).first] = targetAreasP[j]; + } + } ++// printDenoMatrix(); +} + ++ +/*! - * Compute denominators. ++ * Compute denominators for ConvervativeVolumic interp. + */ +void OverlapMapping::computeDenoConservativeVolumic(int nbOfTuplesTrg) +{ - CommInterface commInterface=_group.getCommInterface(); + int myProcId=_group.myRank(); + // + _the_deno_st.clear(); + std::size_t sz1=_the_matrix_st.size(); + _the_deno_st.resize(sz1); + std::vector deno(nbOfTuplesTrg); ++ // Fills in the vector indexed by target cell ID: + for(std::size_t i=0;i >& mat=_the_matrix_st[i]; ++ const std::vector< SparseDoubleVec >& mat=_the_matrix_st[i]; + int curSrcId=_the_matrix_st_source_proc_id[i]; - std::vector::iterator isItem1=std::find(_trg_proc_st2.begin(),_trg_proc_st2.end(),curSrcId); ++ map < int, MEDCouplingAutoRefCountObjectPtr >::const_iterator isItem1 = _sent_trg_ids.find(curSrcId); + int rowId=0; - if(isItem1==_trg_proc_st2.end() || curSrcId==myProcId)//item1 of step2 main algo. Simple, because rowId of mat are directly target ids. ++ if(isItem1==_sent_trg_ids.end() || curSrcId==myProcId) // Local computation: simple, because rowId of mat are directly target cell ids. + { - for(std::vector< std::map >::const_iterator it1=mat.begin();it1!=mat.end();it1++,rowId++) - for(std::map::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) ++ for(std::vector< SparseDoubleVec >::const_iterator it1=mat.begin();it1!=mat.end();it1++,rowId++) ++ for(SparseDoubleVec::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + deno[rowId]+=(*it2).second; + } - else - {//item0 of step2 main algo. More complicated. - std::vector::iterator fnd=isItem1;//std::find(_trg_proc_st2.begin(),_trg_proc_st2.end(),curSrcId); - int locId=std::distance(_trg_proc_st2.begin(),fnd); - const DataArrayInt *trgIds=_trg_ids_st2[locId]; ++ else // matrix was received, remote computation ++ { ++ const DataArrayInt *trgIds = (*isItem1).second; + const int *trgIds2=trgIds->getConstPointer(); - for(std::vector< std::map >::const_iterator it1=mat.begin();it1!=mat.end();it1++,rowId++) - for(std::map::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) ++ for(std::vector< SparseDoubleVec >::const_iterator it1=mat.begin();it1!=mat.end();it1++,rowId++) ++ for(SparseDoubleVec::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + deno[trgIds2[rowId]]+=(*it2).second; + } + } - // ++ // Broadcast the vector into a structure similar to the initial sparse matrix of numerators: + for(std::size_t i=0;i >& mat=_the_matrix_st[i]; ++ const std::vector< SparseDoubleVec >& mat=_the_matrix_st[i]; + int curSrcId=_the_matrix_st_source_proc_id[i]; - std::vector::iterator isItem1=std::find(_trg_proc_st2.begin(),_trg_proc_st2.end(),curSrcId); - std::vector< std::map >& denoM=_the_deno_st[i]; ++ map < int, MEDCouplingAutoRefCountObjectPtr >::const_iterator isItem1 = _sent_trg_ids.find(curSrcId); ++ std::vector< SparseDoubleVec >& denoM=_the_deno_st[i]; + denoM.resize(mat.size()); - if(isItem1==_trg_proc_st2.end() || curSrcId==myProcId)//item1 of step2 main algo. Simple, because rowId of mat are directly target ids. ++ if(isItem1==_sent_trg_ids.end() || curSrcId==myProcId)//item1 of step2 main algo. Simple, because rowId of mat are directly target ids. + { + int rowId=0; - for(std::vector< std::map >::const_iterator it1=mat.begin();it1!=mat.end();it1++,rowId++) - for(std::map::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) ++ for(std::vector< SparseDoubleVec >::const_iterator it1=mat.begin();it1!=mat.end();it1++,rowId++) ++ for(SparseDoubleVec::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + denoM[rowId][(*it2).first]=deno[rowId]; + } + else + { - std::vector::iterator fnd=isItem1; - int locId=std::distance(_trg_proc_st2.begin(),fnd); - const DataArrayInt *trgIds=_trg_ids_st2[locId]; ++ const DataArrayInt *trgIds = (*isItem1).second; + const int *trgIds2=trgIds->getConstPointer(); - for(std::vector< std::map >::const_iterator it1=mat.begin();it1!=mat.end();it1++,rowId++) - for(std::map::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) ++ for(std::vector< SparseDoubleVec >::const_iterator it1=mat.begin();it1!=mat.end();it1++,rowId++) ++ for(SparseDoubleVec::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + denoM[rowId][(*it2).first]=deno[trgIds2[rowId]]; + } + } ++// printDenoMatrix(); +} + +/*! + * This method performs step #0/3 in serialization process. + * \param count tells specifies nb of elems to send to corresponding proc id. size equal to _group.size(). + * \param offsets tells for a proc i where to start serialize#0 matrix. size equal to _group.size(). + * \param nbOfElemsSrc of size _group.size(). Comes from previous all2all call. tells how many srcIds per proc contains matrix for current proc. + */ +void OverlapMapping::serializeMatrixStep0ST(const int *nbOfElemsSrc, int *&bigArr, int *count, int *offsets, + int *countForRecv, int *offsetsForRecv) const +{ + int grpSize=_group.size(); + std::fill(count,count+grpSize,0); + int szz=0; + int myProcId=_group.myRank(); + for(std::size_t i=0;i<_matrixes_st.size();i++) + { + if(_source_proc_id_st[i]==myProcId)// && _target_proc_id_st[i]!=myProcId + { + count[_target_proc_id_st[i]]=_matrixes_st[i].size()+1; + szz+=_matrixes_st[i].size()+1; + } + } + bigArr=new int[szz]; + offsets[0]=0; + for(int i=1;i >& mat=_matrixes_st[i]; - for(std::vector< std::map >::const_iterator it=mat.begin();it!=mat.end();it++,work++) ++ const std::vector< SparseDoubleVec >& mat=_matrixes_st[i]; ++ for(std::vector< SparseDoubleVec >::const_iterator it=mat.begin();it!=mat.end();it++,work++) + work[1]=work[0]+(*it).size(); + } + } + // + offsetsForRecv[0]=0; + for(int i=0;i0) + countForRecv[i]=nbOfElemsSrc[i]+1; + else + countForRecv[i]=0; + if(i>0) + offsetsForRecv[i]=offsetsForRecv[i-1]+countForRecv[i-1]; + } +} + +/*! + * This method performs step#1 and step#2/3. It returns the size of expected array to get allToAllV. ++ * It is where the locally computed matrices are serialized to be sent to adequate final proc. + */ +int OverlapMapping::serializeMatrixStep1ST(const int *nbOfElemsSrc, const int *recvStep0, const int *countStep0, const int *offsStep0, + int *&bigArrI, double *&bigArrD, int *count, int *offsets, + int *countForRecv, int *offsForRecv) const +{ + int grpSize=_group.size(); + int myProcId=_group.myRank(); + offsForRecv[0]=0; + int szz=0; + for(int i=0;i0) + offsForRecv[i]=offsForRecv[i-1]+countForRecv[i-1]; + } + // + std::fill(count,count+grpSize,0); + offsets[0]=0; + int fullLgth=0; + for(std::size_t i=0;i<_matrixes_st.size();i++) + { + if(_source_proc_id_st[i]==myProcId) + { - const std::vector< std::map >& mat=_matrixes_st[i]; ++ const std::vector< SparseDoubleVec >& mat=_matrixes_st[i]; + int lgthToSend=0; - for(std::vector< std::map >::const_iterator it=mat.begin();it!=mat.end();it++) ++ for(std::vector< SparseDoubleVec >::const_iterator it=mat.begin();it!=mat.end();it++) + lgthToSend+=(*it).size(); + count[_target_proc_id_st[i]]=lgthToSend; + fullLgth+=lgthToSend; + } + } + for(int i=1;i >& mat=_matrixes_st[i]; - for(std::vector< std::map >::const_iterator it1=mat.begin();it1!=mat.end();it1++) ++ const std::vector< SparseDoubleVec >& mat=_matrixes_st[i]; ++ for(std::vector< SparseDoubleVec >::const_iterator it1=mat.begin();it1!=mat.end();it1++) + { + int j=0; - for(std::map::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++,j++) ++ for(SparseDoubleVec::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++,j++) + { + bigArrI[fullLgth+j]=(*it2).first; + bigArrD[fullLgth+j]=(*it2).second; + } + fullLgth+=(*it1).size(); + } + } + } + return szz; +} + +/*! + * This is the last step after all2Alls for matrix exchange. + * _the_matrix_st is the final matrix : + * - The first entry is srcId in current proc. + * - The second is the pseudo id of source proc (correspondance with true id is in attribute _the_matrix_st_source_proc_id and _the_matrix_st_source_ids) + * - the third is the srcId in the pseudo source proc + */ +void OverlapMapping::unserializationST(int nbOfTrgElems, + const int *nbOfElemsSrcPerProc,//first all2all + const int *bigArrRecv, const int *bigArrRecvCounts, const int *bigArrRecvOffs,//2nd all2all + const int *bigArrRecv2, const double *bigArrDRecv2, const int *bigArrRecv2Count, const int *bigArrRecv2Offs)//3rd and 4th all2alls +{ + _the_matrix_st.clear(); + _the_matrix_st_source_proc_id.clear(); + // + int grpSize=_group.size(); + for(int i=0;i_the_matrix_st' and 'this->_the_matrix_st_target_proc_id' - * and 'this->_the_matrix_st_target_ids'. - * This method finish the job of filling 'this->_the_matrix_st' and 'this->_the_matrix_st_target_proc_id' by putting candidates in 'this->_matrixes_st' into them. ++ * This method should be called when all remote matrix with sourceProcId==thisProcId have been retrieved and are ++ * in 'this->_the_matrix_st' and 'this->_the_matrix_st_target_proc_id' and 'this->_the_matrix_st_target_ids'. ++ * This method finish the job of filling 'this->_the_matrix_st' and 'this->_the_matrix_st_target_proc_id' ++ * by putting candidates in 'this->_matrixes_st' into them (i.e. local computation result). + */ +void OverlapMapping::finishToFillFinalMatrixST() +{ + int myProcId=_group.myRank(); + int sz=_matrixes_st.size(); + int nbOfEntryToAdd=0; + for(int i=0;i >& mat=_matrixes_st[i]; ++ const std::vector& mat=_matrixes_st[i]; + _the_matrix_st[j]=mat; + _the_matrix_st_source_proc_id.push_back(_source_proc_id_st[i]); + j++; + } - _matrixes_st.clear(); +} + - /*! - * This method performs the operation of target ids broadcasting. - */ - void OverlapMapping::prepareIdsToSendST() - { - CommInterface commInterface=_group.getCommInterface(); - const MPIProcessorGroup *group=static_cast(&_group); - const MPI_Comm *comm=group->getComm(); - int grpSize=_group.size(); - _source_ids_to_send_st.clear(); - _source_ids_to_send_st.resize(grpSize); - INTERP_KERNEL::AutoPtr nbsend=new int[grpSize]; - std::fill(nbsend,nbsend+grpSize,0); - for(std::size_t i=0;i<_the_matrix_st_source_proc_id.size();i++) - nbsend[_the_matrix_st_source_proc_id[i]]=_the_matrix_st_source_ids[i].size(); - INTERP_KERNEL::AutoPtr nbrecv=new int[grpSize]; - commInterface.allToAll(nbsend,1,MPI_INT,nbrecv,1,MPI_INT,*comm); - // - INTERP_KERNEL::AutoPtr nbsend2=new int[grpSize]; - std::copy((int *)nbsend,((int *)nbsend)+grpSize,(int *)nbsend2); - INTERP_KERNEL::AutoPtr nbsend3=new int[grpSize]; - nbsend3[0]=0; - for(int i=1;i bigDataSend=new int[sendSz]; - for(std::size_t i=0;i<_the_matrix_st_source_proc_id.size();i++) - { - int offset=nbsend3[_the_matrix_st_source_proc_id[i]]; - std::copy(_the_matrix_st_source_ids[i].begin(),_the_matrix_st_source_ids[i].end(),((int *)nbsend3)+offset); - } - INTERP_KERNEL::AutoPtr nbrecv2=new int[grpSize]; - INTERP_KERNEL::AutoPtr nbrecv3=new int[grpSize]; - std::copy((int *)nbrecv,((int *)nbrecv)+grpSize,(int *)nbrecv2); - nbrecv3[0]=0; - for(int i=1;i bigDataRecv=new int[recvSz]; - // - commInterface.allToAllV(bigDataSend,nbsend2,nbsend3,MPI_INT, - bigDataRecv,nbrecv2,nbrecv3,MPI_INT, - *comm); - for(int i=0;i0) - { - _source_ids_to_send_st[i].insert(_source_ids_to_send_st[i].end(),((int *)bigDataRecv)+nbrecv3[i],((int *)bigDataRecv)+nbrecv3[i]+nbrecv2[i]); - } - } - } + +/*! + * This method performs a transpose multiply of 'fieldInput' and put the result into 'fieldOutput'. + * 'fieldInput' is expected to be the sourcefield and 'fieldOutput' the targetfield. + */ - void OverlapMapping::multiply(const MEDCouplingFieldDouble *fieldInput, MEDCouplingFieldDouble *fieldOutput) const ++void OverlapMapping::multiply(const MEDCouplingFieldDouble *fieldInput, MEDCouplingFieldDouble *fieldOutput, double default_val) const +{ ++ using namespace std; ++ + int nbOfCompo=fieldInput->getNumberOfComponents();//to improve same number of components to test + CommInterface commInterface=_group.getCommInterface(); + const MPIProcessorGroup *group=static_cast(&_group); + const MPI_Comm *comm=group->getComm(); + int grpSize=_group.size(); - int myProcId=_group.myRank(); ++ int myProcID=_group.myRank(); + // + INTERP_KERNEL::AutoPtr nbsend=new int[grpSize]; + INTERP_KERNEL::AutoPtr nbsend2=new int[grpSize]; + INTERP_KERNEL::AutoPtr nbrecv=new int[grpSize]; + INTERP_KERNEL::AutoPtr nbrecv2=new int[grpSize]; - std::fill(nbsend,nbsend+grpSize,0); - std::fill(nbrecv,nbrecv+grpSize,0); ++ fill(nbsend,nbsend+grpSize,0); ++ fill(nbrecv,nbrecv+grpSize,0); + nbsend2[0]=0; + nbrecv2[0]=0; - std::vector valsToSend; - for(int i=0;i valsToSend; ++ ++ /* ++ * FIELD VALUE XCHGE: ++ * We call the 'BB source IDs' (bounding box source IDs) the set of source cell IDs transmitted just based on the bounding box information. ++ * This is potentially bigger than what is finally in the interp matrix and this is stored in _sent_src_ids. ++ * We call 'interp source IDs' the set of source cell IDs with non null entries in the interp matrix. This is a sub-set of the above. ++ */ ++ for(int procID=0;procID::const_iterator isItem1=std::find(_src_proc_st2.begin(),_src_proc_st2.end(),i); - MEDCouplingAutoRefCountObjectPtr vals; - if(isItem1!=_src_proc_st2.end())//item1 of step2 main algo - { - int id=std::distance(_src_proc_st2.begin(),isItem1); - vals=fieldInput->getArray()->selectByTupleId(_src_ids_st2[id]->getConstPointer(),_src_ids_st2[id]->getConstPointer()+_src_ids_st2[id]->getNumberOfTuples()); - } - else - {//item0 of step2 main algo - int id=std::distance(_src_ids_zip_proc_st2.begin(),std::find(_src_ids_zip_proc_st2.begin(),_src_ids_zip_proc_st2.end(),i)); - vals=fieldInput->getArray()->selectByTupleId(&(_src_ids_zip_st2[id])[0],&(_src_ids_zip_st2[id])[0]+_src_ids_zip_st2[id].size()); - } - nbsend[i]=vals->getNbOfElems(); - valsToSend.insert(valsToSend.end(),vals->getConstPointer(),vals->getConstPointer()+nbsend[i]); - } - if(std::find(_proc_ids_to_recv_vector_st.begin(),_proc_ids_to_recv_vector_st.end(),i)!=_proc_ids_to_recv_vector_st.end()) - { - std::vector::const_iterator isItem0=std::find(_trg_proc_st2.begin(),_trg_proc_st2.end(),i); - if(isItem0==_trg_proc_st2.end())//item1 of step2 main algo [ (0,1) computed on proc1 and Matrix-Vector on proc1 ] - { - std::vector::const_iterator it1=std::find(_src_ids_proc_st2.begin(),_src_ids_proc_st2.end(),i); - if(it1!=_src_ids_proc_st2.end()) - { - int id=std::distance(_src_ids_proc_st2.begin(),it1); - nbrecv[i]=_nb_of_src_ids_proc_st2[id]*nbOfCompo; - } - else if(i==myProcId) - { - nbrecv[i]=fieldInput->getNumberOfTuplesExpected()*nbOfCompo; - } - else - throw INTERP_KERNEL::Exception("Plouff ! send email to anthony.geay@cea.fr ! "); - } - else - {//item0 of step2 main algo [ (2,1) computed on proc2 but Matrix-Vector on proc1 ] [(1,0) computed on proc1 but Matrix-Vector on proc0] - int id=std::distance(_src_ids_zip_proc_st2.begin(),std::find(_src_ids_zip_proc_st2.begin(),_src_ids_zip_proc_st2.end(),i)); - nbrecv[i]=_src_ids_zip_st2[id].size()*nbOfCompo; - } - } ++ /* SENDING part: compute field values to be SENT (and how many of them) ++ * - for all proc 'procID' in group ++ * * if procID == myProcID, send nothing ++ * * elif 'procID' in _proc_ids_to_send_vector_st (computed from the BB intersection) ++ * % if myProcID computed the job (myProcID, procID) ++ * => send only 'interp source IDs' field values (i.e. IDs stored in _src_ids_zip_comp) ++ * % else (=we just sent mesh data to procID, but have never seen the matrix, i.e. matrix was computed remotely by procID) ++ * => send 'BB source IDs' set of field values (i.e. IDs stored in _sent_src_ids) ++ */ ++ if (procID == myProcID) ++ nbsend[procID] = 0; ++ else ++ if(find(_proc_ids_to_send_vector_st.begin(),_proc_ids_to_send_vector_st.end(),procID)!=_proc_ids_to_send_vector_st.end()) ++ { ++ MEDCouplingAutoRefCountObjectPtr vals; ++ if(_locator.isInMyTodoList(myProcID, procID)) ++ { ++ map >::const_iterator isItem11 = _src_ids_zip_comp.find(procID); ++ if (isItem11 == _src_ids_zip_comp.end()) ++ throw INTERP_KERNEL::Exception("OverlapMapping::multiply(): internal error: SEND: unexpected end iterator in _src_ids_zip_comp!"); ++ const vector & v = (*isItem11).second; ++ int sz = v.size(); ++ vals=fieldInput->getArray()->selectByTupleId(&(v[0]),&(v[0])+sz); ++ } ++ else ++ { ++ map < int, MEDCouplingAutoRefCountObjectPtr >::const_iterator isItem11 = _sent_src_ids.find( procID ); ++ if (isItem11 == _sent_src_ids.end()) ++ throw INTERP_KERNEL::Exception("OverlapMapping::multiply(): internal error: SEND: unexpected end iterator in _sent_src_ids!"); ++ vals=fieldInput->getArray()->selectByTupleId(*(*isItem11).second); ++ } ++ nbsend[procID] = vals->getNbOfElems(); ++ valsToSend.insert(valsToSend.end(),vals->getConstPointer(),vals->getConstPointer()+nbsend[procID]); ++ } ++ ++ /* RECEIVE: compute number of field values to be RECEIVED ++ * - for all proc 'procID' in group ++ * * if procID == myProcID, rcv nothing ++ * * elif 'procID' in _proc_ids_to_recv_vector_st (computed from BB intersec) ++ * % if myProcID computed the job (procID, myProcID) ++ * => receive full set ('BB source IDs') of field data from proc #procID which has never seen the matrix ++ * i.e. prepare to receive the numb in _nb_of_rcv_src_ids ++ * % else (=we did NOT compute the job, hence procID has, and knows the matrix) ++ * => receive 'interp source IDs' set of field values ++ */ ++ const std::vector< int > & _proc_ids_to_recv_vector_st = _the_matrix_st_source_proc_id; ++ if (procID == myProcID) ++ nbrecv[procID] = 0; ++ else ++ if(find(_proc_ids_to_recv_vector_st.begin(),_proc_ids_to_recv_vector_st.end(),procID)!=_proc_ids_to_recv_vector_st.end()) ++ { ++ if(_locator.isInMyTodoList(procID, myProcID)) ++ { ++ map ::const_iterator isItem11 = _nb_of_rcv_src_ids.find(procID); ++ if (isItem11 == _nb_of_rcv_src_ids.end()) ++ throw INTERP_KERNEL::Exception("OverlapMapping::multiply(): internal error: RCV: unexpected end iterator in _nb_of_rcv_src_ids!"); ++ nbrecv[procID] = (*isItem11).second; ++ } ++ else ++ { ++ map >::const_iterator isItem11 = _src_ids_zip_recv.find(procID); ++ if (isItem11 == _src_ids_zip_recv.end()) ++ throw INTERP_KERNEL::Exception("OverlapMapping::multiply(): internal error: RCV: unexpected end iterator in _src_ids_zip_recv!"); ++ nbrecv[procID] = (*isItem11).second.size()*nbOfCompo; ++ } ++ } + } ++ // Compute offsets in the sending/receiving array. + for(int i=1;i bigArr=new double[nbrecv2[grpSize-1]+nbrecv[grpSize-1]]; ++ ++#ifdef DEC_DEBUG ++ stringstream scout; ++ scout << "(" << myProcID << ") nbsend :" << nbsend[0] << "," << nbsend[1] << "," << nbsend[2] << "\n"; ++ scout << "(" << myProcID << ") nbrecv :" << nbrecv[0] << "," << nbrecv[1] << "," << nbrecv[2] << "\n"; ++ scout << "(" << myProcID << ") valsToSend: "; ++ for (int iii=0; iiigetArray()->fillWithZero(); + INTERP_KERNEL::AutoPtr tmp=new double[nbOfCompo]; - for(int i=0;i hit_cells = new bool[fieldOutput->getNumberOfTuples()]; ++ ++ for(vector::const_iterator itProc=_the_matrix_st_source_proc_id.begin(); itProc != _the_matrix_st_source_proc_id.end();itProc++) ++ // For each source processor corresponding to a locally held matrix: + { - if(nbrecv[i]>0) ++ int srcProcID = *itProc; ++ int id = distance(_the_matrix_st_source_proc_id.begin(),itProc); ++ const vector< SparseDoubleVec >& mat =_the_matrix_st[id]; ++ const vector< SparseDoubleVec >& deno = _the_deno_st[id]; ++ ++ /* FINAL MULTIPLICATION ++ * * if srcProcID == myProcID, local multiplication without any mapping ++ * => for all target cell ID 'tgtCellID' ++ * => for all src cell ID 'srcCellID' in the sparse vector ++ * => tgtFieldLocal[tgtCellID] += srcFieldLocal[srcCellID] * matrix[tgtCellID][srcCellID] / deno[tgtCellID][srcCellID] ++ */ ++ if (srcProcID == myProcID) ++ { ++ int nbOfTrgTuples=mat.size(); ++ double * targetBase = fieldOutput->getArray()->getPointer(); ++ for(int j=0; jgetArray()->getConstPointer(); ++ double * targetPt = targetBase+j*nbOfCompo; ++ for(SparseDoubleVec::const_iterator it3=mat1.begin();it3!=mat1.end();it3++,it5++) ++ { ++ // Apply the multiplication for all components: ++ double ratio = (*it3).second/(*it5).second; ++ transform(localSrcField+((*it3).first)*nbOfCompo, ++ localSrcField+((*it3).first+1)*nbOfCompo, ++ (double *)tmp, ++ bind2nd(multiplies(),ratio) ); ++ // Accumulate with current value: ++ transform((double *)tmp,(double *)tmp+nbOfCompo,targetPt,targetPt,plus()); ++ hit_cells[j] = true; ++ } ++ } ++ } ++ ++ if(nbrecv[srcProcID]<=0) // also covers the preceding 'if' ++ continue; ++ ++ /* * if something was received ++ * % if received matrix (=we didn't compute the job), this means that : ++ * 1. we sent part of our targetIDs to srcProcID before, so that srcProcId can do the computation. ++ * 2. srcProcID has sent us only the 'interp source IDs' field values ++ * => invert _src_ids_zip_recv -> 'revert_zip' ++ * => for all target cell ID 'tgtCellID' ++ * => mappedTgtID = _sent_trg_ids[srcProcID][tgtCellID] ++ * => for all src cell ID 'srcCellID' in the sparse vector ++ * => idx = revert_zip[srcCellID] ++ * => tgtFieldLocal[mappedTgtID] += rcvValue[srcProcID][idx] * matrix[tgtCellID][srcCellID] / deno[tgtCellID][srcCellID] ++ */ ++ if(!_locator.isInMyTodoList(srcProcID, myProcID)) + { - double *pt=fieldOutput->getArray()->getPointer(); - std::vector::const_iterator it=std::find(_the_matrix_st_source_proc_id.begin(),_the_matrix_st_source_proc_id.end(),i); - if(it==_the_matrix_st_source_proc_id.end()) - throw INTERP_KERNEL::Exception("Big problem !"); - int id=std::distance(_the_matrix_st_source_proc_id.begin(),it); - const std::vector< std::map >& mat=_the_matrix_st[id]; - const std::vector< std::map >& deno=_the_deno_st[id]; - std::vector::const_iterator isItem0=std::find(_trg_proc_st2.begin(),_trg_proc_st2.end(),i); - if(isItem0==_trg_proc_st2.end())//item1 of step2 main algo [ (0,1) computed on proc1 and Matrix-Vector on proc1 ] ++ // invert _src_ids_zip_recv ++ map revert_zip; ++ map >::const_iterator it11= _src_ids_zip_recv.find(srcProcID); ++ if (it11 == _src_ids_zip_recv.end()) ++ throw INTERP_KERNEL::Exception("OverlapMapping::multiply(): internal error: MULTIPLY: unexpected end iterator in _src_ids_zip_recv!"); ++ const vector & vec = (*it11).second; ++ int newId=0; ++ for(vector::const_iterator it=vec.begin();it!=vec.end();it++,newId++) ++ revert_zip[*it]=newId; ++ map < int, MEDCouplingAutoRefCountObjectPtr >::const_iterator isItem24 = _sent_trg_ids.find(srcProcID); ++ if (isItem24 == _sent_trg_ids.end()) ++ throw INTERP_KERNEL::Exception("OverlapMapping::multiply(): internal error: MULTIPLY: unexpected end iterator in _sent_trg_ids!"); ++ const DataArrayInt *tgrIdsDA = (*isItem24).second; ++ const int *tgrIds = tgrIdsDA->getConstPointer(); ++ ++ int nbOfTrgTuples=mat.size(); ++ double * targetBase = fieldOutput->getArray()->getPointer(); ++ for(int j=0;j& mat1=mat[j]; - const std::map& deno1=deno[j]; - std::map::const_iterator it4=deno1.begin(); - for(std::map::const_iterator it3=mat1.begin();it3!=mat1.end();it3++,it4++) - { - std::transform(bigArr+nbrecv2[i]+((*it3).first)*nbOfCompo,bigArr+nbrecv2[i]+((*it3).first+1)*(nbOfCompo),(double *)tmp,std::bind2nd(std::multiplies(),(*it3).second/(*it4).second)); - std::transform((double *)tmp,(double *)tmp+nbOfCompo,pt,pt,std::plus()); - } ++ map::const_iterator it4=revert_zip.find((*it3).first); ++ if(it4==revert_zip.end()) ++ throw INTERP_KERNEL::Exception("OverlapMapping::multiply(): internal error: MULTIPLY: unexpected end iterator in revert_zip!"); ++ double ratio = (*it3).second/(*it5).second; ++ transform(bigArr+nbrecv2[srcProcID]+((*it4).second)*nbOfCompo, ++ bigArr+nbrecv2[srcProcID]+((*it4).second+1)*nbOfCompo, ++ (double *)tmp, ++ bind2nd(multiplies(),ratio) ); ++ transform((double *)tmp,(double *)tmp+nbOfCompo,targetPt,targetPt,plus()); ++ hit_cells[tgrIds[j]] = true; + } + } - else - {//item0 of step2 main algo [ (2,1) computed on proc2 but Matrix-Vector on proc1 ] - double *pt=fieldOutput->getArray()->getPointer(); - std::map zipCor; - int id=std::distance(_src_ids_zip_proc_st2.begin(),std::find(_src_ids_zip_proc_st2.begin(),_src_ids_zip_proc_st2.end(),i)); - const std::vector zipIds=_src_ids_zip_st2[id]; - int newId=0; - for(std::vector::const_iterator it=zipIds.begin();it!=zipIds.end();it++,newId++) - zipCor[*it]=newId; - int id2=std::distance(_trg_proc_st2.begin(),std::find(_trg_proc_st2.begin(),_trg_proc_st2.end(),i)); - const DataArrayInt *tgrIds=_trg_ids_st2[id2]; - const int *tgrIds2=tgrIds->getConstPointer(); - int nbOfTrgTuples=mat.size(); - for(int j=0;j for all target cell ID 'tgtCellID' ++ * => for all src cell ID 'srcCellID' in the sparse vector ++ * => tgtFieldLocal[tgtCellID] += rcvValue[srcProcID][srcCellID] * matrix[tgtCellID][srcCellID] / deno[tgtCellID][srcCellID] ++ */ ++ { ++ // Same loop as in the case srcProcID == myProcID, except that instead of working on local field data, we work on bigArr ++ int nbOfTrgTuples=mat.size(); ++ double * targetBase = fieldOutput->getArray()->getPointer(); ++ for(int j=0;j& mat1=mat[j]; - const std::map& deno1=deno[j]; - std::map::const_iterator it5=deno1.begin(); - for(std::map::const_iterator it3=mat1.begin();it3!=mat1.end();it3++,it5++) - { - std::map::const_iterator it4=zipCor.find((*it3).first); - if(it4==zipCor.end()) - throw INTERP_KERNEL::Exception("Hmmmmm send e mail to anthony.geay@cea.fr !"); - std::transform(bigArr+nbrecv2[i]+((*it4).second)*nbOfCompo,bigArr+nbrecv2[i]+((*it4).second+1)*(nbOfCompo),(double *)tmp,std::bind2nd(std::multiplies(),(*it3).second/(*it5).second)); - std::transform((double *)tmp,(double *)tmp+nbOfCompo,pt+tgrIds2[j]*nbOfCompo,pt+tgrIds2[j]*nbOfCompo,std::plus()); - } ++ // Apply the multiplication for all components: ++ double ratio = (*it3).second/(*it5).second; ++ transform(bigArr+nbrecv2[srcProcID]+((*it3).first)*nbOfCompo, ++ bigArr+nbrecv2[srcProcID]+((*it3).first+1)*nbOfCompo, ++ (double *)tmp, ++ bind2nd(multiplies(),ratio)); ++ // Accumulate with current value: ++ transform((double *)tmp,(double *)tmp+nbOfCompo,targetPt,targetPt,plus()); ++ hit_cells[j] = true; + } + } + } + } ++ ++ // Fill in default values for cells which haven't been hit: ++ int i = 0; ++ for(bool * hit_cells_ptr=hit_cells; i< fieldOutput->getNumberOfTuples(); hit_cells_ptr++,i++) ++ if (!(*hit_cells_ptr)) ++ { ++ double * targetPt=fieldOutput->getArray()->getPointer(); ++ fill(targetPt+i*nbOfCompo, targetPt+(i+1)*nbOfCompo, default_val); ++ } +} + +/*! + * This method performs a transpose multiply of 'fieldInput' and put the result into 'fieldOutput'. + * 'fieldInput' is expected to be the targetfield and 'fieldOutput' the sourcefield. + */ +void OverlapMapping::transposeMultiply(const MEDCouplingFieldDouble *fieldInput, MEDCouplingFieldDouble *fieldOutput) +{ +} + +/*! - * This method should be called immediately after _the_matrix_st has been filled with remote computed matrix put in this proc for Matrix-Vector. - * This method computes for these matrix the minimal set of source ids corresponding to the source proc id. ++ * This method should be called immediately after _the_matrix_st has been filled with remote computed matrix ++ * put in this proc for Matrix-Vector. ++ * It fills _src_ids_zip_recv (see member doc) + */ - void OverlapMapping::updateZipSourceIdsForFuture() ++void OverlapMapping::fillSourceIdsZipReceivedForMultiply() +{ ++ /* When it is called, only the bits received from other processors (i.e. the remotely executed jobs) are in the ++ big matrix _the_matrix_st. */ ++ + CommInterface commInterface=_group.getCommInterface(); + int myProcId=_group.myRank(); + int nbOfMatrixRecveived=_the_matrix_st_source_proc_id.size(); + for(int i=0;i >& mat=_the_matrix_st[i]; - _src_ids_zip_proc_st2.push_back(curSrcProcId); - _src_ids_zip_st2.resize(_src_ids_zip_st2.size()+1); ++ const std::vector< SparseDoubleVec >& mat=_the_matrix_st[i]; + std::set s; - for(std::vector< std::map >::const_iterator it1=mat.begin();it1!=mat.end();it1++) - for(std::map::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) ++ for(std::vector< SparseDoubleVec >::const_iterator it1=mat.begin();it1!=mat.end();it1++) ++ for(SparseDoubleVec::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) + s.insert((*it2).first); - _src_ids_zip_st2.back().insert(_src_ids_zip_st2.back().end(),s.begin(),s.end()); ++ vector vec(s.begin(),s.end()); ++ _src_ids_zip_recv[curSrcProcId] = vec; + } + } +} + - // #include - - // void OverlapMapping::printTheMatrix() const - // { - // CommInterface commInterface=_group.getCommInterface(); - // const MPIProcessorGroup *group=static_cast(&_group); - // const MPI_Comm *comm=group->getComm(); - // int grpSize=_group.size(); - // int myProcId=_group.myRank(); - // std::cerr << "I am proc #" << myProcId << std::endl; - // int nbOfMat=_the_matrix_st.size(); - // std::cerr << "I do manage " << nbOfMat << "matrix : "<< std::endl; - // for(int i=0;i >& locMat=_the_matrix_st[i]; - // for(std::vector< std::map >::const_iterator it1=locMat.begin();it1!=locMat.end();it1++) - // { - // for(std::map::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) - // std::cerr << "(" << (*it2).first << "," << (*it2).second << "), "; - // std::cerr << std::endl; - // } - // } - // std::cerr << "*********" << std::endl; - // } ++#ifdef DEC_DEBUG ++ void OverlapMapping::printTheMatrix() const ++ { ++ CommInterface commInterface=_group.getCommInterface(); ++ const MPIProcessorGroup *group=static_cast(&_group); ++ const MPI_Comm *comm=group->getComm(); ++ int grpSize=_group.size(); ++ int myProcId=_group.myRank(); ++ std::stringstream oscerr; ++ int nbOfMat=_the_matrix_st.size(); ++ oscerr << "(" << myProcId << ") I hold " << nbOfMat << " matrix(ces) : "<< std::endl; ++ for(int i=0;i& locMat=_the_matrix_st[i]; ++ int j = 0; ++ for(std::vector< SparseDoubleVec >::const_iterator it1=locMat.begin();it1!=locMat.end();it1++, j++) ++ { ++ oscerr << " Target Cell #" << j; ++ for(SparseDoubleVec::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) ++ oscerr << " (" << (*it2).first << "," << (*it2).second << "), "; ++ oscerr << std::endl; ++ } ++ } ++ oscerr << "*********" << std::endl; ++ ++ // Hope this will be flushed in one go: ++ std::cerr << oscerr.str() << std::endl; ++// if(myProcId != 0) ++// MPI_Barrier(MPI_COMM_WORLD); ++ } ++ ++ void OverlapMapping::printMatrixesST() const ++ { ++ CommInterface commInterface=_group.getCommInterface(); ++ const MPIProcessorGroup *group=static_cast(&_group); ++ const MPI_Comm *comm=group->getComm(); ++ int grpSize=_group.size(); ++ int myProcId=_group.myRank(); ++ std::stringstream oscerr; ++ int nbOfMat=_matrixes_st.size(); ++ oscerr << "(" << myProcId << ") I hold " << nbOfMat << " LOCAL matrix(ces) : "<< std::endl; ++ for(int i=0;i& locMat=_matrixes_st[i]; ++ int j = 0; ++ for(std::vector< SparseDoubleVec >::const_iterator it1=locMat.begin();it1!=locMat.end();it1++, j++) ++ { ++ oscerr << " Target Cell #" << j; ++ for(SparseDoubleVec::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) ++ oscerr << " (" << (*it2).first << "," << (*it2).second << "), "; ++ oscerr << std::endl; ++ } ++ } ++ oscerr << "*********" << std::endl; ++ ++ // Hope this will be flushed in one go: ++ std::cerr << oscerr.str() << std::endl; ++ } ++ ++ void OverlapMapping::printDenoMatrix() const ++ { ++ CommInterface commInterface=_group.getCommInterface(); ++ const MPIProcessorGroup *group=static_cast(&_group); ++ const MPI_Comm *comm=group->getComm(); ++ int grpSize=_group.size(); ++ int myProcId=_group.myRank(); ++ std::stringstream oscerr; ++ int nbOfMat=_the_deno_st.size(); ++ oscerr << "(" << myProcId << ") I hold " << nbOfMat << " DENOMINATOR matrix(ces) : "<< std::endl; ++ for(int i=0;i& locMat=_the_deno_st[i]; ++ int j = 0; ++ for(std::vector< SparseDoubleVec >::const_iterator it1=locMat.begin();it1!=locMat.end();it1++, j++) ++ { ++ oscerr << " Target Cell #" << j; ++ for(SparseDoubleVec::const_iterator it2=(*it1).begin();it2!=(*it1).end();it2++) ++ oscerr << " (" << (*it2).first << "," << (*it2).second << "), "; ++ oscerr << std::endl; ++ } ++ } ++ oscerr << "*********" << std::endl; ++ ++ // Hope this will be flushed in one go: ++ std::cerr << oscerr.str() << std::endl; ++ } ++#endif diff --cc medtool/src/ParaMEDMEM/OverlapMapping.hxx index cfb06b1bb,000000000..ab9cb3139 mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEM/OverlapMapping.hxx +++ b/medtool/src/ParaMEDMEM/OverlapMapping.hxx @@@ -1,97 -1,0 +1,130 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// +// Author : Anthony Geay (CEA/DEN) + +#ifndef __OVERLAPMAPPING_HXX__ +#define __OVERLAPMAPPING_HXX__ + +#include "MEDCouplingAutoRefCountObjectPtr.hxx" ++#include "OverlapElementLocator.hxx" + +#include +#include ++//#define DEC_DEBUG + +namespace ParaMEDMEM +{ + class ProcessorGroup; + class DataArrayInt; + class MEDCouplingFieldDouble; + - /* ++ using namespace std; ++ typedef map SparseDoubleVec; ++ ++ /*! + * Internal class, not part of the public API. + * + * Used by the impl of OverlapInterpolationMatrix, plays an equivalent role than what the NxM_Mapping + * does for the InterpolationMatrix. - * + */ + class OverlapMapping + { + public: - OverlapMapping(const ProcessorGroup& group); ++ ++ OverlapMapping(const ProcessorGroup& group, const OverlapElementLocator& locator); + void keepTracksOfSourceIds(int procId, DataArrayInt *ids); + void keepTracksOfTargetIds(int procId, DataArrayInt *ids); - void addContributionST(const std::vector< std::map >& matrixST, const DataArrayInt *srcIds, int srcProcId, const DataArrayInt *trgIds, int trgProcId); - void prepare(const std::vector< std::vector >& procsInInteraction, int nbOfTrgElems); ++ void addContributionST(const vector< SparseDoubleVec >& matrixST, const DataArrayInt *srcIds, int srcProcId, const DataArrayInt *trgIds, int trgProcId); ++ void prepare(const vector< int >& procsToSendField, int nbOfTrgElems); + void computeDenoConservativeVolumic(int nbOfTuplesTrg); - void computeDenoGlobConstraint(); ++// void computeDenoIntegralGlobConstraint(); ++// void computeDenoIntegral(); ++ void computeDenoRevIntegral(const DataArrayDouble & targetAreas); + // - void multiply(const MEDCouplingFieldDouble *fieldInput, MEDCouplingFieldDouble *fieldOutput) const; ++ void multiply(const MEDCouplingFieldDouble *fieldInput, MEDCouplingFieldDouble *fieldOutput, double default_val) const; + void transposeMultiply(const MEDCouplingFieldDouble *fieldInput, MEDCouplingFieldDouble *fieldOutput); + private: + void serializeMatrixStep0ST(const int *nbOfElemsSrc, int *&bigArr, int *count, int *offsets, + int *countForRecv, int *offsetsForRecv) const; + int serializeMatrixStep1ST(const int *nbOfElemsSrc, const int *recvStep0, const int *countStep0, const int *offsStep0, + int *&bigArrI, double *&bigArrD, int *count, int *offsets, + int *countForRecv, int *offsForRecv) const; + void unserializationST(int nbOfTrgElems, const int *nbOfElemsSrcPerProc, const int *bigArrRecv, const int *bigArrRecvCounts, const int *bigArrRecvOffs, + const int *bigArrRecv2, const double *bigArrDRecv2, const int *bigArrRecv2Count, const int *bigArrRecv2Offs); + void finishToFillFinalMatrixST(); - void prepareIdsToSendST(); - void updateZipSourceIdsForFuture(); - //void printTheMatrix() const; ++ void fillSourceIdsZipReceivedForMultiply(); ++ ++#ifdef DEC_DEBUG ++ void printMatrixesST() const; ++ void printTheMatrix() const; ++ void printDenoMatrix() const; ++#endif + private: + const ProcessorGroup &_group; - //! vector of ids - std::vector< MEDCouplingAutoRefCountObjectPtr > _src_ids_st2;//item #1 - std::vector< int > _src_proc_st2;//item #1 - std::vector< MEDCouplingAutoRefCountObjectPtr > _trg_ids_st2;//item #0 - std::vector< int > _trg_proc_st2;//item #0 - std::vector< int > _nb_of_src_ids_proc_st2;//item #1 - std::vector< int > _src_ids_proc_st2;//item #1 - std::vector< std::vector > _src_ids_zip_st2;//same size as _src_ids_zip_proc_st2. Sorted. specifies for each id the corresponding ids to send. This is for item0 of Step2 of main algorithm - std::vector< int > _src_ids_zip_proc_st2; - //! vector of matrixes the first entry correspond to source proc id in _source_ids_st - std::vector< std::vector< std::map > > _matrixes_st; - std::vector< std::vector > _source_ids_st; - std::vector< int > _source_proc_id_st; - std::vector< std::vector > _target_ids_st; - std::vector< int > _target_proc_id_st; - //! the matrix for matrix-vector product. The first dimension the set of target procs that interacts with local source mesh. The second dimension correspond to nb of local source ids. - std::vector< std::vector< std::map > > _the_matrix_st; - std::vector< int > _the_matrix_st_source_proc_id; - std::vector< std::vector > _the_matrix_st_source_ids; - std::vector< std::vector< std::map > > _the_deno_st; - //! this attribute stores the proc ids that wait for data from this proc ids for matrix-vector computation - std::vector< int > _proc_ids_to_send_vector_st; - std::vector< int > _proc_ids_to_recv_vector_st; - //! this attribute is of size _group.size(); for each procId in _group _source_ids_to_send_st[procId] contains tupleId to send abroad - std::vector< std::vector > _source_ids_to_send_st; ++ const OverlapElementLocator& _locator; ++ ++ /**! Map of DAInt of cell identifiers. For a proc ID i, ++ * gives an old2new map for the local part of the source mesh that has been sent to proc#i, just based on the ++ * bounding box computation (this is potentially a larger set than what is finally in the interp matrix). ++ * Second member gives proc ID. */ ++ map < int, MEDCouplingAutoRefCountObjectPtr > _sent_src_ids; ++ ++ //! See _sent_src_ids. Same for target mesh. ++ map < int, MEDCouplingAutoRefCountObjectPtr > _sent_trg_ids; ++ ++ /**! Vector of matrixes (partial interpolation ratios), result of the LOCAL interpolator run. ++ * Indexing shared with _source_proc_id_st, and _target_proc_id_st. */ ++ vector< vector< SparseDoubleVec > > _matrixes_st; ++ //! See _matrixes_st - vec of source proc IDs ++ vector< int > _source_proc_id_st; ++ //! See _matrixes_st - vec of target proc IDs ++ vector< int > _target_proc_id_st; ++ ++ /**! Number of received source mesh IDs at mesh data exchange. ++ Counting the number of IDs suffices, as we just need this to prepare the receive side, when doing the final vector matrix multiplication. ++ First dimension is the remote proc ID from which we received. */ ++ map _nb_of_rcv_src_ids; ++ ++ /**! Specifies for each (target) remote proc ID (first dim of the map) the corresponding ++ * source cell IDs to use. ++ * This information is stored from the *locally* COMPuted matrices, and corresponds hence to field value that will need to ++ * sent later on, if this matrix bit itself is sent aways. */ ++ map > _src_ids_zip_comp; ++ ++ /**! Same idea as _src_ids_zip_comp above, but for RECEIVED matrix. */ ++ map > _src_ids_zip_recv; ++ ++ /**! THE matrix for matrix-vector product. The first dimension is indexed in the set of target procs ++ * that interacts with local source mesh. The second dim is the target cell ID. ++ * Same indexing as _the_matrix_st_source_proc_id and _the_deno_st. ++ * We don't use a map here to be more efficient in the final matrix-vector computation which requires the joint ++ * taversal of _the_matrix_st and _the_deno_st. ++ * This matrix is filled after receival from other procs, contrary to _matrixes_st which contains local computations.*/ ++ vector< vector< SparseDoubleVec > > _the_matrix_st; ++ //! See _the_matrix_st above. List of source proc IDs contributing to _the_matrix_st ++ vector< int > _the_matrix_st_source_proc_id; ++ // Denominators (computed from the numerator matrix). As for _the_matrix_st it is paired with _the_matrix_st_source_proc_id ++ vector< vector< SparseDoubleVec > > _the_deno_st; ++ ++ //! Proc IDs to which data will be sent (originating this current proc) for matrix-vector computation ++ vector< int > _proc_ids_to_send_vector_st; + }; +} + +#endif diff --cc medtool/src/ParaMEDMEMTest/CMakeLists.txt index 09fed6aad,000000000..90d84290d mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEMTest/CMakeLists.txt +++ b/medtool/src/ParaMEDMEMTest/CMakeLists.txt @@@ -1,136 -1,0 +1,136 @@@ +# Copyright (C) 2012-2015 CEA/DEN, EDF R&D +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +ADD_DEFINITIONS(${MPI_DEFINITIONS} ${CPPUNIT_DEFINITIONS}) + +INCLUDE_DIRECTORIES( + ${MPI_INCLUDE_DIRS} + ${CPPUNIT_INCLUDE_DIRS} + ${CMAKE_CURRENT_SOURCE_DIR}/../ParaMEDLoader + ${CMAKE_CURRENT_SOURCE_DIR}/../ParaMEDMEM + ${CMAKE_CURRENT_SOURCE_DIR}/../MEDLoader + ${CMAKE_CURRENT_SOURCE_DIR}/../MEDCoupling + ${CMAKE_CURRENT_SOURCE_DIR}/../INTERP_KERNEL + ${CMAKE_CURRENT_SOURCE_DIR}/../INTERP_KERNEL/Bases + ) + +SET(ParaMEDMEMTest_SOURCES + ParaMEDMEMTest.cxx + ParaMEDMEMTest_MPIProcessorGroup.cxx + ParaMEDMEMTest_BlockTopology.cxx + ParaMEDMEMTest_InterpKernelDEC.cxx + ParaMEDMEMTest_StructuredCoincidentDEC.cxx + ParaMEDMEMTest_ICoco.cxx + ParaMEDMEMTest_Gauthier1.cxx + ParaMEDMEMTest_FabienAPI.cxx + ParaMEDMEMTest_NonCoincidentDEC.cxx + ParaMEDMEMTest_OverlapDEC.cxx + MPIAccessDECTest.cxx + test_AllToAllDEC.cxx + test_AllToAllvDEC.cxx + test_AllToAllTimeDEC.cxx + test_AllToAllvTimeDEC.cxx + test_AllToAllvTimeDoubleDEC.cxx + MPIAccessTest.cxx + test_MPI_Access_Send_Recv.cxx + test_MPI_Access_Cyclic_Send_Recv.cxx + test_MPI_Access_SendRecv.cxx + test_MPI_Access_ISend_IRecv.cxx + test_MPI_Access_Cyclic_ISend_IRecv.cxx + test_MPI_Access_ISendRecv.cxx + test_MPI_Access_Probe.cxx + test_MPI_Access_IProbe.cxx + test_MPI_Access_Cancel.cxx + test_MPI_Access_Send_Recv_Length.cxx + test_MPI_Access_ISend_IRecv_Length.cxx + test_MPI_Access_ISend_IRecv_Length_1.cxx + test_MPI_Access_Time.cxx + test_MPI_Access_Time_0.cxx + test_MPI_Access_ISend_IRecv_BottleNeck.cxx + ) + +ADD_LIBRARY(ParaMEDMEMTest SHARED ${ParaMEDMEMTest_SOURCES}) +SET_TARGET_PROPERTIES(ParaMEDMEMTest PROPERTIES COMPILE_FLAGS "") - TARGET_LINK_LIBRARIES(ParaMEDMEMTest paramedmem paramedloader ${CPPUNIT_LIBRARIES}) ++TARGET_LINK_LIBRARIES(ParaMEDMEMTest paramedmem paramedloader medcouplingremapper ${CPPUNIT_LIBRARIES}) +INSTALL(TARGETS ParaMEDMEMTest DESTINATION ${MEDCOUPLING_INSTALL_LIBS}) + +SET(TESTSParaMEDMEM) +SET(TestParaMEDMEM_SOURCES + TestParaMEDMEM.cxx + ) +SET(TESTSParaMEDMEM ${TESTSParaMEDMEM} TestParaMEDMEM) + +SET(TestMPIAccessDEC_SOURCES + TestMPIAccessDEC.cxx + ) +SET(TESTSParaMEDMEM ${TESTSParaMEDMEM} TestMPIAccessDEC) + +SET(TestMPIAccess_SOURCES + TestMPIAccess.cxx + ) +SET(TESTSParaMEDMEM ${TESTSParaMEDMEM} TestMPIAccess) + +SET(test_perf_SOURCES + test_perf.cxx + ) +SET(TESTSParaMEDMEM ${TESTSParaMEDMEM} test_perf) + +IF(MPI2_IS_OK) + SET(ParaMEDMEMTestMPI2_1_SOURCES + MPI2Connector.cxx + ParaMEDMEMTestMPI2_1.cxx + ) + SET(TESTSParaMEDMEM ${TESTSParaMEDMEM} ParaMEDMEMTestMPI2_1) + + SET(ParaMEDMEMTestMPI2_2_SOURCES + MPI2Connector.cxx + ParaMEDMEMTestMPI2_2.cxx + ) + SET(TESTSParaMEDMEM ${TESTSParaMEDMEM} ParaMEDMEMTestMPI2_2) +ENDIF(MPI2_IS_OK) + +FOREACH(bintestparamem ${TESTSParaMEDMEM}) + ADD_EXECUTABLE(${bintestparamem} ${${bintestparamem}_SOURCES}) + TARGET_LINK_LIBRARIES(${bintestparamem} ParaMEDMEMTest) +ENDFOREACH(bintestparamem ${TESTSParaMEDMEM}) + +# Now add CMake tests - test_perf, ParaMEDMEMTestMPI2_1 and ParaMEDMEMTestMPI2_2 +# are left aside, as they are too specific +# +# -- some tests require 2, 3, 4 or 5 procs -- +ADD_TEST(NAME TestParaMEDMEM_Proc2 COMMAND ${MPIEXEC} -np 2 $) +ADD_TEST(NAME TestParaMEDMEM_Proc3 COMMAND ${MPIEXEC} -np 3 $) +ADD_TEST(NAME TestParaMEDMEM_Proc4 COMMAND ${MPIEXEC} -np 4 $) +ADD_TEST(NAME TestParaMEDMEM_Proc5 COMMAND ${MPIEXEC} -np 5 $) + +ADD_TEST(NAME TestMPIAccess_Proc2 COMMAND ${MPIEXEC} -np 2 $) +ADD_TEST(NAME TestMPIAccess_Proc3 COMMAND ${MPIEXEC} -np 3 $) + +ADD_TEST(NAME TestMPIAccessDEC_Proc4 COMMAND ${MPIEXEC} -np 4 $) + +# Installation rules +INSTALL(TARGETS ${TESTSParaMEDMEM} DESTINATION ${MEDCOUPLING_INSTALL_BINS}) +SET(COMMON_HEADERS_HXX + MPIMainTest.hxx + MPIAccessDECTest.hxx + MPIAccessTest.hxx + ParaMEDMEMTest.hxx + MPI2Connector.hxx +) +INSTALL(FILES ${COMMON_HEADERS_HXX} DESTINATION ${MEDCOUPLING_INSTALL_HEADERS}) diff --cc medtool/src/ParaMEDMEMTest/ParaMEDMEMTest.hxx index b0295a08f,000000000..7deb11dca mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEMTest/ParaMEDMEMTest.hxx +++ b/medtool/src/ParaMEDMEMTest/ParaMEDMEMTest.hxx @@@ -1,178 -1,0 +1,194 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#ifndef _ParaMEDMEMTEST_HXX_ +#define _ParaMEDMEMTEST_HXX_ + +#include + +#include +#include +#include +#include "mpi.h" + + +class ParaMEDMEMTest : public CppUnit::TestFixture +{ + CPPUNIT_TEST_SUITE( ParaMEDMEMTest ); - CPPUNIT_TEST(testMPIProcessorGroup_constructor); - CPPUNIT_TEST(testMPIProcessorGroup_boolean); - CPPUNIT_TEST(testMPIProcessorGroup_rank); - CPPUNIT_TEST(testBlockTopology_constructor); - CPPUNIT_TEST(testBlockTopology_serialize); - CPPUNIT_TEST(testInterpKernelDEC_1D); - CPPUNIT_TEST(testInterpKernelDEC_2DCurve); - CPPUNIT_TEST(testInterpKernelDEC_2D); - CPPUNIT_TEST(testInterpKernelDEC2_2D); - CPPUNIT_TEST(testInterpKernelDEC_2DP0P1); - CPPUNIT_TEST(testInterpKernelDEC_3D); - CPPUNIT_TEST(testInterpKernelDECNonOverlapp_2D_P0P0); - CPPUNIT_TEST(testInterpKernelDECNonOverlapp_2D_P0P1P1P0); - CPPUNIT_TEST(testInterpKernelDEC2DM1D_P0P0); - CPPUNIT_TEST(testInterpKernelDECPartialProcs); - CPPUNIT_TEST(testInterpKernelDEC3DSurfEmptyBBox); - CPPUNIT_TEST(testOverlapDEC1); - - CPPUNIT_TEST(testSynchronousEqualInterpKernelWithoutInterpNativeDEC_2D); - CPPUNIT_TEST(testSynchronousEqualInterpKernelWithoutInterpDEC_2D); - CPPUNIT_TEST(testSynchronousEqualInterpKernelDEC_2D); - CPPUNIT_TEST(testSynchronousFasterSourceInterpKernelDEC_2D); - CPPUNIT_TEST(testSynchronousSlowerSourceInterpKernelDEC_2D); - CPPUNIT_TEST(testSynchronousSlowSourceInterpKernelDEC_2D); - CPPUNIT_TEST(testSynchronousFastSourceInterpKernelDEC_2D); - CPPUNIT_TEST(testAsynchronousEqualInterpKernelDEC_2D); - CPPUNIT_TEST(testAsynchronousFasterSourceInterpKernelDEC_2D); - CPPUNIT_TEST(testAsynchronousSlowerSourceInterpKernelDEC_2D); - CPPUNIT_TEST(testAsynchronousSlowSourceInterpKernelDEC_2D); - CPPUNIT_TEST(testAsynchronousFastSourceInterpKernelDEC_2D); ++ CPPUNIT_TEST(testMPIProcessorGroup_constructor); // 1 and 2 procs ++ CPPUNIT_TEST(testMPIProcessorGroup_boolean); // 1 and 2 procs ++ CPPUNIT_TEST(testMPIProcessorGroup_rank); // >=2 procs ++ CPPUNIT_TEST(testBlockTopology_constructor); // >=2 procs ++ CPPUNIT_TEST(testBlockTopology_serialize); // 1 proc ++ CPPUNIT_TEST(testInterpKernelDEC_1D); // 5 procs ++ CPPUNIT_TEST(testInterpKernelDEC_2DCurve); // 5 procs ++ CPPUNIT_TEST(testInterpKernelDEC_2D); // 5 procs ++ CPPUNIT_TEST(testInterpKernelDEC2_2D); // 5 procs ++ CPPUNIT_TEST(testInterpKernelDEC_2DP0P1); // Not impl. ++ CPPUNIT_TEST(testInterpKernelDEC_3D); // 3 procs ++ CPPUNIT_TEST(testInterpKernelDECNonOverlapp_2D_P0P0); // 5 procs ++ CPPUNIT_TEST(testInterpKernelDECNonOverlapp_2D_P0P1P1P0); // 5 procs ++ CPPUNIT_TEST(testInterpKernelDEC2DM1D_P0P0); // 3 procs ++ CPPUNIT_TEST(testInterpKernelDECPartialProcs); // 3 procs ++ CPPUNIT_TEST(testInterpKernelDEC3DSurfEmptyBBox); // 3 procs ++ CPPUNIT_TEST(testOverlapDEC1); // 3 procs ++ CPPUNIT_TEST(testOverlapDEC1_bis); // 3 procs ++ CPPUNIT_TEST(testOverlapDEC1_ter); // 3 procs ++ CPPUNIT_TEST(testOverlapDEC2); // 3 procs ++ CPPUNIT_TEST(testOverlapDEC2_bis); // 3 procs ++ CPPUNIT_TEST(testOverlapDEC2_ter); // 3 procs ++ CPPUNIT_TEST(testOverlapDEC3); // 2 procs ++ CPPUNIT_TEST(testOverlapDEC4); // 2 procs ++ ++ CPPUNIT_TEST(testSynchronousEqualInterpKernelWithoutInterpNativeDEC_2D);// 5 procs ++ CPPUNIT_TEST(testSynchronousEqualInterpKernelWithoutInterpDEC_2D); // 5 procs ++ CPPUNIT_TEST(testSynchronousEqualInterpKernelDEC_2D); // 5 procs ++ CPPUNIT_TEST(testSynchronousFasterSourceInterpKernelDEC_2D); // 5 procs ++ CPPUNIT_TEST(testSynchronousSlowerSourceInterpKernelDEC_2D); // 5 procs ++ CPPUNIT_TEST(testSynchronousSlowSourceInterpKernelDEC_2D); // 5 procs ++ CPPUNIT_TEST(testSynchronousFastSourceInterpKernelDEC_2D); // 5 procs ++ CPPUNIT_TEST(testAsynchronousEqualInterpKernelDEC_2D); // 5 procs ++ CPPUNIT_TEST(testAsynchronousFasterSourceInterpKernelDEC_2D); // 5 procs ++ CPPUNIT_TEST(testAsynchronousSlowerSourceInterpKernelDEC_2D); // 5 procs ++ CPPUNIT_TEST(testAsynchronousSlowSourceInterpKernelDEC_2D); // 5 procs ++ CPPUNIT_TEST(testAsynchronousFastSourceInterpKernelDEC_2D); // 5 procs +#ifdef MED_ENABLE_FVM + //can be added again after FVM correction for 2D + // CPPUNIT_TEST(testNonCoincidentDEC_2D); + CPPUNIT_TEST(testNonCoincidentDEC_3D); +#endif - CPPUNIT_TEST(testStructuredCoincidentDEC); - CPPUNIT_TEST(testStructuredCoincidentDEC); - CPPUNIT_TEST(testICoco1); - CPPUNIT_TEST(testGauthier1); - CPPUNIT_TEST(testGauthier2); - CPPUNIT_TEST(testGauthier3); - CPPUNIT_TEST(testGauthier4); - CPPUNIT_TEST(testFabienAPI1); - CPPUNIT_TEST(testFabienAPI2); ++ CPPUNIT_TEST(testStructuredCoincidentDEC); // 5 procs ++ CPPUNIT_TEST(testICoco1); // 2 procs ++ CPPUNIT_TEST(testGauthier1); // 4 procs ++ CPPUNIT_TEST(testGauthier2); // >= 2 procs ++ CPPUNIT_TEST(testGauthier3); // 4 procs ++ CPPUNIT_TEST(testGauthier4); // 3 procs ++ CPPUNIT_TEST(testFabienAPI1); // 3 procs ++ CPPUNIT_TEST(testFabienAPI2); // 3 procs ++ + CPPUNIT_TEST_SUITE_END(); + +public: + + ParaMEDMEMTest():CppUnit::TestFixture(){} + ~ParaMEDMEMTest(){} + void setUp(){} + void tearDown(){} + void testMPIProcessorGroup_constructor(); + void testMPIProcessorGroup_boolean(); + void testMPIProcessorGroup_rank(); + void testBlockTopology_constructor(); + void testBlockTopology_serialize(); + void testInterpKernelDEC_1D(); + void testInterpKernelDEC_2DCurve(); + void testInterpKernelDEC_2D(); + void testInterpKernelDEC2_2D(); + void testInterpKernelDEC_2DP0P1(); + void testInterpKernelDEC_3D(); + void testInterpKernelDECNonOverlapp_2D_P0P0(); + void testInterpKernelDECNonOverlapp_2D_P0P1P1P0(); + void testInterpKernelDEC2DM1D_P0P0(); + void testInterpKernelDECPartialProcs(); + void testInterpKernelDEC3DSurfEmptyBBox(); + void testOverlapDEC1(); ++ void testOverlapDEC1_bis(); ++ void testOverlapDEC1_ter(); ++ void testOverlapDEC2(); ++ void testOverlapDEC2_bis(); ++ void testOverlapDEC2_ter(); ++ void testOverlapDEC3(); ++// void testOverlapDEC3_bis(); ++ void testOverlapDEC4(); +#ifdef MED_ENABLE_FVM + void testNonCoincidentDEC_2D(); + void testNonCoincidentDEC_3D(); +#endif + void testStructuredCoincidentDEC(); + void testSynchronousEqualInterpKernelWithoutInterpNativeDEC_2D(); + void testSynchronousEqualInterpKernelWithoutInterpDEC_2D(); + void testSynchronousEqualInterpKernelDEC_2D(); + void testSynchronousFasterSourceInterpKernelDEC_2D(); + void testSynchronousSlowerSourceInterpKernelDEC_2D(); + void testSynchronousSlowSourceInterpKernelDEC_2D(); + void testSynchronousFastSourceInterpKernelDEC_2D(); + + void testAsynchronousEqualInterpKernelDEC_2D(); + void testAsynchronousFasterSourceInterpKernelDEC_2D(); + void testAsynchronousSlowerSourceInterpKernelDEC_2D(); + void testAsynchronousSlowSourceInterpKernelDEC_2D(); + void testAsynchronousFastSourceInterpKernelDEC_2D(); + // + void testICoco1(); + void testGauthier1(); + void testGauthier2(); + void testGauthier3(); + void testGauthier4(); + void testFabienAPI1(); + void testFabienAPI2(); + + std::string getResourceFile( const std::string& ); + std::string getTmpDirectory(); + std::string makeTmpFile( const std::string&, const std::string& = "" ); + +private: +#ifdef MED_ENABLE_FVM + void testNonCoincidentDEC(const std::string& filename1, + const std::string& meshname1, + const std::string& filename2, + const std::string& meshname2, + int nbprocsource, double epsilon); +#endif + void testAsynchronousInterpKernelDEC_2D(double dtA, double tmaxA, + double dtB, double tmaxB, + bool WithPointToPoint, bool Asynchronous, bool WithInterp, const char *srcMeth, const char *targetMeth); + void testInterpKernelDEC_2D_(const char *srcMeth, const char *targetMeth); + void testInterpKernelDEC2_2D_(const char *srcMeth, const char *targetMeth); + void testInterpKernelDEC_3D_(const char *srcMeth, const char *targetMeth); ++ +}; + +// to automatically remove temporary files from disk +class ParaMEDMEMTest_TmpFilesRemover +{ +public: + ParaMEDMEMTest_TmpFilesRemover() {} + ~ParaMEDMEMTest_TmpFilesRemover(); + bool Register(const std::string theTmpFile); + +private: + std::set myTmpFiles; +}; + +/*! + * Tool to print array to stream. + */ +template +void ParaMEDMEMTest_DumpArray (std::ostream & stream, const T* array, const int length, const std::string text) +{ + stream << text << ": {"; + if (length > 0) { + stream << array[0]; + for (int i = 1; i < length; i++) { + stream << ", " << array[i]; + } + } + stream << "}" << std::endl; +} + +#endif diff --cc medtool/src/ParaMEDMEMTest/ParaMEDMEMTest_Gauthier1.cxx index cc97ede18,000000000..e11b5a944 mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEMTest/ParaMEDMEMTest_Gauthier1.cxx +++ b/medtool/src/ParaMEDMEMTest/ParaMEDMEMTest_Gauthier1.cxx @@@ -1,665 -1,0 +1,666 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "ParaMEDMEMTest.hxx" +#include + +#include "CommInterface.hxx" +#include "ProcessorGroup.hxx" +#include "MPIProcessorGroup.hxx" +#include "DEC.hxx" +#include "InterpKernelDEC.hxx" +#include "MEDCouplingUMesh.hxx" +#include "MEDCouplingFieldDouble.hxx" +#include "ParaMESH.hxx" +#include "ParaFIELD.hxx" +#include "ComponentTopology.hxx" +#include "BlockTopology.hxx" + +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace ParaMEDMEM; +using namespace ICoCo; + +void afficheGauthier1(const ParaFIELD& field, const double *vals, int lgth) +{ + const DataArrayDouble *valsOfField(field.getField()->getArray()); + CPPUNIT_ASSERT_EQUAL(lgth,valsOfField->getNumberOfTuples()); + for (int ele=0;elegetNumberOfTuples();ele++) + CPPUNIT_ASSERT_DOUBLES_EQUAL(vals[ele],valsOfField->getIJ(ele,0),1e-12); +} + +MEDCouplingUMesh *init_quadGauthier1(int is_master) +{ + MEDCouplingAutoRefCountObjectPtr m(MEDCouplingUMesh::New("champ_quad",2)); + MEDCouplingAutoRefCountObjectPtr coo(DataArrayDouble::New()); + if(is_master) + { + const double dataCoo[24]={0,0,0,1,0,0,0,0,1,1,0,1,0,1,0,1,1,0,0,1,1,1,1,1}; + coo->alloc(8,3); + std::copy(dataCoo,dataCoo+24,coo->getPointer()); + const int conn[8]={0,1,3,2,4,5,7,6}; + m->allocateCells(2); + m->insertNextCell(INTERP_KERNEL::NORM_QUAD4,4,conn); + m->insertNextCell(INTERP_KERNEL::NORM_QUAD4,4,conn+4); + } + else + { + coo->alloc(0,3); + m->allocateCells(0); + } + m->setCoords(coo); + return m.retn(); +} + +MEDCouplingUMesh *init_triangleGauthier1(int is_master) +{ + MEDCouplingAutoRefCountObjectPtr m(MEDCouplingUMesh::New("champ_triangle",2)); + MEDCouplingAutoRefCountObjectPtr coo(DataArrayDouble::New()); + if(is_master) + { + const double dataCoo[24]={0,0,0,1,0,0,0,0,1,1,0,1,0,1,0,1,1,0,0,1,1,1,1,1}; + coo->alloc(8,3); + std::copy(dataCoo,dataCoo+24,coo->getPointer()); + const int conn[12]={0,1,2,1,2,3,4,5,7,4,6,7}; + m->allocateCells(2); + for(int i=0;i<4;i++) + m->insertNextCell(INTERP_KERNEL::NORM_TRI3,3,conn+3*i); + } + else + { + coo->alloc(0,3); + m->allocateCells(0); + } + m->setCoords(coo); + return m.retn(); +} + + +void ParaMEDMEMTest::testGauthier1() +{ + int num_cas=0; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD,&rank); + MPI_Comm_size(MPI_COMM_WORLD,&size); + + int is_master=0; + + CommInterface comm; + set emetteur_ids; + set recepteur_ids; + emetteur_ids.insert(0); + if(size!=4) + return; + recepteur_ids.insert(1); + if (size >2) + recepteur_ids.insert(2); + if (size >2) + emetteur_ids.insert(3); + if ((rank==0)||(rank==1)) + is_master=1; + + MPIProcessorGroup recepteur_group(comm,recepteur_ids); + MPIProcessorGroup emetteur_group(comm,emetteur_ids); + + string cas; + if (recepteur_group.containsMyRank()) + { + cas="recepteur"; + //freopen("recpeteur.out","w",stdout); + //freopen("recepteur.err","w",stderr); + } + else + { + cas="emetteur"; + // freopen("emetteur.out","w",stdout); + //freopen("emetteur.err","w",stderr); + } + double expected[8][4]={ + {1.,1.,1.,1.}, + {40., 40., 1., 1.}, + {1.,1.,1e200,1e200}, + {40.,1.,1e200,1e200}, + {1.,1.,1.,1.}, + {40.,1.,1.,1.}, + {1.,1.,1e200,1e200}, + {20.5,1.,1e200,1e200} + }; + int expectedLgth[8]={4,4,2,2,4,4,2,2}; + + for (int send=0;send<2;send++) + for (int rec=0;rec<2;rec++) + { + InterpKernelDEC dec_emetteur(emetteur_group, recepteur_group); + ParaMEDMEM::ParaFIELD *champ_emetteur(0),*champ_recepteur(0); + ParaMEDMEM::ParaMESH *paramesh(0); + MEDCouplingAutoRefCountObjectPtr mesh; + dec_emetteur.setOrientation(2); + if (send==0) + { + mesh=init_quadGauthier1(is_master); + } + else + { + mesh=init_triangleGauthier1(is_master); + } + paramesh=new ParaMEDMEM::ParaMESH(mesh,recepteur_group.containsMyRank()?recepteur_group:emetteur_group,"emetteur mesh"); + ParaMEDMEM::ComponentTopology comptopo; + champ_emetteur=new ParaMEDMEM::ParaFIELD(ON_CELLS,ONE_TIME,paramesh,comptopo); + champ_emetteur->getField()->setNature(ConservativeVolumic); + champ_emetteur->setOwnSupport(true); + if (rec==0) + { + mesh=init_triangleGauthier1(is_master); + } + else + { + mesh=init_quadGauthier1(is_master); + } + paramesh=new ParaMEDMEM::ParaMESH(mesh,recepteur_group.containsMyRank()?recepteur_group:emetteur_group,"recepteur mesh"); + champ_recepteur=new ParaMEDMEM::ParaFIELD(ON_CELLS,ONE_TIME,paramesh,comptopo); + champ_recepteur->getField()->setNature(ConservativeVolumic); + champ_recepteur->setOwnSupport(true); + if (cas=="emetteur") + { + champ_emetteur->getField()->getArray()->fillWithValue(1.); + } + + + MPI_Barrier(MPI_COMM_WORLD); + + //clock_t clock0= clock (); + int compti=0; + + bool init=true; // first time step ?? + bool stop=false; + //boucle sur les pas de quads + while (!stop) { + + compti++; + //clock_t clocki= clock (); + //cout << compti << " CLOCK " << (clocki-clock0)*1.e-6 << endl; + for (int non_unif=0;non_unif<2;non_unif++) + { + if (cas=="emetteur") + { + if (non_unif) + if(rank!=3) + champ_emetteur->getField()->getArray()->setIJ(0,0,40); + } + //bool ok=false; // Is the time interval successfully solved ? + + // Loop on the time interval tries + if(1) { + + + if (cas=="emetteur") + dec_emetteur.attachLocalField(champ_emetteur); + else + dec_emetteur.attachLocalField(champ_recepteur); + + + if(init) dec_emetteur.synchronize(); + init=false; + + if (cas=="emetteur") { + // affiche(champ_emetteur); + dec_emetteur.sendData(); + } + else if (cas=="recepteur") + { + dec_emetteur.recvData(); + if (is_master) + afficheGauthier1(*champ_recepteur,expected[num_cas],expectedLgth[num_cas]); + } + else + throw 0; + MPI_Barrier(MPI_COMM_WORLD); + } + stop=true; + num_cas++; + } + } + delete champ_emetteur; + delete champ_recepteur; + } +} + +void ParaMEDMEMTest::testGauthier2() +{ ++ std::cout << "testGauthier2\n"; + double valuesExpected1[2]={0.,0.}; + double valuesExpected2[2]={0.95,0.970625}; + + double valuesExpected30[]={0., 0., 0.05, 0., 0., 0.15, 0., 0., 0.25, 0., 0., 0.35, 0., 0., 0.45, 0., 0., 0.55, 0., 0., 0.65, 0., 0., 0.75, 0., 0., 0.85, 0., 0., 0.95}; + double valuesExpected31[]={0., 0., 0.029375, 0., 0., 0.029375, 0., 0., 0.1, 0., 0., 0.1, 0., 0., 0.2, 0., 0., 0.2, 0., 0., 0.3, 0., 0., 0.3, 0., 0., 0.4, 0., 0., 0.4, 0., 0., 0.5, 0., 0., 0.5, 0., 0., 0.6, 0., 0., 0.6, 0., 0., 0.7, 0., 0., 0.7, 0., 0., 0.8, 0., 0., 0.8, 0., 0., 0.9, 0., 0., 0.9, 0., 0., 0.970625, 0., 0., 0.970625 }; + + double *valuesExpected3[2]={valuesExpected30,valuesExpected31}; + + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD,&rank); + MPI_Comm_size(MPI_COMM_WORLD,&size); + if (size <2) + return ; + CommInterface comm; + set Genepi_ids; + set entree_chaude_ids; + Genepi_ids.insert(0); + for (int i=1;i mesh(MEDCouplingUMesh::New("mesh",2)); + MEDCouplingAutoRefCountObjectPtr arr(DataArrayDouble::New()); arr->alloc(63,3); + const double cooData[189]={0.,0.,0.,0.5,0.,0.,0.5,0.05,0.,0.,0.1,0.,0.5,0.1,0.,0.5,0.15,0.,0.,0.2,0.,0.5,0.2,0.,0.5,0.25,0.,0.,0.3,0.,0.5,0.3,0.,0.5,0.35,0.,0.,0.4,0.,0.5,0.4,0.,0.5,0.45,0.,0.,0.5,0.,0.5,0.5,0.,0.5,0.55,0.,0.,0.6,0.,0.5,0.6,0.,0.5,0.65,0.,0.,0.7,0.,0.5,0.7,0.,0.5,0.75,0.,0.,0.8,0.,0.5,0.8,0.,0.5,0.85,0.,0.,0.9,0.,0.5,0.9,0.,0.5,0.95,0.,1.,0.,0.,1.,0.1,0.,1.,0.2,0.,1.,0.3,0.,1.,0.4,0.,1.,0.5,0.,1.,0.6,0.,1.,0.7,0.,1.,0.8,0.,1.,0.9,0.,1.,0.05,0.,1.,0.15,0.,1.,0.25,0.,1.,0.35,0.,1.,0.45,0.,1.,0.55,0.,1.,0.65,0.,1.,0.75,0.,1.,0.85,0.,1.,0.95,0.,1.,1.,0.,0.,1.,0.,0.5,1.,0.,0.,0.05,0.,0.,0.15,0.,0.,0.25,0.,0.,0.35,0.,0.,0.45,0.,0.,0.55,0.,0.,0.65,0.,0.,0.75,0.,0.,0.85,0.,0.,0.95,0.}; + std::copy(cooData,cooData+189,arr->getPointer()); + mesh->setCoords(arr); + mesh->allocateCells(80); + const int conn[240]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,2,1,31,5,4,32,8,7,33,11,10,34,14,13,35,17,16,36,20,19,37,23,22,38,26,25,39,29,28,30,40,2,31,41,5,32,42,8,33,43,11,34,44,14,35,45,17,36,46,20,37,47,23,38,48,26,39,49,29,31,2,40,32,5,41,33,8,42,34,11,43,35,14,44,36,17,45,37,20,46,38,23,47,39,26,48,50,29,49,3,2,4,6,5,7,9,8,10,12,11,13,15,14,16,18,17,19,21,20,22,24,23,25,27,26,28,51,29,52,31,4,2,32,7,5,33,10,8,34,13,11,35,16,14,36,19,17,37,22,20,38,25,23,39,28,26,50,52,29,0,2,53,3,5,54,6,8,55,9,11,56,12,14,57,15,17,58,18,20,59,21,23,60,24,26,61,27,29,62,3,53,2,6,54,5,9,55,8,12,56,11,15,57,14,18,58,17,21,59,20,24,60,23,27,61,26,51,62,29}; + for(int i=0;i<80;i++) + mesh->insertNextCell(INTERP_KERNEL::NORM_TRI3,3,conn+3*i); + MEDCouplingAutoRefCountObjectPtr f(MEDCouplingFieldDouble::New(ON_NODES,ONE_TIME)); + const double valsOfField[189]={0.,0.,0.,0.,0.,0.,0.,0.,0.05,0.,0.,0.1,0.,0.,0.1,0.,0.,0.15,0.,0.,0.2,0.,0.,0.2,0.,0.,0.25,0.,0.,0.3,0.,0.,0.3,0.,0.,0.35,0.,0.,0.4,0.,0.,0.4,0.,0.,0.45,0.,0.,0.5,0.,0.,0.5,0.,0.,0.55,0.,0.,0.6,0.,0.,0.6,0.,0.,0.65,0.,0.,0.7,0.,0.,0.7,0.,0.,0.75,0.,0.,0.8,0.,0.,0.8,0.,0.,0.85,0.,0.,0.9,0.,0.,0.9,0.,0.,0.95,0.,0.,0.,0.,0.,0.1,0.,0.,0.2,0.,0.,0.3,0.,0.,0.4,0.,0.,0.5,0.,0.,0.6,0.,0.,0.7,0.,0.,0.8,0.,0.,0.9,0.,0.,0.05,0.,0.,0.15,0.,0.,0.25,0.,0.,0.35,0.,0.,0.45,0.,0.,0.55,0.,0.,0.65,0.,0.,0.75,0.,0.,0.85,0.,0.,0.95,0.,0.,1.,0.,0.,1.,0.,0.,1.,0.,0.,0.05,0.,0.,0.15,0.,0.,0.25,0.,0.,0.35,0.,0.,0.45,0.,0.,0.55,0.,0.,0.65,0.,0.,0.75,0.,0.,0.85,0.,0.,0.95}; + f->setMesh(mesh); f->setName("VITESSE_P1_OUT"); + arr=DataArrayDouble::New(); arr->alloc(63,3); + std::copy(valsOfField,valsOfField+189,arr->getPointer()); + f->setArray(arr); f->setNature(ConservativeVolumic); + ParaMEDMEM::ParaMESH *paramesh(new ParaMEDMEM::ParaMESH(mesh,entree_chaude_group,"emetteur mesh")); + vitesse=new ParaMEDMEM::ParaFIELD(f,paramesh,entree_chaude_group); + vitesse->setOwnSupport(true); + dec_vit_in_chaude.setMethod("P1"); + } + else + { + MEDCouplingAutoRefCountObjectPtr mesh(MEDCouplingUMesh::New("mesh",2)); + MEDCouplingAutoRefCountObjectPtr arr(DataArrayDouble::New()); arr->alloc(22,3); + const double cooData[66]={0,0,0,1,0,0,0,0.1,0,1,0.1,0,0,0.2,0,1,0.2,0,0,0.3,0,1,0.3,0,0,0.4,0,1,0.4,0,0,0.5,0,1,0.5,0,0,0.6,0,1,0.6,0,0,0.7,0,1,0.7,0,0,0.8,0,1,0.8,0,0,0.9,0,1,0.9,0,0,1,0,1,1,0}; + std::copy(cooData,cooData+66,arr->getPointer()); + mesh->setCoords(arr); + mesh->allocateCells(10); + const int conn[40]={0,1,3,2,2,3,5,4,4,5,7,6,6,7,9,8,8,9,11,10,10,11,13,12,12,13,15,14,14,15,17,16,16,17,19,18,18,19,21,20}; + for(int i=0;i<10;i++) + mesh->insertNextCell(INTERP_KERNEL::NORM_QUAD4,4,conn+4*i); + MEDCouplingAutoRefCountObjectPtr f(MEDCouplingFieldDouble::New(type==0?ON_CELLS:ON_NODES,ONE_TIME)); + f->setMesh(mesh); f->setName("vitesse_in_chaude"); + arr=DataArrayDouble::New(); arr->alloc(f->getNumberOfTuplesExpected()*3); arr->fillWithZero(); arr->rearrange(3); + f->setArray(arr); f->setNature(ConservativeVolumic); + ParaMEDMEM::ParaMESH *paramesh(new ParaMEDMEM::ParaMESH(mesh,Genepi_group,"recepteur mesh")); + vitesse=new ParaMEDMEM::ParaFIELD(f,paramesh,Genepi_group); + vitesse->setOwnSupport(true); + dec_vit_in_chaude.setMethod(f->getDiscretization()->getRepr()); + } + + dec_vit_in_chaude.attachLocalField(vitesse); + + dec_vit_in_chaude.synchronize(); + + + // Envois - receptions + if (entree_chaude_group.containsMyRank()) + { + dec_vit_in_chaude.sendData(); + } + else + { + dec_vit_in_chaude.recvData(); + } + if ( !entree_chaude_group.containsMyRank() ) + { + double pmin=1e38, pmax=-1e38; + const double *p(vitesse->getField()->getArray()->begin()); + for(std::size_t i=0;igetField()->getArray()->getNbOfElems();i++,p++) + { + if (*ppmax) pmax=*p; + } + CPPUNIT_ASSERT_DOUBLES_EQUAL(valuesExpected1[type],pmin,1e-12); + CPPUNIT_ASSERT_DOUBLES_EQUAL(valuesExpected2[type],pmax,1e-12); + + int nbCompo(vitesse->getField()->getNumberOfComponents()); + p=vitesse->getField()->getArray()->begin(); + for(int i=0;igetField()->getNumberOfTuples();i++) + for(int c=0;c emetteur_ids; + set recepteur_ids; + emetteur_ids.insert(0); + if(size!=4) + return; + recepteur_ids.insert(1); + if (size >2) + recepteur_ids.insert(2); + if (size >2) + emetteur_ids.insert(3); + if ((rank==0)||(rank==1)) + is_master=1; + + MPIProcessorGroup recepteur_group(comm,recepteur_ids); + MPIProcessorGroup emetteur_group(comm,emetteur_ids); + + string cas; + if (recepteur_group.containsMyRank()) + { + cas="recepteur"; + //freopen("recpeteur.out","w",stdout); + //freopen("recepteur.err","w",stderr); + } + else + { + cas="emetteur"; + // freopen("emetteur.out","w",stdout); + //freopen("emetteur.err","w",stderr); + } + double expected[8][4]={ + {1.,1.,1.,1.}, + {40., 40., 1., 1.}, + {1.,1.,1e200,1e200}, + {40.,1.,1e200,1e200}, + {1.,1.,1.,1.}, + {40.,1.,1.,1.}, + {1.,1.,1e200,1e200}, + {20.5,1.,1e200,1e200} + }; + int expectedLgth[8]={4,4,2,2,4,4,2,2}; + + for (int send=0;send<2;send++) + for (int rec=0;rec<2;rec++) + { + std::vector decu(1); + decu[0]=InterpKernelDEC(emetteur_group,recepteur_group); + InterpKernelDEC& dec_emetteur=decu[0]; + ParaMEDMEM::ParaFIELD *champ_emetteur(0),*champ_recepteur(0); + ParaMEDMEM::ParaMESH *paramesh(0); + MEDCouplingAutoRefCountObjectPtr mesh; + dec_emetteur.setOrientation(2); + if (send==0) + { + mesh=init_quadGauthier1(is_master); + } + else + { + mesh=init_triangleGauthier1(is_master); + } + paramesh=new ParaMEDMEM::ParaMESH(mesh,recepteur_group.containsMyRank()?recepteur_group:emetteur_group,"emetteur mesh"); + ParaMEDMEM::ComponentTopology comptopo; + champ_emetteur=new ParaMEDMEM::ParaFIELD(ON_CELLS,ONE_TIME,paramesh,comptopo); + champ_emetteur->getField()->setNature(ConservativeVolumic); + champ_emetteur->setOwnSupport(true); + if (rec==0) + { + mesh=init_triangleGauthier1(is_master); + } + else + { + mesh=init_quadGauthier1(is_master); + } + paramesh=new ParaMEDMEM::ParaMESH(mesh,recepteur_group.containsMyRank()?recepteur_group:emetteur_group,"recepteur mesh"); + champ_recepteur=new ParaMEDMEM::ParaFIELD(ON_CELLS,ONE_TIME,paramesh,comptopo); + champ_recepteur->getField()->setNature(ConservativeVolumic); + champ_recepteur->setOwnSupport(true); + if (cas=="emetteur") + { + champ_emetteur->getField()->getArray()->fillWithValue(1.); + } + + + MPI_Barrier(MPI_COMM_WORLD); + + //clock_t clock0= clock (); + int compti=0; + + bool init=true; // first time step ?? + bool stop=false; + //boucle sur les pas de quads + while (!stop) { + + compti++; + //clock_t clocki= clock (); + //cout << compti << " CLOCK " << (clocki-clock0)*1.e-6 << endl; + for (int non_unif=0;non_unif<2;non_unif++) + { + if (cas=="emetteur") + { + if (non_unif) + if(rank!=3) + champ_emetteur->getField()->getArray()->setIJ(0,0,40); + } + //bool ok=false; // Is the time interval successfully solved ? + + // Loop on the time interval tries + if(1) { + + + if (cas=="emetteur") + dec_emetteur.attachLocalField(champ_emetteur); + else + dec_emetteur.attachLocalField(champ_recepteur); + + + if(init) dec_emetteur.synchronize(); + init=false; + + if (cas=="emetteur") { + // affiche(champ_emetteur); + dec_emetteur.sendData(); + } + else if (cas=="recepteur") + { + dec_emetteur.recvData(); + if (is_master) + afficheGauthier1(*champ_recepteur,expected[num_cas],expectedLgth[num_cas]); + } + else + throw 0; + MPI_Barrier(MPI_COMM_WORLD); + } + stop=true; + num_cas++; + } + } + delete champ_emetteur; + delete champ_recepteur; + } +} + +/*! + * This test is the parallel version of MEDCouplingBasicsTest.test3D1DOnP1P0_1 test. + */ +void ParaMEDMEMTest::testGauthier4() +{ + // + const double sourceCoords[19*3]={0.5,0.5,0.1,0.5,0.5,1.2,0.5,0.5,1.6,0.5,0.5,1.8,0.5,0.5,2.43,0.5,0.5,2.55,0.5,0.5,4.1,0.5,0.5,4.4,0.5,0.5,4.9,0.5,0.5,5.1,0.5,0.5,7.6,0.5,0.5,7.7,0.5,0.5,8.2,0.5,0.5,8.4,0.5,0.5,8.6,0.5,0.5,8.8,0.5,0.5,9.2,0.5,0.5,9.6,0.5,0.5,11.5}; + const int sourceConn[18*2]={0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18}; + const double sourceVals[19]={0.49,2.8899999999999997,7.29,13.69,22.09,32.49,44.89,59.29,75.69,94.09, 114.49,136.89,161.29,187.69,216.09,246.49,278.89,313.29,349.69}; + const double targetCoords0[20*3]={0.,0.,0.,1.,0.,0.,0.,1.,0.,1.,1.,0.,0.,0.,1.,1.,0.,1.,0.,1.,1.,1.,1.,1.,0.,0.,2.,1.,0.,2.,0.,1.,2.,1.,1.,2.,0.,0.,3.,1.,0.,3.,0.,1.,3.,1.,1.,3.,0.,0.,4.,1.,0.,4.,0.,1.,4.,1.,1.,4.}; + const int targetConn0[8*4]={1,0,2,3,5,4,6,7,5,4,6,7,9,8,10,11,9,8,10,11,13,12,14,15,13,12,14,15,17,16,18,19}; + const double targetCoords1[28*3]={0.,0.,4.,1.,0.,4.,0.,1.,4.,1.,1.,4.,0.,0.,5.,1.,0.,5.,0.,1.,5.,1.,1.,5.,0.,0.,6.,1.,0.,6.,0.,1.,6.,1.,1.,6.,0.,0.,7.,1.,0.,7.,0.,1.,7.,1.,1.,7.,0.,0.,8.,1.,0.,8.,0.,1.,8.,1.,1.,8.,0.,0.,9.,1.,0.,9.,0.,1.,9.,1.,1.,9.,0.,0.,10.,1.,0.,10.,0.,1.,10.,1.,1.,10.}; + const int targetConn1[8*6]={1,0,2,3,5,4,6,7,5,4,6,7,9,8,10,11,9,8,10,11,13,12,14,15,13,12,14,15,17,16,18,19,17,16,18,19,21,20,22,23,21,20,22,23,25,24,26,27}; + // + int size; + int rank; + MPI_Comm_size(MPI_COMM_WORLD,&size); + MPI_Comm_rank(MPI_COMM_WORLD,&rank); + // + if(size!=3) + return ; + int nproc_source = 1; + set self_procs; + set procs_source; + set procs_target; + + for (int i=0; icontainsMyRank()) + { + std::ostringstream stream; stream << "sourcemesh2D proc " << rank; + mesh=MEDCouplingUMesh::New(stream.str().c_str(),1); + mesh->allocateCells(); + for(int i=0;i<18;i++) + mesh->insertNextCell(INTERP_KERNEL::NORM_SEG2,2,sourceConn+2*i); + mesh->finishInsertingCells(); + DataArrayDouble *myCoords=DataArrayDouble::New(); + myCoords->alloc(19,3); + std::copy(sourceCoords,sourceCoords+19*3,myCoords->getPointer()); + mesh->setCoords(myCoords); + myCoords->decrRef(); + paramesh=new ParaMESH(mesh,*source_group,"source mesh"); + ParaMEDMEM::ComponentTopology comptopo; + parafield = new ParaFIELD(ON_NODES,NO_TIME,paramesh,comptopo); + double *value=parafield->getField()->getArray()->getPointer(); + std::copy(sourceVals,sourceVals+19,value); + } + else + { + if(rank==1) + { + std::ostringstream stream; stream << "targetmesh2D proc " << rank-nproc_source; + mesh=MEDCouplingUMesh::New(stream.str().c_str(),3); + mesh->allocateCells(); + for(int i=0;i<4;i++) + mesh->insertNextCell(INTERP_KERNEL::NORM_HEXA8,8,targetConn0+8*i); + mesh->finishInsertingCells(); + DataArrayDouble *myCoords=DataArrayDouble::New(); + myCoords->alloc(20,3); + std::copy(targetCoords0,targetCoords0+20*3,myCoords->getPointer()); + mesh->setCoords(myCoords); + myCoords->decrRef(); + paramesh=new ParaMESH (mesh,*target_group,"target mesh"); + ParaMEDMEM::ComponentTopology comptopo; + parafield = new ParaFIELD(ON_CELLS,NO_TIME,paramesh, comptopo); + } + else if(rank==2) + { + std::ostringstream stream; stream << "targetmesh2D proc " << rank-nproc_source; + mesh=MEDCouplingUMesh::New(stream.str().c_str(),3); + mesh->allocateCells(); + for(int i=0;i<6;i++) + mesh->insertNextCell(INTERP_KERNEL::NORM_HEXA8,8,targetConn1+8*i); + mesh->finishInsertingCells(); + DataArrayDouble *myCoords=DataArrayDouble::New(); + myCoords->alloc(28,3); + std::copy(targetCoords1,targetCoords1+28*3,myCoords->getPointer()); + mesh->setCoords(myCoords); + myCoords->decrRef(); + paramesh=new ParaMESH (mesh,*target_group,"target mesh"); + ParaMEDMEM::ComponentTopology comptopo; + parafield = new ParaFIELD(ON_CELLS,NO_TIME,paramesh, comptopo); + } + } + //test 1 - primaire -> secondaire + ParaMEDMEM::InterpKernelDEC dec(*source_group,*target_group); + dec.setIntersectionType(INTERP_KERNEL::PointLocator); + parafield->getField()->setNature(ConservativeVolumic);//very important + if (source_group->containsMyRank()) + { + dec.setMethod("P1"); + dec.attachLocalField(parafield); + dec.synchronize(); + dec.setForcedRenormalization(false); + dec.sendData(); + } + else + { + dec.setMethod("P0"); + dec.attachLocalField(parafield); + dec.synchronize(); + dec.setForcedRenormalization(false); + dec.recvData(); + const double *res(parafield->getField()->getArray()->getConstPointer()); + if(rank==1) + { + const double expected0[4]={0.49,7.956666666666667,27.29,0.}; + for(int i=0;i<4;i++) + CPPUNIT_ASSERT_DOUBLES_EQUAL(expected0[i],res[i],1e-13); + } + else + { + const double expected1[6]={59.95666666666667,94.09,0.,125.69,202.89,296.09}; + for(int i=0;i<6;i++) + CPPUNIT_ASSERT_DOUBLES_EQUAL(expected1[i],res[i],1e-13); + } + } + MPI_Barrier(MPI_COMM_WORLD); + if (source_group->containsMyRank()) + { + dec.recvData(); + const double expected2[19]={0.49,7.956666666666667,7.956666666666667,7.956666666666667,27.29,27.29,59.95666666666667,59.95666666666667,59.95666666666667,94.09,125.69,125.69,202.89,202.89,202.89,202.89,296.09,296.09,0.}; + const double *res(parafield->getField()->getArray()->getConstPointer()); + for(int i=0;i<19;i++) + CPPUNIT_ASSERT_DOUBLES_EQUAL(expected2[i],res[i],1e-13); + } + else + { + dec.sendData(); + } + delete parafield; + mesh->decrRef(); + delete paramesh; + delete self_group; + delete target_group; + delete source_group; + // + MPI_Barrier(MPI_COMM_WORLD); +} diff --cc medtool/src/ParaMEDMEMTest/ParaMEDMEMTest_OverlapDEC.cxx index c7a610461,000000000..f6b14cf49 mode 100644,000000..100644 --- a/medtool/src/ParaMEDMEMTest/ParaMEDMEMTest_OverlapDEC.cxx +++ b/medtool/src/ParaMEDMEMTest/ParaMEDMEMTest_OverlapDEC.cxx @@@ -1,212 -1,0 +1,704 @@@ +// Copyright (C) 2007-2015 CEA/DEN, EDF R&D +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +// + +#include "ParaMEDMEMTest.hxx" +#include + +#include "CommInterface.hxx" +#include "ProcessorGroup.hxx" +#include "MPIProcessorGroup.hxx" +#include "Topology.hxx" +#include "OverlapDEC.hxx" +#include "ParaMESH.hxx" +#include "ParaFIELD.hxx" +#include "ComponentTopology.hxx" + +#include "MEDCouplingUMesh.hxx" + +#include + - void ParaMEDMEMTest::testOverlapDEC1() - { - std::string srcM("P0"); - std::string targetM("P0"); - int size; - int rank; - MPI_Comm_size(MPI_COMM_WORLD,&size); - MPI_Comm_rank(MPI_COMM_WORLD,&rank); ++using namespace std; + - if (size != 3) return ; - - int nproc = 3; - std::set procs; - - for (int i=0; i MUMesh; ++typedef MEDCouplingAutoRefCountObjectPtr MFDouble; ++typedef MEDCouplingAutoRefCountObjectPtr DADouble; ++ ++//void ParaMEDMEMTest::testOverlapDEC_LMEC_seq() ++//{ ++// // T_SC_Trio_src.med -- "SupportOf_" ++// // T_SC_Trio_dst.med -- "SupportOf_T_SC_Trio" ++// // h_TH_Trio_src.med -- "SupportOf_" ++// // h_TH_Trio_dst.med -- "SupportOf_h_TH_Trio" ++// string rep("/export/home/adrien/support/antoine_LMEC/"); ++// string src_mesh_nam(rep + string("T_SC_Trio_src.med")); ++// string tgt_mesh_nam(rep + string("T_SC_Trio_dst.med")); ++//// string src_mesh_nam(rep + string("h_TH_Trio_src.med")); ++//// string tgt_mesh_nam(rep + string("h_TH_Trio_dst.med")); ++// MUMesh src_mesh=MEDLoader::ReadUMeshFromFile(src_mesh_nam,"SupportOf_",0); ++// MUMesh tgt_mesh=MEDLoader::ReadUMeshFromFile(tgt_mesh_nam,"SupportOf_T_SC_Trio",0); ++//// MUMesh tgt_mesh=MEDLoader::ReadUMeshFromFile(tgt_mesh_nam,"SupportOf_h_TH_Trio",0); ++// ++// MFDouble srcField = MEDCouplingFieldDouble::New(ON_CELLS, ONE_TIME); ++// srcField->setMesh(src_mesh); ++// DataArrayDouble * dad = DataArrayDouble::New(); dad->alloc(src_mesh->getNumberOfCells(),1); ++// dad->fillWithValue(1.0); ++// srcField->setArray(dad); ++// srcField->setNature(ConservativeVolumic); ++// ++// MEDCouplingRemapper remap; ++// remap.setOrientation(2); // always consider surface intersections as absolute areas. ++// remap.prepare(src_mesh, tgt_mesh, "P0P0"); ++// MFDouble tgtField = remap.transferField(srcField, 1.0e+300); ++// tgtField->setName("result"); ++// string out_nam(rep + string("adrien.med")); ++// MEDLoader::WriteField(out_nam,tgtField, true); ++// cout << "wrote: " << out_nam << "\n"; ++// double integ1 = 0.0, integ2 = 0.0; ++// srcField->integral(true, &integ1); ++// tgtField->integral(true, &integ2); ++//// tgtField->reprQuickOverview(cout); ++// CPPUNIT_ASSERT_DOUBLES_EQUAL(integ1,integ2,1e-8); ++// ++// dad->decrRef(); ++//} ++// ++//void ParaMEDMEMTest::testOverlapDEC_LMEC_para() ++//{ ++// using namespace ParaMEDMEM; ++// ++// int size; ++// int rank; ++// MPI_Comm_size(MPI_COMM_WORLD,&size); ++// MPI_Comm_rank(MPI_COMM_WORLD,&rank); ++// ++// if (size != 1) return ; ++// ++// int nproc = 1; ++// std::set procs; ++// ++// for (int i=0; isetMesh(src_mesh); ++// DataArrayDouble * dad = DataArrayDouble::New(); dad->alloc(src_mesh->getNumberOfCells(),1); ++// dad->fillWithValue(1.0); ++// srcField->setArray(dad); ++// srcField->setNature(ConservativeVolumic); ++// ++// ComponentTopology comptopo; ++// parameshS = new ParaMESH(src_mesh,*dec.getGroup(),"source mesh"); ++// parafieldS = new ParaFIELD(ON_CELLS,ONE_TIME,parameshS,comptopo); ++// parafieldS->getField()->setNature(ConservativeVolumic);//IntegralGlobConstraint ++// parafieldS->getField()->setArray(dad); ++// ++// // **** TARGET ++// parameshT=new ParaMESH(tgt_mesh,*dec.getGroup(),"target mesh"); ++// parafieldT=new ParaFIELD(ON_CELLS,ONE_TIME,parameshT,comptopo); ++// parafieldT->getField()->setNature(ConservativeVolumic);//IntegralGlobConstraint ++// parafieldT->getField()->getArray()->fillWithValue(1.0e300); ++//// valsT[0]=7.; ++// } ++// dec.setOrientation(2); ++// dec.attachSourceLocalField(parafieldS); ++// dec.attachTargetLocalField(parafieldT); ++// dec.synchronize(); ++// dec.sendRecvData(true); ++// // ++// if(rank==0) ++// { ++// double integ1 = 0.0, integ2 = 0.0; ++// MEDCouplingFieldDouble * tgtField; ++// ++// srcField->integral(true, &integ1); ++// tgtField = parafieldT->getField(); ++//// tgtField->reprQuickOverview(cout); ++// tgtField->integral(true, &integ2); ++// tgtField->setName("result"); ++// string out_nam(rep + string("adrien_para.med")); ++// MEDLoader::WriteField(out_nam,tgtField, true); ++// cout << "wrote: " << out_nam << "\n"; ++// CPPUNIT_ASSERT_DOUBLES_EQUAL(integ1,integ2,1e-8); ++// } ++// delete parafieldS; ++// delete parafieldT; ++// delete parameshS; ++// delete parameshT; ++// ++// MPI_Barrier(MPI_COMM_WORLD); ++//} ++// ++void prepareData1(int rank, NatureOfField nature, ++ MEDCouplingFieldDouble *& fieldS, MEDCouplingFieldDouble *& fieldT) ++{ + if(rank==0) + { + const double coordsS[10]={0.,0.,0.5,0.,1.,0.,0.,0.5,0.5,0.5}; + const double coordsT[6]={0.,0.,1.,0.,1.,1.}; - meshS=ParaMEDMEM::MEDCouplingUMesh::New(); ++ MUMesh meshS=MEDCouplingUMesh::New(); + meshS->setMeshDimension(2); - ParaMEDMEM::DataArrayDouble *myCoords=ParaMEDMEM::DataArrayDouble::New(); ++ DataArrayDouble *myCoords=DataArrayDouble::New(); + myCoords->alloc(5,2); + std::copy(coordsS,coordsS+10,myCoords->getPointer()); + meshS->setCoords(myCoords); + myCoords->decrRef(); + int connS[7]={0,3,4,1, 1,4,2}; + meshS->allocateCells(2); + meshS->insertNextCell(INTERP_KERNEL::NORM_QUAD4,4,connS); + meshS->insertNextCell(INTERP_KERNEL::NORM_TRI3,3,connS+4); + meshS->finishInsertingCells(); - ParaMEDMEM::ComponentTopology comptopo; - parameshS=new ParaMEDMEM::ParaMESH(meshS,*dec.getGrp(),"source mesh"); - parafieldS=new ParaMEDMEM::ParaFIELD(ParaMEDMEM::ON_CELLS,ParaMEDMEM::NO_TIME,parameshS,comptopo); - parafieldS->getField()->setNature(ParaMEDMEM::ConservativeVolumic);//IntegralGlobConstraint - double *valsS=parafieldS->getField()->getArray()->getPointer(); ++ fieldS = MEDCouplingFieldDouble::New(ON_CELLS,NO_TIME); ++ DADouble arr = DataArrayDouble::New(); arr->alloc(meshS->getNumberOfCells(), 1); ++ fieldS->setMesh(meshS); fieldS->setArray(arr); ++ fieldS->setNature(nature); ++ double *valsS=fieldS->getArray()->getPointer(); + valsS[0]=7.; valsS[1]=8.; + // - meshT=ParaMEDMEM::MEDCouplingUMesh::New(); ++ MUMesh meshT=MEDCouplingUMesh::New(); + meshT->setMeshDimension(2); - myCoords=ParaMEDMEM::DataArrayDouble::New(); ++ myCoords=DataArrayDouble::New(); + myCoords->alloc(3,2); + std::copy(coordsT,coordsT+6,myCoords->getPointer()); + meshT->setCoords(myCoords); + myCoords->decrRef(); + int connT[3]={0,2,1}; + meshT->allocateCells(1); + meshT->insertNextCell(INTERP_KERNEL::NORM_TRI3,3,connT); + meshT->finishInsertingCells(); - parameshT=new ParaMEDMEM::ParaMESH(meshT,*dec.getGrp(),"target mesh"); - parafieldT=new ParaMEDMEM::ParaFIELD(ParaMEDMEM::ON_CELLS,ParaMEDMEM::NO_TIME,parameshT,comptopo); - parafieldT->getField()->setNature(ParaMEDMEM::ConservativeVolumic);//IntegralGlobConstraint - double *valsT=parafieldT->getField()->getArray()->getPointer(); ++ fieldT = MEDCouplingFieldDouble::New(ON_CELLS,NO_TIME); ++ DADouble arr2 = DataArrayDouble::New(); arr2->alloc(meshT->getNumberOfCells(), 1); ++ fieldT->setMesh(meshT); fieldT->setArray(arr2); ++ fieldT->setNature(nature); ++ double *valsT=fieldT->getArray()->getPointer(); + valsT[0]=7.; + } + // + if(rank==1) + { + const double coordsS[10]={1.,0.,0.5,0.5,1.,0.5,0.5,1.,1.,1.}; + const double coordsT[6]={0.,0.,0.5,0.5,0.,1.}; - meshS=ParaMEDMEM::MEDCouplingUMesh::New(); ++ MUMesh meshS=MEDCouplingUMesh::New(); + meshS->setMeshDimension(2); - ParaMEDMEM::DataArrayDouble *myCoords=ParaMEDMEM::DataArrayDouble::New(); ++ DataArrayDouble *myCoords=DataArrayDouble::New(); + myCoords->alloc(5,2); + std::copy(coordsS,coordsS+10,myCoords->getPointer()); + meshS->setCoords(myCoords); + myCoords->decrRef(); + int connS[7]={0,1,2, 1,3,4,2}; + meshS->allocateCells(2); + meshS->insertNextCell(INTERP_KERNEL::NORM_TRI3,3,connS); + meshS->insertNextCell(INTERP_KERNEL::NORM_QUAD4,4,connS+3); + meshS->finishInsertingCells(); - ParaMEDMEM::ComponentTopology comptopo; - parameshS=new ParaMEDMEM::ParaMESH(meshS,*dec.getGrp(),"source mesh"); - parafieldS=new ParaMEDMEM::ParaFIELD(ParaMEDMEM::ON_CELLS,ParaMEDMEM::NO_TIME,parameshS,comptopo); - parafieldS->getField()->setNature(ParaMEDMEM::ConservativeVolumic);//IntegralGlobConstraint - double *valsS=parafieldS->getField()->getArray()->getPointer(); ++ fieldS = MEDCouplingFieldDouble::New(ON_CELLS,NO_TIME); ++ DADouble arr = DataArrayDouble::New(); arr->alloc(meshS->getNumberOfCells(), 1); ++ fieldS->setMesh(meshS); fieldS->setArray(arr); ++ fieldS->setNature(nature); ++ double *valsS=fieldS->getArray()->getPointer(); + valsS[0]=9.; valsS[1]=11.; + // - meshT=ParaMEDMEM::MEDCouplingUMesh::New(); ++ MUMesh meshT=MEDCouplingUMesh::New(); + meshT->setMeshDimension(2); - myCoords=ParaMEDMEM::DataArrayDouble::New(); ++ myCoords=DataArrayDouble::New(); + myCoords->alloc(3,2); + std::copy(coordsT,coordsT+6,myCoords->getPointer()); + meshT->setCoords(myCoords); + myCoords->decrRef(); + int connT[3]={0,2,1}; + meshT->allocateCells(1); + meshT->insertNextCell(INTERP_KERNEL::NORM_TRI3,3,connT); + meshT->finishInsertingCells(); - parameshT=new ParaMEDMEM::ParaMESH(meshT,*dec.getGrp(),"target mesh"); - parafieldT=new ParaMEDMEM::ParaFIELD(ParaMEDMEM::ON_CELLS,ParaMEDMEM::NO_TIME,parameshT,comptopo); - parafieldT->getField()->setNature(ParaMEDMEM::ConservativeVolumic);//IntegralGlobConstraint - double *valsT=parafieldT->getField()->getArray()->getPointer(); ++ fieldT = MEDCouplingFieldDouble::New(ON_CELLS,NO_TIME); ++ DADouble arr2 = DataArrayDouble::New(); arr2->alloc(meshT->getNumberOfCells(), 1); ++ fieldT->setMesh(meshT); fieldT->setArray(arr2); ++ fieldT->setNature(nature); ++ double *valsT=fieldT->getArray()->getPointer(); + valsT[0]=8.; + } + // + if(rank==2) + { + const double coordsS[8]={0.,0.5, 0.5,0.5, 0.,1., 0.5,1.}; + const double coordsT[6]={0.5,0.5,0.,1.,1.,1.}; - meshS=ParaMEDMEM::MEDCouplingUMesh::New(); ++ MUMesh meshS=MEDCouplingUMesh::New(); + meshS->setMeshDimension(2); - ParaMEDMEM::DataArrayDouble *myCoords=ParaMEDMEM::DataArrayDouble::New(); ++ DataArrayDouble *myCoords=DataArrayDouble::New(); + myCoords->alloc(4,2); + std::copy(coordsS,coordsS+8,myCoords->getPointer()); + meshS->setCoords(myCoords); + myCoords->decrRef(); + int connS[4]={0,2,3,1}; + meshS->allocateCells(1); + meshS->insertNextCell(INTERP_KERNEL::NORM_QUAD4,4,connS); + meshS->finishInsertingCells(); - ParaMEDMEM::ComponentTopology comptopo; - parameshS=new ParaMEDMEM::ParaMESH(meshS,*dec.getGrp(),"source mesh"); - parafieldS=new ParaMEDMEM::ParaFIELD(ParaMEDMEM::ON_CELLS,ParaMEDMEM::NO_TIME,parameshS,comptopo); - parafieldS->getField()->setNature(ParaMEDMEM::ConservativeVolumic);//IntegralGlobConstraint - double *valsS=parafieldS->getField()->getArray()->getPointer(); ++ fieldS = MEDCouplingFieldDouble::New(ON_CELLS,NO_TIME); ++ DADouble arr = DataArrayDouble::New(); arr->alloc(meshS->getNumberOfCells(), 1); ++ fieldS->setMesh(meshS); fieldS->setArray(arr); ++ fieldS->setNature(nature); ++ double *valsS=fieldS->getArray()->getPointer(); + valsS[0]=10.; + // - meshT=ParaMEDMEM::MEDCouplingUMesh::New(); ++ MUMesh meshT=MEDCouplingUMesh::New(); + meshT->setMeshDimension(2); - myCoords=ParaMEDMEM::DataArrayDouble::New(); ++ myCoords=DataArrayDouble::New(); + myCoords->alloc(3,2); + std::copy(coordsT,coordsT+6,myCoords->getPointer()); + meshT->setCoords(myCoords); + myCoords->decrRef(); + int connT[3]={0,1,2}; + meshT->allocateCells(1); + meshT->insertNextCell(INTERP_KERNEL::NORM_TRI3,3,connT); + meshT->finishInsertingCells(); - parameshT=new ParaMEDMEM::ParaMESH(meshT,*dec.getGrp(),"target mesh"); - parafieldT=new ParaMEDMEM::ParaFIELD(ParaMEDMEM::ON_CELLS,ParaMEDMEM::NO_TIME,parameshT,comptopo); - parafieldT->getField()->setNature(ParaMEDMEM::ConservativeVolumic);//IntegralGlobConstraint - double *valsT=parafieldT->getField()->getArray()->getPointer(); ++ fieldT = MEDCouplingFieldDouble::New(ON_CELLS,NO_TIME); ++ DADouble arr2 = DataArrayDouble::New(); arr2->alloc(meshT->getNumberOfCells(), 1); ++ fieldT->setMesh(meshT); fieldT->setArray(arr2); ++ fieldT->setNature(nature); ++ double *valsT=fieldT->getArray()->getPointer(); + valsT[0]=9.; + } ++} ++ ++void prepareData2_buildOneSquare(MEDCouplingUMesh* & meshS_0, MEDCouplingUMesh* & meshT_0) ++{ ++ const double coords[10] = {0.0,0.0, 0.0,1.0, 1.0,1.0, 1.0,0.0, 0.5,0.5}; ++ meshS_0 = MEDCouplingUMesh::New("source", 2); ++ DataArrayDouble *myCoords=DataArrayDouble::New(); ++ myCoords->alloc(5,2); ++ std::copy(coords,coords+10,myCoords->getPointer()); ++ meshS_0->setCoords(myCoords); myCoords->decrRef(); ++ int connS[4]={0,1,2,3}; ++ meshS_0->allocateCells(2); ++ meshS_0->insertNextCell(INTERP_KERNEL::NORM_QUAD4,4,connS); ++ // ++ meshT_0 = MEDCouplingUMesh::New("target", 2); ++ myCoords=DataArrayDouble::New(); ++ myCoords->alloc(5,2); ++ std::copy(coords,coords+10,myCoords->getPointer()); ++ meshT_0->setCoords(myCoords); ++ myCoords->decrRef(); ++ int connT[12]={0,1,4, 1,2,4, 2,3,4, 3,0,4}; ++ meshT_0->allocateCells(4); ++ meshT_0->insertNextCell(INTERP_KERNEL::NORM_TRI3,3,connT); ++ meshT_0->insertNextCell(INTERP_KERNEL::NORM_TRI3,3,connT+3); ++ meshT_0->insertNextCell(INTERP_KERNEL::NORM_TRI3,3,connT+6); ++ meshT_0->insertNextCell(INTERP_KERNEL::NORM_TRI3,3,connT+9); ++} ++ ++/** ++ * Prepare five (detached) QUAD4 disposed like this: ++ * (0) (1) (2) ++ * (3) (4) ++ * ++ * On the target side the global mesh is identical except that each QUAD4 is split in 4 TRI3 (along the diagonals). ++ * This is a case for two procs: ++ * - proc #0 has source squares 0,1,2 and target squares 0,3 (well, sets of TRI3s actually) ++ * - proc #1 has source squares 3,4 and target squares 1,2,4 ++ */ ++void prepareData2(int rank, ProcessorGroup * grp, NatureOfField nature, ++ MEDCouplingUMesh *& meshS, MEDCouplingUMesh *& meshT, ++ ParaMESH*& parameshS, ParaMESH*& parameshT, ++ ParaFIELD*& parafieldS, ParaFIELD*& parafieldT, ++ bool stripPartOfSource=false, ++ int fieldCompoNum=1) ++{ ++ MEDCouplingUMesh *meshS_0 = 0, *meshT_0 = 0; ++ prepareData2_buildOneSquare(meshS_0, meshT_0); ++ ++ if(rank==0) ++ { ++ const double tr1[] = {1.5, 0.0}; ++ MEDCouplingUMesh *meshS_1 = static_cast(meshS_0->deepCpy()); ++ meshS_1->translate(tr1); ++ const double tr2[] = {3.0, 0.0}; ++ MEDCouplingUMesh *meshS_2 = static_cast(meshS_0->deepCpy()); ++ meshS_2->translate(tr2); ++ ++ std::vector vec; ++ vec.push_back(meshS_0);vec.push_back(meshS_1); ++ if (!stripPartOfSource) ++ vec.push_back(meshS_2); ++ meshS = MEDCouplingUMesh::MergeUMeshes(vec); ++ meshS_1->decrRef(); meshS_2->decrRef(); ++ ++ ComponentTopology comptopo(fieldCompoNum); ++ parameshS=new ParaMESH(meshS, *grp,"source mesh"); ++ parafieldS=new ParaFIELD(ON_CELLS,ONE_TIME,parameshS,comptopo); ++ parafieldS->getField()->setNature(nature); ++ double *valsS=parafieldS->getField()->getArray()->getPointer(); ++ for(int i=0; i < fieldCompoNum; i++) ++ { ++ valsS[i] = 1. * (10^i); ++ valsS[fieldCompoNum+i] = 2. * (10^i); ++ if (!stripPartOfSource) ++ { ++ valsS[2*fieldCompoNum+i] = 3. * (10^i); ++ } ++ } ++ ++ // ++ const double tr3[] = {0.0, -1.5}; ++ MEDCouplingUMesh *meshT_3 = static_cast(meshT_0->deepCpy()); ++ meshT_3->translate(tr3); ++ vec.clear(); ++ vec.push_back(meshT_0);vec.push_back(meshT_3); ++ meshT = MEDCouplingUMesh::MergeUMeshes(vec); ++ meshT_3->decrRef(); ++ ++ parameshT=new ParaMESH(meshT,*grp,"target mesh"); ++ parafieldT=new ParaFIELD(ON_CELLS,ONE_TIME,parameshT,comptopo); ++ parafieldT->getField()->setNature(nature); ++ } ++ // ++ if(rank==1) ++ { ++ const double tr3[] = {0.0, -1.5}; ++ MEDCouplingUMesh *meshS_3 = static_cast(meshS_0->deepCpy()); ++ meshS_3->translate(tr3); ++ const double tr4[] = {1.5, -1.5}; ++ MEDCouplingUMesh *meshS_4 = static_cast(meshS_0->deepCpy()); ++ meshS_4->translate(tr4); ++ ++ std::vector vec; ++ vec.push_back(meshS_3);vec.push_back(meshS_4); ++ meshS = MEDCouplingUMesh::MergeUMeshes(vec); ++ meshS_3->decrRef(); meshS_4->decrRef(); ++ ++ ComponentTopology comptopo(fieldCompoNum); ++ parameshS=new ParaMESH(meshS, *grp,"source mesh"); ++ parafieldS=new ParaFIELD(ON_CELLS,ONE_TIME,parameshS,comptopo); ++ parafieldS->getField()->setNature(nature); ++ double *valsS=parafieldS->getField()->getArray()->getPointer(); ++ for(int i=0; i < fieldCompoNum; i++) ++ { ++ valsS[i] = 4. * (10^i); ++ valsS[fieldCompoNum+i] = 5. * (10^i); ++ } ++ ++ // ++ const double tr5[] = {1.5, 0.0}; ++ MEDCouplingUMesh *meshT_1 = static_cast(meshT_0->deepCpy()); ++ meshT_1->translate(tr5); ++ const double tr6[] = {3.0, 0.0}; ++ MEDCouplingUMesh *meshT_2 = static_cast(meshT_0->deepCpy()); ++ meshT_2->translate(tr6); ++ const double tr7[] = {1.5, -1.5}; ++ MEDCouplingUMesh *meshT_4 = static_cast(meshT_0->deepCpy()); ++ meshT_4->translate(tr7); ++ ++ vec.clear(); ++ vec.push_back(meshT_1);vec.push_back(meshT_2);vec.push_back(meshT_4); ++ meshT = MEDCouplingUMesh::MergeUMeshes(vec); ++ meshT_1->decrRef(); meshT_2->decrRef(); meshT_4->decrRef(); ++ ++ parameshT=new ParaMESH(meshT,*grp,"target mesh"); ++ parafieldT=new ParaFIELD(ON_CELLS,ONE_TIME,parameshT,comptopo); ++ parafieldT->getField()->setNature(nature); ++ } ++ meshS_0->decrRef(); ++ meshT_0->decrRef(); ++} ++ ++/*! Test case from the official doc of the OverlapDEC. ++ * WARNING: bounding boxes might be tweaked here to make the case more interesting (i.e. to avoid an all to all exchange ++ * between all procs). ++ */ ++void testOverlapDEC_generic(int workSharingAlgo, double bbAdj) ++{ ++ int size, rank; ++ MPI_Comm_size(MPI_COMM_WORLD,&size); ++ MPI_Comm_rank(MPI_COMM_WORLD,&rank); ++ // char hostname[256]; ++ // printf("(%d) PID %d on localhost ready for attach\n", rank, getpid()); ++ // fflush(stdout); ++ ++// if (rank == 0) ++// { ++// int i=1, j=0; ++// while (i!=0) ++// j=2; ++// } ++ ++ if (size != 3) return ; ++ int nproc = 3; ++ std::set procs; ++ for (int i=0; igetArray()->getIJ(0,0),1e-12); ++ } ++ if(rank==1) ++ { ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(8.5,mcfieldT->getArray()->getIJ(0,0),1e-12); ++ } ++ if(rank==2) ++ { ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(10.5,mcfieldT->getArray()->getIJ(0,0),1e-12); ++ } ++ ++ mcfieldS->decrRef(); ++ mcfieldT->decrRef(); ++ ++ MPI_Barrier(MPI_COMM_WORLD); ++} ++ ++void ParaMEDMEMTest::testOverlapDEC1() ++{ ++ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ++ * HACK ON BOUNDING BOX TO MAKE THIS CASE SIMPLE AND USABLE IN DEBUG ++ * Bounding boxes are slightly smaller than should be, thus localizing the work to be done ++ * and avoiding every proc talking to everyone else. ++ * Obviously this is NOT a good idea to do this in production code :-) ++ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ++ */ ++ testOverlapDEC_generic(0,-1.0e-12); ++} ++ ++void ParaMEDMEMTest::testOverlapDEC1_bis() ++{ ++ // Same BB hack as above ++ testOverlapDEC_generic(1,-1.0e-12); ++} ++ ++void ParaMEDMEMTest::testOverlapDEC1_ter() ++{ ++ // Same BB hack as above ++ testOverlapDEC_generic(2, -1.0e-12); ++} ++ ++ ++/*! ++ * Same as testOverlapDEC1() but with regular bounding boxes. If you're looking for a nice debug case, ++ * testOverlapDEC1() is identical in terms of geometry and field values, and more appropriate. ++ */ ++void ParaMEDMEMTest::testOverlapDEC2() ++{ ++ testOverlapDEC_generic(0,1.0e-12); ++} ++ ++void ParaMEDMEMTest::testOverlapDEC2_bis() ++{ ++ testOverlapDEC_generic(1,1.0e-12); ++} ++ ++void ParaMEDMEMTest::testOverlapDEC2_ter() ++{ ++ testOverlapDEC_generic(2,1.0e-12); ++} ++ ++ ++/*! Test focused on the mapping of cell IDs. ++ * (i.e. when only part of the source/target mesh is transmitted) ++ */ ++void ParaMEDMEMTest::testOverlapDEC3() ++{ ++ int size, rank; ++ MPI_Comm_size(MPI_COMM_WORLD,&size); ++ MPI_Comm_rank(MPI_COMM_WORLD,&rank); ++ ++ int nproc = 2; ++ if (size != nproc) return ; ++ std::set procs; ++ for (int i=0; igetField(); + if(rank==0) + { - CPPUNIT_ASSERT_DOUBLES_EQUAL(8.75,parafieldT->getField()->getArray()->getIJ(0,0),1e-12); ++ CPPUNIT_ASSERT_EQUAL(8, resField->getNumberOfTuples()); ++ for(int i=0;i<4;i++) ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0,resField->getArray()->getIJ(i,0),1e-12); ++ for(int i=4;i<8;i++) ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(4.0,resField->getArray()->getIJ(i,0),1e-12); + } + if(rank==1) + { - CPPUNIT_ASSERT_DOUBLES_EQUAL(8.5,parafieldT->getField()->getArray()->getIJ(0,0),1e-12); ++ CPPUNIT_ASSERT_EQUAL(12, resField->getNumberOfTuples()); ++ for(int i=0;i<4;i++) ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(2.0,resField->getArray()->getIJ(i,0),1e-12); ++ for(int i=4;i<8;i++) ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(3.0,resField->getArray()->getIJ(i,0),1e-12); ++ for(int i=8;i<12;i++) ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(5.0,resField->getArray()->getIJ(i,0),1e-12); + } - if(rank==2) ++ delete parafieldS; ++ delete parafieldT; ++ delete parameshS; ++ delete parameshT; ++ meshS->decrRef(); ++ meshT->decrRef(); ++ ++ MPI_Barrier(MPI_COMM_WORLD); ++} ++ ++/*! ++ * Tests: ++ * - default value ++ * - multi-component fields ++ */ ++void ParaMEDMEMTest::testOverlapDEC4() ++{ ++ int size, rank; ++ MPI_Comm_size(MPI_COMM_WORLD,&size); ++ MPI_Comm_rank(MPI_COMM_WORLD,&rank); ++ ++ int nproc = 2; ++ if (size != nproc) return ; ++ std::set procs; ++ for (int i=0; igetField(); ++ if(rank==0) ++ { ++ CPPUNIT_ASSERT_EQUAL(8, resField->getNumberOfTuples()); ++ for(int i=0;i<4;i++) ++ { ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(1.0,resField->getArray()->getIJ(i*2,0),1e-12); ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(10.0,resField->getArray()->getIJ(i*2+1,0),1e-12); ++ } ++ for(int i=4;i<8;i++) ++ { ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(4.0,resField->getArray()->getIJ(i*2,0),1e-12); ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(40.0,resField->getArray()->getIJ(i*2+1,0),1e-12); ++ } ++ } ++ if(rank==1) + { - CPPUNIT_ASSERT_DOUBLES_EQUAL(10.5,parafieldT->getField()->getArray()->getIJ(0,0),1e-12); ++ CPPUNIT_ASSERT_EQUAL(12, resField->getNumberOfTuples()); ++ for(int i=0;i<4;i++) ++ { ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(2.0,resField->getArray()->getIJ(i*2,0),1e-12); ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(20.0,resField->getArray()->getIJ(i*2+1,0),1e-12); ++ } ++ // Default value should be here: ++ for(int i=4;i<8;i++) ++ { ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(defVal,resField->getArray()->getIJ(i*2,0),1e-12); ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(defVal,resField->getArray()->getIJ(i*2+1,0),1e-12); ++ } ++ for(int i=8;i<12;i++) ++ { ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(5.0,resField->getArray()->getIJ(i*2,0),1e-12); ++ CPPUNIT_ASSERT_DOUBLES_EQUAL(50.0,resField->getArray()->getIJ(i*2+1,0),1e-12); ++ } + } + delete parafieldS; + delete parafieldT; + delete parameshS; + delete parameshT; + meshS->decrRef(); + meshT->decrRef(); + + MPI_Barrier(MPI_COMM_WORLD); +} +