keyword stringclasses 7 values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29 values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14 values |
|---|---|---|---|---|---|---|---|
3D | febiosoftware/FEBio | FEBioRVE/FERVEModel2O.h | .h | 3,892 | 127 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEModel.h>
#include <FECore/mat3d.h>
#include <FECore/tens3d.h>
#include <FECore/tens4d.h>
#include <FECore/tens5d.h>
#include <FECore/tens6d.h>
//-----------------------------------------------------------------------------
// Class describing the second-order RVE model.
// This is used by the second-order homogenization code.
class FERVEModel2O : public FEModel
{
public:
enum RVE_TYPE
{
DISPLACEMENT, // prescribed displacement
PERIODIC_LC, // periodic, linear constraints
PERIODIC_AL // periodic, augmented Lagrangian (obsolete, should probably delete)
};
public:
FERVEModel2O();
~FERVEModel2O();
//! one time initialization
bool InitRVE(int rveType, const char* szbc);
// scale the geometry
void ScaleGeometry(double scale);
public:
//! Return the initial volume (calculated in Init)
double InitialVolume() const { return m_V0; }
//! periodicity flag
int RVEType() const { return m_rveType; }
//! get boundary nodes
const vector<int>& BoundaryList() const { return m_BN; }
protected:
//! Calculate the initial volume
void EvalInitialVolume();
//! find the list of boundary nodes
void FindBoundaryNodes(vector<int>& BN);
//! Center the RVE
void CenterRVE();
bool PrepDisplacementBC();
bool PrepPeriodicBC(const char* szbc);
bool PrepPeriodicLC();
private:
double m_V0; //!< initial volume
int m_rveType; //!< type of RVE
FEBoundingBox m_bb; //!< bounding box of mesh
vector<int> m_BN; //!< boundary node flags
};
//-----------------------------------------------------------------------------
//! class representing the RVE models at the material points.
class FEMicroModel2O : public FEModel
{
public:
FEMicroModel2O();
~FEMicroModel2O();
public:
//! Initialize the micro model from the parent RVE model
bool Init(FERVEModel2O& rve);
//! Solve the RVE model
bool Solve(const mat3d& F, const tens3drs& G);
//! calculate average PK1 stress
mat3d AveragedStressPK1(FEMaterialPoint &mp);
void AveragedStress2O (mat3d& Pa, tens3drs& Qa);
// void AveragedStress2OPK1(FEMaterialPoint &mp, mat3d& PK1a, tens3drs& QK1a);
// void AveragedStress2OPK2(FEMaterialPoint &mp, mat3ds& Sa, tens3ds& Ta);
void AveragedStiffness(FEMaterialPoint &mp, tens4d& C, tens5d& L, tens5d& H, tens6d& J);
protected:
//! Update the boundary conditions
void UpdateBC(const mat3d& F, const tens3drs& G);
//! see if node is boundary node
bool IsBoundaryNode(int i) const { return ((*m_BN)[i]==1); }
protected:
int m_rveType; //!< RVE type flag
double m_V0; //!< initial RVE volume
const vector<int>* m_BN;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioRVE/FEElasticMultiscaleDomain1O.cpp | .cpp | 2,712 | 79 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEElasticMultiscaleDomain1O.h"
#include "FEMicroMaterial.h"
#include "FECore/mat3d.h"
#include "FECore/tens6d.h"
#include <FECore/log.h>
//-----------------------------------------------------------------------------
//! constructor
FEElasticMultiscaleDomain1O::FEElasticMultiscaleDomain1O(FEModel* pfem) : FEElasticSolidDomain(pfem)
{
}
//-----------------------------------------------------------------------------
//! intialize domain
bool FEElasticMultiscaleDomain1O::Init()
{
if (FEElasticSolidDomain::Init() == false) return false;
// get the material
FEModel& fem = *GetFEModel();
FEMicroMaterial* pmat = dynamic_cast<FEMicroMaterial*>(m_pMat);
if (m_pMat == 0) return false;
// get the parent RVE
FERVEModel& rve = pmat->m_mrve;
// loop over all elements
for (size_t i=0; i<m_Elem.size(); ++i)
{
FESolidElement& el = m_Elem[i];
int nint = el.GaussPoints();
for (int j=0; j<nint; ++j)
{
FEMaterialPoint& mp = *el.GetMaterialPoint(j);
FEElasticMaterialPoint& pt = *mp.ExtractData<FEElasticMaterialPoint>();
FEMicroMaterialPoint& mmpt = *mp.ExtractData<FEMicroMaterialPoint>();
// create the material point RVEs
mmpt.m_F_prev = pt.m_F; // TODO: I think I can remove this line
mmpt.m_rve.CopyFrom(rve);
if (mmpt.m_rve.Init() == false) return false;
// initialize RCI solve
if (mmpt.m_rve.RCI_Init() == false) return false;
}
}
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEBioRVE/FEBioRVEPlot.cpp | .cpp | 4,618 | 143 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include <FECore/writeplot.h>
#include "FEBioRVEPlot.h"
#include "FEMicroMaterial.h"
#include "FEMicroMaterial2O.h"
//-----------------------------------------------------------------------------
//! Store the average deformation Hessian (G) for each element.
class FEMicro2OG
{
public:
tens3drs operator()(const FEMaterialPoint& mp)
{
const FEElasticMaterialPoint2O& pt2O = *(mp.ExtractData<FEElasticMaterialPoint2O>());
return pt2O.m_G;
}
};
bool FEPlotElementGnorm::Save(FEDomain& dom, FEDataStream& a)
{
FEElasticMaterial2O* pme = dom.GetMaterial()->ExtractProperty<FEElasticMaterial2O>();
if (pme == 0) return false;
writeAverageElementValue<tens3drs, double>(dom, a, FEMicro2OG(), [](const tens3drs& m) { return m.tripledot(m); });
return true;
}
//-----------------------------------------------------------------------------
//! Store the norm of the average PK1 stress for each element.
class FEMicro1OPK1Stress
{
public:
FEMicro1OPK1Stress(FEMicroMaterial* pm) : m_mat(pm) {}
mat3d operator()(const FEMaterialPoint& mp)
{
FEMaterialPoint& mp_noconst = const_cast<FEMaterialPoint&>(mp);
FEMicroMaterialPoint* mmppt = mp_noconst.ExtractData<FEMicroMaterialPoint>();
return m_mat->AveragedStressPK1(mmppt->m_rve, mp_noconst);
}
private:
FEMicroMaterial* m_mat;
};
class FEMicro2OPK1Stress
{
public:
mat3d operator()(const FEMaterialPoint& mp)
{
FEMaterialPoint& mp_noconst = const_cast<FEMaterialPoint&>(mp);
FEMicroMaterialPoint2O* mmppt = mp_noconst.ExtractData<FEMicroMaterialPoint2O>();
return mmppt->m_rve.AveragedStressPK1(mp_noconst);
}
};
bool FEPlotElementPK1norm::Save(FEDomain& dom, FEDataStream& a)
{
FEMicroMaterial* pm1O = dynamic_cast<FEMicroMaterial*>(dom.GetMaterial());
if (pm1O)
{
writeAverageElementValue<mat3d, double>(dom, a, FEMicro1OPK1Stress(pm1O), [](const mat3d& m) {return m.dotdot(m); });
return true;
}
FEMicroMaterial2O* pm2O = dynamic_cast<FEMicroMaterial2O*>(dom.GetMaterial());
if (pm2O)
{
writeAverageElementValue<mat3d, double>(dom, a, FEMicro2OPK1Stress(), [](const mat3d& m) {return m.dotdot(m); });
return true;
}
return false;
}
//-----------------------------------------------------------------------------
//! Store the norm of the average PK1 stress moment for each element.
class FEMicro2OQK1
{
public:
tens3drs operator()(const FEMaterialPoint& mp)
{
const FEElasticMaterialPoint2O& pt2O = *(mp.ExtractData<FEElasticMaterialPoint2O>());
return pt2O.m_Q;
}
};
bool FEPlotElementQK1norm::Save(FEDomain& dom, FEDataStream& a)
{
FEElasticMaterial2O* pme = dynamic_cast<FEElasticMaterial2O*>(dom.GetMaterial());
if (pme == 0) return false;
// write solid element data
writeAverageElementValue<tens3drs, double>(dom, a, FEMicro2OQK1(), [](const tens3drs& m) { return m.tripledot(m); });
return true;
}
//-----------------------------------------------------------------------------
//! Element macro energy
bool FEPlotElementMicroEnergy::Save(FEDomain& dom, FEDataStream& a)
{
FEMicroMaterial* pm1O = dynamic_cast<FEMicroMaterial*>(dom.GetMaterial());
if (pm1O)
{
writeAverageElementValue<double>(dom, a, [](const FEMaterialPoint& mp) {
const FEMicroMaterialPoint& mmpt = *(mp.ExtractData<FEMicroMaterialPoint>());
return mmpt.m_micro_energy;
});
return true;
}
return false;
}
| C++ |
3D | febiosoftware/FEBio | FEBioRVE/FEBioRVE.h | .h | 1,585 | 38 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "febiorve_api.h"
//-----------------------------------------------------------------------------
//! The FEBioRVE module
//! This module defines classes for dealing with homogenization problems
namespace FEBioRVE
{
//! Initialize the FEBioMech module
FEBIORVE_API void InitModule();
}
| Unknown |
3D | febiosoftware/FEBio | FEBioRVE/FEBioRVEPlot.h | .h | 2,579 | 65 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEPlotData.h>
#include <FECore/FEElement.h>
//-----------------------------------------------------------------------------
//! Element norm for PK1 stress
class FEPlotElementPK1norm : public FEPlotDomainData
{
public:
FEPlotElementPK1norm(FEModel* pfem) : FEPlotDomainData(pfem, PLT_FLOAT, FMT_ITEM) {}
bool Save(FEDomain& dom, FEDataStream& a);
};
//-----------------------------------------------------------------------------
//! Element norm for G
class FEPlotElementGnorm : public FEPlotDomainData
{
public:
FEPlotElementGnorm(FEModel* pfem) : FEPlotDomainData(pfem, PLT_FLOAT, FMT_ITEM) {}
bool Save(FEDomain& dom, FEDataStream& a);
};
//-----------------------------------------------------------------------------
//! Element norm for PK1 stress moment
class FEPlotElementQK1norm : public FEPlotDomainData
{
public:
FEPlotElementQK1norm(FEModel* pfem) : FEPlotDomainData(pfem, PLT_FLOAT, FMT_ITEM) {}
bool Save(FEDomain& dom, FEDataStream& a);
};
//-----------------------------------------------------------------------------
//! Element micro energy
class FEPlotElementMicroEnergy : public FEPlotDomainData
{
public:
FEPlotElementMicroEnergy(FEModel* pfem) : FEPlotDomainData(pfem, PLT_FLOAT, FMT_ITEM) {}
bool Save(FEDomain& dom, FEDataStream& a);
};
| Unknown |
3D | febiosoftware/FEBio | FEBioRVE/FERVEProbe.cpp | .cpp | 4,352 | 159 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FERVEProbe.h"
#include "FEMicroMaterial.h"
#include <FEBioPlot/FEBioPlotFile.h>
#include <FECore/FEModel.h>
#include <FECore/FEDomain.h>
#include <FECore/log.h>
FERVEProbe::FERVEProbe(FEModel* fem) : FECallBack(fem, CB_ALWAYS)
{
m_rve = nullptr;
m_file = "rve.xplt";
m_bdebug = false;
}
bool FERVEProbe::Init()
{
// make sure we have an RVE
if (m_rve == nullptr) return false;
return FECallBack::Init();
}
bool FERVEProbe::Execute(FEModel& fem, int nwhen)
{
if (nwhen == CB_INIT) // initialize the plot file
{
assert(m_rve);
if (m_rve == nullptr) return false;
// create a plot file
m_xplt = new FEBioPlotFile(m_rve);
if (m_xplt->Open(m_file.c_str()) == false)
{
feLog("Failed creating probe.\n\n");
delete m_xplt; m_xplt = 0;
}
// write the initial state
Save();
}
else if (nwhen == CB_MINOR_ITERS)
{
if (m_bdebug) Save();
}
else if (nwhen == CB_MAJOR_ITERS) // store the current state
{
Save();
}
else if (nwhen == CB_SOLVED) // clean up
{
if (m_xplt) delete m_xplt;
m_xplt = 0;
}
return true;
}
void FERVEProbe::Save()
{
assert(m_rve);
if (m_rve)
{
if (m_xplt) m_xplt->Write((float)m_rve->GetCurrentTime());
}
}
void FERVEProbe::SetRVEModel(FEModel* rve)
{
m_rve = rve;
}
//=============================================================================
BEGIN_FECORE_CLASS(FEMicroProbe, FERVEProbe)
ADD_PARAMETER(m_neid , "element_id");
ADD_PARAMETER(m_ngp , "gausspt" );
ADD_PARAMETER(m_file , "file" );
ADD_PARAMETER(m_bdebug, "debug" );
END_FECORE_CLASS();
FEMicroProbe::FEMicroProbe(FEModel* fem) : FERVEProbe(fem)
{
m_neid = -1; // invalid element - this must be defined by user
m_ngp = -1; // invalid gauss point
}
bool FEMicroProbe::Init()
{
// get the (parent) model
FEModel& fem = *GetFEModel();
// get the micro-material
FEMicroMaterial* mat = dynamic_cast<FEMicroMaterial*>(GetParent());
if (mat == nullptr)
{
feLogError("The RVE probe must be a property of a micro-material.");
return false;
}
// find the element from the ID
FEMesh& mesh = fem.GetMesh();
FEElement* pel = mesh.FindElementFromID(m_neid);
if (pel == nullptr)
{
feLogError("Invalid Element ID for micro probe %d in material %d (%s)", m_neid, mat->GetID(), mat->GetName().c_str());
return false;
}
// make sure the element's parent domain has this material
FEDomain* dom = dynamic_cast<FEDomain*>(pel->GetMeshPartition());
if ((dom == nullptr) || (dom->GetMaterial() != mat))
{
feLogError("The specified element does not belong to this material's domain.");
return false;
}
// get the gauss-point
int nint = pel->GaussPoints();
if ((m_ngp >= 0) && (m_ngp < nint))
{
FEMaterialPoint* mp = pel->GetMaterialPoint(m_ngp);
FEMicroMaterialPoint* mmp = mp->ExtractData<FEMicroMaterialPoint>();
if (mmp == nullptr) return false;
SetRVEModel(&mmp->m_rve);
}
else
{
feLogError("Invalid gausspt number for micro-probe %d in material %d (%s)", m_ngp, mat->GetID(), mat->GetName().c_str());
return false;
}
return FERVEProbe::Init();
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEMMGRemesh.cpp | .cpp | 16,254 | 650 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEMMGRemesh.h"
#include <FECore/FEMeshTopo.h>
#include <FECore/FEModel.h>
#include <FECore/FEDomain.h>
#include <FECore/FESolidDomain.h>
#include <FECore/FESurface.h>
#include <FECore/log.h>
#include <FECore/FEOctreeSearch.h>
#include <FECore/FENNQuery.h>
#include <FECore/FEMeshAdaptorCriterion.h>
#include <FECore/FEDomainMap.h>
#include "FELeastSquaresInterpolator.h"
#include "FEMeshShapeInterpolator.h"
#include "FEDomainShapeInterpolator.h"
#include <FECore/FECoreKernel.h>
#include <FECore/FEMaterial.h>
#ifdef HAS_MMG
#include "mmg/mmg3d/libmmg3d.h"
class FEMMGRemesh::MMG
{
public:
MMG(FEMMGRemesh* mmgRemesh) : m_mmgRemesh(mmgRemesh) {}
bool build_mmg_mesh(MMG5_pMesh mmgMesg, MMG5_pSol mmgSol, FEMeshTopo& topo);
bool build_new_mesh(MMG5_pMesh mmgMesh, MMG5_pSol mmgSol, FEModel& fem);
public:
FEMMGRemesh* m_mmgRemesh;
std::vector<double> m_metric; // refinement metric
std::vector<int> m_nodeSetTag; // surface tags for node sets
};
#endif
BEGIN_FECORE_CLASS(FEMMGRemesh, FERefineMesh)
ADD_PARAMETER(m_hmin, "min_element_size");
ADD_PARAMETER(m_hausd, "hausdorff");
ADD_PARAMETER(m_hgrad, "gradation");
ADD_PARAMETER(m_relativeSize, "relative_size");
ADD_PARAMETER(m_meshCoarsen, "mesh_coarsen");
ADD_PARAMETER(m_normalizeData, "normalize_data");
ADD_PROPERTY(m_criterion, "criterion");
ADD_PROPERTY(m_sfunc, "size_function", 0);
END_FECORE_CLASS();
FEMMGRemesh::FEMMGRemesh(FEModel* fem) : FERefineMesh(fem)
{
m_maxelem = 0;
m_relativeSize = true;
m_meshCoarsen = false;
m_normalizeData = false;
m_hmin = 0.0;
m_hausd = 0.01;
m_hgrad = 1.3;
m_criterion = nullptr;
m_transferMethod = TRANSFER_MLQ;
m_nnc = 8;
m_sfunc = nullptr;
#ifdef HAS_MMG
mmg = new FEMMGRemesh::MMG(this);
#endif
}
bool FEMMGRemesh::Init()
{
FEMesh& mesh = GetMesh();
if (mesh.IsType(ET_TET4) == false) return false;
return FERefineMesh::Init();
}
bool FEMMGRemesh::RefineMesh()
{
#ifdef HAS_MMG
FEMesh& mesh = GetMesh();
// initialize the MMG mesh
MMG5_pMesh mmgMesh = NULL;
MMG5_pSol mmgSol = NULL;
MMG3D_Init_mesh(MMG5_ARG_start,
MMG5_ARG_ppMesh, &mmgMesh, MMG5_ARG_ppMet, &mmgSol,
MMG5_ARG_end);
// --- build the MMG mesh ---
FEMeshTopo& topo = *m_topo;
if (mmg->build_mmg_mesh(mmgMesh, mmgSol, topo) == false) return false;
// set the control parameters
MMG3D_Set_dparameter(mmgMesh, mmgSol, MMG3D_DPARAM_hmin, m_hmin);
MMG3D_Set_dparameter(mmgMesh, mmgSol, MMG3D_DPARAM_hausd, m_hausd);
MMG3D_Set_dparameter(mmgMesh, mmgSol, MMG3D_DPARAM_hgrad, m_hgrad);
// run the mesher
int ier = MMG3D_mmg3dlib(mmgMesh, mmgSol);
if (ier == MMG5_STRONGFAILURE) {
feLogError("MMG was not able to remesh the mesh.");
return false;
}
else if (ier == MMG5_LOWFAILURE)
{
feLogError("MMG return low failure error");
}
// build the new mesh
bool bret = mmg->build_new_mesh(mmgMesh, mmgSol, *GetFEModel());
// Clean up
MMG3D_Free_all(MMG5_ARG_start,
MMG5_ARG_ppMesh, &mmgMesh, MMG5_ARG_ppMet, &mmgSol,
MMG5_ARG_end);
return bret;
#else
return false;
#endif
}
#ifdef HAS_MMG
bool FEMMGRemesh::MMG::build_mmg_mesh(MMG5_pMesh mmgMesh, MMG5_pSol mmgSol, FEMeshTopo& topo)
{
FEMeshAdaptorCriterion* criterion = m_mmgRemesh->GetCriterion();
assert(criterion);
if (criterion == nullptr) return false;
FEElementSet* elset = m_mmgRemesh->GetElementSet();
FEMeshAdaptorSelection elemList = criterion->GetElementSelection(elset);
if (elemList.size() == 0) return false;
FEMesh& mesh = *topo.GetMesh();
int NN = mesh.Nodes();
int NE = topo.Elements();
int NF = topo.Faces();
// allocate mesh size
if (MMG3D_Set_meshSize(mmgMesh, NN, NE, 0, NF, 0, 0) != 1)
{
assert(false);
return false;
}
// set the vertex coordinates
for (int i = 0; i < NN; ++i)
{
FENode& vi = mesh.Node(i);
vec3d r = vi.m_r0;
MMG3D_Set_vertex(mmgMesh, r.x, r.y, r.z, 0, i + 1);
}
// set the tetrahedra
int c = 1;
for (int i = 0; i < mesh.Domains(); ++i)
{
FEDomain& dom = mesh.Domain(i);
int ne = dom.Elements();
for (int j = 0; j < ne; ++j, ++c)
{
FEElement& e = dom.ElementRef(j);
int* n = &e.m_node[0];
MMG3D_Set_tetrahedron(mmgMesh, n[0] + 1, n[1] + 1, n[2] + 1, n[3] + 1, i, c);
}
}
// set the facet markers
vector<int> faceMarker(NF, 0);
int faceMark = 1;
for (int i = 0; i < mesh.Surfaces(); ++i)
{
FESurface& surf = mesh.Surface(i);
vector<int> faceIndexList = topo.FaceIndexList(surf);
for (int j = 0; j < faceIndexList.size(); ++j)
{
faceMarker[faceIndexList[j]] = faceMark;
}
faceMark++;
}
// for node sets we are going to create artificial surfaces
m_nodeSetTag.assign(mesh.NodeSets(), -1);
for (int i = 0; i < mesh.NodeSets(); ++i)
{
FENodeSet& nset = *mesh.NodeSet(i);
if (nset.Size() != mesh.Nodes())
{
vector<int> nodeTags(mesh.Nodes(), 0);
for (int j = 0; j < nset.Size(); ++j) nodeTags[nset[j]] = 2;
// see if this is indeed a surface node set
for (int j = 0; j < NF; ++j)
{
const FEFaceList::FACE& face = topo.Face(j);
const int* fn = face.node;
if ((nodeTags[fn[0]] != 0) && (nodeTags[fn[1]] != 0) && (nodeTags[fn[2]] != 0))
{
nodeTags[fn[0]] = 1;
nodeTags[fn[1]] = 1;
nodeTags[fn[2]] = 1;
}
}
int twos = 0;
for (int j = 0; j < mesh.Nodes(); ++j) if (nodeTags[j] == 2) twos++;
if (twos == 0)
{
for (int j = 0; j < NF; ++j)
{
const FEFaceList::FACE& face = topo.Face(j);
const int* fn = face.node;
if ((nodeTags[fn[0]] == 1) && (nodeTags[fn[1]] == 1) && (nodeTags[fn[2]] == 1))
{
if (faceMarker[j] == 0)
{
faceMarker[j] = faceMark;
m_nodeSetTag[i] = faceMark;
}
else
{
if (m_nodeSetTag[i] == -1)
{
m_nodeSetTag[i] = faceMarker[j];
}
else if (faceMarker[j] != m_nodeSetTag[i])
{
return false;
}
}
}
}
}
faceMark++;
}
}
// create the faces
for (int i = 0; i < NF; ++i)
{
const FEFaceList::FACE& f = topo.Face(i);
const int* n = &f.node[0];
MMG3D_Set_triangle(mmgMesh, n[0] + 1, n[1] + 1, n[2] + 1, faceMarker[i], i + 1);
}
// Now, we build the "solution", i.e. the target element size.
// If no elements are selected, we set a homogenous remeshing using the element size parameter.
// set the "solution", i.e. desired element size
if (MMG3D_Set_solSize(mmgMesh, mmgSol, MMG5_Vertex, NN, MMG5_Scalar) != 1)
{
assert(false);
return false;
}
if (m_metric.empty())
{
// build the edge length table
int ET_TET[6][2] = { { 0,1 },{ 1,2 },{ 2,0 },{ 0,3 },{ 1,3 },{ 2,3 } };
vector<pair<double, int> > edgeLength(NN, pair<double, int>(0.0, 0));
for (int i = 0; i < NE; ++i)
{
FEElement& el = *topo.Element(i);
for (int j = 0; j < 6; ++j)
{
int a = el.m_node[ET_TET[j][0]];
int b = el.m_node[ET_TET[j][1]];
vec3d ra = mesh.Node(a).m_r0;
vec3d rb = mesh.Node(b).m_r0;
double L = (ra - rb).norm2();
// if (L > edgeLength[a].first) edgeLength[a].first = L;
// if (L > edgeLength[b].first) edgeLength[b].first = L;
edgeLength[a].first += L; edgeLength[a].second++;
edgeLength[b].first += L; edgeLength[b].second++;
}
}
m_metric.resize(NN, 0.0);
for (int i = 0; i < NN; ++i)
{
if (edgeLength[i].second != 0)
{
edgeLength[i].first /= (double)edgeLength[i].second;
edgeLength[i].first = sqrt(edgeLength[i].first);
}
m_metric[i] = edgeLength[i].first;
}
}
if (elset)
{
// elements that are not in the element set will be flagged as required.
FEElementIterator it(&mesh);
int c = 1;
for (; it.isValid(); ++it, ++c)
{
FEElement& el = *it;
if (elset->Contains(el) == false)
{
MMG3D_Set_requiredTetrahedron(mmgMesh, c);
}
}
}
// scale factors
vector<double> nodeScale(NN, 0.0);
// see if want to normalize the data
if (m_mmgRemesh->m_normalizeData)
{
// Find data range
double vmin, vmax;
for (int i = 0; i < (int)elemList.size(); ++i)
{
double v = elemList[i].m_elemValue;
if ((i == 0) || (v < vmin)) vmin = v;
if ((i == 0) || (v > vmax)) vmax = v;
}
if (vmax == vmin) vmax++;
// normalize data
for (int i = 0; i < (int)elemList.size(); ++i)
{
double v = elemList[i].m_elemValue;
elemList[i].m_elemValue = (v - vmin) / (vmax - vmin);
}
}
// map to nodal data
vector<int> tag(NN, 0);
for (int i = 0; i < (int)elemList.size(); ++i)
{
FEElement& el = *mesh.FindElementFromID(elemList[i].m_elementId);
for (int j = 0; j < el.Nodes(); ++j)
{
double s = elemList[i].m_elemValue;
FEFunction1D* fs = m_mmgRemesh->m_sfunc;
if (fs)
{
s = fs->value(s);
}
assert(s > 0.0);
if (s <= 0.0) return false;
nodeScale[el.m_node[j]] += s;
tag[el.m_node[j]]++;
}
}
for (int i = 0; i < NN; ++i)
{
if (tag[i] > 0) nodeScale[i] /= (double)tag[i];
else nodeScale[i] = (m_mmgRemesh->m_relativeSize ? 1.0 : m_metric[i]);
}
// adjust for relative scale flag
if (m_mmgRemesh->m_relativeSize)
{
for (int k = 0; k < NN; k++) {
nodeScale[k] *= m_metric[k];
}
}
// determine new size field
bool meshCoarsen = m_mmgRemesh->m_meshCoarsen;
for (int k = 0; k < NN; k++)
{
double s = nodeScale[k];
if ((meshCoarsen) || (s < m_metric[k])) m_metric[k] = s;
}
// set the new metric
for (int k = 0; k < NN; k++) {
MMG3D_Set_scalarSol(mmgSol, m_metric[k], k + 1);
}
return true;
}
bool FEMMGRemesh::MMG::build_new_mesh(MMG5_pMesh mmgMesh, MMG5_pSol mmgSol, FEModel& fem)
{
FEMesh& mesh = fem.GetMesh();
int N0 = mesh.Nodes();
// get the new mesh sizes
int nodes, elems, faces;
MMG3D_Get_meshSize(mmgMesh, &nodes, &elems, NULL, &faces, NULL, NULL);
// get old node positions
vector<vec3d> oldNodePos(N0);
for (int i = 0; i < N0; ++i) oldNodePos[i] = mesh.Node(i).m_r0;
// copy nodal positions
vector<vec3d> nodePos0(nodes);
for (int i = 0; i<nodes; ++i)
{
vec3d r;
MMG3D_Get_vertex(mmgMesh, &r.x, &r.y, &r.z, NULL, NULL, NULL);
nodePos0[i] = r;
}
// copy the metric
m_metric.resize(nodes, 0.0);
for (int i = 0; i < nodes; ++i)
{
MMG3D_Get_scalarSol(mmgSol, &m_metric[i]);
}
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
vector<vec3d> nodePos(nodes);
vector<vector<double> > nodeVal(nodes, vector<double>(MAX_DOFS, 0.0));
// allocate data mapper
FEMeshDataInterpolator* mapper = nullptr;
switch (m_mmgRemesh->m_transferMethod)
{
case TRANSFER_SHAPE: mapper = new FEMeshShapeInterpolator(&mesh); break;
case TRANSFER_MLQ:
{
FELeastSquaresInterpolator* MLQ = new FELeastSquaresInterpolator;
MLQ->SetNearestNeighborCount(m_mmgRemesh->m_nnc);
MLQ->SetDimension(m_mmgRemesh->m_nsdim);
MLQ->SetSourcePoints(oldNodePos);
mapper = MLQ;
}
break;
default:
assert(false);
return false;
}
// map nodal positions and nodal data
for (int i = 0; i < nodes; ++i)
{
vec3d ri = nodePos0[i];
if (mapper->SetTargetPoint(ri) == false)
{
assert(false);
delete mapper;
throw std::runtime_error("Fatal error in MMG remesh during nodal mapping.");
return false;
}
// get the nodal coordinates
nodePos[i] = mapper->MapVec3d([&mesh](int sourceNode) {
return mesh.Node(sourceNode).m_rt;
});
// update values
for (int l = 0; l < MAX_DOFS; ++l)
{
nodeVal[i][l] = mapper->Map([&mesh, l](int sourceNode) {
return mesh.Node(sourceNode).get(l);
});
}
}
delete mapper;
// reallocate nodes
mesh.CreateNodes(nodes);
// assign dofs to new nodes
for (int i = 0; i < nodes; ++i)
{
FENode& node = mesh.Node(i);
node.SetDOFS(MAX_DOFS);
node.m_r0 = nodePos0[i];
node.m_rt = nodePos[i];
if (m_mmgRemesh->m_nsdim == 2) node.m_rt.z = node.m_r0.z;
for (int j = 0; j < node.m_ID.size(); ++j) {
node.set(j, nodeVal[i][j]);
}
node.UpdateValues();
}
// recreate domains
for (int i = 0; i < mesh.Domains(); ++i)
{
FESolidDomain& dom = dynamic_cast<FESolidDomain&>(mesh.Domain(i));
int nelems = 0;
for (int j = 0; j < elems; ++j)
{
int n[4], gid, breq;
MMG3D_Get_tetrahedron(mmgMesh, n, n + 1, n + 2, n + 3, &gid, &breq);
if (gid == i) nelems++;
}
dom.Create(nelems, dom.GetElementSpec());
int c = 0;
for (int j = 0; j < elems; ++j)
{
int n[4], gid;
MMG3D_Get_tetrahedron(mmgMesh, n, n + 1, n + 2, n + 3, &gid, NULL);
if (gid == i)
{
FESolidElement& el = dom.Element(c++);
el.m_node[0] = n[0] - 1;
el.m_node[1] = n[1] - 1;
el.m_node[2] = n[2] - 1;
el.m_node[3] = n[3] - 1;
}
}
// re-init domain
FEMaterial* mat = dom.GetMaterial();
dom.SetMatID(mat->GetID() - 1);
dom.CreateMaterialPointData();
dom.Reset(); // NOTE: we need to call this to actually call the Init function on the material points.
dom.Init();
dom.Activate();
}
mesh.RebuildLUT();
// recreate element sets
for (int i = 0; i < mesh.ElementSets(); ++i)
{
FEElementSet& eset = mesh.ElementSet(i);
// get the domain list
// NOTE: Don't get the reference, since then the same reference
// is passed to Create below, which causes problems.
FEDomainList domList = eset.GetDomainList();
if (domList.IsEmpty()) { throw std::runtime_error("Error in FEMMGRemesh!"); }
// recreate the element set from the domain list
eset.Create(domList);
}
// recreate surfaces
int faceMark = 1;
for (int i = 0; i < mesh.Surfaces(); ++i)
{
FESurface& surf = mesh.Surface(i);
// count faces
int nfaces = 0;
for (int j = 0; j < faces; ++j)
{
int n[3], gid, breq;
MMG3D_Get_triangle(mmgMesh, n, n + 1, n + 2, &gid, &breq);
if (gid == faceMark) nfaces++;
}
assert(nfaces > 0);
surf.Create(nfaces);
int c = 0;
for (int j = 0; j < faces; ++j)
{
int n[3], gid;
MMG3D_Get_triangle(mmgMesh, n, n + 1, n + 2, &gid, NULL);
if (gid == faceMark)
{
FESurfaceElement& face = surf.Element(c++);
face.SetType(FE_TRI3G3);
face.m_node[0] = n[0] - 1;
face.m_node[1] = n[1] - 1;
face.m_node[2] = n[2] - 1;
}
}
assert(c == nfaces);
surf.CreateMaterialPointData();
surf.Init();
// also update the facet set if the surface has one
FEFacetSet* fset = surf.GetFacetSet();
if (fset)
{
fset->Create(surf);
}
faceMark++;
}
// update nodesets
for (int i = 0; i < mesh.NodeSets(); ++i)
{
int tag = m_nodeSetTag[i];
FENodeSet& nset = *mesh.NodeSet(i);
if (nset.Size() != N0)
{
vector<int> nodeTags(mesh.Nodes(), 0);
for (int j = 0; j < faces; ++j)
{
int n[3], gid;
MMG3D_Get_triangle(mmgMesh, n, n + 1, n + 2, &gid, NULL);
if (gid == tag)
{
nodeTags[n[0] - 1] = 1;
nodeTags[n[1] - 1] = 1;
nodeTags[n[2] - 1] = 1;
}
}
std::vector<int> nodeList;
for (int i = 0; i < nodeTags.size(); ++i) if (nodeTags[i] == 1) nodeList.push_back(i);
if (nodeList.size() > 0)
{
nset.Clear();
nset.Add(nodeList);
}
faceMark++;
}
else
{
// assume this node set is determined by the entire mesh
nset.Clear();
int N = mesh.Nodes();
for (int i = 0; i < N; ++i) nset.Add(i);
}
}
return true;
}
#endif
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEHexRefine2D.h | .h | 2,195 | 67 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FERefineMesh.h"
class FEHexRefine2D : public FERefineMesh
{
public:
FEHexRefine2D(FEModel* fem);
bool Init() override;
bool RefineMesh() override;
protected:
bool BuildSplitLists(FEModel& fem);
void UpdateNewNodes(FEModel& fem);
void FindHangingNodes(FEModel& fem);
void BuildNewDomains(FEModel& fem);
void UpdateNodeSet(FENodeSet& nset);
bool UpdateSurface(FESurface& surf);
bool UpdateElementSet(FEElementSet& set);
private:
double m_maxValue;
int m_elemRefine; // max nr of elements to refine per step
vector<int> m_elemList;
vector<int> m_edgeList; // list of edge flags to see whether the edge was split
vector<int> m_faceList; // list of face flags to see whether the face was split
int m_N0;
int m_NC;
int m_NN;
int m_splitElems;
int m_splitFaces;
int m_splitEdges;
int m_hangingNodes;
FEMeshAdaptorCriterion* m_criterion;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/sphericalHarmonics.h | .h | 2,399 | 49 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include <memory>
#include <FECore/matrix.h>
#include "feamr_api.h"
FEAMR_API void getSphereCoords(std::vector<vec3d>& coords, std::vector<double>& theta, std::vector<double>& phi);
FEAMR_API std::unique_ptr<matrix> compSH(int order, std::vector<double>& theta, std::vector<double>& phi);
FEAMR_API double harmonicY(int degree, int order, double theta, double phi, int numType);
FEAMR_API void reconstructODF(std::vector<double>& sphHarm, std::vector<double>& ODF, std::vector<double>& theta, std::vector<double>& phi);
FEAMR_API void altGradient(int order, std::vector<double>& sphHarm, std::vector<double>& gradient);
FEAMR_API void remesh(std::vector<double>& gradient, double lengthScale, double hausd, double grad, std::vector<vec3d>& nodePos, std::vector<vec3i>& elems);
FEAMR_API void remeshFull(std::vector<double>& gradient, double lengthScale, double hausd, double grad, std::vector<vec3d>& nodePos, std::vector<vec3i>& elems);
// Taken from std::assoc_legendre definition in GCC
template<typename _Tp>
_Tp
__assoc_legendre_p(unsigned int __l, unsigned int __m, _Tp __x,
_Tp __phase = _Tp(+1));
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FETetRefine.h | .h | 1,451 | 38 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FERefineMesh.h"
class FETetRefine : public FERefineMesh
{
public:
FETetRefine(FEModel* fem);
bool RefineMesh() override;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FEFilterAdaptorCriterion.h | .h | 1,781 | 48 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEMeshAdaptorCriterion.h>
#include <FECore/FEMaterialPoint.h>
#include "feamr_api.h"
class FEAMR_API FEMinMaxFilterAdaptorCriterion : public FEMeshAdaptorCriterion
{
public:
FEMinMaxFilterAdaptorCriterion(FEModel* fem);
bool GetMaterialPointValue(FEMaterialPoint& el, double& value) override;
bool GetElementValue(FEElement& el, double& value) override;
private:
double m_min;
double m_max;
bool m_clamp;
FEMeshAdaptorCriterion* m_data;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/SpherePointsGenerator.cpp | .cpp | 9,671 | 306 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2025 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include <algorithm>
#include <cassert>
#include "SpherePointsGenerator.h"
SpherePointsGenerator* SpherePointsGenerator::m_instance = nullptr;
void SpherePointsGenerator::Instantiate()
{
if (m_instance == nullptr) {
m_instance = new SpherePointsGenerator();
}
}
size_t SpherePointsGenerator::GetNumNodes(int n)
{
Instantiate();
m_instance->GeneratePoints(n);
return m_instance->m_nodes[n].size();
}
size_t SpherePointsGenerator::GetNumFaces(int n)
{
Instantiate();
m_instance->GeneratePoints(n);
return m_instance->m_faces[n].size();
}
std::vector<vec3d>& SpherePointsGenerator::GetNodes(int n)
{
Instantiate();
m_instance->GeneratePoints(n);
return m_instance->m_nodes[n];
}
std::vector<std::array<int, 3>>& SpherePointsGenerator::GetFaces(int n)
{
Instantiate();
m_instance->GeneratePoints(n);
return m_instance->m_faces[n];
}
void SpherePointsGenerator::GeneratePoints(int n)
{
if(m_nodes.find(n) == m_nodes.end() || m_faces.find(n) == m_faces.end())
{
m_nodes[n] = std::vector<vec3d>();
m_faces[n] = std::vector<std::array<int, 3>>();
std::vector<vec3d>& vertices = m_nodes[n];
std::vector<std::array<int, 3>>& faces = m_faces[n];
// Create icosahedron
create_icosahedron(vertices, faces);
// Align equator with x-y plane
align_equator(vertices);
// Subdivide
subdivide(vertices, faces, n);
}
}
vec3d SpherePointsGenerator::midpoint(const vec3d& a, const vec3d& b)
{
vec3d out = (a + b).normalized();
// Ensure that points on the equator are exactly on the x-y plane
if(abs(out.z) < 1e-5)
{
out.z = 0;
}
return out;
}
void SpherePointsGenerator::create_icosahedron(std::vector<vec3d>& vertices, std::vector<std::array<int, 3>>& faces)
{
double phi = (1.0 + sqrt(5.0)) / 2.0;
// Match Python vertices exactly
std::vector<vec3d> verts =
{
{0, 1, phi}, {0, -1, phi}, {0, 1, -phi}, {0, -1, -phi},
{1, phi, 0}, {-1, phi, 0}, {1, -phi, 0}, {-1, -phi, 0},
{phi, 0, 1}, {-phi, 0, 1}, {phi, 0, -1}, {-phi, 0, -1}
};
// Normalize vertices
for (auto& v : verts)
{
v.Normalize();
}
vertices = verts;
// Use same face connectivity as in Python
faces =
{
{0, 1, 8}, {0, 8, 4}, {0, 4, 5}, {0, 5, 9}, {0, 9, 1},
{1, 9, 7}, {1, 7, 6}, {1, 6, 8}, {8, 6, 10}, {8, 10, 4},
{4, 10, 2}, {4, 2, 5}, {5, 2, 11}, {5, 11, 9}, {9, 11, 7},
{3, 2, 10}, {3, 10, 6}, {3, 6, 7}, {3, 7, 11}, {3, 11, 2}
};
}
// Rotation function to match Python's implementation
void SpherePointsGenerator::rotate(std::vector<vec3d>& vertices, const vec3d& axis, double angle_rad)
{
// Normalize axis
vec3d norm_axis = axis.normalized();
// Create rotation matrix using Rodrigues' formula (same as Python)
double cos_a = cosf(angle_rad);
double sin_a = sinf(angle_rad);
double one_minus_cos = 1.0f - cos_a;
// K matrix (skew-symmetric cross-product matrix)
double K[3][3] =
{
{0, -norm_axis.z, norm_axis.y},
{norm_axis.z, 0, -norm_axis.x},
{-norm_axis.y, norm_axis.x, 0}
};
// K^2 matrix
double K2[3][3] =
{
{-norm_axis.y*norm_axis.y - norm_axis.z*norm_axis.z, norm_axis.x*norm_axis.y, norm_axis.x*norm_axis.z},
{norm_axis.x*norm_axis.y, -norm_axis.x*norm_axis.x - norm_axis.z*norm_axis.z, norm_axis.y*norm_axis.z},
{norm_axis.x*norm_axis.z, norm_axis.y*norm_axis.z, -norm_axis.x*norm_axis.x - norm_axis.y*norm_axis.y}
};
// R = I + sin(θ)K + (1-cos(θ))K²
double R[3][3] =
{
{1.0f + sin_a*K[0][0] + one_minus_cos*K2[0][0], sin_a*K[0][1] + one_minus_cos*K2[0][1], sin_a*K[0][2] + one_minus_cos*K2[0][2]},
{sin_a*K[1][0] + one_minus_cos*K2[1][0], 1.0f + sin_a*K[1][1] + one_minus_cos*K2[1][1], sin_a*K[1][2] + one_minus_cos*K2[1][2]},
{sin_a*K[2][0] + one_minus_cos*K2[2][0], sin_a*K[2][1] + one_minus_cos*K2[2][1], 1.0f + sin_a*K[2][2] + one_minus_cos*K2[2][2]}
};
// Apply rotation to each vertex
for (auto& v : vertices)
{
double x = v.x, y = v.y, z = v.z;
v.x = R[0][0]*x + R[0][1]*y + R[0][2]*z;
v.y = R[1][0]*x + R[1][1]*y + R[1][2]*z;
v.z = R[2][0]*x + R[2][1]*y + R[2][2]*z;
}
}
// Match Python's align_equator implementation
void SpherePointsGenerator::align_equator(std::vector<vec3d>& vertices)
{
// Step 1: Detect "belt" axis
double abs_mean_x = 0, abs_mean_y = 0, abs_mean_z = 0;
for (const auto& v : vertices)
{
abs_mean_x += abs(v.x);
abs_mean_y += abs(v.y);
abs_mean_z += abs(v.z);
}
int n = (int)vertices.size();
abs_mean_x /= n;
abs_mean_y /= n;
abs_mean_z /= n;
int belt_axis = (abs_mean_x < abs_mean_y && abs_mean_x < abs_mean_z) ? 0 :
(abs_mean_y < abs_mean_z) ? 1 : 2;
// Step 2: Find vertices in the belt
std::vector<vec3d> band_vertices;
std::vector<double> abs_coords;
for (const auto& v : vertices)
{
double coord = (belt_axis == 0) ? v.x : (belt_axis == 1) ? v.y : v.z;
abs_coords.push_back(abs(coord));
}
// Calculate median of absolute coordinates (approximate)
std::vector<double> sorted_abs_coords = abs_coords;
std::sort(sorted_abs_coords.begin(), sorted_abs_coords.end());
double belt_band = sorted_abs_coords[sorted_abs_coords.size() / 2];
for (size_t i = 0; i < vertices.size(); i++)
{
double coord = (belt_axis == 0) ? vertices[i].x : (belt_axis == 1) ? vertices[i].y : vertices[i].z;
if (abs(abs(coord) - belt_band) < 1e-3f)
{
band_vertices.push_back(vertices[i]);
}
}
if (band_vertices.empty())
{
assert(false); // No vertices in belt
}
// Pick first band vertex and normalize
vec3d target_vertex = band_vertices[0].normalized();
// Step 3: Rotate this vertex to Z axis
vec3d z_axis(0, 0, 1);
vec3d axis = vec3d(
target_vertex.y * z_axis.z - target_vertex.z * z_axis.y,
target_vertex.z * z_axis.x - target_vertex.x * z_axis.z,
target_vertex.x * z_axis.y - target_vertex.y * z_axis.x
);
axis.Normalize();
double dot = target_vertex.x * z_axis.x + target_vertex.y * z_axis.y + target_vertex.z * z_axis.z;
double angle = acos(std::clamp(dot, -1.0, 1.0));
// Rotate all vertices
rotate(vertices, axis, angle);
// Ensure that points on the equator are exactly on the x-y plane
for(int index = 0; index < vertices.size(); index++)
{
if(abs(vertices[index].z) < 1e-5)
{
vertices[index].z = 0;
}
}
}
int SpherePointsGenerator::get_midpoint_index(int i1, int i2, std::vector<vec3d>& vertices,
std::unordered_map<std::pair<int, int>, int, pair_hash>& midpoint_cache)
{
std::pair<int, int> key = (i1 < i2) ? std::make_pair(i1, i2) : std::make_pair(i2, i1);
if (midpoint_cache.count(key))
{
return midpoint_cache[key];
}
// Calculate midpoint
vec3d mid = midpoint(vertices[i1], vertices[i2]);
vertices.push_back(mid);
int idx = (int)vertices.size() - 1;
midpoint_cache[key] = idx;
return idx;
}
void SpherePointsGenerator::subdivide(std::vector<vec3d>& vertices, std::vector<std::array<int, 3>>& faces, int depth)
{
for (int i = 0; i < depth; ++i)
{
std::unordered_map<std::pair<int, int>, int, pair_hash> midpoint_cache;
std::vector<std::array<int, 3>> new_faces;
for (const auto& tri : faces)
{
int v1 = tri[0], v2 = tri[1], v3 = tri[2];
// Get midpoints
int a = get_midpoint_index(v1, v2, vertices, midpoint_cache);
int b = get_midpoint_index(v2, v3, vertices, midpoint_cache);
int c = get_midpoint_index(v3, v1, vertices, midpoint_cache);
// Create new faces
new_faces.push_back({v1, a, c});
new_faces.push_back({v2, b, a});
new_faces.push_back({v3, c, b});
new_faces.push_back({a, b, c});
}
faces = new_faces;
}
} | C++ |
3D | febiosoftware/FEBio | FEAMR/FEElementDataCriterion.cpp | .cpp | 1,921 | 54 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "FEElementDataCriterion.h"
#include <FECore/FECoreKernel.h>
BEGIN_FECORE_CLASS(FEElementDataCriterion, FEMeshAdaptorCriterion)
ADD_PARAMETER(m_data, "element_data");
END_FECORE_CLASS();
FEElementDataCriterion::FEElementDataCriterion(FEModel* fem) : FEMeshAdaptorCriterion(fem)
{
m_pd = nullptr;
}
bool FEElementDataCriterion::Init()
{
m_pd = fecore_new<FELogElemData>(m_data.c_str(), GetFEModel());
if (m_pd == nullptr) return false;
return FEMeshAdaptorCriterion::Init();
}
bool FEElementDataCriterion::GetElementValue(FEElement& el, double& val)
{
if (m_pd)
{
val = m_pd->value(el);
return true;
}
else return false;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FETetRefine.cpp | .cpp | 7,789 | 311 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FETetRefine.h"
#include <FECore/FESolidDomain.h>
#include <FECore/FEMeshTopo.h>
#include <FECore/FEFixedBC.h>
#include <FECore/FESurface.h>
#include <FECore/FEModel.h>
#include <FECore/log.h>
BEGIN_FECORE_CLASS(FETetRefine, FERefineMesh)
END_FECORE_CLASS();
FETetRefine::FETetRefine(FEModel* fem) : FERefineMesh(fem)
{
}
struct TRI
{
int n[3];
};
bool FETetRefine::RefineMesh()
{
FEModel& fem = *GetFEModel();
if (m_topo == nullptr) return false;
FEMeshTopo& topo = *m_topo;
FEMesh& mesh = GetMesh();
FESolidDomain& dom = dynamic_cast<FESolidDomain&>(mesh.Domain(0));
int NEL = dom.Elements();
// we need to create a new node for each edge
int N0 = mesh.Nodes();
int newNodes = topo.Edges();
mesh.AddNodes(newNodes);
int N1 = N0 + newNodes;
// update the position of these new nodes
int n = N0;
for (int i = 0; i < topo.Edges(); ++i)
{
const FEEdgeList::EDGE& edge = topo.Edge(i);
FENode& node = mesh.Node(n++);
vec3d r0 = mesh.Node(edge.node[0]).m_r0;
vec3d r1 = mesh.Node(edge.node[1]).m_r0;
node.m_r0 = (r0 + r1)*0.5;
r0 = mesh.Node(edge.node[0]).m_rt;
r1 = mesh.Node(edge.node[1]).m_rt;
node.m_rt = (r0 + r1)*0.5;
}
assert(n == N1);
// assign dofs to new nodes
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
int NN = mesh.Nodes();
for (int i = N0; i<NN; ++i)
{
FENode& node = mesh.Node(i);
node.SetDOFS(MAX_DOFS);
}
// re-evaluate solution at nodes
n = N0;
for (int i = 0; i < topo.Edges(); ++i)
{
const FEEdgeList::EDGE& edge = topo.Edge(i);
FENode& node0 = mesh.Node(edge.node[0]);
FENode& node1 = mesh.Node(edge.node[1]);
FENode& node = mesh.Node(n++);
for (int j = 0; j < MAX_DOFS; ++j)
{
double v = (node0.get(j) + node1.get(j))*0.5;
node.set(j, v);
}
node.UpdateValues();
}
assert(n == N1);
const int LUT[8][4] = {
{ 0, 4, 6, 7 },
{ 4, 1, 5, 8 },
{ 2, 6, 5, 9 },
{ 7, 8, 9, 3 },
{ 4, 8, 6, 7 },
{ 4, 8, 5, 6 },
{ 5, 6, 8, 9 },
{ 6, 7, 8, 9 },
};
// now we recreate the domains
const int NDOM = mesh.Domains();
for (int i = 0; i < NDOM; ++i)
{
// get the old domain
FEDomain& oldDom = mesh.Domain(i);
int NE0 = oldDom.Elements();
// create a copy of old domain (since we want to retain the old domain)
FEDomain* newDom = fecore_new<FESolidDomain>(oldDom.GetTypeStr(), &fem);
newDom->Create(NE0, FEElementLibrary::GetElementSpecFromType(FE_TET4G4));
for (int j = 0; j < NE0; ++j)
{
FEElement& el0 = oldDom.ElementRef(j);
FEElement& el1 = newDom->ElementRef(j);
for (int k = 0; k < el0.Nodes(); ++k) el1.m_node[k] = el0.m_node[k];
}
// reallocate the old domain
oldDom.Create(8 * NE0, FEElementLibrary::GetElementSpecFromType(FE_TET4G4));
// set new element nodes
int nel = 0;
for (int j = 0; j < NE0; ++j)
{
FEElement& el0 = newDom->ElementRef(j);
std::vector<int> ee = topo.ElementEdgeList(j); assert(ee.size() == 6);
// build the look-up table
int ENL[10] = { 0 };
ENL[0] = el0.m_node[0];
ENL[1] = el0.m_node[1];
ENL[2] = el0.m_node[2];
ENL[3] = el0.m_node[3];
ENL[4] = N0 + ee[0];
ENL[5] = N0 + ee[1];
ENL[6] = N0 + ee[2];
ENL[7] = N0 + ee[3];
ENL[8] = N0 + ee[4];
ENL[9] = N0 + ee[5];
for (int k = 0; k < 8; ++k)
{
FEElement& el1 = oldDom.ElementRef(nel++);
el1.m_node[0] = ENL[LUT[k][0]];
el1.m_node[1] = ENL[LUT[k][1]];
el1.m_node[2] = ENL[LUT[k][2]];
el1.m_node[3] = ENL[LUT[k][3]];
int a = 0;
}
}
// we don't need this anymore
delete newDom;
}
mesh.RebuildLUT();
// re-init domains
for (int i = 0; i < NDOM; ++i)
{
FEDomain& dom = mesh.Domain(i);
dom.CreateMaterialPointData();
dom.Reset(); // NOTE: we need to call this to actually call the Init function on the material points.
dom.Init();
dom.Activate();
}
const int FLUT[4][3] = {
{ 0, 3, 5 },
{ 1, 4, 3 },
{ 2, 5, 4 },
{ 3, 4, 5 },
};
// recreate element sets
for (int i = 0; i < mesh.ElementSets(); ++i)
{
FEElementSet& eset = mesh.ElementSet(i);
// get the domain list
// NOTE: Don't get the reference, since then the same reference
// is passed to Create below, which causes problems.
FEDomainList domList = eset.GetDomainList();
if (domList.IsEmpty()) { throw std::runtime_error("Error in FEMMGRemesh!"); }
// recreate the element set from the domain list
eset.Create(domList);
}
// recreate surfaces
int faceMark = 1;
for (int i = 0; i < mesh.Surfaces(); ++i)
{
FESurface& surf = mesh.Surface(i);
int NF0 = surf.Elements();
vector<int> faceList = topo.FaceIndexList(surf);
assert(faceList.size() == NF0);
vector<TRI> tri(NF0);
for (int j = 0; j < NF0; ++j)
{
FESurfaceElement& el = surf.Element(j);
TRI t;
t.n[0] = el.m_node[0];
t.n[1] = el.m_node[1];
t.n[2] = el.m_node[2];
tri[j] = t;
}
int NF1 = NF0 * 4;
surf.Create(NF1);
int nf = 0;
for (int j = 0; j < NF0; ++j)
{
TRI& t = tri[j];
std::vector<int> ee = topo.FaceEdgeList(faceList[j]); assert(ee.size() == 3);
// build the look-up table
int FNL[6] = { 0 };
FNL[0] = t.n[0];
FNL[1] = t.n[1];
FNL[2] = t.n[2];
// the edges may not be ordered correctly, so we need to do a search here.
for (int k = 0; k < 3; k++)
{
int a = t.n[k];
int b = t.n[(k+1)%3];
int e = -1;
for (int l = 0; l < 3; ++l)
{
const FEEdgeList::EDGE& edge = topo.Edge(ee[l]);
if ((edge.node[0] == a) && (edge.node[1] == b)) { e = l; break; }
if ((edge.node[1] == a) && (edge.node[0] == b)) { e = l; break; }
}
assert(e >= 0);
FNL[k + 3] = N0 + ee[e];
}
for (int k = 0; k < 4; ++k)
{
FESurfaceElement& fj = surf.Element(nf++);
fj.SetType(FE_TRI3G3);
fj.m_node[0] = FNL[FLUT[k][0]];
fj.m_node[1] = FNL[FLUT[k][1]];
fj.m_node[2] = FNL[FLUT[k][2]];
}
}
surf.CreateMaterialPointData();
surf.Init();
// also update the facet set if the surface has one
FEFacetSet* fset = surf.GetFacetSet();
if (fset)
{
fset->Create(surf);
}
faceMark++;
}
// update node sets
const int NSETS = mesh.NodeSets();
for (int i=0; i<NSETS; ++i)
{
FENodeSet& nset = *mesh.NodeSet(i);
vector<int> tag(mesh.Nodes(), 0);
for (int j = 0; j < nset.Size(); ++j) tag[nset[j]] = 1;
for (int j = 0; j < topo.Edges(); ++j)
{
const FEEdgeList::EDGE& edge = topo.Edge(j);
if ((tag[edge.node[0]] == 1) && (tag[edge.node[1]] == 1))
{
nset.Add(N0 + j);
}
}
}
// re-activate the model
UpdateModel();
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEElementDataCriterion.h | .h | 1,646 | 45 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEMeshAdaptorCriterion.h>
#include <FECore/ElementDataRecord.h>
class FEElementDataCriterion : public FEMeshAdaptorCriterion
{
public:
FEElementDataCriterion(FEModel* fem);
bool Init() override;
bool GetElementValue(FEElement& el, double& val) override;
private:
std::string m_data;
FELogElemData* m_pd;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FEElementSelectionCriterion.cpp | .cpp | 2,313 | 73 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEElementSelectionCriterion.h"
#include <FECore/FEMesh.h>
BEGIN_FECORE_CLASS(FEElementSelectionCriterion, FEMeshAdaptorCriterion)
ADD_PARAMETER(m_value, "value");
ADD_PARAMETER(m_elemList, "element_list");
END_FECORE_CLASS();
FEElementSelectionCriterion::FEElementSelectionCriterion(FEModel* fem) : FEMeshAdaptorCriterion(fem)
{
m_value = 1.0;
}
FEMeshAdaptorSelection FEElementSelectionCriterion::GetElementSelection(FEElementSet* elemSet)
{
FEMesh& mesh = GetMesh();
FEMeshAdaptorSelection elemList;
FEElementIterator it(&mesh, elemSet);
for (; it.isValid(); ++it)
{
FEElement& el = *it;
if (el.isActive())
{
// see if this element is in the element_list
// TODO: This is really slow. Need to speed this up!
int eid = el.GetID();
int n = -1;
for (int i = 0; i < m_elemList.size(); ++i)
{
if (m_elemList[i] == eid)
{
n = i;
break;
}
}
// set the value
if (n != -1)
{
elemList.push_back(eid, m_value);
}
}
}
return elemList;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEErosionAdaptor.h | .h | 2,359 | 65 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEMeshAdaptor.h>
#include <FECore/FEMeshAdaptorCriterion.h>
class FEMeshTopo;
class FEErosionAdaptor : public FEMeshAdaptor
{
enum SurfaceErodeOption {
DONT_ERODE, // don't erode surface elements (default)
ERODE, // erode surface elements
GROW, // add newly exposed surface elements
RECONSTRUCT // reconstruct surfaces
};
public:
FEErosionAdaptor(FEModel* fem);
bool Apply(int iteration) override;
private:
void RemoveIslands(FEMeshTopo& topo);
void DeactivateOrphanedNodes();
void ErodeSurfaces();
void GrowErodedSurfaces(FEMeshTopo& topo);
void ReconstructSurfaces(FEMeshTopo& topo);
void UpdateLinearConstraints();
private:
int m_maxIters; // max iterations per time step
bool m_bremoveIslands; // remove disconnected elements
int m_maxelem; // the max nr of elements to erode per adaptation iteration
int m_nsort; // sort option (0 = none, 1 = smallest to largest, 2 = largest to smallest)
int m_erodeSurfaces; // option to erode surfaces
FEMeshAdaptorCriterion* m_criterion;
DECLARE_FECORE_CLASS()
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FEElementSelectionCriterion.h | .h | 1,687 | 42 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEMeshAdaptorCriterion.h>
//-----------------------------------------------------------------------------
class FEElementSelectionCriterion : public FEMeshAdaptorCriterion
{
public:
FEElementSelectionCriterion(FEModel* fem);
FEMeshAdaptorSelection GetElementSelection(FEElementSet* elset) override;
private:
double m_value;
vector<int> m_elemList;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FEDomainShapeInterpolator.cpp | .cpp | 3,459 | 120 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "FEDomainShapeInterpolator.h"
#include <FECore/FESolidDomain.h>
#include <FECore/FEOctreeSearch.h>
FEDomainShapeInterpolator::FEDomainShapeInterpolator(FEDomain* domain)
{
m_dom = domain;
m_mesh = m_dom->GetMesh();
m_os = nullptr;
}
FEDomainShapeInterpolator::~FEDomainShapeInterpolator()
{
delete m_os;
}
bool FEDomainShapeInterpolator::Init()
{
if (m_mesh == nullptr) return false;
if (m_os == nullptr)
{
m_os = new FEOctreeSearch(m_dom);
if (m_os->Init() == false) return false;
}
int nodes = m_trgPoints.size();
m_data.resize(nodes);
for (int i = 0; i < nodes; ++i)
{
Data& di = m_data[i];
vec3d ri = m_trgPoints[i];
// find the element
di.r[0] = di.r[1] = di.r[2] = 0.0;
di.el = (FESolidElement*)m_os->FindElement(ri, di.r);
if (di.el == nullptr)
{
assert(false);
return false;
}
assert(di.el->GetMeshPartition() == m_dom);
}
return true;
}
void FEDomainShapeInterpolator::SetTargetPoints(const vector<vec3d>& trgPoints)
{
m_trgPoints = trgPoints;
}
bool FEDomainShapeInterpolator::SetTargetPoint(const vec3d& r)
{
m_trgPoints.clear();
m_trgPoints.push_back(r);
return Init();
}
bool FEDomainShapeInterpolator::Map(std::vector<double>& tval, function<double(int sourceNode)> src)
{
// update solution
int nodes = m_trgPoints.size();
for (int i = 0; i < nodes; ++i)
{
Data& di = m_data[i];
// update values
double v[FEElement::MAX_NODES] = { 0 };
for (int j = 0; j < di.el->Nodes(); ++j) v[j] = src(di.el->m_lnode[j]);
double vl = di.el->evaluate(v, di.r[0], di.r[1], di.r[2]);
tval[i] = vl;
}
return true;
}
double FEDomainShapeInterpolator::Map(int inode, function<double(int sourceNode)> f)
{
Data& di = m_data[inode];
double v[FEElement::MAX_NODES];
for (int j = 0; j < di.el->Nodes(); ++j) v[j] = f(di.el->m_lnode[j]);
double vl = di.el->evaluate(v, di.r[0], di.r[1], di.r[2]);
return vl;
}
vec3d FEDomainShapeInterpolator::MapVec3d(int inode, function<vec3d(int sourceNode)> f)
{
Data& di = m_data[inode];
vec3d v[FEElement::MAX_NODES];
for (int j = 0; j < di.el->Nodes(); ++j) v[j] = f(di.el->m_lnode[j]);
vec3d vl = di.el->evaluate(v, di.r[0], di.r[1], di.r[2]);
return vl;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/stdafx.h | .h | 1,287 | 27 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FEMeshDataInterpolator.h | .h | 2,439 | 60 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <vector>
#include <functional>
#include <FECore/matrix.h>
// Base classes for classes that interpolate data on a mesh
class FEMeshDataInterpolator
{
public:
FEMeshDataInterpolator();
virtual ~FEMeshDataInterpolator();
// do one-time initalization
virtual bool Init();
// set the next target point
// should return false if the target point cannot be evaluated
virtual bool SetTargetPoint(const vec3d& r) = 0;
//! map source data onto target data
//! output: tval - values at the target points
//! input: sval - values of the source points
virtual bool Map(std::vector<double>& tval, std::function<double(int sourceNode)> src) = 0;
virtual double Map(int inode, std::function<double(int sourceNode)> src) = 0;
virtual vec3d MapVec3d(int inode, std::function<vec3d(int sourceNode)> src) = 0;
double Map(std::function<double(int sourceNode)> f);
vec3d MapVec3d(std::function<vec3d(int sourceNode)> f);
};
inline double FEMeshDataInterpolator::Map(std::function<double(int sourceNode)> f) { return Map(0, f); }
inline vec3d FEMeshDataInterpolator::MapVec3d(std::function<vec3d(int sourceNode)> f) { return MapVec3d(0, f); }
| Unknown |
3D | febiosoftware/FEBio | FEAMR/feamr_api.h | .h | 1,517 | 45 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#ifdef WIN32
#ifdef FECORE_DLL
#ifdef feamr_EXPORTS
#define FEAMR_API __declspec(dllexport)
#else
#define FEAMR_API __declspec(dllimport)
#endif
#else
#define FEAMR_API
#endif
#else
#define FEAMR_API
#endif
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FEDomainShapeInterpolator.h | .h | 2,171 | 66 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEMeshDataInterpolator.h"
class FEDomain;
class FESolidElement;
class FEMesh;
class FEOctreeSearch;
//! Maps data by using element shape functions
class FEDomainShapeInterpolator : public FEMeshDataInterpolator
{
struct Data
{
FESolidElement* el;
double r[3];
};
public:
FEDomainShapeInterpolator(FEDomain* domain);
~FEDomainShapeInterpolator();
bool Init() override;
void SetTargetPoints(const std::vector<vec3d>& trgPoints);
bool SetTargetPoint(const vec3d& r) override;
bool Map(std::vector<double>& tval, std::function<double(int sourceNode)> src) override;
double Map(int inode, std::function<double(int sourceNode)> src) override;
vec3d MapVec3d(int inode, std::function<vec3d(int sourceNode)> src) override;
private:
FEDomain* m_dom;
FEMesh* m_mesh;
FEOctreeSearch* m_os;
std::vector<vec3d> m_trgPoints;
std::vector<Data> m_data;
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FEErosionAdaptor.cpp | .cpp | 11,979 | 476 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEErosionAdaptor.h"
#include <FECore/FEMeshAdaptorCriterion.h>
#include <FECore/FEModel.h>
#include <FECore/FEMesh.h>
#include <FECore/FEDomain.h>
#include <FECore/FESurface.h>
#include <FECore/log.h>
#include <FECore/FELinearConstraintManager.h>
#include <FECore/FEElementList.h>
#include <FECore/FEMeshTopo.h>
#include <algorithm>
#include <stack>
#include <set>
BEGIN_FECORE_CLASS(FEErosionAdaptor, FEMeshAdaptor)
ADD_PARAMETER(m_maxIters, "max_iters");
ADD_PARAMETER(m_maxelem, "max_elems");
ADD_PARAMETER(m_nsort, "sort");
ADD_PARAMETER(m_bremoveIslands, "remove_islands");
ADD_PARAMETER(m_erodeSurfaces, "erode_surfaces")->setEnums("no\0yes\0grow\0reconstruct\0");
ADD_PROPERTY(m_criterion, "criterion");
END_FECORE_CLASS();
FEErosionAdaptor::FEErosionAdaptor(FEModel* fem) : FEMeshAdaptor(fem)
{
m_maxIters = -1;
m_maxelem = 0;
m_nsort = 0;
m_erodeSurfaces = SurfaceErodeOption::ERODE;
m_criterion = nullptr;
m_bremoveIslands = false;
}
bool FEErosionAdaptor::Apply(int iteration)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
if ((m_maxIters >= 0) && (iteration >= m_maxIters))
{
feLog("\tMax iterations reached.");
return false;
}
// Make sure there is a criterion
if (m_criterion == nullptr) return false;
// get the element selection
FEMeshAdaptorSelection selection = m_criterion->GetElementSelection(GetElementSet());
if (selection.empty())
{
feLog("\tNothing to do.\n");
return false;
}
// see if we need to sort the data
// (This is only necessary if the max_elem parameter is set)
if ((m_maxelem > 0) && (m_nsort != 0))
{
if (m_nsort == 1)
{
// sort largest-to-smallest
selection.Sort(FEMeshAdaptorSelection::SORT_DECREASING);
}
else if (m_nsort == 2)
{
// sort smallest-to-largest
selection.Sort(FEMeshAdaptorSelection::SORT_INCREASING);
}
}
// process the list
int nsize = selection.size();
if ((m_maxelem > 0) && (nsize > m_maxelem)) nsize = m_maxelem;
int deactivatedElements = 0;
for (int i = 0; i < nsize; ++i)
{
FEMeshAdaptorSelection::Item& it = selection[i];
FEElement& el = *mesh.FindElementFromID(it.m_elementId);
if (el.isActive())
{
el.setInactive();
deactivatedElements++;
}
}
feLog("\tDeactivated elements: %d\n", deactivatedElements);
if (deactivatedElements == 0) return false;
FEMeshTopo topo;
if (topo.Create(&mesh) == false)
{
feLogError("Failed building mesh topo.");
return false;
}
// remove any islands
if (m_bremoveIslands) RemoveIslands(topo);
// if any nodes were orphaned, we need to deactivate them as well
DeactivateOrphanedNodes();
// any facets attached to a eroded element will be eroded as well.
switch (m_erodeSurfaces)
{
case SurfaceErodeOption::DONT_ERODE: break;// don't do anything
case SurfaceErodeOption::ERODE: ErodeSurfaces(); break;
case SurfaceErodeOption::GROW : GrowErodedSurfaces(topo); break;
case SurfaceErodeOption::RECONSTRUCT: ReconstructSurfaces(topo); break;
}
// remove any linear constraints of excluded nodes
UpdateLinearConstraints();
// update model
UpdateModel();
return (nsize != 0);
}
void FEErosionAdaptor::RemoveIslands(FEMeshTopo& topo)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int NE = topo.Elements();
vector<int> tag(NE, -1);
// find an unprocessed element
stack<int> s;
int m = 0; // island counter
for (int n = 0; n < NE; ++n)
{
FEElement* el = topo.Element(n);
if (el->isActive() && (tag[n] == -1))
{
// see if this is an island
vector<int> island;
tag[n] = m++;
// push it on the stack
s.push(n);
while (s.empty() == false)
{
// pop the element
int id = s.top(); s.pop();
FEElement* el = topo.Element(id);
island.push_back(id);
// loop over all the neighbors
vector<int> nbrList = topo.ElementNeighborIndexList(id);
for (int i = 0; i < nbrList.size(); ++i)
{
FEElement* eli = topo.Element(nbrList[i]);
if (eli && eli->isActive() && (tag[nbrList[i]] == -1))
{
tag[nbrList[i]] = m;
s.push(nbrList[i]);
}
}
}
// Next, see if the island should be deactivated.
// It will be deactivated if all the nodes on the island are open
bool isolated = true;
for (int i = 0; i < island.size(); ++i)
{
FEElement* el = topo.Element(island[i]);
int neln = el->Nodes();
for (int j = 0; j < neln; ++j)
{
FENode& nj = mesh.Node(el->m_node[j]);
// TODO: mechanics only!
if ((nj.get_bc(0) != DOF_OPEN) ||
(nj.get_bc(1) != DOF_OPEN) ||
(nj.get_bc(2) != DOF_OPEN))
{
isolated = false;
break;
}
}
if (isolated == false) break;
}
if (isolated)
{
// island is isolated so deactivate all elements
feLog("\tIsland of %d elements removed\n", island.size());
for (int i = 0; i < island.size(); ++i)
{
FEElement* el = topo.Element(island[i]);
el->setInactive();
}
}
}
}
}
void FEErosionAdaptor::DeactivateOrphanedNodes()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int NN = mesh.Nodes();
vector<int> tag(NN, 0);
for (int i = 0; i < mesh.Domains(); ++i)
{
FEDomain& dom = mesh.Domain(i);
int NE = dom.Elements();
for (int j = 0; j < NE; ++j)
{
FEElement& el = dom.ElementRef(j);
if (el.isActive())
{
int neln = el.Nodes();
for (int n = 0; n < neln; ++n) tag[el.m_node[n]] = 1;
}
}
}
for (int i = 0; i < NN; ++i)
{
FENode& node = mesh.Node(i);
if (tag[i] == 0)
{
node.SetFlags(FENode::EXCLUDE);
int ndofs = node.dofs();
for (int j = 0; j < ndofs; ++j)
node.set_inactive(j);
}
}
}
void FEErosionAdaptor::ErodeSurfaces()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
for (int i = 0; i < mesh.Surfaces(); ++i)
{
int erodedFaces = 0;
FESurface& surf = mesh.Surface(i);
for (int j = 0; j < surf.Elements(); ++j)
{
FESurfaceElement& face = surf.Element(j);
FEElement* pe = face.m_elem[0].pe; assert(pe);
if (pe && (pe->isActive() == false))
{
face.setInactive();
erodedFaces++;
}
}
if (erodedFaces != 0) surf.Init();
}
}
void FEErosionAdaptor::GrowErodedSurfaces(FEMeshTopo& topo)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
for (int i = 0; i < mesh.Surfaces(); ++i)
{
FESurface& surf = mesh.Surface(i);
// do a search to see if we need to modify this surface
bool doErode = false;
for (int j = 0; j < surf.Elements(); ++j)
{
FESurfaceElement& face = surf.Element(j);
if (face.isActive())
{
FEElement* pe = face.m_elem[0].pe; assert(pe);
if (pe && (pe->isActive() == false))
{
doErode = true;
break;
}
}
}
if (doErode)
{
std::vector<FEFaceList::FACE> newFaces;
std::set<FEElement*> processedElements;
newFaces.reserve(surf.Elements());
int erodedFaces = 0;
for (int j = 0; j < surf.Elements(); ++j)
{
FESurfaceElement& face = surf.Element(j);
if (face.isActive())
{
FEElement* pe = face.m_elem[0].pe; assert(pe);
if (pe && (pe->isActive() == false))
{
// make sure we didn't process this element yet
if (processedElements.find(pe) == processedElements.end())
{
int id = topo.GetElementIndexFromID(pe->GetID());
std::vector<FEElement*> nbrList = topo.ElementNeighborList(id);
for (int k = 0; k < nbrList.size(); ++k)
{
FEElement* pk = nbrList[k];
if ((pk != nullptr) && pk->isActive())
{
int node[FEElement::MAX_NODES] = { 0 };
int nf = pe->GetFace(k, node);
// Note that we invert the element to
// make sure the new face is outward pointing
FEFaceList::FACE newFace;
newFace.ntype = nf;
for (int l = 0; l < nf; ++l)
newFace.node[l] = node[nf - 1 - l];
if (!newFace.IsEqual(face.m_node.data()))
newFaces.push_back(newFace);
}
}
processedElements.insert(pe);
}
face.setInactive();
erodedFaces++;
}
else
{
FEFaceList::FACE newFace;
newFace.ntype = face.Nodes();
for (int k = 0; k < face.Nodes(); ++k)
newFace.node[k] = face.m_node[k];
newFaces.push_back(newFace);
}
}
}
feLog("eroded faces: %d", erodedFaces);
if (erodedFaces != 0)
{
int faces = newFaces.size();
surf.Create(faces);
for (int j = 0; j < faces; ++j)
{
FEFaceList::FACE& f = newFaces[j];
FESurfaceElement& face = surf.Element(j);
face.setActive();
if (f.ntype == 3)
face.SetType(FE_TRI3G3);
else if (f.ntype == 4)
face.SetType(FE_QUAD4G4);
for (int k = 0; k < f.ntype; ++k)
face.m_node[k] = f.node[k];
}
surf.CreateMaterialPointData();
surf.Init();
// also update the facet set if the surface has one
FEFacetSet* fset = surf.GetFacetSet();
if (fset)
{
fset->Create(surf);
}
}
}
}
}
void FEErosionAdaptor::UpdateLinearConstraints()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
FELinearConstraintManager& LCM = fem.GetLinearConstraintManager();
for (int j = 0; j < LCM.LinearConstraints();)
{
FELinearConstraint& lc = LCM.LinearConstraint(j);
if (mesh.Node(lc.GetParentNode()).HasFlags(FENode::EXCLUDE))
{
LCM.RemoveLinearConstraint(j);
}
else ++j;
}
// also remove any linear constraints that have excluded child nodes
for (int j = 0; j < LCM.LinearConstraints();)
{
FELinearConstraint& lc = LCM.LinearConstraint(j);
bool del = false;
int n = lc.Size();
for (int k = 0; k < n; ++k)
{
if (mesh.Node(lc.GetChildDof(k).node).HasFlags(FENode::EXCLUDE))
{
del = true;
break;
}
}
if (del) LCM.RemoveLinearConstraint(j); else ++j;
}
}
void FEErosionAdaptor::ReconstructSurfaces(FEMeshTopo& topo)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// We assume that the surfaces are definded through part lists.
// We don't actually store which surfaces are generated from part lists,
// but they should have the same name.
for (int i = 0; i < mesh.Surfaces(); ++i)
{
FESurface& surf = mesh.Surface(i);
// see if a part list exists with this name
FEDomainList* domList = mesh.FindDomainList(surf.GetName());
if (domList)
{
// build the outer surface
FEFacetSet* facetSet = mesh.DomainBoundary(*domList);
FEFacetSet* oldFacetSet = surf.GetFacetSet();
if (oldFacetSet == nullptr)
{
surf.Create(*facetSet);
}
else
{
oldFacetSet->Clear();
oldFacetSet->Add(facetSet);
surf.Create(*oldFacetSet);
}
surf.CreateMaterialPointData();
surf.Init();
}
}
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEScaleAdaptorCriterion.cpp | .cpp | 1,696 | 43 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEScaleAdaptorCriterion.h"
BEGIN_FECORE_CLASS(FEScaleAdaptorCriterion, FEMeshAdaptorCriterion)
ADD_PARAMETER(m_scale, "math");
END_FECORE_CLASS();
FEScaleAdaptorCriterion::FEScaleAdaptorCriterion(FEModel* fem) : FEMeshAdaptorCriterion(fem)
{
m_scale = 1.0;
}
bool FEScaleAdaptorCriterion::GetMaterialPointValue(FEMaterialPoint& mp, double& value)
{
value = m_scale(mp);
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEMeshShapeInterpolator.h | .h | 2,227 | 63 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEMeshDataInterpolator.h"
//=======================================================================================
class FEMesh;
class FEOctreeSearch;
class FESolidElement;
//! Interpolates data by using the element shape functions
class FEMeshShapeInterpolator : public FEMeshDataInterpolator
{
struct Data
{
FESolidElement* el;
double r[3];
};
public:
FEMeshShapeInterpolator(FEMesh* mesh);
~FEMeshShapeInterpolator();
bool Init() override;
void SetTargetPoints(const std::vector<vec3d>& trgPoints);
bool SetTargetPoint(const vec3d& r) override;
bool Map(std::vector<double>& tval, std::function<double(int sourceNode)> src) override;
double Map(int inode, std::function<double(int sourceNode)> src) override;
vec3d MapVec3d(int inode, std::function<vec3d(int sourceNode)> src) override;
private:
FEMesh* m_mesh;
FEOctreeSearch* m_os;
std::vector<vec3d> m_trgPoints;
std::vector<Data> m_data;
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FEMMGRemesh.h | .h | 1,945 | 65 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <vector>
#include "FERefineMesh.h"
#include <FECore/FEFunction1D.h>
#include <FECore/FEModelParam.h>
class FEMMGRemesh : public FERefineMesh
{
class MMG;
public:
FEMMGRemesh(FEModel* fem);
bool Init() override;
bool RefineMesh() override;
private:
FEMeshAdaptorCriterion* GetCriterion() { return m_criterion; }
private:
bool m_relativeSize;
bool m_meshCoarsen;
bool m_normalizeData;
double m_hmin; // minimum element size
double m_hausd; // Hausdorff value
double m_hgrad; // gradation
FEMeshAdaptorCriterion* m_criterion;
FEFunction1D* m_sfunc; // sizing function
MMG* mmg;
friend class MMG;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FELeastSquaresInterpolator.h | .h | 2,916 | 89 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEMeshDataInterpolator.h"
//! Helper class for mapping data between two point sets using moving least squares.
class FELeastSquaresInterpolator : public FEMeshDataInterpolator
{
class Data
{
public:
Data();
Data(const Data& d);
void operator = (const Data& d);
public:
matrix A;
std::vector<int> index;
std::vector<double> W;
std::vector<vec3d> X;
std::vector<int> cpl;
};
public:
//! constructor
FELeastSquaresInterpolator();
//! Set dimension (2 or 3)
void SetDimension(int d);
//! Set the number of nearest neighbors to use (should be larger than 4)
void SetNearestNeighborCount(int nnc);
//! Set check for match flag. This will return the source value
//! if the target point coincides
void SetCheckForMatch(bool b);
//! set the source points
void SetSourcePoints(const std::vector<vec3d>& srcPoints);
//! set the target points
void SetTargetPoints(const std::vector<vec3d>& trgPoints);
bool SetTargetPoint(const vec3d& trgPoint) override;
//! initialize MLQ data
bool Init() override;
//! map source data onto target data
//! input: sval - values of the source points
//! output: tval - values at the target points
bool Map(std::vector<double>& tval, std::function<double(int sourceNode)> src) override;
// evaluate map
double Map(int inode, std::function<double(int sourceNode)> src) override;
vec3d MapVec3d(int inode, std::function<vec3d(int sourceNode)> src) override;
private:
int m_dim;
int m_nnc;
bool m_checkForMatch;
std::vector<vec3d> m_src; // source points
std::vector<vec3d> m_trg; // target points
std::vector< Data > m_data;
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FERefineMesh.h | .h | 3,085 | 96 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEMeshAdaptor.h>
class FEModel;
class FEMeshTopo;
class FEBoundaryCondition;
class FESurfaceLoad;
class FESurfacePairConstraint;
class FESurface;
class FENodeSet;
class FEDomainMap;
//-----------------------------------------------------------------------------
// Base class for mesh refinement algorithms
class FERefineMesh : public FEMeshAdaptor
{
protected:
// Supported transfer methods for mapping data between meshes
enum TransferMethod {
TRANSFER_SHAPE,
TRANSFER_MLQ
};
public:
FERefineMesh(FEModel* fem);
~FERefineMesh();
// Apply mesh refinement
bool Apply(int iteration) override;
protected:
// Derived classes need to override this function
// The return value should be true if the mesh was refined
// or false otherwise.
virtual bool RefineMesh() = 0;
protected:
bool BuildMeshTopo();
void CopyMesh();
bool BuildMapData();
void TransferMapData();
void ClearMapData();
bool BuildDomainMapData();
bool BuildDomainMapData(FEDomain& dom, int domIndex);
void TransferDomainMapData();
bool BuildUserMapData();
void TransferUserMapData();
protected:
FEMeshTopo* m_topo; //!< mesh topo structure
int m_maxiter; // max nr of iterations per time step
int m_maxelem; // max nr of elements
int m_transferMethod; //!< method for transferring data between meshes
bool m_bmap_data; //!< map data flag
int m_nnc; //!< nearest-neighbor-count for MLQ transfer method
int m_nsdim; //!< nearest-neighbor search dimension (2 or 3)
FEMesh* m_meshCopy; //!< copy of "old" mesh, before refinement
std::vector< std::vector<FEDomainMap*> > m_domainMapList; // list of nodal data for each domain
std::vector< FEDomainMap* > m_userDataList; // list of nodal data for user-defined mesh data
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FERefineMesh.cpp | .cpp | 26,467 | 1,051 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FERefineMesh.h"
#include <FECore/FEModel.h>
#include <FECore/FESolidDomain.h>
#include <FECore/FEEdgeList.h>
#include <FECore/FEElementList.h>
#include <FECore/FEFaceList.h>
#include <FECore/FEFixedBC.h>
#include <FECore/FEPrescribedDOF.h>
#include <FECore/FEMeshTopo.h>
#include <FECore/FELinearConstraintManager.h>
#include <FECore/FESurfacePairConstraint.h>
#include <FECore/FESurfaceLoad.h>
#include <FECore/FENodalLoad.h>
#include <FECore/FEDomainMap.h>
#include <FECore/FESurfaceMap.h>
#include <FECore/DumpMemStream.h>
#include <FECore/log.h>
#include "FELeastSquaresInterpolator.h"
#include "FEMeshShapeInterpolator.h"
#include "FEDomainShapeInterpolator.h"
BEGIN_FECORE_CLASS(FERefineMesh, FEMeshAdaptor)
ADD_PARAMETER(m_maxiter, "max_iters");
ADD_PARAMETER(m_maxelem, "max_elements");
ADD_PARAMETER(m_bmap_data, "map_data");
ADD_PARAMETER(m_nnc , "nnc");
ADD_PARAMETER(m_nsdim , "nsdim");
ADD_PARAMETER(m_transferMethod, "transfer_method");
END_FECORE_CLASS();
FERefineMesh::FERefineMesh(FEModel* fem) : FEMeshAdaptor(fem), m_topo(nullptr)
{
m_meshCopy = nullptr;
m_bmap_data = false;
m_transferMethod = TRANSFER_SHAPE;
m_nnc = 8;
m_nsdim = 3;
m_maxiter = -1;
m_maxelem = -1;
}
FERefineMesh::~FERefineMesh()
{
if (m_meshCopy) delete m_meshCopy;
m_meshCopy = nullptr;
ClearMapData();
}
// Apply mesh refinement
bool FERefineMesh::Apply(int iteration)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// check for max iterations
if ((m_maxiter > 0) && (iteration >= m_maxiter))
{
feLog("Skipping refinement: Max iterations reached.");
return false;
}
// see if we reached max elements
if ((m_maxelem > 0) && (mesh.Elements() >= m_maxelem))
{
feLog("Skipping refinement: Element limit reached.\n");
return false;
}
// build the mesh-topo
if (BuildMeshTopo() == false)
{
throw std::runtime_error("Error building topo structure.");
}
// build data maps
feLog("-- Building map data:\n");
if (BuildMapData() == false)
{
throw std::runtime_error("Failed mapping data.");
}
// refine the mesh (This is done by sub-classes)
feLog("-- Starting Mesh refinement.\n");
if (RefineMesh() == false)
{
feLog("Nothing to refine.");
return false;
}
feLog("-- Mesh refinement completed.\n");
// map data to new mesh
feLog("-- Transferring map data to new mesh:\n");
TransferMapData();
// update the model
UpdateModel();
// print some mesh statistics
int NN = mesh.Nodes();
int NE = mesh.Elements();
feLog("\n Mesh Statistics:\n");
feLog(" \tNumber of nodes : %d\n", NN);
feLog(" \tNumber of elements : %d\n", NE);
feLog("\n");
// all done!
return true;
}
void FERefineMesh::ClearMapData()
{
// clear domain maps
for (size_t i = 0; i < m_domainMapList.size(); ++i)
{
std::vector<FEDomainMap*>& map_i = m_domainMapList[i];
for (size_t j = 0; j < map_i.size(); ++j) delete map_i[j];
}
m_domainMapList.clear();
// clear user maps
for (int i = 0; i < m_userDataList.size(); ++i) delete m_userDataList[i];
m_userDataList.clear();
}
bool FERefineMesh::BuildMeshTopo()
{
FEModel& fem = *GetFEModel();
if (m_topo) { delete m_topo; m_topo = nullptr; }
m_topo = new FEMeshTopo;
return m_topo->Create(&fem.GetMesh());
}
void FERefineMesh::CopyMesh()
{
if (m_meshCopy) delete m_meshCopy;
m_meshCopy = new FEMesh(nullptr);
FEMesh& mesh = GetFEModel()->GetMesh();
m_meshCopy->CopyFrom(mesh);
}
FEDomainMap* createElemDataMap(FEModel& fem, FEDomain& dom, vector<vec3d>& nodePos, FEDomainMap* map, FEMeshDataInterpolator* dataMapper)
{
assert(map->StorageFormat() == Storage_Fmt::FMT_NODE);
FEDataType dataType = map->DataType();
int dataSize = 0;
switch (dataType)
{
case FEDataType::FE_DOUBLE: dataSize = 1; break;
case FEDataType::FE_VEC3D: dataSize = 3; break;
case FEDataType::FE_MAT3D: dataSize = 9; break;
case FEDataType::FE_MAT3DS: dataSize = 6; break;
default:
assert(false);
return nullptr;
}
// count nr of integration points
int NMP = 0;
for (int i = 0; i < dom.Elements(); ++i)
{
FEElement& el = dom.ElementRef(i);
NMP += el.GaussPoints();
}
int N0 = nodePos.size();
// create new domain map
FEDomainMap* elemData = new FEDomainMap(map->DataType(), Storage_Fmt::FMT_MATPOINTS);
FEElementSet* eset = new FEElementSet(&fem);
eset->Create(&dom);
elemData->Create(eset);
vector<double> srcData(N0);
vector<double> trgData(NMP);
vector< vector<double> > mappedData(NMP, vector<double>(9, 0.0));
// loop over all the new nodes
for (int l = 0; l < dataSize; ++l)
{
for (int i = 0; i < N0; ++i)
{
double vm = 0.0;
switch (dataType)
{
case FEDataType::FE_DOUBLE: vm = map->value<double>(0, i); break;
case FEDataType::FE_VEC3D:
{
vec3d v = map->value<vec3d>(0, i);
if (l == 0) vm = v.x;
if (l == 1) vm = v.y;
if (l == 2) vm = v.z;
}
break;
case FEDataType::FE_MAT3D:
{
int LUT[9][2] = { {0,0}, {0,1}, {0,2}, {1,0}, {1,1}, {1,2}, {2,0}, {2,1}, {2,2} };
mat3d v = map->value<mat3d>(0, i);
vm = v(LUT[l][0], LUT[l][1]);
}
break;
case FEDataType::FE_MAT3DS:
{
int LUT[6][2] = { {0,0}, {0,1}, {0,2}, {1,1}, {1,2}, {2,2} };
mat3ds v = map->value<mat3ds>(0, i);
vm = v(LUT[l][0], LUT[l][1]);
}
break;
default:
assert(false);
}
srcData[i] = vm;
}
dataMapper->Map(trgData, [&srcData](int sourcePoint) {
return srcData[sourcePoint];
});
for (int i = 0; i < NMP; ++i)
{
mappedData[i][l] = trgData[i];
}
}
// write mapped data to domain map
int n = 0;
for (int i = 0; i < dom.Elements(); ++i)
{
FEElement& el = dom.ElementRef(i);
int nint = el.GaussPoints();
for (int j = 0; j < nint; ++j)
{
vector<double>& vj = mappedData[n++];
for (int l = 0; l < dataSize; ++l)
{
switch (dataType)
{
case FEDataType::FE_DOUBLE: elemData->setValue(i, j, vj[0]); break;
case FEDataType::FE_VEC3D:
{
vec3d v;
v.x = vj[0];
v.y = vj[1];
v.z = vj[2];
elemData->setValue(i, j, v);
}
break;
case FEDataType::FE_MAT3D:
{
mat3d v;
v(0, 0) = vj[0]; v(0, 1) = vj[1]; v(0, 2) = vj[2];
v(1, 0) = vj[3]; v(1, 1) = vj[4]; v(1, 2) = vj[5];
v(2, 0) = vj[6]; v(2, 1) = vj[7]; v(2, 2) = vj[8];
elemData->setValue(i, j, v);
}
break;
case FEDataType::FE_MAT3DS:
{
mat3ds v;
v(0, 0) = vj[0];
v(0, 1) = vj[1];
v(0, 2) = vj[2];
v(1, 1) = vj[3];
v(1, 2) = vj[4];
v(2, 2) = vj[5];
elemData->setValue(i, j, v);
}
break;
default:
assert(false);
}
}
}
}
return elemData;
}
bool createNodeDataMap(FEDomain& dom, FEDomainMap* map, FEDomainMap* nodeMap)
{
FEDataType dataType = map->DataType();
int dataSize = 0;
switch (dataType)
{
case FEDataType::FE_DOUBLE: dataSize = 1; break;
case FEDataType::FE_VEC3D: dataSize = 3; break;
case FEDataType::FE_MAT3D: dataSize = 9; break;
case FEDataType::FE_MAT3DS: dataSize = 6; break;
default:
assert(false);
return false;
}
// temp storage
double si[FEElement::MAX_INTPOINTS * 9];
double sn[FEElement::MAX_NODES * 9];
// allocate node data
int NN = dom.Nodes();
vector<double> nodeData(NN*dataSize);
// build tag list
vector<int> tag(NN, 0);
int NE = dom.Elements();
for (int i = 0; i < NE; ++i)
{
FEElement& e = dom.ElementRef(i);
int ne = e.Nodes();
for (int k = 0; k < ne; ++k)
{
tag[e.m_lnode[k]]++;
}
}
// get the data format
int dataFormat = map->StorageFormat();
if ((dataFormat != FMT_MATPOINTS) && (dataFormat != FMT_MULT)) return false;
// loop over all elements
for (int i = 0; i < NE; ++i)
{
FEElement& e = dom.ElementRef(i);
int ne = e.Nodes();
int ni = (dataFormat == FMT_MATPOINTS ? e.GaussPoints() : ne);
for (int j = 0; j < dataSize; ++j)
{
// get the integration point values
for (int k = 0; k < ni; ++k)
{
switch (dataType)
{
case FEDataType::FE_DOUBLE:
si[k] = map->value<double>(i, k);
break;
case FEDataType::FE_VEC3D:
{
vec3d v = map->value<vec3d>(i, k);
if (j == 0) si[k] = v.x;
if (j == 1) si[k] = v.y;
if (j == 2) si[k] = v.z;
}
break;
case FEDataType::FE_MAT3D:
{
mat3d v = map->value<mat3d>(i, k);
int LUT[9][2] = { {0,0}, {0,1}, {0,2}, {1,0}, {1,1}, {1,2}, {2,0}, {2,1}, {2,2} };
si[k] = v(LUT[j][0], LUT[j][1]);
}
break;
case FEDataType::FE_MAT3DS:
{
mat3ds v = map->value<mat3ds>(i, k);
int LUT[6][2] = { {0,0}, {0,1}, {0,2}, {1,1}, {1,2}, {2,2} };
si[k] = v(LUT[j][0], LUT[j][1]);
}
break;
}
}
// project to nodes
if (dataFormat == FMT_MATPOINTS)
{
e.project_to_nodes(si, sn);
}
else
{
for (int k = 0; k < ne; ++k) sn[k] = si[k];
}
for (int k = 0; k < ne; ++k)
{
nodeData[e.m_lnode[k] * dataSize + j] += sn[k];
}
}
}
// normalize data
for (int i = 0; i < NN; ++i)
{
if (tag[i] > 0)
{
for (int j = 0; j < dataSize; ++j)
nodeData[i*dataSize + j] /= (double)tag[i];
}
}
// check node data map
if (nodeMap->StorageFormat() != Storage_Fmt::FMT_NODE) return false;
if (nodeMap->DataType() != dataType) return false;
if (nodeMap->DataCount() != NN) return false;
// assign data
for (int i = 0; i < NN; ++i)
{
switch (dataType)
{
case FEDataType::FE_DOUBLE: nodeMap->setValue(i, nodeData[i]); break;
case FEDataType::FE_VEC3D:
{
vec3d v;
v.x = nodeData[i*dataSize];
v.y = nodeData[i*dataSize + 1];
v.z = nodeData[i*dataSize + 2];
nodeMap->setValue(i, v);
}
break;
case FEDataType::FE_MAT3D:
{
mat3d v;
v(0, 0) = nodeData[i*dataSize]; v(0, 1) = nodeData[i*dataSize + 1]; v(0, 2) = nodeData[i*dataSize + 2];
v(1, 0) = nodeData[i*dataSize + 3]; v(1, 1) = nodeData[i*dataSize + 4]; v(1, 2) = nodeData[i*dataSize + 5];
v(2, 0) = nodeData[i*dataSize + 6]; v(2, 1) = nodeData[i*dataSize + 7]; v(2, 2) = nodeData[i*dataSize + 8];
nodeMap->setValue(i, v);
}
break;
case FEDataType::FE_MAT3DS:
{
mat3ds v;
v(0, 0) = nodeData[i*dataSize];
v(0, 1) = nodeData[i*dataSize + 1];
v(0, 2) = nodeData[i*dataSize + 2];
v(1, 1) = nodeData[i*dataSize + 3];
v(1, 2) = nodeData[i*dataSize + 4];
v(2, 2) = nodeData[i*dataSize + 5];
nodeMap->setValue(i, v);
}
break;
}
}
return true;
}
void NodeToElemData(FEModel& fem, FEDomain& dom, FEDomainMap* nodeMap, FEDomainMap* elemMap, FEMeshDataInterpolator* dataMapper)
{
assert(nodeMap->StorageFormat() == Storage_Fmt::FMT_NODE);
FEDataType dataType = nodeMap->DataType();
int dataSize = 0;
switch (dataType)
{
case FEDataType::FE_DOUBLE: dataSize = 1; break;
case FEDataType::FE_VEC3D: dataSize = 3; break;
case FEDataType::FE_MAT3D: dataSize = 9; break;
case FEDataType::FE_MAT3DS: dataSize = 6; break;
default:
assert(false);
throw std::runtime_error("Error in FEMMGRemesh::MMG::NodeToElemData");
return;
}
// count nr of points
int NN = nodeMap->DataCount();
// count nr of target points
int NE = dom.Elements();
int NP = 0;
for (int i = 0; i < dom.Elements(); ++i)
{
FEElement& el = dom.ElementRef(i);
NP += el.Nodes();
}
vector<double> srcData(NN);
vector<double> trgData(NP);
vector< vector<double> > mappedData(NP, vector<double>(9, 0.0));
// loop over all the new nodes
for (int l = 0; l < dataSize; ++l)
{
for (int i = 0; i < NN; ++i)
{
double vm = 0.0;
switch (dataType)
{
case FEDataType::FE_DOUBLE: vm = nodeMap->value<double>(0, i); break;
case FEDataType::FE_VEC3D:
{
vec3d v = nodeMap->value<vec3d>(0, i);
if (l == 0) vm = v.x;
if (l == 1) vm = v.y;
if (l == 2) vm = v.z;
}
break;
case FEDataType::FE_MAT3D:
{
int LUT[9][2] = { {0,0}, {0,1}, {0,2}, {1,0}, {1,1}, {1,2}, {2,0}, {2,1}, {2,2} };
mat3d v = nodeMap->value<mat3d>(0, i);
vm = v(LUT[l][0], LUT[l][1]);
}
break;
case FEDataType::FE_MAT3DS:
{
int LUT[6][2] = { {0,0}, {0,1}, {0,2}, {1,1}, {1,2}, {2,2} };
mat3ds v = nodeMap->value<mat3ds>(0, i);
vm = v(LUT[l][0], LUT[l][1]);
}
break;
default:
assert(false);
}
srcData[i] = vm;
}
dataMapper->Map(trgData, [&srcData](int sourcePoint) {
return srcData[sourcePoint];
});
for (int i = 0; i < NP; ++i)
{
mappedData[i][l] = trgData[i];
}
}
// create new element set
FEElementSet* eset = new FEElementSet(&fem);
eset->Create(&dom);
elemMap->Create(eset);
// write mapped data to domain map
int n = 0;
for (int i = 0; i < dom.Elements(); ++i)
{
FEElement& el = dom.ElementRef(i);
for (int k = 0; k < el.Nodes(); ++k)
{
vector<double>& vj = mappedData[n++];
switch (dataType)
{
case FEDataType::FE_DOUBLE: elemMap->setValue(i, k, vj[0]); break;
case FEDataType::FE_VEC3D:
{
vec3d v;
v.x = vj[0];
v.y = vj[1];
v.z = vj[2];
elemMap->setValue(i, k, v);
}
break;
case FEDataType::FE_MAT3D:
{
mat3d v;
v(0, 0) = vj[0]; v(0, 1) = vj[1]; v(0, 2) = vj[2];
v(1, 0) = vj[3]; v(1, 1) = vj[4]; v(1, 2) = vj[5];
v(2, 0) = vj[6]; v(2, 1) = vj[7]; v(2, 2) = vj[8];
elemMap->setValue(i, k, v);
}
break;
case FEDataType::FE_MAT3DS:
{
mat3ds v;
v(0, 0) = vj[0];
v(0, 1) = vj[1];
v(0, 2) = vj[2];
v(1, 1) = vj[3];
v(1, 2) = vj[4];
v(2, 2) = vj[5];
elemMap->setValue(i, k, v);
}
break;
default:
assert(false);
}
}
}
}
bool FERefineMesh::BuildMapData()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// make a copy of the old mesh
// we need it for mapping data
CopyMesh();
// clear all map data
ClearMapData();
m_domainMapList.clear();
m_domainMapList.resize(mesh.Domains());
// only map domain data if requested
if (m_bmap_data)
{
if (BuildDomainMapData() == false)
{
return false;
}
}
// do the same thing for the user-defined mesh data
return BuildUserMapData();
}
bool FERefineMesh::BuildDomainMapData()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// loop over all domains
for (int i = 0; i < mesh.Domains(); ++i)
{
FEDomain& dom = mesh.Domain(i);
feLog(" Processing domain: %s\n", dom.GetName().c_str());
if (BuildDomainMapData(dom, i) == false)
{
return false;
}
}
return true;
}
bool FERefineMesh::BuildDomainMapData(FEDomain& dom, int domIndex)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// write all material point data to a data stream
DumpMemStream ar(fem);
ar.Open(true, true);
ar.WriteTypeInfo(true);
// loop over all integration points
int totalPoints = 0;
for (int j = 0; j < dom.Elements(); ++j)
{
FEElement& el = dom.ElementRef(j);
int nint = el.GaussPoints();
for (int k = 0; k < nint; ++k)
{
FEMaterialPoint* mp = el.GetMaterialPoint(k);
mp->Serialize(ar);
}
totalPoints += nint;
}
// figure out how much data was written for each material point
size_t bytes = ar.bytesSerialized();
size_t bytesPerPoint = bytes / totalPoints;
assert((bytes%totalPoints) == 0);
// re-open for reading
ar.Open(false, true);
// create an element set (we need this for the domain map below)
FEDomain& oldDomain = m_meshCopy->Domain(domIndex);
FEElementSet* elemSet = new FEElementSet(&fem);
elemSet->Create(&oldDomain);
// next, we need to figure out the datamaps for each data item
vector<FEDomainMap*> mapList;
DumpStream::DataBlock d;
while (ar.bytesSerialized() < bytesPerPoint)
{
ar.readBlock(d);
const char* typeStr = nullptr;
FEDomainMap* map = nullptr;
switch (d.dataType())
{
case TypeID::TYPE_DOUBLE: map = new FEDomainMap(FEDataType::FE_DOUBLE, Storage_Fmt::FMT_MATPOINTS); typeStr = "double"; break;
case TypeID::TYPE_VEC3D: map = new FEDomainMap(FEDataType::FE_VEC3D, Storage_Fmt::FMT_MATPOINTS); typeStr = "vec3d"; break;
case TypeID::TYPE_MAT3D: map = new FEDomainMap(FEDataType::FE_MAT3D, Storage_Fmt::FMT_MATPOINTS); typeStr = "mat3d"; break;
case TypeID::TYPE_MAT3DS: map = new FEDomainMap(FEDataType::FE_MAT3DS, Storage_Fmt::FMT_MATPOINTS); typeStr = "mat3ds"; break;
default:
assert(false);
throw std::runtime_error("Error in mapping data.");
}
map->Create(elemSet, 0.0);
feLog("\tData map %d: %s\n", mapList.size(), typeStr);
mapList.push_back(map);
}
feLog(" %d data maps identified.\n", mapList.size());
// rewind for processing
ar.Open(false, true);
for (int j = 0; j < dom.Elements(); ++j)
{
FEElement& el = dom.ElementRef(j);
int nint = el.GaussPoints();
for (int k = 0; k < nint; ++k)
{
int m = 0;
size_t bytesRead = 0;
while (bytesRead < bytesPerPoint)
{
size_t size0 = ar.bytesSerialized();
bool b = ar.readBlock(d); assert(b);
size_t size1 = ar.bytesSerialized();
bytesRead += size1 - size0;
FEDomainMap* map = mapList[m];
switch (d.dataType())
{
case TypeID::TYPE_DOUBLE: { double v = d.value<double>(); map->setValue(j, k, v); } break;
case TypeID::TYPE_MAT3D: { mat3d v = d.value<mat3d >(); map->setValue(j, k, v); } break;
case TypeID::TYPE_MAT3DS: { mat3ds v = d.value<mat3ds>(); map->setValue(j, k, v); } break;
}
m++;
assert(m <= mapList.size());
}
}
}
// Now, we need to project all the data onto the nodes
for (int j = 0; j < mapList.size(); ++j)
{
feLog("\tProcessing data map %d ...", j);
FEDomainMap* elemMap = mapList[j];
FEDataType dataType = elemMap->DataType();
FEDomainMap* nodeMap = new FEDomainMap(dataType, Storage_Fmt::FMT_NODE);
FEElementSet* elset = const_cast<FEElementSet*>(elemMap->GetElementSet());
nodeMap->Create(elset);
bool bret = createNodeDataMap(dom, elemMap, nodeMap); assert(bret);
m_domainMapList[domIndex].push_back(nodeMap);
feLog("done.\n");
}
return true;
}
bool FERefineMesh::BuildUserMapData()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
m_userDataList.clear();
int dataMaps = mesh.DataMaps();
if (dataMaps > 0) feLog(" Processing user data maps:\n");
for (int i = 0; i < dataMaps; ++i)
{
FEDataMap* dataMap = mesh.GetDataMap(i);
// process domain map
FEDomainMap* dmap = dynamic_cast<FEDomainMap*>(dataMap);
if (dmap)
{
FEDataType dataType = dmap->DataType();
if ((dataType != FEDataType::FE_DOUBLE) &&
(dataType != FEDataType::FE_VEC3D)) return false;
feLog("\tProcessing user data map \"%s\" ...", dmap->GetName().c_str());
const FEElementSet* elset = dmap->GetElementSet();
const FEDomainList& domainList = elset->GetDomainList();
if (domainList.Domains() != 1) return false;
FEDomain& dom = const_cast<FEDomain&>(*domainList.GetDomain(0));
FEElementSet* oldElemSet = m_meshCopy->FindElementSet(dom.GetName()); assert(oldElemSet);
FEDomainMap* nodeMap = new FEDomainMap(dataType, Storage_Fmt::FMT_NODE);
nodeMap->Create(oldElemSet);
// create a node data map of this domain map
createNodeDataMap(dom, dmap, nodeMap);
m_userDataList.push_back(nodeMap);
feLog("done.\n");
}
FESurfaceMap* smap = dynamic_cast<FESurfaceMap*>(dataMap);
if (smap)
{
assert(false);
}
}
return true;
}
// Transfer data to new mesh
void FERefineMesh::TransferMapData()
{
// transfer domain data
if (m_bmap_data) TransferDomainMapData();
// transfer user-defined maps
TransferUserMapData();
}
// Transfer domain data back to the new mesh
void FERefineMesh::TransferDomainMapData()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// loop over all domains
if (m_bmap_data && m_domainMapList.size())
{
for (int i = 0; i < mesh.Domains(); ++i)
{
FEDomain& dom = mesh.Domain(i);
std::vector<FEDomainMap*>& nodeMap_i = m_domainMapList[i];
int mapCount = nodeMap_i.size();
if (mapCount > 0)
{
feLog(" Mapping data for domain \"%s\":\n", dom.GetName().c_str());
// we need an element set for the domain maps below
FEElementSet* elemSet = new FEElementSet(&fem);
elemSet->Create(&dom);
// build source point list
FEDomain& oldDomain = m_meshCopy->Domain(i);
vector<vec3d> srcPoints; srcPoints.reserve(oldDomain.Nodes());
for (int i = 0; i < oldDomain.Nodes(); ++i)
{
vec3d r = oldDomain.Node(i).m_r0;
srcPoints.push_back(r);
}
// build target node list
vector<vec3d> trgPoints; trgPoints.reserve(dom.Elements());
for (int i = 0; i < dom.Elements(); ++i)
{
FEElement& el = dom.ElementRef(i);
int nint = el.GaussPoints();
for (int j = 0; j < nint; ++j)
{
FEMaterialPoint& mp = *el.GetMaterialPoint(j);
vec3d r = mp.m_r0;
trgPoints.push_back(r);
}
}
// set up mapper
FEMeshDataInterpolator* mapper = nullptr;
switch (m_transferMethod)
{
case TRANSFER_SHAPE:
{
FEDomain* oldDomain = &m_meshCopy->Domain(i);
FEDomainShapeInterpolator* dsm = new FEDomainShapeInterpolator(oldDomain);
dsm->SetTargetPoints(trgPoints);
mapper = dsm;
}
break;
case TRANSFER_MLQ:
{
FELeastSquaresInterpolator* MLQ = new FELeastSquaresInterpolator;
MLQ->SetNearestNeighborCount(m_nnc);
MLQ->SetDimension(m_nsdim);
MLQ->SetSourcePoints(srcPoints);
MLQ->SetTargetPoints(trgPoints);
mapper = MLQ;
}
break;
default:
assert(false);
return;
}
if (mapper->Init() == false)
{
assert(false);
throw std::runtime_error("Failed to initialize LLQ");
}
// loop over all the domain maps
vector<FEDomainMap*> elemMapList(mapCount);
for (int j = 0; j < mapCount; ++j)
{
feLog("\tMapping map %d ...", j);
FEDomainMap* nodeMap = nodeMap_i[j];
// map node data to integration points
FEDomainMap* elemMap = createElemDataMap(fem, dom, srcPoints, nodeMap, mapper);
elemMapList[j] = elemMap;
feLog("done.\n");
}
// now we need to reconstruct the data stream
DumpMemStream ar(fem);
ar.Open(true, true);
for (int j = 0; j < dom.Elements(); ++j)
{
FEElement& el = dom.ElementRef(j);
int nint = el.GaussPoints();
for (int k = 0; k < nint; ++k)
{
for (int l = 0; l < mapCount; ++l)
{
FEDomainMap* map = elemMapList[l];
switch (map->DataType())
{
case FEDataType::FE_DOUBLE: { double v = map->value<double>(j, k); ar << v; } break;
case FEDataType::FE_VEC3D: { vec3d v = map->value<vec3d >(j, k); ar << v; } break;
case FEDataType::FE_MAT3D: { mat3d v = map->value<mat3d >(j, k); ar << v; } break;
case FEDataType::FE_MAT3DS: { mat3ds v = map->value<mat3ds>(j, k); ar << v; } break;
default:
assert(false);
}
}
}
}
// time to serialize everything back to the new integration points
ar.Open(false, true);
for (int j = 0; j < dom.Elements(); ++j)
{
FEElement& el = dom.ElementRef(j);
int nint = el.GaussPoints();
for (int k = 0; k < nint; ++k)
{
FEMaterialPoint& mp = *el.GetMaterialPoint(k);
mp.Serialize(ar);
}
}
}
}
}
}
// Transfer user data maps to new mesh
void FERefineMesh::TransferUserMapData()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// map mesh data
for (int i = 0; i < m_userDataList.size(); ++i)
{
FEDomainMap* elemMap = dynamic_cast<FEDomainMap*>(mesh.GetDataMap(i));
FEDomainMap* nodeMap = m_userDataList[i];
feLog("\tMapping user map \"%s\" ...", elemMap->GetName().c_str());
// build the source point list
vector<vec3d> srcPoints;
const FEElementSet* oldSet = nodeMap->GetElementSet();
FEMesh* oldMesh = oldSet->GetMesh(); assert(oldMesh == m_meshCopy);
FENodeList oldNodeList = oldSet->GetNodeList();
srcPoints.resize(oldNodeList.Size());
for (int i = 0; i < oldNodeList.Size(); ++i)
{
FENode& oldNode_i = oldMesh->Node(oldNodeList[i]);
vec3d r = oldNode_i.m_r0;
srcPoints[i] = r;
}
// build target points.
const FEDomainList& domainList = elemMap->GetElementSet()->GetDomainList();
FEDomain& dom = const_cast<FEDomain&>(*domainList.GetDomain(0));
int NE = dom.Elements();
vector<vec3d> trgPoints; trgPoints.reserve(NE);
for (int n = 0; n < NE; ++n)
{
FEElement& el = dom.ElementRef(n);
int ne = el.Nodes();
for (int l = 0; l < ne; ++l)
{
vec3d r = mesh.Node(el.m_node[l]).m_r0;
trgPoints.push_back(r);
}
}
// set up mapper
FEMeshDataInterpolator* mapper = nullptr;
switch (m_transferMethod)
{
case TRANSFER_SHAPE:
{
FEDomain* oldDomain = m_meshCopy->FindDomain(dom.GetName());
FEDomainShapeInterpolator* dsm = new FEDomainShapeInterpolator(oldDomain);
dsm->SetTargetPoints(trgPoints);
mapper = dsm;
}
break;
case TRANSFER_MLQ:
{
FELeastSquaresInterpolator* MLQ = new FELeastSquaresInterpolator;
MLQ->SetNearestNeighborCount(m_nnc);
MLQ->SetDimension(m_nsdim);
MLQ->SetSourcePoints(srcPoints);
MLQ->SetTargetPoints(trgPoints);
mapper = MLQ;
}
break;
default:
assert(false);
return;
}
if (mapper->Init() == false)
{
assert(false);
throw std::runtime_error("Failed to initialize LLQ");
}
// map node data to integration points
NodeToElemData(fem, dom, nodeMap, elemMap, mapper);
feLog("done.\n");
}
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEScaleAdaptorCriterion.h | .h | 1,718 | 45 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEMeshAdaptorCriterion.h>
#include <FECore/FEModelParam.h>
class FEMaterialPoint;
//-----------------------------------------------------------------------------
class FEScaleAdaptorCriterion : public FEMeshAdaptorCriterion
{
public:
FEScaleAdaptorCriterion(FEModel* fem);
bool GetMaterialPointValue(FEMaterialPoint& mp, double& value) override;
private:
FEParamDouble m_scale;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FEDomainErrorCriterion.cpp | .cpp | 3,887 | 140 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEDomainErrorCriterion.h"
#include <FECore/FEModel.h>
#include <FECore/FEMesh.h>
#include <FECore/FEMeshAdaptor.h> // for projectToNodes
BEGIN_FECORE_CLASS(FEDomainErrorCriterion, FEMeshAdaptorCriterion)
ADD_PARAMETER(m_error, "error");
ADD_PROPERTY(m_data, "data");
END_FECORE_CLASS();
FEDomainErrorCriterion::FEDomainErrorCriterion(FEModel* fem) : FEMeshAdaptorCriterion(fem)
{
m_error = 0.0;
m_data = nullptr;
}
double MinEdgeLengthSqr(FEMesh* pm, FEElement& el)
{
double h2 = 1e99;
int ne = el.Nodes();
for (int i = 0; i < ne; ++i)
{
for (int j = 0; j < ne; ++j)
{
if (i != j)
{
vec3d a = pm->Node(el.m_node[i]).m_r0;
vec3d b = pm->Node(el.m_node[j]).m_r0;
double L2 = (a - b).norm2();
if (L2 < h2) h2 = L2;
}
}
}
return h2;
}
FEMeshAdaptorSelection FEDomainErrorCriterion::GetElementSelection(FEElementSet* elemSet)
{
// get the mesh
FEMesh& mesh = GetFEModel()->GetMesh();
int NE = mesh.Elements();
int NN = mesh.Nodes();
// calculate the recovered nodal stresses
vector<double> sn(NN);
projectToNodes(mesh, sn, [=](FEMaterialPoint& mp) {
double val = 0.0;
m_data->GetMaterialPointValue(mp, val);
return val;
});
// the element list of elements that need to be refined
FEMeshAdaptorSelection elemList;
// find the min and max stress values
FEElementIterator it(&mesh, elemSet);
double smin = 1e99, smax = -1e99;
for (; it.isValid(); ++it)
{
FEElement& el = *it;
int ni = el.GaussPoints();
for (int j = 0; j < ni; ++j)
{
double sj = 0.0;
m_data->GetMaterialPointValue(*el.GetMaterialPoint(j), sj);
if (sj < smin) smin = sj;
if (sj > smax) smax = sj;
}
}
if (fabs(smin - smax) < 1e-12) return elemList;
// calculate errors
double ev[FEElement::MAX_NODES];
it.reset();
for (int i = 0; it.isValid(); ++it, ++i)
{
FEElement& el = *it;
int ne = el.Nodes();
int ni = el.GaussPoints();
// get the nodal values
for (int j = 0; j < ne; ++j)
{
ev[j] = sn[el.m_node[j]];
}
// evaluate element error
double max_err = 0;
for (int j = 0; j < ni; ++j)
{
double sj = 0.0;
m_data->GetMaterialPointValue(*el.GetMaterialPoint(j), sj);
double snj = el.Evaluate(ev, j);
double err = fabs(sj - snj) / (smax - smin);
if (err > max_err) max_err = err;
}
// calculate size metric (if m_error defined)
double s = max_err;
if (m_error > 0)
{
s = (max_err > m_error ? m_error / max_err : 1.0);
}
if (s <= 0.0) s = 1.0;
elemList.push_back(el.GetID(), s);
}
// create the element list of elements that need to be refined
return elemList;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEHexRefine.h | .h | 2,148 | 66 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FERefineMesh.h"
class FEHexRefine : public FERefineMesh
{
public:
FEHexRefine(FEModel* fem);
bool Init() override;
bool RefineMesh() override;
protected:
void BuildSplitLists(FEModel& fem);
void UpdateNewNodes(FEModel& fem);
void FindHangingNodes(FEModel& fem);
void BuildNewDomains(FEModel& fem);
void UpdateNodeSet(FENodeSet& nset);
bool UpdateSurface(FESurface& surf);
private:
int m_elemRefine; // max nr of elements to refine per step
double m_maxValue;
vector<int> m_elemList;
vector<int> m_edgeList; // list of edge flags to see whether the edge was split
vector<int> m_faceList; // list of face flags to see whether the face was split
int m_N0;
int m_NC;
int m_NN;
int m_splitElems;
int m_splitFaces;
int m_splitEdges;
int m_hangingNodes;
FEMeshAdaptorCriterion* m_criterion;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FEAMR.h | .h | 1,569 | 37 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "feamr_api.h"
//-----------------------------------------------------------------------------
//! The FEAMR namespace encapsulates all classes that belong to the FEAMR library
namespace FEAMR
{
// initialize the module
FEAMR_API void InitModule();
} // namespace FEAMR
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FETestRefine.cpp | .cpp | 4,766 | 177 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FETestRefine.h"
#include <FECore/FESolidDomain.h>
#include <FECore/FEMeshTopo.h>
#include <FECore/FEFixedBC.h>
#include <FECore/FESurface.h>
#include <FECore/FEModel.h>
#include <FECore/log.h>
BEGIN_FECORE_CLASS(FETestRefine, FERefineMesh)
END_FECORE_CLASS();
FETestRefine::FETestRefine(FEModel* fem) : FERefineMesh(fem)
{
}
struct TRI
{
int n[3];
};
bool FETestRefine::RefineMesh()
{
FEModel& fem = *GetFEModel();
if (m_topo == nullptr) return false;
FEMeshTopo& topo = *m_topo;
FEMesh& mesh = fem.GetMesh();
FESolidDomain& dom = dynamic_cast<FESolidDomain&>(mesh.Domain(0));
int NEL = dom.Elements();
int N0 = mesh.Nodes();
// now we recreate the domains
const int NDOM = mesh.Domains();
for (int i = 0; i < NDOM; ++i)
{
// get the old domain
FEDomain& oldDom = mesh.Domain(i);
int NE0 = oldDom.Elements();
// create a copy of old domain (since we want to retain the old domain)
FEDomain* newDom = fecore_new<FESolidDomain>(oldDom.GetTypeStr(), &fem);
newDom->Create(NE0, FEElementLibrary::GetElementSpecFromType(FE_TET4G4));
for (int j = 0; j < NE0; ++j)
{
FEElement& el0 = oldDom.ElementRef(j);
FEElement& el1 = newDom->ElementRef(j);
for (int k = 0; k < el0.Nodes(); ++k) el1.m_node[k] = el0.m_node[k];
}
// reallocate the old domain
oldDom.Create(NE0, FEElementLibrary::GetElementSpecFromType(FE_TET4G4));
// set new element nodes
int nel = 0;
for (int j = 0; j < NE0; ++j)
{
FEElement& el0 = newDom->ElementRef(j);
FEElement& el1 = oldDom.ElementRef(nel++);
el1.m_node[0] = el0.m_node[0];
el1.m_node[1] = el0.m_node[1];
el1.m_node[2] = el0.m_node[2];
el1.m_node[3] = el0.m_node[3];
}
// we don't need this anymore
delete newDom;
}
mesh.RebuildLUT();
// re-init domains
for (int i = 0; i < NDOM; ++i)
{
FEDomain& dom = mesh.Domain(i);
dom.CreateMaterialPointData();
dom.Reset(); // NOTE: we need to call this to actually call the Init function on the material points.
dom.Init();
dom.Activate();
}
// recreate element sets
for (int i = 0; i < mesh.ElementSets(); ++i)
{
FEElementSet& eset = mesh.ElementSet(i);
// get the domain list
// NOTE: Don't get the reference, since then the same reference
// is passed to Create below, which causes problems.
FEDomainList domList = eset.GetDomainList();
if (domList.IsEmpty()) { throw std::runtime_error("Error in FEMMGRemesh!"); }
// recreate the element set from the domain list
eset.Create(domList);
}
// recreate surfaces
int faceMark = 1;
for (int i = 0; i < mesh.Surfaces(); ++i)
{
FESurface& surf = mesh.Surface(i);
int NF0 = surf.Elements();
vector<int> faceList = topo.FaceIndexList(surf);
assert(faceList.size() == NF0);
vector<TRI> tri(NF0);
for (int j = 0; j < NF0; ++j)
{
FESurfaceElement& el = surf.Element(j);
TRI t;
t.n[0] = el.m_node[0];
t.n[1] = el.m_node[1];
t.n[2] = el.m_node[2];
tri[j] = t;
}
int NF1 = NF0;
surf.Create(NF1);
int nf = 0;
for (int j = 0; j < NF0; ++j)
{
TRI& t = tri[j];
FESurfaceElement& fj = surf.Element(nf++);
fj.SetType(FE_TRI3G3);
fj.m_node[0] = t.n[0];
fj.m_node[1] = t.n[1];
fj.m_node[2] = t.n[2];
}
surf.CreateMaterialPointData();
surf.Init();
// also update the facet set if the surface has one
FEFacetSet* fset = surf.GetFacetSet();
if (fset)
{
fset->Create(surf);
}
faceMark++;
}
// re-activate the model
UpdateModel();
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEVariableCriterion.h | .h | 1,641 | 41 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEMeshAdaptorCriterion.h>
//-----------------------------------------------------------------------------
class FEVariableCriterion : public FEMeshAdaptorCriterion
{
public:
FEVariableCriterion(FEModel* fem);
bool GetMaterialPointValue(FEMaterialPoint& mp, double& value) override;
private:
int m_dof;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FETestRefine.h | .h | 1,454 | 39 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FERefineMesh.h"
class FETestRefine : public FERefineMesh
{
public:
FETestRefine(FEModel* fem);
bool RefineMesh() override;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/FEMeshShapeInterpolator.cpp | .cpp | 3,444 | 118 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "FEMeshShapeInterpolator.h"
#include <FECore/FEOctreeSearch.h>
#include <FECore/FEMesh.h>
//=============================================================================================
FEMeshShapeInterpolator::FEMeshShapeInterpolator(FEMesh* mesh) : m_mesh(mesh)
{
m_os = nullptr;
}
FEMeshShapeInterpolator::~FEMeshShapeInterpolator()
{
delete m_os;
}
bool FEMeshShapeInterpolator::Init()
{
if (m_mesh == nullptr) return false;
if (m_os == nullptr)
{
m_os = new FEOctreeSearch(m_mesh);
if (m_os->Init() == false) return false;
}
int nodes = m_trgPoints.size();
m_data.resize(nodes);
for (int i = 0; i < nodes; ++i)
{
Data& di = m_data[i];
vec3d ri = m_trgPoints[i];
// find the element
di.r[0] = di.r[1] = di.r[2] = 0.0;
di.el = (FESolidElement*)m_os->FindElement(ri, di.r);
if (di.el == nullptr)
{
assert(false);
return false;
}
}
return true;
}
void FEMeshShapeInterpolator::SetTargetPoints(const vector<vec3d>& trgPoints)
{
m_trgPoints = trgPoints;
}
bool FEMeshShapeInterpolator::SetTargetPoint(const vec3d& r)
{
m_trgPoints.clear();
m_trgPoints.push_back(r);
return Init();
}
bool FEMeshShapeInterpolator::Map(std::vector<double>& tval, function<double(int sourceNode)> src)
{
// update solution
int nodes = m_trgPoints.size();
for (int i = 0; i < nodes; ++i)
{
Data& di = m_data[i];
// update values
double v[FEElement::MAX_NODES] = { 0 };
for (int j = 0; j < di.el->Nodes(); ++j) v[j] = src(di.el->m_node[j]);
double vl = di.el->evaluate(v, di.r[0], di.r[1], di.r[2]);
tval[i] = vl;
}
return true;
}
double FEMeshShapeInterpolator::Map(int inode, function<double(int sourceNode)> f)
{
Data& di = m_data[inode];
double v[FEElement::MAX_NODES];
for (int j = 0; j < di.el->Nodes(); ++j) v[j] = f(di.el->m_node[j]);
double vl = di.el->evaluate(v, di.r[0], di.r[1], di.r[2]);
return vl;
}
vec3d FEMeshShapeInterpolator::MapVec3d(int inode, function<vec3d(int sourceNode)> f)
{
Data& di = m_data[inode];
vec3d v[FEElement::MAX_NODES];
for (int j = 0; j < di.el->Nodes(); ++j) v[j] = f(di.el->m_node[j]);
vec3d vl = di.el->evaluate(v, di.r[0], di.r[1], di.r[2]);
return vl;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEMeshDataInterpolator.cpp | .cpp | 1,476 | 40 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "FEMeshDataInterpolator.h"
FEMeshDataInterpolator::FEMeshDataInterpolator()
{
}
FEMeshDataInterpolator::~FEMeshDataInterpolator()
{
}
bool FEMeshDataInterpolator::Init()
{
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEHexRefine2D.cpp | .cpp | 21,933 | 855 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEHexRefine2D.h"
#include <FECore/FEModel.h>
#include <FECore/FESolidDomain.h>
#include <FECore/FEMeshTopo.h>
#include <FECore/FEPrescribedDOF.h>
#include <FECore/FEElementList.h>
#include <FECore/FELinearConstraint.h>
#include <FECore/FELinearConstraintManager.h>
#include <FECore/FEMeshAdaptorCriterion.h>
#include <FECore/FESurface.h>
#include <FECore/log.h>
BEGIN_FECORE_CLASS(FEHexRefine2D, FERefineMesh)
ADD_PARAMETER(m_elemRefine, "max_elem_refine");
ADD_PROPERTY(m_criterion, "criterion");
ADD_PARAMETER(m_maxValue, "max_value");
END_FECORE_CLASS();
FEHexRefine2D::FEHexRefine2D(FEModel* fem) : FERefineMesh(fem)
{
m_maxValue = 0.0;
m_elemRefine = 0;
m_criterion = nullptr;
}
bool FEHexRefine2D::Init()
{
FEMesh& mesh = GetMesh();
if (mesh.IsType(ET_HEX8) == false)
{
feLogError("Cannot apply hex refinement: Mesh is not a HEX8 mesh.");
return true;
}
return FERefineMesh::Init();
}
bool FEHexRefine2D::RefineMesh()
{
FEMeshTopo& topo = *m_topo;
FEModel& fem = *GetFEModel();
FEMesh& mesh = GetMesh();
FEElementList allElems(mesh);
const int NEL = mesh.Elements();
const int NDOM = mesh.Domains();
m_N0 = mesh.Nodes();
m_NC = topo.Edges();
int NF = topo.Faces();
// Build the lists of items to split
if (BuildSplitLists(fem) == false) return false;
// make sure we have work to do
if (m_splitElems == 0) return false;
// Next, the position and solution variables for all the nodes are updated.
// Note that this has to be done before recreating the elements since
// the old elements are still needed to determine the new positions and solutions.
UpdateNewNodes(fem);
// find the hanging nodes
// and assign linear constraints to tie them down
FindHangingNodes(fem);
// Now, we can create new elements
BuildNewDomains(fem);
// update node sets
for (int i = 0; i < mesh.NodeSets(); ++i)
{
FENodeSet& nset = *mesh.NodeSet(i);
UpdateNodeSet(nset);
}
// update all surfaces
for (int i = 0; i < mesh.Surfaces(); ++i)
{
FESurface& surf = mesh.Surface(i);
if (UpdateSurface(surf) == false) return false;
}
// update all element sets
for (int i = 0; i < mesh.ElementSets(); ++i)
{
FEElementSet& set = mesh.ElementSet(i);
if (UpdateElementSet(set) == false) return false;
}
return true;
}
bool FEHexRefine2D::BuildSplitLists(FEModel& fem)
{
FEMeshTopo& topo = *m_topo;
FEMesh& mesh = fem.GetMesh();
// Get the elements that we need to refine
int NEL = mesh.Elements();
m_elemList.assign(NEL, -1);
if (m_criterion)
{
FEMeshAdaptorSelection selection = m_criterion->GetElementSelection(GetElementSet());
for (int i = 0; i < selection.size(); ++i)
{
if (selection[i].m_elemValue > m_maxValue)
{
int eid = selection[i].m_elementId;
int lid = topo.GetElementIndexFromID(eid);
m_elemList[lid] = 1;
}
}
}
else
{
// just do'em all
m_elemList.assign(NEL, 1);
}
// We cannot split elements that have hanging nodes
// so remove those elements from the list
int nrejected = 0;
for (int i = 0; i < NEL; ++i)
{
if (m_elemList[i] != -1)
{
FEElement& el = *topo.Element(i);
int nel = el.Nodes();
for (int j = 0; j < nel; ++j)
{
if (mesh.Node(el.m_node[j]).HasFlags(FENode::HANGING))
{
// sorry, can't split this element
m_elemList[i] = -1;
nrejected++;
break;
}
}
}
}
if (nrejected > 0)
{
feLog("\tElements rejected: %d\n", nrejected);
}
// count how many elements to split
m_splitElems = 0;
for (int i = 0; i < m_elemList.size(); ++i) {
if (m_elemList[i] == 1) {
m_splitElems++;
}
}
if (m_splitElems == 0) return true;
// make sure we don't exceed the max elements per refinement step
if ((m_elemRefine > 0) && (m_splitElems > m_elemRefine))
{
m_splitElems = 0;
for (int i = 0; i < m_elemList.size(); ++i) {
if (m_elemList[i] == 0) {
if (m_splitElems >= m_elemRefine)
{
m_elemList[i] = -1;
}
else
{
m_splitElems++;
}
}
}
assert(m_splitElems == m_elemRefine);
}
// figure out which faces to refine
int NF = topo.Faces();
m_faceList.assign(NF, -1);
// Faces in the XY plane will be split in four. Other faces will be split in two.
// So, we need to figure out which faces lie in the XY plane and which do not.
// We will mark faces that are not in the XY plane by a -2
for (int i = 0; i < NF; ++i)
{
const FEFaceList::FACE& face = topo.Face(i);
// calculate face normal
vec3d r0 = mesh.Node(face.node[0]).m_r0;
vec3d r1 = mesh.Node(face.node[1]).m_r0;
vec3d r2 = mesh.Node(face.node[2]).m_r0;
vec3d n = (r1 - r0) ^ (r2 - r0); n.unit();
if (fabs(n.z) < 0.999)
{
// this normal is not perpendicular to XY plane, so mark it
m_faceList[i] = -2;
}
}
for (int i = 0; i < m_elemList.size(); ++i)
{
if (m_elemList[i] != -1)
{
int splitFaces = 0;
const std::vector<int>& elface = topo.ElementFaceList(i);
for (int j = 0; j < elface.size(); ++j)
{
if (m_faceList[elface[j]] == -1)
{
// this face will be split in 4
m_faceList[elface[j]] = 1;
splitFaces++;
}
else if (m_faceList[elface[j]] == -2)
{
// this face will be split in 2
m_faceList[elface[j]] = 2;
splitFaces++;
}
}
// There should always be at least two faces to split.
if (splitFaces < 2)
{
feLog("Cannot refine element due to error.");
return false;
}
}
}
// count how many faces to split
int N1 = mesh.Nodes();
m_splitFaces = 0;
for (int i = 0; i < m_faceList.size(); ++i)
{
if (m_faceList[i] == 1) {
m_faceList[i] = N1++;
m_splitFaces++;
}
else if (m_faceList[i] == 2)
{
m_splitFaces++;
m_faceList[i] = -2;
}
else
{
m_faceList[i] = -1;
}
}
// figure out which edges to refine
m_edgeList.assign(m_NC, -1);
for (int i = 0; i < NF; ++i)
{
if (m_faceList[i] >= 0)
{
const std::vector<int>& faceEdge = topo.FaceEdgeList(i);
for (int j = 0; j < faceEdge.size(); ++j) m_edgeList[faceEdge[j]] = 1;
}
}
// count how many edges to split
m_splitEdges = 0;
for (int i = 0; i < m_NC; ++i) {
if (m_edgeList[i] == 1) {
m_edgeList[i] = N1++;
m_splitEdges++;
}
}
feLog("\tRefinement info:\n");
feLog("\t Elements to refine: %d\n", m_splitElems);
feLog("\t Facets to refine : %d\n", m_splitFaces);
feLog("\t Edges to refine : %d\n", m_splitEdges);
return true;
}
// in FEHexRefine.cpp
int findNodeInMesh(FEMesh& mesh, const vec3d& r, double tol = 1e-9);
void FEHexRefine2D::UpdateNewNodes(FEModel& fem)
{
FEMeshTopo& topo = *m_topo;
FEMesh& mesh = fem.GetMesh();
// we need to create a new node for each edge and face that needs to be split
int newNodes = m_splitEdges + m_splitFaces;
// for now, store the position of these new nodes in an array
vector<vec3d> newPos(newNodes);
// get the position of new nodes
int n = 0;
for (int i = 0; i < topo.Edges(); ++i)
{
if (m_edgeList[i] >= 0)
{
const FEEdgeList::EDGE& edge = topo.Edge(i);
vec3d r0 = mesh.Node(edge.node[0]).m_r0;
vec3d r1 = mesh.Node(edge.node[1]).m_r0;
newPos[n++] = (r0 + r1)*0.5;
}
}
for (int i = 0; i < topo.Faces(); ++i)
{
if (m_faceList[i] >= 0)
{
const FEFaceList::FACE& face = topo.Face(i);
vec3d r0(0, 0, 0);
int nn = face.ntype;
for (int j = 0; j < nn; ++j) r0 += mesh.Node(face.node[j]).m_r0;
r0 /= (double)nn;
newPos[n++] = r0;
}
}
// some of these new nodes may coincide with an existing node
//If we find one, we eliminate it
n = 0;
int nremoved = 0;
for (int i = 0; i < topo.Edges(); ++i)
{
if (m_edgeList[i] >= 0)
{
int nodeId = findNodeInMesh(mesh, newPos[n++]);
if (nodeId >= 0)
{
assert(nodeId < m_N0);
if(mesh.Node(nodeId).HasFlags(FENode::HANGING))
mesh.Node(nodeId).UnsetFlags(FENode::HANGING);
m_edgeList[i] = nodeId;
nremoved++;
}
}
}
for (int i = 0; i < topo.Faces(); ++i)
{
if (m_faceList[i] >= 0)
{
int nodeId = findNodeInMesh(mesh, newPos[n++]);
if (nodeId >= 0)
{
assert(nodeId < m_N0);
if(mesh.Node(nodeId).HasFlags(FENode::HANGING))
mesh.Node(nodeId).UnsetFlags(FENode::HANGING);
m_faceList[i] = nodeId;
nremoved++;
}
}
}
// we need to reindex nodes if some were removed
if (nremoved > 0)
{
n = m_N0;
for (int i = 0; i < topo.Edges(); ++i)
{
if (m_edgeList[i] >= m_N0) m_edgeList[i] = n++;
}
for (int i = 0; i < topo.Faces(); ++i)
{
if (m_faceList[i] >= m_N0) m_faceList[i] = n++;
}
assert(n == (m_N0 + newNodes - nremoved));
newNodes -= nremoved;
}
// now, generate new nodes
mesh.AddNodes(newNodes);
// assign dofs to new nodes
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
m_NN = mesh.Nodes();
for (int i = m_N0; i<m_NN; ++i)
{
FENode& node = mesh.Node(i);
node.SetDOFS(MAX_DOFS);
}
// update the position of these new nodes
n = 0;
for (int i = 0; i < topo.Edges(); ++i)
{
if (m_edgeList[i] >= m_N0)
{
const FEEdgeList::EDGE& edge = topo.Edge(i);
FENode& node = mesh.Node(m_edgeList[i]);
vec3d r0 = mesh.Node(edge.node[0]).m_r0;
vec3d r1 = mesh.Node(edge.node[1]).m_r0;
node.m_r0 = (r0 + r1)*0.5;
r0 = mesh.Node(edge.node[0]).m_rt;
r1 = mesh.Node(edge.node[1]).m_rt;
node.m_rt = (r0 + r1)*0.5;
}
}
for (int i = 0; i < topo.Faces(); ++i)
{
if (m_faceList[i] >= m_N0)
{
const FEFaceList::FACE& face = topo.Face(i);
FENode& node = mesh.Node(m_faceList[i]);
int nn = face.ntype;
vec3d r0(0, 0, 0);
for (int j = 0; j < nn; ++j) r0 += mesh.Node(face.node[j]).m_r0;
r0 /= (double)nn;
node.m_r0 = r0;
vec3d rt(0, 0, 0);
for (int j = 0; j < nn; ++j) rt += mesh.Node(face.node[j]).m_rt;
rt /= (double)nn;
node.m_rt = rt;
}
}
// re-evaluate solution at nodes
for (int i = 0; i < topo.Edges(); ++i)
{
if (m_edgeList[i] >= m_N0)
{
const FEEdgeList::EDGE& edge = topo.Edge(i);
FENode& node0 = mesh.Node(edge.node[0]);
FENode& node1 = mesh.Node(edge.node[1]);
FENode& node = mesh.Node(m_edgeList[i]);
for (int j = 0; j < MAX_DOFS; ++j)
{
double v = (node0.get(j) + node1.get(j))*0.5;
node.set(j, v);
}
}
}
for (int i = 0; i < topo.Faces(); ++i)
{
if (m_faceList[i] >= m_N0)
{
const FEFaceList::FACE& face = topo.Face(i);
FENode& node = mesh.Node(m_faceList[i]);
int nn = face.ntype;
for (int j = 0; j < MAX_DOFS; ++j)
{
double v = 0.0;
for (int k = 0; k < nn; ++k) v += mesh.Node(face.node[k]).get(j);
v /= (double)nn;
node.set(j, v);
}
}
}
}
//-----------------------------------------------------------------------------
// This function identifies the hanging nodes and assigns linear constraints to them.
void FEHexRefine2D::FindHangingNodes(FEModel& fem)
{
FEMeshTopo& topo = *m_topo;
FEMesh& mesh = fem.GetMesh();
m_hangingNodes = 0;
FELinearConstraintManager& LCM = fem.GetLinearConstraintManager();
// First, we remove any constraints on nodes that are no longer hanging
int nremoved = 0;
for (int i = 0; i < LCM.LinearConstraints();)
{
FELinearConstraint& lc = LCM.LinearConstraint(i);
int nodeID = lc.GetParentNode();
if (mesh.Node(nodeID).HasFlags(FENode::HANGING) == false)
{
LCM.RemoveLinearConstraint(i);
nremoved++;
}
else i++;
}
feLog("\tRemoved linear constraints : %d\n", nremoved);
// Total nr of degrees of freedom
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
// we loop over non-split faces
int nadded = 0;
vector<int> tag(m_NC, 0);
int NF = topo.Faces();
for (int i = 0; i < NF; ++i)
{
if (m_faceList[i] == -1)
{
// This face is not split
const std::vector<int>& fel = topo.FaceEdgeList(i);
for (int j = 0; j < fel.size(); ++j)
{
if ((m_edgeList[fel[j]] >= 0) && (tag[fel[j]] == 0))
{
// Tag the node as hanging so we can identify it easier later
int nodeId = m_edgeList[fel[j]];
FENode& node = mesh.Node(nodeId);
node.SetFlags(FENode::HANGING);
// get the edge
const FEEdgeList::EDGE& edge = topo.Edge(fel[j]);
// setup a linear constraint for this node
for (int k = 0; k < MAX_DOFS; ++k)
{
FELinearConstraint* lc = new FELinearConstraint(&fem);
lc->SetParentDof(k, nodeId);
lc->AddChildDof(k, edge.node[0], 0.5);
lc->AddChildDof(k, edge.node[1], 0.5);
LCM.AddLinearConstraint(lc);
nadded++;
}
// set a tag to avoid double-counting
tag[fel[j]] = 1;
m_hangingNodes++;
}
}
}
}
feLog("\tHanging nodes ............ : %d\n", m_hangingNodes);
feLog("\tAdded linear constraints . : %d\n", nadded);
}
void FEHexRefine2D::BuildNewDomains(FEModel& fem)
{
// This lookup table defines how a hex will be split in four smaller hexes
const int LUT[4][8] = {
{ 0, 8, 16, 11, 4, 12, 17, 15 },
{ 8, 1, 9, 16, 12, 5, 13, 17 },
{ 11, 16, 10, 3, 15, 17, 14, 7 },
{ 16, 9, 2, 10, 17, 13, 6, 14 }
};
FEMeshTopo& topo = *m_topo;
FEMesh& mesh = fem.GetMesh();
int nelems = 0;
const int NDOM = mesh.Domains();
for (int i = 0; i < NDOM; ++i)
{
// get the old domain
FEDomain& oldDom = mesh.Domain(i);
int NE0 = oldDom.Elements();
// count how many elements to split in this domain
int newElems = 0;
for (int j = 0; j < NE0; ++j)
{
if (m_elemList[nelems + j] != -1) newElems++;
}
// make sure we have something to do
if (newElems > 0)
{
// create a copy of old domain (since we want to retain the old domain)
FEDomain* newDom = fecore_new<FESolidDomain>(oldDom.GetTypeStr(), &fem);
newDom->Create(NE0, FEElementLibrary::GetElementSpecFromType(FE_HEX8G8));
for (int j = 0; j < NE0; ++j)
{
FEElement& el0 = oldDom.ElementRef(j);
FEElement& el1 = newDom->ElementRef(j);
for (int k = 0; k < el0.Nodes(); ++k) el1.m_node[k] = el0.m_node[k];
el1.m_val = el0.m_val;
}
// reallocate the old domain
oldDom.Create(4 * newElems + (NE0 - newElems), FEElementLibrary::GetElementSpecFromType(FE_HEX8G8));
// set new element nodes
int nel = 0;
for (int j = 0; j < NE0; ++j, nelems++)
{
FEElement& el0 = newDom->ElementRef(j);
if (m_elemList[nelems] != -1)
{
const std::vector<int>& ee = topo.ElementEdgeList(nelems); assert(ee.size() == 12);
const std::vector<int>& ef = topo.ElementFaceList(nelems); assert(ef.size() == 6);
// build the look-up table
int ENL[27] = { 0 };
ENL[ 0] = el0.m_node[0];
ENL[ 1] = el0.m_node[1];
ENL[ 2] = el0.m_node[2];
ENL[ 3] = el0.m_node[3];
ENL[ 4] = el0.m_node[4];
ENL[ 5] = el0.m_node[5];
ENL[ 6] = el0.m_node[6];
ENL[ 7] = el0.m_node[7];
ENL[ 8] = m_edgeList[ee[0]];
ENL[ 9] = m_edgeList[ee[1]];
ENL[10] = m_edgeList[ee[2]];
ENL[11] = m_edgeList[ee[3]];
ENL[12] = m_edgeList[ee[4]];
ENL[13] = m_edgeList[ee[5]];
ENL[14] = m_edgeList[ee[6]];
ENL[15] = m_edgeList[ee[7]];
ENL[16] = m_faceList[ef[4]]; assert(ENL[16] >= 0);
ENL[17] = m_faceList[ef[5]]; assert(ENL[17] >= 0);
// assign nodes to new elements
for (int k = 0; k < 4; ++k)
{
FEElement& el1 = oldDom.ElementRef(nel++);
el1.m_val = el0.m_val;
el1.m_node[0] = ENL[LUT[k][0]];
el1.m_node[1] = ENL[LUT[k][1]];
el1.m_node[2] = ENL[LUT[k][2]];
el1.m_node[3] = ENL[LUT[k][3]];
el1.m_node[4] = ENL[LUT[k][4]];
el1.m_node[5] = ENL[LUT[k][5]];
el1.m_node[6] = ENL[LUT[k][6]];
el1.m_node[7] = ENL[LUT[k][7]];
}
}
else
{
// if the element is not split, we just copy the nodes from
// the old domain
FEElement& el1 = oldDom.ElementRef(nel++);
for (int k = 0; k < el0.Nodes(); ++k) el1.m_node[k] = el0.m_node[k];
el1.m_val = el0.m_val;
}
}
// we don't need this anymore
delete newDom;
}
}
mesh.RebuildLUT();
// re-init domains
for (int i = 0; i < NDOM; ++i)
{
FEDomain& dom = mesh.Domain(i);
dom.CreateMaterialPointData();
dom.Reset(); // NOTE: we need to call this to actually call the Init function on the material points.
dom.Init();
dom.Activate();
}
}
void FEHexRefine2D::UpdateNodeSet(FENodeSet& nset)
{
FEMeshTopo& topo = *m_topo;
vector<int> tag(m_NN, 0);
for (int j = 0; j < nset.Size(); ++j) tag[nset[j]] = 1;
for (int j = 0; j < topo.Edges(); ++j)
{
if (m_edgeList[j] >= 0)
{
const FEEdgeList::EDGE& edge = topo.Edge(j);
if ((tag[edge.node[0]] == 1) && (tag[edge.node[1]] == 1))
{
nset.Add(m_edgeList[j]);
}
}
}
for (int j = 0; j < topo.Faces(); ++j)
{
if (m_faceList[j] >= 0)
{
const FEFaceList::FACE& face = topo.Face(j);
assert(face.ntype == 4);
if ((tag[face.node[0]] == 1) &&
(tag[face.node[1]] == 1) &&
(tag[face.node[2]] == 1) &&
(tag[face.node[3]] == 1))
{
nset.Add(m_faceList[j]);
}
}
}
}
bool FEHexRefine2D::UpdateSurface(FESurface& surf)
{
// look-up table for splitting quads in 4
const int LUT[4][4] = {
{ 0, 4, 8, 7 },
{ 4, 1, 5, 8 },
{ 7, 8, 6, 3 },
{ 8, 5, 2, 6 }
};
FEMeshTopo& topo = *m_topo;
int NF0 = surf.Elements();
// figure out which facets to split
vector<int> faceList = topo.FaceIndexList(surf);
assert((int)faceList.size() == NF0);
// count how many faces to split
int split4 = 0, split2 = 0;
for (int i = 0; i < faceList.size(); ++i)
{
int iface = faceList[i];
if (m_faceList[iface] >= 0) split4++;
if (m_faceList[iface] == -2) split2++;
}
if (split4 + split2 == 0) return surf.Init();
// create a copy of the domain
FESurface oldSurf(GetFEModel());
oldSurf.Create(NF0);
for (int i = 0; i < NF0; ++i)
{
FESurfaceElement& el0 = surf.Element(i);
FESurfaceElement& el1 = oldSurf.Element(i);
el1.SetType(el0.Type());
int nf = el0.Nodes();
for (int j = 0; j < nf; ++j) el1.m_node[j] = el0.m_node[j];
}
// reallocate the domain (Assumes Quad faces!)
int NF1 = NF0 - split4 + 4 * (split4) - split2 + 2*split2;
surf.Create(NF1);
// reinitialize the surface
int n = 0;
for (int i = 0; i < NF0; ++i)
{
FESurfaceElement& el0 = oldSurf.Element(i);
int iface = faceList[i];
if (m_faceList[iface] >= 0)
{
const FEFaceList::FACE& face = topo.Face(iface);
const vector<int>& edge = topo.FaceEdgeList(iface);
int NL[9];
NL[0] = face.node[0];
NL[1] = face.node[1];
NL[2] = face.node[2];
NL[3] = face.node[3];
NL[4] = m_edgeList[edge[0]];
NL[5] = m_edgeList[edge[1]];
NL[6] = m_edgeList[edge[2]];
NL[7] = m_edgeList[edge[3]];
NL[8] = m_faceList[iface];
for (int j = 0; j < 4; ++j)
{
FESurfaceElement& el1 = surf.Element(n++);
el1.SetType(FE_QUAD4G4);
el1.m_node[0] = NL[LUT[j][0]];
el1.m_node[1] = NL[LUT[j][1]];
el1.m_node[2] = NL[LUT[j][2]];
el1.m_node[3] = NL[LUT[j][3]];
}
}
else if (m_faceList[iface] == -2)
{
const FEFaceList::FACE& face = topo.Face(iface);
const vector<int>& edge = topo.FaceEdgeList(iface);
int NL[2][4];
// there should be two edges that are split, and two that are not
int eid[4] = { m_edgeList[edge[0]], m_edgeList[edge[1]], m_edgeList[edge[2]], m_edgeList[edge[3]] };
if ((eid[0] >= 0) && (eid[2] >= 0))
{
assert((eid[1] == -1) && (eid[3] == -1));
NL[0][0] = face.node[0]; NL[1][0] = face.node[1];
NL[0][1] = eid[0]; NL[1][1] = face.node[2];
NL[0][2] = eid[2]; NL[1][2] = eid[2];
NL[0][3] = face.node[3]; NL[1][3] = eid[0];
}
else if ((eid[1] >= 0) && (eid[3] >= 0))
{
assert((eid[0] == -1) && (eid[2] == -1));
NL[0][0] = face.node[0]; NL[1][0] = face.node[2];
NL[0][1] = face.node[1]; NL[1][1] = face.node[3];
NL[0][2] = eid[1]; NL[1][2] = eid[3];
NL[0][3] = eid[3]; NL[1][3] = eid[1];
}
else { assert(false); }
for (int j = 0; j < 2; ++j)
{
FESurfaceElement& el1 = surf.Element(n++);
el1.SetType(FE_QUAD4G4);
el1.m_node[0] = NL[j][0];
el1.m_node[1] = NL[j][1];
el1.m_node[2] = NL[j][2];
el1.m_node[3] = NL[j][3];
}
}
else
{
FESurfaceElement& el1 = surf.Element(n++);
el1.SetType(FE_QUAD4G4);
el1.m_node[0] = el0.m_node[0];
el1.m_node[1] = el0.m_node[1];
el1.m_node[2] = el0.m_node[2];
el1.m_node[3] = el0.m_node[3];
}
}
surf.CreateMaterialPointData();
return surf.Init();
}
bool FEHexRefine2D::UpdateElementSet(FEElementSet& eset)
{
// get the domain list
// NOTE: Don't get the reference, since then the same reference
// is passed to Create below, which causes problems.
FEDomainList domList = eset.GetDomainList();
if (domList.IsEmpty()) { throw std::runtime_error("Error in FEHexRefine2D!"); }
// recreate the element set from the domain list
eset.Create(domList);
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/SpherePointsGenerator.h | .h | 2,965 | 82 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2025 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include <vector>
#include <unordered_map>
#include <array>
#include <FECore/vec3d.h>
#include "feamr_api.h"
struct pair_hash {
template <class T1, class T2>
std::size_t operator()(const std::pair<T1, T2>& p) const {
auto h1 = std::hash<T1>{}(p.first);
auto h2 = std::hash<T2>{}(p.second);
return h1 ^ (h2 << 1);
}
};
enum meshSizes { SMALL = 4, FULL = 6};
class FEAMR_API SpherePointsGenerator
{
public:
static size_t GetNumNodes(int n);
static size_t GetNumFaces(int n);
static std::vector<vec3d>& GetNodes(int n);
static std::vector<std::array<int, 3>>& GetFaces(int n);
private:
SpherePointsGenerator() {}
static void Instantiate();
void GeneratePoints(int n);
vec3d midpoint(const vec3d& a, const vec3d& b);
// Create modified icosahedron which has a belt around the equator
void create_icosahedron(std::vector<vec3d>& vertices, std::vector<std::array<int, 3>>& faces);
void rotate(std::vector<vec3d>& vertices, const vec3d& axis, double angle_rad);
// Aligns the equator of the sphere with the x-y plane
void align_equator(std::vector<vec3d>& vertices);
// Get or create midpoint between two vertices
int get_midpoint_index(int i1, int i2, std::vector<vec3d>& vertices,
std::unordered_map<std::pair<int, int>, int, pair_hash>& midpoint_cache);
// Subdivide icosahedral mesh
void subdivide(std::vector<vec3d>& vertices, std::vector<std::array<int, 3>>& faces, int depth);
private:
static SpherePointsGenerator* m_instance;
std::unordered_map<int, std::vector<vec3d>> m_nodes;
std::unordered_map<int, std::vector<std::array<int, 3>>> m_faces;
};
| Unknown |
3D | febiosoftware/FEBio | FEAMR/sphericalHarmonics.cpp | .cpp | 15,677 | 613 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "sphericalHarmonics.h"
#include "SpherePointsGenerator.h"
#include <algorithm>
#include <unordered_map>
#include <vector>
#ifdef HAS_MMG
#include <mmg/mmgs/libmmgs.h>
#endif
#ifndef M_PI
#define M_PI 3.141592653589793238462643
#endif
using std::vector;
using std::unordered_map;
using sphere = SpherePointsGenerator;
enum NUMTYPE { REALTYPE, IMAGTYPE, COMPLEXTYPE };
double fact(int val)
{
double ans = 1;
for(int i = 1; i <= val; i++)
{
ans *= i;
}
return ans;
}
void getSphereCoords(std::vector<vec3d>& coords, std::vector<double>& theta, std::vector<double>& phi)
{
theta.resize(coords.size());
phi.resize(coords.size());
// get spherical coordinates
for(int index = 0; index < coords.size(); index++)
{
double val = coords[index].z;
if (val<=-1)
{
theta[index] = M_PI;
}
else if (val>=1)
{
theta[index] = 0;
}
else
{
theta[index] = acos(coords[index].z);
}
}
for(int index = 0; index < coords.size(); index++)
{
double x = coords[index].x;
double y = coords[index].y;
if(x > 0)
{
phi[index] = atan(y/x);
}
else if(x < 0 && y >= 0)
{
phi[index] = atan(y/x) + M_PI;
}
else if(x < 0 && y < 0)
{
phi[index] = atan(y/x) - M_PI;
}
else if(x == 0 && y > 0)
{
phi[index] = M_PI/2;
}
else if(x == 0 && y < 0)
{
phi[index] = -M_PI/2;
}
}
}
std::unique_ptr<matrix> compSH(int order, std::vector<double>& theta, std::vector<double>& phi)
{
int numPts = theta.size();
int numCols = (order+1)*(order+2)/2;
std::unique_ptr<matrix> out = std::make_unique<matrix>(numPts, numCols);
out->fill(0,0,numPts, numCols, 0.0);
for(int k = 0; k <= order; k+=2)
{
for(int m = -k; m <= k; m++)
{
int j = (k*k + k + 2)/2 + m - 1;
int numType = COMPLEXTYPE;
double factor = 1;
if(m < 0)
{
numType = REALTYPE;
factor = sqrt(2);
}
else if(m > 0)
{
numType = IMAGTYPE;
factor = sqrt(2);
}
for(int index = 0; index < numPts; index++)
{
(*out)[index][j] = factor*harmonicY(k, m, theta[index], phi[index], numType);
}
}
}
return std::move(out);
}
double harmonicY(int degree, int order, double theta, double phi, int numType)
{
// Will be true if order is both positive and odd
// In that case, we need to negate the answer to match the output
// in Adam's MATLAB code.
int negate = 1;
if(order % 2 == 1) negate = -1;
order = abs(order);
double a = (2*degree+1)/(4*M_PI);
double b = fact(degree-order)/fact(degree+order);
double normalization = sqrt(a*b);
double e;
switch (numType)
{
case REALTYPE:
e = cos(order*phi);
break;
case IMAGTYPE:
e = sin(order*phi);
break;
case COMPLEXTYPE:
e = 1;
break;
default:
break;
}
return normalization*__assoc_legendre_p(degree, order, cos(theta))*pow(-1, degree)*e*negate;
}
void reconstructODF(std::vector<double>& sphHarm, std::vector<double>& ODF, std::vector<double>& theta, std::vector<double>& phi)
{
int order = (sqrt(8*sphHarm.size() + 1) - 3)/2;
ODF.resize(theta.size());
auto T = compSH(order, theta, phi);
(*T).mult(sphHarm, ODF);
// Normalize ODF
double sum = 0;
for(int index = 0; index < ODF.size(); index++)
{
if(ODF[index] < 0)
{
ODF[index] = 0;
}
sum += ODF[index];
}
for(int index = 0; index < ODF.size(); index++)
{
ODF[index] /= sum;
}
}
void altGradient(int order, std::vector<double>& ODF, std::vector<double>& gradient)
{
auto& faces = sphere::GetFaces(FULL);
gradient.resize(ODF.size());
std::fill(gradient.begin(), gradient.end(), 0);
std::vector<int> count(ODF.size(), 0);
for(int index = 0; index < faces.size(); index++)
{
int n0 = faces[index][0];
int n1 = faces[index][1];
int n2 = faces[index][2];
double val0 = ODF[n0];
double val1 = ODF[n1];
double val2 = ODF[n2];
double diff0 = abs(val0 - val1);
double diff1 = abs(val0 - val2);
double diff2 = abs(val1 - val2);
gradient[n0] += diff0 + diff1;
gradient[n1] += diff0 + diff2;
gradient[n2] += diff1 + diff2;
count[n0]++;
count[n1]++;
count[n2]++;
}
for(int index = 0; index < gradient.size(); index++)
{
gradient[index] /= count[index];
}
}
#ifdef HAS_MMG
void remesh(std::vector<double>& gradient, double lengthScale, double hausd, double grad, std::vector<vec3d>& nodePos, std::vector<vec3i>& elems)
{
auto& nodes = sphere::GetNodes(FULL);
auto& faces = sphere::GetFaces(FULL);
int NN = nodes.size();
int NF = faces.size();;
int NC;
// we only want to remesh half of the sphere, so here we discard
// any nodes that have a z coordinate < 0, and any elements defined
// with those nodes.
unordered_map<int, int> newNodeIDs;
int newNodeID = 1;
for(int index = 0; index < NN; index++)
{
if(nodes[index].z >= 0)
{
newNodeIDs[index] = newNodeID;
newNodeID++;
}
}
unordered_map<int, int> newElemIDs;
int newElemID = 1;
for(int index = 0; index < NF; index++)
{
if(newNodeIDs.count(faces[index][0]) == 0 || newNodeIDs.count(faces[index][1]) == 0 || newNodeIDs.count(faces[index][2]) == 0)
{
continue;
}
newElemIDs[index] = newElemID;
newElemID++;
}
// build the MMG mesh
MMG5_pMesh mmgMesh;
MMG5_pSol mmgSol;
mmgMesh = NULL;
mmgSol = NULL;
MMGS_Init_mesh(MMG5_ARG_start,
MMG5_ARG_ppMesh, &mmgMesh,
MMG5_ARG_ppMet, &mmgSol,
MMG5_ARG_end);
// allocate mesh size
if (MMGS_Set_meshSize(mmgMesh, newNodeID-1, newElemID-1, 0) != 1)
{
assert(false);
}
// build the MMG mesh
for (int i = 0; i < NN; ++i)
{
if(newNodeIDs.count(i))
{
MMGS_Set_vertex(mmgMesh, nodes[i].x, nodes[i].y, nodes[i].z, 0, newNodeIDs[i]);
}
}
for (int i = 0; i < NF; ++i)
{
if(newElemIDs.count(i))
{
MMGS_Set_triangle(mmgMesh, newNodeIDs[faces[i][0]], newNodeIDs[faces[i][1]], newNodeIDs[faces[i][2]], 0, newElemIDs[i]);
}
}
// Now, we build the "solution", i.e. the target element size.
// If no elements are selected, we set a homogenous remeshing using the element size parameter.
// set the "solution", i.e. desired element size
if (MMGS_Set_solSize(mmgMesh, mmgSol, MMG5_Vertex, newNodeID-1, MMG5_Scalar) != 1)
{
assert(false);
}
int n0 = faces[0][0];
int n1 = faces[0][1];
vec3d pos0 = nodes[n0];
vec3d pos1 = nodes[n1];
double minLength = (pos0 - pos1).Length();
double maxLength = minLength*lengthScale;
double min = *std::min_element(gradient.begin(), gradient.end());
double max = *std::max_element(gradient.begin(), gradient.end());
double range = max-min;
for (int k = 0; k < NN; k++) {
if(newNodeIDs.count(k))
{
double val = (maxLength - minLength)*(1-(gradient[k] - min)/range) + minLength;
MMGS_Set_scalarSol(mmgSol, val, newNodeIDs[k]);
}
}
// set the control parameters
MMGS_Set_dparameter(mmgMesh, mmgSol, MMGS_DPARAM_hmin, minLength);
MMGS_Set_dparameter(mmgMesh, mmgSol, MMGS_DPARAM_hausd, hausd);
MMGS_Set_dparameter(mmgMesh, mmgSol, MMGS_DPARAM_hgrad, grad);
// prevent MMG from outputing information to stdout
MMGS_Set_iparameter(mmgMesh, mmgSol, MMGS_IPARAM_verbose, -1);
// run the mesher
int ier = MMGS_mmgslib(mmgMesh, mmgSol);
if (ier == MMG5_STRONGFAILURE)
{
assert(false);
}
else if (ier == MMG5_LOWFAILURE)
{
assert(false);
}
// get the new mesh sizes
MMGS_Get_meshSize(mmgMesh, &NN, &NF, &NC);
nodePos.resize(NN);
// get the vertex coordinates
for (int i = 0; i < NN; ++i)
{
double x,y,z;
int g;
int isCorner = 0;
MMGS_Get_vertex(mmgMesh, &x, &y, &z, &g, &isCorner, NULL);
nodePos[i] = vec3d(x,y,z);
}
elems.resize(NF);
// create elements
for (int i=0; i<NF; ++i)
{
int n0, n1, n2, id;
MMGS_Get_triangle(mmgMesh, &n0, &n1, &n2, &id, NULL);
n0--;
n1--;
n2--;
elems[i] = vec3i(n0, n1,n2);
}
// Clean up
MMGS_Free_all(MMG5_ARG_start,
MMG5_ARG_ppMesh, &mmgMesh, MMG5_ARG_ppMet, &mmgSol,
MMG5_ARG_end);
}
void remeshFull(std::vector<double>& gradient, double lengthScale, double hausd, double grad, std::vector<vec3d>& nodePos, std::vector<vec3i>& elems)
{
auto& nodes = sphere::GetNodes(FULL);
auto& faces = sphere::GetFaces(FULL);
int NN = nodes.size();
int NF = faces.size();
int NC;
// build the MMG mesh
MMG5_pMesh mmgMesh;
MMG5_pSol mmgSol;
mmgMesh = NULL;
mmgSol = NULL;
MMGS_Init_mesh(MMG5_ARG_start,
MMG5_ARG_ppMesh, &mmgMesh,
MMG5_ARG_ppMet, &mmgSol,
MMG5_ARG_end);
// allocate mesh size
if (MMGS_Set_meshSize(mmgMesh, NN, NF, 0) != 1)
{
assert(false);
}
// build the MMG mesh
for (int i = 0; i < NN; ++i)
{
MMGS_Set_vertex(mmgMesh, nodes[i].x, nodes[i].y, nodes[i].z, 0, i+1);
}
for (int i = 0; i < NF; ++i)
{
MMGS_Set_triangle(mmgMesh, faces[i][0]+1, faces[i][1]+1, faces[i][2]+1, 0, i+1);
}
// Now, we build the "solution", i.e. the target element size.
// If no elements are selected, we set a homogenous remeshing using the element size parameter.
// set the "solution", i.e. desired element size
if (MMGS_Set_solSize(mmgMesh, mmgSol, MMG5_Vertex, NN, MMG5_Scalar) != 1)
{
assert(false);
}
int n0 = faces[0][0];
int n1 = faces[0][1];
vec3d pos0 = nodes[n0];
vec3d pos1 = nodes[n1];
double minLength = (pos0 - pos1).Length();
double maxLength = minLength*lengthScale;
double min = *std::min_element(gradient.begin(), gradient.end());
double max = *std::max_element(gradient.begin(), gradient.end());
double range = max-min;
for (int k = 0; k < NN; k++)
{
double val = (maxLength - minLength)*(1-(gradient[k] - min)/range) + minLength;
MMGS_Set_scalarSol(mmgSol, val, k+1);
}
// set the control parameters
MMGS_Set_dparameter(mmgMesh, mmgSol, MMGS_DPARAM_hmin, minLength);
MMGS_Set_dparameter(mmgMesh, mmgSol, MMGS_DPARAM_hausd, hausd);
MMGS_Set_dparameter(mmgMesh, mmgSol, MMGS_DPARAM_hgrad, grad);
// prevent MMG from outputing information to stdout
MMGS_Set_iparameter(mmgMesh, mmgSol, MMGS_IPARAM_verbose, -1);
// run the mesher
int ier = MMGS_mmgslib(mmgMesh, mmgSol);
if (ier == MMG5_STRONGFAILURE)
{
assert(false);
}
else if (ier == MMG5_LOWFAILURE)
{
assert(false);
}
// get the new mesh sizes
MMGS_Get_meshSize(mmgMesh, &NN, &NF, &NC);
nodePos.resize(NN);
// get the vertex coordinates
for (int i = 0; i < NN; ++i)
{
double x,y,z;
int g;
int isCorner = 0;
MMGS_Get_vertex(mmgMesh, &x, &y, &z, &g, &isCorner, NULL);
nodePos[i] = vec3d(x,y,z);
}
elems.resize(NF);
// create elements
for (int i=0; i<NF; ++i)
{
int n0, n1, n2, id;
MMGS_Get_triangle(mmgMesh, &n0, &n1, &n2, &id, NULL);
n0--;
n1--;
n2--;
elems[i] = vec3i(n0, n1,n2);
}
// Clean up
MMGS_Free_all(MMG5_ARG_start,
MMG5_ARG_ppMesh, &mmgMesh, MMG5_ARG_ppMet, &mmgSol,
MMG5_ARG_end);
}
#else
void remesh(std::vector<double>& gradient, double lengthScale, double hausd, double grad, std::vector<vec3d>& nodePos, std::vector<vec3i>& elems) {}
void remeshFull(std::vector<double>& gradient, double lengthScale, double hausd, double grad, std::vector<vec3d>& nodePos, std::vector<vec3i>& elems) {}
#endif
// Taken from std::assoc_legendre definition in GCC
template<typename _Tp>
_Tp
__poly_legendre_p(unsigned int __l, _Tp __x)
{
if (isnan(__x))
return std::numeric_limits<_Tp>::quiet_NaN();
else if (__x == +_Tp(1))
return +_Tp(1);
else if (__x == -_Tp(1))
return (__l % 2 == 1 ? -_Tp(1) : +_Tp(1));
else
{
_Tp __p_lm2 = _Tp(1);
if (__l == 0)
return __p_lm2;
_Tp __p_lm1 = __x;
if (__l == 1)
return __p_lm1;
_Tp __p_l = 0;
for (unsigned int __ll = 2; __ll <= __l; ++__ll)
{
// This arrangement is supposed to be better for roundoff
// protection, Arfken, 2nd Ed, Eq 12.17a.
__p_l = _Tp(2) * __x * __p_lm1 - __p_lm2
- (__x * __p_lm1 - __p_lm2) / _Tp(__ll);
__p_lm2 = __p_lm1;
__p_lm1 = __p_l;
}
return __p_l;
}
}
template<typename _Tp>
_Tp
__assoc_legendre_p(unsigned int __l, unsigned int __m, _Tp __x,
_Tp __phase)
{
if (__m > __l)
return _Tp(0);
else if (isnan(__x))
return std::numeric_limits<_Tp>::quiet_NaN();
else if (__m == 0)
return __poly_legendre_p(__l, __x);
else
{
_Tp __p_mm = _Tp(1);
if (__m > 0)
{
// Two square roots seem more accurate more of the time
// than just one.
_Tp __root = std::sqrt(_Tp(1) - __x) * std::sqrt(_Tp(1) + __x);
_Tp __fact = _Tp(1);
for (unsigned int __i = 1; __i <= __m; ++__i)
{
__p_mm *= __phase * __fact * __root;
__fact += _Tp(2);
}
}
if (__l == __m)
return __p_mm;
_Tp __p_mp1m = _Tp(2 * __m + 1) * __x * __p_mm;
if (__l == __m + 1)
return __p_mp1m;
_Tp __p_lm2m = __p_mm;
_Tp __P_lm1m = __p_mp1m;
_Tp __p_lm = _Tp(0);
for (unsigned int __j = __m + 2; __j <= __l; ++__j)
{
__p_lm = (_Tp(2 * __j - 1) * __x * __P_lm1m
- _Tp(__j + __m - 1) * __p_lm2m) / _Tp(__j - __m);
__p_lm2m = __P_lm1m;
__P_lm1m = __p_lm;
}
return __p_lm;
}
} | C++ |
3D | febiosoftware/FEBio | FEAMR/FELeastSquaresInterpolator.cpp | .cpp | 8,048 | 380 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "FELeastSquaresInterpolator.h"
#include <FECore/FENNQuery.h>
#include <algorithm>
using namespace std;
class KDTree
{
public:
KDTree()
{
m_parent = nullptr;
m_left = nullptr;
m_right = nullptr;
}
~KDTree()
{
delete m_left;
delete m_right;
}
void build(vector<vec3d> pts, int depth = 0)
{
size_t n = pts.size();
if (n == 1)
{
m_r = pts[0];
return;
}
int axis = depth % 3;
std::sort(pts.begin(), pts.end(), [=](const vec3d& a, const vec3d& b) {
if (axis == 0) return (a.x < b.x);
if (axis == 1) return (a.y < b.y);
if (axis == 2) return (a.z < b.z);
return false;
});
int med = n / 2;
m_r = pts[med];
// build left list
if (med > 0)
{
vector<vec3d> l(pts.begin(), pts.begin() + med);
m_left = new KDTree(this);
m_left->build(l, depth + 1);
}
// build right list
if (med < n - 1)
{
vector<vec3d> r(pts.begin() + med + 1, pts.end());
m_right = new KDTree(this);
m_right->build(r, depth + 1);
}
}
public:
vec3d m_r;
KDTree* m_parent;
KDTree* m_left;
KDTree* m_right;
public:
KDTree(KDTree* parent) : m_parent(parent)
{
m_left = nullptr;
m_right = nullptr;
}
};
class NearestNeighborSearch
{
public:
NearestNeighborSearch() {}
void Init(const std::vector<vec3d>& points, int k)
{
m_k = k;
m_points = points;
// m_kdtree.build(m_points);
}
int findNearestNeighbors(const vec3d& x, std::vector<int>& closestNodes)
{
return findNeirestNeighbors(m_points, x, m_k, closestNodes);
}
protected:
int m_k;
vector<vec3d> m_points;
KDTree m_kdtree;
};
FELeastSquaresInterpolator::Data::Data() {}
FELeastSquaresInterpolator::Data::Data(const Data& d)
{
A = d.A;
index = d.index;
W = d.W;
X = d.X;
cpl = d.cpl;
}
void FELeastSquaresInterpolator::Data::operator = (const Data& d)
{
A = d.A;
index = d.index;
W = d.W;
X = d.X;
cpl = d.cpl;
}
FELeastSquaresInterpolator::FELeastSquaresInterpolator()
{
m_dim = 3;
m_nnc = 8;
m_checkForMatch = false;
}
//! Set dimension (2 or 3)
void FELeastSquaresInterpolator::SetDimension(int d)
{
assert((d == 2) || (d == 3));
m_dim = d;
}
void FELeastSquaresInterpolator::SetNearestNeighborCount(int nnc) { m_nnc = nnc; }
void FELeastSquaresInterpolator::SetCheckForMatch(bool b) { m_checkForMatch = b; }
void FELeastSquaresInterpolator::SetSourcePoints(const vector<vec3d>& srcPoints)
{
m_src = srcPoints;
}
void FELeastSquaresInterpolator::SetTargetPoints(const vector<vec3d>& trgPoints)
{
m_trg = trgPoints;
}
bool FELeastSquaresInterpolator::SetTargetPoint(const vec3d& trgPoint)
{
m_trg.clear();
m_trg.push_back(trgPoint);
return Init();
}
bool FELeastSquaresInterpolator::Init()
{
if (m_nnc < 4) return false;
if (m_src.empty()) return false;
if (m_trg.empty()) return false;
int N0 = m_src.size();
int N1 = m_trg.size();
m_data.resize(N1);
// initialize nearest neighbor search
NearestNeighborSearch NNS;
NNS.Init(m_src, m_nnc);
// do nearest-neighbor search
for (int i = 0; i < N1; ++i)
{
vec3d ri = m_trg[i];
int M = NNS.findNearestNeighbors(ri, m_data[i].cpl);
assert(M > 4);
m_data[i].cpl.resize(M);
}
for (int i = 0; i < N1; ++i)
{
Data& d = m_data[i];
vec3d x = m_trg[i];
vector<int>& closestNodes = m_data[i].cpl;
int M = closestNodes.size();
// the last node is the farthest and determines the radius
vec3d& r = m_src[closestNodes[M - 1]];
double L = sqrt((r - x)*(r - x));
// add some offset to make sure none of the points will have a weight of zero.
// Such points would otherwise be ignored, which reduces the net number of interpolation
// points and make the MLS system ill-conditioned
L += L * 0.05;
// evaluate weights and displacements
d.X.resize(M);
d.W.resize(M);
for (int m = 0; m < M; ++m)
{
vec3d rm = m_src[closestNodes[m]];
vec3d rj = x - rm;
d.X[m] = rj;
double D = sqrt(rj*rj);
double wj = 1.0 - D / L;
d.W[m] = wj;
}
// setup least squares problems
d.A.resize(m_dim + 1, m_dim + 1);
d.A.zero();
for (int m = 0; m < M; ++m)
{
vec3d ri = d.X[m];
double P[4] = { 1.0, ri.x, ri.y, ri.z };
for (int a = 0; a <= m_dim; ++a)
{
for (int b = 0; b <= m_dim; ++b)
{
d.A(a, b) += d.W[m] * P[a] * P[b];
}
}
}
// solve the linear system of equations
d.index.resize(m_dim + 1);
d.A.lufactor(d.index);
}
return true;
}
bool FELeastSquaresInterpolator::Map(std::vector<double>& tval, function<double(int sourceNode)> src)
{
if (m_data.size() != m_trg.size()) return false;
for (int i = 0; i < m_trg.size(); ++i)
{
Data& d = m_data[i];
vector<int>& closestNodes = m_data[i].cpl;
int M = closestNodes.size();
// evaluate weights and positions
vector<vec3d>& X = d.X;
vector<double>& W = d.W;
// update nodal values
vector<double> b(m_dim + 1, 0.0);
for (int m = 0; m < M; ++m)
{
vec3d ri = d.X[m];
double P[4] = { 1.0, ri.x, ri.y, ri.z };
double vm = src(closestNodes[m]);
for (int a = 0; a <= m_dim; ++a)
{
b[a] += W[m] * P[a] * vm;
}
}
// solve the linear system of equations
d.A.lusolve(b, d.index);
tval[i] = b[0];
}
return true;
}
double FELeastSquaresInterpolator::Map(int inode, function<double(int sourceNode)> f)
{
Data& d = m_data[inode];
vector<int>& closestNodes = m_data[inode].cpl;
int M = closestNodes.size();
// evaluate weights and positions
vector<vec3d>& X = d.X;
vector<double>& W = d.W;
if (m_checkForMatch)
{
if (W[0] > 0.9999)
{
return f(closestNodes[0]);
}
}
// update nodal values
vector<double> b(m_dim + 1, 0.0);
for (int m = 0; m < M; ++m)
{
vec3d ri = d.X[m];
double P[4] = { 1.0, ri.x, ri.y, ri.z };
double vm = f(closestNodes[m]);
for (int a = 0; a <= m_dim; ++a)
{
b[a] += W[m] * P[a] * vm;
}
}
// solve the linear system of equations
d.A.lusolve(b, d.index);
return b[0];
}
vec3d FELeastSquaresInterpolator::MapVec3d(int inode, function<vec3d(int sourceNode)> f)
{
Data& d = m_data[inode];
vector<int>& closestNodes = m_data[inode].cpl;
int M = closestNodes.size();
// evaluate weights and positions
vector<vec3d>& X = d.X;
vector<double>& W = d.W;
if (m_checkForMatch)
{
if (W[0] > 0.9999)
{
return f(closestNodes[0]);
}
}
// update nodal values
vector<double> bx(m_dim+1, 0.0), by(m_dim + 1, 0.0), bz(m_dim + 1, 0.0);
for (int m = 0; m < M; ++m)
{
vec3d ri = d.X[m];
double P[4] = { 1.0, ri.x, ri.y, ri.z };
vec3d vm = f(closestNodes[m]);
for (int a = 0; a <= m_dim; ++a)
{
bx[a] += W[m] * P[a] * vm.x;
by[a] += W[m] * P[a] * vm.y;
bz[a] += W[m] * P[a] * vm.z;
}
}
// solve the linear system of equations
d.A.lusolve(bx, d.index);
d.A.lusolve(by, d.index);
d.A.lusolve(bz, d.index);
return vec3d(bx[0], by[0], bz[0]);
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEFilterAdaptorCriterion.cpp | .cpp | 2,482 | 82 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEFilterAdaptorCriterion.h"
BEGIN_FECORE_CLASS(FEMinMaxFilterAdaptorCriterion, FEMeshAdaptorCriterion)
ADD_PARAMETER(m_min, "min");
ADD_PARAMETER(m_max, "max");
ADD_PARAMETER(m_clamp, "clamp");
ADD_PROPERTY(m_data, "data");
END_FECORE_CLASS();
FEMinMaxFilterAdaptorCriterion::FEMinMaxFilterAdaptorCriterion(FEModel* fem) : FEMeshAdaptorCriterion(fem)
{
m_min = -1.0e37;
m_max = 1.0e37;
m_clamp = true;
m_data = nullptr;
}
bool FEMinMaxFilterAdaptorCriterion::GetElementValue(FEElement& el, double& value)
{
if (m_data == nullptr) return false;
bool b = m_data->GetElementValue(el, value);
if (b)
{
if (m_clamp)
{
if (value < m_min) value = m_min;
if (value > m_max) value = m_max;
}
else if ((value < m_min) || (value > m_max))
{
b = false;
}
}
return b;
}
bool FEMinMaxFilterAdaptorCriterion::GetMaterialPointValue(FEMaterialPoint& mp, double& value)
{
if (m_data == nullptr) return false;
bool b = m_data->GetMaterialPointValue(mp, value);
if (b)
{
if (m_clamp)
{
if (value < m_min) value = m_min;
if (value > m_max) value = m_max;
}
else if ((value < m_min) || (value > m_max))
{
b = false;
}
}
return b;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEHexRefine.cpp | .cpp | 24,576 | 953 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEHexRefine.h"
#include <FECore/FEMesh.h>
#include <FECore/FESolidDomain.h>
#include <FECore/FEMeshTopo.h>
#include <FECore/FEPrescribedDOF.h>
#include <FECore/FEElementList.h>
#include <FECore/FELinearConstraint.h>
#include <FECore/FELinearConstraintManager.h>
#include <FECore/FESurface.h>
#include <FECore/FEMeshAdaptorCriterion.h>
#include <FECore/log.h>
#include <FECore/FEModel.h>
BEGIN_FECORE_CLASS(FEHexRefine, FERefineMesh)
ADD_PARAMETER(m_elemRefine, "max_elem_refine");
ADD_PARAMETER(m_maxValue, "max_value");
ADD_PROPERTY(m_criterion, "criterion");
END_FECORE_CLASS();
FEHexRefine::FEHexRefine(FEModel* fem) : FERefineMesh(fem)
{
m_elemRefine = 0;
m_maxValue = 0.0;
m_criterion = nullptr;
}
bool FEHexRefine::Init()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
if (mesh.IsType(ET_HEX8) == false)
{
feLogError("Cannot apply hex refinement: Mesh is not a HEX8 mesh.");
return false;
}
return FERefineMesh::Init();
}
bool FEHexRefine::RefineMesh()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
FEMeshTopo& topo = *m_topo;
FEElementList allElems(mesh);
const int NEL = mesh.Elements();
const int NDOM = mesh.Domains();
m_N0 = mesh.Nodes();
m_NC = topo.Edges();
int NF = topo.Faces();
// Build the lists of items to split
BuildSplitLists(fem);
// make sure we have work to do
if (m_splitElems == 0) return false;
// Next, the position and solution variables for all the nodes are updated.
// Note that this has to be done before recreating the elements since
// the old elements are still needed to determine the new positions and solutions.
UpdateNewNodes(fem);
// find the hanging nodes
// and assign linear constraints to tie them down
FindHangingNodes(fem);
// Now, we can create new elements
BuildNewDomains(fem);
// recreate element sets
for (int i = 0; i < mesh.ElementSets(); ++i)
{
FEElementSet& eset = mesh.ElementSet(i);
// get the domain list
// NOTE: Don't get the reference, since then the same reference
// is passed to Create below, which causes problems.
FEDomainList domList = eset.GetDomainList();
if (domList.IsEmpty()) { throw std::runtime_error("Error in FEHexRefine!"); }
// recreate the element set from the domain list
eset.Create(domList);
}
// update node sets
for (int i = 0; i < mesh.NodeSets(); ++i)
{
FENodeSet& nset = *mesh.NodeSet(i);
UpdateNodeSet(nset);
}
// update all surfaces
for (int i = 0; i < mesh.Surfaces(); ++i)
{
FESurface& surf = mesh.Surface(i);
if (UpdateSurface(surf) == false)
{
throw std::runtime_error("Error in FEHexRefine!");
}
}
return true;
}
void FEHexRefine::BuildSplitLists(FEModel& fem)
{
FEMeshTopo& topo = *m_topo;
FEMesh& mesh = fem.GetMesh();
// Get the elements that we need to refine
int NEL = mesh.Elements();
m_elemList.assign(NEL, -1);
if (m_criterion)
{
FEMeshAdaptorSelection selection = m_criterion->GetElementSelection(GetElementSet());
for (int i = 0; i < selection.size(); ++i)
{
if (selection[i].m_elemValue > m_maxValue)
{
int eid = selection[i].m_elementId;
int lid = topo.GetElementIndexFromID(eid);
m_elemList[lid] = 1;
}
}
}
else
{
// just do'em all
m_elemList.assign(NEL, 1);
}
// We cannot split elements that have a hanging nodes
// so remove those elements from the list
int nrejected = 0;
for (int i = 0; i < NEL; ++i)
{
if (m_elemList[i] != -1)
{
FEElement& el = *topo.Element(i);
int nel = el.Nodes();
for (int j = 0; j < nel; ++j)
{
if (mesh.Node(el.m_node[j]).HasFlags(FENode::HANGING))
{
// sorry, can't split this element
m_elemList[i] = -1;
nrejected++;
break;
}
}
}
}
if (nrejected > 0)
{
feLog("\tElements rejected: %d\n", nrejected);
}
// count how many elements to split
int N1 = mesh.Nodes();
m_splitElems = 0;
for (int i = 0; i < m_elemList.size(); ++i) {
if (m_elemList[i] == 1) {
m_elemList[i] = N1++;
m_splitElems++;
}
}
if (m_splitElems == 0) return;
// make sure we don't exceed the max elements per refinement step
if ((m_elemRefine > 0) && (m_splitElems > m_elemRefine))
{
N1 = mesh.Nodes();
m_splitElems = 0;
for (int i = 0; i < m_elemList.size(); ++i) {
if (m_elemList[i] >= 0) {
if (m_splitElems >= m_elemRefine)
{
m_elemList[i] = -1;
}
else
{
m_splitElems++;
m_elemList[i] = N1++;
}
}
}
assert(m_splitElems == m_elemRefine);
}
// figure out which faces to refine
int NF = topo.Faces();
m_faceList.assign(NF, -1);
for (int i = 0; i < m_elemList.size(); ++i)
{
if (m_elemList[i] != -1)
{
const std::vector<int>& elface = topo.ElementFaceList(i);
for (int j = 0; j < elface.size(); ++j) m_faceList[elface[j]] = 1;
}
}
// count how many faces to split
m_splitFaces = 0;
for (int i = 0; i < m_faceList.size(); ++i) {
if (m_faceList[i] == 1) {
m_faceList[i] = N1++;
m_splitFaces++;
}
}
// figure out which edges to refine
m_edgeList.assign(m_NC, -1);
for (int i = 0; i < NF; ++i)
{
if (m_faceList[i] != -1)
{
const std::vector<int>& faceEdge = topo.FaceEdgeList(i);
for (int j = 0; j < faceEdge.size(); ++j) m_edgeList[faceEdge[j]] = 1;
}
}
// count how many edges to split
m_splitEdges = 0;
for (int i = 0; i < m_NC; ++i) {
if (m_edgeList[i] == 1) {
m_edgeList[i] = N1++;
m_splitEdges++;
}
}
feLog("\tRefinement info:\n");
feLog("\t Elements to refine: %d\n", m_splitElems);
feLog("\t Facets to refine : %d\n", m_splitFaces);
feLog("\t Edges to refine : %d\n", m_splitEdges);
}
int findNodeInMesh(FEMesh& mesh, const vec3d& r, double tol = 1e-12)
{
int NN = mesh.Nodes();
for (int i = 0; i < NN; ++i)
{
FENode& node = mesh.Node(i);
if (node.HasFlags(FENode::EXCLUDE) == false)
{
vec3d ri = mesh.Node(i).m_r0;
if ((ri - r).norm2() < tol) return i;
}
}
return -1;
}
void FEHexRefine::UpdateNewNodes(FEModel& fem)
{
FEMeshTopo& topo = *m_topo;
FEMesh& mesh = fem.GetMesh();
// we need to create a new node for each edge, face, and element that needs to be split
int newNodes = m_splitEdges + m_splitFaces + m_splitElems;
// for now, store the position of these new nodes in an array
vector<vec3d> newPos(newNodes);
// get the position of new nodes
int n = 0;
for (int i = 0; i < topo.Edges(); ++i)
{
if (m_edgeList[i] != -1)
{
const FEEdgeList::EDGE& edge = topo.Edge(i);
vec3d r0 = mesh.Node(edge.node[0]).m_r0;
vec3d r1 = mesh.Node(edge.node[1]).m_r0;
newPos[n++] = (r0 + r1)*0.5;
}
}
for (int i = 0; i < topo.Faces(); ++i)
{
if (m_faceList[i] != -1)
{
const FEFaceList::FACE& face = topo.Face(i);
vec3d r0(0, 0, 0);
int nn = face.ntype;
for (int j = 0; j < nn; ++j) r0 += mesh.Node(face.node[j]).m_r0;
r0 /= (double)nn;
newPos[n++] = r0;
}
}
for (int i = 0; i < topo.Elements(); ++i)
{
if (m_elemList[i] != -1)
{
FESolidElement& el = dynamic_cast<FESolidElement&>(*topo.Element(i));
vec3d r0(0, 0, 0);
int nn = el.Nodes();
for (int j = 0; j < nn; ++j) r0 += mesh.Node(el.m_node[j]).m_r0;
r0 /= (double)nn;
newPos[n++] = r0;
}
}
// some of these new nodes may coincide with an existing node
//If we find one, we eliminate it
n = 0;
int nremoved = 0;
for (int i = 0; i < topo.Edges(); ++i)
{
if (m_edgeList[i] != -1)
{
int nodeId = findNodeInMesh(mesh, newPos[n++]);
if (nodeId >= 0)
{
if(mesh.Node(nodeId).HasFlags(FENode::HANGING))
mesh.Node(nodeId).UnsetFlags(FENode::HANGING);
m_edgeList[i] = -nodeId-2;
nremoved++;
}
}
}
for (int i = 0; i < topo.Faces(); ++i)
{
if (m_faceList[i] != -1)
{
int nodeId = findNodeInMesh(mesh, newPos[n++]);
if (nodeId >= 0)
{
if(mesh.Node(nodeId).HasFlags(FENode::HANGING))
mesh.Node(nodeId).UnsetFlags(FENode::HANGING);
m_faceList[i] = -nodeId-2;
nremoved++;
}
}
}
for (int i = 0; i < topo.Elements(); ++i)
{
if (m_elemList[i] != -1)
{
int nodeId = findNodeInMesh(mesh, newPos[n++]);
if (nodeId >= 0)
{
if(mesh.Node(nodeId).HasFlags(FENode::HANGING))
mesh.Node(nodeId).UnsetFlags(FENode::HANGING);
m_elemList[i] = -nodeId-2;
nremoved++;
}
}
}
// we need to reindex nodes if some were removed
if (nremoved > 0)
{
n = m_N0;
for (int i = 0; i < topo.Edges(); ++i)
{
if (m_edgeList[i] >= 0) m_edgeList[i] = n++;
}
for (int i = 0; i < topo.Faces(); ++i)
{
if (m_faceList[i] >= 0) m_faceList[i] = n++;
}
for (int i = 0; i < topo.Elements(); ++i)
{
if (m_elemList[i] >= 0) m_elemList[i] = n++;
}
assert(n == (m_N0 + newNodes - nremoved));
newNodes -= nremoved;
}
// now, generate new nodes
mesh.AddNodes(newNodes);
// assign dofs to new nodes
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
m_NN = mesh.Nodes();
for (int i = m_N0; i<m_NN; ++i)
{
FENode& node = mesh.Node(i);
node.SetDOFS(MAX_DOFS);
}
// update the position of these new nodes
n = 0;
for (int i = 0; i < topo.Edges(); ++i)
{
if (m_edgeList[i] >= 0)
{
const FEEdgeList::EDGE& edge = topo.Edge(i);
FENode& node = mesh.Node(m_edgeList[i]);
vec3d r0 = mesh.Node(edge.node[0]).m_r0;
vec3d r1 = mesh.Node(edge.node[1]).m_r0;
node.m_r0 = (r0 + r1)*0.5;
r0 = mesh.Node(edge.node[0]).m_rt;
r1 = mesh.Node(edge.node[1]).m_rt;
node.m_rt = (r0 + r1)*0.5;
}
}
for (int i = 0; i < topo.Faces(); ++i)
{
if (m_faceList[i] >= 0)
{
const FEFaceList::FACE& face = topo.Face(i);
FENode& node = mesh.Node(m_faceList[i]);
int nn = face.ntype;
vec3d r0(0, 0, 0);
for (int j = 0; j < nn; ++j) r0 += mesh.Node(face.node[j]).m_r0;
r0 /= (double)nn;
node.m_r0 = r0;
vec3d rt(0, 0, 0);
for (int j = 0; j < nn; ++j) rt += mesh.Node(face.node[j]).m_rt;
rt /= (double)nn;
node.m_rt = rt;
}
}
for (int i=0; i < topo.Elements(); ++i)
{
if (m_elemList[i] >= 0)
{
FESolidElement& el = dynamic_cast<FESolidElement&>(*topo.Element(i));
int nn = el.Nodes();
FENode& node = mesh.Node(m_elemList[i]);
vec3d r0(0, 0, 0);
for (int j = 0; j < nn; ++j) r0 += mesh.Node(el.m_node[j]).m_r0;
r0 /= (double)nn;
node.m_r0 = r0;
vec3d rt(0, 0, 0);
for (int j = 0; j < nn; ++j) rt += mesh.Node(el.m_node[j]).m_rt;
rt /= (double)nn;
node.m_rt = rt;
}
}
// re-evaluate solution at nodes
for (int i = 0; i < topo.Edges(); ++i)
{
if (m_edgeList[i] >= 0)
{
const FEEdgeList::EDGE& edge = topo.Edge(i);
FENode& node0 = mesh.Node(edge.node[0]);
FENode& node1 = mesh.Node(edge.node[1]);
FENode& node = mesh.Node(m_edgeList[i]);
for (int j = 0; j < MAX_DOFS; ++j)
{
double v = (node0.get(j) + node1.get(j))*0.5;
node.set(j, v);
}
}
}
for (int i = 0; i < topo.Faces(); ++i)
{
if (m_faceList[i] >= 0)
{
const FEFaceList::FACE& face = topo.Face(i);
FENode& node = mesh.Node(m_faceList[i]);
int nn = face.ntype;
for (int j = 0; j < MAX_DOFS; ++j)
{
double v = 0.0;
for (int k = 0; k < nn; ++k) v += mesh.Node(face.node[k]).get(j);
v /= (double)nn;
node.set(j, v);
}
}
}
for (int i=0; i<topo.Elements(); ++i)
{
if (m_elemList[i] >= 0)
{
FESolidElement& el = dynamic_cast<FESolidElement&>(*topo.Element(i));
int nn = el.Nodes();
FENode& node = mesh.Node(m_elemList[i]);
for (int j = 0; j < MAX_DOFS; ++j)
{
double v = 0.0;
for (int k = 0; k < nn; ++k) v += mesh.Node(el.m_node[k]).get(j);
v /= (double)nn;
node.set(j, v);
}
}
}
// make the new node indices all positive
for (int i = 0; i < topo.Edges(); ++i)
{
if (m_edgeList[i] < -1) m_edgeList[i] = -m_edgeList[i]-2;
}
for (int i = 0; i < topo.Faces(); ++i)
{
if (m_faceList[i] < -1) m_faceList[i] = -m_faceList[i]-2;
}
for (int i = 0; i < topo.Elements(); ++i)
{
if (m_elemList[i] < -1) m_elemList[i] = -m_elemList[i] - 2;
}
}
//-----------------------------------------------------------------------------
// This function identifies the hanging nodes and assigns linear constraints to them.
void FEHexRefine::FindHangingNodes(FEModel& fem)
{
FEMeshTopo& topo = *m_topo;
FEMesh& mesh = fem.GetMesh();
m_hangingNodes = 0;
FELinearConstraintManager& LCM = fem.GetLinearConstraintManager();
const int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
// First, we removed any constraints on nodes that are no longer hanging
int nremoved = 0;
for (int i = 0; i < LCM.LinearConstraints();)
{
FELinearConstraint& lc = LCM.LinearConstraint(i);
int nodeID = lc.GetParentNode();
if (mesh.Node(nodeID).HasFlags(FENode::HANGING) == false)
{
LCM.RemoveLinearConstraint(i);
nremoved++;
}
else i++;
}
feLog("\tRemoved linear constraints : %d\n", nremoved);
// we loop over non-split faces
int nadded = 0;
vector<int> tag(m_NC, 0);
int NF = topo.Faces();
for (int i = 0; i < NF; ++i)
{
if (m_faceList[i] == -1)
{
// This face is not split
const std::vector<int>& fel = topo.FaceEdgeList(i);
for (int j = 0; j < fel.size(); ++j)
{
if ((m_edgeList[fel[j]] >= 0) && (tag[fel[j]] == 0))
{
// Tag the node as hanging so we can identify it easier later
int nodeId = m_edgeList[fel[j]];
FENode& node = mesh.Node(nodeId);
node.SetFlags(FENode::HANGING);
// get the edge
const FEEdgeList::EDGE& edge = topo.Edge(fel[j]);
// setup a linear constraint for this node
for (int k = 0; k < MAX_DOFS; ++k)
{
FELinearConstraint* lc = new FELinearConstraint(&fem);
lc->SetParentDof(k, nodeId);
lc->AddChildDof(k, edge.node[0], 0.5);
lc->AddChildDof(k, edge.node[1], 0.5);
LCM.AddLinearConstraint(lc);
nadded++;
}
// set a tag to avoid double-counting
tag[fel[j]] = 1;
// feLog("Added linear constraints to hanging node: %d (%d, %d)\n", nodeId, edge.node[0], edge.node[1]);
m_hangingNodes++;
}
}
}
}
// we loop over the non-split elements
int NEL = topo.Elements();
for (int i = 0; i<NEL; ++i)
{
if (m_elemList[i] == -1)
{
// This element is not split
// If any of its faces are split, then the corresponding node
// will be hanging
const std::vector<int>& elface = topo.ElementFaceList(i);
for (int j = 0; j < elface.size(); ++j)
{
if (m_faceList[elface[j]] >= 0)
{
// Tag the node as hanging so we can identify it easier later
int nodeId = m_faceList[elface[j]];
FENode& node = mesh.Node(nodeId);
node.SetFlags(FENode::HANGING);
// get the face
const FEFaceList::FACE& face = topo.Face(elface[j]);
// setup a linear constraint for this node
for (int k = 0; k < MAX_DOFS; ++k)
{
FELinearConstraint* lc = new FELinearConstraint(&fem);
lc->SetParentDof(k, nodeId);
lc->AddChildDof(k, face.node[0], 0.25);
lc->AddChildDof(k, face.node[1], 0.25);
lc->AddChildDof(k, face.node[2], 0.25);
lc->AddChildDof(k, face.node[3], 0.25);
LCM.AddLinearConstraint(lc);
nadded++;
}
// feLog("Added linear constraints to hanging node: %d (%d, %d, %d, %d)\n", nodeId, face.node[0], face.node[1], face.node[2], face.node[3]);
m_hangingNodes++;
}
}
// This element is not split
// If any of its edges are split, then the corresponding node
// will be hanging
const std::vector<int>& eledge = topo.ElementEdgeList(i);
for (int j = 0; j < eledge.size(); ++j)
{
if ((m_edgeList[eledge[j]] >= 0) && (tag[eledge[j]] == 0))
{
// Tag the node as hanging so we can identify it easier later
int nodeId = m_edgeList[eledge[j]];
FENode& node = mesh.Node(nodeId);
node.SetFlags(FENode::HANGING);
// get the edge
const FEEdgeList::EDGE& edge = topo.Edge(eledge[j]);
// setup a linear constraint for this node
for (int k = 0; k < MAX_DOFS; ++k)
{
FELinearConstraint* lc = new FELinearConstraint(&fem);
lc->SetParentDof(k, nodeId);
lc->AddChildDof(k, edge.node[0], 0.5);
lc->AddChildDof(k, edge.node[1], 0.5);
LCM.AddLinearConstraint(lc);
nadded++;
}
// set a tag to avoid double-counting
tag[eledge[j]] = 1;
// feLog("Added linear constraints to hanging node: %d (%d, %d)\n", nodeId, edge.node[0], edge.node[1]);
m_hangingNodes++;
}
}
}
}
feLog("\tHanging nodes ............ : %d\n", m_hangingNodes);
feLog("\tAdded linear constraints . : %d\n", nadded);
}
void FEHexRefine::BuildNewDomains(FEModel& fem)
{
// This lookup table defines how a hex will be split in eight smaller hexes
const int LUT[8][8] = {
{ 0, 8, 24, 11, 16, 20, 26, 23 },
{ 8, 1, 9, 24, 20, 17, 21, 26 },
{ 11, 24, 10, 3, 23, 26, 22, 19 },
{ 24, 9, 2, 10, 26, 21, 18, 22 },
{ 16, 20, 26, 23, 4, 12, 25, 15 },
{ 20, 17, 21, 26, 12, 5, 13, 25 },
{ 23, 26, 22, 19, 15, 25, 14, 7 },
{ 26, 21, 18, 22, 25, 13, 6, 14 },
};
FEMeshTopo& topo = *m_topo;
FEMesh& mesh = fem.GetMesh();
int nelems = 0;
const int NDOM = mesh.Domains();
for (int i = 0; i < NDOM; ++i)
{
// get the old domain
FEDomain& oldDom = mesh.Domain(i);
int NE0 = oldDom.Elements();
// count how many elements to split in this domain
int newElems = 0;
for (int j = 0; j < NE0; ++j)
{
if (m_elemList[nelems + j] != -1) newElems++;
}
// make sure we have something to do
if (newElems > 0)
{
// create a copy of old domain (since we want to retain the old domain)
FEDomain* newDom = fecore_new<FESolidDomain>(oldDom.GetTypeStr(), &fem);
newDom->Create(NE0, FEElementLibrary::GetElementSpecFromType(FE_HEX8G8));
for (int j = 0; j < NE0; ++j)
{
FEElement& el0 = oldDom.ElementRef(j);
FEElement& el1 = newDom->ElementRef(j);
el1.SetMatID(el0.GetMatID());
el1.setStatus(el0.status());
for (int k = 0; k < el0.Nodes(); ++k) el1.m_node[k] = el0.m_node[k];
}
// reallocate the old domain
oldDom.Create(8 * newElems + (NE0 - newElems), FEElementLibrary::GetElementSpecFromType(FE_HEX8G8));
// set new element nodes
int nel = 0;
for (int j = 0; j < NE0; ++j, nelems++)
{
FEElement& el0 = newDom->ElementRef(j);
if (m_elemList[nelems] != -1)
{
const std::vector<int>& ee = topo.ElementEdgeList(nelems); assert(ee.size() == 12);
const std::vector<int>& ef = topo.ElementFaceList(nelems); assert(ef.size() == 6);
// build the look-up table
int ENL[27] = { 0 };
ENL[ 0] = el0.m_node[0];
ENL[ 1] = el0.m_node[1];
ENL[ 2] = el0.m_node[2];
ENL[ 3] = el0.m_node[3];
ENL[ 4] = el0.m_node[4];
ENL[ 5] = el0.m_node[5];
ENL[ 6] = el0.m_node[6];
ENL[ 7] = el0.m_node[7];
ENL[ 8] = m_edgeList[ee[0]];
ENL[ 9] = m_edgeList[ee[1]];
ENL[10] = m_edgeList[ee[2]];
ENL[11] = m_edgeList[ee[3]];
ENL[12] = m_edgeList[ee[4]];
ENL[13] = m_edgeList[ee[5]];
ENL[14] = m_edgeList[ee[6]];
ENL[15] = m_edgeList[ee[7]];
ENL[16] = m_edgeList[ee[8]];
ENL[17] = m_edgeList[ee[9]];
ENL[18] = m_edgeList[ee[10]];
ENL[19] = m_edgeList[ee[11]];
ENL[20] = m_faceList[ef[0]];
ENL[21] = m_faceList[ef[1]];
ENL[22] = m_faceList[ef[2]];
ENL[23] = m_faceList[ef[3]];
ENL[24] = m_faceList[ef[4]];
ENL[25] = m_faceList[ef[5]];
ENL[26] = m_elemList[nelems];
// assign nodes to new elements
for (int k = 0; k < 8; ++k)
{
FEElement& el1 = oldDom.ElementRef(nel++);
el1.m_node[0] = ENL[LUT[k][0]];
el1.m_node[1] = ENL[LUT[k][1]];
el1.m_node[2] = ENL[LUT[k][2]];
el1.m_node[3] = ENL[LUT[k][3]];
el1.m_node[4] = ENL[LUT[k][4]];
el1.m_node[5] = ENL[LUT[k][5]];
el1.m_node[6] = ENL[LUT[k][6]];
el1.m_node[7] = ENL[LUT[k][7]];
el1.SetMatID(el0.GetMatID());
el1.setStatus(el0.status());
}
}
else
{
// if the element is not split, we just copy the nodes from
// the old domain
FEElement& el1 = oldDom.ElementRef(nel++);
el1.SetMatID(el0.GetMatID());
el1.setStatus(el0.status());
for (int k = 0; k < el0.Nodes(); ++k) el1.m_node[k] = el0.m_node[k];
}
}
// we don't need this anymore
delete newDom;
}
}
mesh.RebuildLUT();
// re-init domains
for (int i = 0; i < NDOM; ++i)
{
FEDomain& dom = mesh.Domain(i);
dom.CreateMaterialPointData();
dom.Reset(); // NOTE: we need to call this to actually call the Init function on the material points.
dom.Init();
dom.Activate();
}
}
void FEHexRefine::UpdateNodeSet(FENodeSet& nset)
{
FEMeshTopo& topo = *m_topo;
vector<int> tag(m_NN, 0);
for (int j = 0; j < nset.Size(); ++j) tag[nset[j]] = 1;
for (int j = 0; j < topo.Edges(); ++j)
{
if (m_edgeList[j] >= 0)
{
const FEEdgeList::EDGE& edge = topo.Edge(j);
if ((tag[edge.node[0]] == 1) && (tag[edge.node[1]] == 1))
{
nset.Add(m_edgeList[j]);
}
}
}
for (int j = 0; j < topo.Faces(); ++j)
{
if (m_faceList[j] >= 0)
{
const FEFaceList::FACE& face = topo.Face(j);
assert(face.ntype == 4);
if ((tag[face.node[0]] == 1) &&
(tag[face.node[1]] == 1) &&
(tag[face.node[2]] == 1) &&
(tag[face.node[3]] == 1))
{
nset.Add(m_faceList[j]);
}
}
}
}
bool FEHexRefine::UpdateSurface(FESurface& surf)
{
// look-up table for splitting quads
const int LUT[4][4] = {
{ 0, 4, 8, 7 },
{ 4, 1, 5, 8 },
{ 7, 8, 6, 3 },
{ 8, 5, 2, 6 }
};
FEMeshTopo& topo = *m_topo;
int NF0 = surf.Elements();
// figure out which facets to split
vector<int> faceList = topo.FaceIndexList(surf);
assert((int)faceList.size() == NF0);
// count how many faces to split
int splitFaces = 0;
for (int i = 0; i < faceList.size(); ++i)
{
int iface = faceList[i];
if (m_faceList[iface] >= 0) splitFaces++;
}
if (splitFaces == 0) return true;
// create a copy of the domain
FESurface oldSurf(GetFEModel());
oldSurf.Create(NF0);
for (int i = 0; i < NF0; ++i)
{
FESurfaceElement& el0 = surf.Element(i);
FESurfaceElement& el1 = oldSurf.Element(i);
el1.SetType(el0.Type());
int nf = el0.Nodes();
for (int j = 0; j < nf; ++j) el1.m_node[j] = el0.m_node[j];
}
// reallocate the domain (Assumes Quad faces!)
int NF1 = NF0 - splitFaces + 4 * (splitFaces);
surf.Create(NF1);
// reinitialize the surface
int n = 0;
for (int i = 0; i < NF0; ++i)
{
FESurfaceElement& el0 = oldSurf.Element(i);
int iface = faceList[i];
if (m_faceList[iface] >= 0)
{
const FEFaceList::FACE& face = topo.Face(iface);
const vector<int>& edge = topo.FaceEdgeList(iface);
int NL[9];
NL[0] = face.node[0];
NL[1] = face.node[1];
NL[2] = face.node[2];
NL[3] = face.node[3];
NL[4] = m_edgeList[edge[0]];
NL[5] = m_edgeList[edge[1]];
NL[6] = m_edgeList[edge[2]];
NL[7] = m_edgeList[edge[3]];
NL[8] = m_faceList[iface];
for (int j = 0; j < 4; ++j)
{
FESurfaceElement& el1 = surf.Element(n++);
el1.SetType(FE_QUAD4G4);
el1.m_node[0] = NL[LUT[j][0]];
el1.m_node[1] = NL[LUT[j][1]];
el1.m_node[2] = NL[LUT[j][2]];
el1.m_node[3] = NL[LUT[j][3]];
}
}
else
{
FESurfaceElement& el1 = surf.Element(n++);
el1.SetType(FE_QUAD4G4);
el1.m_node[0] = el0.m_node[0];
el1.m_node[1] = el0.m_node[1];
el1.m_node[2] = el0.m_node[2];
el1.m_node[3] = el0.m_node[3];
}
}
return surf.Init();
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEAMR.cpp | .cpp | 2,605 | 61 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEAMR.h"
#include <FECore/FECoreKernel.h>
#include "FEErosionAdaptor.h"
#include "FEHexRefine.h"
#include "FEHexRefine2D.h"
#include "FETetRefine.h"
#include "FEMMGRemesh.h"
#include "FETestRefine.h"
#include "FEVariableCriterion.h"
#include "FEElementSelectionCriterion.h"
#include "FEScaleAdaptorCriterion.h"
#include "FEFilterAdaptorCriterion.h"
#include "FEDomainErrorCriterion.h"
#include "FEElementDataCriterion.h"
//-----------------------------------------------------------------------------
void FEAMR::InitModule()
{
// mesh adaptors
REGISTER_FECORE_CLASS(FEErosionAdaptor, "erosion");
REGISTER_FECORE_CLASS(FEHexRefine , "hex_refine");
REGISTER_FECORE_CLASS(FEHexRefine2D , "hex_refine2d");
REGISTER_FECORE_CLASS(FETetRefine , "tet_refine");
REGISTER_FECORE_CLASS(FEMMGRemesh , "mmg_remesh");
REGISTER_FECORE_CLASS(FETestRefine , "test_refine");
// adaptor criteria
REGISTER_FECORE_CLASS(FEVariableCriterion , "max_variable");
REGISTER_FECORE_CLASS(FEElementSelectionCriterion, "element_selection");
REGISTER_FECORE_CLASS(FEScaleAdaptorCriterion , "math");
REGISTER_FECORE_CLASS(FEMinMaxFilterAdaptorCriterion, "min-max filter");
REGISTER_FECORE_CLASS(FEDomainErrorCriterion, "relative error");
REGISTER_FECORE_CLASS(FEElementDataCriterion, "element data");
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEVariableCriterion.cpp | .cpp | 2,192 | 63 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEVariableCriterion.h"
#include <FECore/FESolidDomain.h>
#include <FECore/FEMesh.h>
BEGIN_FECORE_CLASS(FEVariableCriterion, FEMeshAdaptorCriterion)
ADD_PARAMETER(m_dof, "dof");
END_FECORE_CLASS();
FEVariableCriterion::FEVariableCriterion(FEModel* fem) : FEMeshAdaptorCriterion(fem)
{
m_dof = -1;
}
bool FEVariableCriterion::GetMaterialPointValue(FEMaterialPoint& mp, double& value)
{
if (m_dof == -1) return false;
FEElement* pe = mp.m_elem;
if (pe == nullptr) return false;
if ((mp.m_index < 0) || (mp.m_index >= pe->GaussPoints())) return false;
FESolidDomain* dom = dynamic_cast<FESolidDomain*>(pe->GetMeshPartition());
if (dom == nullptr) return false;
FEMesh& mesh = *dom->GetMesh();
double vn[FEElement::MAX_NODES];
for (int i = 0; i < pe->Nodes(); ++i)
{
vn[i] = mesh.Node(pe->m_node[i]).get(m_dof);
}
value = pe->Evaluate(vn, mp.m_index);
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEAMR/FEDomainErrorCriterion.h | .h | 1,743 | 46 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEMeshAdaptorCriterion.h>
#include "feamr_api.h"
class FEMaterialPoint;
//-----------------------------------------------------------------------------
class FEAMR_API FEDomainErrorCriterion : public FEMeshAdaptorCriterion
{
public:
FEDomainErrorCriterion(FEModel* fem);
FEMeshAdaptorSelection GetElementSelection(FEElementSet* elset) override;
private:
double m_error;
FEMeshAdaptorCriterion* m_data;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEOptimizeInput.h | .h | 2,245 | 61 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FEBioXML/XMLReader.h>
//-----------------------------------------------------------------------------
//! FEBio error terminated during the optimization
class FEErrorTermination{};
//-----------------------------------------------------------------------------
class FEOptimizeData;
//=============================================================================
//! Class that reads the optimization input file
class FEOptimizeInput
{
public:
bool Input(const char* szfile, FEOptimizeData* pOpt);
private:
void ParseTask(XMLTag& tag);
void ParseOptions(XMLTag& tag);
void ParseParameters(XMLTag& tag);
void ParseConstraints(XMLTag& tag);
void ParseObjective(XMLTag& tag);
FEDataSource* ParseDataSource(XMLTag& tag);
private:
void ParseObjectiveDataFit(XMLTag& tag);
void ParseObjectiveTarget(XMLTag& tag);
void ParseObjectiveElementData(XMLTag& tag);
void ParseObjectiveNodeData(XMLTag& tag);
private:
FEOptimizeData* m_opt;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEBioParamRun.h | .h | 2,027 | 55 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FECoreTask.h>
#include "FEOptimizeData.h"
//-----------------------------------------------------------------------------
// This task runs FEBio, but sets overwrites the values of some parameters
// of the input model and prints out an output parameter to a file.
class FEBioParamRun : public FECoreTask
{
public:
//! class constructor
FEBioParamRun(FEModel* pfem);
//! initialization
bool Init(const char* szfile);
//! Run the task
bool Run();
private:
//! read control file
bool Input(const char* szfile);
private:
std::vector<FEModelParameter*> m_inVar;
std::vector<FEDataParameter*> m_outVar;
std::string m_outFile;
bool m_febioOutput; // generate standard FEBio log and plot file output?
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEPowellOptimizeMethod.cpp | .cpp | 3,041 | 104 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEPowellOptimizeMethod.h"
#include "FEOptimizeData.h"
#include <FECore/FEAnalysis.h>
#include <FECore/log.h>
#include <FECore/tools.h>
FEPowellOptimizeMethod* FEPowellOptimizeMethod::m_pThis = 0;
FEPowellOptimizeMethod::FEPowellOptimizeMethod(FEModel* fem) : FEOptimizeMethod(fem)
{
}
bool FEPowellOptimizeMethod::Solve(FEOptimizeData *pOpt, vector<double>& amin, vector<double>& ymin, double* minObj)
{
m_pOpt = pOpt;
FEOptimizeData& opt = *pOpt;
int nvar = opt.InputParameters();
// set the initial guess
vector<double> p(nvar);
for (int i=0; i<nvar; ++i) p[i] = opt.GetInputParameter(i)->GetValue();
// set the initial search directions
vector<double> xi(nvar*nvar);
for (int i=0; i<nvar; ++i)
{
for (int j=0; j<nvar; ++j) xi[i*nvar + j] = 0;
xi[i*nvar + i] = 0.05*(1.0 + p[i]);
}
// don't forget to set this
m_pThis = this;
// call the powell routine
int niter = 0;
double fret = 0;
powell(&p[0], &xi[0], nvar, 0.001, &niter, &fret, objfun);
// store optimal values
amin = p;
if (minObj) *minObj = fret;
return true;
}
//------------------------------------------------------------------
double FEPowellOptimizeMethod::ObjFun(double *p)
{
// get the optimization data
FEOptimizeData& opt = *m_pOpt;
FEModel* fem = opt.GetFEModel();
// set the input parameters
int nvar = opt.InputParameters();
vector<double> a(nvar);
for (int i=0; i<nvar; ++i) a[i] = p[i];
// solve the FE problem with the new parameters
if (opt.FESolve(a) == false)
{
feLogEx(fem, "\n\n\nAAAAAAAAARRRRRRRRRGGGGGGGGHHHHHHHHHHH !!!!!!!!!!!!!\n\n\n\n");
return 0;
}
else
{
// evaluate objective function
FEObjectiveFunction& obj = opt.GetObjective();
double fobj = obj.Evaluate();
return fobj;
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/FEOptimizeMethod.h | .h | 2,530 | 70 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FECoreClass.h>
//-----------------------------------------------------------------------------
class FEOptimizeData;
//-----------------------------------------------------------------------------
enum {
PRINT_ITERATIONS,
PRINT_VERBOSE
};
//-----------------------------------------------------------------------------
enum LogLevel {
LOG_NEVER,
LOG_FILE,
LOG_SCREEN,
LOG_FILE_AND_SCREEN
};
//-----------------------------------------------------------------------------
//! Base class for optimization algorithms.
//! Derived class implement specific optimization algorithms.
class FEOptimizeMethod : public FECoreClass
{
FECORE_BASE_CLASS(FEOptimizeMethod)
public:
FEOptimizeMethod(FEModel* fem);
// Implement this function for solve an optimization problem
// should return the optimal values for the input parameters in a, the optimal
// values of the measurement vector in ymin and
// the corresponding objective value in obj.
// If this function returns false, something went wrong
virtual bool Solve(FEOptimizeData* pOpt, vector<double>& amin, vector<double>& ymin, double* minObj) = 0;
public:
int m_loglevel; //!< log file output level
int m_print_level; //!< level of detailed output
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEDataSource.h | .h | 4,907 | 177 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/PointCurve.h>
#include <functional>
#include <FECore/NodeDataRecord.h>
#include <FECore/ElementDataRecord.h>
//-------------------------------------------------------------------------------------------------
// The FEDataSource class is used by the FEObjectiveFunction to query model data and evaluate it
// at the requested time point. This is an abstract base class and derived classes must implement
// the Evaluate function.
class FEDataSource
{
public:
FEDataSource(FEModel* fem);
virtual ~FEDataSource();
// Initialize data source
virtual bool Init();
// Reset data source
virtual void Reset();
// Evaluate source at x
virtual double Evaluate(double x) = 0;
protected:
FEModel& m_fem; //!< reference to model
};
//-------------------------------------------------------------------------------------------------
// The FEDataParameter class is a data source the extracts data from a model parameter. The parameter
// must be set with SetParameterName before calling Init.
class FEDataParameter : public FEDataSource
{
public:
// constructor
FEDataParameter(FEModel* fem);
// Set the model parameter name
void SetParameterName(const std::string& name);
// set the ordinate name
void SetOrdinateName(const std::string& name);
// Initialize data
bool Init() override;
// Reset data
void Reset() override;
// Evaluate the model parameter at x
double Evaluate(double x) override;
// evaluate the current value
double value() { return m_fy(); }
private:
static bool update(FEModel* pmdl, unsigned int nwhen, void* pd);
void update();
private:
string m_param; //!< name of parameter that generates the function data
string m_ord; //!< name of ordinate parameter
std::function<double()> m_fx; //!< pointer to ordinate value
std::function<double()> m_fy; //!< pointer to variable data
PointCurve m_rf; //!< reaction force data
};
//-------------------------------------------------------------------------------------------------
// This data source class evaluates the data using another data source and then applying a filter.
// In this case, the filter only returns positive values or zero otherwise. The data source must be
// set before calling Init
class FEDataFilterPositive : public FEDataSource
{
public:
FEDataFilterPositive(FEModel* fem);
~FEDataFilterPositive();
// Set the data source
void SetDataSource(FEDataSource* src);
// Initialize data
bool Init() override;
// reset data
void Reset() override;
// evaluate data source at x
double Evaluate(double x) override;
private:
FEDataSource* m_src;
};
class FENodeDataFilterSum : public FEDataSource
{
public:
FENodeDataFilterSum(FEModel* fem);
~FENodeDataFilterSum();
void SetData(FELogNodeData* data, FENodeSet* nodeSet);
// Initialize data
bool Init() override;
// reset data
void Reset() override;
// evaluate data source at x
double Evaluate(double x) override;
private:
static bool update(FEModel* pmdl, unsigned int nwhen, void* pd);
void update();
private:
FELogNodeData* m_data;
FENodeSet* m_nodeSet;
PointCurve m_rf;
};
class FEElemDataFilterSum : public FEDataSource
{
public:
FEElemDataFilterSum(FEModel* fem);
~FEElemDataFilterSum();
void SetData(FELogElemData* data, FEElementSet* elemSet);
// Initialize data
bool Init() override;
// reset data
void Reset() override;
// evaluate data source at x
double Evaluate(double x) override;
private:
static bool update(FEModel* pmdl, unsigned int nwhen, void* pd);
void update();
private:
FELogElemData* m_data;
FEElementSet* m_elemSet;
PointCurve m_rf;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEBioParamRun.cpp | .cpp | 4,991 | 198 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEBioParamRun.h"
#include <FECore/FEModel.h>
#include <FECore/FEAnalysis.h>
#include <FECore/FEShellDomain.h>
#include <FECore/log.h>
#include <FEBioXML/XMLReader.h>
//! class constructor
FEBioParamRun::FEBioParamRun(FEModel* pfem) : FECoreTask(pfem)
{
m_febioOutput = false;
}
//! initialization
bool FEBioParamRun::Init(const char* szfile)
{
feLog("P A R A M R U N M O D U L E\n\n");
FEModel* fem = GetFEModel();
if (fem == nullptr) return false;
// read the input file
if (Input(szfile) == false) return false;
// don't plot anything
if (m_febioOutput == false)
{
// NOTE: I need to call GetParameterList to ensure that the parameters are allocated.
FEParameterList& pl = fem->GetParameterList();
fem->SetParameter("log_level", 0);
for (int i = 0; i < fem->Steps(); ++i)
{
fem->GetStep(i)->SetPlotLevel(FE_PLOT_NEVER);
fem->GetStep(i)->SetOutputLevel(FE_OUTPUT_NEVER);
}
}
// do the initialization of the task
if (m_febioOutput == false) GetFEModel()->BlockLog();
if (fem->Init() == false) return false;
if (m_febioOutput == false) GetFEModel()->UnBlockLog();
// initialize all parameters
for (FEModelParameter* v : m_inVar)
{
if (v->Init() == false) return false;
// set the initial value
v->SetValue(v->InitValue());
}
for (FEDataParameter* v : m_outVar)
{
if (v->Init() == false) return false;
}
// since we can change shell thickness now, we need to reinitialize
// the shell elements with the new thickness
FEMesh& mesh = GetFEModel()->GetMesh();
for (int i = 0; i < mesh.Domains(); ++i)
{
FEShellDomainNew* shellDomain = dynamic_cast<FEShellDomainNew*>(&mesh.Domain(i));
if (shellDomain) shellDomain->AssignDefaultShellThickness();
}
if (!fem->InitShells()) return false;
return true;
}
//! read control file
bool FEBioParamRun::Input(const char* szfile)
{
FEModel* fem = GetFEModel();
if (fem == nullptr) return false;
XMLReader xml;
if (xml.Open(szfile) == false) return false;
// find the root tag
XMLTag tag;
if (xml.FindTag("febio_run", tag) == false) return false;
// read the tags
++tag;
do
{
if (tag == "Parameters")
{
++tag;
do
{
if (tag == "param")
{
// read parameter
FEModelParameter* var = new FEModelParameter(fem);
// get the variable name
const char* sz = tag.AttributeValue("name");
var->SetName(sz);
// set the value
double val = 0.0;
tag.value(val);
var->InitValue() = val;
m_inVar.push_back(var);
}
else return false;
++tag;
} while (!tag.isend());
}
else if (tag == "Output")
{
++tag;
do
{
if (tag == "file")
{
tag.value(m_outFile);
}
else if (tag == "generate_febio_output")
{
tag.value(m_febioOutput);
}
else if (tag == "param")
{
// read parameter
FEDataParameter* var = new FEDataParameter(fem);
// get the variable name
const char* sz = tag.AttributeValue("name");
var->SetParameterName(sz);
m_outVar.push_back(var);
}
else return false;
++tag;
}
while (!tag.isend());
}
else return false;
++tag;
} while (!tag.isend());
// cleanup
xml.Close();
return true;
}
//! Run the task
bool FEBioParamRun::Run()
{
// get the model
FEModel* fem = GetFEModel();
if (fem == nullptr) return false;
// solve the model
if (m_febioOutput == false) GetFEModel()->BlockLog();
if (fem->Solve() == false) return false;
if (m_febioOutput == false) GetFEModel()->UnBlockLog();
// output the values
FILE* fp = fopen(m_outFile.c_str(), "wt");
for (FEDataParameter* p : m_outVar)
{
double v = p->value();
fprintf(fp, "%lg\n", v);
}
fclose(fp);
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/targetver.h | .h | 2,681 | 53 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
// The following macros define the minimum required platform. The minimum required platform
// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
// your application. The macros work by enabling all features available on platform versions up to and
// including the version specified.
// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER // Specifies that the minimum required platform is Windows Vista.
#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif
#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0.
#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE.
#endif
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEScanOptimizeMethod.cpp | .cpp | 2,697 | 95 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEScanOptimizeMethod.h"
#include "FEOptimizeData.h"
#include "FECore/log.h"
BEGIN_FECORE_CLASS(FEScanOptimizeMethod, FEOptimizeMethod)
END_FECORE_CLASS();
FEScanOptimizeMethod::FEScanOptimizeMethod(FEModel* fem) : FEOptimizeMethod(fem)
{
}
bool FEScanOptimizeMethod::Solve(FEOptimizeData* pOpt, vector<double>& amin, vector<double>& ymin, double* minObj)
{
if (pOpt == 0) return false;
FEOptimizeData& opt = *pOpt;
FEObjectiveFunction& obj = opt.GetObjective();
// set the intial values for the variables
int ma = opt.InputParameters();
vector<double> a(ma);
for (int i=0; i<ma; ++i)
{
FEInputParameter* var = opt.GetInputParameter(i);
a[i] = var->MinValue();
}
// loop until done
vector<double> y(ma, 0.0);
bool bdone = false;
double fmin = 0.0;
do
{
// solve the problem with the new input parameters
if (opt.FESolve(a) == false) return false;
// calculate objective function
double fobj = obj.Evaluate(y);
// update minimum
if ((fmin == 0.0) || (fobj < fmin))
{
fmin = fobj;
amin = a;
ymin = y;
}
// update indices
for (int i=0; i<ma; ++i)
{
FEInputParameter& vi = *opt.GetInputParameter(i);
a[i] += vi.ScaleFactor();
if (a[i] <= vi.MaxValue()) break;
else if (i<ma-1) a[i] = vi.MinValue();
else { bdone = true; }
}
}
while (!bdone);
// store the optimum data
if (minObj) *minObj = fmin;
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/stdafx.h | .h | 1,391 | 32 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
// Use this file as the precompiler header file
// TODO: Place frequently included header files here
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEConstrainedLMOptimizeMethod.cpp | .cpp | 5,749 | 203 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEConstrainedLMOptimizeMethod.h"
#include "FEOptimizeData.h"
#include "FEOptimizeInput.h"
#include "FECore/FEAnalysis.h"
#include "FECore/log.h"
#ifdef HAVE_LEVMAR
#include "levmar.h"
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FEConstrainedLMOptimizeMethod, FEOptimizeMethod)
ADD_PARAMETER(m_objtol, "obj_tol" );
ADD_PARAMETER(m_tau , "tau" );
ADD_PARAMETER(m_fdiff , "f_diff_scale");
ADD_PARAMETER(m_nmax , "max_iter" );
ADD_PARAMETER(m_scaleParams, "scale_parameters");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
FEConstrainedLMOptimizeMethod::FEConstrainedLMOptimizeMethod(FEModel* fem) : FEOptimizeMethod(fem)
{
m_pOpt = nullptr;
m_tau = 1e-3;
m_objtol = 0.001;
m_fdiff = 0.001;
m_nmax = 100;
m_scaleParams = false;
m_loglevel = LogLevel::LOG_NEVER;
}
//-----------------------------------------------------------------------------
bool FEConstrainedLMOptimizeMethod::Solve(FEOptimizeData *pOpt, vector<double>& amin, vector<double>& ymin, double* minObj)
{
m_pOpt = pOpt;
FEOptimizeData& opt = *pOpt;
// get the data
FEObjectiveFunction& obj = opt.GetObjective();
int ndata = obj.Measurements();
vector<double> y(ndata, 0);
obj.GetMeasurements(y);
// allocate matrices
int ma = opt.InputParameters();
matrix covar(ma, ma), alpha(ma, ma);
opt.m_niter = 0;
// return value
double fret = 0.0;
int niter = 1;
// if parameter scaling is not used, just set all scale factors to one
// to retain backward compatibility
if (m_scaleParams == false)
{
for (int i = 0; i < ma; ++i)
{
opt.GetInputParameter(i)->ScaleFactor() = 1.0;
}
}
try
{
vector<double> p(ma);
vector<double> s(ma);
vector<double> lb(ma);
vector<double> ub(ma);
for (int i = 0; i < ma; ++i)
{
FEInputParameter& v = *opt.GetInputParameter(i);
double a = v.GetValue();
double sf = v.ScaleFactor();
s[i] = sf;
p[i] = a / sf;
lb[i] = v.MinValue() / sf;
ub[i] = v.MaxValue() / sf;
}
vector<double> q(ndata);
for (int i=0; i<ndata; ++i) q[i] = y[i];
const double tol = m_objtol;
double opts[5] = {m_tau, tol, tol, tol, m_fdiff};
int itmax = m_nmax;
if (opt.Constraints() > 0)
{
int NC = opt.Constraints();
vector<double> A(NC * ma);
vector<double> b(NC);
for (int i=0; i<NC; ++i)
{
OPT_LIN_CONSTRAINT& con = opt.Constraint(i);
for (int j=0; j<ma; ++j) A[i*ma + j] = con.a[j] * s[j];
b[i] = con.b;
}
int ret = dlevmar_blec_dif(objfun, p.data(), q.data(), ma, ndata, lb.data(), ub.data(), A.data(), b.data(), NC, 0, itmax, opts, 0, 0, 0, (void*) this);
}
else
{
int ret = dlevmar_bc_dif(objfun, p.data(), q.data(), ma, ndata, lb.data(), ub.data(), 0, itmax, opts, 0, 0, 0, (void*) this);
}
amin.resize(ma);
for (int i = 0; i < ma; ++i)
{
amin[i] = p[i] * s[i];
}
// store the optimal values
fret = obj.Evaluate(m_yopt);
}
catch (FEErrorTermination)
{
FEModel* fem = pOpt->GetFEModel();
feLogErrorEx(fem, "FEBio error terminated. Parameter optimization cannot continue.");
return false;
}
// return optimal values
ymin = m_yopt;
if (minObj) *minObj = fret;
return true;
}
//-----------------------------------------------------------------------------
void FEConstrainedLMOptimizeMethod::ObjFun(double* p, double* hx, int m, int n)
{
// get the optimization data
FEOptimizeData& opt = *GetOptimizeData();
FEObjectiveFunction& obj = opt.GetObjective();
// evaluate at a
vector<double> a(m);
for (int i = 0; i < m; ++i)
{
FEInputParameter& var = *opt.GetInputParameter(i);
a[i] = p[i]*var.ScaleFactor();
}
// poor man's box constraints
for (int i = 0; i < opt.InputParameters(); ++i)
{
FEInputParameter& var = *opt.GetInputParameter(i);
if (a[i] < var.MinValue()) {
feLogEx(opt.GetFEModel(), "Warning: clamping %s to min (was %lg)\n", var.GetName().c_str(), a[i]);
a[i] = var.MinValue();
}
else if (a[i] >= var.MaxValue()) {
feLogEx(opt.GetFEModel(), "Warning: clamping %s to max (was %lg)\n", var.GetName().c_str(), a[i]);
a[i] = var.MaxValue();
}
}
// solve the problem
if (opt.FESolve(a) == false) throw FEErrorTermination();
// store the measurement vector
vector<double> y(n, 0.0);
opt.GetObjective().Evaluate(y);
for (int i = 0; i < n; ++i) hx[i] = y[i];
// store the last calculated values
m_yopt = y;
}
#endif
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/FEConstrainedLMOptimizeMethod.h | .h | 2,442 | 69 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEOptimizeMethod.h"
#include <FECore/matrix.h>
//----------------------------------------------------------------------------
//! Optimization method using contrained Levenberg-Marquardt method
#ifdef HAVE_LEVMAR
class FEConstrainedLMOptimizeMethod : public FEOptimizeMethod
{
public:
FEConstrainedLMOptimizeMethod(FEModel* fem);
bool Solve(FEOptimizeData* pOpt, vector<double>& amin, vector<double>& ymin, double* minObj) override;
FEOptimizeData* GetOptimizeData() { return m_pOpt; }
protected:
FEOptimizeData* m_pOpt;
void ObjFun(double* p, double* hx, int m, int n);
static void objfun(double* p, double* hx, int m, int n, void* adata)
{
FEConstrainedLMOptimizeMethod* clm = (FEConstrainedLMOptimizeMethod*)adata;
return clm->ObjFun(p, hx, m , n);
}
public:
double m_tau; // scale factor for mu
double m_objtol; // objective tolerance
double m_fdiff; // forward difference step size
int m_nmax; // maximum number of iterations
int m_loglevel; // log file output level
bool m_scaleParams; // scale parameters flag
public:
vector<double> m_yopt; // optimal y-values
DECLARE_FECORE_CLASS();
};
#endif
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/febioopt_api.h | .h | 1,529 | 41 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#ifdef WIN32
#ifdef FECORE_DLL
#ifdef febioopt_EXPORTS
#define FEBIOOPT_API __declspec(dllexport)
#else
#define FEBIOOPT_API __declspec(dllimport)
#endif
#else
#define FEBIOOPT_API
#endif
#else
#define FEBIOOPT_API
#endif
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEScanOptimizeMethod.h | .h | 1,900 | 47 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEOptimizeMethod.h"
//----------------------------------------------------------------------------
//! Basic method that scans the parameter space for a minimum.
class FEScanOptimizeMethod : public FEOptimizeMethod
{
public:
FEScanOptimizeMethod(FEModel* fem);
// this implements the solution algorithm.
// returns the optimal parameter values in amin
// returns the optimal measurement vector in ymin
// returns the optimal objective function value in minObj
bool Solve(FEOptimizeData* pOpt, vector<double>& amin, vector<double>& ymin, double* minObj) override;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEOptimizeInput.cpp | .cpp | 15,873 | 614 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEOptimizeData.h"
#include "FELMOptimizeMethod.h"
#include "FEPowellOptimizeMethod.h"
#include "FEScanOptimizeMethod.h"
#include "FEConstrainedLMOptimizeMethod.h"
#include "FEOptimizeInput.h"
#include <FECore/log.h>
#include <FEBioXML/xmltool.h>
#include <FECore/FELogElemMath.h>
#include <FECore/FECoreKernel.h>
//=============================================================================
// FEOptimizeInput
//=============================================================================
//-----------------------------------------------------------------------------
//! Read the data from the xml input file
//!
bool FEOptimizeInput::Input(const char* szfile, FEOptimizeData* pOpt)
{
// try to open the file
XMLReader xml;
if (xml.Open(szfile) == false)
{
fprintf(stderr, "\nFATAL ERROR: Failed to load file %s\n", szfile);
return false;
}
// find the root element
XMLTag tag;
if (xml.FindTag("febio_optimize", tag) == false) return false;
// check for the version attribute
const char* szversion = tag.AttributeValue("version", true);
if ((szversion == 0) || (strcmp(szversion, "2.0") != 0))
{
fprintf(stderr, "\nFATAL ERROR: Invalid version number for febio_optimize!\n\n");
return false;
}
m_opt = pOpt;
// process the file
bool ret = true;
try {
++tag;
do
{
if (tag == "Task" ) ParseTask(tag);
else if (tag == "Options" ) ParseOptions(tag);
else if (tag == "Parameters" ) ParseParameters(tag);
else if (tag == "Constraints") ParseConstraints(tag);
else if (tag == "Objective" ) ParseObjective(tag);
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
catch (...)
{
fprintf(stderr, "Fatal exception while reading optimization input file.\n");
ret = false;
}
// all done
xml.Close();
return ret;
}
//-------------------------------------------------------------------------------------------------
void FEOptimizeInput::ParseTask(XMLTag& tag)
{
m_opt->m_pTask = fecore_new<FECoreTask>(tag.szvalue(), m_opt->GetFEModel());
if (m_opt->m_pTask == nullptr) throw XMLReader::InvalidValue(tag);
}
//-------------------------------------------------------------------------------------------------
void FEOptimizeInput::ParseOptions(XMLTag& tag)
{
FEModel* fem = m_opt->GetFEModel();
const char* szt = tag.AttributeValue("type", true);
if (szt == 0) szt = "levmar";
FEOptimizeMethod* popt = fecore_new< FEOptimizeMethod>(szt, fem);
if (popt == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", szt);
// get the parameter list
FEParameterList& pl = popt->GetParameterList();
if (!tag.isleaf())
{
++tag;
do
{
if (fexml::readParameter(tag, pl) == false)
{
if (tag == "log_level")
{
char szval[256];
tag.value(szval);
if (strcmp(szval, "LOG_DEFAULT") == 0) {} // don't change the plot level
else if (strcmp(szval, "LOG_NEVER") == 0) popt->m_loglevel = LogLevel::LOG_NEVER;
else if (strcmp(szval, "LOG_FILE_ONLY") == 0) popt->m_loglevel = LogLevel::LOG_FILE;
else if (strcmp(szval, "LOG_SCREEN_ONLY") == 0) popt->m_loglevel = LogLevel::LOG_SCREEN;
else if (strcmp(szval, "LOG_FILE_AND_SCREEN") == 0) popt->m_loglevel = LogLevel::LOG_FILE_AND_SCREEN;
else throw XMLReader::InvalidValue(tag);
}
else if (tag == "print_level")
{
char szval[256];
tag.value(szval);
if (strcmp(szval, "PRINT_ITERATIONS") == 0) popt->m_print_level = PRINT_ITERATIONS;
else if (strcmp(szval, "PRINT_VERBOSE" ) == 0) popt->m_print_level = PRINT_VERBOSE;
else
{
int print_level = atoi(szval);
if ((print_level == PRINT_ITERATIONS) || (print_level == PRINT_VERBOSE))
{
popt->m_print_level = print_level;
}
else throw XMLReader::InvalidValue(tag);
}
}
else throw XMLReader::InvalidTag(tag);
}
++tag;
} while (!tag.isend());
}
m_opt->SetSolver(popt);
}
//-------------------------------------------------------------------------------------------------
void FEOptimizeInput::ParseObjective(XMLTag& tag)
{
FEModel& fem = *m_opt->GetFEModel();
// get the type attribute
const char* sztype = tag.AttributeValue("type");
if (strcmp(sztype, "data-fit" ) == 0) ParseObjectiveDataFit(tag);
else if (strcmp(sztype, "target" ) == 0) ParseObjectiveTarget(tag);
else if (strcmp(sztype, "element-data") == 0) ParseObjectiveElementData(tag);
else if (strcmp(sztype, "node-data" ) == 0) ParseObjectiveNodeData(tag);
else throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
FEOptimizeMethod* solver = m_opt->GetSolver();
if (solver)
{
FEObjectiveFunction& obj = m_opt->GetObjective();
if (solver->m_print_level == PRINT_ITERATIONS) obj.SetVerbose(false);
else obj.SetVerbose(true);
}
}
void FEOptimizeInput::ParseObjectiveDataFit(XMLTag& tag)
{
FEModel& fem = *m_opt->GetFEModel();
FEDataFitObjective* obj = new FEDataFitObjective(&fem);
m_opt->SetObjective(obj);
++tag;
do
{
if (tag == "fnc")
{
FEDataSource* src = ParseDataSource(tag);
obj->SetDataSource(src);
}
else if (tag == "data")
{
vector<pair<double, double> > data;
// see if the user wants to read the data from a text file
const char* szf = tag.AttributeValue("import", true);
if (szf)
{
// make sure this tag is a leaf
if ((tag.isempty() == false) || (tag.isleaf() == false)) throw XMLReader::InvalidValue(tag);
// read the data form a text file
FILE* fp = fopen(szf, "rt");
if (fp == 0) throw XMLReader::InvalidAttributeValue(tag, "import", szf);
char szline[256] = { 0 };
do
{
fgets(szline, 255, fp);
double t, v;
int n = sscanf(szline, "%lg%lg", &t, &v);
if (n == 2)
{
pair<double, double> pt(t, v);
data.push_back(pt);
}
else break;
} while ((feof(fp) == 0) && (ferror(fp) == 0));
fclose(fp);
}
else
{
double v[2] = { 0 };
++tag;
do
{
tag.value(v, 2);
pair<double, double> p(v[0], v[1]);
data.push_back(p);
++tag;
} while (!tag.isend());
}
obj->SetMeasurements(data);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
void FEOptimizeInput::ParseObjectiveTarget(XMLTag& tag)
{
FEModel& fem = *m_opt->GetFEModel();
FEMinimizeObjective* obj = new FEMinimizeObjective(&fem);
m_opt->SetObjective(obj);
++tag;
do
{
if (tag == "var")
{
const char* szname = tag.AttributeValue("name");
double trg;
tag.value(trg);
obj->AddFunction(new FEMinimizeObjective::ParamFunction(&fem, szname, trg));
}
else if (tag == "fnc")
{
const char* sztype = tag.AttributeValue("type");
if (strcmp(sztype, "filter_avg") == 0)
{
FEElementSet* elset = nullptr;
FELogElemData* pdata = nullptr;
double target = 0;
++tag;
do
{
if (tag == "elem_data")
{
const char* szdata = tag.AttributeValue("data");
const char* szset = tag.AttributeValue("elem_set");
FEMesh& mesh = fem.GetMesh();
elset = mesh.FindElementSet(szset);
if (elset == nullptr) throw XMLReader::InvalidAttributeValue(tag, "elem_set");
// try to allocate the element data record
if (szdata && (szdata[0] == '='))
{
FELogElemMath* logMath = fecore_alloc(FELogElemMath, &fem);
if (logMath)
{
string smath(szdata + 1);
if (logMath->SetExpression(smath))
{
pdata = logMath;
}
}
}
else
pdata = fecore_new<FELogElemData>(szdata, &fem);
if (pdata == nullptr) throw XMLReader::InvalidAttributeValue(tag, "data");
}
else if (tag == "target") tag.value(target);
++tag;
} while (!tag.isend());
obj->AddFunction(new FEMinimizeObjective::FilterAvgFunction(&fem, pdata, elset, target));
}
else throw XMLReader::InvalidAttributeValue(tag, "type");
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
void FEOptimizeInput::ParseObjectiveElementData(XMLTag& tag)
{
FEModel& fem = *m_opt->GetFEModel();
FEElementDataTable* obj = new FEElementDataTable(&fem);
m_opt->SetObjective(obj);
++tag;
do
{
if (tag == "var")
{
const char* sztype = tag.AttributeValue("type");
// try to allocate the element data record
FELogElemData* var = nullptr;
if (sztype && (sztype[0]=='='))
{
FELogElemMath* logMath = fecore_alloc(FELogElemMath, &fem);
if (logMath)
{
string smath(sztype + 1);
if (logMath->SetExpression(smath))
{
var = logMath;
}
}
}
else
var = fecore_new<FELogElemData>(sztype, &fem);
if (var == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
obj->SetVariable(var);
}
else if (tag == "data")
{
++tag;
do
{
if (tag == "elem")
{
const char* szid = tag.AttributeValue("id");
int nid = atoi(szid);
double v = 0.0;
tag.value(v);
obj->AddValue(nid, v);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
++tag;
} while (!tag.isend());
}
void FEOptimizeInput::ParseObjectiveNodeData(XMLTag& tag)
{
FEModel& fem = *m_opt->GetFEModel();
FENodeDataTable* obj = new FENodeDataTable(&fem);
m_opt->SetObjective(obj);
int nvars = 0;
++tag;
do
{
if (tag == "var")
{
const char* sztype = tag.AttributeValue("type");
char buf[256] = { 0 };
strcpy(buf, sztype);
char* ch = buf;
char* sz = buf;
while (*sz)
{
if ((*ch == 0) || (*ch == ';'))
{
char ch2 = *ch;
*ch = 0;
// try to allocate the element data record
FELogNodeData* var = fecore_new<FELogNodeData>(sz, &fem);
if (var == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
obj->AddVariable(var);
nvars++;
if (ch2 != 0) ch++;
sz = ch;
}
else ch++;
}
}
else if (tag == "data")
{
if (nvars == 0)
{
throw XMLReader::InvalidTag(tag);
}
++tag;
do
{
if (tag == "node")
{
const char* szid = tag.AttributeValue("id");
int nid = atoi(szid);
vector<double> v(nvars, 0.0);
int nread = tag.value(&v[0], nvars);
if (nread != nvars) throw XMLReader::InvalidValue(tag);
obj->AddValue(nid, v);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
++tag;
} while (!tag.isend());
}
FEDataSource* FEOptimizeInput::ParseDataSource(XMLTag& tag)
{
FEOptimizeData& opt = *m_opt;
FEModel& fem = *opt.GetFEModel();
FEMesh& mesh = fem.GetMesh();
const char* sztype = tag.AttributeValue("type");
if (strcmp(sztype, "parameter") == 0)
{
FEDataParameter* src = new FEDataParameter(&fem);
++tag;
do
{
if (tag == "param")
{
const char* szname = tag.AttributeValue("name");
src->SetParameterName(szname);
}
else if (tag == "ordinate")
{
const char* szname = tag.AttributeValue("name");
src->SetOrdinateName(szname);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
return src;
}
else if (strcmp(sztype, "filter_positive_only") == 0)
{
FEDataFilterPositive* src = new FEDataFilterPositive(&fem);
++tag;
do
{
if (tag == "source")
{
FEDataSource* s = ParseDataSource(tag);
src->SetDataSource(s);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
return src;
}
else if (strcmp(sztype, "filter_sum") == 0)
{
FEDataSource* flt = nullptr;
++tag;
do
{
if (tag == "node_data")
{
const char* szdata = tag.AttributeValue("data");
const char* szset = tag.AttributeValue("node_set");
FENodeSet* nodeSet = mesh.FindNodeSet(szset);
if (nodeSet == nullptr) throw XMLReader::InvalidAttributeValue(tag, "node_set", szset);
FELogNodeData* nodeData = fecore_new<FELogNodeData>(szdata, &fem);
if (nodeData == nullptr) throw XMLReader::InvalidAttributeValue(tag, "data", szdata);
FENodeDataFilterSum* dataFlt = new FENodeDataFilterSum(&fem);
dataFlt->SetData(nodeData, nodeSet);
flt = dataFlt;
}
else if (tag == "element_data")
{
const char* szdata = tag.AttributeValue("data");
const char* szset = tag.AttributeValue("elem_set");
FEElementSet* elemSet = mesh.FindElementSet(szset);
if (elemSet == nullptr) throw XMLReader::InvalidAttributeValue(tag, "elem_set", szset);
FELogElemData* elemData = nullptr;
if (szdata && (szdata[0] == '='))
{
FELogElemMath* logMath = fecore_alloc(FELogElemMath, &fem);
if (logMath)
{
string smath(szdata + 1);
if (logMath->SetExpression(smath))
{
elemData = logMath;
}
}
}
else
elemData = fecore_new<FELogElemData>(szdata, &fem);
if (elemData == nullptr) throw XMLReader::InvalidAttributeValue(tag, "data", szdata);
FEElemDataFilterSum* dataFlt = new FEElemDataFilterSum(&fem);
dataFlt->SetData(elemData, elemSet);
flt = dataFlt;
}
++tag;
}
while (!tag.isend());
return flt;
}
else throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
// we shouldn't be here
assert(false);
return 0;
}
//-------------------------------------------------------------------------------------------------
void FEOptimizeInput::ParseParameters(XMLTag& tag)
{
FEModel& fem = *m_opt->GetFEModel();
// read the parameters
++tag;
do
{
if (tag == "param")
{
FEModelParameter* var = new FEModelParameter(&fem);
// get the variable name
const char* sz = tag.AttributeValue("name");
var->SetName(sz);
// set initial values and bounds
double d[4] = { 0, 0, 0, 1 };
tag.value(d, 4);
var->InitValue() = d[0];
var->MinValue() = d[1];
var->MaxValue() = d[2];
var->ScaleFactor() = d[3];
// add the variable
m_opt->AddInputParameter(var);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
//-------------------------------------------------------------------------------------------------
void FEOptimizeInput::ParseConstraints(XMLTag& tag)
{
int NP = m_opt->InputParameters();
if ((NP > OPT_MAX_VAR) || (NP < 2)) throw XMLReader::InvalidTag(tag);
double v[OPT_MAX_VAR + 1];
++tag;
do
{
if (tag == "constraint")
{
int m = tag.value(v, OPT_MAX_VAR + 1);
if (m != NP + 1) throw XMLReader::InvalidValue(tag);
OPT_LIN_CONSTRAINT con;
for (int i = 0; i<NP; ++i) con.a[i] = v[i];
con.b = v[NP];
m_opt->AddLinearConstraint(con);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/FEOptimize.h | .h | 1,801 | 51 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FECore/FECoreTask.h"
#include "FEOptimizeData.h"
//-----------------------------------------------------------------------------
// This class defines the FEOptimize task. It allows FEBio to call the optimization
// module to solve a parameter optimization problem.
class FEOptimize : public FECoreTask
{
public:
//! class constructor
FEOptimize(FEModel* pfem);
//! initialization
bool Init(const char* szfile);
//! Run the optimization module
bool Run();
private:
FEOptimizeData m_opt;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEOptimizeData.cpp | .cpp | 7,202 | 257 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEOptimizeData.h"
#include "FELMOptimizeMethod.h"
#include "FEOptimizeInput.h"
#include <FECore/FECoreKernel.h>
#include <FECore/FEModel.h>
#include <FECore/FEAnalysis.h>
#include <FECore/log.h>
//=============================================================================
//-----------------------------------------------------------------------------
FEModelParameter::FEModelParameter(FEModel* fem) : FEInputParameter(fem)
{
m_pd = 0;
}
//-----------------------------------------------------------------------------
bool FEModelParameter::Init()
{
// find the variable
FEModel& fem = *GetFEModel();
string name = GetName();
FEParamValue val = fem.GetParameterValue(ParamString(name.c_str()));
// see if we found the parameter
if (val.isValid() == false)
{
feLogError("Cannot find parameter %s", name.c_str());
return false;
}
// Make sure it's a double
if (val.type() == FE_PARAM_DOUBLE)
{
// make sure we have a valid data pointer
double* pd = (double*)val.data_ptr();
if (pd == 0)
{
feLogError("Invalid data pointer for parameter %s", name.c_str());
return false;
}
// store the pointer to the parameter
m_pd = pd;
}
else
{
feLogError("Invalid parameter type for parameter %s", name.c_str());
return false;
}
return true;
}
//-----------------------------------------------------------------------------
double FEModelParameter::GetValue()
{
if (m_pd) return *m_pd;
return 0;
}
//-----------------------------------------------------------------------------
bool FEModelParameter::SetValue(double newValue)
{
if (m_pd == 0) return false;
(*m_pd) = newValue;
return true;
}
//=============================================================================
//-----------------------------------------------------------------------------
FEOptimizeData::FEOptimizeData(FEModel* fem) : m_fem(fem)
{
m_pSolver = 0;
m_pTask = 0;
m_niter = 0;
m_obj = 0;
}
//-----------------------------------------------------------------------------
FEOptimizeData::~FEOptimizeData(void)
{
delete m_pSolver;
}
//-----------------------------------------------------------------------------
bool FEOptimizeData::Init()
{
// allocate default optimization solver if none specified in input file
if (m_pSolver == 0) m_pSolver = new FELMOptimizeMethod(GetFEModel());
// allocate default solver if none specified in input file
if (m_pTask == 0) m_pTask = fecore_new<FECoreTask>("solve", m_fem);
// don't plot anything
for (int i = 0; i < m_fem->Steps(); ++i)
{
m_fem->GetStep(i)->SetPlotLevel(FE_PLOT_NEVER);
}
// do the initialization of the task
GetFEModel()->BlockLog();
if (m_pTask->Init(0) == false) return false;
GetFEModel()->UnBlockLog();
// initialize all input parameters
for (int i=0; i<(int)m_Var.size(); ++i)
{
FEInputParameter* p = m_Var[i];
if ((p==0) || (p->Init() == false)) return false;
// set the initial value
p->SetValue(p->InitValue());
}
// initialize the objective function
if (m_obj == 0) return false;
if (m_obj->Init() == false) return false;
return true;
}
//-----------------------------------------------------------------------------
bool FEOptimizeData::Solve()
{
// make sure we have a task that will solve the FE model
if (m_pTask == 0) return false;
// go for it!
int NVAR = (int) m_Var.size();
vector<double> amin(NVAR, 0.0);
vector<double> ymin;
double minObj = 0.0;
bool bret = m_pSolver->Solve(this, amin, ymin, &minObj);
if (bret)
{
feLog("\nP A R A M E T E R O P T I M I Z A T I O N R E S U L T S\n\n");
vector<double> xmin(ymin.size(), 0);
for (int i = 0; i < (int)ymin.size(); ++i) xmin[i] = i + 1;
m_obj->GetXValues(xmin);
feLog("\tFunction values:\n");
feLog(" X F(X)\n");
for (int i=0; i<(int) ymin.size(); ++i)
feLog("%15lg %15lg\n", xmin[i], ymin[i]);
// evaluate final regression coefficient
vector<double> y0;
m_obj->GetMeasurements(y0);
double minR2 = m_obj->RegressionCoefficient(y0, ymin);
feLog("\n\tTotal iterations ........ : %15d\n\n", m_niter);
feLog("\tFinal objective value ... : %15lg\n\n", minObj);
feLog("\tFinal regression coef ... : %15lg\n\n", minR2);
feLog("\tOptimal parameters:\n\n");
// report the parameters for the minimal value
for (int i = 0; i<NVAR; ++i)
{
FEInputParameter& var = *GetInputParameter(i);
string name = var.GetName();
feLog("\t\t%-15s = %.16lg\n", name.c_str(), amin[i]);
}
}
return bret;
}
//-----------------------------------------------------------------------------
//! Read the data from the input file
//!
bool FEOptimizeData::Input(const char *szfile)
{
FEOptimizeInput in;
if (in.Input(szfile, this) == false) return false;
return true;
}
//-----------------------------------------------------------------------------
bool FEOptimizeData::RunTask()
{
if (m_pTask == 0) return false;
return m_pTask->Run();
}
//-----------------------------------------------------------------------------
//! solve the FE problem with a new set of parameters
bool FEOptimizeData::FESolve(const vector<double>& a)
{
// increase iterator counter
m_niter++;
// reset objective function data
FEObjectiveFunction& obj = GetObjective();
obj.Reset();
// set the input parameters
int nvar = InputParameters();
if (nvar != (int)a.size()) return false;
for (int i = 0; i<nvar; ++i)
{
FEInputParameter& var = *GetInputParameter(i);
var.SetValue(a[i]);
}
// report the new values
feLog("\n----- Iteration: %d -----\n", m_niter);
for (int i = 0; i<nvar; ++i)
{
FEInputParameter& var = *GetInputParameter(i);
string name = var.GetName();
feLog("%-15s = %lg\n", name.c_str(), var.GetValue());
}
// reset the FEM data
FEModel& fem = *GetFEModel();
fem.BlockLog();
fem.Reset();
fem.UnBlockLog();
// solve the FE problem
fem.BlockLog();
bool bret = RunTask();
fem.UnBlockLog();
return bret;
}
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/FEObjectiveFunction.cpp | .cpp | 10,896 | 475 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEObjectiveFunction.h"
#include <FECore/FEModel.h>
#include <FECore/log.h>
//=============================================================================
FEObjectiveFunction::FEObjectiveFunction(FEModel* fem) : m_fem(fem)
{
m_verbose = false;
}
FEObjectiveFunction::~FEObjectiveFunction()
{
}
bool FEObjectiveFunction::Init()
{
// make sure we have a model
if (m_fem == 0) return false;
return true;
}
void FEObjectiveFunction::Reset()
{
}
double FEObjectiveFunction::Evaluate()
{
vector<double> dummy(Measurements());
return Evaluate(dummy);
}
double FEObjectiveFunction::Evaluate(vector<double>& y)
{
// get the number of measurements
int ndata = Measurements();
y.resize(ndata);
// evaluate the functions
EvaluateFunctions(y);
// get the measurement vector
vector<double> y0(ndata);
GetMeasurements(y0);
vector<double> x(ndata);
for (int i = 0; i < ndata; ++i) x[i] = i + 1;
GetXValues(x);
// evaluate regression coefficient R^2
double rsq = RegressionCoefficient(y0, y);
double chisq = 0.0;
if (m_verbose) feLog(" CURRENT REQUIRED DIFFERENCE\n");
for (int i = 0; i<ndata; ++i)
{
double dy = (y[i] - y0[i]);
chisq += dy*dy;
if (m_verbose) feLog("%15.10lg %15.10lg %15.10lg %15lg\n", x[i], y[i], y0[i], fabs(y[i] - y0[i]));
}
feLog("objective value: %lg\n", chisq);
feLog("regression coef: %lg\n", rsq);
return chisq;
}
double FEObjectiveFunction::RegressionCoefficient(const std::vector<double>& y0, const std::vector<double>& y)
{
int ndata = (int)y0.size();
double xb = 0, yb = 0, xyb = 0, x2b = 0, y2b = 0;
for (int i = 0; i < ndata; ++i)
{
xb += y0[i]; yb += y[i];
xyb += y0[i] * y[i];
x2b += pow(y0[i], 2); y2b += pow(y[i], 2);
}
xb /= ndata; yb /= ndata;
xyb /= ndata;
x2b /= ndata; y2b /= ndata;
double D = (x2b - xb * xb) * (y2b - yb * yb);
double rsq = (D != 0 ? pow(xyb - xb * yb, 2) / D : 0);
return rsq;
}
//=============================================================================
//----------------------------------------------------------------------------
FEDataFitObjective::FEDataFitObjective(FEModel* fem) : FEObjectiveFunction(fem)
{
m_src = 0;
}
FEDataFitObjective::~FEDataFitObjective()
{
if (m_src) delete m_src;
m_src = 0;
}
//----------------------------------------------------------------------------
bool FEDataFitObjective::Init()
{
if (FEObjectiveFunction::Init() == false) return false;
// get the FE model
FEModel& fem = *GetFEModel();
// initialize data source
if (m_src == 0) return false;
if (m_src->Init() == false) return false;
return true;
}
//----------------------------------------------------------------------------
// set the data source
void FEDataFitObjective::SetDataSource(FEDataSource* src)
{
if (m_src) delete m_src;
m_src = src;
}
//----------------------------------------------------------------------------
// set the data measurements
void FEDataFitObjective::SetMeasurements(const vector<pair<double, double> >& data)
{
m_lc.Clear();
int n = (int)data.size();
for (int i=0; i<n; ++i)
{
const pair<double,double>& pt = data[i];
m_lc.Add(pt.first, pt.second);
}
}
//----------------------------------------------------------------------------
void FEDataFitObjective::Reset()
{
// call base class first
FEObjectiveFunction::Reset();
m_src->Reset();
}
//----------------------------------------------------------------------------
// return the number of measurements. I.e. the size of the measurement vector
int FEDataFitObjective::Measurements()
{
return m_lc.Points();
}
//----------------------------------------------------------------------------
// Evaluate the measurement vector and return in y0
void FEDataFitObjective::GetMeasurements(vector<double>& y0)
{
int ndata = m_lc.Points();
y0.resize(ndata);
for (int i = 0; i<ndata; ++i) y0[i] = m_lc.Point(i).y();
}
void FEDataFitObjective::GetXValues(std::vector<double>& x)
{
x = m_x;
}
//----------------------------------------------------------------------------
void FEDataFitObjective::EvaluateFunctions(vector<double>& f)
{
int ndata = m_lc.Points();
m_x.resize(ndata);
for (int i = 0; i<ndata; ++i)
{
double xi = m_lc.Point(i).x();
m_x[i] = xi;
f[i] = m_src->Evaluate(xi);
}
}
//=============================================================================
bool FEMinimizeObjective::ParamFunction::Init()
{
if (!Function::Init()) return false;
FEParamValue val = m_fem->GetParameterValue(ParamString(m_name.c_str()));
if (val.isValid() == false) return false;
if (val.type() != FE_PARAM_DOUBLE) return false;
m_var = (double*)val.data_ptr();
if (m_var == nullptr) return false;
return true;
}
FEMinimizeObjective::FilterAvgFunction::FilterAvgFunction(FEModel* fem, FELogElemData* pd, FEElementSet* elemSet, double trg) : Function(fem)
{
m_pd = pd;
m_elemSet = elemSet;
m_y0 = trg;
}
bool FEMinimizeObjective::FilterAvgFunction::Init()
{
if (!Function::Init()) return false;
if (m_pd == nullptr) return false;
if (m_elemSet == nullptr) return false;
return true;
}
double FEMinimizeObjective::FilterAvgFunction::Value() const
{
int NE = m_elemSet->Elements();
double sum = 0.0;
for (int i = 0; i < NE; ++i)
{
sum += m_pd->value(m_elemSet->Element(i));
}
sum /= (double)NE;
return sum;
}
FEMinimizeObjective::FEMinimizeObjective(FEModel* fem) : FEObjectiveFunction(fem)
{
}
FEMinimizeObjective::~FEMinimizeObjective()
{
for (Function* f : m_Func) delete f;
m_Func.clear();
}
void FEMinimizeObjective::AddFunction(FEMinimizeObjective::Function* func)
{
m_Func.push_back(func);
}
bool FEMinimizeObjective::Init()
{
if (FEObjectiveFunction::Init() == false) return false;
FEModel* fem = GetFEModel();
if (fem == nullptr) return false;
int N = (int) m_Func.size();
for (int i=0; i<N; ++i)
{
Function& Fi = *m_Func[i];
if (Fi.Init() == false) return false;
}
return true;
}
int FEMinimizeObjective::Measurements()
{
return (int) m_Func.size();
}
void FEMinimizeObjective::EvaluateFunctions(vector<double>& f)
{
int N = (int)m_Func.size();
f.resize(N);
for (int i=0; i<N; ++i)
{
Function& Fi = *m_Func[i];
f[i] = Fi.Value();
}
}
void FEMinimizeObjective::GetMeasurements(vector<double>& y)
{
int N = (int) m_Func.size();
y.resize(N);
for (int i=0; i<N; ++i)
{
y[i] = m_Func[i]->Target();
}
}
//=============================================================================
FEElementDataTable::FEElementDataTable(FEModel* fem) : FEObjectiveFunction(fem)
{
m_var = nullptr;
}
void FEElementDataTable::AddValue(int elemID, double v)
{
Entry d;
d.elemId = elemID;
d.target = v;
d.pe = nullptr;
m_Data.push_back(d);
}
void FEElementDataTable::SetVariable(FELogElemData* var)
{
m_var = var;
}
bool FEElementDataTable::Init()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int N = (int)m_Data.size();
if (N == 0) return false;
for (int i = 0; i < N; ++i)
{
Entry& di = m_Data[i];
FEElement* el = mesh.FindElementFromID(di.elemId);
if (el == nullptr) return false;
di.pe = el;
}
return true;
}
// return number of measurements (i.e. nr of terms in objective function)
int FEElementDataTable::Measurements()
{
return (int)m_Data.size();
}
// evaluate the function values (i.e. the f_i above)
void FEElementDataTable::EvaluateFunctions(vector<double>& f)
{
assert(m_var);
int N = (int)m_Data.size();
f.resize(N);
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
for (int i = 0; i < N; ++i)
{
FEElement* pe = m_Data[i].pe;
// calculate element average measure
double val = m_var->value(*pe);
// store result
f[i] = val;
}
}
// get the measurement vector (i.e. the y_i above)
void FEElementDataTable::GetMeasurements(vector<double>& y)
{
int N = (int)m_Data.size();
y.resize(N);
for (int i = 0; i < N; ++i)
{
y[i] = m_Data[i].target;
}
}
//=============================================================================
FENodeDataTable::FENodeDataTable(FEModel* fem) : FEObjectiveFunction(fem)
{
}
bool FENodeDataTable::AddValue(int nodeID, vector<double>& v)
{
if (v.size() != m_var.size()) return false;
for (int i = 0; i < v.size(); ++i)
{
Entry d;
d.nodeId = nodeID;
d.target = v[i];
d.ivar = i;
d.index = -1;
m_Data.push_back(d);
}
return true;
}
void FENodeDataTable::AddVariable(FELogNodeData* var)
{
m_var.push_back(var);
}
bool FENodeDataTable::Init()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int N = (int)m_Data.size();
if (N == 0) return false;
for (int i = 0; i < N; ++i)
{
Entry& di = m_Data[i];
FENode* node = mesh.FindNodeFromID(di.nodeId);
if (node == nullptr) return false;
di.index = di.nodeId - 1; // NOTE: This assumes one-based indexing of node IDs.
}
return true;
}
// return number of measurements (i.e. nr of terms in objective function)
int FENodeDataTable::Measurements()
{
return (int)m_Data.size();
}
// evaluate the function values (i.e. the f_i above)
void FENodeDataTable::EvaluateFunctions(vector<double>& f)
{
assert(m_var.size() > 0);
int N = (int)m_Data.size();
f.resize(N);
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
for (int i = 0; i < N; ++i)
{
int n = m_Data[i].index;
int v = m_Data[i].ivar;
// calculate node value
double val = m_var[v]->value(mesh.Node(n));
// store result
f[i] = val;
}
}
// get the measurement vector (i.e. the y_i above)
void FENodeDataTable::GetMeasurements(vector<double>& y)
{
int N = (int)m_Data.size();
y.resize(N);
for (int i = 0; i < N; ++i)
{
y[i] = m_Data[i].target;
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/FEParameterSweep.h | .h | 2,116 | 68 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FECoreTask.h>
// This class represents a parameter that will be swept
class FESweepParam
{
public:
FESweepParam();
FESweepParam(const FESweepParam& p);
void operator = (const FESweepParam& p);
void SetValue(double v);
public:
string m_paramName;
double m_min, m_max, m_step;
double* m_pd;
};
// This task implements a parameter sweep, where the same model is run similar times,
// each time with one or more parameters modified.
class FEParameterSweep : public FECoreTask
{
public:
FEParameterSweep(FEModel* fem);
//! initialization
bool Init(const char* szfile) override;
//! Run the optimization module
bool Run() override;
private:
bool Input(const char* szfile);
bool InitParams();
bool FESolve(const vector<double>& a);
private:
vector<FESweepParam> m_params;
int m_niter;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEParameterSweep.cpp | .cpp | 5,501 | 240 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEParameterSweep.h"
#include <FEBioXML/XMLReader.h>
#include <FECore/FEModel.h>
#include <FECore/FEAnalysis.h>
#include <FECore/log.h>
FESweepParam::FESweepParam()
{
m_min = m_max = m_step = 0.0;
m_pd = nullptr;
}
FESweepParam::FESweepParam(const FESweepParam& p)
{
m_min = p.m_min;
m_max = p.m_max;
m_step = p.m_step;
m_paramName = p.m_paramName;
m_pd = p.m_pd;
}
void FESweepParam::operator = (const FESweepParam& p)
{
m_min = p.m_min;
m_max = p.m_max;
m_step = p.m_step;
m_paramName = p.m_paramName;
m_pd = p.m_pd;
}
void FESweepParam::SetValue(double v)
{
*m_pd = v;
}
FEParameterSweep::FEParameterSweep(FEModel* fem) : FECoreTask(fem)
{
m_niter = 0;
}
//! initialization
bool FEParameterSweep::Init(const char* szfile)
{
// read the control file
if (Input(szfile) == false) return false;
// initialize the model
if (GetFEModel()->Init() == false) return false;
// check the parameters
if (InitParams() == false) return false;
// don't plot anything
GetFEModel()->GetCurrentStep()->SetPlotHint(FE_PLOT_APPEND);
GetFEModel()->GetCurrentStep()->SetPlotLevel(FE_PLOT_FINAL);
return true;
}
bool FEParameterSweep::InitParams()
{
// Make sure we have something to do
if (m_params.empty()) return false;
// check the parameters
FEModel& fem = *GetFEModel();
for (size_t i = 0; i<m_params.size(); ++i)
{
FESweepParam& p = m_params[i];
// find the variable
string name = p.m_paramName;
FEParamValue val = fem.GetParameterValue(ParamString(name.c_str()));
// see if we found the parameter
if (val.isValid() == false)
{
feLogError("Cannot find parameter %s", name.c_str());
return false;
}
// see if it's the correct type
if (val.type() != FE_PARAM_DOUBLE)
{
feLogError("Invalid parameter type for parameter %s", name.c_str());
return false;
}
// make sure we have a valid data pointer
double* pd = (double*)val.data_ptr();
if (pd == 0)
{
feLogError("Invalid data pointer for parameter %s", name.c_str());
return false;
}
// store the pointer to the parameter
p.m_pd = pd;
}
return true;
}
bool FEParameterSweep::Input(const char* szfile)
{
// open the xml file
XMLReader xml;
if (xml.Open(szfile) == false) return false;
// find the root tag
XMLTag tag;
if (xml.FindTag("febio_sweep", tag) == false) return false;
++tag;
do
{
if (tag == "param")
{
FESweepParam p;
// read the parameter name
const char* szname = tag.AttributeValue("name");
p.m_paramName = szname;
// read the values
double d[3];
int n = tag.value(d, 3);
if (n != 3) throw XMLReader::InvalidValue(tag);
// some error checking
p.m_min = d[0];
p.m_max = d[1];
p.m_step = d[2];
if (p.m_max < p.m_min) throw XMLReader::InvalidValue(tag);
if (p.m_step <= 0.0) throw XMLReader::InvalidValue(tag);
// looks good, so throw it on the pile
m_params.push_back(p);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
// all done
xml.Close();
return true;
}
//! Run the optimization module
bool FEParameterSweep::Run()
{
size_t ma = m_params.size();
vector<double> a(ma);
for (size_t i = 0; i<ma; ++i)
{
FESweepParam& pi = m_params[i];
a[i] = pi.m_min;
}
// run the parameter sweep
bool bdone = false;
do
{
// solve the problem with the new input parameters
if (FESolve(a) == false) return false;
// update indices
for (size_t i = 0; i<ma; ++i)
{
FESweepParam& pi = m_params[i];
a[i] += pi.m_step;
if (a[i] <= pi.m_max) break;
else if (i<ma - 1) a[i] = pi.m_min;
else { bdone = true; }
}
}
while (!bdone);
return true;
}
bool FEParameterSweep::FESolve(const vector<double>& a)
{
++m_niter;
feLog("\n----- Iteration: %d -----\n", m_niter);
// set the input parameters
size_t nvar = m_params.size();
assert(nvar == a.size());
for (int i = 0; i<nvar; ++i)
{
FESweepParam& var = m_params[i];
var.SetValue(a[i]);
string name = var.m_paramName;
feLog("%-15s = %lg\n", name.c_str(), a[i]);
}
// reset the FEM data
FEModel& fem = *GetFEModel();
fem.BlockLog();
// reset model
fem.Reset();
// solve the FE problem
bool bret = fem.Solve();
fem.UnBlockLog();
return bret;
}
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/FELMOptimizeMethod.cpp | .cpp | 8,761 | 331 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FELMOptimizeMethod.h"
#include "FEOptimizeData.h"
#include "FEOptimizeInput.h"
#include "FECore/FEAnalysis.h"
#include "FECore/log.h"
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FELMOptimizeMethod, FEOptimizeMethod)
ADD_PARAMETER(m_objtol, "obj_tol" );
ADD_PARAMETER(m_fdiff , "f_diff_scale");
ADD_PARAMETER(m_nmax , "max_iter" );
ADD_PARAMETER(m_bcov , "print_cov" );
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
FELMOptimizeMethod* FELMOptimizeMethod::m_pThis = 0;
// forward declarations
void mrqmin(vector<double>& x,
vector<double>& y,
vector<double>& sig,
vector<double>& a,
matrix& covar,
matrix& alpha,
vector<double>& oneda,
vector<double>& atry,
vector<double>& beta,
vector<double>& da,
double& chisq,
void funcs(vector<double>& , vector<double>&, vector<double>&, matrix&),
double& alamda);
void mrqcof(vector<double>& x,
vector<double>& y,
vector<double>& sig,
vector<double>& a,
matrix& alpha,
vector<double>& beta,
double& chisq,
void funcs(vector<double>& , vector<double>&, vector<double>&, matrix&));
//-----------------------------------------------------------------------------
FELMOptimizeMethod::FELMOptimizeMethod(FEModel* fem) : FEOptimizeMethod(fem)
{
m_objtol = 0.001;
m_fdiff = 0.001;
m_nmax = 100;
m_bcov = 0;
m_loglevel = LogLevel::LOG_NEVER;
}
//-----------------------------------------------------------------------------
bool FELMOptimizeMethod::Solve(FEOptimizeData *pOpt, vector<double>& amin, vector<double>& ymin, double* minObj)
{
m_pOpt = pOpt;
FEOptimizeData& opt = *pOpt;
// set the variables
int ma = opt.InputParameters();
vector<double> a(ma);
for (int i=0; i<ma; ++i)
{
FEInputParameter& var = *opt.GetInputParameter(i);
a[i] = var.GetValue();
}
// set the data
FEObjectiveFunction& obj = opt.GetObjective();
int ndata = obj.Measurements();
vector<double> x(ndata), y(ndata);
obj.GetMeasurements(y);
// we don't really need x so we create a dummy array
for (int i = 0; i<ndata; ++i) x[i] = i;
// set the sigma's
// for now we set them all to 1
vector<double> sig(ndata);
for (int i = 0; i<ndata; ++i) sig[i] = 1;
// allocate matrices
matrix covar(ma, ma), alpha(ma, ma);
// allocate vectors for mrqmin
vector<double> oneda(ma), atry(ma), beta(ma), da(ma);
// set the this pointer
m_pThis = this;
opt.m_niter = 0;
// return value
double fret = 0.0;
int niter = 1;
FEModel* fem = pOpt->GetFEModel();
try
{
// do the first call with lamda to intialize the minimization
double alamda = -1.0;
feLogEx(fem, "\n----- Major Iteration: %d -----\n", 0);
mrqmin(x, y, sig, a, covar, alpha, oneda, atry, beta, da, fret, objfun, alamda);
// repeat until converged
double fprev = fret, lam1 = alamda;
bool bconv = false;
do
{
feLogEx(fem, "\n----- Major Iteration: %d -----\n", niter);
mrqmin(x, y, sig, a, covar, alpha, oneda, atry, beta, da, fret, objfun, alamda);
if (alamda < lam1)
{
if (niter != 1)
{
double df = (fprev - fret)/(fprev + fret + 1);
if ( df < m_objtol) bconv = true;
feLogEx(fem, "objective value: %lg (diff = %lg)\n\n", fret, df);
}
}
else feLogEx(fem, "\n objective value: %lg\n\n", fret);
fprev = fret;
lam1 = alamda;
++niter;
}
while ((bconv == false) && (niter < m_nmax));
// do final call with lamda = 0
alamda = 0.0;
mrqmin(x, y, sig, a, covar, alpha, oneda, atry, beta, da, fret, objfun, alamda);
}
catch (FEErrorTermination)
{
feLogErrorEx(fem, "FEBio error terminated. Parameter optimization cannot continue.");
return false;
}
// store optimal values
amin = a;
ymin = m_yopt;
if (minObj) *minObj = fret;
return true;
}
//-----------------------------------------------------------------------------
void FELMOptimizeMethod::ObjFun(vector<double>& x, vector<double>& a, vector<double>& y, matrix& dyda)
{
// get the optimization data
FEOptimizeData& opt = *m_pOpt;
// poor man's box constraints
double dir = 1; // forward difference by default
for (int i=0; i<opt.InputParameters(); ++i)
{
FEInputParameter& var = *opt.GetInputParameter(i);
if (a[i] < var.MinValue()) {
a[i] = var.MinValue();
} else if (a[i] >= var.MaxValue()) {
a[i] = var.MaxValue();
dir = -1; // use backward difference
}
}
// evaluate at a
if (opt.FESolve(a) == false) throw FEErrorTermination();
opt.GetObjective().Evaluate(y);
m_yopt = y;
// now calculate the derivatives using forward differences
int ndata = (int)x.size();
vector<double> a1(a);
vector<double> y1(ndata);
int ma = (int)a.size();
for (int i=0; i<ma; ++i)
{
FEInputParameter& var = *opt.GetInputParameter(i);
double b = var.ScaleFactor();
a1[i] = a1[i] + dir*m_fdiff*(fabs(b) + fabs(a[i]));
assert(a1[i] != a[i]);
if (opt.FESolve(a1) == false) throw FEErrorTermination();
opt.GetObjective().Evaluate(y1);
for (int j=0; j<ndata; ++j) dyda[j][i] = (y1[j] - y[j])/(a1[i] - a[i]);
a1[i] = a[i];
}
}
//-----------------------------------------------------------------------------
void mrqmin(vector<double>& x,
vector<double>& y,
vector<double>& sig,
vector<double>& a,
matrix& covar,
matrix& alpha,
vector<double>& oneda,
vector<double>& atry,
vector<double>& beta,
vector<double>& da,
double& chisq,
void funcs(vector<double>& , vector<double>&, vector<double>&, matrix&),
double& alamda)
{
static double ochisq;
int j, k, l;
int ma = (int)a.size();
if (alamda < 0)
{
alamda = 0.001;
mrqcof(x, y, sig, a, alpha, beta, chisq, funcs);
ochisq = chisq;
for (j=0; j<ma; j++) atry[j] = a[j];
}
matrix temp(ma, ma);
for (j=0; j<ma; j++)
{
for (k=0; k<ma; k++) covar[j][k] = alpha[j][k];
covar[j][j] = alpha[j][j]*(1.0 + alamda);
for (k=0; k<ma; k++) temp[j][k] = covar[j][k];
oneda[j] = beta[j];
}
matrix tempi = temp.inverse();
oneda = tempi*oneda;
for (j=0; j<ma; j++)
{
for (k=0; k<ma; k++) covar[j][k] = tempi[j][k];
da[j] = oneda[j];
}
if (alamda == 0.0) return;
for (j=0, l=0; l<ma; l++) atry[l] = a[l] + da[j++];
mrqcof(x, y, sig, atry, covar, da, chisq, funcs);
if (chisq < ochisq)
{
alamda *= 0.1;
ochisq = chisq;
for (j=0; j<ma; j++)
{
for (k=0; k<ma; k++) alpha[j][k] = covar[j][k];
beta[j] = da[j];
}
for (l=0; l<ma; l++) a[l] = atry[l];
}
else
{
alamda *= 10.0;
chisq = ochisq;
}
}
//-----------------------------------------------------------------------------
void mrqcof(vector<double>& x,
vector<double>& y,
vector<double>& sig,
vector<double>& a,
matrix& alpha,
vector<double>& beta,
double& chisq,
void funcs(vector<double>& , vector<double>&, vector<double>&, matrix&))
{
int i, j, k, l, m;
double wt, sig2i, dy;
int ndata = (int)x.size();
int ma = (int)a.size();
for (j=0; j<ma; j++)
{
for (k=0; k<=j; k++) alpha[j][k] = 0.0;
beta[j] = 0.0;
}
vector<double> ymod(ndata);
matrix dyda(ndata, ma);
funcs(x, a, ymod, dyda);
chisq = 0.0;
for (i=0; i<ndata; i++)
{
sig2i = 1.0 / (sig[i]*sig[i]);
dy = y[i] - ymod[i];
for (j=0, l=0; l<ma; l++)
{
wt = dyda[i][l]*sig2i;
for (k=0, m=0; m<l+1; m++) alpha[j][k++] += wt*dyda[i][m];
beta[j++] += dy*wt;
}
chisq += dy*dy*sig2i;
}
for (j=1; j<ma; j++)
for (k=0; k<j; k++) alpha[k][j] = alpha[j][k];
}
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/FEPowellOptimizeMethod.h | .h | 1,823 | 49 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEOptimizeMethod.h"
//----------------------------------------------------------------------------
//! Optimization method using Powell's method
class FEPowellOptimizeMethod : public FEOptimizeMethod
{
public:
FEPowellOptimizeMethod(FEModel* fem);
bool Solve(FEOptimizeData* pOpt, vector<double>& amin, vector<double>& ymin, double* minObj);
protected:
double ObjFun(double* p);
FEOptimizeData* m_pOpt;
static FEPowellOptimizeMethod* m_pThis;
static double objfun(double* p) { return (m_pThis)->ObjFun(p); }
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEOptimizeData.h | .h | 5,448 | 189 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEModel.h>
#include <FECore/FECoreTask.h>
#include "FEObjectiveFunction.h"
#include <vector>
#include <string>
//-----------------------------------------------------------------------------
class FEOptimizeMethod;
//-----------------------------------------------------------------------------
//! This class represents an input parameter. Input parameters define the parameter
//! space that will be searched for the optimal parameter value.
class FEInputParameter
{
public:
FEInputParameter(FEModel* fem) : m_fem(fem) { m_min = -1e99; m_max = 1e99; m_scale = 1.0; }
virtual ~FEInputParameter() {}
// implement this to initialize the input parameter
virtual bool Init() { return true; }
//! return the current value of the input parameter
virtual double GetValue() = 0;
//! set the current value of the input parameter.
//! should return false is the passed value is invalid
virtual bool SetValue(double newValue) = 0;
//! get/set the initial value
double& InitValue() { return m_initVal; }
//! get/set the min value
double& MinValue() { return m_min; }
//! get/set the max value
double& MaxValue() { return m_max; }
//! get/set scale factor
double& ScaleFactor() { return m_scale; }
//! set the name
void SetName(const string& name) { m_name = name; }
//! get the name
string GetName() { return m_name; }
//! Get the FEModel
FEModel* GetFEModel() { return m_fem; }
private:
string m_name; //!< name of input parameter
double m_initVal; //!< initial value
double m_min, m_max; //!< min, max values for parameter
double m_scale; //!< scale factor
FEModel* m_fem; //!< pointer to model data
};
//-----------------------------------------------------------------------------
// Class for choosing model parameters as input parameters
class FEModelParameter : public FEInputParameter
{
public:
FEModelParameter(FEModel* fem);
//! Initialize
bool Init();
public:
//! return the current value of the input parameter
double GetValue();
//! set the current value of the input parameter.
//! should return false is the passed value is invalid
bool SetValue(double newValue);
private:
string m_name; //!< variable name
double* m_pd; //!< pointer to variable data
double m_val; //!< value
};
//=============================================================================
#define OPT_MAX_VAR 64
struct OPT_LIN_CONSTRAINT
{
double a[OPT_MAX_VAR];
double b;
};
//=============================================================================
//! optimization analyses
//!
class FEOptimizeData
{
public:
//! constructor
FEOptimizeData(FEModel* fem);
~FEOptimizeData(void);
//! input function
bool Input(const char* sz);
//! Initialize data
bool Init();
//! solver the problem
bool Solve();
//! return the FE Model
FEModel* GetFEModel() { return m_fem; }
//! solve the FE problem with a new set of parameters
bool FESolve(const std::vector<double>& a);
public:
// return the number of input parameters
int InputParameters() { return (int)m_Var.size(); }
//! add an input parameter to optimize
void AddInputParameter(FEInputParameter* var) { m_Var.push_back(var); }
//! return an input parameter
FEInputParameter* GetInputParameter(int n) { return m_Var[n]; }
public:
//! add a linear constraint
void AddLinearConstraint(OPT_LIN_CONSTRAINT& con) { m_LinCon.push_back(con); }
//! return number of constraints
int Constraints() { return (int) m_LinCon.size(); }
//! return a linear constraint
OPT_LIN_CONSTRAINT& Constraint(int i) { return m_LinCon[i]; }
FEObjectiveFunction& GetObjective() { return *m_obj; }
void SetObjective(FEObjectiveFunction* obj) { m_obj = obj; }
void SetSolver(FEOptimizeMethod* po) { m_pSolver = po; }
FEOptimizeMethod* GetSolver() { return m_pSolver; }
bool RunTask();
public:
int m_niter; // nr of minor iterations (i.e. FE solves)
FECoreTask* m_pTask; // the task that will solve the FE model
protected:
FEModel* m_fem;
FEObjectiveFunction* m_obj; //!< the objective function
FEOptimizeMethod* m_pSolver;
std::vector<FEInputParameter*> m_Var;
std::vector<OPT_LIN_CONSTRAINT> m_LinCon;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEOptimizeMethod.cpp | .cpp | 1,468 | 34 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEOptimizeMethod.h"
FEOptimizeMethod::FEOptimizeMethod(FEModel* fem) : FECoreClass(fem)
{
m_loglevel = LogLevel::LOG_NEVER;
m_print_level = PRINT_ITERATIONS;
}
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/FEObjectiveFunction.h | .h | 8,158 | 288 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/PointCurve.h>
#include <vector>
#include <string>
#include "FEDataSource.h"
#include <FECore/ElementDataRecord.h>
#include <FECore/NodeDataRecord.h>
class FEModel;
class FEElement;
//=============================================================================
//! This class evaluates the objective function, which is defined as the sum
//! of squares of non-linear functions.
// ----
// \ 2
// f_obj = / [ f_i(a) - y_i]
// ----
// i
//
//! It is an abstract base class and derived classes
//! need to implement the nonlinear functions.
class FEObjectiveFunction
{
public:
// constructor
FEObjectiveFunction(FEModel* fem);
virtual ~FEObjectiveFunction();
// one-time initialization
virtual bool Init();
// This is called before each optimization iteration
// and should be used by derived classes to reset any data
virtual void Reset();
// evaluate objective function
// also returns the function values in f
virtual double Evaluate(std::vector<double>& f);
// evaluate objective function
double Evaluate();
// print output to screen or not
void SetVerbose(bool b) { m_verbose = b; }
bool IsVerbose() const { return m_verbose; }
// return the FE model
FEModel* GetFEModel() { return m_fem; }
public:
double RegressionCoefficient(const std::vector<double>& y0, const std::vector<double>& y);
public: // These functions need to be implemented by derived classes
// return number of measurements (i.e. nr of terms in objective function)
virtual int Measurements() = 0;
// evaluate the function values (i.e. the f_i above)
virtual void EvaluateFunctions(std::vector<double>& f) = 0;
// get the measurement vector (i.e. the y_i above)
virtual void GetMeasurements(std::vector<double>& y) = 0;
// get the x values (ignore if not applicable)
virtual void GetXValues(std::vector<double>& x) {}
private:
FEModel* m_fem;
bool m_verbose; //!< print data flag
};
//=============================================================================
// Objective function for fitting value pairs data
// In this case the nonlinear functions are defined as:
// f_i(a) = F(t_i; a)
// where t_i is the time for time step i, and F is the function that will be fitted to the measurement vector.
class FEDataFitObjective : public FEObjectiveFunction
{
public:
FEDataFitObjective(FEModel* fem);
~FEDataFitObjective();
// one-time initialization
bool Init();
// This is called before each optimization iteration
// and should be used by derived classes to reset any data
void Reset();
// set the data source
void SetDataSource(FEDataSource* src);
// set the data measurements
void SetMeasurements(const std::vector<pair<double, double> >& data);
public:
// return number of measurements
int Measurements();
// evaluate the function values
void EvaluateFunctions(std::vector<double>& f);
// get the measurement vector
void GetMeasurements(std::vector<double>& y);
void GetXValues(std::vector<double>& x);
private:
PointCurve m_lc; //!< data load curve for evaluating measurements
FEDataSource* m_src; //!< source for evaluating functions
std::vector<double> m_x;
};
//=============================================================================
// Objective function for minimization of model parameters
class FEMinimizeObjective : public FEObjectiveFunction
{
class Function
{
public:
Function(FEModel* fem) : m_fem(fem) {}
virtual ~Function() {}
virtual bool Init() { return (m_fem != nullptr); }
virtual double Target() const = 0;
virtual double Value() const = 0;
protected:
FEModel* m_fem;
};
public:
class ParamFunction : public Function
{
public:
string m_name;
double* m_var = nullptr;
double m_y0 = 0; // target value (i.e. "measurment")
ParamFunction(FEModel* fem, const string& name, double trg) : Function(fem), m_name(name), m_y0(trg) {}
public:
bool Init() override;
double Target() const override { return m_y0; }
double Value() const override { return *m_var; }
};
class FilterAvgFunction : public Function
{
public:
FELogElemData* m_pd = nullptr;
FEElementSet* m_elemSet = nullptr;
double m_y0 = 0;
FilterAvgFunction(FEModel* fem, FELogElemData* pd, FEElementSet* elemSet, double trg);
public:
bool Init() override;
double Target() const override { return m_y0; }
double Value() const override;
};
public:
FEMinimizeObjective(FEModel* fem);
~FEMinimizeObjective();
// one-time initialization
bool Init() override;
void AddFunction(Function* func);
public:
// return number of measurements
int Measurements() override;
// evaluate the function values
void EvaluateFunctions(std::vector<double>& f) override;
// get the measurement vector
void GetMeasurements(std::vector<double>& y) override;
private:
std::vector<Function*> m_Func;
};
//=============================================================================
// This objective function evaluates element values with a user-defined
// table of values. The table stores for each element the required value.
class FEElementDataTable : public FEObjectiveFunction
{
struct Entry {
int elemId; // the ID of the element
double target; // the target value
FEElement* pe; // pointer to element
};
public:
FEElementDataTable(FEModel* fem);
bool Init() override;
void AddValue(int elemID, double v);
void SetVariable(FELogElemData* var);
public:
// return number of measurements (i.e. nr of terms in objective function)
int Measurements() override;
// evaluate the function values (i.e. the f_i above)
void EvaluateFunctions(std::vector<double>& f) override;
// get the measurement vector (i.e. the y_i above)
void GetMeasurements(std::vector<double>& y) override;
private:
std::vector<Entry> m_Data;
FELogElemData* m_var;
};
//=============================================================================
// This objective function evaluates node values with a user-defined
// table of values. The table stores for each node the required value.
class FENodeDataTable : public FEObjectiveFunction
{
struct Entry {
int nodeId; // the ID of the node
double target; // the target value
int index; // zero-based node index
int ivar; // variable
};
public:
FENodeDataTable(FEModel* fem);
bool Init() override;
bool AddValue(int elemID, std::vector<double>& v);
void AddVariable(FELogNodeData* var);
public:
// return number of measurements (i.e. nr of terms in objective function)
int Measurements() override;
// evaluate the function values (i.e. the f_i above)
void EvaluateFunctions(std::vector<double>& f) override;
// get the measurement vector (i.e. the y_i above)
void GetMeasurements(std::vector<double>& y) override;
private:
std::vector<Entry> m_Data;
std::vector<FELogNodeData*> m_var;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEBioOpt.h | .h | 1,935 | 45 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "febioopt_api.h"
//-----------------------------------------------------------------------------
//! The FEBioOpt module
//! The FEBioOpt module solves parameter optimization problems with FEBio
//!
namespace FEBioOpt {
FEBIOOPT_API void InitModule();
// wrapper function for some levmar calls.
// This is only used in FEBio Studio, but don't want to link there with levmar.
FEBIOOPT_API int optimize(
void (*func)(double* p, double* hx, int m, int n, void* adata),
double* p, double* x, int m, int n, double* lb, double* ub, double* dscl,
int itmax, double* opts, double* info, double* work, double* covar, void* adata);
}
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FELMOptimizeMethod.h | .h | 2,330 | 61 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEOptimizeMethod.h"
#include <FECore/matrix.h>
#include <vector>
//----------------------------------------------------------------------------
//! Optimization method using Levenberg-Marquardt method
class FELMOptimizeMethod : public FEOptimizeMethod
{
public:
FELMOptimizeMethod(FEModel* fem);
bool Solve(FEOptimizeData* pOpt, std::vector<double>& amin, std::vector<double>& ymin, double* minObj) override;
protected:
FEOptimizeData* m_pOpt;
void ObjFun(std::vector<double>& x, std::vector<double>& a, std::vector<double>& y, matrix& dyda);
static FELMOptimizeMethod* m_pThis;
static void objfun(std::vector<double>& x, std::vector<double>& a, std::vector<double>& y, matrix& dyda) { return m_pThis->ObjFun(x, a, y, dyda); }
public:
double m_objtol; // objective tolerance
double m_fdiff; // forward difference step size
int m_nmax; // maximum number of iterations
bool m_bcov; // flag to print covariant matrix
protected:
std::vector<double> m_yopt; // optimal y-values
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FEBioOpt/FEOptimize.cpp | .cpp | 2,835 | 90 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEOptimize.h"
#include "FEOptimizeData.h"
#include "FECore/FECoreKernel.h"
#include "FECore/log.h"
#include "FECore/Timer.h"
//-----------------------------------------------------------------------------
#define VERSION 2
#define SUB_VERSION 0
//-----------------------------------------------------------------------------
FEOptimize::FEOptimize(FEModel* pfem) : FECoreTask(pfem), m_opt(pfem)
{
}
//-----------------------------------------------------------------------------
bool FEOptimize::Init(const char* szfile)
{
char szversion[32] = { 0 };
snprintf(szversion, sizeof(szversion), "version %d.%d", VERSION, SUB_VERSION);
feLog("P A R A M E T E R O P T I M I Z A T I O N M O D U L E\n%s\n\n", szversion);
// read the data from the xml input file
if (m_opt.Input(szfile) == false) return false;
// do initialization
bool ret = m_opt.Init();
if (ret == false)
{
feLogErrorEx(m_opt.GetFEModel(), "Failed to initialize the optimization data.");
return false;
}
return true;
}
//-----------------------------------------------------------------------------
bool FEOptimize::Run()
{
Timer timer;
timer.start();
// solve the problem
bool bret = m_opt.Solve();
timer.stop();
double elapsedTime = timer.GetTime();
char sztime[64];
Timer::time_str(elapsedTime, sztime);
feLog("\n\tTotal elapsed time : %s (%lg sec)\n\n", sztime, elapsedTime);
if (bret)
feLog("\n\n N O R M A L T E R M I N A T I O N\n\n");
else
feLog("\n\n E R R O R T E R M I N A T I O N\n\n");
return bret;
}
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/FEBioOpt.cpp | .cpp | 2,738 | 74 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEBioOpt.h"
#include "FEOptimize.h"
#include "FEParameterSweep.h"
#include "FEBioParamRun.h"
#include <FECore/FECoreKernel.h>
#include "FELMOptimizeMethod.h"
#include "FEConstrainedLMOptimizeMethod.h"
#include "FEPowellOptimizeMethod.h"
#include "FEScanOptimizeMethod.h"
#ifdef HAVE_LEVMAR
#include "levmar.h"
#endif
//-----------------------------------------------------------------------------
//! Initialization of the FEBioOpt module. This function registers all the classes
//! in this module with the FEBio framework.
void FEBioOpt::InitModule()
{
// Task classes
REGISTER_FECORE_CLASS(FEOptimize , "optimize");
REGISTER_FECORE_CLASS(FEParameterSweep, "parameter_sweep");
REGISTER_FECORE_CLASS(FEBioParamRun , "param_run");
// optimization methods
REGISTER_FECORE_CLASS(FELMOptimizeMethod, "levmar");
#ifdef HAVE_LEVMAR
REGISTER_FECORE_CLASS(FEConstrainedLMOptimizeMethod, "constrained levmar");
#endif
REGISTER_FECORE_CLASS(FEPowellOptimizeMethod, "powell");
REGISTER_FECORE_CLASS(FEScanOptimizeMethod, "scan");
}
int FEBioOpt::optimize(
void (*func)(double* p, double* hx, int m, int n, void* adata),
double* p, double* x, int m, int n, double* lb, double* ub, double* dscl,
int itmax, double* opts, double* info, double* work, double* covar, void* adata)
{
#ifdef HAVE_LEVMAR
return dlevmar_bc_dif(func, p, x, m, n, lb, ub, dscl, itmax, opts, info, work, covar, adata);
#else
return -1;
#endif
}
| C++ |
3D | febiosoftware/FEBio | FEBioOpt/FEDataSource.cpp | .cpp | 13,806 | 551 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include <cwctype>
#include "FEDataSource.h"
#include <FECore/FEModel.h>
#include <FECore/log.h>
#include <FECore/NodeDataRecord.h>
#include <FECore/ElementDataRecord.h>
#include <FECore/SurfaceDataRecord.h>
#include <FECore/DomainDataRecord.h>
//=================================================================================================
FEDataSource::FEDataSource(FEModel* fem) : m_fem(*fem)
{
}
FEDataSource::~FEDataSource()
{
}
bool FEDataSource::Init()
{
return true;
}
void FEDataSource::Reset()
{
}
//=================================================================================================
bool FEDataParameter::update(FEModel* pmdl, unsigned int nwhen, void* pd)
{
// get the optimizaton data
FEDataParameter& src = *((FEDataParameter*)pd);
src.update();
return true;
}
void FEDataParameter::update()
{
// get the current time value
double time = m_fem.GetTime().currentTime;
// evaluate the current reaction force value
double x = m_fx();
double y = m_fy();
// add the data pair to the loadcurve
m_rf.Add(x, y);
}
FEDataParameter::FEDataParameter(FEModel* fem) : FEDataSource(fem)
{
m_ord = "fem.time";
}
void FEDataParameter::SetParameterName(const std::string& name)
{
m_param = name;
}
// set the ordinate name
void FEDataParameter::SetOrdinateName(const std::string& name)
{
m_ord = name;
}
bool FEDataParameter::Init()
{
FEModel* fem = &m_fem;
// find all the parameters
FEParamValue val = m_fem.GetParameterValue(ParamString(m_param.c_str()));
if (val.isValid() == false) {
// see if it's a data parameter
if (strstr(m_param.c_str(), "fem.node_data"))
{
char buf[256] = { 0 };
strcpy(buf, m_param.c_str());
char* sz = buf + 14;
char* c1 = strchr(sz, ',');
*c1++ = 0;
int nid = atoi(c1);
c1 = strrchr(sz, '\'');
if (sz[0] == '\'') sz++;
*c1 = 0;
FELogNodeData* pd = fecore_new<FELogNodeData>(sz, fem);
if (pd == nullptr) { feLogErrorEx(fem, "Invalid parameter name %s", m_param.c_str()); return false; }
FEMesh& mesh = fem->GetMesh();
FENode* pn = mesh.FindNodeFromID(nid);
if (pn == nullptr) { feLogErrorEx(fem, "Invalid node id"); return false; }
m_fy = [=]() { return pd->value(*pn); };
}
else if (strstr(m_param.c_str(), "fem.element_data"))
{
char buf[256] = { 0 };
strcpy(buf, m_param.c_str());
char* sz = buf + 17;
char* c1 = strchr(sz, ',');
*c1++ = 0;
int eid = atoi(c1);
c1 = strrchr(sz, '\'');
if (sz[0] == '\'') sz++;
*c1 = 0;
FELogElemData* pd = fecore_new<FELogElemData>(sz, fem);
if (pd == nullptr) { feLogErrorEx(fem, "Invalid parameter name %s", m_param.c_str()); return false; }
FEMesh& mesh = fem->GetMesh();
FEElement* pe = mesh.FindElementFromID(eid);
if (pe == nullptr) { feLogErrorEx(fem, "Invalid element id"); return false; }
m_fy = [=]() { return pd->value(*pe); };
}
else if (strstr(m_param.c_str(), "fem.surface_data"))
{
char buf[256] = { 0 };
strcpy(buf, m_param.c_str());
char* sz = buf + 17;
char* c1 = strchr(sz, ',');
*c1++ = 0;
char* szsurf = strchr(c1, '\'');
if (szsurf == 0) { feLogErrorEx(fem, "Syntax error in parameter name %s", m_param.c_str()); return false; }
szsurf++;
c1 = strrchr(sz, '\'');
if (sz[0] == '\'') sz++;
*c1 = 0;
c1 = strrchr(szsurf, '\'');
if (c1) *c1 = 0;
FELogSurfaceData* pd = fecore_new<FELogSurfaceData>(sz, fem);
if (pd == nullptr) { feLogErrorEx(fem, "Invalid parameter name %s", m_param.c_str()); return false; }
FEMesh& mesh = fem->GetMesh();
FESurface* surf = mesh.FindSurface(szsurf);
if (surf == nullptr) { feLogErrorEx(fem, "Invalid surface name %s", szsurf); return false; }
m_fy = [=]() { return pd->value(*surf); };
}
else if (strstr(m_param.c_str(), "fem.domain_data"))
{
const char* c = m_param.c_str() + 15;
char buf[256] = { 0 };
int n = 0;
bool skipws = true;
while (c && *c)
{
if (*c == '\'')
{
if (skipws) skipws = false; else skipws = true;
}
if ((skipws == false) || (iswspace(*c) == 0)) buf[n++] = *c;
c++;
}
buf[n] = 0;
char* sz = buf;
int l = strlen(sz);
if (sz[0 ] != '(') { feLogErrorEx(fem, "Syntax error in parameter name %s", m_param.c_str()); return false; }
if (sz[l-1] != ')') { feLogErrorEx(fem, "Syntax error in parameter name %s", m_param.c_str()); return false; }
sz[l - 1] = 0;
*sz++ = 0;
// separate string in data variable and domain name
char* c1 = strrchr(sz, ',');
*c1++ = 0;
// process part name
char* szdom = strchr(c1, '\'');
if (szdom == 0) { feLogErrorEx(fem, "Syntax error in parameter name %s", m_param.c_str()); return false; }
szdom++;
c1 = strrchr(szdom, '\'');
if (c1) *c1 = 0; else { feLogErrorEx(fem, "Syntax error in parameter name %s", m_param.c_str()); return false; }
FEMesh& mesh = fem->GetMesh();
FEDomain* dom = mesh.FindDomain(szdom);
if (dom == nullptr) { feLogErrorEx(fem, "Invalid domain name %s", szdom); return false; }
// process data name
FELogDomainData* pd = nullptr;
if (sz[0] == '\'')
{
sz++;
c1 = strrchr(sz, '\'');
if (c1 == nullptr) { feLogErrorEx(fem, "Invalid domain name %s", szdom); return false; }
*c1 = 0;
pd = fecore_new<FELogDomainData>(sz, fem);
}
else
{
c1 = strchr(sz, '(');
if (c1 == nullptr) { feLogErrorEx(fem, "Syntax error"); return false; }
char* cvar = c1 + 1;
*c1 = 0;
if ((c1 = strrchr(cvar, ')')) == nullptr) { feLogErrorEx(fem, "Syntax error"); return false; }
*c1 = 0;
std::vector<std::string> varList;
do
{
if (cvar[0] == '\'')
{
*cvar++ = 0;
if ((c1 = strchr(cvar, '\'')) == nullptr) { feLogErrorEx(fem, "Syntax error"); return false; }
*c1 = 0;
varList.push_back(cvar);
cvar = c1 + 1;
}
else varList.push_back(cvar);
cvar = strchr(cvar, ',');
if (cvar) cvar++;
} while (cvar && *cvar);
pd = fecore_new<FELogDomainData>(sz, fem);
if (pd == nullptr) { feLogErrorEx(fem, "Syntax error"); return false; }
if (pd->SetParameters(varList) == false) { feLogErrorEx(fem, "Syntax error"); return false; }
}
if (pd == nullptr) { feLogErrorEx(fem, "Invalid parameter name %s", m_param.c_str()); return false; }
m_fy = [=]() { return pd->value(*dom); };
}
else
{
feLogErrorEx(fem, "Invalid parameter name %s", m_param.c_str());
return false;
}
}
else
{
if (val.type() != FE_PARAM_DOUBLE) {
feLogErrorEx(fem, "Invalid type for parameter %s", m_param.c_str());
return false;
}
m_fy = [=]() { return val.value<double>(); };
}
// find the ordinate
val = m_fem.GetParameterValue(ParamString(m_ord.c_str()));
if (val.isValid() == false) {
// see if it's a data parameter
if (strstr(m_ord.c_str(), "fem.node_data"))
{
char buf[256] = { 0 };
strcpy(buf, m_ord.c_str());
char* sz = buf + 14;
char* c1 = strchr(sz, ',');
*c1++ = 0;
int nid = atoi(c1);
c1 = strrchr(sz, '\'');
if (sz[0] == '\'') sz++;
*c1 = 0;
FELogNodeData* pd = fecore_new<FELogNodeData>(sz, fem);
if (pd == nullptr) { feLogErrorEx(fem, "Invalid ordinate name %s", m_ord.c_str()); return false; }
FEMesh& mesh = fem->GetMesh();
FENode* pn = mesh.FindNodeFromID(nid);
if (pn == nullptr) { feLogErrorEx(fem, "Invalid node id"); return false; }
m_fx = [=]() { return pd->value(*pn); };
}
else if (strstr(m_ord.c_str(), "fem.element_data"))
{
char buf[256] = { 0 };
strcpy(buf, m_ord.c_str());
char* sz = buf + 17;
char* c1 = strchr(sz, ',');
*c1++ = 0;
int eid = atoi(c1);
c1 = strrchr(sz, '\'');
if (sz[0] == '\'') sz++;
*c1 = 0;
FELogElemData* pd = fecore_new<FELogElemData>(sz, fem);
if (pd == nullptr) { feLogErrorEx(fem, "Invalid ordinate name %s", m_ord.c_str()); return false; }
FEMesh& mesh = fem->GetMesh();
FEElement* pe = mesh.FindElementFromID(eid);
if (pe == nullptr) { feLogErrorEx(fem, "Invalid element id"); return false; }
m_fx = [=]() { return pd->value(*pe); };
}
else
{
feLogErrorEx(fem, "Invalid ordinate name %s", m_ord.c_str());
return false;
}
}
else
{
if (val.type() != FE_PARAM_DOUBLE) {
feLogErrorEx(fem, "Invalid type for ordinate %s", m_ord.c_str());
return false;
}
m_fx = [=]() { return val.value<double>(); };
}
// register callback
m_fem.AddCallback(update, CB_INIT | CB_MAJOR_ITERS, (void*) this);
return FEDataSource::Init();
}
void FEDataParameter::Reset()
{
// reset the reaction force load curve
m_rf.Clear();
FEDataSource::Reset();
}
double FEDataParameter::Evaluate(double x)
{
return m_rf.value(x);
}
//=================================================================================================
FEDataFilterPositive::FEDataFilterPositive(FEModel* fem) : FEDataSource(fem)
{
m_src = 0;
}
FEDataFilterPositive::~FEDataFilterPositive()
{
if (m_src) delete m_src;
}
void FEDataFilterPositive::SetDataSource(FEDataSource* src)
{
if (m_src) delete m_src;
m_src = src;
}
bool FEDataFilterPositive::Init()
{
if (m_src == 0) return false;
return m_src->Init();
}
void FEDataFilterPositive::Reset()
{
if (m_src) m_src->Reset();
}
double FEDataFilterPositive::Evaluate(double t)
{
double v = m_src->Evaluate(t);
return (v >= 0.0 ? v : -v);
}
//=================================================================================================
FENodeDataFilterSum::FENodeDataFilterSum(FEModel* fem) : FEDataSource(fem)
{
m_data = nullptr;
m_nodeSet = nullptr;
}
FENodeDataFilterSum::~FENodeDataFilterSum()
{
delete m_data;
}
void FENodeDataFilterSum::SetData(FELogNodeData* data, FENodeSet* nodeSet)
{
m_data = data;
m_nodeSet = nodeSet;
}
// Initialize data
bool FENodeDataFilterSum::Init()
{
if (m_data == nullptr) return false;
if (m_nodeSet == nullptr) return false;
if (m_data->Init() == false) return false;
// register callback
m_fem.AddCallback(update, CB_MAJOR_ITERS, (void*)this);
return FEDataSource::Init();
}
// reset data
void FENodeDataFilterSum::Reset()
{
m_rf.Clear();
m_rf.Add(0, 0);
}
// evaluate data source at x
double FENodeDataFilterSum::Evaluate(double x)
{
return m_rf.value(x);
}
bool FENodeDataFilterSum::update(FEModel* pmdl, unsigned int nwhen, void* pd)
{
// get the optimizaton data
FENodeDataFilterSum& src = *((FENodeDataFilterSum*)pd);
src.update();
return true;
}
void FENodeDataFilterSum::update()
{
// get the current time value
double time = m_fem.GetTime().currentTime;
FEMesh* mesh = m_nodeSet->GetMesh();
FENodeSet& ns = *m_nodeSet;
double sum = 0.0;
for (int i = 0; i < m_nodeSet->Size(); ++i)
{
double vi = m_data->value(*ns.Node(i));
sum += vi;
}
// evaluate the current reaction force value
double x = time;
double y = sum;
// add the data pair to the loadcurve
m_rf.Add(x, y);
}
FEElemDataFilterSum::FEElemDataFilterSum(FEModel* fem) : FEDataSource(fem)
{
m_data = nullptr;
m_elemSet = nullptr;
}
FEElemDataFilterSum::~FEElemDataFilterSum()
{
delete m_data;
}
void FEElemDataFilterSum::SetData(FELogElemData* data, FEElementSet* elemSet)
{
m_data = data;
m_elemSet = elemSet;
}
// Initialize data
bool FEElemDataFilterSum::Init()
{
if (m_data == nullptr) return false;
if (m_elemSet == nullptr) return false;
if (m_data->Init() == false) return false;
// register callback
m_fem.AddCallback(update, CB_MAJOR_ITERS, (void*)this);
return FEDataSource::Init();
}
// reset data
void FEElemDataFilterSum::Reset()
{
m_rf.Clear();
m_rf.Add(0, 0);
}
// evaluate data source at x
double FEElemDataFilterSum::Evaluate(double x)
{
return m_rf.value(x);
}
bool FEElemDataFilterSum::update(FEModel* pmdl, unsigned int nwhen, void* pd)
{
// get the optimizaton data
FEElemDataFilterSum& src = *((FEElemDataFilterSum*)pd);
src.update();
return true;
}
void FEElemDataFilterSum::update()
{
// get the current time value
double time = m_fem.GetTime().currentTime;
FEMesh* mesh = m_elemSet->GetMesh();
FEElementSet& eset = *m_elemSet;
double sum = 0.0;
for (int i = 0; i < eset.Elements(); ++i)
{
double vi = m_data->value(eset.Element(i));
sum += vi;
}
// evaluate the current reaction force value
double x = time;
double y = sum;
// add the data pair to the loadcurve
m_rf.Add(x, y);
}
| C++ |
3D | febiosoftware/FEBio | FEBioTest/FEDiagnostic.h | .h | 3,555 | 116 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FECore/FEModel.h"
#include "FEBioXML/FEBioImport.h"
class FEDiagnostic;
//-----------------------------------------------------------------------------
class FEDiagnosticScenario : public FEParamContainer
{
public:
FEDiagnosticScenario(FEDiagnostic* pdia) : m_pdia(pdia) {};
FEDiagnostic* GetDiagnostic() { return m_pdia; }
virtual bool Init() { return true; }
private:
FEDiagnostic* m_pdia;
};
//-----------------------------------------------------------------------------
//! The FEDiagnostic class is a base class that can be used to create
//! diagnostic classes to test FEBio's performance.
class FEDiagnostic : public FECoreClass
{
public:
FECORE_BASE_CLASS(FEDiagnostic)
public:
//! constructor
FEDiagnostic(FEModel* fem);
//! destructor
virtual ~FEDiagnostic();
//! initialization
virtual bool Init() { return true; }
//! run the diagnostic. Returns true on pass, false on failure
virtual bool Run() = 0;
//! load data from file
virtual bool ParseSection(XMLTag& tag) { return false; }
//! create a scenario class
virtual FEDiagnosticScenario* CreateScenario(const std::string& sname) { return 0; }
void SetFileName(const std::string& fileName);
const std::string& GetFileName();
private:
std::string m_file; //!< the input file used
};
//-----------------------------------------------------------------------------
// Control Section
class FEDiagnosticControlSection : public FEFileSection
{
public:
FEDiagnosticControlSection(FEFileImport* pim) : FEFileSection(pim) {}
void Parse(XMLTag& tag);
};
//-----------------------------------------------------------------------------
// Scenario Section parser
class FEDiagnosticScenarioSection : public FEFileSection
{
public:
FEDiagnosticScenarioSection(FEFileImport* pim) : FEFileSection(pim){}
void Parse(XMLTag& tag);
};
//-----------------------------------------------------------------------------
//! The FEDiagnosticImport class creates a specific diagnostic test. Currently
//! the only way to create a diagnostic is to load a diagnostic from file
class FEDiagnosticImport : public FEFileImport
{
public:
FEDiagnostic* LoadFile(FEModel& fem, const char* szfile);
protected:
FEDiagnostic* m_pdia;
friend class FEDiagnosticScenarioSection;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FETangentDiagnostic.h | .h | 3,102 | 110 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEDiagnostic.h"
//-----------------------------------------------------------------------------
class FETangentUniaxial : public FEDiagnosticScenario
{
public:
FETangentUniaxial(FEDiagnostic* pdia) : FEDiagnosticScenario(pdia) { m_strain = 0.0; }
bool Init() override;
private:
double m_strain;
DECLARE_FECORE_CLASS();
};
//-----------------------------------------------------------------------------
class FETangentSimpleShear : public FEDiagnosticScenario
{
public:
FETangentSimpleShear(FEDiagnostic* pdia) : FEDiagnosticScenario(pdia) { m_strain = 0.0; }
bool Init() override;
private:
double m_strain;
DECLARE_FECORE_CLASS();
};
//-----------------------------------------------------------------------------
class FETangentBiaxial : public FEDiagnosticScenario
{
public:
FETangentBiaxial(FEDiagnostic* pdia) : FEDiagnosticScenario(pdia) { m_strain = 0.0; }
bool Init() override;
private:
double m_strain;
DECLARE_FECORE_CLASS();
};
//-----------------------------------------------------------------------------
class FETangentTriaxial : public FEDiagnosticScenario
{
public:
FETangentTriaxial(FEDiagnostic* pdia) : FEDiagnosticScenario(pdia) { m_strain = 0.0; }
bool Init() override;
private:
double m_strain;
DECLARE_FECORE_CLASS();
};
//-----------------------------------------------------------------------------
//! The FETangentDiagnostic class tests the stiffness matrix implementation
//! by comparing it to a numerical approximating of the derivative of the
//! residual.
class FETangentDiagnostic : public FEDiagnostic
{
public:
FETangentDiagnostic(FEModel* fem);
FEDiagnosticScenario* CreateScenario(const std::string& sname);
bool Init();
bool Run();
protected:
void deriv_residual(matrix& ke);
public:
FEDiagnosticScenario* m_pscn;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FEMaterialTest.h | .h | 2,239 | 66 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEDiagnostic.h"
#include <FECore/ElementDataRecord.h>
//-----------------------------------------------------------------------------
//! The material test diagnostics evaluates the stress-strain of a material.
class FEMaterialTest : public FEDiagnostic
{
public:
FEMaterialTest(FEModel* fem);
~FEMaterialTest();
FEDiagnosticScenario* CreateScenario(const std::string& sname);
bool Init();
bool Run();
void SetOutputFileName(const char* szfilename);
void SetOutputVariables(const std::string& xout, const std::string& yout);
std::vector<std::pair<double, double> > GetOutputData() { return m_data; }
private:
static bool cb(FEModel* fem, unsigned int when, void* pd) { return ((FEMaterialTest*)pd)->cb(); }
bool cb();
private:
FEDiagnosticScenario* m_pscn;
const char* m_szoutfile;
std::string m_xout, m_yout;
FELogElemData* m_strain;
FELogElemData* m_stress;
std::vector<std::pair<double, double> > m_data;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FERestartDiagnostic.cpp | .cpp | 5,112 | 201 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FERestartDiagnostics.h"
#include <FECore/FEModel.h>
#include <FECore/FEAnalysis.h>
#include <FECore/DumpFile.h>
#include <FECore/log.h>
FERestartDiagnostic::FERestartDiagnostic(FEModel*pfem) : FECoreTask(pfem), m_dmp(*pfem)
{
m_bok = false;
m_bfile = false;
strcpy(m_szdmp, "out.dmp");
}
//-----------------------------------------------------------------------------
bool restart_test_cb(FEModel* pfem, unsigned int nwen, void* pd)
{
FERestartDiagnostic* ptask = (FERestartDiagnostic*) pd;
// try to create archive
if (ptask->m_bfile)
{
DumpFile ar(*pfem);
if (ar.Create(ptask->m_szdmp) == false)
{
feLogErrorEx(pfem, "FAILED CREATING RESTART DUMP FILE.\n");
return false;
}
// serialize the data
pfem->Serialize(ar);
// close the dump file.
ar.Close();
}
else
{
ptask->m_dmp.Open(true, false);
pfem->Serialize(ptask->m_dmp);
}
// set the ok flag to tell the diagnostic that the restart
// file was created successfully.
ptask->m_bok = true;
// suppress the error output
pfem->BlockLog();
return false;
}
//-----------------------------------------------------------------------------
// initialize the diagnostic
bool FERestartDiagnostic::Init(const char* sz)
{
FEModel& fem = *GetFEModel();
// copy the file name (if any)
if (sz && (sz[0] != 0)) strcpy(m_szdmp, sz);
// Make sure that restart flag is off.
// This is because we are hijacking restart and we don't
// want regular restart to interfere.
// TODO: is this really necessary? This creates a circular link between FEBioTest and FEBioLib
// fem.SetDumpLevel(FE_DUMP_NEVER);
// Add the restart callback
fem.AddCallback(restart_test_cb, CB_MAJOR_ITERS, this);
// do the FE initialization
return fem.Init();
}
//-----------------------------------------------------------------------------
// run the diagnostic
bool FERestartDiagnostic::Run()
{
FEModel* fem = GetFEModel();
while (fem->Solve() == false)
{
// reset output mode (it was turned off in restart_test_cb)
fem->UnBlockLog();
if (m_bok)
{
feLogEx(fem, "Reading restart file...");
if (m_bfile)
{
// reopen the dump file for readin
DumpFile ar(*fem);
if (ar.Open(m_szdmp) == false)
{
feLogErrorEx(fem, "FAILED OPENING RESTART DUMP FILE.\n");
return false;
}
fem->Serialize(ar);
}
else
{
m_dmp.Open(false, false);
fem->Serialize(m_dmp);
}
m_bok = false;
feLogEx(fem, "done!\n");
// reopen the log file for appending
/* const char* szlog = fem.GetLogfileName();
if (felog.append(szlog) == false)
{
printf("WARNING: Could not reopen log file. A new log file is created\n");
felog.open(szlog);
}
*/
}
else return false;
}
return true;
}
FEQuickRestartDiagnostic::FEQuickRestartDiagnostic(FEModel* pfem) : FECoreTask(pfem)
{
strcpy(m_szdmp, "out.dmp");
}
// initialize the diagnostic
bool FEQuickRestartDiagnostic::Init(const char* sz)
{
FEModel& fem = *GetFEModel();
// copy the file name (if any)
if (sz && (sz[0] != 0)) strcpy(m_szdmp, sz);
// do the FE initialization
return fem.Init();
}
// run the diagnostic
bool FEQuickRestartDiagnostic::Run()
{
FEModel* fem = GetFEModel();
// write the restart file
DumpFile out(*fem);
if (out.Create(m_szdmp) == false)
{
feLogErrorEx(fem, "Failed creating dump file!");
return false;
}
feLogEx(fem, "Writing dump file...");
fem->Serialize(out);
out.Close();
feLogEx(fem, "done!\n");
// clear the model
fem->Clear();
// reopen the dump file for reading
DumpFile in(*fem);
if (in.Open(m_szdmp) == false)
{
feLogErrorEx(fem, "failed opening restart dump file.\n");
return false;
}
feLogEx(fem, "Reading dump file...");
fem->Serialize(in);
in.Close();
feLogEx(fem, "done!\n");
feLogEx(fem, "All is well!\n\n");
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEBioTest/FEStiffnessDiagnostic.cpp | .cpp | 8,508 | 312 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEStiffnessDiagnostic.h"
#include <FECore/FEModel.h>
#include <FECore/FEAnalysis.h>
#include <FECore/FENewtonSolver.h>
#include <FECore/FEGlobalMatrix.h>
#include <FECore/FENLConstraint.h>
#include <FECore/log.h>
#include <FEBioMech/FEMechModel.h>
#include <FEBioMech/FERigidBody.h>
#include <FEBioMech/FESolidSolver2.h>
#include <iostream>
//-----------------------------------------------------------------------------
FEStiffnessDiagnostic::FEStiffnessDiagnostic(FEModel* fem) : FECoreTask(fem)
{
m_fp = nullptr;
m_writeMatrix = false;
m_nmax = -1;
}
//-----------------------------------------------------------------------------
// Initialize the diagnostic. In this function we build the FE model depending
// on the scenario.
bool FEStiffnessDiagnostic::Init(const char* szarg)
{
if (szarg && szarg[0])
{
if (strcmp(szarg, "v") == 0) m_writeMatrix = true;
else { m_nmax = atoi(szarg); m_writeMatrix = true; }
}
return GetFEModel()->Init();
}
//-----------------------------------------------------------------------------
bool stiffness_diagnostic_cb(FEModel* fem, unsigned int when, void* pd)
{
FEStiffnessDiagnostic* diagnostic = (FEStiffnessDiagnostic*)pd;
return diagnostic->Diagnose();
}
//-----------------------------------------------------------------------------
// Run the tangent diagnostic. After we run the FE model, we calculate
// the element stiffness matrix and compare that to a finite difference
// of the element residual.
bool FEStiffnessDiagnostic::Run()
{
// solve the problem
FEModel& fem = *GetFEModel();
// fem.AddCallback(stiffness_diagnostic_cb, CB_MATRIX_REFORM, (void*)this);
fem.AddCallback(stiffness_diagnostic_cb, CB_QUASIN_CONVERGED, (void*)this);
// create a file name for the log file
string logfile("diagnostic.log");
m_fp = fopen(logfile.c_str(), "wt");
fprintf(m_fp, "FEBio Stiffness Diagnostics:\n");
fprintf(m_fp, "============================\n");
fem.BlockLog();
bool bret = fem.Solve();
fem.UnBlockLog();
if (bret == false)
{
feLogError("FEBio error terminated. Aborting diagnostic.\n");
return false;
}
fprintf(m_fp, "diagnostic completed.\n");
fclose(m_fp);
m_fp = nullptr;
return true;
}
//-----------------------------------------------------------------------------
bool FEStiffnessDiagnostic::Diagnose()
{
FEModel* fem = GetFEModel();
FEMechModel* mech = dynamic_cast<FEMechModel*>(fem);
FEAnalysis* step = fem->GetCurrentStep();
if (step == nullptr) return false;
FESolidSolver2* solver = dynamic_cast<FESolidSolver2*>(step->GetFESolver());
FENewtonSolver* nlsolve = dynamic_cast<FENewtonSolver*>(solver);
if (nlsolve == nullptr) return false;
SparseMatrix* pA = nlsolve->m_pK->GetSparseMatrixPtr();
if (pA == nullptr) return false;
const double eps = 1e-8;
int neq = pA->Rows();
// need to know which dofs are prescribed
// 0 == fixed, 1 == free
vector<int> bc(neq, 0);
int nmax = -1;
FEMesh& mesh = fem->GetMesh();
for (int i = 0; i < mesh.Nodes(); ++i)
{
FENode& node = mesh.Node(i);
if (node.m_rid < 0)
{
for (int j = 0; j < node.m_ID.size(); ++j)
{
int n = node.m_ID[j];
if (n >= 0) bc[n] = 1;
if (n > nmax) nmax = n;
}
}
else
{
for (int j = 0; j < node.m_ID.size(); ++j)
{
int n = -node.m_ID[j]-2;
if (n >= 0) bc[n] = 1;
if (n > nmax) nmax = n;
}
}
}
if (mech)
{
for (int i = 0; i < mech->RigidBodies(); ++i)
{
FERigidBody& rb = *mech->GetRigidBody(i);
for (int j = 0; j < 6; ++j)
{
int n = rb.m_LM[j];
if (n >= 0) bc[n] = 1;
if (n > nmax) nmax = n;
}
}
}
if (nmax < neq)
{
// these are probably lagrange multiplier dofs
for (int i = nmax + 1; i < neq; ++i) bc[i] = 1;
}
std::vector<double> R0(neq, 0);
nlsolve->Residual(R0);
double max_val = 0, max_err = 0.0;
int i_max = -1, j_max = -1;
std::cerr << "\nstarting diagnostic:\nprogress:";
int pct = 0;
int nreq = (m_nmax <= 0 ? neq : m_nmax);
if (nreq > neq) nreq = neq;
for (int j = 0; j < nreq; ++j)
{
std::vector<double> u(neq, 0);
std::vector<double> R(neq, 0);
u[j] = eps;
nlsolve->Update(u);
nlsolve->Residual(R);
int new_pct = (100 * j) / neq;
if (pct != new_pct) {
if ((new_pct % 10) == 0)
std::cerr << "+";
else
std::cerr << "-";
pct = new_pct;
}
for (int i = 0; i < nreq; ++i)
{
// note that we flip the sign on ka.
// this is because febio actually calculates the negative of the residual
double ka_ij = 0;
if ((bc[i] == 0) || (bc[j] == 0))
{
if (i == j) ka_ij = 1;
else ka_ij = 0;
}
else ka_ij = -(R[i] - R0[i]) / eps;
double kt_ij = pA->get(i, j);
if (fabs(kt_ij) > max_val) max_val = fabs(kt_ij);
double err = fabs(kt_ij - ka_ij);
if (err > max_err)
{
max_err = err;
i_max = i;
j_max = j;
}
if (m_writeMatrix)
{
fprintf(m_fp, "%d, %d : %lg, %lg (%lg)\n", i, j, kt_ij, ka_ij, err);
}
}
}
std::cerr << "\n";
// let's make sure we leave the model in a consistent state
std::vector<double> u(neq, 0);
std::vector<double> R(neq, 0);
nlsolve->Update(u);
nlsolve->Residual(R);
printf("Max abs. value: %lg\n", max_val);
fprintf(m_fp, "Max abs. value: %lg\n", max_val);
if (max_val == 0) max_val = 1;
printf("Max error: %lg (%d, %d)\n", max_err, i_max, j_max);
printf("Max rel. error: %lg (%d, %d)\n", max_err / max_val, i_max, j_max);
fprintf(m_fp, "Max error: %lg (%d, %d)\n", max_err, i_max, j_max);
fprintf(m_fp, "Max rel. error: %lg (%d, %d)\n", max_err / max_val, i_max, j_max);
return true;
}
//-----------------------------------------------------------------------------
// Calculate a finite difference approximation of the derivative of the
// element residual.
void FEStiffnessDiagnostic::deriv_residual(matrix& ke)
{
/* // get the solver
FEModel& fem = *GetFEModel();
FEAnalysis* pstep = fem.GetCurrentStep();
FESolidSolver2& solver = static_cast<FESolidSolver2&>(*pstep->GetFESolver());
// get the degrees of freedom
const int dof_X = fem.GetDOFIndex("x");
const int dof_Y = fem.GetDOFIndex("y");
const int dof_Z = fem.GetDOFIndex("z");
// get the mesh
FEMesh& mesh = fem.GetMesh();
FEElasticSolidDomain& bd = static_cast<FEElasticSolidDomain&>(mesh.Domain(0));
// get the one and only element
FESolidElement& el = bd.Element(0);
// first calculate the initial residual
vector<double> f0(24);
zero(f0);
bd.ElementInternalForce(el, f0);
// now calculate the perturbed residuals
ke.resize(24, 24);
ke.zero();
int i, j, nj;
int N = mesh.Nodes();
double dx = 1e-8;
vector<double> f1(24);
for (j = 0; j < 3 * N; ++j)
{
FENode& node = mesh.Node(el.m_node[j / 3]);
nj = j % 3;
switch (nj)
{
case 0: node.add(dof_X, dx); node.m_rt.x += dx; break;
case 1: node.add(dof_Y, dx); node.m_rt.y += dx; break;
case 2: node.add(dof_Z, dx); node.m_rt.z += dx; break;
}
fem.Update();
zero(f1);
bd.ElementInternalForce(el, f1);
switch (nj)
{
case 0: node.sub(dof_X, dx); node.m_rt.x -= dx; break;
case 1: node.sub(dof_Y, dx); node.m_rt.y -= dx; break;
case 2: node.sub(dof_Z, dx); node.m_rt.z -= dx; break;
}
fem.Update();
for (i = 0; i < 3 * N; ++i) ke[i][j] = -(f1[i] - f0[i]) / dx;
}
*/
}
| C++ |
3D | febiosoftware/FEBio | FEBioTest/FEPrintMatrixDiagnostic.h | .h | 1,552 | 46 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEDiagnostic.h"
class FEPrintMatrixDiagnostic : public FEDiagnostic
{
public:
FEPrintMatrixDiagnostic(FEModel* fem);
~FEPrintMatrixDiagnostic(void);
bool ParseSection(XMLTag& tag);
bool Run();
protected:
char m_szout[1024];
int m_rng[4];
};
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FEJFNKTangentDiagnostic.h | .h | 1,734 | 55 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FECoreTask.h>
class FEJFNKTangentDiagnostic : public FECoreTask
{
public:
FEJFNKTangentDiagnostic(FEModel* fem);
bool Init(const char* szfile) override;
bool Run() override;
public:
bool Diagnose();
private:
double m_max_err;
double m_max_err_K, m_max_err_A;
int m_max_err_i, m_max_err_j;
double m_sum_err;
double m_max_K;
int m_evals;
double m_jfnk_eps;
double m_small_val;
int m_nstep;
int m_nprint;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FEResetTest.h | .h | 1,646 | 46 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FECoreTask.h>
#include <FECore/DumpMemStream.h>
//-----------------------------------------------------------------------------
class FEResetTest : public FECoreTask
{
public:
// constructor
FEResetTest(FEModel* pfem);
// initialize the diagnostic
bool Init(const char* sz) override;
// run the diagnostic
bool Run() override;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FEContactDiagnostic.cpp | .cpp | 7,742 | 303 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEContactDiagnostic.h"
#include "FEBioMech/FENeoHookean.h"
#include "FEBioMech/FESolidSolver2.h"
#include "FEBioMech/FESlidingInterface.h"
#include "FEBioMech/FEElasticSolidDomain.h"
#include "FEBioMech/FEResidualVector.h"
#include "FECore/log.h"
using namespace FECore;
void FEContactDiagnostic::print_matrix(DenseMatrix& m)
{
int i, j;
int N = m.Rows();
int M = m.Columns();
feLog("\n ");
for (i=0; i<N; ++i) feLog("%15d ", i);
feLog("\n----");
for (i=0; i<N; ++i) feLog("----------------", i);
for (i=0; i<N; ++i)
{
feLog("\n%2d: ", i);
for (j=0; j<M; ++j)
{
feLog("%15lg ", m(i,j));
}
}
feLog("\n");
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
FEContactDiagnostic::FEContactDiagnostic(FEModel* fem) : FEDiagnostic(fem)
{
// make sure the correct module is active
fem->SetActiveModule("solid");
FEAnalysis* pstep = new FEAnalysis(fem);
fem->AddStep(pstep);
fem->SetCurrentStep(pstep);
}
FEContactDiagnostic::~FEContactDiagnostic()
{
}
bool FEContactDiagnostic::Run()
{
// get the solver
FEModel& fem = *GetFEModel();
FEAnalysis* pstep = fem.GetCurrentStep();
FESolidSolver2& solver = static_cast<FESolidSolver2&>(*pstep->GetFESolver());
solver.Init();
// make sure contact data is up to data
fem.Update();
// create the stiffness matrix
solver.CreateStiffness(true);
// get the stiffness matrix
FEGlobalMatrix& K = *solver.GetStiffnessMatrix();
SparseMatrix *pA = (SparseMatrix*)(&K);
DenseMatrix& K0 = static_cast<DenseMatrix&>(*pA);
// we need a linear system to evaluate contact
int neq = solver.m_neq;
vector<double> Fd(neq, 0.0);
vector<double> ui(neq, 0.0);
FELinearSystem LS(&fem, K, Fd, ui, true);
// build the stiffness matrix
K0.Zero();
solver.ContactStiffness(LS);
// solver.StiffnessMatrix();
print_matrix(K0);
// calculate the derivative of the residual
DenseMatrix K1;
deriv_residual(K1);
print_matrix(K1);
// calculate difference matrix
const int N = 48;
DenseMatrix Kd; Kd.Create(N, N);
double kij, kmax = 0, k0;
int i0=-1, j0=-1;
for (int i=0; i<N; ++i)
for (int j=0; j<N; ++j)
{
Kd(i,j) = K1(i,j) - K0(i,j);
k0 = fabs(K0(i,j));
if (k0 < 1e-15) k0 = 1;
kij = 100.0*fabs(Kd(i,j))/k0;
if (kij > kmax)
{
kmax = kij;
i0 = i;
j0 = j;
}
}
print_matrix(Kd);
feLog("\nMaximum difference: %lg%% (at (%d,%d))\n", kmax, i0, j0);
return (kmax < 1e-3);
}
//-----------------------------------------------------------------------------
bool FEContactDiagnostic::Init()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// --- create the geometry ---
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
// currently we simply assume a two-element contact problem
// so we create two elements
const double eps = 0.5;
mesh.CreateNodes(16);
mesh.SetDOFS(MAX_DOFS);
mesh.Node( 0).m_r0 = vec3d(0,0,0);
mesh.Node( 1).m_r0 = vec3d(1,0,0);
mesh.Node( 2).m_r0 = vec3d(1,1,0);
mesh.Node( 3).m_r0 = vec3d(0,1,0);
mesh.Node( 4).m_r0 = vec3d(0,0,1);
mesh.Node( 5).m_r0 = vec3d(1,0,1);
mesh.Node( 6).m_r0 = vec3d(1,1,1);
mesh.Node( 7).m_r0 = vec3d(0,1,1);
mesh.Node( 8).m_r0 = vec3d(0,0,1-eps);
mesh.Node( 9).m_r0 = vec3d(1,0,1-eps);
mesh.Node(10).m_r0 = vec3d(1,1,1-eps);
mesh.Node(11).m_r0 = vec3d(0,1,1-eps);
mesh.Node(12).m_r0 = vec3d(0,0,2-eps);
mesh.Node(13).m_r0 = vec3d(1,0,2-eps);
mesh.Node(14).m_r0 = vec3d(1,1,2-eps);
mesh.Node(15).m_r0 = vec3d(0,1,2-eps);
for (int i=0; i<16; ++i)
{
FENode& node = mesh.Node(i);
node.m_rt = node.m_r0;
}
// --- create a material ---
FENeoHookean* pm = new FENeoHookean(&fem);
pm->m_E = 1.0;
pm->m_v = 0.45;
fem.AddMaterial(pm);
// get the one-and-only domain
FEElasticSolidDomain* pbd = new FEElasticSolidDomain(&fem);
pbd->SetMaterial(pm);
pbd->Create(2, FEElementLibrary::GetElementSpecFromType(FE_HEX8G8));
pbd->SetMatID(0);
mesh.AddDomain(pbd);
FESolidElement& el0 = pbd->Element(0);
FESolidElement& el1 = pbd->Element(1);
el0.SetID(1);
el0.m_node[0] = 0;
el0.m_node[1] = 1;
el0.m_node[2] = 2;
el0.m_node[3] = 3;
el0.m_node[4] = 4;
el0.m_node[5] = 5;
el0.m_node[6] = 6;
el0.m_node[7] = 7;
el1.SetID(2);
el1.m_node[0] = 8;
el1.m_node[1] = 9;
el1.m_node[2] = 10;
el1.m_node[3] = 11;
el1.m_node[4] = 12;
el1.m_node[5] = 13;
el1.m_node[6] = 14;
el1.m_node[7] = 15;
// --- create the sliding interface ---
FESlidingInterface* ps = new FESlidingInterface(&fem);
ps->m_atol = 0.1;
ps->m_eps = 1;
ps->m_btwo_pass = false;
ps->m_nsegup = 0;
FESlidingSurface& ms = ps->m_ms;
ms.Create(1, FE_QUAD4NI);
ms.Element(0).m_node[0] = 4;
ms.Element(0).m_node[1] = 5;
ms.Element(0).m_node[2] = 6;
ms.Element(0).m_node[3] = 7;
FESlidingSurface& ss = ps->m_ss;
ss.Create(1, FE_QUAD4NI);
ss.Element(0).m_node[0] = 11;
ss.Element(0).m_node[1] = 10;
ss.Element(0).m_node[2] = 9;
ss.Element(0).m_node[3] = 8;
fem.AddSurfacePairConstraint(ps);
// --- set fem data ---
// Make sure we are using the LU solver
FECoreKernel::GetInstance().SetDefaultSolverType("LU");
return FEDiagnostic::Init();
}
//-----------------------------------------------------------------------------
void FEContactDiagnostic::deriv_residual(DenseMatrix& K)
{
// get the solver
FEModel& fem = *GetFEModel();
FEAnalysis* pstep = fem.GetCurrentStep();
FESolidSolver2& solver = static_cast<FESolidSolver2&>(*pstep->GetFESolver());
// get the mesh
FEMesh& mesh = fem.GetMesh();
fem.Update();
// first calculate the initial residual
vector<double> R0; R0.assign(48, 0);
vector<double> dummy(R0);
FEResidualVector RHS0(fem, R0, dummy);
solver.ContactForces(RHS0);
// solver.Residual(RHS);
// now calculate the perturbed residuals
K.Create(48, 48);
int i, j, nj;
int N = mesh.Nodes();
double dx = 1e-8;
vector<double> R1(48);
for (j=0; j<3*N; ++j)
{
FENode& node = mesh.Node(j/3);
nj = j%3;
switch (nj)
{
case 0: node.m_rt.x += dx; break;
case 1: node.m_rt.y += dx; break;
case 2: node.m_rt.z += dx; break;
}
fem.Update();
zero(R1);
FEResidualVector RHS1(fem, R1, dummy);
solver.ContactForces(RHS1);
// solver.Residual(R1);
switch (nj)
{
case 0: node.m_rt.x -= dx; break;
case 1: node.m_rt.y -= dx; break;
case 2: node.m_rt.z -= dx; break;
}
fem.Update();
for (i=0; i<3*N; ++i) K(i,j) = (1-(R1[i] - R0[i])/dx)-1;
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioTest/FEEASShellTangentDiagnostic.cpp | .cpp | 9,342 | 305 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEEASShellTangentDiagnostic.h"
#include "FEBioMech/FESolidSolver2.h"
#include "FEBioMech/FEElasticEASShellDomain.h"
#include "FECore/log.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FEEASShellTangentUnloaded, FEDiagnosticScenario)
ADD_PARAMETER(m_strain, "strain");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
bool FEEASShellTangentUnloaded::Init()
{
FEModel& fem = *GetDiagnostic()->GetFEModel();
const int NELN = 4;
int i;
vec3d r[NELN] = {
vec3d(0,0,0), vec3d(1,0,0), vec3d(1,1,0), vec3d(0,1,0)
};
vec3d D[NELN] = {
vec3d(0,0,0.01), vec3d(0,0,0.01), vec3d(0,0,0.01), vec3d(0,0,0.01)
};
// get the degrees of freedom
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
// --- create the FE problem ---
// create the mesh
FEMesh& m = fem.GetMesh();
m.CreateNodes(NELN);
m.SetDOFS(MAX_DOFS);
for (i=0; i<NELN; ++i)
{
FENode& n = m.Node(i);
n.m_rt = n.m_r0 = r[i];
n.m_dt = n.m_d0 = D[i];
}
// get the material
FEMaterial* pmat = fem.GetMaterial(0);
// create a solid domain
FEElasticEASShellDomain* pd = new FEElasticEASShellDomain(&fem);
pd->SetMaterial(pmat);
pd->Create(1, FEElementLibrary::GetElementSpecFromType(FE_SHELL_QUAD4G8));
pd->SetMatID(0);
m.AddDomain(pd);
FEShellElement& el = pd->Element(0);
el.SetID(1);
for (i=0; i<NELN; ++i) {
el.m_node[i] = i;
el.m_h0[i] = D[i].norm();
}
pd->CreateMaterialPointData();
return true;
}
//-----------------------------------------------------------------------------
// Constructor
FEEASShellTangentDiagnostic::FEEASShellTangentDiagnostic(FEModel* fem) : FEDiagnostic(fem)
{
// make sure the correct module is active
fem->SetActiveModule("solid");
m_pscn = 0;
// create an analysis step
FEAnalysis* pstep = new FEAnalysis(fem);
// create a new solver
FESolver* pnew_solver = fecore_new<FESolver>("solid", fem);
assert(pnew_solver);
pstep->SetFESolver(pnew_solver);
// keep a pointer to the fem object
fem->AddStep(pstep);
fem->SetCurrentStep(pstep);
}
//-----------------------------------------------------------------------------
FEDiagnosticScenario* FEEASShellTangentDiagnostic::CreateScenario(const std::string& sname)
{
if (sname == "unloaded" ) return (m_pscn = new FEEASShellTangentUnloaded (this));
return 0;
}
//-----------------------------------------------------------------------------
// Helper function to print a matrix
void FEEASShellTangentDiagnostic::print_matrix(matrix& m)
{
int i, j;
int N = m.rows();
int M = m.columns();
feLog("\n ");
for (i=0; i<N; ++i) feLog("%15d ", i);
feLog("\n----");
for (i=0; i<N; ++i) feLog("----------------", i);
for (i=0; i<N; ++i)
{
feLog("\n%2d: ", i);
for (j=0; j<M; ++j)
{
feLog("%15lg ", m[i][j]);
}
}
feLog("\n");
}
//-----------------------------------------------------------------------------
// Initialize the diagnostic. In this function we build the FE model depending
// on the scenario.
bool FEEASShellTangentDiagnostic::Init()
{
// make sure we have a scenario
if (m_pscn == 0) return false;
// initialize the scenario
if (m_pscn->Init() == false) return false;
return FEDiagnostic::Init();
}
//-----------------------------------------------------------------------------
// Run the tangent diagnostic. After we run the FE model, we calculate
// the element stiffness matrix and compare that to a finite difference
// of the element residual.
bool FEEASShellTangentDiagnostic::Run()
{
// solve the problem
FEModel& fem = *GetFEModel();
fem.BlockLog();
bool bret = fem.Solve();
fem.UnBlockLog();
if (bret == false) return false;
FEMesh& mesh = fem.GetMesh();
FEElasticEASShellDomain& bd = static_cast<FEElasticEASShellDomain&>(mesh.Domain(0));
// set up the element stiffness matrix
const int NELN = 4;
const int NDPN = 6;
const int NDOF = NELN*NDPN;
matrix k0(NDOF, NDOF);
k0.zero();
bd.ElementStiffness(0, k0);
// print the element stiffness matrix
feLog("\nActual stiffness matrix:\n");
print_matrix(k0);
// now calculate the derivative of the residual
matrix k1;
deriv_residual(k1);
// print the approximate element stiffness matrix
feLog("\nApproximate stiffness matrix:\n");
print_matrix(k1);
// finally calculate the difference matrix
feLog("\n");
matrix kd(NDOF, NDOF);
double kmax = 0, kij;
int i0 = -1, j0 = -1, i, j;
for (i=0; i<NDOF; ++i)
for (j=0; j<NDOF; ++j)
{
kd[i][j] = k0[i][j] - k1[i][j];
kij = 100.0*fabs(kd[i][j] / k0[0][0]);
if (kij > kmax)
{
kmax = kij;
i0 = i;
j0 = j;
}
}
// print the difference
feLog("\ndifference matrix:\n");
print_matrix(kd);
feLog("\nMaximum difference: %lg%% (at (%d,%d))\n", kmax, i0, j0);
return (kmax < 1e-4);
}
//-----------------------------------------------------------------------------
// Calculate a finite difference approximation of the derivative of the
// element residual.
void FEEASShellTangentDiagnostic::deriv_residual(matrix& ke)
{
// get the solver
FEModel& fem = *GetFEModel();
FEAnalysis* pstep = fem.GetCurrentStep();
FESolidSolver2& solver = static_cast<FESolidSolver2&>(*pstep->GetFESolver());
// get the degrees of freedom
const int dof_X = fem.GetDOFIndex("x");
const int dof_Y = fem.GetDOFIndex("y");
const int dof_Z = fem.GetDOFIndex("z");
const int dof_SX = fem.GetDOFIndex("sx");
const int dof_SY = fem.GetDOFIndex("sy");
const int dof_SZ = fem.GetDOFIndex("sz");
// get the mesh
FEMesh& mesh = fem.GetMesh();
FEElasticEASShellDomain& bd = static_cast<FEElasticEASShellDomain&>(mesh.Domain(0));
// get the one and only element
FEShellElementNew& el = bd.ShellElement(0);
// first calculate the initial residual
const int NELN = 4;
const int NDPN = 6;
const int NDOF = NELN*NDPN;
vector<double> f0(NDOF);
zero(f0);
bd.ElementInternalForce(el, f0);
// now calculate the perturbed residuals
ke.resize(NDOF, NDOF);
ke.zero();
int i, j, nj;
int N = mesh.Nodes();
double dx = 1e-8;
vector<double> f1(NDOF);
vector<double> ui(NDOF,0);
for (j=0; j<NDPN*N; ++j)
{
FENode& node = mesh.Node(el.m_node[j/NDPN]);
nj = j%NDPN;
switch (nj)
{
case 0: node.add(dof_X, dx); node.m_rt.x += dx; break;
case 1: node.add(dof_Y, dx); node.m_rt.y += dx; break;
case 2: node.add(dof_Z, dx); node.m_rt.z += dx; break;
case 3: node.add(dof_SX, dx); break;
case 4: node.add(dof_SY, dx); break;
case 5: node.add(dof_SZ, dx); break;
}
ui[j] += dx;
solver.Update(ui);
zero(f1);
bd.ElementInternalForce(el, f1);
switch (nj)
{
case 0: node.sub(dof_X, dx); node.m_rt.x -= dx; break;
case 1: node.sub(dof_Y, dx); node.m_rt.y -= dx; break;
case 2: node.sub(dof_Z, dx); node.m_rt.z -= dx; break;
case 3: node.sub(dof_SX, dx); break;
case 4: node.sub(dof_SY, dx); break;
case 5: node.sub(dof_SZ, dx); break;
}
ui[j] -= dx;
solver.Update(ui);
for (i=0; i<NDPN*N; ++i) ke[i][j] = -(f1[i] - f0[i])/dx;
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioTest/FEMemoryDiagnostic.cpp | .cpp | 2,444 | 91 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEMemoryDiagnostic.h"
#include "FECore/log.h"
FEMemoryDiagnostic::FEMemoryDiagnostic(FEModel* fem) : FEDiagnostic(fem)
{
m_szfile[0] = 0;
m_iters = 1;
FEAnalysis* pstep = new FEAnalysis(fem);
fem->AddStep(pstep);
fem->SetCurrentStep(pstep);
}
FEMemoryDiagnostic::~FEMemoryDiagnostic(void)
{
}
bool FEMemoryDiagnostic::Init()
{
FEModel& fem = *GetFEModel();
// try to open the file
FEBioImport im;
if (im.Load(fem, m_szfile) == false)
{
return false;
}
// make sure the iters is a positive number
if (m_iters <= 0) return false;
// turn off all output
fem.GetCurrentStep()->SetPlotLevel(FE_PLOT_NEVER);
return true;
}
bool FEMemoryDiagnostic::Run()
{
// run the problem
FEModel& fem = *GetFEModel();
for (int i=0; i<m_iters; ++i)
{
fprintf(stderr, "%d/%d: ...", i+1, m_iters);
fem.Reset();
bool b = fem.Solve();
// system("ps -C febio.test -o rss,vsize h");
fprintf(stderr, "%s\n", (b?"NT" : "ET"));
}
return true;
}
bool FEMemoryDiagnostic::ParseSection(XMLTag &tag)
{
if (tag == "file") tag.value(m_szfile);
else if (tag == "iters") tag.value(m_iters);
else return false;
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEBioTest/FEMaterialTest.cpp | .cpp | 5,134 | 182 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEMaterialTest.h"
#include "FETangentDiagnostic.h"
#include <FECore/log.h>
#include <FECore/DataRecord.h>
#include <FECore/FECoreKernel.h>
#include <FECore/FEDomain.h>
FEMaterialTest::FEMaterialTest(FEModel* fem) : FEDiagnostic(fem)
{
m_szoutfile = "stress.txt";
// make sure the correct module is active
fem->SetActiveModule("solid");
m_xout = "Ex";
m_yout = "sx";
m_pscn = nullptr;
m_strain = nullptr;
m_stress = nullptr;
// create an analysis step
FEAnalysis* pstep = new FEAnalysis(fem);
// create a new solver
FESolver* pnew_solver = fecore_new<FESolver>("solid", fem);
assert(pnew_solver);
pstep->SetFESolver(pnew_solver);
// keep a pointer to the fem object
fem->AddStep(pstep);
fem->SetCurrentStep(pstep);
}
//-----------------------------------------------------------------------------
FEMaterialTest::~FEMaterialTest()
{
delete m_strain;
delete m_stress;
}
//-----------------------------------------------------------------------------
void FEMaterialTest::SetOutputFileName(const char* szfilename)
{
m_szoutfile = szfilename;
}
void FEMaterialTest::SetOutputVariables(const std::string& xout, const std::string& yout)
{
m_xout = xout;
m_yout = yout;
}
//-----------------------------------------------------------------------------
FEDiagnosticScenario* FEMaterialTest::CreateScenario(const std::string& sname)
{
if (sname == "uni-axial")
{
m_pscn = new FETangentUniaxial(this);
SetOutputVariables("Ex", "sx");
}
else if (sname == "biaxial")
{
m_pscn = new FETangentBiaxial(this);
SetOutputVariables("Ex", "sx");
}
else if (sname == "triaxial")
{
m_pscn = new FETangentTriaxial(this);
SetOutputVariables("Ex", "sx");
}
else if (sname == "simple shear")
{
m_pscn = new FETangentSimpleShear(this);
SetOutputVariables("Exz", "sx");
}
return m_pscn;
}
//-----------------------------------------------------------------------------
// Initialize the diagnostic. In this function we build the FE model depending
// on the scenario.
bool FEMaterialTest::Init()
{
// make sure we have a scenario
if (m_pscn == 0) return false;
// initialize the scenario
if (m_pscn->Init() == false) return false;
FEModel* fem = GetFEModel();
fem->AddCallback(cb, CB_INIT | CB_MAJOR_ITERS, this);
m_strain = fecore_new<FELogElemData>(m_xout.c_str(), fem); assert(m_strain);
m_stress = fecore_new<FELogElemData>(m_yout.c_str(), fem); assert(m_stress);
// add the stress output
if (m_szoutfile)
{
DataRecord* pdr = fecore_new<DataRecord>("element_data", fem);
FEDomain& dom = fem->GetMesh().Domain(0);
FEElementSet* es = new FEElementSet(fem);
es->Create(&dom);
std::vector<int> dummy;
pdr->SetItemList(es, dummy);
pdr->SetData("Exy;sx");
pdr->SetComments(false);
pdr->SetFileName(m_szoutfile);
DataStore& ds = fem->GetDataStore();
ds.AddRecord(pdr);
}
return FEDiagnostic::Init();
}
//-----------------------------------------------------------------------------
bool FEMaterialTest::cb()
{
FEModel* fem = GetFEModel();
FEDomain& dom= fem->GetMesh().Domain(0);
FEElement& el = dom.ElementRef(0);
double E = (m_strain ? m_strain->value(el) : 0);
double s = (m_stress ? m_stress->value(el) : 0);
m_data.push_back(pair<double, double>(E, s));
return true;
}
//-----------------------------------------------------------------------------
// Run the tangent diagnostic. After we run the FE model, we calculate
// the element stiffness matrix and compare that to a finite difference
// of the element residual.
bool FEMaterialTest::Run()
{
// solve the problem
FEModel& fem = *GetFEModel();
fem.BlockLog();
bool bret = fem.Solve();
fem.UnBlockLog();
if (bret == false)
{
feLogError("FEBio error terminated. Aborting diagnostic.\n");
return false;
}
else
{
feLog("Material test completed.");
}
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEBioTest/stdafx.h | .h | 1,276 | 28 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FEPolarFluidTangentDiagnostic.cpp | .cpp | 12,417 | 393 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEPolarFluidTangentDiagnostic.h"
#include "FETangentDiagnostic.h"
#include <FEBioFluid/FEPolarFluidSolver.h>
#include <FEBioFluid/FEPolarFluidDomain3D.h>
#include <FEBioFluid/FEPolarFluidAnalysis.h>
#include <FECore/log.h>
#include <FECore/FEPrescribedDOF.h>
#include <FECore/FEFixedBC.h>
#include <FECore/FELoadCurve.h>
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FEPolarFluidTangentUniaxial, FEPolarFluidScenario)
ADD_PARAMETER(m_velocity, "fluid_velocity");
ADD_PARAMETER(m_angular_velocity, "fluid_angular_velocity");
ADD_PARAMETER(m_dt , "time_step" );
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
FEPolarFluidTangentUniaxial::FEPolarFluidTangentUniaxial(FEDiagnostic* pdia) : FEPolarFluidScenario(pdia)
{
m_velocity = 0;
m_angular_velocity = 0;
m_dt = 0;
}
//-----------------------------------------------------------------------------
// Build the uniaxial loading scenario
// Cube with uniaxial velocity prescribed along x on left face and dilatation
// fixed on right face. Dynamic analysis.
bool FEPolarFluidTangentUniaxial::Init()
{
int i;
vec3d r[8] = {
vec3d(0,0,0), vec3d(1,0,0), vec3d(1,1,0), vec3d(0,1,0),
vec3d(0,0,1), vec3d(1,0,1), vec3d(1,1,1), vec3d(0,1,1)
};
int BC[8][7] = {
{ 0, 0, 0, 0, 0, 0,-1},
{-1,-1,-1, 0, 0, 0, 0},
{-1,-1,-1, 0, 0, 1,-1},
{ 1, 0, 0, 0, 0, 1,-1},
{ 0, 0, 0,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1, 0},
{-1,-1,-1,-1,-1,-1, 0},
{ 1, 0, 0,-1,-1,-1,-1}
};
FEModel& fem = *GetDiagnostic()->GetFEModel();
FEAnalysis* pstep = fem.GetCurrentStep();
// pstep->m_nanalysis = FEPolarFluidAnalysis::DYNAMIC;
pstep->m_nanalysis = FEPolarFluidAnalysis::STEADY_STATE;
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
const int dof_WX = fem.GetDOFIndex("wx");
const int dof_WY = fem.GetDOFIndex("wy");
const int dof_WZ = fem.GetDOFIndex("wz");
const int dof_GX = fem.GetDOFIndex("gx");
const int dof_GY = fem.GetDOFIndex("gy");
const int dof_GZ = fem.GetDOFIndex("gz");
const int dof_EF = fem.GetDOFIndex("ef");
// --- create the FE problem ---
// create the mesh
FEMesh& m = fem.GetMesh();
m.CreateNodes(8);
m.SetDOFS(MAX_DOFS);
FENodeSet* nfset[7] = { 0 };
for (int i=0; i<7; ++i) nfset[i] = new FENodeSet(&fem);
for (i=0; i<8; ++i)
{
FENode& n = m.Node(i);
n.m_rt = n.m_r0 = r[i];
// set displacement BC's
for (int j=0; j<7; ++j)
if (BC[i][j] == 0) nfset[j]->Add(i);
}
fem.AddBoundaryCondition(new FEFixedBC(&fem, dof_WX, nfset[0]));
fem.AddBoundaryCondition(new FEFixedBC(&fem, dof_WY, nfset[1]));
fem.AddBoundaryCondition(new FEFixedBC(&fem, dof_WZ, nfset[2]));
fem.AddBoundaryCondition(new FEFixedBC(&fem, dof_GX, nfset[3]));
fem.AddBoundaryCondition(new FEFixedBC(&fem, dof_GY, nfset[4]));
fem.AddBoundaryCondition(new FEFixedBC(&fem, dof_GZ, nfset[5]));
fem.AddBoundaryCondition(new FEFixedBC(&fem, dof_EF, nfset[6]));
// get the material
FEMaterial* pmat = fem.GetMaterial(0);
// create a fluid domain
FEPolarFluidDomain3D* pd = new FEPolarFluidDomain3D(&fem);
pd->SetMaterial(pmat);
pd->Create(1, FEElementLibrary::GetElementSpecFromType(FE_HEX8G8));
pd->SetMatID(0);
m.AddDomain(pd);
FESolidElement& el = pd->Element(0);
el.SetID(1);
for (i=0; i<8; ++i) el.m_node[i] = i;
pd->CreateMaterialPointData();
// Add a loadcurve
FELoadCurve* plc = new FELoadCurve(&fem);
plc->Add(0.0, 0.0);
plc->Add(1.0, 1.0);
fem.AddLoadController(plc);
// Add a prescribed velocity BC
FENodeSet* dcv = new FENodeSet(&fem);
dcv->Add({ 3, 7 });
FEPrescribedDOF* pdcv = new FEPrescribedDOF(&fem, dof_WX, dcv);
pdcv->SetScale(m_velocity, 0);
fem.AddBoundaryCondition(pdcv);
// Add a prescribed angular velocity BC
FENodeSet* dcg = new FENodeSet(&fem);
dcg->Add({ 2, 3 });
FEPrescribedDOF* pdcg = new FEPrescribedDOF(&fem, dof_GZ, dcg);
pdcg->SetScale(m_angular_velocity, 0);
fem.AddBoundaryCondition(pdcg);
m_time_increment = m_dt;
return true;
}
//-----------------------------------------------------------------------------
// Constructor
FEPolarFluidTangentDiagnostic::FEPolarFluidTangentDiagnostic(FEModel* fem) : FEDiagnostic(fem)
{
m_pscn = 0;
// make sure the correct module is active
fem->SetActiveModule("polar fluid");
FEAnalysis* pstep = new FEAnalysis(fem);
// create a new solver
FESolver* pnew_solver = fecore_new<FESolver>("polar fluid", fem);
assert(pnew_solver);
pnew_solver->m_msymm = REAL_UNSYMMETRIC;
pstep->SetFESolver(pnew_solver);
fem->AddStep(pstep);
fem->SetCurrentStep(pstep);
}
//-----------------------------------------------------------------------------
FEDiagnosticScenario* FEPolarFluidTangentDiagnostic::CreateScenario(const std::string& sname)
{
if (sname == "polar fluid uni-axial") return (m_pscn = new FEPolarFluidTangentUniaxial(this));
return 0;
}
//-----------------------------------------------------------------------------
// Initialize the diagnostic. In this function we build the FE model depending
// on the scenario.
bool FEPolarFluidTangentDiagnostic::Init()
{
if (m_pscn == 0) return false;
if (m_pscn->Init() == false) return false;
return FEDiagnostic::Init();
}
//-----------------------------------------------------------------------------
// Helper function to print a matrix
void FEPolarFluidTangentDiagnostic::print_matrix(matrix& m)
{
int i, j;
int N = m.rows();
int M = m.columns();
feLog("\n ");
for (i=0; i<N; ++i) feLog("%15d ", i);
feLog("\n----");
for (i=0; i<N; ++i) feLog("----------------", i);
for (i=0; i<N; ++i)
{
feLog("\n%2d: ", i);
for (j=0; j<M; ++j)
{
feLog("%15lg ", m[i][j]);
}
}
feLog("\n");
}
//-----------------------------------------------------------------------------
// Run the tangent diagnostic. After we run the FE model, we calculate
// the element stiffness matrix and compare that to a finite difference
// of the element residual.
bool FEPolarFluidTangentDiagnostic::Run()
{
// solve the problem
FEModel& fem = *GetFEModel();
FEAnalysis* pstep = fem.GetCurrentStep();
double dt = m_pscn->m_time_increment;
fem.GetTime().timeIncrement = pstep->m_dt0 = dt;
pstep->m_tstart = 0;
pstep->m_tend = dt;
pstep->m_final_time = dt;
pstep->Activate();
fem.BlockLog();
fem.Solve();
fem.UnBlockLog();
FETimeInfo tp;
tp.timeIncrement = dt;
tp.alpha = 0.5;
tp.beta = 0.25;
tp.gamma = 0.5;
tp.alphaf = 0.5;
tp.alpham = 0.5;
FEMesh& mesh = fem.GetMesh();
FEPolarFluidDomain3D& bd = dynamic_cast<FEPolarFluidDomain3D&>(mesh.Domain(0));
// get the one and only element
FESolidElement& el = bd.Element(0);
int N = mesh.Nodes();
// set up the element stiffness matrix
const int ndpn = 7;
matrix k0(ndpn*N, ndpn*N);
k0.zero();
bd.ElementStiffness(el, k0);
bd.ElementMassMatrix(el,k0);
// print the element stiffness matrix
feLog("\nActual stiffness matrix:\n");
print_matrix(k0);
// now calculate the derivative of the residual
matrix k1(ndpn*N, ndpn*N);
deriv_residual(k1);
// print the approximate element stiffness matrix
feLog("\nApproximate stiffness matrix:\n");
print_matrix(k1);
// finally calculate the difference matrix
feLog("\n");
matrix kd(ndpn*N, ndpn*N);
double kmax = 0, kij;
int i0 = -1, j0 = -1, i, j;
for (i=0; i<ndpn*N; ++i)
for (j=0; j<ndpn*N; ++j)
{
kd[i][j] = k0[i][j] - k1[i][j];
kij = 100.0*fabs(kd[i][j] / k0[0][0]);
if (kij > kmax)
{
kmax = kij;
i0 = i;
j0 = j;
}
}
// print the difference
feLog("\ndifference matrix:\n");
print_matrix(kd);
feLog("\nMaximum difference: %lg%% (at (%d,%d))\n", kmax, i0, j0);
return (kmax < 1e-4);
}
//-----------------------------------------------------------------------------
// Calculate a finite difference approximation of the derivative of the
// element residual.
void FEPolarFluidTangentDiagnostic::deriv_residual(matrix& ke)
{
int i, j, nj;
// get the solver
FEModel& fem = *GetFEModel();
FEAnalysis* pstep = fem.GetCurrentStep();
double dt = m_pscn->m_time_increment;
fem.GetTime().timeIncrement = pstep->m_dt0 = dt;
pstep->m_tstart = 0;
pstep->m_tend = dt;
pstep->m_final_time = dt;
FEPolarFluidSolver& solver = static_cast<FEPolarFluidSolver&>(*pstep->GetFESolver());
FETimeInfo tp;
tp.timeIncrement = dt;
tp.alpha = 1;
tp.beta = 0.25;
tp.gamma = 0.5;
tp.alphaf = 1;
tp.alpham = 1;
// get the dof indices
const int dof_WX = fem.GetDOFIndex("wx");
const int dof_WY = fem.GetDOFIndex("wy");
const int dof_WZ = fem.GetDOFIndex("wz");
const int dof_GX = fem.GetDOFIndex("gx");
const int dof_GY = fem.GetDOFIndex("gy");
const int dof_GZ = fem.GetDOFIndex("gz");
const int dof_EF = fem.GetDOFIndex("ef");
// get the mesh
FEMesh& mesh = fem.GetMesh();
FEPolarFluidDomain3D& bd = dynamic_cast<FEPolarFluidDomain3D&>(mesh.Domain(0));
// get the one and only element
FESolidElement& el = bd.Element(0);
int N = mesh.Nodes();
// first calculate the initial residual
const int ndpn = 7;
vector<double> f0(ndpn*N);
zero(f0);
bd.ElementInternalForce(el, f0);
bd.ElementInertialForce(el, f0);
// now calculate the perturbed residuals
ke.zero();
double dx = 1e-8;
vector<double> f1(ndpn*N);
for (j=0; j<ndpn*N; ++j)
{
FENode& node = mesh.Node(el.m_node[j/ndpn]);
nj = j%ndpn;
switch (nj)
{
case 0: node.add(dof_WX, dx); break;
case 1: node.add(dof_WY, dx); break;
case 2: node.add(dof_WZ, dx); break;
case 3: node.add(dof_GX, dx); break;
case 4: node.add(dof_GY, dx); break;
case 5: node.add(dof_GZ, dx); break;
case 6: node.add(dof_EF, dx); break;
}
fem.Update();
zero(f1);
bd.ElementInternalForce(el, f1);
bd.ElementInertialForce(el, f1);
switch (nj)
{
case 0: node.sub(dof_WX, dx); break;
case 1: node.sub(dof_WY, dx); break;
case 2: node.sub(dof_WZ, dx); break;
case 3: node.sub(dof_GX, dx); break;
case 4: node.sub(dof_GY, dx); break;
case 5: node.sub(dof_GZ, dx); break;
case 6: node.sub(dof_EF, dx); break;
}
fem.Update();
for (i=0; i<ndpn*N; ++i) ke[i][j] = -(f1[i] - f0[i])/dx;
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioTest/FEBioDiagnostic.h | .h | 1,599 | 47 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEDiagnostic.h"
#include <FECore/FECoreTask.h>
class FEBioDiagnostic : public FECoreTask
{
public:
FEBioDiagnostic(FEModel* pfem) : FECoreTask(pfem){ m_pdia = 0; }
//! initialization
bool Init(const char* szfile);
//! Run the FE model
virtual bool Run();
private:
FEDiagnostic* m_pdia;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FEEASShellTangentDiagnostic.h | .h | 2,325 | 69 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEDiagnostic.h"
//-----------------------------------------------------------------------------
class FEEASShellTangentUnloaded : public FEDiagnosticScenario
{
public:
FEEASShellTangentUnloaded(FEDiagnostic* pdia) : FEDiagnosticScenario(pdia) { m_strain = 0.0; }
bool Init() override;
private:
double m_strain;
DECLARE_FECORE_CLASS();
};
//-----------------------------------------------------------------------------
//! The FETangentDiagnostic class tests the stiffness matrix implementation
//! by comparing it to a numerical approximating of the derivative of the
//! residual.
class FEEASShellTangentDiagnostic : public FEDiagnostic
{
public:
FEEASShellTangentDiagnostic(FEModel* fem);
virtual ~FEEASShellTangentDiagnostic(){}
FEDiagnosticScenario* CreateScenario(const std::string& sname);
bool Init();
bool Run();
protected:
void deriv_residual(matrix& ke);
void print_matrix(matrix& m);
public:
FEDiagnosticScenario* m_pscn;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FEMultiphasicTangentDiagnostic.h | .h | 2,561 | 82 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEDiagnostic.h"
//-----------------------------------------------------------------------------
class FEMultiphasicScenario : public FEDiagnosticScenario
{
public:
FEMultiphasicScenario(FEDiagnostic* pdia) : FEDiagnosticScenario(pdia) { m_dt = 1.0; }
public:
double m_dt;
};
//-----------------------------------------------------------------------------
class FEMultiphasicTangentUniaxial : public FEMultiphasicScenario
{
public:
FEMultiphasicTangentUniaxial(FEDiagnostic* pdia);
bool Init() override;
private:
double m_strain;
double m_pressure;
double m_concentration;
DECLARE_FECORE_CLASS();
};
//-----------------------------------------------------------------------------
//! The FEMultiphasicTangentDiagnostic class tests the stiffness matrix implementation
//! by comparing it to a numerical approximating of the derivative of the
//! residual.
class FEMultiphasicTangentDiagnostic : public FEDiagnostic
{
public:
FEMultiphasicTangentDiagnostic(FEModel* fem);
bool Init();
bool Run();
FEDiagnosticScenario* CreateScenario(const std::string& sname);
protected:
void deriv_residual(matrix& ke);
void print_matrix(matrix& m);
public:
FEMultiphasicScenario* m_pscn;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FEStiffnessDiagnostic.h | .h | 1,704 | 50 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FECoreTask.h>
#include <string>
//-----------------------------------------------------------------------------
class FEStiffnessDiagnostic : public FECoreTask
{
public:
FEStiffnessDiagnostic(FEModel* fem);
bool Init(const char* szfile) override;
bool Run() override;
bool Diagnose();
protected:
void deriv_residual(matrix& ke);
private:
FILE* m_fp;
bool m_writeMatrix;
int m_nmax;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FEPrintMatrixDiagnostic.cpp | .cpp | 3,920 | 139 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEPrintMatrixDiagnostic.h"
#include "FEBioMech/FESolidSolver2.h"
#include "FECore/FEGlobalMatrix.h"
#include <stdio.h>
//-----------------------------------------------------------------------------
//! Print a block from a sparse matrix to file
void print(SparseMatrix& m, FILE* fp, int i0, int j0, int i1, int j1)
{
int nr = m.Rows();
int nc = m.Columns();
if ((i1 < 0) || (i1 >= nr)) i1 = nr-1;
if ((j1 < 0) || (j1 >= nc)) j1 = nc-1;
for (int i=i0; i<=i1; ++i)
{
for (int j=j0; j<=j1; ++j)
{
fprintf(fp, "%10.3g", m.get(i,j));
}
fprintf(fp, "\n");
}
}
//-----------------------------------------------------------------------------
FEPrintMatrixDiagnostic::FEPrintMatrixDiagnostic(FEModel* fem) : FEDiagnostic(fem)
{
m_szout[0] = 0;
m_rng[0] = m_rng[1] = 0;
m_rng[2] = m_rng[3] = -1;
FEAnalysis* pstep = new FEAnalysis(fem);
fem->AddStep(pstep);
fem->SetCurrentStep(pstep);
}
//-----------------------------------------------------------------------------
FEPrintMatrixDiagnostic::~FEPrintMatrixDiagnostic(void)
{
}
//-----------------------------------------------------------------------------
bool FEPrintMatrixDiagnostic::ParseSection(XMLTag &tag)
{
if (tag == "input")
{
// get the input file name
const char* szfile = tag.szvalue();
// try to read the file
FEBioImport im;
FEModel& fem = *GetFEModel();
if (im.Load(fem, szfile) == false)
{
char szerr[256];
im.GetErrorMessage(szerr);
fprintf(stderr, "%s", szerr);
return false;
}
return true;
}
else if (tag == "output")
{
strcpy(m_szout, tag.szvalue());
return true;
}
else if (tag == "range")
{
tag.value(m_rng, 4);
return true;
}
return false;
}
//-----------------------------------------------------------------------------
bool FEPrintMatrixDiagnostic::Run()
{
// get and initialize the first step
FEModel& fem = *GetFEModel();
FEAnalysis* pstep = fem.GetStep(0);
pstep->Init();
pstep->Activate();
// get and initialize the solver
FESolidSolver2& solver = static_cast<FESolidSolver2&>(*pstep->GetFESolver());
solver.Init();
// build the stiffness matrix
// recalculate the shape of the stiffness matrix if necessary
fem.Update();
// reshape the stiffness matrix
if (!solver.CreateStiffness(true)) return false;
// calculate the stiffness matrices
solver.StiffnessMatrix();
// print the matrix
FILE* fp = fopen(m_szout, "wt");
if (fp == 0) { fprintf(stderr, "Failed creating output file."); return false; }
int* n = m_rng;
print(*solver.GetStiffnessMatrix()->GetSparseMatrixPtr(), fp, n[0], n[1], n[2], n[3]);
fclose(fp);
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEBioTest/FEBioDiagnostic.cpp | .cpp | 2,528 | 89 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEBioDiagnostic.h"
#include <FECore/log.h>
//-----------------------------------------------------------------------------
bool FEBioDiagnostic::Init(const char *szfile)
{
FEModel& fem = *GetFEModel();
// read the diagnostic file
// this will also create a specific diagnostic test
FEDiagnosticImport im;
m_pdia = im.LoadFile(fem, szfile);
if (m_pdia == 0)
{
fprintf(stderr, "Failed reading diagnostic file\n");
return false;
}
// intialize diagnostic
if (m_pdia->Init() == false)
{
fprintf(stderr, "Diagnostic initialization failed\n\n");
return false;
}
// --- initialize FE Model data ---
if (fem.Init() == false)
{
fprintf(stderr, "FE-model data initialized has failed\n\n");
return false;
}
return true;
}
//-----------------------------------------------------------------------------
bool FEBioDiagnostic::Run()
{
if (m_pdia == 0) return false;
// --- run the diagnostic ---
// the return value will designate the pass/fail result
bool bret = false;
try
{
bret = m_pdia->Run();
}
catch (...)
{
feLogError("Exception thrown. Aborting diagnostic.\n");
bret = false;
}
if (bret) feLog("Diagnostic passed\n");
else feLog("Diagnostic failed\n");
return bret;
}
| C++ |
3D | febiosoftware/FEBio | FEBioTest/FEPrintHBMatrixDiagnostic.h | .h | 1,649 | 48 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEDiagnostic.h"
//! Harwell-Boeing Matrix Print Diagnostic
//! Class to run a diagnostic to print the initial matrix in
//! Harwell-Boeing matrix format
class FEPrintHBMatrixDiagnostic : public FEDiagnostic
{
public:
FEPrintHBMatrixDiagnostic(FEModel* fem);
~FEPrintHBMatrixDiagnostic(void);
bool ParseSection(XMLTag& tag);
bool Run();
};
| Unknown |
3D | febiosoftware/FEBio | FEBioTest/FETiedBiphasicDiagnostic.cpp | .cpp | 15,466 | 510 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FETiedBiphasicDiagnostic.h"
#include "FEBioMix/FEBiphasicSolver.h"
#include "FEBioMix/FEBiphasicSolidDomain.h"
#include "FEBioMix/FETiedBiphasicInterface.h"
#include "FEBioMech/FEResidualVector.h"
#include <FECore/log.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
FETiedBiphasicDiagnostic::FETiedBiphasicDiagnostic(FEModel* fem) : FEDiagnostic(fem)
{
// make sure the correct module is active
fem->SetActiveModule("biphasic");
m_pscn = 0;
FEAnalysis* pstep = new FEAnalysis(fem);
// create a new solver
FESolver* pnew_solver = fecore_new<FESolver>("biphasic", fem);
assert(pnew_solver);
pnew_solver->m_msymm = REAL_UNSYMMETRIC;
pstep->SetFESolver(pnew_solver);
fem->AddStep(pstep);
fem->SetCurrentStep(pstep);
}
//-----------------------------------------------------------------------------
FETiedBiphasicDiagnostic::~FETiedBiphasicDiagnostic()
{
}
//-----------------------------------------------------------------------------
// Helper function to print a matrix
void FETiedBiphasicDiagnostic::print_matrix(matrix& m)
{
int i, j;
int N = m.rows();
int M = m.columns();
feLog("\n ");
for (i=0; i<N; ++i) feLog("%15d ", i);
feLog("\n----");
for (i=0; i<N; ++i) feLog("----------------", i);
for (i=0; i<N; ++i)
{
feLog("\n%2d: ", i);
for (j=0; j<M; ++j)
{
feLog("%15lg ", m[i][j]);
}
}
feLog("\n");
}
//-----------------------------------------------------------------------------
// Helper function to print a sparse matrix
void FETiedBiphasicDiagnostic::print_matrix(SparseMatrix& m)
{
int i, j;
int N = m.Rows();
int M = m.Columns();
feLog("\n ");
for (i=0; i<N; ++i) feLog("%15d ", i);
feLog("\n----");
for (i=0; i<N; ++i) feLog("----------------", i);
for (i=0; i<N; ++i)
{
feLog("\n%2d: ", i);
for (j=0; j<M; ++j)
{
feLog("%15lg ", m.get(i,j));
}
}
feLog("\n");
}
//-----------------------------------------------------------------------------
// Initialize the diagnostic. In this function we build the FE model depending
// on the scenario.
bool FETiedBiphasicDiagnostic::Init()
{
if (m_pscn == 0) return false;
if (m_pscn->Init() == false) return false;
return FEDiagnostic::Init();
}
//-----------------------------------------------------------------------------
bool FETiedBiphasicDiagnostic::Run()
{
// get the solver
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
FEAnalysis* pstep = fem.GetCurrentStep();
double dt = m_pscn->m_dt;
fem.GetTime().timeIncrement = pstep->m_dt0 =dt;
pstep->m_tstart = 0;
pstep->m_tend = dt;
pstep->m_final_time = dt;
pstep->Activate();
FEBiphasicSolver& solver = static_cast<FEBiphasicSolver&>(*pstep->GetFESolver());
solver.m_msymm = REAL_UNSYMMETRIC;
solver.Init();
// make sure contact data is up to data
fem.Update();
// create the stiffness matrix
solver.CreateStiffness(true);
// get the stiffness matrix
FEGlobalMatrix& K = *solver.GetStiffnessMatrix();
SparseMatrix& K0 = *K;
// build the stiffness matrix
K.Zero();
print_matrix(K0);
// calculate the derivative of the residual
matrix K1;
deriv_residual(K1);
print_matrix(K1);
// calculate difference matrix
int ndpn = 4;
int N = mesh.Nodes();
const int ndof = N*ndpn;
matrix Kd; Kd.resize(ndof, ndof);
double kij, kmax = 0, k0;
int i0=-1, j0=-1;
for (int i=0; i<ndof; ++i)
for (int j=0; j<ndof; ++j)
{
Kd(i,j) = K1(i,j) - K0.get(i,j);
k0 = fabs(K0.get(i,j));
if (k0 < 1e-15) k0 = 1;
kij = 100.0*fabs(Kd(i,j))/k0;
if (kij > kmax)
{
kmax = kij;
i0 = i;
j0 = j;
}
}
print_matrix(Kd);
feLog("\nMaximum difference: %lg%% (at (%d,%d))\n", kmax, i0, j0);
return (kmax < 1e-3);
}
//-----------------------------------------------------------------------------
void FETiedBiphasicDiagnostic::deriv_residual(matrix& K)
{
// get the solver
FEModel& fem = *GetFEModel();
FEAnalysis* pstep = fem.GetCurrentStep();
double dt = m_pscn->m_dt;
fem.GetTime().timeIncrement = pstep->m_dt0 = dt;
pstep->m_tstart = 0;
pstep->m_tend = dt;
pstep->m_final_time = dt;
FEBiphasicSolver& solver = static_cast<FEBiphasicSolver&>(*pstep->GetFESolver());
// get the DOFs
const int dof_x = fem.GetDOFIndex("x");
const int dof_y = fem.GetDOFIndex("y");
const int dof_z = fem.GetDOFIndex("z");
const int dof_p = fem.GetDOFIndex("p");
// get the mesh
FEMesh& mesh = fem.GetMesh();
int ndpn = 4;
int N = mesh.Nodes();
int ndof = N*ndpn;
solver.UpdateModel();
// first calculate the initial residual
vector<double> R0; R0.assign(ndof, 0);
vector<double> dummy(R0);
FEResidualVector RHS0(fem, R0, dummy);
solver.ContactForces(RHS0);
// now calculate the perturbed residuals
K.resize(ndof,ndof);
int i, j, nj;
double dx = 1e-8;
vector<double> R1(ndof);
for (j=0; j<ndof; ++j)
{
FENode& node = mesh.Node(j/ndpn);
nj = j%ndpn;
switch (nj)
{
case 0: node.add(dof_x, dx); node.m_rt.x += dx; break;
case 1: node.add(dof_y, dx); node.m_rt.y += dx; break;
case 2: node.add(dof_z, dx); node.m_rt.z += dx; break;
case 3: node.add(dof_p, dx); break;
}
solver.UpdateModel();
zero(R1);
FEResidualVector RHS1(fem, R1, dummy);
solver.ContactForces(RHS1);
switch (nj)
{
case 0: node.sub(dof_x, dx); node.m_rt.x -= dx; break;
case 1: node.sub(dof_y, dx); node.m_rt.y -= dx; break;
case 2: node.sub(dof_z, dx); node.m_rt.z -= dx; break;
case 3: node.sub(dof_p, dx); break;
}
solver.UpdateModel();
for (i=0; i<ndof; ++i) K(i,j) = (R0[i] - R1[i])/dx;
}
}
//-----------------------------------------------------------------------------
FEDiagnosticScenario* FETiedBiphasicDiagnostic::CreateScenario(const std::string& sname)
{
if (sname == "hex8") return (m_pscn = new FETiedBiphasicTangentHex8(this));
else if (sname == "hex20") return (m_pscn = new FETiedBiphasicTangentHex20(this));
return 0;
}
//////////////////////////////////////////////////////////////////////
// Biphasic Contact Tangent Diagnostic for hex8 Elements
//////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FETiedBiphasicTangentHex8, FETiedBiphasicScenario)
ADD_PARAMETER(m_dt, "time_step" );
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
FETiedBiphasicTangentHex8::FETiedBiphasicTangentHex8(FEDiagnostic* pdia) : FETiedBiphasicScenario(pdia)
{
m_dt = 1;
}
//-----------------------------------------------------------------------------
bool FETiedBiphasicTangentHex8::Init()
{
vec3d r[16] = {
vec3d(0,0,0), vec3d(1,0,0), vec3d(1,1,0), vec3d(0,1,0),
vec3d(0,0,1), vec3d(1,0,1), vec3d(1,1,1), vec3d(0,1,1),
vec3d(0,0,1), vec3d(1,0,1), vec3d(1,1,1), vec3d(0,1,1),
vec3d(0,0,2), vec3d(1,0,2), vec3d(1,1,2), vec3d(0,1,2)
};
double p[16] = {
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1
};
FEModel& fem = *GetDiagnostic()->GetFEModel();
FEMesh& mesh = fem.GetMesh();
// --- create the geometry ---
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
// get the DOFs
const int dof_p = fem.GetDOFIndex("p");
// currently we simply assume a two-element tied interface problem
// so we create two elements
mesh.CreateNodes(16);
mesh.SetDOFS(MAX_DOFS);
for (int i=0; i<16; ++i) {
mesh.Node(i).m_r0 = r[i];
mesh.Node(i).set(dof_p, p[i]);
}
for (int i=0; i<16; ++i)
{
FENode& node = mesh.Node(i);
node.m_rt = node.m_r0;
}
// get the material
FEMaterial* pm = fem.GetMaterial(0);
// get the one-and-only domain
FEBiphasicSolidDomain* pbd = new FEBiphasicSolidDomain(&fem);
pbd->SetMaterial(pm);
pbd->Create(2, FEElementLibrary::GetElementSpecFromType(FE_HEX8G8));
pbd->SetMatID(0);
mesh.AddDomain(pbd);
FESolidElement& el0 = pbd->Element(0);
FESolidElement& el1 = pbd->Element(1);
el0.SetID(1);
el0.m_node[0] = 0;
el0.m_node[1] = 1;
el0.m_node[2] = 2;
el0.m_node[3] = 3;
el0.m_node[4] = 4;
el0.m_node[5] = 5;
el0.m_node[6] = 6;
el0.m_node[7] = 7;
el1.SetID(2);
el1.m_node[0] = 8;
el1.m_node[1] = 9;
el1.m_node[2] = 10;
el1.m_node[3] = 11;
el1.m_node[4] = 12;
el1.m_node[5] = 13;
el1.m_node[6] = 14;
el1.m_node[7] = 15;
pbd->CreateMaterialPointData();
// --- create the tied interface ---
FETiedBiphasicInterface* ps = new FETiedBiphasicInterface(&fem);
ps->m_atol = 0.1;
ps->m_epsn = 1;
ps->m_epsp = 1;
ps->m_btwo_pass = false;
ps->m_bautopen = true;
ps->m_bsymm = false;
ps->m_stol = 0.01;
FETiedBiphasicSurface& ms = ps->m_ms;
ms.Create(1, FE_QUAD4G4);
ms.Element(0).m_node[0] = 4;
ms.Element(0).m_node[1] = 5;
ms.Element(0).m_node[2] = 6;
ms.Element(0).m_node[3] = 7;
FETiedBiphasicSurface& ss = ps->m_ss;
ss.Create(1, FE_QUAD4G4);
ss.Element(0).m_node[0] = 11;
ss.Element(0).m_node[1] = 10;
ss.Element(0).m_node[2] = 9;
ss.Element(0).m_node[3] = 8;
fem.AddSurfacePairConstraint(ps);
return true;
}
//////////////////////////////////////////////////////////////////////
// Tied Biphasic Interface Tangent Diagnostic for hex20 Elements
//////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FETiedBiphasicTangentHex20, FETiedBiphasicScenario)
ADD_PARAMETER(m_dt, "time_step" );
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
FETiedBiphasicTangentHex20::FETiedBiphasicTangentHex20(FEDiagnostic* pdia) : FETiedBiphasicScenario(pdia)
{
m_dt = 1;
}
//-----------------------------------------------------------------------------
bool FETiedBiphasicTangentHex20::Init()
{
vec3d r[40] = {
vec3d(0,0,0), vec3d(0,0,0.5), vec3d(0,0,1), vec3d(0,0.5,0),
vec3d(0,0.5,1), vec3d(0,1,0), vec3d(0,1,0.5), vec3d(0,1,1),
vec3d(0.5,0,0), vec3d(0.5,0,1), vec3d(0.5,1,0), vec3d(0.5,1,1),
vec3d(1,0,0), vec3d(1,0,0.5), vec3d(1,0,1), vec3d(1,0.5,0),
vec3d(1,0.5,1), vec3d(1,1,0), vec3d(1,1,0.5), vec3d(1,1,1),
vec3d(0,0,1), vec3d(0,0,1.5), vec3d(0,0,2), vec3d(0,0.5,1),
vec3d(0,0.5,2), vec3d(0,1,1), vec3d(0,1,1.5), vec3d(0,1,2),
vec3d(0.5,0,1), vec3d(0.5,0,2), vec3d(0.5,1,1), vec3d(0.5,1,2),
vec3d(1,0,1), vec3d(1,0,1.5), vec3d(1,0,2), vec3d(1,0.5,1),
vec3d(1,0.5,2), vec3d(1,1,1), vec3d(1,1,1.5), vec3d(1,1,2),
};
double p[40] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
int el0n[20] = {
1, 13, 18, 6, 3, 15, 20, 8, 9, 16,
11, 4, 10, 17, 12, 5, 2, 14, 19, 7
};
int el1n[20] = {
21, 33, 38, 26, 23, 35, 40, 28, 29, 36,
31, 24, 30, 37, 32, 25, 22, 34, 39, 27
};
int msn[8] = {
21, 26, 38, 33, 24, 31, 36, 29
};
int ssn[9] = {
3, 15, 20, 8, 10, 17, 12, 5
};
FEModel& fem = *GetDiagnostic()->GetFEModel();
FEMesh& mesh = fem.GetMesh();
// --- create the geometry ---
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
// get the DOFs
const int dof_p = fem.GetDOFIndex("p");
// currently we simply assume a two-element tied interface problem
// so we create two elements
mesh.CreateNodes(40);
mesh.SetDOFS(MAX_DOFS);
for (int i=0; i<40; ++i) {
mesh.Node(i).m_r0 = r[i];
mesh.Node(i).set(dof_p, p[i]);
}
for (int i=0; i<40; ++i)
{
FENode& node = mesh.Node(i);
node.m_rt = node.m_r0;
}
// get the material
FEMaterial* pm = fem.GetMaterial(0);
// get the one-and-only domain
FEBiphasicSolidDomain* pbd = new FEBiphasicSolidDomain(&fem);
pbd->SetMaterial(pm);
pbd->Create(2, FEElementLibrary::GetElementSpecFromType(FE_HEX20G27));
pbd->SetMatID(0);
mesh.AddDomain(pbd);
FESolidElement& el0 = pbd->Element(0);
FESolidElement& el1 = pbd->Element(1);
el0.SetID(1);
for (int i=0; i<20; ++i) {
el0.m_node[i] = el0n[i] - 1;
}
el1.SetID(2);
for (int i=0; i<20; ++i) {
el1.m_node[i] = el1n[i] - 1;
}
pbd->CreateMaterialPointData();
// --- create the tied interface ---
FETiedBiphasicInterface* ps = new FETiedBiphasicInterface(&fem);
ps->m_atol = 0.1;
ps->m_epsn = 1;
ps->m_epsp = 1;
ps->m_btwo_pass = false;
ps->m_bautopen = true;
ps->m_bsymm = false;
FETiedBiphasicSurface& ms = ps->m_ms;
ms.Create(1, FE_QUAD8G9);
for (int i=0; i<8; ++i)
ms.Element(0).m_node[i] = msn[i] - 1;
FETiedBiphasicSurface& ss = ps->m_ss;
ss.Create(1, FE_QUAD8G9);
for (int i=0; i<8; ++i)
ss.Element(0).m_node[i] = ssn[i] - 1;
fem.AddSurfacePairConstraint(ps);
return true;
}
| C++ |
3D | febiosoftware/FEBio | FEBioTest/FETangentDiagnostic.cpp | .cpp | 17,124 | 607 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FETangentDiagnostic.h"
#include "FEBioMech/FESolidSolver2.h"
#include "FEBioMech/FEElasticSolidDomain.h"
#include <FECore/FEPrescribedDOF.h>
#include <FECore/FEFixedBC.h>
#include <FECore/FELoadCurve.h>
#include "FECore/log.h"
#include <FECore/FECoreKernel.h>
// Helper function to print a matrix
void print_matrix(FILE* fp, matrix& m)
{
int N = m.rows();
int M = m.columns();
fprintf(fp, "\n ");
for (int i=0; i<N; ++i) fprintf(fp, "%15d ", i);
fprintf(fp, "\n----");
for (int i=0; i<N; ++i) fprintf(fp, "----------------");
for (int i=0; i<N; ++i)
{
fprintf(fp, "\n%2d: ", i);
for (int j=0; j<M; ++j)
{
fprintf(fp, "%15lg ", m[i][j]);
}
}
fprintf(fp, "\n");
}
// helper function for creating a box mesh
void BuildBoxMesh(FEMesh& mesh, FEMaterial* mat)
{
constexpr int N = 8;
vec3d r[N] = {
vec3d(0,0,0), vec3d(1,0,0), vec3d(1,1,0), vec3d(0,1,0),
vec3d(0,0,1), vec3d(1,0,1), vec3d(1,1,1), vec3d(0,1,1)
};
mesh.CreateNodes(N);
for (int i = 0; i < N; ++i)
{
FENode& node = mesh.Node(i);
node.m_rt = node.m_r0 = r[i];
}
FE_Element_Spec es;
es.eclass = FE_Element_Class::FE_ELEM_SOLID;
es.eshape = FE_Element_Shape::ET_HEX8;
es.etype = FE_Element_Type::FE_HEX8G8;
// create a solid domain
FECoreKernel& fecore = FECoreKernel::GetInstance();
FEElasticSolidDomain* pd = dynamic_cast<FEElasticSolidDomain*>(fecore.CreateDomain(es, &mesh, mat));
pd->Create(1, es);
pd->SetMatID(0);
mesh.AddDomain(pd);
FESolidElement& el = pd->Element(0);
el.SetID(1);
for (int i = 0; i < 8; ++i) el.m_node[i] = i;
pd->CreateMaterialPointData();
}
//////////////////////////////////////////////////////////////////////
// FETangentUniaxial
//////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FETangentUniaxial, FEDiagnosticScenario)
ADD_PARAMETER(m_strain, "strain");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
bool FETangentUniaxial::Init()
{
FEModel& fem = *GetDiagnostic()->GetFEModel();
int BC[8][3] = {
{-1,-1,-1},{ 0,-1,-1},{ 0, 0,-1}, {-1, 0,-1},
{-1,-1, 0},{ 0,-1, 0},{ 0, 0, 0}, {-1, 0, 0}
};
// --- create the FE problem ---
// get the material (must already be defined)
if (fem.Materials() == 0) return false;
FEMaterial* pmat = fem.GetMaterial(0);
// create the mesh
FEMesh& m = fem.GetMesh();
BuildBoxMesh(m, pmat);
// build boundary conditions
FENodeSet* nset[3];
nset[0] = new FENodeSet(&fem);
nset[1] = new FENodeSet(&fem);
nset[2] = new FENodeSet(&fem);
// get the degrees of freedom
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
const int dof_X = fem.GetDOFIndex("x");
const int dof_Y = fem.GetDOFIndex("y");
const int dof_Z = fem.GetDOFIndex("z");
m.SetDOFS(MAX_DOFS);
for (int i=0; i<8; ++i)
{
FENode& n = m.Node(i);
// set displacement BC's
if (BC[i][0] == -1) nset[0]->Add(i);
if (BC[i][1] == -1) nset[1]->Add(i);
if (BC[i][2] == -1) nset[2]->Add(i);
}
FEFixedBC* bc_x = new FEFixedBC(&fem, dof_X, nset[0]); fem.AddBoundaryCondition(bc_x);
FEFixedBC* bc_y = new FEFixedBC(&fem, dof_Y, nset[1]); fem.AddBoundaryCondition(bc_y);
FEFixedBC* bc_z = new FEFixedBC(&fem, dof_Z, nset[2]); fem.AddBoundaryCondition(bc_z);
// get the simulation time
FEAnalysis* step = fem.GetStep(0);
double tend = step->m_ntime * step->m_dt0;
// Add a loadcurve
FELoadCurve* plc = new FELoadCurve(&fem);
plc->Add(0.0, 0.0);
plc->Add(tend, 1.0);
fem.AddLoadController(plc);
// Add a prescribed BC
std::vector<int> prescribedNodes = {1, 2, 5, 6};
FENodeSet* dc = new FENodeSet(&fem);
dc->Add(prescribedNodes);
// convert strain to a displacement
double d = sqrt(2 * m_strain + 1) - 1;
FEPrescribedDOF* pdc = new FEPrescribedDOF(&fem, dof_X, dc);
pdc->SetScale(d, 0);
fem.AddBoundaryCondition(pdc);
return true;
}
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FETangentSimpleShear, FEDiagnosticScenario)
ADD_PARAMETER(m_strain, "strain");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
bool FETangentSimpleShear::Init()
{
FEModel& fem = *GetDiagnostic()->GetFEModel();
int BC[8][3] = {
{-1,-1,-1},{-1,-1,-1},{-1, 0,-1}, {-1, 0,-1},
{ 0,-1,-1},{ 0,-1,-1},{ 0, 0,-1}, { 0, 0,-1}
};
// get the degrees of freedom
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
const int dof_X = fem.GetDOFIndex("x");
const int dof_Y = fem.GetDOFIndex("y");
const int dof_Z = fem.GetDOFIndex("z");
// --- create the FE problem ---
// get the material (must already be defined)
if (fem.Materials() == 0) return false;
FEMaterial* pmat = fem.GetMaterial(0);
// create the mesh
FEMesh& m = fem.GetMesh();
BuildBoxMesh(m, pmat);
m.SetDOFS(MAX_DOFS);
FENodeSet* nset[3];
nset[0] = new FENodeSet(&fem);
nset[1] = new FENodeSet(&fem);
nset[2] = new FENodeSet(&fem);
for (int i = 0; i<8; ++i)
{
FENode& n = m.Node(i);
// set displacement BC's
if (BC[i][0] == -1) nset[0]->Add(i);
if (BC[i][1] == -1) nset[1]->Add(i);
if (BC[i][2] == -1) nset[2]->Add(i);
}
FEFixedBC* bc_x = new FEFixedBC(&fem, dof_X, nset[0]); fem.AddBoundaryCondition(bc_x);
FEFixedBC* bc_y = new FEFixedBC(&fem, dof_Y, nset[1]); fem.AddBoundaryCondition(bc_y);
FEFixedBC* bc_z = new FEFixedBC(&fem, dof_Z, nset[2]); fem.AddBoundaryCondition(bc_z);
// get the simulation time
FEAnalysis* step = fem.GetStep(0);
double tend = step->m_ntime * step->m_dt0;
// Add a loadcurve
FELoadCurve* plc = new FELoadCurve(&fem);
plc->Add(0.0, 0.0);
plc->Add(tend, 1.0);
fem.AddLoadController(plc);
// Add a prescribed BC
std::vector<int> precribedNodes = { 4, 5, 6, 7 };
FENodeSet* dc = new FENodeSet(&fem);
dc->Add(precribedNodes);
// convert strain to a displacement
double d = 2 * m_strain;
FEPrescribedDOF* pdc = new FEPrescribedDOF(&fem, dof_X, dc);
pdc->SetScale(d, 0);
fem.AddBoundaryCondition(pdc);
return true;
}
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FETangentBiaxial, FEDiagnosticScenario)
ADD_PARAMETER(m_strain, "strain");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
bool FETangentBiaxial::Init()
{
FEModel& fem = *GetDiagnostic()->GetFEModel();
int BC[8][3] = {
{-1,-1,-1},{ 0,-1,-1},{ 0, 0,-1}, {-1, 0,-1},
{-1,-1, 0},{ 0,-1, 0},{ 0, 0, 0}, {-1, 0, 0}
};
// --- create the FE problem ---
// get the material (must already be defined)
if (fem.Materials() == 0) return false;
FEMaterial* pmat = fem.GetMaterial(0);
// create the mesh
FEMesh& m = fem.GetMesh();
BuildBoxMesh(m, pmat);
// build boundary conditions
FENodeSet* nset[3];
nset[0] = new FENodeSet(&fem);
nset[1] = new FENodeSet(&fem);
nset[2] = new FENodeSet(&fem);
// get the degrees of freedom
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
const int dof_X = fem.GetDOFIndex("x");
const int dof_Y = fem.GetDOFIndex("y");
const int dof_Z = fem.GetDOFIndex("z");
m.SetDOFS(MAX_DOFS);
for (int i = 0; i < 8; ++i)
{
FENode& n = m.Node(i);
// set displacement BC's
if (BC[i][0] == -1) nset[0]->Add(i);
if (BC[i][1] == -1) nset[1]->Add(i);
if (BC[i][2] == -1) nset[2]->Add(i);
}
FEFixedBC* bc_x = new FEFixedBC(&fem, dof_X, nset[0]); fem.AddBoundaryCondition(bc_x);
FEFixedBC* bc_y = new FEFixedBC(&fem, dof_Y, nset[1]); fem.AddBoundaryCondition(bc_y);
FEFixedBC* bc_z = new FEFixedBC(&fem, dof_Z, nset[2]); fem.AddBoundaryCondition(bc_z);
// get the simulation time
FEAnalysis* step = fem.GetStep(0);
double tend = step->m_ntime * step->m_dt0;
// Add a loadcurve
FELoadCurve* plc = new FELoadCurve(&fem);
plc->Add(0.0, 0.0);
plc->Add(tend, 1.0);
fem.AddLoadController(plc);
// Add two prescribed BCs, one for X and one for Y
FENodeSet* dcx = new FENodeSet(&fem);
dcx->Add({ 1, 2, 5, 6 });
FENodeSet* dcy = new FENodeSet(&fem);
dcy->Add({ 2, 3, 6, 7 });
// convert strain to a displacement
double d = sqrt(2 * m_strain + 1) - 1;
FEPrescribedDOF* pdcx = new FEPrescribedDOF(&fem, dof_X, dcx);
pdcx->SetScale(d, 0);
fem.AddBoundaryCondition(pdcx);
FEPrescribedDOF* pdcy = new FEPrescribedDOF(&fem, dof_Y, dcy);
pdcy->SetScale(d, 0);
fem.AddBoundaryCondition(pdcy);
return true;
}
BEGIN_FECORE_CLASS(FETangentTriaxial, FEDiagnosticScenario)
ADD_PARAMETER(m_strain, "strain");
END_FECORE_CLASS();
bool FETangentTriaxial::Init()
{
FEModel& fem = *GetDiagnostic()->GetFEModel();
int BC[8][3] = {
{-1,-1,-1},{ 0,-1,-1},{ 0, 0,-1}, {-1, 0,-1},
{-1,-1, 0},{ 0,-1, 0},{ 0, 0, 0}, {-1, 0, 0}
};
// --- create the FE problem ---
// get the material (must already be defined)
if (fem.Materials() == 0) return false;
FEMaterial* pmat = fem.GetMaterial(0);
// create the mesh
FEMesh& m = fem.GetMesh();
BuildBoxMesh(m, pmat);
// build boundary conditions
FENodeSet* nset[3];
nset[0] = new FENodeSet(&fem);
nset[1] = new FENodeSet(&fem);
nset[2] = new FENodeSet(&fem);
// get the degrees of freedom
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
const int dof_X = fem.GetDOFIndex("x");
const int dof_Y = fem.GetDOFIndex("y");
const int dof_Z = fem.GetDOFIndex("z");
m.SetDOFS(MAX_DOFS);
for (int i = 0; i < 8; ++i)
{
FENode& n = m.Node(i);
// set displacement BC's
if (BC[i][0] == -1) nset[0]->Add(i);
if (BC[i][1] == -1) nset[1]->Add(i);
if (BC[i][2] == -1) nset[2]->Add(i);
}
FEFixedBC* bc_x = new FEFixedBC(&fem, dof_X, nset[0]); fem.AddBoundaryCondition(bc_x);
FEFixedBC* bc_y = new FEFixedBC(&fem, dof_Y, nset[1]); fem.AddBoundaryCondition(bc_y);
FEFixedBC* bc_z = new FEFixedBC(&fem, dof_Z, nset[2]); fem.AddBoundaryCondition(bc_z);
// get the simulation time
FEAnalysis* step = fem.GetStep(0);
double tend = step->m_ntime * step->m_dt0;
// Add a loadcurve
FELoadCurve* plc = new FELoadCurve(&fem);
plc->Add(0.0, 0.0);
plc->Add(tend, 1.0);
fem.AddLoadController(plc);
// Add 3 prescribed BCs, one for X, Y, and Z
FENodeSet* dcx = new FENodeSet(&fem);
dcx->Add({ 1, 2, 5, 6 });
FENodeSet* dcy = new FENodeSet(&fem);
dcy->Add({ 2, 3, 6, 7 });
FENodeSet* dcz = new FENodeSet(&fem);
dcz->Add({ 4, 5, 6, 7 });
// convert strain to a displacement
double d = sqrt(2 * m_strain + 1) - 1;
FEPrescribedDOF* pdcx = new FEPrescribedDOF(&fem, dof_X, dcx);
pdcx->SetScale(d, 0);
fem.AddBoundaryCondition(pdcx);
FEPrescribedDOF* pdcy = new FEPrescribedDOF(&fem, dof_Y, dcy);
pdcy->SetScale(d, 0);
fem.AddBoundaryCondition(pdcy);
FEPrescribedDOF* pdcz = new FEPrescribedDOF(&fem, dof_Z, dcz);
pdcz->SetScale(d, 0);
fem.AddBoundaryCondition(pdcz);
return true;
}
FETangentDiagnostic::FETangentDiagnostic(FEModel* fem) : FEDiagnostic(fem)
{
// make sure the correct module is active
fem->SetActiveModule("solid");
m_pscn = 0;
// create an analysis step
FEAnalysis* pstep = new FEAnalysis(fem);
// create a new solver
FENewtonSolver* pnew_solver = dynamic_cast<FENewtonSolver*>(fecore_new<FESolver>("solid", fem));
assert(pnew_solver);
pnew_solver->SetSolutionStrategy(fecore_new<FENewtonStrategy>("full Newton", fem));
pstep->SetFESolver(pnew_solver);
// keep a pointer to the fem object
fem->AddStep(pstep);
fem->SetCurrentStep(pstep);
}
//-----------------------------------------------------------------------------
FEDiagnosticScenario* FETangentDiagnostic::CreateScenario(const std::string& sname)
{
if (sname == "uni-axial" ) return (m_pscn = new FETangentUniaxial (this));
if (sname == "simple shear") return (m_pscn = new FETangentSimpleShear(this));
return 0;
}
//-----------------------------------------------------------------------------
// Initialize the diagnostic. In this function we build the FE model depending
// on the scenario.
bool FETangentDiagnostic::Init()
{
// make sure we have a scenario
if (m_pscn == 0) return false;
// initialize the scenario
if (m_pscn->Init() == false) return false;
return FEDiagnostic::Init();
}
//-----------------------------------------------------------------------------
// Run the tangent diagnostic. After we run the FE model, we calculate
// the element stiffness matrix and compare that to a finite difference
// of the element residual.
bool FETangentDiagnostic::Run()
{
// solve the problem
FEModel& fem = *GetFEModel();
fem.BlockLog();
bool bret = fem.Solve();
fem.UnBlockLog();
if (bret == false)
{
feLogError("FEBio error terminated. Aborting diagnostic.\n");
return false;
}
FEMesh& mesh = fem.GetMesh();
FEElasticSolidDomain& bd = static_cast<FEElasticSolidDomain&>(mesh.Domain(0));
// get the one and only element
FESolidElement& el = bd.Element(0);
// set up the element stiffness matrix
matrix k0(24, 24);
k0.zero();
bd.ElementStiffness(fem.GetTime(), 0, k0);
// create a file name for the tangent log file
std::string febFile = GetFileName();
string fileName = febFile;
size_t n = fileName.rfind('.');
if (n != string::npos) fileName.erase(n);
fileName.append("_out.log");
FILE* fp = fopen(fileName.c_str(), "wt");
fprintf(fp, "FEBio Tangent Diagnostics Results:\n");
fprintf(fp, "==================================\n");
fprintf(fp, "Diagnostics file: %s\n\n", febFile.c_str());
// print the element stiffness matrix
fprintf(fp, "\nActual stiffness matrix:\n");
print_matrix(fp, k0);
// now calculate the derivative of the residual
matrix k1;
deriv_residual(k1);
// print the approximate element stiffness matrix
fprintf(fp, "\nApproximate stiffness matrix:\n");
print_matrix(fp, k1);
// finally calculate the difference matrix
fprintf(fp, "\n");
matrix kd(24, 24);
double kmax = 0, kij;
int i0 = -1, j0 = -1, i, j;
for (i=0; i<24; ++i)
for (j=0; j<24; ++j)
{
kd[i][j] = k0[i][j] - k1[i][j];
kij = 100.0*fabs(kd[i][j] / k0[0][0]);
if (kij > kmax)
{
kmax = kij;
i0 = i;
j0 = j;
}
}
// print the difference
fprintf(fp, "\ndifference matrix:\n");
print_matrix(fp, kd);
fprintf(fp, "\nMaximum difference: %lg%% (at (%d,%d))\n", kmax, i0, j0);
fprintf(stderr, "\nMaximum difference: %lg%% (at (%d,%d))\n", kmax, i0, j0);
fclose(fp);
return (kmax < 1e-4);
}
//-----------------------------------------------------------------------------
// Calculate a finite difference approximation of the derivative of the
// element residual.
void FETangentDiagnostic::deriv_residual(matrix& ke)
{
// get the solver
FEModel& fem = *GetFEModel();
FEAnalysis* pstep = fem.GetCurrentStep();
FESolidSolver2& solver = static_cast<FESolidSolver2&>(*pstep->GetFESolver());
// get the degrees of freedom
const int dof_X = fem.GetDOFIndex("x");
const int dof_Y = fem.GetDOFIndex("y");
const int dof_Z = fem.GetDOFIndex("z");
// get the mesh
FEMesh& mesh = fem.GetMesh();
FEElasticSolidDomain& bd = static_cast<FEElasticSolidDomain&>(mesh.Domain(0));
// get the one and only element
FESolidElement& el = bd.Element(0);
// first calculate the initial residual
vector<double> f0(24);
zero(f0);
bd.ElementInternalForce(el, f0);
// now calculate the perturbed residuals
ke.resize(24, 24);
ke.zero();
int i, j, nj;
int N = mesh.Nodes();
double dx = 1e-8;
vector<double> f1(24);
for (j=0; j<3*N; ++j)
{
FENode& node = mesh.Node(el.m_node[j/3]);
nj = j%3;
switch (nj)
{
case 0: node.add(dof_X, dx); node.m_rt.x += dx; break;
case 1: node.add(dof_Y, dx); node.m_rt.y += dx; break;
case 2: node.add(dof_Z, dx); node.m_rt.z += dx; break;
}
fem.Update();
zero(f1);
bd.ElementInternalForce(el, f1);
switch (nj)
{
case 0: node.sub(dof_X, dx); node.m_rt.x -= dx; break;
case 1: node.sub(dof_Y, dx); node.m_rt.y -= dx; break;
case 2: node.sub(dof_Z, dx); node.m_rt.z -= dx; break;
}
fem.Update();
for (i=0; i<3*N; ++i) ke[i][j] = -(f1[i] - f0[i])/dx;
}
}
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.