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
FEBioMix/FESupplyBinding.h
.h
2,759
75
/*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 "FEBiphasic.h" #include "FEBiphasicSolute.h" //----------------------------------------------------------------------------- // This class implements a material that has a solute supply based on // receptor-ligand binding kinetics as described by the Langmuir or Hill equation class FEBIOMIX_API FESupplyBinding : public FESoluteSupply { public: //! constructor FESupplyBinding(FEModel* pfem); //! Solute supply double Supply(FEMaterialPoint& pt) override; //! Tangent of supply with respect to strain double Tangent_Supply_Strain(FEMaterialPoint& mp) override; //! Tangent of supply with respect to concentration double Tangent_Supply_Concentration(FEMaterialPoint& mp) override; //! receptor-ligand complex supply double ReceptorLigandSupply(FEMaterialPoint& mp) override; //! Solute supply at steady-state double SupplySS(FEMaterialPoint& pt) override; //! receptor-ligand complex concentration at steady-state double ReceptorLigandConcentrationSS(FEMaterialPoint& mp) override; //! referential solid supply double SolidSupply(FEMaterialPoint& pt) override; //! referential solid volume fraction under steady-state conditions double SolidConcentrationSS(FEMaterialPoint& pt) override; public: double m_kf; //!< forward reaction rate constant double m_kr; //!< reverse reaction rate constant double m_crt; //!< total receptor concentration (referential) // declare parameter list DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FEBiphasicSoluteAnalysis.h
.h
1,565
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.*/ #pragma once #include <FECore/FEAnalysis.h> #include "febiomix_api.h" class FEBIOMIX_API FEBiphasicSoluteAnalysis : public FEAnalysis { public: enum BiphasicSoluteAnalysisType { STEADY_STATE, TRANSIENT }; public: FEBiphasicSoluteAnalysis(FEModel* fem); DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FEInitialConcentration.h
.h
1,595
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) 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 #include <FECore/FEInitialCondition.h> class FEInitialConcentration : public FEInitialDOF { public: FEInitialConcentration(FEModel* fem); DECLARE_FECORE_CLASS(); }; class FEInitialShellConcentration : public FEInitialDOF { public: FEInitialShellConcentration(FEModel* fem); DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FEPressureStabilization.cpp
.cpp
5,118
157
/*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 "FEPressureStabilization.h" #include "FEBiphasic.h" #include "FECore/FEModel.h" //----------------------------------------------------------------------------- BEGIN_FECORE_CLASS(FEPressureStabilization, FESurfaceLoad) ADD_PARAMETER(m_bstab, "stabilize" ); END_FECORE_CLASS(); //----------------------------------------------------------------------------- //! constructor FEPressureStabilization::FEPressureStabilization(FEModel* pfem) : FESurfaceLoad(pfem) { m_bstab = true; } //----------------------------------------------------------------------------- //! allocate storage void FEPressureStabilization::SetSurface(FESurface* ps) { FESurfaceLoad::SetSurface(ps); } //----------------------------------------------------------------------------- bool FEPressureStabilization::Init() { FESurface& ps = GetSurface(); ps.Init(); return true; } //----------------------------------------------------------------------------- void FEPressureStabilization::Activate() { FESurface& ps = GetSurface(); // get the mesh FEMesh& m = GetFEModel()->GetMesh(); // loop over all surface elements for (int i=0; i<ps.Elements(); ++i) { // get the surface element FESurfaceElement& el = ps.Element(i); // find the element this face belongs to FEElement* pe = el.m_elem[0].pe; assert(pe); // calculate time constant double tau = TimeConstant(el, ps); } FESurfaceLoad::Activate(); } //----------------------------------------------------------------------------- double FEPressureStabilization::TimeConstant(FESurfaceElement& el, FESurface& s) { // get the mesh FEMesh& m = GetFEModel()->GetMesh(); double tau = 0; // get the element this surface element belongs to FEElement* pe = el.m_elem[0].pe; if (pe) { // evaluate element surface normal at parametric center vec3d t[2]; s.CoBaseVectors0(el, 0, 0, t); vec3d n = t[0] ^ t[1]; n.unit(); // get the material FEMaterial* pm = GetFEModel()->GetMaterial(pe->GetMatID()); // see if this is a poro-elastic element FEBiphasic* biph = dynamic_cast<FEBiphasic*> (pm); if (biph) { // get the area of the surface element double A = s.FaceArea(el); // get the volume of the volume element double V = m.ElementVolume(*pe); // calculate the element thickness double h = V/A; // get a material point FEMaterialPoint& mp = *pe->GetMaterialPoint(0); FEElasticMaterialPoint& ept = *(mp.ExtractData<FEElasticMaterialPoint>()); // setup the material point ept.m_F = mat3dd(1.0); ept.m_J = 1; ept.m_s.zero(); // get the tangent (stiffness) and it inverse (compliance) at this point tens4dmm C = biph->Tangent(mp); double Ha = n*(vdotTdotv(n, C, n)*n); // if this is a poroelastic element, then get the permeability tensor FEBiphasicMaterialPoint& pt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); pt.m_p = 0; pt.m_w = vec3d(0,0,0); mat3ds K = biph->Permeability(mp); double k = n*(K*n); tau = h*h/(4*Ha*k); // if time constant not yet set if (biph->m_tau == 0) biph->m_tau = tau; // set it to calculated value else // pick smallest value biph->m_tau = max(biph->m_tau, tau); } } return tau; }
C++
3D
febiosoftware/FEBio
FEBioMix/FEBiphasicSoluteDomain.cpp
.cpp
1,737
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 "FEBiphasicSoluteDomain.h" #include "FECore/FEModel.h" //----------------------------------------------------------------------------- FEBiphasicSoluteDomain::FEBiphasicSoluteDomain(FEModel* pfem) : FEElasticDomain(pfem) { m_pMat = 0; m_dofP = pfem->GetDOFIndex("p"); m_dofQ = pfem->GetDOFIndex("q"); m_dofC = pfem->GetDOFIndex("concentration", 0); m_dofD = pfem->GetDOFIndex("shell concentration", 0); }
C++
3D
febiosoftware/FEBio
FEBioMix/FEBiphasic.h
.h
7,645
204
/*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 <FEBioMech/FEElasticMaterial.h> #include "FEHydraulicPermeability.h" #include "FESolventSupply.h" #include "FEActiveMomentumSupply.h" #include <FEBioMech/FEBodyForce.h> #include <FECore/FEModelParam.h> //----------------------------------------------------------------------------- //! Biphasic material point class. // class FEBIOMIX_API FEBiphasicMaterialPoint : public FEMaterialPointData { public: //! constructor FEBiphasicMaterialPoint(FEMaterialPointData* ppt); //! create a shallow copy FEMaterialPointData* Copy() override; //! data serialization void Serialize(DumpStream& ar) override; //! Data initialization void Init() override; public: // poro-elastic material data // The actual fluid pressure is the same as the effective fluid pressure // in a poroelastic material without solute(s). The actual fluid pressure // is included here so that models that include both poroelastic and // solute-poroelastic domains produce plotfiles with consistent fluid // pressure fields. double m_p; //!< fluid pressure vec3d m_gradp; //!< spatial gradient of p vec3d m_gradpp; //!< gradp at previous time vec3d m_w; //!< fluid flux double m_pa; //!< actual fluid pressure double m_phi0; //!< referential solid volume fraction at initial time double m_phi0t; //!< referential solid volume fraction at current time double m_phi0p; //!< referential solid volume fraction at previous time double m_phi0hat; //!< referential solid volume fraction supply at current time double m_Jp; //!< determinant of solid deformation gradient at previous time mat3ds m_ss; //!< solid (elastic or effective) stress }; //----------------------------------------------------------------------------- class FEBIOMIX_API FEBiphasicInterface { public: FEBiphasicInterface() {} virtual ~FEBiphasicInterface() {} public: virtual double GetReferentialSolidVolumeFraction(const FEMaterialPoint& mp) { return 0.0; } // TODO: These are only used by multiphasic materials. Perhapse move to separate interface class? //! solid referential apparent density virtual double SolidReferentialApparentDensity(FEMaterialPoint& pt) { return 0.0; } //! solid referential volume fraction virtual double SolidReferentialVolumeFraction(FEMaterialPoint& pt) { return 0.0; }; virtual double TangentSRVFStrain(FEMaterialPoint& pt) { return 0.0; } // TODO: This is a bit of a hack to get the fluid pressure. virtual double GetActualFluidPressure(const FEMaterialPoint& pt) { return 0.0; } }; //----------------------------------------------------------------------------- //! Base class for biphasic materials. class FEBIOMIX_API FEBiphasic : public FEMaterial, public FEBiphasicInterface { public: FEBiphasic(FEModel* pfem); // returns a pointer to a new material point object FEMaterialPointData* CreateMaterialPointData() override; // Get the elastic component (overridden from FEMaterial) FEElasticMaterial* GetElasticMaterial() { return m_pSolid; } public: //! initialize bool Init() override; //! specialized material points void UpdateSpecializedMaterialPoints(FEMaterialPoint& mp, const FETimeInfo& tp) override; //! calculate stress at material point mat3ds Stress(FEMaterialPoint& pt); //! calculate secant stress at material point mat3ds SecantStress(FEMaterialPoint& pt); //! calculate tangent stiffness at material point tens4dmm Tangent(FEMaterialPoint& pt); //! calculate secant tangent stiffness at material point tens4dmm SecantTangent(FEMaterialPoint& pt); //! return the permeability tensor as a matrix void Permeability(double k[3][3], FEMaterialPoint& pt); //! return the permeability as a tensor mat3ds Permeability(FEMaterialPoint& pt); //! return tangent of permeability with strain tens4dmm Tangent_Permeability_Strain(FEMaterialPoint& mp); //! return secant tangent of permeability with strain tens4dmm SecantTangent_Permeability_Strain(FEMaterialPoint& mp); //! return the permeability property FEHydraulicPermeability* GetPermeability() { return m_pPerm; } //! return the material permeability property mat3ds MaterialPermeability(FEMaterialPoint& mp, const mat3ds E); //! calculate actual fluid pressure double Pressure(FEMaterialPoint& pt); //! porosity double Porosity(FEMaterialPoint& pt); //! solid density double SolidDensity(FEMaterialPoint& mp) { return m_pSolid->Density(mp); } //! fluid density double FluidDensity() { return m_rhoTw; } //! get the solvent supply double SolventSupply(FEMaterialPoint& mp) { return (m_pSupp? m_pSupp->Supply(mp) : 0); } //! get the solvent supply property FESolventSupply* GetSolventSupply() { return m_pSupp; } //! Get the active momentum supply FEActiveMomentumSupply* GetActiveMomentumSupply() { return m_pAmom; } public: // overridden from FEBiphasicInterface double GetReferentialSolidVolumeFraction(const FEMaterialPoint& mp) override { const FEBiphasicMaterialPoint* pt = (mp.ExtractData<FEBiphasicMaterialPoint>()); return pt->m_phi0t; } double GetActualFluidPressure(const FEMaterialPoint& mp) override { const FEBiphasicMaterialPoint* pt = (mp.ExtractData<FEBiphasicMaterialPoint>()); return pt->m_pa; } //! evaluate and return solid referential volume fraction double SolidReferentialVolumeFraction(FEMaterialPoint& mp) override { double phisr = m_phi0(mp); FEBiphasicMaterialPoint* bp = (mp.ExtractData<FEBiphasicMaterialPoint>()); bp->m_phi0 = bp->m_phi0t = phisr; return phisr; }; public: // material parameters double m_rhoTw; //!< true fluid density FEParamDouble m_phi0; //!< solid volume fraction in reference configuration double m_tau; //!< characteristic time constant for stabilization vector<FEBodyForce*> m_bf; //!< body forces acting on this biphasic material private: // material properties FEElasticMaterial* m_pSolid; //!< pointer to elastic solid material FEHydraulicPermeability* m_pPerm; //!< pointer to permeability material FESolventSupply* m_pSupp; //!< pointer to solvent supply FEActiveMomentumSupply* m_pAmom; //!< pointer to active momentum supply DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FEMultiphasic.h
.h
11,669
294
/*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 "FEBiphasic.h" #include "FESolutesMaterialPoint.h" #include "FESolute.h" #include "FEOsmoticCoefficient.h" #include "FEChemicalReaction.h" #include "FEMembraneReaction.h" #include "FESoluteInterface.h" #include <FECore/FEModelParam.h> #include <FECore/FEShellElement.h> //----------------------------------------------------------------------------- //! Base class for multiphasic materials. class FEBIOMIX_API FEMultiphasic : public FEMaterial, public FEBiphasicInterface, public FESoluteInterface_T<FESolutesMaterialPoint> { public: //! constructor FEMultiphasic(FEModel* pfem); //! initialization bool Init() override; //! specialized material points void UpdateSpecializedMaterialPoints(FEMaterialPoint& mp, const FETimeInfo& tp) override; //! Serialization void Serialize(DumpStream& ar) override; // return elastic material component FEElasticMaterial* GetElasticMaterial() { return m_pSolid; } //! Update solid bound molecules virtual void UpdateSolidBoundMolecules(FEMaterialPoint& mp) = 0; public: //! calculate stress at material point mat3ds Stress(FEMaterialPoint& pt); //! calculate tangent stiffness at material point tens4ds Tangent(FEMaterialPoint& pt); //! calculate fluid (solvent) flux vec3d FluidFlux(FEMaterialPoint& pt); //! calculate solute molar flux vec3d SoluteFlux(FEMaterialPoint& pt, const int sol); //! actual fluid pressure (as opposed to effective pressure) double Pressure(FEMaterialPoint& pt); //! partition coefficient double PartitionCoefficient(FEMaterialPoint& pt, const int sol); //! partition coefficients and their derivatives void PartitionCoefficientFunctions(FEMaterialPoint& mp, vector<double>& kappa, vector<double>& dkdJ, vector< vector<double> >& dkdc, vector< vector<double> >& dkdr, vector< vector<double> >& dkdJr, vector< vector< vector<double> > >& dkdrc); //! return solid referential apparent density double GetReferentialSolidVolumeFraction(const FEMaterialPoint& mp) override; //! evaluate and return solid referential apparent density double SolidReferentialApparentDensity(FEMaterialPoint& pt) override; //! evaluate and return solid referential volume fraction double SolidReferentialVolumeFraction(FEMaterialPoint& pt) override; //! evaluate and return tangent of solid referential volume fraction w.r.t. to J (volume ratio) double TangentSRVFStrain(FEMaterialPoint& pt) override; //! evaluate and return tangent of solid referential volume fraction w.r.t. to concentration double TangentSRVFConcentration(FEMaterialPoint& pt, const int sol); //! actual concentration (as opposed to effective concentration) double Concentration(FEMaterialPoint& pt, const int sol); //! porosity double Porosity(FEMaterialPoint& pt); //! fixed charge density virtual double FixedChargeDensity(FEMaterialPoint& pt); //! electric potential double ElectricPotential(FEMaterialPoint& pt, const bool eform = false); //! current density vec3d CurrentDensity(FEMaterialPoint& pt); //! fluid true density double FluidDensity() { return m_rhoTw; } //! solute density double SoluteDensity(const int sol) { return m_pSolute[sol]->Density(); } //! solute molar mass double SoluteMolarMass(const int sol) { return m_pSolute[sol]->MolarMass(); } //! solute charge number int SoluteChargeNumber(const int sol) { return m_pSolute[sol]->ChargeNumber(); } //! SBM density double SBMDensity(const int sbm) { return m_pSBM[sbm]->Density(); } //! SBM molar mass double SBMMolarMass(const int sbm) { return m_pSBM[sbm]->MolarMass(); } //! SBM charge number int SBMChargeNumber(const int sbm) { return m_pSBM[sbm]->ChargeNumber(); } //! SBM actual concentration (molar concentration per fluid volume in current configuration) double SBMConcentration(FEMaterialPoint& pt, const int sbm) override { FEElasticMaterialPoint& ept = *pt.ExtractData<FEElasticMaterialPoint>(); FEBiphasicMaterialPoint& bpt = *pt.ExtractData<FEBiphasicMaterialPoint>(); FESolutesMaterialPoint& spt = *pt.ExtractData<FESolutesMaterialPoint>(); return spt.m_sbmr[sbm] / (ept.m_J - bpt.m_phi0t) / SBMMolarMass(sbm); } //! SBM areal concentration (mole per shell area) -- should only be called from shell domains double SBMArealConcentration(FEMaterialPoint& pt, const int sbm) override { FEShellElement* sel = dynamic_cast<FEShellElement*>(pt.m_elem); assert(sel); double h = sel->Evaluate(sel->m_ht, pt.m_index); // shell thickness FEElasticMaterialPoint& ept = *pt.ExtractData<FEElasticMaterialPoint>(); FESolutesMaterialPoint& spt = *pt.ExtractData<FESolutesMaterialPoint>(); return spt.m_sbmr[sbm] / SBMMolarMass(sbm) * h / ept.m_J; } // return the number of solutes on external side int SolutesExternal(FEMaterialPoint& pt) override { FESolutesMaterialPoint& spt = *pt.ExtractData<FESolutesMaterialPoint>(); return (int)spt.m_ce.size(); } // return the number of solutes on internal side int SolutesInternal(FEMaterialPoint& pt) override { FESolutesMaterialPoint& spt = *pt.ExtractData<FESolutesMaterialPoint>(); return (int)spt.m_ci.size(); } //! return the solute ID on external side int GetSoluteIDExternal(FEMaterialPoint& mp, int soluteIndex) override { FESolutesMaterialPoint& spt = *mp.ExtractData<FESolutesMaterialPoint>(); return spt.m_ide[soluteIndex]; } //! return the solute ID on internal side int GetSoluteIDInternal(FEMaterialPoint& mp, int soluteIndex) override { FESolutesMaterialPoint& spt = *mp.ExtractData<FESolutesMaterialPoint>(); return spt.m_idi[soluteIndex]; } //! return the effective solute concentration on external side double GetEffectiveSoluteConcentrationExternal(FEMaterialPoint& mp, int soluteIndex) override { FESolutesMaterialPoint& spt = *mp.ExtractData<FESolutesMaterialPoint>(); return spt.m_ce[soluteIndex]; } //! return the effective solute concentration on internal side double GetEffectiveSoluteConcentrationInternal(FEMaterialPoint& mp, int soluteIndex) override { FESolutesMaterialPoint& spt = *mp.ExtractData<FESolutesMaterialPoint>(); return spt.m_ci[soluteIndex]; } //! return the effective pressure on external side double GetEffectiveFluidPressureExternal(FEMaterialPoint& mp) override { FESolutesMaterialPoint& spt = *mp.ExtractData<FESolutesMaterialPoint>(); return spt.m_pe; } //! return the effective pressure on internal side double GetEffectiveFluidPressureInternal(FEMaterialPoint& mp) override { FESolutesMaterialPoint& spt = *mp.ExtractData<FESolutesMaterialPoint>(); return spt.m_pi; } //! return the membrane areal strain double GetMembraneArealStrain(FEMaterialPoint& mp) override { FESolutesMaterialPoint& spt = *mp.ExtractData<FESolutesMaterialPoint>(); return spt.m_strain; } //! SBM referential volume fraction double SBMReferentialVolumeFraction(FEMaterialPoint& pt, const int sbm) { FESolutesMaterialPoint& spt = *pt.ExtractData<FESolutesMaterialPoint>(); return spt.m_sbmr[sbm] / SBMDensity(sbm); } //! find local SBM ID from global one int FindLocalSBMID(int nid); //! Add a solid bound molecule void AddSolidBoundMolecule(FESolidBoundMolecule* psbm); //! Add a chemical reaction void AddChemicalReaction(FEChemicalReaction* pcr); //! Add a membrane reaction void AddMembraneReaction(FEMembraneReaction* pcr); public: // solute interface double GetReferentialFixedChargeDensity(const FEMaterialPoint& mp) override; double GetFixedChargeDensity(const FEMaterialPoint& mp) override { const FESolutesMaterialPoint* spt = (mp.ExtractData<FESolutesMaterialPoint>()); return spt->m_cF; } public: //! Evaluate effective permeability mat3ds EffectivePermeability(FEMaterialPoint& pt); tens4dmm TangentPermeabilityStrain(FEMaterialPoint& pt, const mat3ds& Ke); mat3ds TangentPermeabilityConcentration(FEMaterialPoint& pt, const int sol, const mat3ds& Ke); // solute interface public: int Solutes() override { return (int)m_pSolute.size(); } FESolute* GetSolute(int i) override { return m_pSolute[i]; } public: FEElasticMaterial* GetSolid() { return m_pSolid; } FEHydraulicPermeability* GetPermeability() { return m_pPerm; } FEOsmoticCoefficient* GetOsmoticCoefficient() override { return m_pOsmC; } FESolventSupply* GetSolventSupply() { return m_pSupp; } FESolidBoundMolecule* GetSBM(int i) override { return m_pSBM[i]; } FEChemicalReaction* GetReaction(int i) { return m_pReact[i]; } FEMembraneReaction* GetMembraneReaction(int i) { return m_pMReact[i]; } public: // From FESoluteInterface int SBMs() const override { return (int)m_pSBM.size(); } public: int Reactions() { return (int)m_pReact.size(); } int MembraneReactions() { return (int)m_pMReact.size(); } public: // parameters FEParamDouble m_phi0; //!< solid volume fraction in reference configuration FEParamDouble m_cFr; //!< fixed charge density in reference configurations double m_rhoTw; //!< true fluid density double m_penalty; //!< penalty for enforcing electroneutrality public: double m_Rgas; //!< universal gas constant double m_Tabs; //!< absolute temperature double m_Fc; //!< Faraday's constant int m_zmin; //!< minimum charge number in mixture int m_ndeg; //!< polynomial degree of zeta in electroneutrality protected: // material properties FEElasticMaterial* m_pSolid; //!< pointer to elastic solid material FEHydraulicPermeability* m_pPerm; //!< pointer to permeability material FEOsmoticCoefficient* m_pOsmC; //!< pointer to osmotic coefficient material FESolventSupply* m_pSupp; //!< pointer to solvent supply material std::vector<FESolute*> m_pSolute; //!< pointer to solute materials std::vector<FESolidBoundMolecule*> m_pSBM; //!< pointer to solid-bound molecule materials std::vector<FEChemicalReaction*> m_pReact; //!< pointer to chemical reactions std::vector<FEMembraneReaction*> m_pMReact; //!< pointer to membrane reactions DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FEBiphasicShellDomain.cpp
.cpp
42,608
1,242
/*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 "FEBiphasicShellDomain.h" #include "FECore/FEMesh.h" #include "FECore/log.h" #include <FECore/FEModel.h> #include <FECore/FESolidDomain.h> #include <FECore/FELinearSystem.h> BEGIN_FECORE_CLASS(FEBiphasicShellDomain, FESSIShellDomain) ADD_PARAMETER(m_secant_stress, "secant_stress"); ADD_PARAMETER(m_secant_tangent, "secant_tangent"); ADD_PARAMETER(m_secant_perm_tangent, "secant_permeability_tangent"); END_FECORE_CLASS(); //----------------------------------------------------------------------------- FEBiphasicShellDomain::FEBiphasicShellDomain(FEModel* pfem) : FESSIShellDomain(pfem), FEBiphasicDomain(pfem), m_dof(pfem) { m_dofSX = pfem->GetDOFIndex("sx"); m_dofSY = pfem->GetDOFIndex("sy"); m_dofSZ = pfem->GetDOFIndex("sz"); m_secant_stress = false; m_secant_tangent = false; m_secant_perm_tangent = false; } //----------------------------------------------------------------------------- //! get the material (overridden from FEDomain) FEMaterial* FEBiphasicShellDomain::GetMaterial() { return m_pMat; } //----------------------------------------------------------------------------- //! get the total dof const FEDofList& FEBiphasicShellDomain::GetDOFList() const { return m_dof; } //----------------------------------------------------------------------------- void FEBiphasicShellDomain::SetMaterial(FEMaterial* pmat) { FEDomain::SetMaterial(pmat); m_pMat = dynamic_cast<FEBiphasic*>(pmat); assert(m_pMat); } //----------------------------------------------------------------------------- //! Initialize element data void FEBiphasicShellDomain::PreSolveUpdate(const FETimeInfo& timeInfo) { // initialize base class FESSIShellDomain::PreSolveUpdate(timeInfo); const int NE = FEElement::MAX_NODES; vec3d x0[NE], xt[NE], r0, rt; double pn[NE], qn[NE], p; FEMesh& m = *GetMesh(); for (size_t iel=0; iel<m_Elem.size(); ++iel) { FEShellElement& el = m_Elem[iel]; int neln = el.Nodes(); for (int i=0; i<neln; ++i) { x0[i] = m.Node(el.m_node[i]).m_r0; xt[i] = m.Node(el.m_node[i]).m_rt; pn[i] = m.Node(el.m_node[i]).get(m_dofP); qn[i] = m.Node(el.m_node[i]).get(m_dofQ); } int n = el.GaussPoints(); for (int j=0; j<n; ++j) { r0 = el.Evaluate(x0, j); rt = el.Evaluate(xt, j); p = evaluate(el, pn, qn, j); FEMaterialPoint& mp = *el.GetMaterialPoint(j); FEElasticMaterialPoint& pt = *mp.ExtractData<FEElasticMaterialPoint>(); FEBiphasicMaterialPoint& pb = *mp.ExtractData<FEBiphasicMaterialPoint>(); mp.m_r0 = r0; mp.m_rt = rt; pt.m_J = defgrad(el, pt.m_F, j); pb.m_Jp = pt.m_J; pb.m_p = p; pb.m_gradp = gradient(el, pn, qn, j); pb.m_gradpp = pb.m_gradp; pb.m_phi0p = pb.m_phi0t; mp.Update(timeInfo); } } } //----------------------------------------------------------------------------- void FEBiphasicShellDomain::Activate() { for (int i=0; i<Nodes(); ++i) { FENode& node = Node(i); if (node.HasFlags(FENode::EXCLUDE) == false) { if (node.m_rid < 0) { node.set_active(m_dofU[0]); node.set_active(m_dofU[1]); node.set_active(m_dofU[2]); if (node.HasFlags(FENode::SHELL)) { node.set_active(m_dofSU[0]); node.set_active(m_dofSU[1]); node.set_active(m_dofSU[2]); } } node.set_active(m_dofP); if (node.HasFlags(FENode::SHELL)) node.set_active(m_dofQ); } } } //----------------------------------------------------------------------------- //! Unpack the element LM data. void FEBiphasicShellDomain::UnpackLM(FEElement& el, vector<int>& lm) { int N = el.Nodes(); lm.resize(N*11); for (int i=0; i<N; ++i) { int n = el.m_node[i]; FENode& node = m_pMesh->Node(n); vector<int>& id = node.m_ID; // first the displacement dofs lm[8*i ] = id[m_dofU[0]]; lm[8*i+1] = id[m_dofU[1]]; lm[8*i+2] = id[m_dofU[2]]; // next the shell dofs lm[8*i+3] = id[m_dofSX]; lm[8*i+4] = id[m_dofSY]; lm[8*i+5] = id[m_dofSZ]; // now the pressure dofs lm[8*i+6] = id[m_dofP]; lm[8*i+7] = id[m_dofQ]; // rigid rotational dofs // TODO: Do I really need this? lm[8*N + 3*i ] = id[m_dofR[0]]; lm[8*N + 3*i+1] = id[m_dofR[1]]; lm[8*N + 3*i+2] = id[m_dofR[2]]; } } //----------------------------------------------------------------------------- void FEBiphasicShellDomain::Reset() { // reset base class data FESSIShellDomain::Reset(); // get the biphasic material FEBiphasic* pmb = m_pMat; // initialize all element data ForEachMaterialPoint([=](FEMaterialPoint& mp) { FEBiphasicMaterialPoint& pt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // initialize referential solid volume fraction pt.m_phi0 = pt.m_phi0t = pmb->m_phi0(mp); }); } //----------------------------------------------------------------------------- void FEBiphasicShellDomain::InternalForces(FEGlobalVector& R) { int NE = (int)m_Elem.size(); #pragma omp parallel for shared (NE) for (int i=0; i<NE; ++i) { // element force vector vector<double> fe; vector<int> lm; // get the element FEShellElement& el = m_Elem[i]; // get the element force vector and initialize it to zero int ndof = 8*el.Nodes(); fe.assign(ndof, 0); // calculate internal force vector ElementInternalForce(el, fe); // get the element's LM vector UnpackLM(el, lm); // assemble element 'fe'-vector into global R vector R.Assemble(el.m_node, lm, fe, true); } } //----------------------------------------------------------------------------- //! calculates the internal equivalent nodal forces for shell elements void FEBiphasicShellDomain::ElementInternalForce(FEShellElement& el, vector<double>& fe) { int i, n; // jacobian matrix determinant double detJt; vec3d gradM, gradMu, gradMd; double Mu, Md; mat3ds s; const double* Mr, *Ms, *M; int nint = el.GaussPoints(); int neln = el.Nodes(); double dt = GetFEModel()->GetTime().timeIncrement; double* gw = el.GaussWeights(); double eta; vec3d gcnt[3]; // repeat for all integration points for (n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); FEElasticMaterialPoint& pt = *(mp.ExtractData<FEElasticMaterialPoint>()); FEBiphasicMaterialPoint& bpt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // calculate the jacobian detJt = detJ(el, n); detJt *= gw[n]; // get the stress vector for this integration point s = pt.m_s; eta = el.gt(n); Mr = el.Hr(n); Ms = el.Hs(n); M = el.H(n); ContraBaseVectors(el, n, gcnt); // next we get the determinant double Jp = bpt.m_Jp; double J = pt.m_J; // and then finally double divv = ((J-Jp)/dt)/J; // get the flux vec3d& w = bpt.m_w; // get the solvent supply double phiwhat = m_pMat->SolventSupply(mp); for (i=0; i<neln; ++i) { gradM = gcnt[0]*Mr[i] + gcnt[1]*Ms[i]; gradMu = (gradM*(1+eta) + gcnt[2]*M[i])/2; gradMd = (gradM*(1-eta) - gcnt[2]*M[i])/2; vec3d fu = s*gradMu; vec3d fd = s*gradMd; Mu = (1+eta)/2*M[i]; Md = (1-eta)/2*M[i]; // calculate internal force // the '-' sign is so that the internal forces get subtracted // from the global residual vector fe[8*i ] -= fu.x*detJt; fe[8*i+1] -= fu.y*detJt; fe[8*i+2] -= fu.z*detJt; fe[8*i+3] -= fd.x*detJt; fe[8*i+4] -= fd.y*detJt; fe[8*i+5] -= fd.z*detJt; fe[8*i+6] -= dt*(w*gradMu + (phiwhat - divv)*Mu)*detJt; fe[8*i+7] -= dt*(w*gradMd + (phiwhat - divv)*Md)*detJt; } } } //----------------------------------------------------------------------------- void FEBiphasicShellDomain::InternalForcesSS(FEGlobalVector& R) { int NE = (int)m_Elem.size(); #pragma omp parallel for shared (NE) for (int i=0; i<NE; ++i) { // element force vector vector<double> fe; vector<int> lm; // get the element FEShellElement& el = m_Elem[i]; // get the element force vector and initialize it to zero int ndof = 8*el.Nodes(); fe.assign(ndof, 0); // calculate internal force vector ElementInternalForceSS(el, fe); // get the element's LM vector UnpackLM(el, lm); // assemble element 'fe'-vector into global R vector R.Assemble(el.m_node, lm, fe, true); } } //----------------------------------------------------------------------------- //! calculates the internal equivalent nodal forces for shell elements //! stead-state analysis void FEBiphasicShellDomain::ElementInternalForceSS(FEShellElement& el, vector<double>& fe) { int i, n; // jacobian matrix determinant double detJt; vec3d gradM, gradMu, gradMd; double Mu, Md; mat3ds s; const double* Mr, *Ms, *M; int nint = el.GaussPoints(); int neln = el.Nodes(); double dt = GetFEModel()->GetTime().timeIncrement; double* gw = el.GaussWeights(); double eta; vec3d gcnt[3]; // repeat for all integration points for (n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); FEElasticMaterialPoint& pt = *(mp.ExtractData<FEElasticMaterialPoint>()); FEBiphasicMaterialPoint& bpt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // calculate the jacobian detJt = detJ(el, n); detJt *= gw[n]; // get the stress vector for this integration point s = pt.m_s; eta = el.gt(n); Mr = el.Hr(n); Ms = el.Hs(n); M = el.H(n); ContraBaseVectors(el, n, gcnt); // get the flux vec3d& w = bpt.m_w; // get the solvent supply double phiwhat = m_pMat->SolventSupply(mp); for (i=0; i<neln; ++i) { gradM = gcnt[0]*Mr[i] + gcnt[1]*Ms[i]; gradMu = (gradM*(1+eta) + gcnt[2]*M[i])/2; gradMd = (gradM*(1-eta) - gcnt[2]*M[i])/2; vec3d fu = s*gradMu; vec3d fd = s*gradMd; Mu = (1+eta)/2*M[i]; Md = (1-eta)/2*M[i]; // calculate internal force // the '-' sign is so that the internal forces get subtracted // from the global residual vector fe[8*i ] -= fu.x*detJt; fe[8*i+1] -= fu.y*detJt; fe[8*i+2] -= fu.z*detJt; fe[8*i+3] -= fd.x*detJt; fe[8*i+4] -= fd.y*detJt; fe[8*i+5] -= fd.z*detJt; fe[8*i+6] -= dt*(w*gradMu + phiwhat*Mu)*detJt; fe[8*i+7] -= dt*(w*gradMd + phiwhat*Md)*detJt; } } } //----------------------------------------------------------------------------- void FEBiphasicShellDomain::StiffnessMatrix(FELinearSystem& LS, bool bsymm) { // repeat over all solid elements int NE = (int)m_Elem.size(); #pragma omp parallel for shared(NE) for (int iel=0; iel<NE; ++iel) { FEShellElement& el = m_Elem[iel]; // element stiffness matrix FEElementMatrix ke(el); int neln = el.Nodes(); int ndof = neln*8; ke.resize(ndof, ndof); // calculate the element stiffness matrix ElementBiphasicStiffness(el, ke, bsymm); vector<int> lm; UnpackLM(el, lm); ke.SetIndices(lm); // assemble element matrix in global stiffness matrix LS.Assemble(ke); } } //----------------------------------------------------------------------------- void FEBiphasicShellDomain::StiffnessMatrixSS(FELinearSystem& LS, bool bsymm) { // repeat over all solid elements int NE = (int)m_Elem.size(); #pragma omp parallel for shared(NE) for (int iel=0; iel<NE; ++iel) { FEShellElement& el = m_Elem[iel]; // element stiffness matrix FEElementMatrix ke(el); int neln = el.Nodes(); int ndof = neln*8; ke.resize(ndof, ndof); // calculate the element stiffness matrix ElementBiphasicStiffnessSS(el, ke, bsymm); vector<int> lm; UnpackLM(el, lm); ke.SetIndices(lm); // assemble element matrix in global stiffness matrix LS.Assemble(ke); } } //----------------------------------------------------------------------------- //! calculates element stiffness matrix for element iel //! bool FEBiphasicShellDomain::ElementBiphasicStiffness(FEShellElement& el, matrix& ke, bool bsymm) { int i, j, n; // jacobian matrix determinant double detJt; const double* Mr, *Ms, *M; int nint = el.GaussPoints(); int neln = el.Nodes(); double dt = GetFEModel()->GetTime().timeIncrement; double tau = m_pMat->m_tau; vector<vec3d> gradMu(neln), gradMd(neln); vector<double> Mu(neln), Md(neln); vec3d gradM; double* gw = el.GaussWeights(); double eta; vec3d gcnt[3]; // zero stiffness matrix ke.zero(); // loop over gauss-points for (n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); FEElasticMaterialPoint& ept = *(mp.ExtractData<FEElasticMaterialPoint >()); FEBiphasicMaterialPoint& pt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // calculate the jacobian detJt = detJ(el, n); detJt *= gw[n]; eta = el.gt(n); Mr = el.Hr(n); Ms = el.Hs(n); M = el.H(n); ContraBaseVectors(el, n, gcnt); for (i=0; i<neln; ++i) { // calculate global gradient of shape functions gradM = gcnt[0]*Mr[i] + gcnt[1]*Ms[i]; gradMu[i] = (gradM*(1+eta) + gcnt[2]*M[i])/2; gradMd[i] = (gradM*(1-eta) - gcnt[2]*M[i])/2; Mu[i] = (1+eta)/2*M[i]; Md[i] = (1-eta)/2*M[i]; } // get the stress mat3ds s = ept.m_s; // get elasticity tensor tens4dmm c = (m_secant_tangent) ? m_pMat->SecantTangent(mp) : m_pMat->Tangent(mp); // get the fluid flux and pressure gradient vec3d gradp = pt.m_gradp + (pt.m_gradp - pt.m_gradpp)*(tau/dt); // evaluate the permeability and its derivatives mat3ds K = m_pMat->Permeability(mp); tens4dmm dKdE = (m_secant_perm_tangent) ? m_pMat->SecantTangent_Permeability_Strain(mp) : m_pMat->Tangent_Permeability_Strain(mp); // evaluate the solvent supply and its derivatives double phiwhat = 0; mat3ds Phie; Phie.zero(); double Phip = 0; if (m_pMat->GetSolventSupply()) { phiwhat = m_pMat->GetSolventSupply()->Supply(mp); Phie = m_pMat->GetSolventSupply()->Tangent_Supply_Strain(mp); Phip = m_pMat->GetSolventSupply()->Tangent_Supply_Pressure(mp); } // Miscellaneous constants mat3dd I(1); // Kuu matrix for (i=0; i<neln; ++i) for (j=0; j<neln; ++j) { mat3d Kuu = (mat3dd(gradMu[i]*(s*gradMu[j])) + vdotTdotv(gradMu[i], c, gradMu[j]))*detJt; mat3d Kud = (mat3dd(gradMu[i]*(s*gradMd[j])) + vdotTdotv(gradMu[i], c, gradMd[j]))*detJt; mat3d Kdu = (mat3dd(gradMd[i]*(s*gradMu[j])) + vdotTdotv(gradMd[i], c, gradMu[j]))*detJt; mat3d Kdd = (mat3dd(gradMd[i]*(s*gradMd[j])) + vdotTdotv(gradMd[i], c, gradMd[j]))*detJt; ke[8*i ][8*j ] += Kuu[0][0]; ke[8*i ][8*j+1] += Kuu[0][1]; ke[8*i ][8*j+2] += Kuu[0][2]; ke[8*i+1][8*j ] += Kuu[1][0]; ke[8*i+1][8*j+1] += Kuu[1][1]; ke[8*i+1][8*j+2] += Kuu[1][2]; ke[8*i+2][8*j ] += Kuu[2][0]; ke[8*i+2][8*j+1] += Kuu[2][1]; ke[8*i+2][8*j+2] += Kuu[2][2]; ke[8*i ][8*j+3] += Kud[0][0]; ke[8*i ][8*j+4] += Kud[0][1]; ke[8*i ][8*j+5] += Kud[0][2]; ke[8*i+1][8*j+3] += Kud[1][0]; ke[8*i+1][8*j+4] += Kud[1][1]; ke[8*i+1][8*j+5] += Kud[1][2]; ke[8*i+2][8*j+3] += Kud[2][0]; ke[8*i+2][8*j+4] += Kud[2][1]; ke[8*i+2][8*j+5] += Kud[2][2]; ke[8*i+3][8*j ] += Kdu[0][0]; ke[8*i+3][8*j+1] += Kdu[0][1]; ke[8*i+3][8*j+2] += Kdu[0][2]; ke[8*i+4][8*j ] += Kdu[1][0]; ke[8*i+4][8*j+1] += Kdu[1][1]; ke[8*i+4][8*j+2] += Kdu[1][2]; ke[8*i+5][8*j ] += Kdu[2][0]; ke[8*i+5][8*j+1] += Kdu[2][1]; ke[8*i+5][8*j+2] += Kdu[2][2]; ke[8*i+3][8*j+3] += Kdd[0][0]; ke[8*i+3][8*j+4] += Kdd[0][1]; ke[8*i+3][8*j+5] += Kdd[0][2]; ke[8*i+4][8*j+3] += Kdd[1][0]; ke[8*i+4][8*j+4] += Kdd[1][1]; ke[8*i+4][8*j+5] += Kdd[1][2]; ke[8*i+5][8*j+3] += Kdd[2][0]; ke[8*i+5][8*j+4] += Kdd[2][1]; ke[8*i+5][8*j+5] += Kdd[2][2]; } // kup matrix for (i=0; i<neln; ++i) for (j=0; j<neln; ++j) { vec3d kup = gradMu[i]*(Mu[j]*detJt); vec3d kuq = gradMu[i]*(Md[j]*detJt); vec3d kdp = gradMd[i]*(Mu[j]*detJt); vec3d kdq = gradMd[i]*(Md[j]*detJt); ke[8*i ][8*j+6] -= kup.x; ke[8*i+1][8*j+6] -= kup.y; ke[8*i+2][8*j+6] -= kup.z; ke[8*i ][8*j+7] -= kuq.x; ke[8*i+1][8*j+7] -= kuq.y; ke[8*i+2][8*j+7] -= kuq.z; ke[8*i+3][8*j+6] -= kdp.x; ke[8*i+4][8*j+6] -= kdp.y; ke[8*i+5][8*j+6] -= kdp.z; ke[8*i+3][8*j+7] -= kdq.x; ke[8*i+4][8*j+7] -= kdq.y; ke[8*i+5][8*j+7] -= kdq.z; } // kpu matrix mat3ds Q = mat3dd(1/dt-phiwhat) - Phie*ept.m_J; for (i=0; i<neln; ++i) for (j=0; j<neln; ++j) { vec3d kpu = (vdotTdotv(gradMu[i], dKdE, gradMu[j])*gradp + Q*(gradMu[j]*Mu[i]))*(detJt*dt); vec3d kpd = (vdotTdotv(gradMu[i], dKdE, gradMd[j])*gradp + Q*(gradMd[j]*Mu[i]))*(detJt*dt); vec3d kqu = (vdotTdotv(gradMd[i], dKdE, gradMu[j])*gradp + Q*(gradMu[j]*Md[i]))*(detJt*dt); vec3d kqd = (vdotTdotv(gradMd[i], dKdE, gradMd[j])*gradp + Q*(gradMd[j]*Md[i]))*(detJt*dt); ke[8*i+6][8*j ] -= kpu.x; ke[8*i+6][8*j+1] -= kpu.y; ke[8*i+6][8*j+2] -= kpu.z; ke[8*i+6][8*j+3] -= kpd.x; ke[8*i+6][8*j+4] -= kpd.y; ke[8*i+6][8*j+5] -= kpd.z; ke[8*i+7][8*j ] -= kqu.x; ke[8*i+7][8*j+1] -= kqu.y; ke[8*i+7][8*j+2] -= kqu.z; ke[8*i+7][8*j+3] -= kqd.x; ke[8*i+7][8*j+4] -= kqd.y; ke[8*i+7][8*j+5] -= kqd.z; } // kpp matrix for (i=0; i<neln; ++i) for (j=0; j<neln; ++j) { double kpp = (gradMu[i]*(K*gradMu[j])*(1+tau/dt) - Phip*Mu[i]*Mu[j])*(detJt*dt); double kpq = (gradMu[i]*(K*gradMd[j])*(1+tau/dt) - Phip*Mu[i]*Md[j])*(detJt*dt); double kqp = (gradMd[i]*(K*gradMu[j])*(1+tau/dt) - Phip*Md[i]*Mu[j])*(detJt*dt); double kqq = (gradMd[i]*(K*gradMd[j])*(1+tau/dt) - Phip*Md[i]*Md[j])*(detJt*dt); ke[8*i+6][8*j+6] -= kpp; ke[8*i+6][8*j+7] -= kpq; ke[8*i+7][8*j+6] -= kqp; ke[8*i+7][8*j+7] -= kqq; } } return true; } //----------------------------------------------------------------------------- //! calculates element stiffness matrix for element iel //! for the steady-state response (zero solid velocity) //! bool FEBiphasicShellDomain::ElementBiphasicStiffnessSS(FEShellElement& el, matrix& ke, bool bsymm) { int i, j, n; // jacobian matrix determinant double detJt; const double* Mr, *Ms, *M; int nint = el.GaussPoints(); int neln = el.Nodes(); double dt = GetFEModel()->GetTime().timeIncrement; vector<vec3d> gradMu(neln), gradMd(neln); vector<double> Mu(neln), Md(neln); vec3d gradM; double* gw = el.GaussWeights(); double eta; vec3d gcnt[3]; // zero stiffness matrix ke.zero(); // loop over gauss-points for (n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); FEElasticMaterialPoint& ept = *(mp.ExtractData<FEElasticMaterialPoint >()); FEBiphasicMaterialPoint& pt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // calculate the jacobian detJt = detJ(el, n); detJt *= gw[n]; eta = el.gt(n); Mr = el.Hr(n); Ms = el.Hs(n); M = el.H(n); ContraBaseVectors(el, n, gcnt); for (i=0; i<neln; ++i) { // calculate global gradient of shape functions gradM = gcnt[0]*Mr[i] + gcnt[1]*Ms[i]; gradMu[i] = (gradM*(1+eta) + gcnt[2]*M[i])/2; gradMd[i] = (gradM*(1-eta) - gcnt[2]*M[i])/2; Mu[i] = (1+eta)/2*M[i]; Md[i] = (1-eta)/2*M[i]; } // get the stress mat3ds s = ept.m_s; // get elasticity tensor tens4dmm c = (m_secant_tangent) ? m_pMat->SecantTangent(mp) : m_pMat->Tangent(mp); // get the fluid flux and pressure gradient vec3d gradp = pt.m_gradp; // evaluate the permeability and its derivatives mat3ds K = m_pMat->Permeability(mp); tens4dmm dKdE = (m_secant_perm_tangent) ? m_pMat->SecantTangent_Permeability_Strain(mp) : m_pMat->Tangent_Permeability_Strain(mp); // evaluate the solvent supply and its derivatives double phiwhat = 0; mat3ds Phie; Phie.zero(); double Phip = 0; if (m_pMat->GetSolventSupply()) { phiwhat = m_pMat->GetSolventSupply()->Supply(mp); Phie = m_pMat->GetSolventSupply()->Tangent_Supply_Strain(mp); Phip = m_pMat->GetSolventSupply()->Tangent_Supply_Pressure(mp); } // Miscellaneous constants mat3dd I(1); // Kuu matrix for (i=0; i<neln; ++i) for (j=0; j<neln; ++j) { mat3d Kuu = (mat3dd(gradMu[i]*(s*gradMu[j])) + vdotTdotv(gradMu[i], c, gradMu[j]))*detJt; mat3d Kud = (mat3dd(gradMu[i]*(s*gradMd[j])) + vdotTdotv(gradMu[i], c, gradMd[j]))*detJt; mat3d Kdu = (mat3dd(gradMd[i]*(s*gradMu[j])) + vdotTdotv(gradMd[i], c, gradMu[j]))*detJt; mat3d Kdd = (mat3dd(gradMd[i]*(s*gradMd[j])) + vdotTdotv(gradMd[i], c, gradMd[j]))*detJt; ke[8*i ][8*j ] += Kuu[0][0]; ke[8*i ][8*j+1] += Kuu[0][1]; ke[8*i ][8*j+2] += Kuu[0][2]; ke[8*i+1][8*j ] += Kuu[1][0]; ke[8*i+1][8*j+1] += Kuu[1][1]; ke[8*i+1][8*j+2] += Kuu[1][2]; ke[8*i+2][8*j ] += Kuu[2][0]; ke[8*i+2][8*j+1] += Kuu[2][1]; ke[8*i+2][8*j+2] += Kuu[2][2]; ke[8*i ][8*j+3] += Kud[0][0]; ke[8*i ][8*j+4] += Kud[0][1]; ke[8*i ][8*j+5] += Kud[0][2]; ke[8*i+1][8*j+3] += Kud[1][0]; ke[8*i+1][8*j+4] += Kud[1][1]; ke[8*i+1][8*j+5] += Kud[1][2]; ke[8*i+2][8*j+3] += Kud[2][0]; ke[8*i+2][8*j+4] += Kud[2][1]; ke[8*i+2][8*j+5] += Kud[2][2]; ke[8*i+3][8*j ] += Kdu[0][0]; ke[8*i+3][8*j+1] += Kdu[0][1]; ke[8*i+3][8*j+2] += Kdu[0][2]; ke[8*i+4][8*j ] += Kdu[1][0]; ke[8*i+4][8*j+1] += Kdu[1][1]; ke[8*i+4][8*j+2] += Kdu[1][2]; ke[8*i+5][8*j ] += Kdu[2][0]; ke[8*i+5][8*j+1] += Kdu[2][1]; ke[8*i+5][8*j+2] += Kdu[2][2]; ke[8*i+3][8*j+3] += Kdd[0][0]; ke[8*i+3][8*j+4] += Kdd[0][1]; ke[8*i+3][8*j+5] += Kdd[0][2]; ke[8*i+4][8*j+3] += Kdd[1][0]; ke[8*i+4][8*j+4] += Kdd[1][1]; ke[8*i+4][8*j+5] += Kdd[1][2]; ke[8*i+5][8*j+3] += Kdd[2][0]; ke[8*i+5][8*j+4] += Kdd[2][1]; ke[8*i+5][8*j+5] += Kdd[2][2]; } // kup matrix for (i=0; i<neln; ++i) for (j=0; j<neln; ++j) { vec3d kup = gradMu[i]*(Mu[j]*detJt); vec3d kuq = gradMu[i]*(Md[j]*detJt); vec3d kdp = gradMd[i]*(Mu[j]*detJt); vec3d kdq = gradMd[i]*(Md[j]*detJt); ke[8*i ][8*j+6] -= kup.x; ke[8*i+1][8*j+6] -= kup.y; ke[8*i+2][8*j+6] -= kup.z; ke[8*i ][8*j+7] -= kuq.x; ke[8*i+1][8*j+7] -= kuq.y; ke[8*i+2][8*j+7] -= kuq.z; ke[8*i+3][8*j+6] -= kdp.x; ke[8*i+4][8*j+6] -= kdp.y; ke[8*i+5][8*j+6] -= kdp.z; ke[8*i+3][8*j+7] -= kdq.x; ke[8*i+4][8*j+7] -= kdq.y; ke[8*i+5][8*j+7] -= kdq.z; } // kpu matrix mat3ds Q = mat3dd(-phiwhat) - Phie*ept.m_J; for (i=0; i<neln; ++i) for (j=0; j<neln; ++j) { vec3d kpu = (vdotTdotv(gradMu[i], dKdE, gradMu[j])*gradp + Q*(gradMu[j]*Mu[i]))*(detJt*dt); vec3d kpd = (vdotTdotv(gradMu[i], dKdE, gradMd[j])*gradp + Q*(gradMd[j]*Mu[i]))*(detJt*dt); vec3d kqu = (vdotTdotv(gradMd[i], dKdE, gradMu[j])*gradp + Q*(gradMu[j]*Md[i]))*(detJt*dt); vec3d kqd = (vdotTdotv(gradMd[i], dKdE, gradMd[j])*gradp + Q*(gradMd[j]*Md[i]))*(detJt*dt); ke[8*i+6][8*j ] -= kpu.x; ke[8*i+6][8*j+1] -= kpu.y; ke[8*i+6][8*j+2] -= kpu.z; ke[8*i+6][8*j+3] -= kpd.x; ke[8*i+6][8*j+4] -= kpd.y; ke[8*i+6][8*j+5] -= kpd.z; ke[8*i+7][8*j ] -= kqu.x; ke[8*i+7][8*j+1] -= kqu.y; ke[8*i+7][8*j+2] -= kqu.z; ke[8*i+7][8*j+3] -= kqd.x; ke[8*i+7][8*j+4] -= kqd.y; ke[8*i+7][8*j+5] -= kqd.z; } // kpp matrix for (i=0; i<neln; ++i) for (j=0; j<neln; ++j) { double kpp = (gradMu[i]*(K*gradMu[j]) - Phip*Mu[i]*Mu[j])*(detJt*dt); double kpq = (gradMu[i]*(K*gradMd[j]) - Phip*Mu[i]*Mu[j])*(detJt*dt); double kqp = (gradMd[i]*(K*gradMu[j]) - Phip*Md[i]*Mu[j])*(detJt*dt); double kqq = (gradMd[i]*(K*gradMd[j]) - Phip*Md[i]*Md[j])*(detJt*dt); ke[8*i+6][8*j+6] -= kpp; ke[8*i+6][8*j+7] -= kpq; ke[8*i+7][8*j+6] -= kqp; ke[8*i+7][8*j+7] -= kqq; } } return true; } //----------------------------------------------------------------------------- void FEBiphasicShellDomain::Update(const FETimeInfo& tp) { FESSIShellDomain::Update(tp); bool berr = false; int NE = (int) m_Elem.size(); #pragma omp parallel for shared(NE, berr) for (int i=0; i<NE; ++i) { try { UpdateElementStress(i); } catch (NegativeJacobian e) { #pragma omp critical { berr = true; if (e.DoOutput()) feLogError(e.what()); } } } if (berr) throw NegativeJacobianDetected(); } //----------------------------------------------------------------------------- void FEBiphasicShellDomain::UpdateElementStress(int iel) { double dt = GetFEModel()->GetTime().timeIncrement; // get the solid element FEShellElement& el = m_Elem[iel]; // get the number of integration points int nint = el.GaussPoints(); // get the number of nodes int neln = el.Nodes(); // get the nodal data FEMesh& mesh = *m_pMesh; vec3d r0[FEElement::MAX_NODES]; vec3d rt[FEElement::MAX_NODES]; double pn[FEElement::MAX_NODES]; double qn[FEElement::MAX_NODES]; for (int j=0; j<neln; ++j) { r0[j] = mesh.Node(el.m_node[j]).m_r0; rt[j] = mesh.Node(el.m_node[j]).m_rt; pn[j] = mesh.Node(el.m_node[j]).get(m_dofP); qn[j] = mesh.Node(el.m_node[j]).get(m_dofQ); } // loop over the integration points and calculate // the stress at the integration point for (int n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); FEElasticMaterialPoint& pt = *(mp.ExtractData<FEElasticMaterialPoint>()); // material point coordinates // TODO: I'm not entirly happy with this solution // since the material point coordinates are used by most materials. mp.m_r0 = el.Evaluate(r0, n); mp.m_rt = el.Evaluate(rt, n); // get the deformation gradient and determinant pt.m_J = defgrad(el, pt.m_F, n); mat3d Fp; defgradp(el, Fp, n); mat3d Fi = pt.m_F.inverse(); pt.m_L = (pt.m_F - Fp)*Fi / dt; // biphasic data FEBiphasicMaterialPoint& ppt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // evaluate fluid pressure at gauss-point ppt.m_p = evaluate(el, pn, qn, n); // calculate the gradient of p at gauss-point ppt.m_gradp = gradient(el, pn, qn, n); // for biphasic materials also update the fluid flux // ppt.m_w = m_pMat->Flux(mp); ppt.m_w = FluidFlux(mp); ppt.m_pa = m_pMat->Pressure(mp); // update specialized material points m_pMat->UpdateSpecializedMaterialPoints(mp, GetFEModel()->GetTime()); // calculate the solid stress at this material point ppt.m_ss = (m_secant_stress) ? m_pMat->GetElasticMaterial()->SecantStress(mp) : m_pMat->GetElasticMaterial()->Stress(mp); // calculate the stress at this material point pt.m_s = (m_secant_stress) ? m_pMat->SecantStress(mp) : m_pMat->Stress(mp); } } //----------------------------------------------------------------------------- void FEBiphasicShellDomain::BodyForce(FEGlobalVector& R, FEBodyForce& BF) { int NE = (int)m_Elem.size(); #pragma omp parallel for for (int i=0; i<NE; ++i) { vector<double> fe; vector<int> lm; // get the element FEShellElement& el = m_Elem[i]; // get the element force vector and initialize it to zero int ndof = 8*el.Nodes(); fe.assign(ndof, 0); // apply body forces ElementBodyForce(BF, el, fe); // get the element's LM vector UnpackLM(el, lm); // assemble element 'fe'-vector into global R vector R.Assemble(el.m_node, lm, fe, true); } } //----------------------------------------------------------------------------- //! calculates the body forces void FEBiphasicShellDomain::ElementBodyForce(FEBodyForce& BF, FEShellElement& el, vector<double>& fe) { // get true solid and fluid densities double rhoTw = m_pMat->FluidDensity(); // jacobian double detJt, eta; double *M; double* gw = el.GaussWeights(); vec3d b, fu, fd; // number of nodes int neln = el.Nodes(); // nodal coordinates vec3d r0[FEElement::MAX_NODES], rt[FEElement::MAX_NODES]; for (int i=0; i<neln; ++i) { r0[i] = m_pMesh->Node(el.m_node[i]).m_r0; rt[i] = m_pMesh->Node(el.m_node[i]).m_rt; } // loop over integration points int nint = el.GaussPoints(); for (int n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); mp.m_r0 = el.Evaluate(r0, n); mp.m_rt = el.Evaluate(rt, n); detJt = detJ(el, n)*gw[n]; // get the force b = BF.force(mp); eta = el.gt(n); // evaluate apparent solid and fluid densities and mixture density double phiw = m_pMat->Porosity(mp); double rhos = (1-phiw)*m_pMat->SolidDensity(mp); double rhow = phiw*rhoTw; double rho = rhos + rhow; M = el.H(n); for (int i=0; i<neln; ++i) { fu = b*(rho*(1+eta)/2*M[i]*detJt); fd = b*(rho*(1-eta)/2*M[i]*detJt); fe[8*i ] -= fu.x; fe[8*i+1] -= fu.y; fe[8*i+2] -= fu.z; fe[8*i+3] -= fd.x; fe[8*i+4] -= fd.y; fe[8*i+5] -= fd.z; } } } //----------------------------------------------------------------------------- void FEBiphasicShellDomain::BodyForceStiffness(FELinearSystem& LS, FEBodyForce& bf) { FEBiphasic* pmb = dynamic_cast<FEBiphasic*>(GetMaterial()); assert(pmb); // element stiffness matrix vector<int> lm; // repeat over all solid elements int NE = (int)m_Elem.size(); for (int iel=0; iel<NE; ++iel) { FEShellElement& el = m_Elem[iel]; // create the element's stiffness matrix FEElementMatrix ke(el); int neln = el.Nodes(); int ndof = 8*neln; ke.resize(ndof, ndof); ke.zero(); // calculate inertial stiffness ElementBodyForceStiffness(bf, el, ke); // get the element's LM vector UnpackLM(el, lm); ke.SetIndices(lm); // assemble element matrix in global stiffness matrix LS.Assemble(ke); } } //----------------------------------------------------------------------------- //! This function calculates the stiffness due to body forces void FEBiphasicShellDomain::ElementBodyForceStiffness(FEBodyForce& BF, FEShellElement &el, matrix &ke) { int neln = el.Nodes(); double dt = GetFEModel()->GetTime().timeIncrement; // get true solid and fluid densities double rhoTw = m_pMat->FluidDensity(); // jacobian double detJt; const double* Mr, *Ms, *M; vector<vec3d> gradMu(neln), gradMd(neln); vector<double> Mu(neln), Md(neln); vec3d gradM; double* gw = el.GaussWeights(); double eta; vec3d gcnt[3]; vec3d b; mat3d gradb; mat3d Kuu, Kud, Kdu, Kdd; vec3d kpu, kpd, kqu, kqd; // loop over integration points int nint = el.GaussPoints(); for (int n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); // get the body force b = BF.force(mp); // get the body force stiffness gradb = BF.stiffness(mp); // evaluate apparent solid and fluid densities and mixture density double phiw = m_pMat->Porosity(mp); double rhos = (1-phiw)*m_pMat->SolidDensity(mp); double rhow = phiw*rhoTw; double rho = rhos + rhow; // evaluate the permeability and its derivatives mat3ds K = m_pMat->Permeability(mp); tens4dmm dKdE = m_pMat->Tangent_Permeability_Strain(mp); // calculate the jacobian detJt = detJ(el, n); detJt *= gw[n]; eta = el.gt(n); Mr = el.Hr(n); Ms = el.Hs(n); M = el.H(n); ContraBaseVectors(el, n, gcnt); for (int i=0; i<neln; ++i) { // calculate global gradient of shape functions gradM = gcnt[0]*Mr[i] + gcnt[1]*Ms[i]; gradMu[i] = (gradM*(1+eta) + gcnt[2]*M[i])/2; gradMd[i] = (gradM*(1-eta) - gcnt[2]*M[i])/2; Mu[i] = (1+eta)/2*M[i]; Md[i] = (1-eta)/2*M[i]; } for (int i=0; i<neln; ++i) for (int j=0; j<neln; ++j) { Kuu = (gradb*(Mu[j]*rho) + (b & gradMu[j])*rhoTw)*(Mu[i]*detJt); Kud = (gradb*(Md[j]*rho) + (b & gradMd[j])*rhoTw)*(Mu[i]*detJt); Kdu = (gradb*(Mu[j]*rho) + (b & gradMu[j])*rhoTw)*(Md[i]*detJt); Kdd = (gradb*(Md[j]*rho) + (b & gradMd[j])*rhoTw)*(Md[i]*detJt); ke[8*i ][8*j ] += Kuu(0,0); ke[8*i ][8*j+1] += Kuu(0,1); ke[8*i ][8*j+2] += Kuu(0,2); ke[8*i+1][8*j ] += Kuu(1,0); ke[8*i+1][8*j+1] += Kuu(1,1); ke[8*i+1][8*j+2] += Kuu(1,2); ke[8*i+2][8*j ] += Kuu(2,0); ke[8*i+2][8*j+1] += Kuu(2,1); ke[8*i+2][8*j+2] += Kuu(2,2); ke[8*i ][8*j+3] += Kud(0,0); ke[8*i ][8*j+4] += Kud(0,1); ke[8*i ][8*j+5] += Kud(0,2); ke[8*i+1][8*j+3] += Kud(1,0); ke[8*i+1][8*j+4] += Kud(1,1); ke[8*i+1][8*j+5] += Kud(1,2); ke[8*i+2][8*j+3] += Kud(2,0); ke[8*i+2][8*j+4] += Kud(2,1); ke[8*i+2][8*j+5] += Kud(2,2); ke[8*i+3][8*j ] += Kdu(0,0); ke[8*i+3][8*j+1] += Kdu(0,1); ke[8*i+3][8*j+2] += Kdu(0,2); ke[8*i+4][8*j ] += Kdu(1,0); ke[8*i+4][8*j+1] += Kdu(1,1); ke[8*i+4][8*j+2] += Kdu(1,2); ke[8*i+5][8*j ] += Kdu(2,0); ke[8*i+5][8*j+1] += Kdu(2,1); ke[8*i+5][8*j+2] += Kdu(2,2); ke[8*i+3][8*j+3] += Kdd(0,0); ke[8*i+3][8*j+4] += Kdd(0,1); ke[8*i+3][8*j+5] += Kdd(0,2); ke[8*i+4][8*j+3] += Kdd(1,0); ke[8*i+4][8*j+4] += Kdd(1,1); ke[8*i+4][8*j+5] += Kdd(1,2); ke[8*i+5][8*j+3] += Kdd(2,0); ke[8*i+5][8*j+4] += Kdd(2,1); ke[8*i+5][8*j+5] += Kdd(2,2); kpu = (vdotTdotv(gradMu[i], dKdE, gradMu[j])*b + ((b & gradMu[j]) + gradb*Mu[j])*K*gradMu[i])*(rhoTw*detJt*dt); kpd = (vdotTdotv(gradMu[i], dKdE, gradMd[j])*b + ((b & gradMd[j]) + gradb*Md[j])*K*gradMu[i])*(rhoTw*detJt*dt); kqu = (vdotTdotv(gradMd[i], dKdE, gradMu[j])*b + ((b & gradMu[j]) + gradb*Mu[j])*K*gradMd[i])*(rhoTw*detJt*dt); kqd = (vdotTdotv(gradMd[i], dKdE, gradMd[j])*b + ((b & gradMd[j]) + gradb*Md[j])*K*gradMd[i])*(rhoTw*detJt*dt); ke[8*i+6][8*j ] -= kpu.x; ke[8*i+6][8*j+1] -= kpu.y; ke[8*i+6][8*j+2] -= kpu.z; ke[8*i+6][8*j+3] -= kpd.x; ke[8*i+6][8*j+4] -= kpd.y; ke[8*i+6][8*j+5] -= kpd.z; ke[8*i+7][8*j ] -= kqu.x; ke[8*i+7][8*j+1] -= kqu.y; ke[8*i+7][8*j+2] -= kqu.z; ke[8*i+7][8*j+3] -= kqd.x; ke[8*i+7][8*j+4] -= kqd.y; ke[8*i+7][8*j+5] -= kqd.z; } } } //----------------------------------------------------------------------------- vec3d FEBiphasicShellDomain::FluidFlux(FEMaterialPoint& mp) { FEBiphasicMaterialPoint& ppt = *mp.ExtractData<FEBiphasicMaterialPoint>(); // pressure gradient vec3d gradp = ppt.m_gradp; // fluid flux w = -k*grad(p) mat3ds kt = m_pMat->Permeability(mp); vec3d w = -(kt*gradp); // get true fluid density double rhoTw = m_pMat->FluidDensity(); // body force contribution FEModel& fem = *m_pMat->GetFEModel(); int nbf = fem.ModelLoads(); if (nbf) { vec3d b(0,0,0); for (int i=0; i<nbf; ++i) { FEBodyForce* pbf = dynamic_cast<FEBodyForce*>(fem.ModelLoad(i)); if (pbf && pbf->IsActive()) { // negate b because body forces are defined with a negative sign in FEBio b -= pbf->force(mp); } } w += (kt*b)*(rhoTw); } // active momentum supply contribution FEActiveMomentumSupply* pAmom = m_pMat->GetActiveMomentumSupply(); if (pAmom) { vec3d pw = pAmom->ActiveSupply(mp); w += kt*pw; } return w; }
C++
3D
febiosoftware/FEBio
FEBioMix/FEOsmoticCoefficient.cpp
.cpp
1,331
31
/*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 "FEOsmoticCoefficient.h"
C++
3D
febiosoftware/FEBio
FEBioMix/FESFDSBM.cpp
.cpp
12,700
496
/*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 "FESFDSBM.h" #include "FEMultiphasic.h" #include <FECore/log.h> // The following file contains the integration points and weights // for the integration over a unit sphere in spherical coordinates #include "FEBioMech/geodesic.h" #ifndef SQR #define SQR(x) ((x)*(x)) #endif // we store the cos and sin of the angles here int FESFDSBM::m_nres = 0; double FESFDSBM::m_cth[NSTH]; double FESFDSBM::m_sth[NSTH]; double FESFDSBM::m_cph[NSTH]; double FESFDSBM::m_sph[NSTH]; double FESFDSBM::m_w[NSTH]; // define the material parameters BEGIN_FECORE_CLASS(FESFDSBM, FEElasticMaterial) ADD_PARAMETER(m_alpha, FE_RANGE_GREATER_OR_EQUAL(0.0), "alpha"); ADD_PARAMETER(m_beta , FE_RANGE_GREATER_OR_EQUAL(2.0), "beta"); ADD_PARAMETER(m_ksi0 , FE_RANGE_GREATER_OR_EQUAL(0.0), "ksi0" ); ADD_PARAMETER(m_rho0 , FE_RANGE_GREATER_OR_EQUAL(0.0), "rho0" ); ADD_PARAMETER(m_g , FE_RANGE_GREATER_OR_EQUAL(0.0), "gamma"); ADD_PARAMETER(m_sbm , "sbm")->setEnums("$(sbms)"); ADD_PROPERTY(m_Q, "mat_axis")->SetFlags(FEProperty::Optional); END_FECORE_CLASS(); //----------------------------------------------------------------------------- // FESphericalFiberDistribution //----------------------------------------------------------------------------- bool FESFDSBM::Init() { if (FEElasticMaterial::Init() == false) return false; // get the parent material which must be a multiphasic material FEMultiphasic* pMP = dynamic_cast<FEMultiphasic*> (GetAncestor()); if (pMP == 0) { feLogError("Parent material must be multiphasic"); return false; } // extract the local id of the SBM whose density controls Young's modulus from the global id m_lsbm = pMP->FindLocalSBMID(m_sbm); if (m_lsbm == -1) { feLogError("Invalid value for sbm"); return false; } return true; } //----------------------------------------------------------------------------- mat3ds FESFDSBM::Stress(FEMaterialPoint& mp) { FEElasticMaterialPoint& pt = *mp.ExtractData<FEElasticMaterialPoint>(); FESolutesMaterialPoint& spt = *mp.ExtractData<FESolutesMaterialPoint>(); // deformation gradient mat3d &F = pt.m_F; double J = pt.m_J; // get the local coordinate systems mat3d Q = GetLocalCS(mp); // loop over all integration points vec3d n0e, n0a, n0q, nt; double In, Wl; const double eps = 0; mat3ds s; s.zero(); // calculate material coefficients double alpha = m_alpha; double beta = m_beta; double rhor = spt.m_sbmr[m_lsbm]; double ksi = FiberModulus(rhor); const int nint = 45; for (int n=0; n<nint; ++n) { // set the global fiber direction in material coordinate system n0a.x = XYZ2[n][0]; n0a.y = XYZ2[n][1]; n0a.z = XYZ2[n][2]; double wn = XYZ2[n][3]; // --- quadrant 1,1,1 --- // rotate to reference configuration n0e = Q*n0a; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy derivative Wl = beta*ksi*pow(In - 1.0, beta-1.0)*exp(alpha*pow(In - 1.0, beta)); // calculate the stress s += dyad(nt)*(Wl*wn); } // --- quadrant -1,1,1 --- n0q = vec3d(-n0a.x, n0a.y, n0a.z); // rotate to reference configuration n0e = Q*n0q; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy derivative Wl = beta*ksi*pow(In - 1.0, beta-1.0)*exp(alpha*pow(In - 1.0, beta)); // calculate the stress s += dyad(nt)*(Wl*wn); } // --- quadrant -1,-1,1 --- n0q = vec3d(-n0a.x, -n0a.y, n0a.z); // rotate to reference configuration n0e = Q*n0q; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy derivative Wl = beta*ksi*pow(In - 1.0, beta-1.0)*exp(alpha*pow(In - 1.0, beta)); // calculate the stress s += dyad(nt)*(Wl*wn); } // --- quadrant 1,-1,1 --- n0q = vec3d(n0a.x, -n0a.y, n0a.z); // rotate to reference configuration n0e = Q*n0q; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy derivative Wl = beta*ksi*pow(In - 1.0, beta-1.0)*exp(alpha*pow(In - 1.0, beta)); // calculate the stress s += dyad(nt)*(Wl*wn); } } // we multiply by two to add contribution from other half-sphere return s*(4.0/J); } //----------------------------------------------------------------------------- tens4ds FESFDSBM::Tangent(FEMaterialPoint& mp) { FEElasticMaterialPoint& pt = *mp.ExtractData<FEElasticMaterialPoint>(); FESolutesMaterialPoint& spt = *mp.ExtractData<FESolutesMaterialPoint>(); // deformation gradient mat3d &F = pt.m_F; double J = pt.m_J; // get the local coordinate systems mat3d Q = GetLocalCS(mp); // loop over all integration points vec3d n0e, n0a, n0q, nt; double In, Wll; const double eps = 0; tens4ds cf, cfw; cf.zero(); mat3ds N2; tens4ds N4; tens4ds c; c.zero(); // calculate material coefficients double alpha = m_alpha; double beta = m_beta; double rhor = spt.m_sbmr[m_lsbm]; double ksi = FiberModulus(rhor); const int nint = 45; for (int n=0; n<nint; ++n) { // set the global fiber direction in material coordinate system n0a.x = XYZ2[n][0]; n0a.y = XYZ2[n][1]; n0a.z = XYZ2[n][2]; double wn = XYZ2[n][3]; // --- quadrant 1,1,1 --- // rotate to reference configuration n0e = Q*n0a; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy derivative double pIn = alpha*pow(In - 1.0,beta); Wll = beta*ksi*pow(In - 1.0, beta-2.0)*(beta*pIn+beta-1.0)*exp(pIn); N2 = dyad(nt); N4 = dyad1s(N2); c += N4*(Wll*wn); } // --- quadrant -1,1,1 --- n0q = vec3d(-n0a.x, n0a.y, n0a.z); // rotate to reference configuration n0e = Q*n0q; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy derivative double pIn = alpha*pow(In - 1.0,beta); Wll = beta*ksi*pow(In - 1.0, beta-2.0)*(beta*pIn+beta-1.0)*exp(pIn); N2 = dyad(nt); N4 = dyad1s(N2); c += N4*(Wll*wn); } // --- quadrant -1,-1,1 --- n0q = vec3d(-n0a.x, -n0a.y, n0a.z); // rotate to reference configuration n0e = Q*n0q; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy derivative double pIn = alpha*pow(In - 1.0,beta); Wll = beta*ksi*pow(In - 1.0, beta-2.0)*(beta*pIn+beta-1.0)*exp(pIn); N2 = dyad(nt); N4 = dyad1s(N2); c += N4*(Wll*wn); } // --- quadrant 1,-1,1 --- n0q = vec3d(n0a.x, -n0a.y, n0a.z); // rotate to reference configuration n0e = Q*n0q; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy derivative double pIn = alpha*pow(In - 1.0,beta); Wll = beta*ksi*pow(In - 1.0, beta-2.0)*(beta*pIn+beta-1.0)*exp(pIn); N2 = dyad(nt); N4 = dyad1s(N2); c += N4*(Wll*wn); } } // multiply by two to integrate over other half of sphere return c*(2.0*4.0/J); } //----------------------------------------------------------------------------- double FESFDSBM::StrainEnergyDensity(FEMaterialPoint& mp) { FEElasticMaterialPoint& pt = *mp.ExtractData<FEElasticMaterialPoint>(); FESolutesMaterialPoint& spt = *mp.ExtractData<FESolutesMaterialPoint>(); // deformation gradient mat3d &F = pt.m_F; // get the local coordinate systems mat3d Q = GetLocalCS(mp); // loop over all integration points vec3d n0e, n0a, n0q, nt; double In, W; const double eps = 0; double sed = 0.0; // calculate material coefficients double alpha = m_alpha; double beta = m_beta; double rhor = spt.m_sbmr[m_lsbm]; double ksi = FiberModulus(rhor); const int nint = 45; for (int n=0; n<nint; ++n) { // set the global fiber direction in material coordinate system n0a.x = XYZ2[n][0]; n0a.y = XYZ2[n][1]; n0a.z = XYZ2[n][2]; double wn = XYZ2[n][3]; // --- quadrant 1,1,1 --- // rotate to reference configuration n0e = Q*n0a; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy density if (m_alpha > 0) W = ksi/m_alpha*(exp(alpha*pow(In - 1.0, beta))-1); else W = ksi*pow(In - 1.0, beta); // add to total sed sed += W*wn; } // --- quadrant -1,1,1 --- n0q = vec3d(-n0a.x, n0a.y, n0a.z); // rotate to reference configuration n0e = Q*n0q; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy density if (m_alpha > 0) W = ksi/m_alpha*(exp(alpha*pow(In - 1.0, beta))-1); else W = ksi*pow(In - 1.0, beta); // add to total sed sed += W*wn; } // --- quadrant -1,-1,1 --- n0q = vec3d(-n0a.x, -n0a.y, n0a.z); // rotate to reference configuration n0e = Q*n0q; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy density if (m_alpha > 0) W = ksi/m_alpha*(exp(alpha*pow(In - 1.0, beta))-1); else W = ksi*pow(In - 1.0, beta); // add to total sed sed += W*wn; } // --- quadrant 1,-1,1 --- n0q = vec3d(n0a.x, -n0a.y, n0a.z); // rotate to reference configuration n0e = Q*n0q; // get the global spatial fiber direction in current configuration nt = F*n0e; // Calculate In = n0e*C*n0e In = nt*nt; // only take fibers in tension into consideration if (In > 1. + eps) { // calculate strain energy density if (m_alpha > 0) W = ksi/m_alpha*(exp(alpha*pow(In - 1.0, beta))-1); else W = ksi*pow(In - 1.0, beta); // add to total sed sed += W*wn; } } // we multiply by two to add contribution from other half-sphere return sed*2.0; }
C++
3D
febiosoftware/FEBio
FEBioMix/FESolutePointSource.cpp
.cpp
15,762
525
/*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 "FESolutePointSource.h" #include "FESolute.h" #include "FEMultiphasic.h" #include <FECore/FEModel.h> #include <FECore/FESolidDomain.h> #include <FECore/FEElemElemList.h> #include <algorithm> #include <FEBioMech/FEElasticMaterialPoint.h> #include <iostream> #include <unordered_set> #include <unordered_map> #include <FECore/FEAnalysis.h> BEGIN_FECORE_CLASS(FESolutePointSource, FEBodyLoad) ADD_PARAMETER(m_soluteId, "solute"); ADD_PARAMETER(m_rate, "rate"); ADD_PARAMETER(m_pos.x, "x"); ADD_PARAMETER(m_pos.y, "y"); ADD_PARAMETER(m_pos.z, "z"); END_FECORE_CLASS(); FESolutePointSource::FESolutePointSource(FEModel* fem) : FEBodyLoad(fem), m_search(&fem->GetMesh()) { m_dofC = -1; m_soluteId = -1; m_pos = vec3d(0, 0, 0); m_rate = 0.0; } vec3d FESolutePointSource::GetPosition() const { return m_pos; } void FESolutePointSource::SetPosition(const vec3d& pos) { m_pos = pos; } int FESolutePointSource::GetSoluteID() const { return m_soluteId; } void FESolutePointSource::SetSoluteID(int soluteID) { m_soluteId = soluteID; } double FESolutePointSource::GetRate() const { return m_rate; } void FESolutePointSource::SetRate(double rate) { m_rate = rate; } double FESolutePointSource::GetdC() const { return m_dC; } double FESolutePointSource::GetdCp() const { return m_dCp; } void FESolutePointSource::SetdC(double dC) { m_dC = dC; } void FESolutePointSource::SetdCp(double dCp) { m_dCp = dCp; } void FESolutePointSource::SetRadius(double radius) { m_radius = radius; m_Vc = (4.0 / 3.0) * PI * pow(m_radius, 3.0); } void FESolutePointSource::SetAccumulateFlag(bool b) { m_accumulate = b; } void FESolutePointSource::SetAccumulateCAFlag(bool b) { m_accumulate_ca = b; } bool FESolutePointSource::Init() { // see if the solute exists FEModel* fem = GetFEModel(); bool bfound = false; int ndata = fem->GlobalDataItems(); for (int i=0; i<ndata; ++i) { FESoluteData* soluteData = dynamic_cast<FESoluteData*>(fem->GetGlobalData(i)); if (soluteData && (soluteData->GetID() == m_soluteId)) { bfound = true; break; } } if (bfound == false) return false; // initialize octree search if (m_search.Init() == false) return false; // get the degree of freedom of the concentration m_dofC = fem->GetDOFIndex("concentration", m_soluteId - 1); m_el = dynamic_cast<FESolidElement*>(m_search.FindElement(m_pos, m_q)); return FEBodyLoad::Init(); } // allow species to accumulate at the point source void FESolutePointSource::Accumulate(double dc) { // find the element in which the point lies m_el = dynamic_cast<FESolidElement*>(m_search.FindElement(m_pos, m_q)); if (m_el == nullptr) return; // make sure this element is part of a multiphasic domain FEDomain* dom = dynamic_cast<FEDomain*>(m_el->GetMeshPartition()); FEMultiphasic* mat = dynamic_cast<FEMultiphasic*>(dom->GetMaterial()); if (mat == nullptr) return; // Make sure the material has the correct solute int solid = -1; int sols = mat->Solutes(); for (int j = 0; j < sols; ++j) { int solj = mat->GetSolute(j)->GetSoluteID(); if (solj == m_soluteId) { solid = j; break; } } if (solid == -1) return; m_rate = dc + m_rate; m_accumulate = true; } void FESolutePointSource::Update() { if (m_accumulate) { // find the element in which the point lies m_el = dynamic_cast<FESolidElement*>(m_search.FindElement(m_pos, m_q)); if (m_el == nullptr) return; // make sure this element is part of a multiphasic domain FESolidDomain* dom = dynamic_cast<FESolidDomain*>(m_el->GetMeshPartition()); FEMultiphasic* mat = dynamic_cast<FEMultiphasic*>(dom->GetMaterial()); if (mat == nullptr) return; // calculate the element volume FEMesh* mesh = dom->GetMesh(); double Ve = mesh->ElementVolume(*m_el); std::cout << "rate is " << m_rate << endl; int solid = -1; int sols = mat->Solutes(); for (int j = 0; j < sols; ++j) { int solj = mat->GetSolute(j)->GetSoluteID(); if (solj == m_soluteId) { solid = j; break; } } if (solid == -1) return; // evaluate the concentration at this point int neln = m_el->Nodes(); double c[FEElement::MAX_NODES]; for (int i = 0; i < neln; ++i) c[i] = mesh->Node(m_el->m_node[i]).get(m_dofC); double cx = m_el->evaluate(c, m_q[0], m_q[1], m_q[2]); double dt = mesh->GetFEModel()->GetCurrentStep()->m_dt; double cxx = cx * Ve + dt * m_rate; // assemble the element load vector vector<double> fe(neln, 0.0); vector<int> lm(neln, -1); std::vector<FEElement*> possible_nodes; double total_elem = 0.0; FindNodesInRadius(possible_nodes, total_elem); double total_change = 0.0; //SL: Currently this just assigns within the current element. We will instead want this to assign to the closest integration points. if (possible_nodes.size() == 0) { // set the concentration of all nodes via the shape functions for each integration point double H[FEElement::MAX_NODES]; m_el->shape_fnc(H, m_q[0], m_q[1], m_q[2]); int nint = m_el->GaussPoints(); double* w = m_el->GaussWeights(); for (int n = 0; n < nint; ++n) { double* H_int = m_el->H(n); FEMaterialPoint* mp = m_el->GetMaterialPoint(n); double m_J = mp->m_J0; // loop over all nodes for (int j = 0; j < neln; ++j) { // only allow internalization if the species won't go negative if (cxx > 0.0) { total_change += m_rate * H[n] * H_int[j] * dt * w[n]; } } } } else { // set the concentration of all nodes via the shape functions for each integration point double n_elem = possible_nodes.size(); double H[FEElement::MAX_NODES]; for (auto iter = possible_nodes.begin(); iter != possible_nodes.end(); iter++) { FESolidElement* c_el = dynamic_cast<FESolidElement*>(*iter); double r[3]; dom->ProjectToElement(*c_el, m_pos, r); vec3d r3 = ClampNatC(r); r[0] = r3.x; r[1] = r3.y; r[2] = r3.z; int nint = c_el->GaussPoints(); double* w = c_el->GaussWeights(); int neln = c_el->Nodes(); // for this element get the shape functions and constants c_el->shape_fnc(H, r[0], r[1], r[2]); // for each integration point in this element project to the nodes. for (int n = 0; n < nint; ++n) { double* H_int = c_el->H(n); FEMaterialPoint* mp = c_el->GetMaterialPoint(n); double m_J = mp->m_J0; // loop over all nodes for (int j = 0; j < neln; ++j) { // only allow internalization if the species won't go negative if (cxx > 0.0) { total_change += m_rate * H[n] * H_int[j] * dt * w[n] / n_elem; } } } } } m_dC = -total_change / (m_Vc); m_accumulate = false; } } //! Evaluate force vector void FESolutePointSource::LoadVector(FEGlobalVector& R) { // get the domain in which this element resides m_el = dynamic_cast<FESolidElement*>(m_search.FindElement(m_pos, m_q)); FESolidDomain* dom = dynamic_cast<FESolidDomain*>(m_el->GetMeshPartition()); FEMesh* mesh = dom->GetMesh(); // get time increment double dt = CurrentTimeIncrement(); // evaluate the shape functions at the position double H[FEElement::MAX_NODES]; m_el->shape_fnc(H, m_q[0], m_q[1], m_q[2]); // evaluate the concentration at this point int neln = m_el->Nodes(); double c[FEElement::MAX_NODES]; for (int i = 0; i < neln; ++i) c[i] = mesh->Node(m_el->m_node[i]).get(m_dofC); double cx = m_el->evaluate(c, m_q[0], m_q[1], m_q[2]); double Ve = mesh->ElementVolume(*m_el); double cxx = cx * Ve + dt * m_rate; double v_rate = m_rate / Ve; // assemble the element load vector vector<double> fe(neln, 0.0); vector<int> lm(neln, -1); std::vector<FEElement*> possible_nodes; double total_elem = 0; FindNodesInRadius(possible_nodes, total_elem); //SL: Currently this just assigns within the current element. We will instead want this to assign to the closest integration points. if (possible_nodes.size() == 0) { int nint = m_el->GaussPoints(); double* w = m_el->GaussWeights(); for (int n = 0; n < nint; ++n) { double* H_int = m_el->H(n); FEMaterialPoint* mp = m_el->GetMaterialPoint(n); double m_J = mp->m_J0; // loop over all nodes for (int j = 0; j < neln; ++j) fe[j] += -v_rate * m_J * H[n] * H_int[j] * dt * w[n] * neln; } //// get the LM vector for (int i = 0; i < neln; ++i) lm[i] = mesh->Node(m_el->m_node[i]).m_ID[m_dofC]; R.Assemble(lm, fe); } else { double n_elem = possible_nodes.size(); //vec3d global_pos = GetGlobalPos(vec3d(m_q[0],m_q[1],m_q[2]), m_el); for (auto iter = possible_nodes.begin(); iter != possible_nodes.end(); iter++) { FESolidElement* c_el = dynamic_cast<FESolidElement*>(*iter); //std::cout << "element " << c_el->GetID() << endl; double r[3]; dom->ProjectToElement(*c_el, m_pos, r); vec3d r3 = ClampNatC(r); r[0] = r3.x; r[1] = r3.y; r[2] = r3.z; //std::cout << "r is " << r[0] << ", " << r[1] << ", " << r[2] << endl; int nint = c_el->GaussPoints(); double* w = c_el->GaussWeights(); int neln = c_el->Nodes(); vector<double> fe(neln, 0.0); vector<int> lm(neln, -1); for (int n = 0; n < nint; ++n) { double* H_int = c_el->H(n); c_el->shape_fnc(H, r[0], r[1], r[2]); FEMaterialPoint* mp = c_el->GetMaterialPoint(n); double m_J = mp->m_J0; for (int j = 0; j < neln; ++j) fe[j] += -v_rate * m_J * H[n] * H_int[j] * dt * w[n] * neln / n_elem; } for (int i = 0; i < neln; ++i) lm[i] = mesh->Node(c_el->m_node[i]).m_ID[m_dofC]; R.Assemble(lm, fe); } } } //! evaluate stiffness matrix void FESolutePointSource::StiffnessMatrix(FELinearSystem& S) { // get time increment double dt = CurrentTimeIncrement(); // get the domain in which this element resides m_el = dynamic_cast<FESolidElement*>(m_search.FindElement(m_pos, m_q)); FESolidDomain* dom = dynamic_cast<FESolidDomain*>(m_el->GetMeshPartition()); FEMesh* mesh = dom->GetMesh(); // evaluate the shape functions at the position double H[FEElement::MAX_NODES]; m_el->shape_fnc(H, m_q[0], m_q[1], m_q[2]); // evaluate the concentration at this point int neln = m_el->Nodes(); int nint = m_el->GaussPoints(); // assemble the element load vector FEElementMatrix ke(neln, neln); ke.zero(); double* w = m_el->GaussWeights(); double Ve = mesh->ElementVolume(*m_el); double v_rate = m_rate / Ve; double c[FEElement::MAX_NODES]; for (int i = 0; i < neln; ++i) c[i] = mesh->Node(m_el->m_node[i]).get(m_dofC); std::vector<FEElement*> possible_nodes; double total_elem = 0; FindNodesInRadius(possible_nodes, total_elem); if (possible_nodes.size() == 0) { for (int k = 0; k < nint; k++) { FEMaterialPoint* mp = m_el->GetMaterialPoint(k); double m_J = mp->m_J0; for (int i = 0; i < neln; ++i) for (int j = 0; j < neln; ++j) { ke[i][j] = H[i] * m_J * H[j] * v_rate * w[k] * dt; } } // get the LM vector vector<int> lm(neln, -1); for (int i = 0; i < neln; ++i) lm[i] = mesh->Node(m_el->m_node[i]).m_ID[m_dofC]; // get the nodes vector<int> nodes(neln, -1); for (int i = 0; i < neln; ++i) nodes[i] = m_el->m_node[i]; // assemble into global matrix ke.SetIndices(lm); ke.SetNodes(nodes); S.Assemble(ke); } else { for (auto iter = possible_nodes.begin(); iter != possible_nodes.end(); ++iter) { FESolidElement* c_el = dynamic_cast<FESolidElement*>(*iter); double r[3]; dom->ProjectToElement(*c_el, m_pos, r); vec3d r3 = ClampNatC(r); r[0] = r3.x; r[1] = r3.y; r[2] = r3.z; double* w = c_el->GaussWeights(); c_el->shape_fnc(H, r[0], r[1], r[2]); nint = c_el->GaussPoints(); neln = c_el->Nodes(); FEElementMatrix ke(neln, neln); ke.zero(); for (int k = 0; k < nint; k++) { FEMaterialPoint* mp = c_el->GetMaterialPoint(k); double m_J = mp->m_J0; for (int i = 0; i < neln; ++i) for (int j = 0; j < neln; ++j) { ke[i][j] = H[i] * m_J * H[j] * v_rate * w[k] * dt; } } // get the LM vector vector<int> lm(neln, -1); for (int i = 0; i < neln; ++i) lm[i] = mesh->Node(c_el->m_node[i]).m_ID[m_dofC]; // get the nodes vector<int> nodes(neln, -1); for (int i = 0; i < neln; ++i) nodes[i] = c_el->m_node[i]; // assemble into global matrix ke.SetIndices(lm); ke.SetNodes(nodes); S.Assemble(ke); } } } void FESolutePointSource::FindNodesInRadius(std::vector<FEElement*>& possible_nodes, double& total_elem) { // get element and set up buffers m_el = dynamic_cast<FESolidElement*>(m_search.FindElement(m_pos, m_q)); std::unordered_set<FESolidElement*> visited; std::set<FESolidElement*> next; //std::vector<FEMaterialPoint*> possible_ints; visited.reserve(1000); possible_nodes.reserve(500); //we will need to check the current element first next.insert(m_el); // create the element adjacency list. FEDomain* dom = dynamic_cast<FEDomain*>(m_el->GetMeshPartition()); FEMultiphasic* mat = dynamic_cast<FEMultiphasic*>(dom->GetMaterial()); if (mat == nullptr) return; // calculate the element volume auto mesh = dom->GetMesh(); // create the element-element list FEElemElemList EEL; EEL.Create(mesh); //while there are still elements to evaluate while (next.size()) { // get the element to be evaluated FESolidElement* cur = *next.begin(); // remove the current element from the next buffer and add it to the visited buffer next.erase(next.begin()); visited.insert(cur); // get the current element bounds std::vector<vec3d> cur_element_bounds; // add integration points within the radius bool int_flag = false; for (int i = 0; i < cur->Nodes(); i++) { FENode* mn = &(mesh->Node(cur->m_node[i])); vec3d disp = mn->m_rt - m_pos; if (disp.norm() <= m_radius) { possible_nodes.push_back(cur); int_flag = true; } } if (int_flag) { total_elem++; } // Add neighboring element to the next buffer as long as they haven't been visited. // get the global ID of the current element int cur_id = cur->GetID() - 1; // for each neighboring element for (int i = 0; i < EEL.NeighborSize(); i++) { if (EEL.Neighbor(cur_id, i)) { // if that element has not been visited yet add it to the next list if (!visited.count(dynamic_cast<FESolidElement*>(EEL.Neighbor(cur_id, i)))) { next.insert(dynamic_cast<FESolidElement*>(EEL.Neighbor(cur_id, i))); } } } } } vec3d FESolutePointSource::ClampNatC(double r[3]) { return vec3d(std::max(std::min(1.0, r[0]), -1.0), std::max(std::min(1.0, r[1]), -1.0), std::max(std::min(1.0, r[2]), -1.0) ); }
C++
3D
febiosoftware/FEBio
FEBioMix/FESlidingInterface2.cpp
.cpp
56,214
1,928
/*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 "FESlidingInterface2.h" #include "FEBiphasic.h" #include "FECore/FEModel.h" #include "FECore/FEAnalysis.h" #include "FECore/FENormalProjection.h" #include <FECore/FELinearSystem.h> #include "FECore/log.h" //----------------------------------------------------------------------------- // Define sliding interface parameters BEGIN_FECORE_CLASS(FESlidingInterface2, FEContactInterface) ADD_PARAMETER(m_laugon , "laugon")->setLongName("Enforcement method")->setEnums("PENALTY\0AUGLAG\0"); ADD_PARAMETER(m_atol , "tolerance" ); ADD_PARAMETER(m_gtol , "gaptol" )->setUnits(UNIT_LENGTH);; ADD_PARAMETER(m_ptol , "ptol" ); ADD_PARAMETER(m_epsn , "penalty" ); ADD_PARAMETER(m_bautopen , "auto_penalty" ); ADD_PARAMETER(m_bupdtpen , "update_penalty" ); ADD_PARAMETER(m_btwo_pass, "two_pass" ); ADD_PARAMETER(m_knmult , "knmult" ); ADD_PARAMETER(m_stol , "search_tol" ); ADD_PARAMETER(m_epsp , "pressure_penalty" ); ADD_PARAMETER(m_bsymm , "symmetric_stiffness"); ADD_PARAMETER(m_srad , "search_radius" )->setUnits(UNIT_LENGTH);; ADD_PARAMETER(m_nsegup , "seg_up" ); ADD_PARAMETER(m_naugmin , "minaug" ); ADD_PARAMETER(m_naugmax , "maxaug" ); ADD_PARAMETER(m_breloc , "node_reloc" ); ADD_PARAMETER(m_bsmaug , "smooth_aug" ); ADD_PARAMETER(m_bdupr , "dual_proj" ); END_FECORE_CLASS(); //----------------------------------------------------------------------------- // FESlidingSurface2 //----------------------------------------------------------------------------- FESlidingSurface2::FESlidingSurface2(FEModel* pfem) : FEBiphasicContactSurface(pfem) { m_bporo = false; } //----------------------------------------------------------------------------- bool FESlidingSurface2::Init() { // initialize surface data first if (FEBiphasicContactSurface::Init() == false) return false; // allocate node normals and pressures m_nn.assign(Nodes(), vec3d(0,0,0)); m_pn.assign(Nodes(), 0); // determine biphasic status m_poro.resize(Elements(),false); for (int i=0; i<Elements(); ++i) { // get the surface element FESurfaceElement& se = Element(i); // get the element this surface element belongs to FEElement* pe = se.m_elem[0].pe; if (pe) { // get the material FEMaterial* pm = m_pfem->GetMaterial(pe->GetMatID()); // see if this is a poro-elastic element FEBiphasic* biph = dynamic_cast<FEBiphasic*> (pm); if (biph) { m_poro[i] = true; m_bporo = true; } } } return true; } //----------------------------------------------------------------------------- //! create material point data FEMaterialPoint* FESlidingSurface2::CreateMaterialPoint() { return new FEBiphasicContactPoint; } //----------------------------------------------------------------------------- //! Evaluate the nodal contact pressures by averaging values from surrounding //! faces. This function ensures that nodal contact pressures are always //! positive, so that they can be used to detect free-draining status. void FESlidingSurface2::EvaluateNodalContactPressures() { const int N = Nodes(); // number of faces with non-zero contact pressure connected to this node vector<int> nfaces(N,0); // zero nodal contact pressures zero(m_pn); // loop over all elements for (int i=0; i<Elements(); ++i) { FESurfaceElement& el = Element(i); int ne = el.Nodes(); // get the average contact pressure for that face double pn = 0; GetContactPressure(i, pn); if (pn > 0) { for (int j=0; j<ne; ++j) { m_pn[el.m_lnode[j]] += pn; ++nfaces[el.m_lnode[j]]; } } } // get average over all contacting faces sharing that node for (int i=0; i<N; ++i) if (nfaces[i] > 0) m_pn[i] /= nfaces[i]; } //----------------------------------------------------------------------------- //! This function calculates the node normal. Due to the piecewise continuity //! of the surface elements this normal is not uniquely defined so in order to //! obtain a unique normal the normal is averaged for each node over all the //! element normals at the node void FESlidingSurface2::UpdateNodeNormals() { const int MN = FEElement::MAX_NODES; vec3d y[MN]; // zero nodal normals zero(m_nn); // loop over all elements for (int i=0; i<Elements(); ++i) { FESurfaceElement& el = Element(i); int ne = el.Nodes(); // get the nodal coordinates for (int j=0; j<ne; ++j) y[j] = Node(el.m_lnode[j]).m_rt; // calculate the normals for (int j=0; j<ne; ++j) { int jp1 = (j+1)%ne; int jm1 = (j+ne-1)%ne; vec3d n = (y[jp1] - y[j]) ^ (y[jm1] - y[j]); m_nn[el.m_lnode[j]] += n; } } // normalize all vectors const int N = Nodes(); for (int i=0; i<N; ++i) m_nn[i].unit(); } //----------------------------------------------------------------------------- vec3d FESlidingSurface2::GetContactForce() { return m_Ft; } //----------------------------------------------------------------------------- vec3d FESlidingSurface2::GetContactForceFromElementStress() { // get the mesh FEMesh& m = GetFEModel()->GetMesh(); // initialize contact force vec3d f(0,0,0); // loop over all elements of the surface for (int n=0; n<Elements(); ++n) { FESurfaceElement& el = Element(n); // get the element this surface element belongs to FEElement* pe = el.m_elem[0].pe; mat3ds s(0,0,0,0,0,0); for (int j=0; j<pe->GaussPoints(); ++j) { // get a material point FEMaterialPoint& mp = *pe->GetMaterialPoint(0); FEElasticMaterialPoint& pt = *(mp.ExtractData<FEElasticMaterialPoint>()); s += pt.m_s; } s /= pe->GaussPoints(); double sp[3]; s.eigen2(sp); int nint = el.GaussPoints(); // evaluate the contact force for that element for (int i=0; i<nint; ++i) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(i)); if (data.m_Ln > 0) { // get the base vectors vec3d g[2]; CoBaseVectors(el, i, g); // normal (magnitude = area) vec3d a = g[0] ^ g[1]; // gauss weight double w = el.GaussWeights()[i]; // contact force f += a*(sp[0]*w); } } } return f; } //----------------------------------------------------------------------------- double FESlidingSurface2::GetContactArea() { // initialize contact area double area = 0; // loop over all elements of the primary surface for (int n=0; n<Elements(); ++n) { FESurfaceElement& el = Element(n); int nint = el.GaussPoints(); // evaluate the contact force for that element for (int i=0; i<nint; ++i) { // get data for this integration point FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(i)); if (data.m_Ln > 0) { // get the base vectors vec3d g[2]; CoBaseVectors(el, i, g); // normal (magnitude = area) vec3d a = g[0] ^ g[1]; // gauss weight double w = el.GaussWeights()[i]; // contact force area += a.norm()*w; } } } return area; } //----------------------------------------------------------------------------- vec3d FESlidingSurface2::GetFluidForce() { // initialize contact force vec3d f(0,0,0); if (m_dofP < 0) return f; // loop over all elements of the surface for (int n=0; n<Elements(); ++n) { FESurfaceElement& el = Element(n); int nint = el.GaussPoints(); // evaluate the fluid force for that element for (int i=0; i<nint; ++i) { // get data for this integration point FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(i)); if (data.m_Ln > 0) { // get the base vectors vec3d g[2]; CoBaseVectors(el, i, g); // normal (magnitude = area) vec3d a = g[0] ^ g[1]; // gauss weight double w = el.GaussWeights()[i]; // fluid pressure double p = data.m_p1; // contact force f += a*(w*p); } } } return f; } //----------------------------------------------------------------------------- vec3d FESlidingSurface2::GetFluidForceFromElementPressure() { // get the mesh FEMesh& m = GetFEModel()->GetMesh(); // initialize contact force vec3d f(0,0,0); if (m_dofP < 0) return f; // loop over all elements of the surface for (int n=0; n<Elements(); ++n) { FESurfaceElement& el = Element(n); // get the element this surface element belongs to FEElement* pe = el.m_elem[0].pe; double p = 0; for (int j=0; j<pe->GaussPoints(); ++j) { // get a material point FEMaterialPoint& mp = *pe->GetMaterialPoint(0); FEBiphasicMaterialPoint& pt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); p += pt.m_p; } p /= pe->GaussPoints(); int nint = el.GaussPoints(); // evaluate the fluid force for that element for (int i=0; i<nint; ++i) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(i)); if (data.m_Ln > 0) { // get the base vectors vec3d g[2]; CoBaseVectors(el, i, g); // normal (magnitude = area) vec3d a = g[0] ^ g[1]; // gauss weight double w = el.GaussWeights()[i]; // contact force f += a*(w*p); } } } return f; } //----------------------------------------------------------------------------- double FESlidingSurface2::GetFluidLoadSupport() { double W = GetContactForceFromElementStress().norm(); double Wp = GetFluidForceFromElementPressure().norm(); if (W == 0) return 0; return Wp/W; } //----------------------------------------------------------------------------- void FESlidingSurface2::Serialize(DumpStream& ar) { FEBiphasicContactSurface::Serialize(ar); ar & m_bporo; ar & m_poro; ar & m_nn; ar & m_pn; ar & m_Ft; } //----------------------------------------------------------------------------- void FESlidingSurface2::GetContactPressure(int nface, double& pg) { FESurfaceElement& el = Element(nface); int ni = el.GaussPoints(); pg = 0; for (int k = 0; k < ni; ++k) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(k)); pg += data.m_Ln; } pg /= ni; } //----------------------------------------------------------------------------- void FESlidingSurface2::GetContactTraction(int nface, vec3d& pt) { FESurfaceElement& el = Element(nface); int ni = el.GaussPoints(); pt = vec3d(0,0,0); for (int k = 0; k < ni; ++k) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(k)); pt -= data.m_nu*data.m_Ln; } pt /= ni; } //----------------------------------------------------------------------------- void FESlidingSurface2::GetNodalContactPressure(int nface, double* pg) { FESurfaceElement& el = Element(nface); for (int k=0; k<el.Nodes(); ++k) pg[k] = m_pn[el.m_lnode[k]]; } //----------------------------------------------------------------------------- void FESlidingSurface2::GetNodalContactTraction(int nface, vec3d* pt) { FESurfaceElement& el = Element(nface); for (int k=0; k<el.Nodes(); ++k) pt[k] = m_nn[el.m_lnode[k]]*(-m_pn[el.m_lnode[k]]); } //----------------------------------------------------------------------------- // FESlidingInterface2 //----------------------------------------------------------------------------- FESlidingInterface2::FESlidingInterface2(FEModel* pfem) : FEContactInterface(pfem), m_ss(pfem), m_ms(pfem) { static int count = 1; SetID(count++); // initial values m_knmult = 1; m_atol = 0.1; m_epsn = 1; m_epsp = 1; m_btwo_pass = false; m_stol = 0.01; m_bsymm = true; m_srad = 1.0; m_gtol = 0; m_ptol = 0; m_nsegup = 0; m_bautopen = false; m_bupdtpen = false; m_breloc = false; m_bsmaug = false; m_bdupr = true; m_naugmin = 0; m_naugmax = 10; m_dofP = pfem->GetDOFIndex("p"); // set parents m_ss.SetContactInterface(this); m_ms.SetContactInterface(this); m_ss.SetSibling(&m_ms); m_ms.SetSibling(&m_ss); } //----------------------------------------------------------------------------- FESlidingInterface2::~FESlidingInterface2() { } //----------------------------------------------------------------------------- bool FESlidingInterface2::Init() { // initialize surface data if (m_ss.Init() == false) return false; if (m_ms.Init() == false) return false; return true; } //----------------------------------------------------------------------------- void FESlidingInterface2::BuildMatrixProfile(FEGlobalMatrix& K) { FEModel& fem = *GetFEModel(); FEMesh& mesh = fem.GetMesh(); // 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"); const int dof_RU = fem.GetDOFIndex("Ru"); const int dof_RV = fem.GetDOFIndex("Rv"); const int dof_RW = fem.GetDOFIndex("Rw"); vector<int> lm(7*FEElement::MAX_NODES*2); int npass = (m_btwo_pass?2:1); for (int np=0; np<npass; ++np) { FESlidingSurface2& ss = (np == 0? m_ss : m_ms); int k, l; for (int j=0; j<ss.Elements(); ++j) { FESurfaceElement& se = ss.Element(j); int nint = se.GaussPoints(); int* sn = &se.m_node[0]; for (k=0; k<nint; ++k) { FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*se.GetMaterialPoint(k)); FESurfaceElement* pe = pt.m_pme; if (pe != 0) { FESurfaceElement& me = *pe; int* mn = &me.m_node[0]; assign(lm, -1); int nseln = se.Nodes(); int nmeln = me.Nodes(); for (l=0; l<nseln; ++l) { vector<int>& id = mesh.Node(sn[l]).m_ID; lm[7*l ] = id[dof_X]; lm[7*l+1] = id[dof_Y]; lm[7*l+2] = id[dof_Z]; lm[7*l+3] = id[dof_P]; lm[7*l+4] = id[dof_RU]; lm[7*l+5] = id[dof_RV]; lm[7*l+6] = id[dof_RW]; } for (l=0; l<nmeln; ++l) { vector<int>& id = mesh.Node(mn[l]).m_ID; lm[7*(l+nseln) ] = id[dof_X]; lm[7*(l+nseln)+1] = id[dof_Y]; lm[7*(l+nseln)+2] = id[dof_Z]; lm[7*(l+nseln)+3] = id[dof_P]; lm[7*(l+nseln)+4] = id[dof_RU]; lm[7*(l+nseln)+5] = id[dof_RV]; lm[7*(l+nseln)+6] = id[dof_RW]; } K.build_add(lm); } } } } } //----------------------------------------------------------------------------- void FESlidingInterface2::UpdateAutoPenalty() { // calculate the penalty if (m_bautopen) { CalcAutoPenalty(m_ss); CalcAutoPenalty(m_ms); CalcAutoPressurePenalty(m_ss); CalcAutoPressurePenalty(m_ms); } } //----------------------------------------------------------------------------- //! This function is called during the initialization void FESlidingInterface2::Activate() { // don't forget to call base member FEContactInterface::Activate(); UpdateAutoPenalty(); // update sliding interface data Update(); } //----------------------------------------------------------------------------- void FESlidingInterface2::CalcAutoPenalty(FESlidingSurface2& s) { // loop over all surface elements for (int i=0; i<s.Elements(); ++i) { // get the surface element FESurfaceElement& el = s.Element(i); // calculate a penalty double eps = AutoPenalty(el, s); // assign to integation points of surface element int nint = el.GaussPoints(); for (int j=0; j<nint; ++j) { FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); pt.m_epsn = eps; } } } //----------------------------------------------------------------------------- void FESlidingInterface2::CalcAutoPressurePenalty(FESlidingSurface2& s) { // loop over all surface elements for (int i=0; i<s.Elements(); ++i) { // get the surface element FESurfaceElement& el = s.Element(i); // calculate a penalty double eps = AutoPressurePenalty(el, s); // assign to integation points of surface element int nint = el.GaussPoints(); for (int j=0; j<nint; ++j) { FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); pt.m_epsp = eps; } } } //----------------------------------------------------------------------------- double FESlidingInterface2::AutoPressurePenalty(FESurfaceElement& el, FESlidingSurface2& s) { // get the mesh FEMesh& m = GetFEModel()->GetMesh(); // evaluate element surface normal at parametric center vec3d t[2]; s.CoBaseVectors0(el, 0, 0, t); vec3d n = t[0] ^ t[1]; n.unit(); // get the element this surface element belongs to FEElement* pe = el.m_elem[0].pe; if (pe == 0) return 0.0; // get the material FEMaterial* pm = GetFEModel()->GetMaterial(pe->GetMatID()); // see if this is a poro-elastic element FEBiphasic* biph = dynamic_cast<FEBiphasic*> (pm); if (biph == 0) return 0.0; // get a material point FEMaterialPoint& mp = *pe->GetMaterialPoint(0); FEElasticMaterialPoint& ept = *(mp.ExtractData<FEElasticMaterialPoint>()); // setup the material point ept.m_F = mat3dd(1.0); ept.m_J = 1; ept.m_s.zero(); // if this is a poroelastic element, then get the permeability tensor FEBiphasicMaterialPoint& pt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); pt.m_p = 0; pt.m_w = vec3d(0,0,0); double K[3][3]; biph->Permeability(K, mp); double eps = n.x*(K[0][0]*n.x+K[0][1]*n.y+K[0][2]*n.z) +n.y*(K[1][0]*n.x+K[1][1]*n.y+K[1][2]*n.z) +n.z*(K[2][0]*n.x+K[2][1]*n.y+K[2][2]*n.z); // get the area of the surface element double A = s.FaceArea(el); // get the volume of the volume element double V = m.ElementVolume(*pe); return eps*A/V; } //----------------------------------------------------------------------------- void FESlidingInterface2::ProjectSurface(FESlidingSurface2& ss, FESlidingSurface2& ms, bool bupseg, bool bmove) { FEMesh& mesh = GetFEModel()->GetMesh(); FESurfaceElement* pme; vec3d r, nu; double rs[2]; double Ln; double ps[FEElement::MAX_NODES], p1; double psf = GetPenaltyScaleFactor(); FENormalProjection np(ms); np.SetTolerance(m_stol); np.SetSearchRadius(m_srad); np.Init(); // if we need to project the nodes onto the secondary surface, // let's do this first if (bmove) { int NN = ss.Nodes(); int NE = ss.Elements(); // first we need to calculate the node normals vector<vec3d> normal; normal.assign(NN, vec3d(0,0,0)); for (int i=0; i<NE; ++i) { FESurfaceElement& el = ss.Element(i); int ne = el.Nodes(); for (int j=0; j<ne; ++j) { vec3d r0 = ss.Node(el.m_lnode[ j ]).m_rt; vec3d rp = ss.Node(el.m_lnode[(j+ 1)%ne]).m_rt; vec3d rm = ss.Node(el.m_lnode[(j+ne-1)%ne]).m_rt; vec3d n = (rp - r0)^(rm - r0); normal[el.m_lnode[j]] += n; } } for (int i=0; i<NN; ++i) normal[i].unit(); // loop over all nodes for (int i=0; i<NN; ++i) { FENode& node = ss.Node(i); // get the spatial nodal coordinates vec3d rt = node.m_rt; vec3d nu = normal[i]; // project onto the secondary surface vec3d q; double rs[2] = {0,0}; FESurfaceElement* pme = np.Project(rt, nu, rs); if (pme) { // the node could potentially be in contact // find the global location of the intersection point vec3d q = ms.Local2Global(*pme, rs[0], rs[1]); // calculate the gap function // NOTE: this has the opposite sign compared // to Gerard's notes. double gap = nu*(rt - q); if (gap>0) node.m_r0 = node.m_rt = q; } } } // loop over all integration points // #pragma omp parallel for shared(R, bupseg) for (int i=0; i<ss.Elements(); ++i) { FESurfaceElement& el = ss.Element(i); bool sporo = ss.m_poro[i]; int ne = el.Nodes(); int nint = el.GaussPoints(); // get the nodal pressures if (sporo) { for (int j=0; j<ne; ++j) ps[j] = mesh.Node(el.m_node[j]).get(m_dofP); } for (int j=0; j<nint; ++j) { // get the integration point data FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); // calculate the global position of the integration point r = ss.Local2Global(el, j); // get the pressure at the integration point if (sporo) p1 = el.eval(ps, j); // calculate the normal at this integration point nu = ss.SurfaceNormal(el, j); // first see if the old intersected face is still good enough pme = pt.m_pme; if (pme) { double g; // see if the ray intersects this element if (ms.Intersect(*pme, r, nu, rs, g, m_stol)) { pt.m_rs[0] = rs[0]; pt.m_rs[1] = rs[1]; } else { pme = 0; } } // find the intersection point with the secondary surface if (pme == 0 && bupseg) pme = np.Project(r, nu, rs); pt.m_pme = pme; pt.m_nu = nu; pt.m_rs[0] = rs[0]; pt.m_rs[1] = rs[1]; if (pme) { // the node could potentially be in contact // find the global location of the intersection point vec3d q = ms.Local2Global(*pme, rs[0], rs[1]); // calculate the gap function // NOTE: this has the opposite sign compared // to Gerard's notes. double g = nu*(r - q); double eps = m_epsn*pt.m_epsn*psf; Ln = pt.m_Lmd + eps*g; pt.m_gap = (g <= m_srad? g : 0); if ((Ln >= 0) && (g <= m_srad)) { // calculate the pressure gap function bool mporo = ms.m_poro[pme->m_lid]; if (sporo) { pt.m_p1 = p1; if (mporo) { double pm[FEElement::MAX_NODES]; for (int k=0; k<pme->Nodes(); ++k) pm[k] = mesh.Node(pme->m_node[k]).get(m_dofP); double p2 = pme->eval(pm, rs[0], rs[1]); pt.m_pg = p1 - p2; } } } else { pt.m_Lmd = 0; pt.m_gap = 0; pt.m_pme = 0; if (sporo) { pt.m_Lmp = 0; pt.m_pg = 0; pt.m_p1 = 0; } } } else { // the node is not in contact pt.m_Lmd = 0; pt.m_gap = 0; if (sporo) { pt.m_Lmp = 0; pt.m_pg = 0; pt.m_p1 = 0; } } } } } //----------------------------------------------------------------------------- void FESlidingInterface2::Update() { double rs[2]; static int naug = 0; static int biter = 0; FEModel& fem = *GetFEModel(); // get the iteration number // we need this number to see if we can do segment updates or not // also reset number of iterations after each augmentation FEAnalysis* pstep = fem.GetCurrentStep(); FESolver* psolver = pstep->GetFESolver(); if (psolver->m_niter == 0) { biter = 0; naug = psolver->m_naug; // check update of auto-penalty if (m_bupdtpen) UpdateAutoPenalty(); } else if (psolver->m_naug > naug) { biter = psolver->m_niter; naug = psolver->m_naug; } int niter = psolver->m_niter - biter; bool bupseg = ((m_nsegup == 0)? true : (niter <= m_nsegup)); // get the logfile // Logfile& log = GetLogfile(); // log.printf("seg_up iteration # %d\n", niter+1); // project the surfaces onto each other // this will update the gap functions as well static bool bfirst = true; ProjectSurface(m_ss, m_ms, bupseg, (m_breloc && bfirst)); if (m_btwo_pass || m_ms.m_bporo) ProjectSurface(m_ms, m_ss, bupseg); bfirst = false; // Update the net contact pressures UpdateContactPressures(); // update node normals m_ss.UpdateNodeNormals(); m_ms.UpdateNodeNormals(); // set poro flag bool bporo = (m_ss.m_bporo || m_ms.m_bporo); // only continue if we are doing a poro-elastic simulation if (bporo == false) return; // Now that the nodes have been projected, we need to figure out // if we need to modify the constraints on the pressure dofs. // If the nodes are not in contact, they must be free // draining. Since all nodes have been previously marked to be // free-draining in MarkFreeDraining(), we just need to reverse // this setting here, for nodes that are in contact. // Next, we loop over each surface, visiting the nodes // and finding out if that node is in contact or not int npass = (m_btwo_pass?2:1); for (int np=0; np<npass; ++np) { FESlidingSurface2& ss = (np == 0? m_ss : m_ms); FESlidingSurface2& ms = (np == 0? m_ms : m_ss); // loop over all the nodes of the primary surface for (int n=0; n<ss.Nodes(); ++n) { FENode& node = ss.Node(n); int id = node.m_ID[m_dofP]; if ((id < -1) && (ss.m_pn[n] > 0)) { // mark node as non-free-draining (= pos ID) node.m_ID[m_dofP] = -id-2; } } // loop over all nodes of the secondary surface // the secondary surface is trickier since we need // to look at the primary surface's projection if (ms.m_bporo && ((npass == 1) || m_bdupr)) { FENormalProjection np(ss); np.SetTolerance(m_stol); np.SetSearchRadius(m_srad); np.Init(); for (int n=0; n<ms.Nodes(); ++n) { // get the node FENode& node = ms.Node(n); // project it onto the primary surface FESurfaceElement* pse = np.Project(node.m_rt, ms.m_nn[n], rs); if (pse) { // we found an element, so let's see if it's even remotely close to contact // find the global location of the intersection point vec3d q = ss.Local2Global(*pse, rs[0], rs[1]); // calculate the gap function double g = ms.m_nn[n]*(node.m_rt - q); if (fabs(g) <= m_srad) { // we found an element so let's calculate the nodal traction values for this element // get the normal tractions at the nodes double tn[FEElement::MAX_NODES]; for (int i=0; i<pse->Nodes(); ++i) tn[i] = ss.m_pn[pse->m_lnode[i]]; // now evaluate the traction at the intersection point double tp = pse->eval(tn, rs[0], rs[1]); // if tp > 0, mark node as non-free-draining. (= pos ID) int id = node.m_ID[m_dofP]; if ((id < -1) && (tp > 0)) { // mark as non free-draining node.m_ID[m_dofP] = -id-2; } } } } } } } //----------------------------------------------------------------------------- void FESlidingInterface2::LoadVector(FEGlobalVector& R, const FETimeInfo& tp) { int i, j, k; vector<int> sLM, mLM, LM, en; vector<double> fe; const int MN = FEElement::MAX_NODES; double detJ[MN], w[MN], *Hs, Hm[MN]; double N[4*MN*2]; // TODO: is the size correct? FEModel& fem = *GetFEModel(); // if we're using the symmetric formulation // we need to multiply with the timestep double dt = fem.GetTime().timeIncrement; double psf = GetPenaltyScaleFactor(); m_ss.m_Ft = vec3d(0, 0, 0); m_ms.m_Ft = vec3d(0, 0, 0); // loop over the nr of passes int npass = (m_btwo_pass?2:1); for (int np=0; np<npass; ++np) { // get primary and secondary surface FESlidingSurface2& ss = (np == 0? m_ss : m_ms); FESlidingSurface2& ms = (np == 0? m_ms : m_ss); // loop over all primary surface elements for (i=0; i<ss.Elements(); ++i) { // get the surface element FESurfaceElement& se = ss.Element(i); bool sporo = ss.m_poro[i]; // get the nr of nodes and integration points int nseln = se.Nodes(); int nint = se.GaussPoints(); // copy the LM vector; we'll need it later ss.UnpackLM(se, sLM); // we calculate all the metrics we need before we // calculate the nodal forces for (j=0; j<nint; ++j) { // get the base vectors vec3d g[2]; ss.CoBaseVectors(se, j, g); // jacobians: J = |g0xg1| detJ[j] = (g[0] ^ g[1]).norm(); // integration weights w[j] = se.GaussWeights()[j]; } // loop over all integration points // note that we are integrating over the current surface for (j=0; j<nint; ++j) { // get the integration point data FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*se.GetMaterialPoint(j)); // get the secondary surface element FESurfaceElement* pme = pt.m_pme; if (pme) { // get the secondary surface element FESurfaceElement& me = *pme; bool mporo = ms.m_poro[pme->m_lid]; // get the nr of element nodes int nmeln = me.Nodes(); // copy LM vector ms.UnpackLM(me, mLM); // calculate degrees of freedom int ndof = 3*(nseln + nmeln); // build the LM vector LM.resize(ndof); for (k=0; k<nseln; ++k) { LM[3*k ] = sLM[3*k ]; LM[3*k+1] = sLM[3*k+1]; LM[3*k+2] = sLM[3*k+2]; } for (k=0; k<nmeln; ++k) { LM[3*(k+nseln) ] = mLM[3*k ]; LM[3*(k+nseln)+1] = mLM[3*k+1]; LM[3*(k+nseln)+2] = mLM[3*k+2]; } // build the en vector en.resize(nseln+nmeln); for (k=0; k<nseln; ++k) en[k ] = se.m_node[k]; for (k=0; k<nmeln; ++k) en[k+nseln] = me.m_node[k]; // get element shape functions Hs = se.H(j); // get secondary surface element shape functions double r = pt.m_rs[0]; double s = pt.m_rs[1]; me.shape_fnc(Hm, r, s); // get normal vector vec3d nu = pt.m_nu; // gap function double g = pt.m_gap; // lagrange multiplier double Lm = pt.m_Lmd; // penalty double eps = m_epsn*pt.m_epsn*psf; // contact traction double tn = Lm + eps*g; tn = MBRACKET(tn); // calculate the force vector fe.resize(ndof); zero(fe); for (k=0; k<nseln; ++k) { N[3*k ] = -Hs[k]*nu.x; N[3*k+1] = -Hs[k]*nu.y; N[3*k+2] = -Hs[k]*nu.z; } for (k=0; k<nmeln; ++k) { N[3*(k+nseln) ] = Hm[k]*nu.x; N[3*(k+nseln)+1] = Hm[k]*nu.y; N[3*(k+nseln)+2] = Hm[k]*nu.z; } for (k=0; k<ndof; ++k) fe[k] += tn*N[k]*detJ[j]*w[j]; for (k=0; k<nseln; ++k) { ss.m_Ft += vec3d(fe[k*3], fe[k*3+1], fe[k*3+2]); } for (k = 0; k<nmeln; ++k) { ms.m_Ft += vec3d(fe[(k + nseln) * 3], fe[(k + nseln) * 3 + 1], fe[(k + nseln) * 3 + 2]); } // assemble the global residual R.Assemble(en, LM, fe); // do the biphasic stuff if (sporo && mporo && (tn > 0)) { // calculate nr of pressure dofs int ndof = nseln + nmeln; // calculate the flow rate double epsp = m_epsp*pt.m_epsp*psf; double wn = pt.m_Lmp + epsp*pt.m_pg; // fill the LM LM.resize(ndof); for (k=0; k<nseln; ++k) LM[k ] = sLM[3*nseln+k]; for (k=0; k<nmeln; ++k) LM[k + nseln] = mLM[3*nmeln+k]; // fill the force array fe.resize(ndof); zero(fe); for (k=0; k<nseln; ++k) N[k ] = Hs[k]; for (k=0; k<nmeln; ++k) N[k+nseln] = -Hm[k]; for (k=0; k<ndof; ++k) fe[k] += dt*wn*N[k]*detJ[j]*w[j]; // assemble residual R.Assemble(en, LM, fe); } } } } } } //----------------------------------------------------------------------------- void FESlidingInterface2::StiffnessMatrix(FELinearSystem& LS, const FETimeInfo& tp) { int i, j, k, l; vector<int> sLM, mLM, LM, en; const int MN = FEElement::MAX_NODES; double detJ[MN], w[MN], *Hs, Hm[MN], pt[MN], dpr[MN], dps[MN]; double N[4*MN*2]; FEElementMatrix ke; FEModel& fem = *GetFEModel(); double psf = GetPenaltyScaleFactor(); // see how many reformations we've had to do so far int nref = GetSolver()->m_nref; // set higher order stiffness mutliplier // NOTE: this algrotihm doesn't really need this // but I've added this functionality to compare with the other contact // algorithms and to see the effect of the different stiffness contributions double knmult = m_knmult; if (m_knmult < 0) { int ni = int(-m_knmult); if (nref >= ni) { knmult = 1; feLog("Higher order stiffness terms included.\n"); } else knmult = 0; } // do single- or two-pass int npass = (m_btwo_pass?2:1); for (int np=0; np < npass; ++np) { // get the primary and secondary surface FESlidingSurface2& ss = (np == 0? m_ss : m_ms); FESlidingSurface2& ms = (np == 0? m_ms : m_ss); // loop over all primary surface elements for (i=0; i<ss.Elements(); ++i) { // get the next element FESurfaceElement& se = ss.Element(i); bool sporo = ss.m_poro[i]; // get nr of nodes and integration points int nseln = se.Nodes(); int nint = se.GaussPoints(); // nodal pressures double pn[MN] = {0}; if (sporo) { for (j=0; j<nseln; ++j) pn[j] = ss.GetMesh()->Node(se.m_node[j]).get(m_dofP); } // copy the LM vector ss.UnpackLM(se, sLM); // we calculate all the metrics we need before we // calculate the nodal forces for (j=0; j<nint; ++j) { // get the base vectors vec3d g[2]; ss.CoBaseVectors(se, j, g); // jacobians: J = |g0xg1| detJ[j] = (g[0] ^ g[1]).norm(); // integration weights w[j] = se.GaussWeights()[j]; // pressure if (sporo) { pt[j] = se.eval(pn, j); dpr[j] = se.eval_deriv1(pn, j); dps[j] = se.eval_deriv2(pn, j); } } // loop over all integration points for (j=0; j<nint; ++j) { // get integration point data FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*se.GetMaterialPoint(j)); // get the secondary surface element FESurfaceElement* pme = pt.m_pme; if (pme) { FESurfaceElement& me = *pme; bool mporo = ms.m_poro[pme->m_lid]; // get the nr of nodes int nmeln = me.Nodes(); // nodal pressure double pm[MN] = {0}; if (sporo && mporo) { for (k=0; k<nmeln; ++k) pm[k] = ms.GetMesh()->Node(me.m_node[k]).get(m_dofP); } // copy the LM vector ms.UnpackLM(me, mLM); int ndpn; // number of dofs per node int ndof; // number of dofs in stiffness matrix if (sporo && mporo) { // calculate degrees of freedom for biphasic-on-biphasic contact ndpn = 4; ndof = ndpn*(nseln+nmeln); // build the LM vector LM.resize(ndof); for (k=0; k<nseln; ++k) { LM[4*k ] = sLM[3*k ]; // x-dof LM[4*k+1] = sLM[3*k+1]; // y-dof LM[4*k+2] = sLM[3*k+2]; // z-dof LM[4*k+3] = sLM[3*nseln+k]; // p-dof } for (k=0; k<nmeln; ++k) { LM[4*(k+nseln) ] = mLM[3*k ]; // x-dof LM[4*(k+nseln)+1] = mLM[3*k+1]; // y-dof LM[4*(k+nseln)+2] = mLM[3*k+2]; // z-dof LM[4*(k+nseln)+3] = mLM[3*nmeln+k]; // p-dof } } else { // calculate degrees of freedom for biphasic-on-elastic or elastic-on-elastic contact ndpn = 3; ndof = ndpn*(nseln + nmeln); // build the LM vector LM.resize(ndof); for (k=0; k<nseln; ++k) { LM[3*k ] = sLM[3*k ]; LM[3*k+1] = sLM[3*k+1]; LM[3*k+2] = sLM[3*k+2]; } for (k=0; k<nmeln; ++k) { LM[3*(k+nseln) ] = mLM[3*k ]; LM[3*(k+nseln)+1] = mLM[3*k+1]; LM[3*(k+nseln)+2] = mLM[3*k+2]; } } // build the en vector en.resize(nseln+nmeln); for (k=0; k<nseln; ++k) en[k ] = se.m_node[k]; for (k=0; k<nmeln; ++k) en[k+nseln] = me.m_node[k]; // shape functions Hs = se.H(j); // secondary surface shape functions double r = pt.m_rs[0]; double s = pt.m_rs[1]; me.shape_fnc(Hm, r, s); // get normal vector vec3d nu = pt.m_nu; // gap function double g = pt.m_gap; // lagrange multiplier double Lm = pt.m_Lmd; // penalty double eps = m_epsn*pt.m_epsn*psf; // contact traction double tn = Lm + eps*g; tn = MBRACKET(tn); // double dtn = m_eps*HEAVYSIDE(Lm + eps*g); double dtn = (tn > 0.? eps :0.); // create the stiffness matrix ke.resize(ndof, ndof); ke.zero(); // --- S O L I D - S O L I D C O N T A C T --- // a. NxN-term //------------------------------------ // calculate the N-vector for (k=0; k<nseln; ++k) { N[ndpn*k ] = Hs[k]*nu.x; N[ndpn*k+1] = Hs[k]*nu.y; N[ndpn*k+2] = Hs[k]*nu.z; } for (k=0; k<nmeln; ++k) { N[ndpn*(k+nseln) ] = -Hm[k]*nu.x; N[ndpn*(k+nseln)+1] = -Hm[k]*nu.y; N[ndpn*(k+nseln)+2] = -Hm[k]*nu.z; } if (ndpn == 4) { for (k=0; k<nseln; ++k) N[ndpn*k+3] = 0; for (k=0; k<nmeln; ++k) N[ndpn*(k+nseln)+3] = 0; } for (k=0; k<ndof; ++k) for (l=0; l<ndof; ++l) ke[k][l] += dtn*N[k]*N[l]*detJ[j]*w[j]; // b. A-term //------------------------------------- for (k=0; k<nseln; ++k) N[k ] = Hs[k]; for (k=0; k<nmeln; ++k) N[k+nseln] = -Hm[k]; double* Gr = se.Gr(j); double* Gs = se.Gs(j); vec3d gs[2]; ss.CoBaseVectors(se, j, gs); mat3d S1, S2; S1.skew(gs[0]); S2.skew(gs[1]); mat3d As[FEElement::MAX_NODES]; for (l=0; l<nseln; ++l) As[l] = S2*Gr[l] - S1*Gs[l]; if (!m_bsymm) { // non-symmetric for (l=0; l<nseln; ++l) { for (k=0; k<nseln+nmeln; ++k) { ke[k*ndpn ][l*ndpn ] -= knmult*tn*w[j]*N[k]*As[l][0][0]; ke[k*ndpn ][l*ndpn+1] -= knmult*tn*w[j]*N[k]*As[l][0][1]; ke[k*ndpn ][l*ndpn+2] -= knmult*tn*w[j]*N[k]*As[l][0][2]; ke[k*ndpn+1][l*ndpn ] -= knmult*tn*w[j]*N[k]*As[l][1][0]; ke[k*ndpn+1][l*ndpn+1] -= knmult*tn*w[j]*N[k]*As[l][1][1]; ke[k*ndpn+1][l*ndpn+2] -= knmult*tn*w[j]*N[k]*As[l][1][2]; ke[k*ndpn+2][l*ndpn ] -= knmult*tn*w[j]*N[k]*As[l][2][0]; ke[k*ndpn+2][l*ndpn+1] -= knmult*tn*w[j]*N[k]*As[l][2][1]; ke[k*ndpn+2][l*ndpn+2] -= knmult*tn*w[j]*N[k]*As[l][2][2]; } } } else { // symmetric for (l=0; l<nseln; ++l) { for (k=0; k<nseln+nmeln; ++k) { ke[k*ndpn ][l*ndpn ] -= 0.5*knmult*tn*w[j]*N[k]*As[l][0][0]; ke[k*ndpn ][l*ndpn+1] -= 0.5*knmult*tn*w[j]*N[k]*As[l][0][1]; ke[k*ndpn ][l*ndpn+2] -= 0.5*knmult*tn*w[j]*N[k]*As[l][0][2]; ke[k*ndpn+1][l*ndpn ] -= 0.5*knmult*tn*w[j]*N[k]*As[l][1][0]; ke[k*ndpn+1][l*ndpn+1] -= 0.5*knmult*tn*w[j]*N[k]*As[l][1][1]; ke[k*ndpn+1][l*ndpn+2] -= 0.5*knmult*tn*w[j]*N[k]*As[l][1][2]; ke[k*ndpn+2][l*ndpn ] -= 0.5*knmult*tn*w[j]*N[k]*As[l][2][0]; ke[k*ndpn+2][l*ndpn+1] -= 0.5*knmult*tn*w[j]*N[k]*As[l][2][1]; ke[k*ndpn+2][l*ndpn+2] -= 0.5*knmult*tn*w[j]*N[k]*As[l][2][2]; ke[l*ndpn ][k*ndpn ] -= 0.5*knmult*tn*w[j]*N[k]*As[l][0][0]; ke[l*ndpn+1][k*ndpn ] -= 0.5*knmult*tn*w[j]*N[k]*As[l][0][1]; ke[l*ndpn+2][k*ndpn ] -= 0.5*knmult*tn*w[j]*N[k]*As[l][0][2]; ke[l*ndpn ][k*ndpn+1] -= 0.5*knmult*tn*w[j]*N[k]*As[l][1][0]; ke[l*ndpn+1][k*ndpn+1] -= 0.5*knmult*tn*w[j]*N[k]*As[l][1][1]; ke[l*ndpn+2][k*ndpn+1] -= 0.5*knmult*tn*w[j]*N[k]*As[l][1][2]; ke[l*ndpn ][k*ndpn+2] -= 0.5*knmult*tn*w[j]*N[k]*As[l][2][0]; ke[l*ndpn+1][k*ndpn+2] -= 0.5*knmult*tn*w[j]*N[k]*As[l][2][1]; ke[l*ndpn+2][k*ndpn+2] -= 0.5*knmult*tn*w[j]*N[k]*As[l][2][2]; } } } // c. M-term //--------------------------------------- vec3d Gm[2]; ms.ContraBaseVectors(me, r, s, Gm); // evaluate secondary surface normal vec3d mnu = Gm[0] ^ Gm[1]; mnu.unit(); double Hmr[FEElement::MAX_NODES], Hms[FEElement::MAX_NODES]; me.shape_deriv(Hmr, Hms, r, s); vec3d mm[FEElement::MAX_NODES]; for (k=0; k<nmeln; ++k) mm[k] = Gm[0]*Hmr[k] + Gm[1]*Hms[k]; if (!m_bsymm) { // non-symmetric for (k=0; k<nmeln; ++k) { for (l=0; l<nseln+nmeln; ++l) { ke[(k+nseln)*ndpn ][l*ndpn ] += tn*knmult*detJ[j]*w[j]*mnu.x*mm[k].x*N[l]; ke[(k+nseln)*ndpn ][l*ndpn+1] += tn*knmult*detJ[j]*w[j]*mnu.x*mm[k].y*N[l]; ke[(k+nseln)*ndpn ][l*ndpn+2] += tn*knmult*detJ[j]*w[j]*mnu.x*mm[k].z*N[l]; ke[(k+nseln)*ndpn+1][l*ndpn ] += tn*knmult*detJ[j]*w[j]*mnu.y*mm[k].x*N[l]; ke[(k+nseln)*ndpn+1][l*ndpn+1] += tn*knmult*detJ[j]*w[j]*mnu.y*mm[k].y*N[l]; ke[(k+nseln)*ndpn+1][l*ndpn+2] += tn*knmult*detJ[j]*w[j]*mnu.y*mm[k].z*N[l]; ke[(k+nseln)*ndpn+2][l*ndpn ] += tn*knmult*detJ[j]*w[j]*mnu.z*mm[k].x*N[l]; ke[(k+nseln)*ndpn+2][l*ndpn+1] += tn*knmult*detJ[j]*w[j]*mnu.z*mm[k].y*N[l]; ke[(k+nseln)*ndpn+2][l*ndpn+2] += tn*knmult*detJ[j]*w[j]*mnu.z*mm[k].z*N[l]; } } } else { // symmetric for (k=0; k<nmeln; ++k) { for (l=0; l<nseln+nmeln; ++l) { ke[(k+nseln)*ndpn ][l*ndpn ] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.x*mm[k].x*N[l]; ke[(k+nseln)*ndpn ][l*ndpn+1] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.x*mm[k].y*N[l]; ke[(k+nseln)*ndpn ][l*ndpn+2] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.x*mm[k].z*N[l]; ke[(k+nseln)*ndpn+1][l*ndpn ] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.y*mm[k].x*N[l]; ke[(k+nseln)*ndpn+1][l*ndpn+1] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.y*mm[k].y*N[l]; ke[(k+nseln)*ndpn+1][l*ndpn+2] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.y*mm[k].z*N[l]; ke[(k+nseln)*ndpn+2][l*ndpn ] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.z*mm[k].x*N[l]; ke[(k+nseln)*ndpn+2][l*ndpn+1] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.z*mm[k].y*N[l]; ke[(k+nseln)*ndpn+2][l*ndpn+2] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.z*mm[k].z*N[l]; ke[l*ndpn ][(k+nseln)*ndpn ] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.x*mm[k].x*N[l]; ke[l*ndpn+1][(k+nseln)*ndpn ] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.y*mm[k].x*N[l]; ke[l*ndpn+2][(k+nseln)*ndpn ] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.z*mm[k].x*N[l]; ke[l*ndpn ][(k+nseln)*ndpn+1] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.x*mm[k].y*N[l]; ke[l*ndpn+1][(k+nseln)*ndpn+1] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.y*mm[k].y*N[l]; ke[l*ndpn+2][(k+nseln)*ndpn+1] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.z*mm[k].y*N[l]; ke[l*ndpn ][(k+nseln)*ndpn+2] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.x*mm[k].z*N[l]; ke[l*ndpn+1][(k+nseln)*ndpn+2] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.y*mm[k].z*N[l]; ke[l*ndpn+2][(k+nseln)*ndpn+2] += 0.5*knmult*tn*detJ[j]*w[j]*mnu.z*mm[k].z*N[l]; } } } // --- B I P H A S I C S T I F F N E S S --- if (sporo && mporo) { // the variable dt is either the timestep or one // depending on whether we are using the symmetric // poro version or not. double dt = fem.GetTime().timeIncrement; double epsp = (tn > 0) ? m_epsp*pt.m_epsp*psf : 0.; // --- S O L I D - P R E S S U R E C O N T A C T --- if (!m_bsymm) { // a. q-term //------------------------------------- double dpmr, dpms; dpmr = me.eval_deriv1(pm, r, s); dpms = me.eval_deriv2(pm, r, s); for (k=0; k<nseln+nmeln; ++k) for (l=0; l<nseln+nmeln; ++l) { ke[4*k + 3][4*l ] += dt*w[j]*detJ[j]*epsp*N[k]*N[l]*(dpmr*Gm[0].x + dpms*Gm[1].x); ke[4*k + 3][4*l+1] += dt*w[j]*detJ[j]*epsp*N[k]*N[l]*(dpmr*Gm[0].y + dpms*Gm[1].y); ke[4*k + 3][4*l+2] += dt*w[j]*detJ[j]*epsp*N[k]*N[l]*(dpmr*Gm[0].z + dpms*Gm[1].z); } double wn = pt.m_Lmp + epsp*pt.m_pg; // b. A-term //------------------------------------- for (l=0; l<nseln; ++l) for (k=0; k<nseln+nmeln; ++k) { ke[4*k + 3][4*l ] -= dt*w[j]*wn*N[k]*(As[l][0][0]*nu.x + As[l][0][1]*nu.y + As[l][0][2]*nu.z); ke[4*k + 3][4*l+1] -= dt*w[j]*wn*N[k]*(As[l][1][0]*nu.x + As[l][1][1]*nu.y + As[l][1][2]*nu.z); ke[4*k + 3][4*l+2] -= dt*w[j]*wn*N[k]*(As[l][2][0]*nu.x + As[l][2][1]*nu.y + As[l][2][2]*nu.z); } // c. m-term //--------------------------------------- for (k=0; k<nmeln; ++k) for (l=0; l<nseln+nmeln; ++l) { ke[4*(k+nseln) + 3][4*l ] += dt*w[j]*detJ[j]*wn*N[l]*mm[k].x; ke[4*(k+nseln) + 3][4*l+1] += dt*w[j]*detJ[j]*wn*N[l]*mm[k].y; ke[4*(k+nseln) + 3][4*l+2] += dt*w[j]*detJ[j]*wn*N[l]*mm[k].z; } } // --- P R E S S U R E - P R E S S U R E C O N T A C T --- // calculate the N-vector for (k=0; k<nseln; ++k) { N[ndpn*k ] = 0; N[ndpn*k+1] = 0; N[ndpn*k+2] = 0; N[ndpn*k+3] = Hs[k]; } for (k=0; k<nmeln; ++k) { N[ndpn*(k+nseln) ] = 0; N[ndpn*(k+nseln)+1] = 0; N[ndpn*(k+nseln)+2] = 0; N[ndpn*(k+nseln)+3] = -Hm[k]; } for (k=0; k<ndof; ++k) for (l=0; l<ndof; ++l) ke[k][l] -= dt*epsp*w[j]*detJ[j]*N[k]*N[l]; } // assemble the global stiffness ke.SetNodes(en); ke.SetIndices(LM); LS.Assemble(ke); } } } } } //----------------------------------------------------------------------------- void FESlidingInterface2::UpdateContactPressures() { int npass = (m_btwo_pass?2:1); for (int np=0; np<npass; ++np) { FESlidingSurface2& ss = (np == 0? m_ss : m_ms); FESlidingSurface2& ms = (np == 0? m_ms : m_ss); // loop over all elements of the primary surface for (int n=0; n<ss.Elements(); ++n) { FESurfaceElement& el = ss.Element(n); int nint = el.GaussPoints(); // get the normal tractions at the integration points double gap, eps; for (int i=0; i<nint; ++i) { // get integration point data FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(i)); gap = pt.m_gap; eps = m_epsn*pt.m_epsn; pt.m_Ln = MBRACKET(pt.m_Lmd + eps*gap); FESurfaceElement* pme = pt.m_pme; if (m_btwo_pass && pme) { int mint = pme->GaussPoints(); double ti[FEElement::MAX_NODES]; for (int j=0; j<mint; ++j) { FEBiphasicContactPoint& mp = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); gap = mp.m_gap; eps = m_epsn*mp.m_epsn; ti[j] = MBRACKET(mp.m_Lmd + m_epsn*mp.m_epsn*mp.m_gap); } // project the data to the nodes double tn[FEElement::MAX_NODES]; pme->FEElement::project_to_nodes(ti, tn); // now evaluate the traction at the intersection point double Ln = pme->eval(tn, pt.m_rs[0], pt.m_rs[1]); pt.m_Ln += MBRACKET(Ln); } } } ss.EvaluateNodalContactPressures(); } } //----------------------------------------------------------------------------- bool FESlidingInterface2::Augment(int naug, const FETimeInfo& tp) { // make sure we need to augment if (m_laugon != FECore::AUGLAG_METHOD) return true; double Ln, Lp; bool bconv = true; bool bporo = (m_ss.m_bporo && m_ms.m_bporo); int NS = m_ss.Elements(); int NM = m_ms.Elements(); // --- c a l c u l a t e i n i t i a l n o r m s --- // a. normal component double normL0 = 0, normP = 0, normDP = 0; for (int i=0; i<NS; ++i) { FESurfaceElement& el = m_ss.Element(i); for (int j=0; j<el.GaussPoints(); ++j) { FEBiphasicContactPoint& ds = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); normL0 += ds.m_Lmd*ds.m_Lmd; } } for (int i=0; i<NM; ++i) { FESurfaceElement& el = m_ms.Element(i); for (int j = 0; j<el.GaussPoints(); ++j) { FEBiphasicContactPoint& dm = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); normL0 += dm.m_Lmd*dm.m_Lmd; } } // b. gap component // (is calculated during update) double maxgap = 0; double maxpg = 0; // update Lagrange multipliers double normL1 = 0, eps, epsp; for (int i=0; i<m_ss.Elements(); ++i) { FESurfaceElement& el = m_ss.Element(i); vec3d tn[FEElement::MAX_INTPOINTS]; if (m_bsmaug) m_ss.GetGPSurfaceTraction(i, tn); for (int j=0; j<el.GaussPoints(); ++j) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); // update Lagrange multipliers on primary surface if (m_bsmaug) { // replace this multiplier with a smoother version Ln = -(tn[j]*data.m_nu); data.m_Lmd = MBRACKET(Ln); if (m_btwo_pass) data.m_Lmd /= 2; } else { eps = m_epsn*data.m_epsn; Ln = data.m_Lmd + eps*data.m_gap; data.m_Lmd = MBRACKET(Ln); } normL1 += data.m_Lmd*data.m_Lmd; if (m_ss.m_bporo) { Lp = 0; if (Ln > 0) { epsp = m_epsp*data.m_epsp; Lp = data.m_Lmp + epsp*data.m_pg; maxpg = max(maxpg,fabs(data.m_pg)); normDP += data.m_pg*data.m_pg; } data.m_Lmp = Lp; } if (Ln > 0) maxgap = max(maxgap,fabs(data.m_gap)); } } for (int i=0; i<m_ms.Elements(); ++i) { FESurfaceElement& el = m_ms.Element(i); vec3d tn[FEElement::MAX_INTPOINTS]; if (m_bsmaug) m_ms.GetGPSurfaceTraction(i, tn); for (int j=0; j<el.GaussPoints(); ++j) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); // update Lagrange multipliers on secondary surface if (m_bsmaug) { // replace this multiplier with a smoother version Ln = -(tn[j]*data.m_nu); data.m_Lmd = MBRACKET(Ln); if (m_btwo_pass) data.m_Lmd /= 2; } else { eps = m_epsn*data.m_epsn; Ln = data.m_Lmd + eps*data.m_gap; data.m_Lmd = MBRACKET(Ln); } normL1 += data.m_Lmd*data.m_Lmd; if (m_ms.m_bporo) { Lp = 0; if (Ln > 0) { epsp = m_epsp*data.m_epsp; Lp = data.m_Lmp + epsp*data.m_pg; maxpg = max(maxpg,fabs(data.m_pg)); normDP += data.m_pg*data.m_pg; } data.m_Lmp = Lp; } if (Ln > 0) maxgap = max(maxgap,fabs(data.m_gap)); } } // normP should be a measure of the fluid pressure at the // contact interface. However, since it could be zero, // use an average measure of the contact traction instead. normP = normL1; // calculate relative norms double lnorm = (normL1 != 0 ? fabs((normL1 - normL0) / normL1) : fabs(normL1 - normL0)); double pnorm = (normP != 0 ? (normDP/normP) : normDP); // check convergence if ((m_gtol > 0) && (maxgap > m_gtol)) bconv = false; if ((m_ptol > 0) && (bporo && maxpg > m_ptol)) bconv = false; if ((m_atol > 0) && (lnorm > m_atol)) bconv = false; if ((m_atol > 0) && (pnorm > m_atol)) bconv = false; if (naug < m_naugmin ) bconv = false; if (naug >= m_naugmax) bconv = true; feLog(" sliding interface # %d\n", GetID()); feLog(" CURRENT REQUIRED\n"); feLog(" D multiplier : %15le", lnorm); if (m_atol > 0) feLog("%15le\n", m_atol); else feLog(" ***\n"); if (bporo) { feLog(" P gap : %15le", pnorm); if (m_atol > 0) feLog("%15le\n", m_atol); else feLog(" ***\n"); } feLog(" maximum gap : %15le", maxgap); if (m_gtol > 0) feLog("%15le\n", m_gtol); else feLog(" ***\n"); if (bporo) { feLog(" maximum pgap : %15le", maxpg); if (m_ptol > 0) feLog("%15le\n", m_ptol); else feLog(" ***\n"); } if (bconv) UpdateContactPressures(); return bconv; } //----------------------------------------------------------------------------- void FESlidingInterface2::Serialize(DumpStream &ar) { // serialize contact data FEContactInterface::Serialize(ar); // serialize contact surface data m_ms.Serialize(ar); m_ss.Serialize(ar); // serialize pointers for deep streaming SerializeElementPointers(m_ss, m_ms, ar); SerializeElementPointers(m_ms, m_ss, ar); } //----------------------------------------------------------------------------- void FESlidingInterface2::MarkFreeDraining() { int i, id, np; // Mark all nodes as free-draining. This needs to be done for ALL // contact interfaces prior to executing Update(), where nodes that are // in contact are subsequently marked as non free-draining. This ensures // that for surfaces involved in more than one contact interface, nodes // that have been marked as non free-draining are not reset to // free-draining. for (np=0; np<2; ++np) { FESlidingSurface2& s = (np == 0? m_ss : m_ms); if (s.m_bporo) { // first, mark all nodes as free-draining (= neg. ID) // this is done by setting the dof's equation number // to a negative number for (i=0; i<s.Nodes(); ++i) { id = s.Node(i).m_ID[m_dofP]; if (id >= 0) { FENode& node = s.Node(i); // mark node as free-draining node.m_ID[m_dofP] = -id-2; } } } } } //----------------------------------------------------------------------------- void FESlidingInterface2::SetFreeDraining() { int i, np; // Set the pressure to zero for the free-draining nodes for (np=0; np<2; ++np) { FESlidingSurface2& s = (np == 0? m_ss : m_ms); if (s.m_bporo) { // loop over all nodes for (i=0; i<s.Nodes(); ++i) { if (s.Node(i).m_ID[m_dofP] < -1) { FENode& node = s.Node(i); // set the fluid pressure to zero node.set(m_dofP, 0); } } } } }
C++
3D
febiosoftware/FEBio
FEBioMix/FESolventSupplyStarling.cpp
.cpp
3,792
115
/*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 <sstream> #include <iostream> #include <cstdlib> #include "FESolventSupplyStarling.h" #include "FESolutesMaterialPoint.h" #include "FECore/FEModel.h" // define the material parameters BEGIN_FECORE_CLASS(FESolventSupplyStarling, FESolventSupply) ADD_PARAMETER(m_kp, "kp")->setLongName("filtration coefficient"); ADD_PARAMETER(m_pv, "pv")->setLongName("external pressure"); END_FECORE_CLASS(); //----------------------------------------------------------------------------- //! Constructor. FESolventSupplyStarling::FESolventSupplyStarling(FEModel* pfem) : FESolventSupply(pfem) { m_kp = 0; m_pv = 0; // get number of DOFS DOFS& fedofs = pfem->GetDOFS(); int MAX_CDOFS = fedofs.GetVariableSize("concentration"); if (MAX_CDOFS > 0) { FEParamDouble tmp; tmp = 0; m_qc.assign(MAX_CDOFS,tmp); m_cv.assign(MAX_CDOFS,tmp); } } //----------------------------------------------------------------------------- //! Solvent supply double FESolventSupplyStarling::Supply(FEMaterialPoint& mp) { FEBiphasicMaterialPoint& ppt = *mp.ExtractData<FEBiphasicMaterialPoint>(); FESolutesMaterialPoint* mpt = mp.ExtractData<FESolutesMaterialPoint>(); // evaluate solvent supply from pressure drop double kp = m_kp(mp); double pv = m_pv(mp); double phiwhat = kp*(pv - ppt.m_p); // evaluate solvent supply from concentration drop if (mpt) { int nsol = mpt->m_nsol; for (int isol=0; isol<nsol; ++isol) { double qc = m_qc[isol](mp); double cv = m_cv[isol](mp); phiwhat += qc*(cv - mpt->m_c[isol]); } } return phiwhat; } //----------------------------------------------------------------------------- //! Tangent of solvent supply with respect to strain mat3ds FESolventSupplyStarling::Tangent_Supply_Strain(FEMaterialPoint &mp) { mat3dd Phie(Supply(mp)); return Phie; } //----------------------------------------------------------------------------- //! Tangent of solvent supply with respect to pressure double FESolventSupplyStarling::Tangent_Supply_Pressure(FEMaterialPoint &mp) { return -m_kp(mp); } //----------------------------------------------------------------------------- //! Tangent of solvent supply with respect to concentration double FESolventSupplyStarling::Tangent_Supply_Concentration(FEMaterialPoint &mp, const int isol) { FESolutesMaterialPoint& mpt = *mp.ExtractData<FESolutesMaterialPoint>(); if (isol < mpt.m_nsol) { return -m_qc[isol](mp); } return 0; }
C++
3D
febiosoftware/FEBio
FEBioMix/FEPorousNeoHookean.h
.h
2,707
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 <FEBioMech/FEElasticMaterial.h> #include <FECore/FEModelParam.h> #include "febiomix_api.h" //----------------------------------------------------------------------------- //! Porous Neo Hookean material //! This compressible material produces infinite stress as the porosity approaches //! zero (i.e., when J = 1 - porosity). This behavior helps to prevent pore collape. //! Implementation of a porous neo-Hookean hyperelastic material. class FEBIOMIX_API FEPorousNeoHookean : public FEElasticMaterial { public: FEPorousNeoHookean(FEModel* pfem) : FEElasticMaterial(pfem) { m_phisr = 1; m_lam = 0; } public: FEParamDouble m_E; //!< Young's modulus FEParamDouble m_lam; //!< first Lamé coefficient FEParamDouble m_phisr; //!< referential solidity public: //! initialize the material bool Init() override; //! calculate stress at material point mat3ds Stress(FEMaterialPoint& pt) override; //! calculate tangent stiffness at material point tens4ds Tangent(FEMaterialPoint& pt) override; //! calculate strain energy density at material point double StrainEnergyDensity(FEMaterialPoint& pt) override; //! calculate the referential solid volume fraction at material point double ReferentialSolidVolumeFraction(FEMaterialPoint& pt); // declare the parameter list DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FEReactionRateConst.cpp
.cpp
1,525
36
/*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 "FEReactionRateConst.h" // Material parameters for the FEReactionRateConst material BEGIN_FECORE_CLASS(FEReactionRateConst, FEReactionRate) ADD_PARAMETER(m_k, FE_RANGE_GREATER_OR_EQUAL(0.0), "k"); END_FECORE_CLASS();
C++
3D
febiosoftware/FEBio
FEBioMix/FEMichaelisMenten.cpp
.cpp
5,286
172
/*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 "FEMichaelisMenten.h" #include "FESoluteInterface.h" #include "FEMultiphasic.h" #include <FECore/log.h> // define the material parameters BEGIN_FECORE_CLASS(FEMichaelisMenten, FEChemicalReaction) ADD_PARAMETER(m_Km, "Km"); ADD_PARAMETER(m_c0, "c0"); // set material properties ADD_PROPERTY(m_pFwd, "forward_rate", FEProperty::Optional); END_FECORE_CLASS(); #ifndef SQR #define SQR(x) ((x)*(x)) #endif //----------------------------------------------------------------------------- FEMichaelisMenten::FEMichaelisMenten(FEModel* pfem) : FEChemicalReaction(pfem) { m_Rid = m_Pid = -1; m_Km = m_c0 = 0; m_Rtype = false; } //----------------------------------------------------------------------------- //! data initialization and checking bool FEMichaelisMenten::Init() { // Initialize base class if (FEChemicalReaction::Init() == false) return false; // there is only one reactant and one product in a Michaelis-Menten reaction if (m_solR.size() + m_sbmR.size() > 1) { feLogError("Provide only one vR for this reaction"); return false; } if (m_solP.size() + m_sbmP.size() > 1) { feLogError("Provide only one vP for this reaction"); return false; } if (m_c0 < 0) { feLogError("c0 must be positive"); return false; } const int ntot = (int)m_v.size(); for (int itot=0; itot<ntot; itot++) { if (m_vR[itot] > 0) m_Rid = itot; if (m_vP[itot] > 0) m_Pid = itot; } if (m_Rid == -1) { feLogError("Provide vR for the reactant"); return false; } // check if reactant is a solute or a solid-bound molecule if (m_Rid >= m_nsol) m_Rtype = true; return true; } //----------------------------------------------------------------------------- //! molar supply at material point double FEMichaelisMenten::ReactionSupply(FEMaterialPoint& pt) { // get reaction rate double Vmax = m_pFwd->ReactionRate(pt); double c = 0.0; if (m_Rtype) { c = m_psm->SBMConcentration(pt, m_Rid); } else { c = m_psm->GetActualSoluteConcentration(pt, m_Rid); } double zhat = 0; if (c > m_c0) zhat = Vmax*c/(m_Km + c); return zhat; } //----------------------------------------------------------------------------- //! tangent of molar supply with strain at material point mat3ds FEMichaelisMenten::Tangent_ReactionSupply_Strain(FEMaterialPoint& pt) { double ca = 0.0; double dcdJ = 0.0; if (m_Rtype) { FEBiphasicInterface* pbm = dynamic_cast<FEBiphasicInterface*>(GetAncestor()); assert(pbm); FEElasticMaterialPoint& ept = *pt.ExtractData<FEElasticMaterialPoint>(); ca = m_psm->SBMConcentration(pt, m_Rid); double J = ept.m_J; double phi0 = pbm->GetReferentialSolidVolumeFraction(pt); dcdJ = -ca/(J-phi0); } else { ca = m_psm->GetActualSoluteConcentration(pt, m_Rid); double c = m_psm->GetEffectiveSoluteConcentration(pt, m_Rid); double dkdJ = m_psm->dkdJ(pt, m_Rid); dcdJ = dkdJ*c; } double dzhatdJ = 0; if (ca > m_c0) { double Vmax = m_pFwd->ReactionRate(pt); dzhatdJ = dcdJ*m_Km*Vmax/SQR(m_Km + ca); } return mat3dd(1)*dzhatdJ; } //----------------------------------------------------------------------------- //! tangent of molar supply with effective pressure at material point double FEMichaelisMenten::Tangent_ReactionSupply_Pressure(FEMaterialPoint& pt) { return 0; } //----------------------------------------------------------------------------- //! tangent of molar supply with effective concentration at material point double FEMichaelisMenten::Tangent_ReactionSupply_Concentration(FEMaterialPoint& pt, const int sol) { if (m_Rtype || (m_Rid != sol)) return 0; double dzhatdc = 0; double ca = m_psm->GetActualSoluteConcentration(pt, m_Rid); if (ca > m_c0) { double Vmax = m_pFwd->ReactionRate(pt); double k = m_psm->GetPartitionCoefficient(pt, m_Rid); double c = m_psm->GetEffectiveSoluteConcentration(pt, m_Rid); double dkdc = m_psm->dkdc(pt, m_Rid, m_Rid); dzhatdc = m_Km*Vmax/SQR(m_Km + ca)*(k + dkdc*c); } return dzhatdc; }
C++
3D
febiosoftware/FEBio
FEBioMix/FETiedBiphasicInterface.h
.h
5,544
170
/*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 <FEBioMech/FEContactInterface.h> #include "FEBiphasicContactSurface.h" //----------------------------------------------------------------------------- class FEBIOMIX_API FETiedBiphasicContactPoint: public FEBiphasicContactPoint { public: vec3d m_Gap; //!< initial gap in reference configuration vec3d m_dg; //!< gap function at integration points vec3d m_nu; //!< normal at integration points vec2d m_rs; //!< natural coordinates of projection of integration point vec3d m_Lmd; //!< lagrange multipliers for displacements vec3d m_tr; //!< contact traction double m_epsn; //!< penalty factors double m_epsp; //!< pressure penalty factors void Init() override { FEBiphasicContactPoint::Init(); m_Gap = m_dg = m_nu = m_Lmd = m_tr = vec3d(0,0,0); m_rs = vec2d(0,0); m_epsn = 1.0; m_epsp = 1.0; } void Serialize(DumpStream& ar) override; }; //----------------------------------------------------------------------------- class FEBIOMIX_API FETiedBiphasicSurface : public FEBiphasicContactSurface { public: //! constructor FETiedBiphasicSurface(FEModel* pfem); //! initialization bool Init() override; //! create material point data FEMaterialPoint* CreateMaterialPoint() override; //! calculate the nodal normals void UpdateNodeNormals(); void Serialize(DumpStream& ar) override; void SetPoroMode(bool bporo) { m_bporo = bporo; } public: void GetVectorGap (int nface, vec3d& pg) override; void GetContactTraction(int nface, vec3d& pt) override; public: bool m_bporo; //!< set poro-mode vector<bool> m_poro; //!< surface element poro status vector<vec3d> m_nn; //!< node normals }; //----------------------------------------------------------------------------- class FEBIOMIX_API FETiedBiphasicInterface : public FEContactInterface { public: //! constructor FETiedBiphasicInterface(FEModel* pfem); //! destructor ~FETiedBiphasicInterface(); //! initialization bool Init() override; //! interface activation void Activate() override; //! serialize data to archive void Serialize(DumpStream& ar) override; //! return the primary and secondary surface FESurface* GetPrimarySurface() override { return &m_ss; } FESurface* GetSecondarySurface() override { return &m_ms; } //! return integration rule class bool UseNodalIntegration() override { return false; } //! build the matrix profile for use in the stiffness matrix void BuildMatrixProfile(FEGlobalMatrix& K) override; public: //! calculate contact forces void LoadVector(FEGlobalVector& R, const FETimeInfo& tp) override; //! calculate contact stiffness void StiffnessMatrix(FELinearSystem& LS, const FETimeInfo& tp) override; //! calculate Lagrangian augmentations bool Augment(int naug, const FETimeInfo& tp) override; //! update void Update() override; protected: void InitialProjection(FETiedBiphasicSurface& ss, FETiedBiphasicSurface& ms); void ProjectSurface(FETiedBiphasicSurface& ss, FETiedBiphasicSurface& ms); //! calculate penalty factor void UpdateAutoPenalty(); void CalcAutoPenalty(FETiedBiphasicSurface& s); void CalcAutoPressurePenalty(FETiedBiphasicSurface& s); double AutoPressurePenalty(FESurfaceElement& el, FETiedBiphasicSurface& s); public: FETiedBiphasicSurface m_ss; //!< primary surface FETiedBiphasicSurface m_ms; //!< secondary surface int m_knmult; //!< higher order stiffness multiplier bool m_btwo_pass; //!< two-pass flag double m_atol; //!< augmentation tolerance double m_gtol; //!< gap tolerance double m_ptol; //!< pressure gap tolerance double m_stol; //!< search tolerance bool m_bsymm; //!< use symmetric stiffness components only double m_srad; //!< contact search radius int m_naugmax; //!< maximum nr of augmentations int m_naugmin; //!< minimum nr of augmentations double m_epsn; //!< normal penalty factor bool m_bautopen; //!< use autopenalty factor bool m_bupdtpen; //!< update penalty at each time step // biphasic contact parameters double m_epsp; //!< flow rate penalty protected: int m_dofP; DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FETiedMultiphasicInterface.h
.h
6,560
185
/*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 "FETiedBiphasicInterface.h" #include "FESolute.h" //----------------------------------------------------------------------------- class FEBIOMIX_API FETiedMultiphasicContactPoint: public FETiedBiphasicContactPoint { public: vector<double> m_Lmc; //!< Lagrange multipliers for solute concentrations vector<double> m_epsc; //!< concentration penatly factors vector<double> m_cg; //!< concentration "gap" void Init() override { FEBiphasicContactPoint::Init(); m_Gap = m_dg = m_nu = m_Lmd = m_tr = vec3d(0,0,0); m_rs = vec2d(0,0); m_epsn = 1.0; m_epsp = 1.0; } void Serialize(DumpStream& ar) override; }; //----------------------------------------------------------------------------- class FEBIOMIX_API FETiedMultiphasicSurface : public FEBiphasicContactSurface { public: //! constructor FETiedMultiphasicSurface(FEModel* pfem); //! initialization bool Init() override; //! calculate the nodal normals void UpdateNodeNormals(); void Serialize(DumpStream& ar) override; void SetPoroMode(bool bporo) { m_bporo = bporo; } void UnpackLM(FEElement& el, vector<int>& lm) override; //! create material point data FEMaterialPoint* CreateMaterialPoint() override; public: bool m_bporo; //!< set poro-mode bool m_bsolu; //!< set solute-mode vector<bool> m_poro; //!< surface element poro status vector<vec3d> m_nn; //!< node normals vector<int> m_sid; //!< list of solute id's for this surface protected: int m_dofC; }; //----------------------------------------------------------------------------- class FETiedMultiphasicInterface : public FEContactInterface { public: //! constructor FETiedMultiphasicInterface(FEModel* pfem); //! destructor ~FETiedMultiphasicInterface(); //! initialization bool Init() override; //! interface activation void Activate() override; //! serialize data to archive void Serialize(DumpStream& ar) override; //! return the primary and secondary surface FESurface* GetPrimarySurface() override { return &m_ss; } FESurface* GetSecondarySurface() override { return &m_ms; } //! return integration rule class bool UseNodalIntegration() override { return false; } //! build the matrix profile for use in the stiffness matrix void BuildMatrixProfile(FEGlobalMatrix& K) override; public: //! calculate contact forces void LoadVector(FEGlobalVector& R, const FETimeInfo& tp) override; //! calculate contact stiffness void StiffnessMatrix(FELinearSystem& LS, const FETimeInfo& tp) override; //! calculate Lagrangian augmentations bool Augment(int naug, const FETimeInfo& tp) override; //! update void Update() override; protected: void InitialProjection(FETiedMultiphasicSurface& ss, FETiedMultiphasicSurface& ms); void ProjectSurface(FETiedMultiphasicSurface& ss, FETiedMultiphasicSurface& ms); //! calculate penalty factor void UpdateAutoPenalty(); void CalcAutoPenalty(FETiedMultiphasicSurface& s); void CalcAutoPressurePenalty(FETiedMultiphasicSurface& s); double AutoPressurePenalty(FESurfaceElement& el, FETiedMultiphasicSurface& s); void CalcAutoConcentrationPenalty(FETiedMultiphasicSurface& s, const int isol); double AutoConcentrationPenalty(FESurfaceElement& el, FETiedMultiphasicSurface& s, const int isol); double AutoPenalty(FESurfaceElement& el, FESurface &s); //! get solute data FESoluteData* FindSoluteData(int nid); public: FETiedMultiphasicSurface m_ss; //!< primary surface FETiedMultiphasicSurface m_ms; //!< secondary surface int m_knmult; //!< higher order stiffness multiplier bool m_btwo_pass; //!< two-pass flag double m_atol; //!< augmentation tolerance double m_gtol; //!< gap tolerance double m_ptol; //!< pressure gap tolerance double m_ctol; //!< concentration gap tolerance double m_stol; //!< search tolerance bool m_bsymm; //!< use symmetric stiffness components only double m_srad; //!< contact search radius int m_naugmax; //!< maximum nr of augmentations int m_naugmin; //!< minimum nr of augmentations double m_epsn; //!< normal penalty factor bool m_bautopen; //!< use autopenalty factor bool m_bupdtpen; //!< update penalty at each time step // multiphasic contact parameters double m_epsp; //!< fluid flow rate penalty double m_epsc; //!< solute molar flow rate penalty double m_Rgas; //!< universal gas constant double m_Tabs; //!< absolute temperature vector<int> m_sid; //!< list of solute ids common to both contact surfaces vector<int> m_ssl; //!< list of primary surface solutes common to both contact surfaces vector<int> m_msl; //!< list of secondary surface solutes common to both contact surfaces vector<int> m_sz; //!< charge number of solutes common to both contact surfaces protected: int m_dofP; int m_dofC; DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FEMultiphasicAnalysis.cpp
.cpp
1,694
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.*/ #include "FEMultiphasicAnalysis.h" BEGIN_FECORE_CLASS(FEMultiphasicAnalysis, FEAnalysis) // The analysis parameter is already defined in the FEAnalysis base class. // Here, we just need to set the enum values for the analysis parameter. FindParameterFromData(&m_nanalysis)->setEnums("STEADY-STATE\0TRANSIENT\0"); END_FECORE_CLASS() FEMultiphasicAnalysis::FEMultiphasicAnalysis(FEModel* fem) : FEAnalysis(fem) { }
C++
3D
febiosoftware/FEBio
FEBioMix/FEMatchingOsmoticCoefficientBC.cpp
.cpp
5,866
161
/*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 "FEMatchingOsmoticCoefficientBC.h" #include "FEBioMix.h" #include <FECore/FEModel.h> //============================================================================= BEGIN_FECORE_CLASS(FEMatchingOsmoticCoefficientBC, FEPrescribedSurface) ADD_PARAMETER(m_ambp , "ambient_pressure"); ADD_PARAMETER(m_ambc , "ambient_osmolarity"); ADD_PARAMETER(m_bshellb , "shell_bottom"); END_FECORE_CLASS(); //----------------------------------------------------------------------------- //! constructor FEMatchingOsmoticCoefficientBC::FEMatchingOsmoticCoefficientBC(FEModel* pfem) : FEPrescribedSurface(pfem) { m_ambp = m_ambc = 0.0; m_bshellb = false; m_dofP = pfem->GetDOFIndex("p"); m_dofQ = pfem->GetDOFIndex("q"); } //----------------------------------------------------------------------------- //! Activate the degrees of freedom for this BC void FEMatchingOsmoticCoefficientBC::Activate() { FESurface* ps = GetSurface(); FEModel* fem = GetFEModel(); for (int i=0; i<ps->Elements(); ++i) { FESurfaceElement& el = ps->Element(i); // get the element connected to this surface FEElement* elem = el.m_elem[0].pe; FEMaterial* pm = fem->GetMaterial(elem->GetMatID()); // get the multihasic material for this element FEMultiphasic* pmp = dynamic_cast<FEMultiphasic*>(pm); // if the material is multiphasic, set prescribable fluid dofs if (pmp) { for (int j=0; j<el.Nodes(); ++j) { FENode& node = ps->Node(el.m_lnode[j]); // mark node as having prescribed DOF if (!m_bshellb) node.set_bc(m_dofP, DOF_PRESCRIBED); else node.set_bc(m_dofQ, DOF_PRESCRIBED); } } } // NOTE: Hmmm, not sure about this one. Maybe skip immediate base class? // FEPrescribedSurface::Activate(); FESurfaceBC::Activate(); } //----------------------------------------------------------------------------- //! Evaluate and prescribe the ambient effective fluid pressure, using the multiphasic osmotic coefficient void FEMatchingOsmoticCoefficientBC::Update() { FESurface* ps = GetSurface(); FEModel* fem = GetFEModel(); vector<double> pn(ps->Nodes(),0); vector<int> cnt(ps->Nodes(),0); for (int i=0; i<ps->Elements(); ++i) { FESurfaceElement& el = ps->Element(i); // get the element connected to this surface FEElement* elem = el.m_elem[0].pe; FEMaterial* pm = fem->GetMaterial(elem->GetMatID()); // get the multihasic material for this element FEMultiphasic* pmp = dynamic_cast<FEMultiphasic*>(pm); double Phi = 0; if (pmp) { // get average osmotic coefficient in this multiphasic element int nint = elem->GaussPoints(); for (int n=0; n<nint; ++n) { FEMaterialPoint& mp = *elem->GetMaterialPoint(n); Phi += pmp->GetOsmoticCoefficient()->OsmoticCoefficient(mp); } Phi /= nint; // evaluate effective fluid pressure on the boundary double pe = m_ambp - pmp->m_Rgas*pmp->m_Tabs*Phi*m_ambc; // project to nodes of that face for (int j=0; j<el.Nodes(); ++j) { int n = el.m_lnode[j]; pn[n] += pe; ++cnt[n]; } } } // prescribe the projected nodal values of the effective fluid pressure for (int i=0; i<ps->Nodes(); ++i) { if (ps->Node(i).m_ID[m_dofP] < -1) { assert(cnt[i]); FENode& node = ps->Node(i); // prescribe effective pressure at this node double pe = pn[i]/cnt[i]; if (!m_bshellb) node.set(m_dofP, pe); else node.set(m_dofQ, pe); } } } //----------------------------------------------------------------------------- void FEMatchingOsmoticCoefficientBC::GetNodalValues(int nodelid, std::vector<double>& val) { // TODO: implement this assert(false); } //----------------------------------------------------------------------------- void FEMatchingOsmoticCoefficientBC::CopyFrom(FEBoundaryCondition* pbc) { // TODO: implement this assert(false); } //----------------------------------------------------------------------------- //! serialization void FEMatchingOsmoticCoefficientBC::Serialize(DumpStream& ar) { FEPrescribedSurface::Serialize(ar); if (ar.IsShallow() == false) { ar& m_dofP; ar& m_dofQ; } }
C++
3D
febiosoftware/FEBio
FEBioMix/FESolubConst.h
.h
2,520
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 "FEBiphasicSolute.h" //----------------------------------------------------------------------------- // This class implements a material that has a constant solute solubility class FEBIOMIX_API FESolubConst : public FESoluteSolubility { public: //! constructor FESolubConst(FEModel* pfem); //! solubility double Solubility(FEMaterialPoint& pt) override; //! Tangent of solubility with respect to strain double Tangent_Solubility_Strain(FEMaterialPoint& mp) override; //! Tangent of solubility with respect to concentration double Tangent_Solubility_Concentration(FEMaterialPoint& mp, const int isol) override; //! Cross derivative of solubility with respect to strain and concentration double Tangent_Solubility_Strain_Concentration(FEMaterialPoint& mp, const int isol) override; //! Second derivative of solubility with respect to strain double Tangent_Solubility_Strain_Strain(FEMaterialPoint& mp) override; //! Second derivative of solubility with respect to concentration double Tangent_Solubility_Concentration_Concentration(FEMaterialPoint& mp, const int isol, const int jsol) override; public: double m_solub; //!< solubility // declare parameter list DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FEPermConstIso.cpp
.cpp
2,190
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 "FEPermConstIso.h" // define the material parameters BEGIN_FECORE_CLASS(FEPermConstIso, FEHydraulicPermeability) ADD_PARAMETER(m_perm, FE_RANGE_GREATER_OR_EQUAL(0.0), "perm")->setUnits(UNIT_PERMEABILITY); END_FECORE_CLASS(); //----------------------------------------------------------------------------- //! Constructor. FEPermConstIso::FEPermConstIso(FEModel* pfem) : FEHydraulicPermeability(pfem) { m_perm = 1; } //----------------------------------------------------------------------------- //! Permeability tensor. mat3ds FEPermConstIso::Permeability(FEMaterialPoint& mp) { // --- constant isotropic permeability --- return mat3dd(m_perm(mp)); } //----------------------------------------------------------------------------- //! Tangent of permeability tens4dmm FEPermConstIso::Tangent_Permeability_Strain(FEMaterialPoint &mp) { tens4dmm K; K.zero(); return K; }
C++
3D
febiosoftware/FEBio
FEBioMix/FEBioMix.h
.h
1,751
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"febiomix_api.h" //----------------------------------------------------------------------------- //! The FEBioMix module //! The FEBioMix module adds mixture capabilites to FEBio, including biphasic, //! biphasic-solute, multiphasic, charged solutes and chemical reations. //! namespace FEBioMix { FEBIOMIX_API void InitModule(); enum FEBIOMIX_VARIABLE { FLUID_PRESSURE }; FEBIOMIX_API const char* GetVariableName(FEBIOMIX_VARIABLE var); }
Unknown
3D
febiosoftware/FEBio
FEBioMix/FEFixedFluidPressure.cpp
.cpp
1,619
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) 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.*/ #include "stdafx.h" #include "FEFixedFluidPressure.h" BEGIN_FECORE_CLASS(FEFixedFluidPressure, FEFixedBC) END_FECORE_CLASS(); FEFixedFluidPressure::FEFixedFluidPressure(FEModel* fem) : FEFixedBC(fem) { } bool FEFixedFluidPressure::Init() { vector<int> dofs; dofs.push_back(GetDOFIndex("p")); SetDOFList(dofs); return FEFixedBC::Init(); }
C++
3D
febiosoftware/FEBio
FEBioMix/FEMassActionReversibleEffective.cpp
.cpp
6,770
200
/*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 "FEMassActionReversibleEffective.h" #include "FESoluteInterface.h" #include "FEBiphasic.h" BEGIN_FECORE_CLASS(FEMassActionReversibleEffective, FEChemicalReaction) // set material properties ADD_PROPERTY(m_pFwd, "forward_rate", FEProperty::Optional); ADD_PROPERTY(m_pRev, "reverse_rate", FEProperty::Optional); END_FECORE_CLASS(); //----------------------------------------------------------------------------- FEMassActionReversibleEffective::FEMassActionReversibleEffective(FEModel* pfem) : FEChemicalReaction(pfem) { } //----------------------------------------------------------------------------- //! molar supply at material point double FEMassActionReversibleEffective::FwdReactionSupply(FEMaterialPoint& pt) { // get forward reaction rate double k = m_pFwd->ReactionRate(pt); // evaluate the reaction molar supply double zhat = k; // start with contribution from solutes int nsol = 0; nsol = m_psm->Solutes(); for (int i=0; i<nsol; ++i) { int vR = m_vR[i]; if (vR > 0) { double c = m_psm->GetEffectiveSoluteConcentration(pt, i); zhat *= pow(c, vR); } } // add contribution of solid-bound molecules const int nsbm = m_psm->SBMs(); for (int i=0; i<nsbm; ++i) { int vR = m_vR[nsol+i]; if (vR > 0) { double c = m_psm->SBMConcentration(pt, i); zhat *= pow(c, vR); } } return zhat; } //----------------------------------------------------------------------------- //! molar supply at material point double FEMassActionReversibleEffective::RevReactionSupply(FEMaterialPoint& pt) { // get forward reaction rate double k = m_pRev->ReactionRate(pt); // evaluate the reaction molar supply double zhat = k; // start with contribution from solutes int nsol = m_psm->Solutes(); for (int i=0; i<nsol; ++i) { int vP = m_vP[i]; if (vP > 0) { double c = m_psm->GetEffectiveSoluteConcentration(pt, i); zhat *= pow(c, vP); } } // add contribution of solid-bound molecules const int nsbm = m_psm->SBMs(); for (int i=0; i<nsbm; ++i) { int vP = m_vP[nsol+i]; if (vP > 0) { double c = m_psm->SBMConcentration(pt, i); zhat *= pow(c, vP); } } return zhat; } //----------------------------------------------------------------------------- //! molar supply at material point double FEMassActionReversibleEffective::ReactionSupply(FEMaterialPoint& pt) { double zhatF = FwdReactionSupply(pt); double zhatR = RevReactionSupply(pt); return zhatF - zhatR; } //----------------------------------------------------------------------------- //! tangent of molar supply with strain at material point mat3ds FEMassActionReversibleEffective::Tangent_ReactionSupply_Strain(FEMaterialPoint& pt) { FEBiphasicInterface* pbm = dynamic_cast<FEBiphasicInterface*>(GetAncestor()); FEElasticMaterialPoint& ept = *pt.ExtractData<FEElasticMaterialPoint>(); const int nsol = m_nsol; const int nsbm = (int)m_v.size() - nsol; double J = ept.m_J; double phi0 = pbm->GetReferentialSolidVolumeFraction(pt); // forward reaction double kF = m_pFwd->ReactionRate(pt); mat3ds dkFde = m_pFwd->Tangent_ReactionRate_Strain(pt); double zhatF = FwdReactionSupply(pt); mat3ds dzhatFde = mat3dd(0); if (kF > 0) dzhatFde = dkFde*(zhatF/kF); // reverse reaction double kR = m_pRev->ReactionRate(pt); mat3ds dkRde = m_pRev->Tangent_ReactionRate_Strain(pt); double zhatR = RevReactionSupply(pt); mat3ds dzhatRde = mat3dd(0); if (kR > 0) dzhatRde = dkRde*(zhatR/kR); return dzhatFde - dzhatRde; } //----------------------------------------------------------------------------- //! tangent of molar supply with effective pressure at material point double FEMassActionReversibleEffective::Tangent_ReactionSupply_Pressure(FEMaterialPoint& pt) { // forward reaction double kF = m_pFwd->ReactionRate(pt); double dzhatFdp = 0; if (kF > 0) { double dkFdp = m_pFwd->Tangent_ReactionRate_Pressure(pt); double zhatF = FwdReactionSupply(pt); dzhatFdp = dkFdp*zhatF/kF; } // reverse reaction double kR = m_pRev->ReactionRate(pt); double dzhatRdp = 0; if (kR > 0) { double dkRdp = m_pRev->Tangent_ReactionRate_Pressure(pt); double zhatR = RevReactionSupply(pt); dzhatRdp = dkRdp*zhatR/kR; } return dzhatFdp - dzhatRdp; } //----------------------------------------------------------------------------- //! tangent of molar supply with effective concentration at material point double FEMassActionReversibleEffective::Tangent_ReactionSupply_Concentration(FEMaterialPoint& pt, const int sol) { const int nsol = m_nsol; // if the derivative is taken with respect to a solid-bound molecule, return 0 if (sol >= nsol) { return 0; } // forward reaction double zhatF = FwdReactionSupply(pt); double dzhatFdc = 0; double c = m_psm->GetEffectiveSoluteConcentration(pt, sol); if ((zhatF > 0) && (c > 0)) dzhatFdc = m_vR[sol]*zhatF/c; // reverse reaction double zhatR = RevReactionSupply(pt); double dzhatRdc = 0; if ((zhatR > 0) && (c > 0)) dzhatRdc = m_vP[sol]*zhatR/c; return dzhatFdc - dzhatRdc; }
C++
3D
febiosoftware/FEBio
FEBioMix/FEInitialConcentration.cpp
.cpp
2,097
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) 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.*/ #include "FEInitialConcentration.h" //============================================================================= BEGIN_FECORE_CLASS(FEInitialConcentration, FEInitialCondition) ADD_PARAMETER(m_dof, "dof", 0, "$(dof_list:concentration)")->setLongName("Solute"); ADD_PARAMETER(m_data, "value")->setUnits(UNIT_CONCENTRATION); END_FECORE_CLASS(); FEInitialConcentration::FEInitialConcentration(FEModel* fem) : FEInitialDOF(fem) { } //============================================================================= BEGIN_FECORE_CLASS(FEInitialShellConcentration, FEInitialCondition) ADD_PARAMETER(m_dof, "dof", 0, "$(dof_list:shell_concentration)")->setLongName("Solute"); ADD_PARAMETER(m_data, "value"); END_FECORE_CLASS(); FEInitialShellConcentration::FEInitialShellConcentration(FEModel* fem) : FEInitialDOF(fem) { }
C++
3D
febiosoftware/FEBio
FEBioMix/FESupplyConst.cpp
.cpp
3,420
106
/*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 "FESupplyConst.h" // define the material parameters BEGIN_FECORE_CLASS(FESupplyConst, FESoluteSupply) ADD_PARAMETER(m_supp, "supp"); END_FECORE_CLASS(); //----------------------------------------------------------------------------- //! Constructor. FESupplyConst::FESupplyConst(FEModel* pfem) : FESoluteSupply(pfem) { m_supp = 0; } //----------------------------------------------------------------------------- //! Solute supply double FESupplyConst::Supply(FEMaterialPoint& mp) { // --- constant solubility --- return m_supp; } //----------------------------------------------------------------------------- //! Tangent of solute supply with respect to strain double FESupplyConst::Tangent_Supply_Strain(FEMaterialPoint &mp) { return 0; } //----------------------------------------------------------------------------- //! Tangent of solute supply with respect to concentration double FESupplyConst::Tangent_Supply_Concentration(FEMaterialPoint &mp) { return 0; } //----------------------------------------------------------------------------- //! Receptor-ligand complex supply double FESupplyConst::ReceptorLigandSupply(FEMaterialPoint &mp) { return 0; } //----------------------------------------------------------------------------- //! Solute supply at steady-state double FESupplyConst::SupplySS(FEMaterialPoint& mp) { // --- constant solubility --- return m_supp; } //----------------------------------------------------------------------------- //! Receptor-ligand concentration at steady-state double FESupplyConst::ReceptorLigandConcentrationSS(FEMaterialPoint& mp) { return 0; } //----------------------------------------------------------------------------- //! Referential solid supply (moles of solid/referential volume/time) double FESupplyConst::SolidSupply(FEMaterialPoint& mp) { return ReceptorLigandSupply(mp); } //----------------------------------------------------------------------------- //! Referential solid concentration (moles of solid/referential volume) //! at steady-state double FESupplyConst::SolidConcentrationSS(FEMaterialPoint& mp) { return 0; }
C++
3D
febiosoftware/FEBio
FEBioMix/FEBiphasicSolidDomain.cpp
.cpp
40,063
1,253
/*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 "FEBiphasicSolidDomain.h" #include "FECore/FEMesh.h" #include "FECore/log.h" #include <FECore/FEDataExport.h> #include <FECore/FEModel.h> #include <FEBioMech/FEBioMech.h> #include <FECore/FELinearSystem.h> #include "FEBioMix.h" BEGIN_FECORE_CLASS(FEBiphasicSolidDomain, FESolidDomain) ADD_PARAMETER(m_secant_stress, "secant_stress"); ADD_PARAMETER(m_secant_tangent, "secant_tangent"); ADD_PARAMETER(m_secant_perm_tangent, "secant_permeability_tangent"); END_FECORE_CLASS(); //----------------------------------------------------------------------------- FEBiphasicSolidDomain::FEBiphasicSolidDomain(FEModel* pfem) : FESolidDomain(pfem), FEBiphasicDomain(pfem), m_dofU(pfem), m_dofSU(pfem), m_dofR(pfem), m_dof(pfem) { EXPORT_DATA(PLT_FLOAT, FMT_NODE, &m_nodePressure, "NPR fluid pressure"); m_secant_stress = false; m_secant_tangent = false; m_secant_perm_tangent = false; if (pfem) { m_varU = pfem->GetDOFS().GetVariableIndex(FEBioMech::GetVariableName(FEBioMech::DISPLACEMENT)); assert(m_varU >= 0); m_varP = pfem->GetDOFS().GetVariableIndex(FEBioMix::GetVariableName(FEBioMix::FLUID_PRESSURE)); assert(m_varP >= 0); m_dofU.AddVariable(FEBioMech::GetVariableName(FEBioMech::DISPLACEMENT)); m_dofSU.AddVariable(FEBioMech::GetVariableName(FEBioMech::SHELL_DISPLACEMENT)); m_dofR.AddVariable(FEBioMech::GetVariableName(FEBioMech::RIGID_ROTATION)); } } //----------------------------------------------------------------------------- //! get the total dof list const FEDofList& FEBiphasicSolidDomain::GetDOFList() const { return m_dof; } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::Serialize(DumpStream& ar) { FESolidDomain::Serialize(ar); if (ar.IsShallow() == false) { ar & m_nodePressure; } } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::SetMaterial(FEMaterial* pmat) { FEDomain::SetMaterial(pmat); m_pMat = dynamic_cast<FEBiphasic*>(pmat); assert(m_pMat); } //----------------------------------------------------------------------------- //! Initialize element data void FEBiphasicSolidDomain::PreSolveUpdate(const FETimeInfo& timeInfo) { const int NE = FEElement::MAX_NODES; vec3d x0[NE], xt[NE], r0, rt; double pn[NE], p; FEMesh& m = *GetMesh(); for (size_t iel=0; iel<m_Elem.size(); ++iel) { FESolidElement& el = m_Elem[iel]; int neln = el.Nodes(); for (int i=0; i<neln; ++i) { FENode& node = m.Node(el.m_node[i]); x0[i] = node.m_r0; xt[i] = node.m_rt; if (el.m_bitfc.size()>0 && el.m_bitfc[i] && node.m_ID[m_dofQ] != -1) pn[i] = node.get(m_dofQ); else pn[i] = node.get(m_dofP); } int n = el.GaussPoints(); for (int j=0; j<n; ++j) { r0 = el.Evaluate(x0, j); rt = el.Evaluate(xt, j); p = el.Evaluate(pn, j); FEMaterialPoint& mp = *el.GetMaterialPoint(j); FEElasticMaterialPoint& pt = *mp.ExtractData<FEElasticMaterialPoint>(); FEBiphasicMaterialPoint& pb = *mp.ExtractData<FEBiphasicMaterialPoint>(); mp.m_r0 = r0; mp.m_rt = rt; pt.m_J = defgrad(el, pt.m_F, j); pb.m_Jp = pt.m_J; pb.m_p = p; pb.m_gradp = gradient(el, pn, j); pb.m_gradpp = pb.m_gradp; pb.m_phi0p = pb.m_phi0t; mp.Update(timeInfo); } } } //----------------------------------------------------------------------------- bool FEBiphasicSolidDomain::Init() { // initialize base class if (FESolidDomain::Init() == false) return false; // initialize body forces FEModel& fem = *GetFEModel(); m_pMat->m_bf.clear(); for (int j=0; j<fem.ModelLoads(); ++j) { FEBodyForce* pbf = dynamic_cast<FEBodyForce*>(fem.ModelLoad(j)); if (pbf) m_pMat->m_bf.push_back(pbf); } // allocate nodal pressures m_nodePressure.resize(Nodes(), 0.0); return true; } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::Activate() { for (int i=0; i<Nodes(); ++i) { FENode& node = Node(i); if (node.HasFlags(FENode::EXCLUDE) == false) { if (node.m_rid < 0) { node.set_active(m_dofU[0]); node.set_active(m_dofU[1]); node.set_active(m_dofU[2]); } } } // Activate dof_P, except when a biphasic solid is connected to the // back of a shell element, in which case activate dof_Q for those nodes. FEMesh& m = *GetMesh(); for (int i=0; i<Elements(); ++i) { FESolidElement& el = m_Elem[i]; int neln = el.Nodes(); for (int j=0; j<neln; ++j) { FENode& node = m.Node(el.m_node[j]); if (el.m_bitfc.size()>0 && el.m_bitfc[j]) node.set_active(m_dofQ); else node.set_active(m_dofP); } } } //----------------------------------------------------------------------------- //! Unpack the element LM data. void FEBiphasicSolidDomain::UnpackLM(FEElement& el, vector<int>& lm) { DOFS& dofs = GetFEModel()->GetDOFS(); int degree_d = dofs.GetVariableInterpolationOrder(m_varU); int degree_p = dofs.GetVariableInterpolationOrder(m_varP); // number of nodes for velocity interpolation int neln_d = el.ShapeFunctions(degree_d); // number of nodes for pressure interpolation int neln_p = el.ShapeFunctions(degree_p); // allocate lm lm.resize(neln_d*4 + 3*neln_d); // displacement dofs for (int i=0; i<neln_d; ++i) { int n = el.m_node[i]; FENode& node = m_pMesh->Node(n); vector<int>& id = node.m_ID; // first the displacement dofs lm[4*i ] = id[m_dofU[0]]; lm[4*i+1] = id[m_dofU[1]]; lm[4*i+2] = id[m_dofU[2]]; // now the pressure dofs lm[4*i + 3] = id[m_dofP]; // rigid rotational dofs lm[4 * neln_d + 3 * i ] = id[m_dofR[0]]; lm[4 * neln_d + 3 * i + 1] = id[m_dofR[1]]; lm[4 * neln_d + 3 * i + 2] = id[m_dofR[2]]; } // substitute interface dofs for solid-shell interfaces FESolidElement& sel = static_cast<FESolidElement&>(el); for (int i = 0; i<sel.m_bitfc.size(); ++i) { if (sel.m_bitfc[i]) { FENode& node = m_pMesh->Node(el.m_node[i]); vector<int>& id = node.m_ID; // first the back-face displacement dofs lm[4*i ] = id[m_dofSU[0]]; lm[4*i+1] = id[m_dofSU[1]]; lm[4*i+2] = id[m_dofSU[2]]; // now the pressure dof (if the shell has it) if (id[m_dofQ] > -1) lm[4*i + 3] = id[m_dofQ]; } } } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::Reset() { // reset base class data FESolidDomain::Reset(); // initialize all element data ForEachMaterialPoint([=](FEMaterialPoint& mp) { FEBiphasicMaterialPoint& pt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // initialize referential solid volume fraction pt.m_phi0 = pt.m_phi0t = m_pMat->m_phi0(mp); }); } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::InternalForces(FEGlobalVector& R) { DOFS& dofs = GetFEModel()->GetDOFS(); int degree_d = dofs.GetVariableInterpolationOrder(m_varU); int degree_p = dofs.GetVariableInterpolationOrder(m_varP); int NE = (int)m_Elem.size(); #pragma omp parallel for shared (NE) for (int i=0; i<NE; ++i) { // element force vector vector<double> fe; vector<int> lm; // get the element FESolidElement& el = m_Elem[i]; int nel_d = el.ShapeFunctions(degree_d); int nel_p = el.ShapeFunctions(degree_p); // get the element force vector and initialize it to zero int ndof = 4*nel_d; fe.assign(ndof, 0); // calculate internal force vector ElementInternalForce(el, fe); // get the element's LM vector UnpackLM(el, lm); // assemble element 'fe'-vector into global R vector R.Assemble(el.m_node, lm, fe); } } //----------------------------------------------------------------------------- //! calculates the internal equivalent nodal forces for solid elements void FEBiphasicSolidDomain::ElementInternalForce(FESolidElement& el, vector<double>& fe) { // jacobian matrix, inverse jacobian matrix and determinants double Ji[3][3]; DOFS& dofs = GetFEModel()->GetDOFS(); int degree_d = dofs.GetVariableInterpolationOrder(m_varU); int degree_p = dofs.GetVariableInterpolationOrder(m_varP); int nint = el.GaussPoints(); int nel_d = el.ShapeFunctions(degree_d); int nel_p = el.ShapeFunctions(degree_p); double* gw = el.GaussWeights(); double dt = GetFEModel()->GetTime().timeIncrement; // repeat for all integration points for (int n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); FEElasticMaterialPoint& pt = *(mp.ExtractData<FEElasticMaterialPoint>()); FEBiphasicMaterialPoint& bpt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // calculate the jacobian double Jw = invjact(el, Ji, n)*gw[n]; // get the stress vector for this integration point mat3ds s = pt.m_s; double* Gr = el.Gr(n); double* Gs = el.Gs(n); double* Gt = el.Gt(n); double* H = el.H(n); // --- stress contribution for (int i=0; i<nel_d; ++i) { // calculate global gradient of shape functions // note that we need the transposed of Ji, not Ji itself ! vec3d gradN(Ji[0][0]*Gr[i]+Ji[1][0]*Gs[i]+Ji[2][0]*Gt[i], Ji[0][1]*Gr[i]+Ji[1][1]*Gs[i]+Ji[2][1]*Gt[i], Ji[0][2]*Gr[i]+Ji[1][2]*Gs[i]+Ji[2][2]*Gt[i]); // calculate internal force vec3d fu = s*gradN; // the '-' sign is so that the internal forces get subtracted // from the global residual vector fe[4*i ] -= fu.x*Jw; fe[4*i+1] -= fu.y*Jw; fe[4*i+2] -= fu.z*Jw; } // --- pressure contribution // next we get the determinant double Jp = bpt.m_Jp; double J = pt.m_J; // and then finally double divv = ((J - Jp) / dt) / J; // get the flux vec3d& w = bpt.m_w; // get the solvent supply double phiwhat = m_pMat->SolventSupply(mp); // pressure shape functions double* Hp = el.H(degree_p, n); double* Gpr = el.Gr(degree_p, n); double* Gps = el.Gs(degree_p, n); double* Gpt = el.Gt(degree_p, n); for (int i = 0; i<nel_p; ++i) { // calculate global gradient of shape functions // note that we need the transposed of Ji, not Ji itself ! vec3d gradHp = vec3d(Ji[0][0] * Gpr[i] + Ji[1][0] * Gps[i] + Ji[2][0] * Gpt[i], Ji[0][1] * Gpr[i] + Ji[1][1] * Gps[i] + Ji[2][1] * Gpt[i], Ji[0][2] * Gpr[i] + Ji[1][2] * Gps[i] + Ji[2][2] * Gpt[i]); // the '-' sign is so that the internal forces get subtracted // from the global residual vector fe[4*i + 3] -= dt*(w*gradHp + (phiwhat - divv)*Hp[i])*Jw; } } } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::InternalForcesSS(FEGlobalVector& R) { int NE = (int)m_Elem.size(); #pragma omp parallel for shared (NE) for (int i=0; i<NE; ++i) { // element force vector vector<double> fe; vector<int> lm; // get the element FESolidElement& el = m_Elem[i]; // get the element force vector and initialize it to zero int ndof = 4*el.Nodes(); fe.assign(ndof, 0); // calculate internal force vector ElementInternalForceSS(el, fe); // get the element's LM vector UnpackLM(el, lm); // assemble element 'fe'-vector into global R vector R.Assemble(el.m_node, lm, fe); } } //----------------------------------------------------------------------------- //! calculates the internal equivalent nodal forces for solid elements (steady-state) void FEBiphasicSolidDomain::ElementInternalForceSS(FESolidElement& el, vector<double>& fe) { // jacobian matrix, inverse jacobian matrix and determinants double Ji[3][3], detJt; vec3d gradN, GradN; DOFS& dofs = GetFEModel()->GetDOFS(); int degree_d = dofs.GetVariableInterpolationOrder(m_varU); int degree_p = dofs.GetVariableInterpolationOrder(m_varP); int nint = el.GaussPoints(); int nel_d = el.ShapeFunctions(degree_d); int nel_p = el.ShapeFunctions(degree_p); double* gw = el.GaussWeights(); double dt = GetFEModel()->GetTime().timeIncrement; // repeat for all integration points for (int n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); FEElasticMaterialPoint& pt = *(mp.ExtractData<FEElasticMaterialPoint>()); FEBiphasicMaterialPoint& bpt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // calculate the jacobian detJt = invjact(el, Ji, n); detJt *= gw[n]; // get the stress vector for this integration point mat3d s = pt.m_s; double* Gr = el.Gr(n); double* Gs = el.Gs(n); double* Gt = el.Gt(n); double* H = el.H(n); // get the flux vec3d& w = bpt.m_w; // get the solvent supply double phiwhat = m_pMat->SolventSupply(mp); for (int i=0; i<nel_d; ++i) { // calculate global gradient of shape functions // note that we need the transposed of Ji, not Ji itself ! gradN = vec3d(Ji[0][0]*Gr[i]+Ji[1][0]*Gs[i]+Ji[2][0]*Gt[i], Ji[0][1]*Gr[i]+Ji[1][1]*Gs[i]+Ji[2][1]*Gt[i], Ji[0][2]*Gr[i]+Ji[1][2]*Gs[i]+Ji[2][2]*Gt[i]); // calculate internal force vec3d fu = s*gradN; // the '-' sign is so that the internal forces get subtracted // from the global residual vector fe[4*i ] -= fu.x*detJt; fe[4*i+1] -= fu.y*detJt; fe[4*i+2] -= fu.z*detJt; } // --- pressure contribution double* Gpr = el.Gr(degree_p, n); double* Gps = el.Gs(degree_p, n); double* Gpt = el.Gt(degree_p, n); double* Hp = el.H(degree_p, n); for (int i = 0; i<nel_p; ++i) { // calculate global gradient of shape functions // note that we need the transposed of Ji, not Ji itself ! vec3d gradH(Ji[0][0] * Gpr[i] + Ji[1][0] * Gps[i] + Ji[2][0] * Gpt[i], Ji[0][1] * Gpr[i] + Ji[1][1] * Gps[i] + Ji[2][1] * Gpt[i], Ji[0][2] * Gpr[i] + Ji[1][2] * Gps[i] + Ji[2][2] * Gpt[i]); fe[4*i + 3] -= dt*(w*gradH + phiwhat*Hp[i])*detJt; } } } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::StiffnessMatrix(FELinearSystem& LS, bool bsymm) { // repeat over all solid elements int NE = (int)m_Elem.size(); #pragma omp parallel for shared(NE) for (int iel=0; iel<NE; ++iel) { FESolidElement& el = m_Elem[iel]; // element stiffness matrix FEElementMatrix ke(el); int ndof = el.Nodes()*4; ke.resize(ndof, ndof); // calculate the element stiffness matrix ElementBiphasicStiffness(el, ke, bsymm); // TODO: the problem here is that the LM array that is returned by the UnpackLM // function does not give the equation numbers in the right order. For this reason we // have to create a new lm array and place the equation numbers in the right order. // What we really ought to do is fix the UnpackLM function so that it returns // the LM vector in the right order for poroelastic elements. vector<int> lm; UnpackLM(el, lm); ke.SetIndices(lm); // assemble element matrix in global stiffness matrix LS.Assemble(ke); } } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::StiffnessMatrixSS(FELinearSystem& LS, bool bsymm) { // repeat over all solid elements int NE = (int)m_Elem.size(); #pragma omp parallel for shared(NE) for (int iel=0; iel<NE; ++iel) { FESolidElement& el = m_Elem[iel]; // element stiffness matrix FEElementMatrix ke(el); int ndof = el.Nodes()*4; ke.resize(ndof, ndof); // calculate the element stiffness matrix ElementBiphasicStiffnessSS(el, ke, bsymm); // TODO: the problem here is that the LM array that is returned by the UnpackLM // function does not give the equation numbers in the right order. For this reason we // have to create a new lm array and place the equation numbers in the right order. // What we really ought to do is fix the UnpackLM function so that it returns // the LM vector in the right order for poroelastic elements. vector<int> lm; UnpackLM(el, lm); ke.SetIndices(lm); // assemble element matrix in global stiffness matrix LS.Assemble(ke); } } //----------------------------------------------------------------------------- //! calculates element stiffness matrix for element iel //! bool FEBiphasicSolidDomain::ElementBiphasicStiffness(FESolidElement& el, matrix& ke, bool bsymm) { DOFS& dofs = GetFEModel()->GetDOFS(); int degree_d = dofs.GetVariableInterpolationOrder(m_varU); int degree_p = dofs.GetVariableInterpolationOrder(m_varP); int nint = el.GaussPoints(); int nel_d = el.ShapeFunctions(degree_d); int nel_p = el.ShapeFunctions(degree_p); // jacobian double Ji[3][3]; // Bp-matrix vector<vec3d> gradNu(FEElement::MAX_NODES), gradNp(FEElement::MAX_NODES); // gauss-weights double* gw = el.GaussWeights(); double dt = GetFEModel()->GetTime().timeIncrement; double tau = m_pMat->m_tau; // zero stiffness matrix ke.zero(); // loop over gauss-points for (int n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); FEElasticMaterialPoint& ept = *(mp.ExtractData<FEElasticMaterialPoint >()); FEBiphasicMaterialPoint& pt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // calculate jacobian double detJ = invjact(el, Ji, n); // contravariant basis vectors in spatial frame vec3d g1(Ji[0][0],Ji[0][1],Ji[0][2]); vec3d g2(Ji[1][0],Ji[1][1],Ji[1][2]); vec3d g3(Ji[2][0],Ji[2][1],Ji[2][2]); // displacement shape functions double* Hu = el.H(n); double* Gur = el.Gr(n); double* Gus = el.Gs(n); double* Gut = el.Gt(n); // pressure shape functions double* Hp = el.H (degree_p, n); double* Gpr = el.Gr(degree_p, n); double* Gps = el.Gs(degree_p, n); double* Gpt = el.Gt(degree_p, n); for (int i=0; i<nel_d; ++i) { // calculate global gradient of shape functions // note that we need the transposed of Ji, not Ji itself ! gradNu[i] = g1*Gur[i] + g2*Gus[i] + g3*Gut[i]; } for (int i = 0; i<nel_p; ++i) { // calculate global gradient of shape functions // note that we need the transposed of Ji, not Ji itself ! gradNp[i] = g1*Gpr[i] + g2*Gps[i] + g3*Gpt[i]; } // get stress tensor mat3ds s = ept.m_s; // get elasticity tensor tens4dmm c = (m_secant_tangent) ? m_pMat->SecantTangent(mp) : m_pMat->Tangent(mp); // get the fluid flux and pressure gradient vec3d gradp = pt.m_gradp + (pt.m_gradp - pt.m_gradpp)*(tau/dt); // evaluate the permeability and its derivatives mat3ds K = m_pMat->Permeability(mp); tens4dmm dKdE = (m_secant_perm_tangent) ? m_pMat->SecantTangent_Permeability_Strain(mp) : m_pMat->Tangent_Permeability_Strain(mp); // evaluate the solvent supply and its derivatives double phiwhat = 0; mat3ds Phie; Phie.zero(); double Phip = 0; if (m_pMat->GetSolventSupply()) { phiwhat = m_pMat->GetSolventSupply()->Supply(mp); Phie = m_pMat->GetSolventSupply()->Tangent_Supply_Strain(mp); Phip = m_pMat->GetSolventSupply()->Tangent_Supply_Pressure(mp); } // Miscellaneous constants mat3dd I(1); // Kuu matrix double Jw = detJ*gw[n]; for (int i=0; i<nel_d; ++i) for (int j=0; j<nel_d; ++j) { mat3d Kuu = (mat3dd(gradNu[i]*(s*gradNu[j])) + vdotTdotv(gradNu[i], c, gradNu[j]))*Jw; ke.add(4 * i, 4 * j, Kuu); } // calculate the kpp matrix for (int i=0; i<nel_p; ++i) for (int j=0; j<nel_p; ++j) { ke[4*i+3][4*j+3] += (Hp[i]*Hp[j]*Phip - gradNp[i]*(K*gradNp[j])*(1+tau/dt))*(dt*Jw); } if (!bsymm) { // calculate the kup matrix for (int i=0; i<nel_d; ++i) { for (int j=0; j<nel_p; ++j) { ke[4*i ][4*j+3] -= Jw*gradNu[i].x*Hp[j]; ke[4*i+1][4*j+3] -= Jw*gradNu[i].y*Hp[j]; ke[4*i+2][4*j+3] -= Jw*gradNu[i].z*Hp[j]; } } // calculate the kpu matrix mat3ds Q = Phie*ept.m_J + mat3dd(phiwhat - 1./dt); for (int i=0; i<nel_p; ++i) { for (int j=0; j<nel_d; ++j) { vec3d vt = ((vdotTdotv(-gradNp[i], dKdE, gradNu[j])*gradp) +(Q*gradNu[j])*Hp[i])*(Jw*dt); ke[4*i+3][4*j ] += vt.x; ke[4*i+3][4*j+1] += vt.y; ke[4*i+3][4*j+2] += vt.z; } } } else { // calculate the kup matrix and let kpu be its symmetric part for (int i=0; i<nel_d; ++i) { for (int j=0; j<nel_p; ++j) { ke[4*i ][4*j+3] -= Jw*gradNu[i].x*Hp[j]; ke[4*i+1][4*j+3] -= Jw*gradNu[i].y*Hp[j]; ke[4*i+2][4*j+3] -= Jw*gradNu[i].z*Hp[j]; ke[4*j+3][4*i ] -= Jw*gradNu[i].x*Hp[j]; ke[4*j+3][4*i+1] -= Jw*gradNu[i].y*Hp[j]; ke[4*j+3][4*i+2] -= Jw*gradNu[i].z*Hp[j]; } } } } return true; } //----------------------------------------------------------------------------- //! calculates element stiffness matrix for element iel //! for the steady-state response (zero solid velocity) //! bool FEBiphasicSolidDomain::ElementBiphasicStiffnessSS(FESolidElement& el, matrix& ke, bool bsymm) { DOFS& dofs = GetFEModel()->GetDOFS(); int degree_d = dofs.GetVariableInterpolationOrder(m_varU); int degree_p = dofs.GetVariableInterpolationOrder(m_varP); int nint = el.GaussPoints(); int nel_d = el.ShapeFunctions(degree_d); int nel_p = el.ShapeFunctions(degree_p); // jacobian double Ji[3][3]; // Bp-matrix vector<vec3d> gradNu(nel_d), gradNp(nel_p); double tmp; // gauss-weights double* gw = el.GaussWeights(); double dt = GetFEModel()->GetTime().timeIncrement; // zero stiffness matrix ke.zero(); // loop over gauss-points for (int n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); FEElasticMaterialPoint& ept = *(mp.ExtractData<FEElasticMaterialPoint >()); FEBiphasicMaterialPoint& pt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // calculate jacobian double detJ = invjact(el, Ji, n); // contravariant basis vectors in spatial frame vec3d g1(Ji[0][0],Ji[0][1],Ji[0][2]); vec3d g2(Ji[1][0],Ji[1][1],Ji[1][2]); vec3d g3(Ji[2][0],Ji[2][1],Ji[2][2]); double* Hu = el.H(n); double* Hp = el.H(degree_p, n); double* Gur = el.Gr(n); double* Gus = el.Gs(n); double* Gut = el.Gt(n); double* Gpr = el.Gr(degree_p, n); double* Gps = el.Gs(degree_p, n); double* Gpt = el.Gt(degree_p, n); for (int i=0; i<nel_d; ++i) { // calculate global gradient of shape functions // note that we need the transposed of Ji, not Ji itself ! gradNu[i] = g1*Gur[i] + g2*Gus[i] + g3*Gut[i]; } for (int i = 0; i<nel_p; ++i) { // calculate global gradient of shape functions // note that we need the transposed of Ji, not Ji itself ! gradNp[i] = g1*Gpr[i] + g2*Gps[i] + g3*Gpt[i]; } // get stress tensor mat3ds s = ept.m_s; // get elasticity tensor tens4dmm c = (m_secant_tangent) ? m_pMat->SecantTangent(mp) : m_pMat->Tangent(mp); // get the fluid flux and pressure gradient vec3d gradp = pt.m_gradp; // evaluate the permeability and its derivatives mat3ds K = m_pMat->Permeability(mp); tens4dmm dKdE = (m_secant_perm_tangent) ? m_pMat->SecantTangent_Permeability_Strain(mp) : m_pMat->Tangent_Permeability_Strain(mp); // evaluate the solvent supply and its derivatives double phiwhat = 0; mat3ds Phie; Phie.zero(); double Phip = 0; if (m_pMat->GetSolventSupply()) { phiwhat = m_pMat->GetSolventSupply()->Supply(mp); Phie = m_pMat->GetSolventSupply()->Tangent_Supply_Strain(mp); Phip = m_pMat->GetSolventSupply()->Tangent_Supply_Pressure(mp); } // Miscellaneous constants mat3dd I(1); // Kuu matrix tmp = detJ*gw[n]; for (int i=0; i<nel_d; ++i) for (int j=0; j<nel_d; ++j) { mat3d Kuu = (mat3dd(gradNu[i]*(s*gradNu[j])) + vdotTdotv(gradNu[i], c, gradNu[j]))*tmp; ke.add(4 * i, 4 * j, Kuu); } // calculate the kpp matrix tmp = detJ*gw[n]*dt; for (int i=0; i<nel_p; ++i) for (int j=0; j<nel_p; ++j) { ke[4*i+3][4*j+3] += (Hp[i]*Hp[j]*Phip - gradNp[i]*(K*gradNp[j]))*tmp; } if (!bsymm) { // calculate the kup matrix for (int i=0; i<nel_d; ++i) { for (int j=0; j<nel_p; ++j) { tmp = detJ*gw[n]*Hp[j]; ke[4*i ][4*j+3] -= tmp*gradNu[i].x; ke[4*i + 1][4*j+3] -= tmp*gradNu[i].y; ke[4*i + 2][4*j+3] -= tmp*gradNu[i].z; } } // calculate the kpu matrix // tmp = detJ*gw[n]; tmp = detJ*gw[n]*dt; for (int i=0; i<nel_p; ++i) { for (int j=0; j<nel_d; ++j) { vec3d vt = ((vdotTdotv(-gradp, dKdE, gradNu[j])*(gradNp[i])) +(mat3dd(phiwhat) + Phie*ept.m_J)*gradNu[j]*Hp[i])*tmp; ke[4*i+3][4*j ] += vt.x; ke[4*i+3][4*j+1] += vt.y; ke[4*i+3][4*j+2] += vt.z; } } } else { // calculate the kup matrix and let kpu be its symmetric part tmp = detJ*gw[n]; for (int i=0; i<nel_d; ++i) { for (int j=0; j<nel_p; ++j) { ke[4*i ][4*j+3] -= tmp*Hu[j]*gradNp[i].x; ke[4*i+1][4*j+3] -= tmp*Hu[j]*gradNp[i].y; ke[4*i+2][4*j+3] -= tmp*Hu[j]*gradNp[i].z; ke[4*j+3][4*i ] -= tmp*Hu[j]*gradNp[i].x; ke[4*j+3][4*i+1] -= tmp*Hu[j]*gradNp[i].y; ke[4*j+3][4*i+2] -= tmp*Hu[j]*gradNp[i].z; } } } } return true; } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::Update(const FETimeInfo& tp) { bool berr = false; int NE = (int) m_Elem.size(); #pragma omp parallel for shared(NE, berr) for (int i=0; i<NE; ++i) { try { UpdateElementStress(i); } catch (NegativeJacobian e) { #pragma omp critical { berr = true; if (e.DoOutput()) feLogError(e.what()); } } } if (berr) throw NegativeJacobianDetected(); // also update the nodal pressures UpdateNodalPressures(); } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::UpdateElementStress(int iel) { double dt = GetFEModel()->GetTime().timeIncrement; // extract the elastic component FEElasticMaterial* pme = m_pMat->GetElasticMaterial(); // get the solid element FESolidElement& el = m_Elem[iel]; // get the number of integration points int nint = el.GaussPoints(); DOFS& dofs = GetFEModel()->GetDOFS(); int degree_d = dofs.GetVariableInterpolationOrder(m_varU); int degree_p = dofs.GetVariableInterpolationOrder(m_varP); // get the number of nodes int nel_d = el.ShapeFunctions(degree_d); int nel_p = el.ShapeFunctions(degree_p); // get the nodal data FEMesh& mesh = *m_pMesh; vec3d rt[FEElement::MAX_NODES]; double pn[FEElement::MAX_NODES]; GetCurrentNodalCoordinates(el, rt, 1.0); for (int j = 0; j<nel_p; ++j) { FENode& node = mesh.Node(el.m_node[j]); if (el.m_bitfc.size()>0 && el.m_bitfc[j] && node.m_ID[m_dofQ] != -1) pn[j] = node.get(m_dofQ); else pn[j] = node.get(m_dofP); } // loop over the integration points and calculate // the stress at the integration point for (int n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); FEElasticMaterialPoint& pt = *(mp.ExtractData<FEElasticMaterialPoint>()); // material point coordinates // TODO: I'm not entirly happy with this solution // since the material point coordinates are used by most materials. mp.m_rt = el.Evaluate(rt, n); // get the deformation gradient and determinant pt.m_J = defgrad(el, pt.m_F, n); mat3d Fp; defgradp(el, Fp, n); mat3d Fi = pt.m_F.inverse(); pt.m_L = (pt.m_F - Fp)*Fi / dt; // poroelasticity data FEBiphasicMaterialPoint& ppt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); // evaluate fluid pressure at gauss-point ppt.m_p = el.Evaluate(degree_p, pn, n); // calculate the gradient of p at gauss-point ppt.m_gradp = gradient(el, degree_p, pn, n); // for biphasic materials also update the fluid flux ppt.m_w = FluidFlux(mp); ppt.m_pa = m_pMat->Pressure(mp); // update specialized material points m_pMat->UpdateSpecializedMaterialPoints(mp, GetFEModel()->GetTime()); // calculate the solid stress at this material point ppt.m_ss = (m_secant_stress) ? m_pMat->GetElasticMaterial()->SecantStress(mp) : m_pMat->GetElasticMaterial()->Stress(mp); // calculate the stress at this material point pt.m_s = (m_secant_stress) ? m_pMat->SecantStress(mp) : m_pMat->Stress(mp); } } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::BodyForce(FEGlobalVector& R, FEBodyForce& BF) { FEBodyForce* bf = &BF; LoadVector(R, m_dofU, [=](FEMaterialPoint& mp, int node_a, vector<double>& fa) { // get true solid and fluid densities double rhoTs = m_pMat->SolidDensity(mp); double rhoTw = m_pMat->FluidDensity(); // Jacobian double detJ = mp.m_Jt; // get the force vec3d b = bf->force(mp); // evaluate apparent solid and fluid densities and mixture density double phiw = m_pMat->Porosity(mp); double rhos = (1 - phiw)*rhoTs; double rhow = phiw*rhoTw; double rho = rhos + rhow; double* H = mp.m_shape; fa[0] = -H[node_a] * rho*b.x*detJ; fa[1] = -H[node_a] * rho*b.y*detJ; fa[2] = -H[node_a] * rho*b.z*detJ; }); } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::BodyForceStiffness(FELinearSystem& LS, FEBodyForce& bf) { FEBiphasic* pmb = dynamic_cast<FEBiphasic*>(GetMaterial()); assert(pmb); // repeat over all solid elements int NE = (int)m_Elem.size(); for (int iel=0; iel<NE; ++iel) { FESolidElement& el = m_Elem[iel]; // element stiffness matrix FEElementMatrix ke(el); int neln = el.Nodes(); int ndof = 4*neln; ke.resize(ndof, ndof); ke.zero(); // calculate inertial stiffness ElementBodyForceStiffness(bf, el, ke); // TODO: the problem here is that the LM array that is returned by the UnpackLM // function does not give the equation numbers in the right order. For this reason we // have to create a new lm array and place the equation numbers in the right order. // What we really ought to do is fix the UnpackLM function so that it returns // the LM vector in the right order for poroelastic elements. vector<int> lm; UnpackLM(el, lm); ke.SetIndices(lm); // assemble element matrix in global stiffness matrix LS.Assemble(ke); } } //----------------------------------------------------------------------------- //! This function calculates the stiffness due to body forces void FEBiphasicSolidDomain::ElementBodyForceStiffness(FEBodyForce& BF, FESolidElement &el, matrix &ke) { int neln = el.Nodes(); // get true solid and fluid densities double rhoTw = m_pMat->FluidDensity(); double dt = GetFEModel()->GetTime().timeIncrement; // jacobian double detJt, Ji[3][3]; double *N; double* gw = el.GaussWeights(); vec3d gradN[FEElement::MAX_NODES]; double *Grn, *Gsn, *Gtn; double Gr, Gs, Gt; vec3d b, kpu; mat3d gradb; mat3d Kw, Kuu; // loop over integration points int nint = el.GaussPoints(); for (int n=0; n<nint; ++n) { FEMaterialPoint& mp = *el.GetMaterialPoint(n); // get the body force b = BF.force(mp); // get the body force stiffness gradb = BF.stiffness(mp); // evaluate apparent solid and fluid densities and mixture density double phiw = m_pMat->Porosity(mp); double rhos = (1-phiw)*m_pMat->SolidDensity(mp); double rhow = phiw*rhoTw; double rho = rhos + rhow; // evaluate the permeability and its derivatives mat3ds K = m_pMat->Permeability(mp); tens4dmm dKdE = m_pMat->Tangent_Permeability_Strain(mp); N = el.H(n); // calculate jacobian detJt = invjact(el, Ji, n)*gw[n]; Grn = el.Gr(n); Gsn = el.Gs(n); Gtn = el.Gt(n); for (int i=0; i<neln; ++i) { Gr = Grn[i]; Gs = Gsn[i]; Gt = Gtn[i]; // calculate global gradient of shape functions // note that we need the transposed of Ji, not Ji itself ! gradN[i] = vec3d(Ji[0][0]*Gr+Ji[1][0]*Gs+Ji[2][0]*Gt, Ji[0][1]*Gr+Ji[1][1]*Gs+Ji[2][1]*Gt, Ji[0][2]*Gr+Ji[1][2]*Gs+Ji[2][2]*Gt); } for (int i=0; i<neln; ++i) for (int j=0; j<neln; ++j) { Kw = b & gradN[j]; Kuu = (gradb*(N[j]*rho) + Kw*rhoTw)*(N[i]*detJt); ke[4*i ][4*j ] += Kuu(0,0); ke[4*i ][4*j+1] += Kuu(0,1); ke[4*i ][4*j+2] += Kuu(0,2); ke[4*i+1][4*j ] += Kuu(1,0); ke[4*i+1][4*j+1] += Kuu(1,1); ke[4*i+1][4*j+2] += Kuu(1,2); ke[4*i+2][4*j ] += Kuu(2,0); ke[4*i+2][4*j+1] += Kuu(2,1); ke[4*i+2][4*j+2] += Kuu(2,2); kpu = (vdotTdotv(gradN[i], dKdE, gradN[j])*b + (Kw + gradb*N[j])*K*gradN[i])*(rhoTw*detJt*dt); ke[4*i+3][4*j ] -= kpu.x; ke[4*i+3][4*j+1] -= kpu.y; ke[4*i+3][4*j+2] -= kpu.z; } } } //----------------------------------------------------------------------------- vec3d FEBiphasicSolidDomain::FluidFlux(FEMaterialPoint& mp) { FEBiphasicMaterialPoint& ppt = *mp.ExtractData<FEBiphasicMaterialPoint>(); // pressure gradient vec3d gradp = ppt.m_gradp; // fluid flux w = -k*grad(p) mat3ds kt = m_pMat->Permeability(mp); vec3d w = -(kt*gradp); double tau = m_pMat->m_tau; if (tau > 0) { double dt = GetFEModel()->GetTime().timeIncrement; w -= kt*(gradp - ppt.m_gradpp)*(tau/dt); } // get true fluid density double rhoTw = m_pMat->FluidDensity(); // body force contribution FEModel& fem = *m_pMat->GetFEModel(); int nbf = fem.ModelLoads(); if (nbf) { vec3d b(0,0,0); for (int i=0; i<nbf; ++i) { FEBodyForce* pbf = dynamic_cast<FEBodyForce*>(fem.ModelLoad(i)); if (pbf && pbf->IsActive()) { // negate b because body forces are defined with a negative sign in FEBio b -= pbf->force(mp); } } w += (kt*b)*(rhoTw); } // active momentum supply contribution FEActiveMomentumSupply* pAmom = m_pMat->GetActiveMomentumSupply(); if (pAmom) { vec3d pw = pAmom->ActiveSupply(mp); w += kt*pw; } return w; } //----------------------------------------------------------------------------- void FEBiphasicSolidDomain::UpdateNodalPressures() { vector<double> pi(FEElement::MAX_INTPOINTS); vector<double> pn(FEElement::MAX_NODES); int NN = Nodes(); vector<int> tag(NN, 0); m_nodePressure.assign(NN, 0.0); for (int i = 0; i<Elements(); ++i) { FESolidElement& el = Element(i); int nint = el.GaussPoints(); int neln = el.Nodes(); // get integration point pressures double pavg = 0.0; int c = 0; for (int j = 0; j<nint; ++j) { FEMaterialPoint& mp = *el.GetMaterialPoint(j); FEBiphasicMaterialPoint* pt = (mp.ExtractData<FEBiphasicMaterialPoint>()); if (pt) { pavg += pt->m_pa; c++; } } if (c > 0) pavg /= (double) c; // store the nodal values for (int j=0; j<neln; ++j) { int m = el.m_lnode[j]; m_nodePressure[m] += pavg; tag[m]++; } } for (int i=0; i<NN; ++i) if (tag[i] > 0) m_nodePressure[i] /= (double) tag[i]; } //----------------------------------------------------------------------------- // Note that the data vector stores the values for all of the nodes of the mesh, not just the domain nodes. // The values will be set to zero for nodes that don't belong to this domain. void FEBiphasicSolidDomain::GetNodalPressures(vector<double>& data) { FEMesh& mesh = *GetMesh(); data.resize(mesh.Nodes(), 0.0); int NN = Nodes(); for (int i=0; i<NN; ++i) { data[NodeIndex(i)] = m_nodePressure[i]; } }
C++
3D
febiosoftware/FEBio
FEBioMix/FEBiphasicSolidDomain.h
.h
6,262
153
/*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/FESolidDomain.h> #include <FECore/FEDofList.h> #include "FEBiphasicDomain.h" #include "FEBiphasic.h" //----------------------------------------------------------------------------- //! Domain class for biphasic 3D solid elements //! Note that this class inherits from FEElasticSolidDomain since the biphasic domain //! also needs to calculate elastic stiffness contributions. //! class FEBIOMIX_API FEBiphasicSolidDomain : public FESolidDomain, public FEBiphasicDomain { public: //! constructor FEBiphasicSolidDomain(FEModel* pfem); //! initialize class bool Init() override; //! activate void Activate() override; //! reset domain data void Reset() override; //! intitialize element data void PreSolveUpdate(const FETimeInfo& timeInfo) override; //! Unpack solid element data (overridden from FEDomain) void UnpackLM(FEElement& el, vector<int>& lm) override; //! get the material (overridden from FEDomain) FEMaterial* GetMaterial() override { return m_pMat; } //! set the material void SetMaterial(FEMaterial* pmat) override; //! get the total dof list const FEDofList& GetDOFList() const override; //! serialization void Serialize(DumpStream& ar) override; public: // update domain data void Update(const FETimeInfo& tp) override; // update element stress void UpdateElementStress(int iel); //! calculates the global stiffness matrix for this domain void StiffnessMatrix(FELinearSystem& LS, bool bsymm) override; //! calculates the global stiffness matrix (steady-state case) void StiffnessMatrixSS(FELinearSystem& LS, bool bsymm) override; public: // internal work (overridden from FEElasticDomain) void InternalForces(FEGlobalVector& R) override; // internal work (steady-state case) void InternalForcesSS(FEGlobalVector& R) override; public: //! element internal force vector void ElementInternalForce(FESolidElement& el, vector<double>& fe); //! element internal force vector (steady-state case) void ElementInternalForceSS(FESolidElement& el, vector<double>& fe); //! calculates the element biphasic stiffness matrix bool ElementBiphasicStiffness(FESolidElement& el, matrix& ke, bool bsymm); //! calculates the element biphasic stiffness matrix for steady-state response bool ElementBiphasicStiffnessSS(FESolidElement& el, matrix& ke, bool bsymm); public: // overridden from FEElasticDomain, but not all implemented in this domain void BodyForce(FEGlobalVector& R, FEBodyForce& bf) override; void InertialForces(FEGlobalVector& R, vector<double>& F) override {} void StiffnessMatrix(FELinearSystem& LS) override {} void BodyForceStiffness(FELinearSystem& LS, FEBodyForce& bf) override; void ElementBodyForceStiffness(FEBodyForce& BF, FESolidElement &el, matrix &ke); void MassMatrix(FELinearSystem& LS, double scale) override {} public: // biphasic domain "properties" // NOTE: I'm thinking about defining properties for domain classes. These would be similar to material // properties (and may require material properties to be evaluated), but are different in that they are // not meant to be customized. For example, the biphasic solver assumes Darcy's law in the evaluation // of the fluid flux. Although one can see the fluid flux as a material property, since the code makes explicit // use of this constitutive equation (apparent from the fact that the biphasic material needs to define the permeability and its // strain derivate) it is not a true material property: i.e. it is not meant to be changed and is an inherent // assumption in this implementation. Consequently, the fluid flux would be a good example of a domain property. // That is why I've taken this calculation out of the FEBiphasic class and placed it here. vec3d FluidFlux(FEMaterialPoint& mp) override; // Evaluate the nodal pressures // Note that the data vector stores the values for all of the nodes of the mesh, not just the domain nodes. // The values will be set to zero for nodes that don't belong to this domain. void GetNodalPressures(vector<double>& data); private: // NOTE: This is a temporary construction. Just trying something out here. // Idea is here to construct a data export for the nodal pressures (the ones from the integration points, not the nodal dofs). vector<double> m_nodePressure; //!< nodal pressures projected from the integration points // This function updates the m_nodePressure variable void UpdateNodalPressures(); protected: bool m_secant_stress; //!< use secant approximation to stress bool m_secant_tangent; //!< flag for using secant tangent bool m_secant_perm_tangent; //!< flag for using secant tangent on permeability protected: int m_varU, m_varP; // displacement, pressure field indices FEDofList m_dofU; // displacement dofs FEDofList m_dofSU; // shell displacement dofs FEDofList m_dofR; // rigid rotation FEDofList m_dof; DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FESlidingInterfaceBiphasic.cpp
.cpp
100,807
2,611
/*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 "FESlidingInterfaceBiphasic.h" #include "FEBiphasic.h" #include "FECore/FEAnalysis.h" #include "FECore/FENormalProjection.h" #include <FECore/FELinearSystem.h> #include <FECore/FEModel.h> #include "FECore/log.h" //----------------------------------------------------------------------------- // Define sliding interface parameters BEGIN_FECORE_CLASS(FESlidingInterfaceBiphasic, FEContactInterface) ADD_PARAMETER(m_laugon , "laugon" )->setLongName("Enforcement method")->setEnums("PENALTY\0AUGLAG\0"); ADD_PARAMETER(m_atol , "tolerance" ); ADD_PARAMETER(m_gtol , "gaptol" )->setUnits(UNIT_LENGTH);; ADD_PARAMETER(m_ptol , "ptol" ); ADD_PARAMETER(m_epsn , "penalty" ); ADD_PARAMETER(m_bautopen , "auto_penalty" ); ADD_PARAMETER(m_bupdtpen , "update_penalty" ); ADD_PARAMETER(m_btwo_pass, "two_pass" ); ADD_PARAMETER(m_knmult , "knmult" ); ADD_PARAMETER(m_stol , "search_tol" ); ADD_PARAMETER(m_epsp , "pressure_penalty" ); ADD_PARAMETER(m_bsymm , "symmetric_stiffness"); ADD_PARAMETER(m_srad , "search_radius" )->setUnits(UNIT_LENGTH);; ADD_PARAMETER(m_nsegup , "seg_up" ); ADD_PARAMETER(m_naugmin , "minaug" ); ADD_PARAMETER(m_naugmax , "maxaug" ); ADD_PARAMETER(m_breloc , "node_reloc" ); ADD_PARAMETER(m_mu , "fric_coeff" ); ADD_PARAMETER(m_phi , "contact_frac" ); ADD_PARAMETER(m_bsmaug , "smooth_aug" ); ADD_PARAMETER(m_bsmfls , "smooth_fls" ); ADD_PARAMETER(m_bflips , "flip_primary" ); ADD_PARAMETER(m_bflipm , "flip_secondary" ); ADD_PARAMETER(m_bshellbs , "shell_bottom_primary" ); ADD_PARAMETER(m_bshellbm , "shell_bottom_secondary"); END_FECORE_CLASS(); //----------------------------------------------------------------------------- // FESlidingSurfaceBiphasic //----------------------------------------------------------------------------- FESlidingSurfaceBiphasic::FESlidingSurfaceBiphasic(FEModel* pfem) : FEBiphasicContactSurface(pfem) { m_bporo = false; } //----------------------------------------------------------------------------- //! create material point data FEMaterialPoint* FESlidingSurfaceBiphasic::CreateMaterialPoint() { return new FEBiphasicContactPoint; } //----------------------------------------------------------------------------- bool FESlidingSurfaceBiphasic::Init() { // initialize surface data first if (FEBiphasicContactSurface::Init() == false) return false; // allocate node normals and contact tractions m_nn.assign(Nodes(), vec3d(0,0,0)); m_tn.assign(Nodes(), vec3d(0,0,0)); m_pn.assign(Nodes(), 0); // determine biphasic status m_poro.resize(Elements(),false); for (int i=0; i<Elements(); ++i) { // get the surface element FESurfaceElement& se = Element(i); // get the element this surface element belongs to FEElement* pe = se.m_elem[0].pe; if (pe) { // get the material FEMaterial* pm = m_pfem->GetMaterial(pe->GetMatID()); // see if this is a poro-elastic element FEBiphasic* biph = dynamic_cast<FEBiphasic*> (pm); if (biph) { m_poro[i] = true; m_bporo = true; } } } return true; } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::InitSlidingSurface() { for (int i=0; i<Elements(); ++i) { FESurfaceElement& el = Element(i); int nint = el.GaussPoints(); for (int j=0; j<nint; ++j) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); // Store current surface projection values as previous data.m_rsp = data.m_rs; data.m_pmep = data.m_pme; } } } //----------------------------------------------------------------------------- //! Evaluate the nodal contact pressures by averaging values from surrounding //! faces. This function ensures that nodal contact pressures are always //! positive, so that they can be used to detect free-draining status. void FESlidingSurfaceBiphasic::EvaluateNodalContactPressures() { const int N = Nodes(); // number of faces with non-zero contact pressure connected to this node vector<int> nfaces(N,0); // zero nodal contact pressures zero(m_pn); // loop over all elements for (int i=0; i<Elements(); ++i) { FESurfaceElement& el = Element(i); int ne = el.Nodes(); // get the average contact pressure for that face double pn = 0; GetContactPressure(i, pn); if (pn > 0) { for (int j=0; j<ne; ++j) { m_pn[el.m_lnode[j]] += pn; ++nfaces[el.m_lnode[j]]; } } } // get average over all contacting faces sharing that node for (int i=0; i<N; ++i) if (nfaces[i] > 0) m_pn[i] /= nfaces[i]; } //----------------------------------------------------------------------------- //! Evaluate the nodal contact tractions by averaging values from surrounding //! faces. This function ensures that nodal contact tractions are always //! compressive, so that they can be used to detect free-draining status. void FESlidingSurfaceBiphasic::EvaluateNodalContactTractions() { const int N = Nodes(); // number of faces with non-zero contact pressure connected to this node vector<int> nfaces(N,0); // zero nodal contact tractions zero(m_tn); // loop over all elements for (int i=0; i<Elements(); ++i) { FESurfaceElement& el = Element(i); int ne = el.Nodes(); // get the average contact traction and pressure for that face vec3d tn(0,0,0); GetContactTraction(i, tn); double pn = 0; GetContactPressure(i, pn); if (pn > 0) { for (int j=0; j<ne; ++j) { m_tn[el.m_lnode[j]] += tn; ++nfaces[el.m_lnode[j]]; } } } // get average over all contacting faces sharing that node for (int i=0; i<N; ++i) if (nfaces[i] > 0) m_tn[i] /= nfaces[i]; } //----------------------------------------------------------------------------- //! This function calculates the node normal. Due to the piecewise continuity //! of the surface elements this normal is not uniquely defined so in order to //! obtain a unique normal the normal is averaged for each node over all the //! element normals at the node void FESlidingSurfaceBiphasic::UpdateNodeNormals() { const int MN = FEElement::MAX_NODES; vec3d y[MN]; // zero nodal normals zero(m_nn); // loop over all elements for (int i=0; i<Elements(); ++i) { FESurfaceElement& el = Element(i); int ne = el.Nodes(); // get the nodal coordinates for (int j=0; j<ne; ++j) y[j] = Node(el.m_lnode[j]).m_rt; // calculate the normals for (int j=0; j<ne; ++j) { int jp1 = (j+1)%ne; int jm1 = (j+ne-1)%ne; vec3d n = (y[jp1] - y[j]) ^ (y[jm1] - y[j]); m_nn[el.m_lnode[j]] += n; } } // normalize all vectors const int N = Nodes(); for (int i=0; i<N; ++i) m_nn[i].unit(); } //----------------------------------------------------------------------------- vec3d FESlidingSurfaceBiphasic::GetContactForce() { return m_Ft; } //----------------------------------------------------------------------------- double FESlidingSurfaceBiphasic::GetContactArea() { // initialize contact area double a = 0; // loop over all elements of the primary surface for (int n=0; n<Elements(); ++n) { FESurfaceElement& el = Element(n); int nint = el.GaussPoints(); // evaluate the contact force for that element for (int i=0; i<nint; ++i) { // get data for this integration point FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(i)); if (data.m_Ln > 0) { // get the base vectors vec3d g[2]; CoBaseVectors(el, i, g); // normal (magnitude = area) vec3d n = g[0] ^ g[1]; // gauss weight double w = el.GaussWeights()[i]; // contact force a += n.norm()*w; } } } return a; } //----------------------------------------------------------------------------- vec3d FESlidingSurfaceBiphasic::GetFluidForce() { int n, i; const int MN = FEElement::MAX_NODES; double pn[MN]; // initialize contact force vec3d f(0,0,0); // loop over all elements of the surface for (n=0; n<Elements(); ++n) { FESurfaceElement& el = Element(n); int nseln = el.Nodes(); // nodal pressures for (i=0; i<nseln; ++i) pn[i] = GetMesh()->Node(el.m_node[i]).get(m_dofP); int nint = el.GaussPoints(); // evaluate the fluid force for that element for (i=0; i<nint; ++i) { // get the base vectors vec3d g[2]; CoBaseVectors(el, i, g); // normal (magnitude = area) vec3d n = g[0] ^ g[1]; // gauss weight double w = el.GaussWeights()[i]; // fluid pressure double p = el.eval(pn, i); // contact force f += n*(w*p); } } return f; } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::Serialize(DumpStream& ar) { FEBiphasicContactSurface::Serialize(ar); ar & m_bporo; ar & m_poro; ar & m_nn; ar & m_pn; ar & m_tn; ar & m_Ft; } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::GetVectorGap(int nface, vec3d& pg) { FESurfaceElement& el = Element(nface); int ni = el.GaussPoints(); pg = vec3d(0,0,0); for (int k = 0; k < ni; ++k) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(k)); pg += data.m_dg; } pg /= ni; } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::GetContactPressure(int nface, double& pg) { FESurfaceElement& el = Element(nface); int ni = el.GaussPoints(); pg = 0; for (int k = 0; k < ni; ++k) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(k)); pg += data.m_Ln; } pg /= ni; } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::GetContactTraction(int nface, vec3d& pt) { FESurfaceElement& el = Element(nface); int ni = el.GaussPoints(); pt = vec3d(0,0,0); for (int k = 0; k < ni; ++k) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(k)); pt += data.m_tr; } pt /= ni; } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::GetSlipTangent(int nface, vec3d& pt) { FESurfaceElement& el = Element(nface); int ni = el.GaussPoints(); pt = vec3d(0,0,0); for (int k = 0; k < ni; ++k) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(k)); if (!data.m_bstick) pt += data.m_s1; } pt /= ni; } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::GetMuEffective(int nface, double& pg) { FESurfaceElement& el = Element(nface); int ni = el.GaussPoints(); pg = 0; for (int k = 0; k < ni; ++k) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(k)); pg += data.m_mueff; } pg /= ni; } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::GetLocalFLS(int nface, double& pg) { FESurfaceElement& el = Element(nface); int ni = el.GaussPoints(); pg = 0; for (int k = 0; k < ni; ++k) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(k)); pg += data.m_fls; } pg /= ni; } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::GetNodalVectorGap(int nface, vec3d* pg) { FESurfaceElement& el = Element(nface); int ni = el.GaussPoints(); vec3d gi[FEElement::MAX_INTPOINTS]; for (int k = 0; k < ni; ++k) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(k)); gi[k] = data.m_dg; } el.project_to_nodes(gi, pg); } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::GetNodalContactPressure(int nface, double* pg) { FESurfaceElement& el = Element(nface); for (int k=0; k<el.Nodes(); ++k) pg[k] = m_pn[el.m_lnode[k]]; } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::GetStickStatus(int nface, double& pg) { FESurfaceElement& el = Element(nface); int ni = el.GaussPoints(); pg = 0; for (int k = 0; k < ni; ++k) { FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(k)); if (data.m_bstick) pg += 1.0; } pg /= ni; } //----------------------------------------------------------------------------- void FESlidingSurfaceBiphasic::GetNodalContactTraction(int nface, vec3d* tn) { FESurfaceElement& el = Element(nface); for (int k=0; k<el.Nodes(); ++k) tn[k] = m_tn[el.m_lnode[k]]; } //----------------------------------------------------------------------------- // FESlidingInterfaceBiphasic //----------------------------------------------------------------------------- FESlidingInterfaceBiphasic::FESlidingInterfaceBiphasic(FEModel* pfem) : FEContactInterface(pfem), m_ss(pfem), m_ms(pfem) { static int count = 1; SetID(count++); // initial values m_knmult = 0; m_atol = 0.1; m_epsn = 1; m_epsp = 1; m_btwo_pass = false; m_stol = 0.01; m_bsymm = true; m_srad = 1.0; m_gtol = 0; m_ptol = 0; m_nsegup = 0; m_bautopen = false; m_breloc = false; m_bsmaug = false; m_bsmfls = false; m_bupdtpen = false; m_mu = 0.0; m_phi = 0.0; m_naugmin = 0; m_naugmax = 10; m_bfreeze = false; m_bflipm = m_bflips = false; m_bshellbm = m_bshellbs = false; m_dofP = pfem->GetDOFIndex("p"); // set parents m_ss.SetContactInterface(this); m_ms.SetContactInterface(this); m_ss.SetSibling(&m_ms); m_ms.SetSibling(&m_ss); } //----------------------------------------------------------------------------- FESlidingInterfaceBiphasic::~FESlidingInterfaceBiphasic() { } //----------------------------------------------------------------------------- bool FESlidingInterfaceBiphasic::Init() { // initialize surface data if (m_ss.Init() == false) return false; if (m_ms.Init() == false) return false; // Flip secondary and primary surfaces, if requested. // Note that we turn off those flags because otherwise we keep flipping, each time we get here (e.g. in optimization) // TODO: Of course, we shouldn't get here more than once. I think we also get through the FEModel::Reset, so I'll have // look into that. if (m_bflips) { m_ss.Invert(); m_bflips = false; } if (m_bflipm) { m_ms.Invert(); m_bflipm = false; } if (m_bshellbs) { m_ss.SetShellBottom(m_bshellbs); m_bshellbs = false; } if (m_bshellbm) { m_ms.SetShellBottom(m_bshellbm); m_bshellbm = false; } return true; } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::BuildMatrixProfile(FEGlobalMatrix& K) { FEModel& fem = *GetFEModel(); FEMesh& mesh = fem.GetMesh(); // 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"); const int dof_RU = fem.GetDOFIndex("Ru"); const int dof_RV = fem.GetDOFIndex("Rv"); const int dof_RW = fem.GetDOFIndex("Rw"); vector<int> lm(7*FEElement::MAX_NODES*2); int npass = (m_btwo_pass?2:1); for (int np=0; np<npass; ++np) { FESlidingSurfaceBiphasic& ss = (np == 0? m_ss : m_ms); int k, l; for (int j=0; j<ss.Elements(); ++j) { FESurfaceElement& se = ss.Element(j); int nint = se.GaussPoints(); int* sn = &se.m_node[0]; for (k=0; k<nint; ++k) { FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*se.GetMaterialPoint(k)); FESurfaceElement* pe = pt.m_pme; if (pe != 0) { FESurfaceElement& me = *pe; int* mn = &me.m_node[0]; assign(lm, -1); int nseln = se.Nodes(); int nmeln = me.Nodes(); for (l=0; l<nseln; ++l) { vector<int>& id = mesh.Node(sn[l]).m_ID; lm[7*l ] = id[dof_X]; lm[7*l+1] = id[dof_Y]; lm[7*l+2] = id[dof_Z]; lm[7*l+3] = id[dof_P]; lm[7*l+4] = id[dof_RU]; lm[7*l+5] = id[dof_RV]; lm[7*l+6] = id[dof_RW]; } for (l=0; l<nmeln; ++l) { vector<int>& id = mesh.Node(mn[l]).m_ID; lm[7*(l+nseln) ] = id[dof_X]; lm[7*(l+nseln)+1] = id[dof_Y]; lm[7*(l+nseln)+2] = id[dof_Z]; lm[7*(l+nseln)+3] = id[dof_P]; lm[7*(l+nseln)+4] = id[dof_RU]; lm[7*(l+nseln)+5] = id[dof_RV]; lm[7*(l+nseln)+6] = id[dof_RW]; } K.build_add(lm); } } } } } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::UpdateAutoPenalty() { // calculate the penalty if (m_bautopen) { CalcAutoPenalty(m_ss); CalcAutoPenalty(m_ms); CalcAutoPressurePenalty(m_ss); CalcAutoPressurePenalty(m_ms); } } //----------------------------------------------------------------------------- //! This function is called during the initialization void FESlidingInterfaceBiphasic::Activate() { // don't forget to call base member FEContactInterface::Activate(); UpdateAutoPenalty(); // update sliding interface data Update(); } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::CalcAutoPenalty(FESlidingSurfaceBiphasic& s) { // loop over all surface elements for (int i=0; i<s.Elements(); ++i) { // get the surface element FESurfaceElement& el = s.Element(i); // calculate a penalty double eps = AutoPenalty(el, s); // assign to integation points of surface element int nint = el.GaussPoints(); for (int j=0; j<nint; ++j) { FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); pt.m_epsn = eps; } } } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::CalcAutoPressurePenalty(FESlidingSurfaceBiphasic& s) { // loop over all surface elements for (int i=0; i<s.Elements(); ++i) { // get the surface element FESurfaceElement& el = s.Element(i); // calculate a penalty double eps = AutoPressurePenalty(el, s); // assign to integation points of surface element int nint = el.GaussPoints(); for (int j=0; j<nint; ++j) { FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); pt.m_epsp = eps; } } } //----------------------------------------------------------------------------- double FESlidingInterfaceBiphasic::AutoPressurePenalty(FESurfaceElement& el, FESlidingSurfaceBiphasic& s) { // get the mesh FEMesh& m = GetFEModel()->GetMesh(); // evaluate element surface normal at parametric center vec3d t[2]; s.CoBaseVectors0(el, 0, 0, t); vec3d n = t[0] ^ t[1]; n.unit(); // get the element this surface element belongs to FEElement* pe = el.m_elem[0].pe; if (pe == 0) return 0.0; // get the material FEMaterial* pm = GetFEModel()->GetMaterial(pe->GetMatID()); // see if this is a poro-elastic element FEBiphasic* biph = dynamic_cast<FEBiphasic*> (pm); if (biph == 0) return 0.0; // get a material point FEMaterialPoint& mp = *pe->GetMaterialPoint(0); FEElasticMaterialPoint& ept = *(mp.ExtractData<FEElasticMaterialPoint>()); // setup the material point ept.m_F = mat3dd(1.0); ept.m_J = 1; ept.m_s.zero(); // if this is a poroelastic element, then get the permeability tensor FEBiphasicMaterialPoint& pt = *(mp.ExtractData<FEBiphasicMaterialPoint>()); pt.m_p = 0; pt.m_w = vec3d(0,0,0); double K[3][3]; biph->Permeability(K, mp); double eps = n.x*(K[0][0]*n.x+K[0][1]*n.y+K[0][2]*n.z) +n.y*(K[1][0]*n.x+K[1][1]*n.y+K[1][2]*n.z) +n.z*(K[2][0]*n.x+K[2][1]*n.y+K[2][2]*n.z); // get the area of the surface element double A = s.FaceArea(el); // get the volume of the volume element double V = m.ElementVolume(*pe); return eps*A/V; } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::ProjectSurface(FESlidingSurfaceBiphasic& ss, FESlidingSurfaceBiphasic& ms, bool bupseg, bool bmove) { FEMesh& mesh = GetFEModel()->GetMesh(); // initialize projection data FENormalProjection np(ms); np.SetTolerance(m_stol); np.SetSearchRadius(m_srad); np.Init(); double psf = GetPenaltyScaleFactor(); // if we need to project the nodes onto the secondary surface, // let's do this first if (bmove) { int NN = ss.Nodes(); int NE = ss.Elements(); // first we need to calculate the node normals vector<vec3d> normal; normal.assign(NN, vec3d(0,0,0)); for (int i=0; i<NE; ++i) { FESurfaceElement& el = ss.Element(i); int ne = el.Nodes(); for (int j=0; j<ne; ++j) { vec3d r0 = ss.Node(el.m_lnode[ j ]).m_rt; vec3d rp = ss.Node(el.m_lnode[(j+ 1)%ne]).m_rt; vec3d rm = ss.Node(el.m_lnode[(j+ne-1)%ne]).m_rt; vec3d n = (rp - r0)^(rm - r0); normal[el.m_lnode[j]] += n; } } for (int i=0; i<NN; ++i) normal[i].unit(); // loop over all nodes for (int i=0; i<NN; ++i) { FENode& node = ss.Node(i); // get the spatial nodal coordinates vec3d rt = node.m_rt; vec3d nu = normal[i]; // project onto the secondary surface vec3d q; double rs[2] = {0,0}; FESurfaceElement* pme = np.Project(rt, nu, rs); if (pme) { // the node could potentially be in contact // find the global location of the intersection point vec3d q = ms.Local2Global(*pme, rs[0], rs[1]); // calculate the gap function // NOTE: this has the opposite sign compared // to Gerard's notes. double gap = nu*(rt - q); if (gap>0) node.m_r0 = node.m_rt = q; } } } // loop over all integration points #pragma omp parallel for for (int i=0; i<ss.Elements(); ++i) { FESurfaceElement& el = ss.Element(i); bool sporo = ss.m_poro[i]; int ne = el.Nodes(); int nint = el.GaussPoints(); double ps[FEElement::MAX_INTPOINTS]; // get the nodal pressures if (sporo) { for (int j=0; j<ne; ++j) ps[j] = mesh.Node(el.m_node[j]).get(m_dofP); } for (int j=0; j<nint; ++j) { // get the integration point data FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); // calculate the global position of the integration point vec3d r = ss.Local2Global(el, j); // get the pressure at the integration point double p1 = 0; if (sporo) p1 = el.eval(ps, j); // calculate the normal at this integration point vec3d nu = ss.SurfaceNormal(el, j); // first see if the old intersected face is still good enough FESurfaceElement* pme = pt.m_pme; double rs[2] = {0,0}; if (pme) { double g; // see if the ray intersects this element if (ms.Intersect(*pme, r, nu, rs, g, m_stol)) { pt.m_rs[0] = rs[0]; pt.m_rs[1] = rs[1]; } else { pme = 0; } } // find the intersection point with the secondary surface if (pme == 0 && bupseg) pme = np.Project(r, nu, rs); pt.m_pme = pme; pt.m_nu = nu; pt.m_rs[0] = rs[0]; pt.m_rs[1] = rs[1]; if (pme) { // the node could potentially be in contact // find the global location of the intersection point vec3d q = ms.Local2Global(*pme, rs[0], rs[1]); // calculate the gap function // NOTE: this has the opposite sign compared // to Gerard's notes. double g = nu*(r - q); double eps = m_epsn*pt.m_epsn*psf; double Ln = pt.m_Lmd + eps*g; pt.m_gap = (g <= m_srad? g : 0); // calculate the pressure gap function bool mporo = ms.m_poro[pme->m_lid]; if ((Ln >= 0) && (g <= m_srad)) { // get the pressure at the projection point double p2 = 0; if (mporo) { double pm[FEElement::MAX_NODES]; for (int k=0; k<pme->Nodes(); ++k) pm[k] = mesh.Node(pme->m_node[k]).get(m_dofP); p2 = pme->eval(pm, rs[0], rs[1]); } if (sporo) { pt.m_p1 = p1; if (mporo) { pt.m_pg = p1 - p2; } } else if (mporo) { pt.m_p1 = p2; } } else { pt.m_Lmd = 0; pt.m_pme = 0; pt.m_gap = 0; pt.m_dg = pt.m_Lmt = vec3d(0,0,0); if (sporo || mporo) { pt.m_Lmp = 0; pt.m_pg = 0; pt.m_p1 = 0; } } } else { // the node is not in contact pt.m_Lmd = 0; pt.m_gap = 0; pt.m_dg = pt.m_Lmt = vec3d(0,0,0); if (sporo) { pt.m_Lmp = 0; pt.m_pg = 0; pt.m_p1 = 0; } } } } } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::Update() { static int naug = 0; static int biter = 0; FEModel& fem = *GetFEModel(); // get the iteration number // we need this number to see if we can do segment updates or not // also reset number of iterations after each augmentation FEAnalysis* pstep = fem.GetCurrentStep(); FESolver* psolver = pstep->GetFESolver(); if (psolver->m_niter == 0) { biter = 0; naug = psolver->m_naug; // check update of auto-penalty if (m_bupdtpen) UpdateAutoPenalty(); } else if (psolver->m_naug > naug) { biter = psolver->m_niter; naug = psolver->m_naug; } int niter = psolver->m_niter - biter; bool bupseg = ((m_nsegup == 0)? true : (niter <= m_nsegup)); // get the logfile // Logfile& log = GetLogfile(); // log.printf("seg_up iteration # %d\n", niter+1); // project the surfaces onto each other // this will update the gap functions as well static bool bfirst = true; ProjectSurface(m_ss, m_ms, bupseg, (m_breloc && bfirst)); if (m_btwo_pass || m_ms.m_bporo) ProjectSurface(m_ms, m_ss, bupseg); bfirst = false; // Call InitSlidingSurface on the first iteration of each time step int nsolve_iter = psolver->m_niter; if (nsolve_iter == 0) { m_ss.InitSlidingSurface(); if (m_btwo_pass) m_ms.InitSlidingSurface(); m_bfreeze = false; } // Update the net contact pressures UpdateContactPressures(); if (niter == 0) m_bfreeze = false; // set poro flag bool bporo = (m_ss.m_bporo || m_ms.m_bporo); // only continue if we are doing a poro-elastic simulation if (bporo == false) return; // update node normals m_ss.UpdateNodeNormals(); if (bporo) m_ms.UpdateNodeNormals(); // Now that the nodes have been projected, we need to figure out // if we need to modify the constraints on the pressure dofs. // If the nodes are not in contact, they must be free // draining. Since all nodes have been previously marked to be // free-draining in MarkFreeDraining(), we just need to reverse // this setting here, for nodes that are in contact. // Next, we loop over each surface, visiting the nodes // and finding out if that node is in contact or not int npass = (m_btwo_pass?2:1); for (int np=0; np<npass; ++np) { FESlidingSurfaceBiphasic& ss = (np == 0? m_ss : m_ms); FESlidingSurfaceBiphasic& ms = (np == 0? m_ms : m_ss); // loop over all the nodes of the primary surface for (int n=0; n<ss.Nodes(); ++n) { FENode& node = ss.Node(n); int id = node.m_ID[m_dofP]; if ((id < -1) && (ss.m_pn[n] > 0)) { // mark node as non-free-draining (= pos ID) node.m_ID[m_dofP] = -id-2; } } // loop over all nodes of the secondary surface // the secondary surface is trickier since we need // to look at the primary surface's projection if (ms.m_bporo) { FENormalProjection np(ss); np.SetTolerance(m_stol); np.SetSearchRadius(m_srad); np.Init(); for (int n=0; n<ms.Nodes(); ++n) { // get the node FENode& node = ms.Node(n); // project it onto the primary surface double rs[2] = {0,0}; FESurfaceElement* pse = np.Project(node.m_rt, ms.m_nn[n], rs); if (pse) { // we found an element, so let's see if it's even remotely close to contact // find the global location of the intersection point vec3d q = ss.Local2Global(*pse, rs[0], rs[1]); // calculate the gap function double g = ms.m_nn[n]*(node.m_rt - q); if (fabs(g) <= m_srad) { // we found an element so let's calculate the nodal traction values for this element // get the normal tractions at the nodes double tn[FEElement::MAX_NODES]; for (int i=0; i<pse->Nodes(); ++i) tn[i] = ss.m_pn[pse->m_lnode[i]]; // now evaluate the traction at the intersection point double tp = pse->eval(tn, rs[0], rs[1]); // if tp > 0, mark node as non-free-draining. (= pos ID) int id = node.m_ID[m_dofP]; if ((id < -1) && (tp > 0)) { // mark as non free-draining node.m_ID[m_dofP] = -id-2; } } } } } } } //----------------------------------------------------------------------------- vec3d FESlidingInterfaceBiphasic::SlipTangent(FESlidingSurfaceBiphasic& ss, const int nel, const int nint, FESlidingSurfaceBiphasic& ms, double& dh, vec3d& r) { vec3d s1(0,0,0); dh = 0; r = vec3d(0,0,0); // get primary surface element FESurfaceElement& se = ss.Element(nel); // get integration point data FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*se.GetMaterialPoint(nint)); double g = data.m_gap; vec3d nu = data.m_nu; // find secondary surface element FESurfaceElement* pme = data.m_pme; // calculate previous positions vec3d x2p = ms.Local2GlobalP(*pme, data.m_rs[0], data.m_rs[1]); vec3d x1p = ss.Local2GlobalP(se, nint); // calculate dx2 vec3d x2 = ms.Local2Global(*pme, data.m_rs[0], data.m_rs[1]); vec3d dx2 = x2 - x2p; // calculate dx1 vec3d x1 = ss.Local2Global(se, nint); vec3d dx1 = x1 - x1p; // get current and previous covariant basis vectors vec3d gscov[2], gscovp[2]; ss.CoBaseVectors(se, nint, gscov); ss.CoBaseVectorsP(se, nint, gscovp); // calculate delta gscov vec3d dgscov[2]; dgscov[0] = gscov[0] - gscovp[0]; dgscov[1] = gscov[1] - gscovp[1]; // calculate m, J, Nhat vec3d m = ((dgscov[0] ^ gscov[1]) + (gscov[0] ^ dgscov[1])); double detJ = (gscov[0] ^ gscov[1]).norm(); mat3d Nhat = (mat3dd(1) - (nu & nu)); // calculate c vec3d c = Nhat*m*(1.0/detJ); // calculate slip direction s1 double norm = (Nhat*(c*(-g) + dx1 - dx2)).norm(); if (norm != 0) { s1 = (Nhat*(c*(-g) + dx1 - dx2))/norm; dh = norm; r = c*(-g) + dx1 - dx2; } return s1; } //----------------------------------------------------------------------------- vec3d FESlidingInterfaceBiphasic::ContactTraction(FESlidingSurfaceBiphasic& ss, const int nel, const int n, FESlidingSurfaceBiphasic& ms, double& pn) { vec3d s1(0,0,0); vec3d dr(0,0,0); vec3d t(0,0,0); pn = 0; double tn = 0, ts = 0, mueff = 0; double psf = GetPenaltyScaleFactor(); // get the mesh FEMesh& m = GetFEModel()->GetMesh(); // get the primary surface element FESurfaceElement& se = ss.Element(nel); // get the integration point data FEBiphasicContactPoint& data = static_cast<FEBiphasicContactPoint&>(*se.GetMaterialPoint(n)); // penalty double eps = m_epsn*data.m_epsn*psf; // normal gap double g = data.m_gap; // normal traction Lagrange multiplier double Lm = data.m_Lmd; // vector traction Lagrange multiplier vec3d Lt = data.m_Lmt; // get the normal at this integration point vec3d nu = data.m_nu; // get the fluid pressure at this integration point double p = data.m_p1; // get poro status of primary surface bool sporo = ss.m_poro[nel]; // get current and previous secondary elements FESurfaceElement* pme = data.m_pme; FESurfaceElement* pmep = data.m_pmep; // zero the effective friction coefficient data.m_mueff = 0.0; data.m_fls = 0.0; data.m_s1 = vec3d(0,0,0); double flsmax = 1./(1-m_phi); // theoretical upper bound on fluid load support // get local FLS from element projection double fls = 0; if (m_bsmfls) { double lfls[FEElement::MAX_INTPOINTS]; ss.GetGPLocalFLS(nel, lfls); fls = lfls[n]; } // if we just returned from an augmentation, do not update stick or slip status if (m_bfreeze && pme) { if (data.m_bstick) { // calculate current global position of the integration point vec3d xo = ss.Local2Global(se, n); // calculate current global position of the previous intersection point vec3d xt = ms.Local2Global(*pmep, data.m_rsp[0], data.m_rsp[1]); // calculate vector gap vec3d dg = xt - xo; // calculate trial stick traction, normal component, shear component t = Lt + dg*eps; tn = t*nu; ts = (t - nu*tn).norm(); // contact pressure pn = MBRACKET(-tn); // calculate effective friction coefficient if (pn > 0) { data.m_mueff = ts/pn; data.m_fls = m_bsmfls ? fls : p/pn; if (data.m_fls > flsmax) data.m_fls = flsmax; } // store the previous values as the current data.m_pme = data.m_pmep; data.m_rs = data.m_rsp; // recalculate gap data.m_dg = dg; // recalculate pressure gap bool mporo = ms.m_poro[pme->m_lid]; if (sporo && mporo) { double pm[FEElement::MAX_NODES]; for (int k=0; k<pme->Nodes(); ++k) pm[k] = m.Node(pme->m_node[k]).get(m_dofP); double p2 = pme->eval(pm, data.m_rs[0], data.m_rs[1]); data.m_pg = p - p2; } } else { // recalculate contact pressure for slip pn = MBRACKET(Lm + eps*g); if (pn != 0) { double dh = 0; // slip direction s1 = SlipTangent(ss, nel, n, ms, dh, dr); // calculate effective friction coefficient data.m_fls = m_bsmfls ? fls : p/pn; if (data.m_fls > flsmax) data.m_fls = flsmax; data.m_mueff = m_mu*(1.0-(1.0-m_phi)*data.m_fls); data.m_mueff = MBRACKET(data.m_mueff); // total traction t = nu*(-pn) - s1*pn*data.m_mueff; // reset slip direction data.m_s1 = s1; } else { t = vec3d(0,0,0); } } } // update contact tractions else { data.m_bstick = false; if (pme) { // assume stick and calculate traction if (pmep) { // calculate current global position of the integration point vec3d xo = ss.Local2Global(se, n); // calculate current global position of the previous intersection point vec3d xt = ms.Local2Global(*pmep, data.m_rsp[0], data.m_rsp[1]); // calculate vector gap vec3d dg = xt - xo; // calculate trial stick traction, normal component, shear component t = Lt + dg*eps; tn = t*nu; ts = (t - nu*tn).norm(); // calculate effective friction coefficient if (tn != 0) { data.m_fls = m_bsmfls ? fls : p/(-tn); if (data.m_fls > flsmax) data.m_fls = flsmax; mueff = m_mu*(1.0-(1.0-m_phi)*data.m_fls); mueff = MBRACKET(mueff); } // check if stick if ( (tn < 0) && (ts < fabs(tn*mueff)) ) { // set boolean flag for stick data.m_bstick = true; // contact pressure pn = MBRACKET(-tn); // calculate effective friction coefficient if (pn > 0) { data.m_mueff = ts/pn; data.m_fls = m_bsmfls ? fls : p/pn; if (data.m_fls > flsmax) data.m_fls = flsmax; } // store the previous values as the current data.m_pme = data.m_pmep; data.m_rs = data.m_rsp; // recalculate gaps data.m_dg = dg; // recalculate pressure gap bool mporo = ms.m_poro[pme->m_lid]; if (sporo && mporo) { double pm[FEElement::MAX_NODES]; for (int k=0; k<pme->Nodes(); ++k) pm[k] = m.Node(pme->m_node[k]).get(m_dofP); double p2 = pme->eval(pm, data.m_rs[0], data.m_rs[1]); data.m_pg = p - p2; } } else { // recalculate contact pressure for slip pn = MBRACKET(Lm + eps*g); if (pn != 0) { double dh = 0; // slip direction s1 = SlipTangent(ss, nel, n, ms, dh, dr); // calculate effective friction coefficient data.m_fls = p/pn; data.m_fls = m_bsmfls ? fls : p/pn; if (data.m_fls > flsmax) data.m_fls = flsmax; data.m_mueff = m_mu*(1.0-(1.0-m_phi)*data.m_fls); data.m_mueff = MBRACKET(data.m_mueff); // total traction t = nu*(-pn) - s1*pn*data.m_mueff; // reset slip direction data.m_s1 = s1; data.m_bstick = false; } else { t = vec3d(0,0,0); } } } else { // assume slip upon first contact // calculate contact pressure for slip pn = MBRACKET(Lm + eps*g); if (pn != 0) { double dh = 0; // slip direction s1 = SlipTangent(ss, nel, n, ms, dh, dr); // calculate effective friction coefficient data.m_fls = m_bsmfls ? fls : p/pn; if (data.m_fls > flsmax) data.m_fls = flsmax; data.m_mueff = m_mu*(1.0-(1.0-m_phi)*data.m_fls); data.m_mueff = MBRACKET(data.m_mueff); // total traction t = nu*(-pn) - s1*pn*data.m_mueff; // reset slip direction data.m_s1 = s1; data.m_bstick = false; } } } } return t; } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::LoadVector(FEGlobalVector& R, const FETimeInfo& tp) { const int MN = FEElement::MAX_NODES; vector<int> sLM, mLM, LM, en; vector<double> fe; double detJ[MN], w[MN], *Hs, Hm[MN]; double N[4*MN*2]; m_ss.m_Ft = vec3d(0,0,0); m_ms.m_Ft = vec3d(0,0,0); FEModel& fem = *GetFEModel(); // need to multiply biphasic stiffness entries by the timestep double dt = fem.GetTime().timeIncrement; // loop over the nr of passes int npass = (m_btwo_pass?2:1); for (int np=0; np<npass; ++np) { // get primary and secondary surface FESlidingSurfaceBiphasic& ss = (np == 0? m_ss : m_ms); FESlidingSurfaceBiphasic& ms = (np == 0? m_ms : m_ss); // loop over all primary surface elements for (int i=0; i<ss.Elements(); ++i) { // get the surface element FESurfaceElement& se = ss.Element(i); bool sporo = ss.m_poro[i]; // get the nr of nodes and integration points int nseln = se.Nodes(); int nint = se.GaussPoints(); // copy the LM vector; we'll need it later ss.UnpackLM(se, sLM); // we calculate all the metrics we need before we // calculate the nodal forces for (int j=0; j<nint; ++j) { // get the base vectors vec3d g[2]; ss.CoBaseVectors(se, j, g); // jacobians: J = |g0xg1| detJ[j] = (g[0] ^ g[1]).norm(); // integration weights w[j] = se.GaussWeights()[j]; } // loop over all integration points // note that we are integrating over the current surface for (int j=0; j<nint; ++j) { // get the integration point data FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*se.GetMaterialPoint(j)); // calculate contact pressure and account for stick double pn; vec3d t = ContactTraction(ss, i, j, ms, pn); // get the secondary element FESurfaceElement* pme = pt.m_pme; if (pme) { // get the secondary element FESurfaceElement& me = *pme; bool mporo = ms.m_poro[pme->m_lid]; // get the nr of secondary element nodes int nmeln = me.Nodes(); // copy LM vector ms.UnpackLM(me, mLM); // calculate degrees of freedom int ndof = 3*(nseln + nmeln); // build the LM vector LM.resize(ndof); for (int k=0; k<nseln; ++k) { LM[3*k ] = sLM[3*k ]; LM[3*k+1] = sLM[3*k+1]; LM[3*k+2] = sLM[3*k+2]; } for (int k=0; k<nmeln; ++k) { LM[3*(k+nseln) ] = mLM[3*k ]; LM[3*(k+nseln)+1] = mLM[3*k+1]; LM[3*(k+nseln)+2] = mLM[3*k+2]; } // build the en vector en.resize(nseln+nmeln); for (int k=0; k<nseln; ++k) en[k ] = se.m_node[k]; for (int k=0; k<nmeln; ++k) en[k+nseln] = me.m_node[k]; // get primary element shape functions Hs = se.H(j); // get secondary element shape functions double r = pt.m_rs[0]; double s = pt.m_rs[1]; me.shape_fnc(Hm, r, s); if (pn > 0) { // calculate the force vector fe.resize(ndof); zero(fe); for (int k=0; k<nseln; ++k) { N[3*k ] = Hs[k]*t.x; N[3*k+1] = Hs[k]*t.y; N[3*k+2] = Hs[k]*t.z; } for (int k=0; k<nmeln; ++k) { N[3*(k+nseln) ] = -Hm[k]*t.x; N[3*(k+nseln)+1] = -Hm[k]*t.y; N[3*(k+nseln)+2] = -Hm[k]*t.z; } for (int k=0; k<ndof; ++k) fe[k] += N[k]*detJ[j]*w[j]; // calculate contact forces for (int k=0; k<nseln; ++k) ss.m_Ft += vec3d(fe[3*k], fe[3*k+1], fe[3*k+2]); for (int k = 0; k<nmeln; ++k) ms.m_Ft += vec3d(fe[3*(k+nseln)], fe[3*(k+nseln)+1], fe[3*(k+nseln)+2]); // assemble the global residual R.Assemble(en, LM, fe); // do the biphasic stuff if (sporo && mporo) { // calculate nr of pressure dofs int ndof = nseln + nmeln; // calculate the flow rate double epsp = m_epsp*pt.m_epsp; double wn = pt.m_Lmp + epsp*pt.m_pg; // fill the LM LM.resize(ndof); for (int k=0; k<nseln; ++k) LM[k ] = sLM[3*nseln+k]; for (int k=0; k<nmeln; ++k) LM[k + nseln] = mLM[3*nmeln+k]; // fill the force array fe.resize(ndof); zero(fe); for (int k=0; k<nseln; ++k) N[k ] = Hs[k]; for (int k=0; k<nmeln; ++k) N[k+nseln] = -Hm[k]; for (int k=0; k<ndof; ++k) fe[k] += dt*wn*N[k]*detJ[j]*w[j]; // assemble residual R.Assemble(en, LM, fe); } } } } } } } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::StiffnessMatrix(FELinearSystem& LS, const FETimeInfo& tp) { // see how many reformations we've had to do so far int nref = GetSolver()->m_nref; const int MN = FEElement::MAX_NODES; double detJ[MN], w[MN], *Hs, Hm[MN]; double N[4*MN*2]; vector<int> sLM, mLM, LM, en; FEElementMatrix ke; FEModel& fem = *GetFEModel(); double psf = GetPenaltyScaleFactor(); // do single- or two-pass int npass = (m_btwo_pass?2:1); for (int np=0; np < npass; ++np) { // get the primary and secondary surface FESlidingSurfaceBiphasic& ss = (np == 0? m_ss : m_ms); FESlidingSurfaceBiphasic& ms = (np == 0? m_ms : m_ss); FEMesh& mesh = *ms.GetMesh(); // loop over all primary elements for (int i=0; i<ss.Elements(); ++i) { // get the primary element FESurfaceElement& se = ss.Element(i); bool sporo = ss.m_poro[i]; // get nr of nodes and integration points int nseln = se.Nodes(); int nint = se.GaussPoints(); // nodal pressures double pn[MN] = {0}; if (sporo) { for (int j=0; j<nseln; ++j) pn[j] = ss.GetMesh()->Node(se.m_node[j]).get(m_dofP); } // copy the LM vector ss.UnpackLM(se, sLM); // we calculate all the metrics we need before we // calculate the nodal forces for (int j=0; j<nint; ++j) { // get the base vectors vec3d g[2]; ss.CoBaseVectors(se, j, g); // jacobians: J = |g0xg1| detJ[j] = (g[0] ^ g[1]).norm(); // integration weights w[j] = se.GaussWeights()[j]; } // loop over all integration points for (int j=0; j<nint; ++j) { // get integration point data FEBiphasicContactPoint& pt = static_cast<FEBiphasicContactPoint&>(*se.GetMaterialPoint(j)); // calculate contact pressure and account for stick double pn; vec3d t = ContactTraction(ss, i, j, ms, pn); // get the secondary element FESurfaceElement* pme = pt.m_pme; if (pme) { FESurfaceElement& me = *pme; bool mporo = ms.m_poro[pme->m_lid]; // get the nr of secondary nodes int nmeln = me.Nodes(); // nodal pressure double pm[MN] = {0}; for (int k=0; k<nmeln; ++k) pm[k] = ms.GetMesh()->Node(me.m_node[k]).get(m_dofP); // copy the LM vector ms.UnpackLM(me, mLM); // calculate degrees of freedom int ndpn; // number of dofs per node int ndof; // number of dofs in stiffness matrix if (sporo && mporo) { // calculate degrees of freedom for biphasic-on-biphasic contact ndpn = 4; ndof = ndpn*(nseln+nmeln); // build the LM vector LM.resize(ndof); for (int k=0; k<nseln; ++k) { LM[4*k ] = sLM[3*k ]; // x-dof LM[4*k+1] = sLM[3*k+1]; // y-dof LM[4*k+2] = sLM[3*k+2]; // z-dof LM[4*k+3] = sLM[3*nseln+k]; // p-dof } for (int k=0; k<nmeln; ++k) { LM[4*(k+nseln) ] = mLM[3*k ]; // x-dof LM[4*(k+nseln)+1] = mLM[3*k+1]; // y-dof LM[4*(k+nseln)+2] = mLM[3*k+2]; // z-dof LM[4*(k+nseln)+3] = mLM[3*nmeln+k]; // p-dof } } else { // calculate degrees of freedom for biphasic-on-elastic or elastic-on-elastic contact ndpn = 3; ndof = ndpn*(nseln + nmeln); // build the LM vector LM.resize(ndof); for (int k=0; k<nseln; ++k) { LM[3*k ] = sLM[3*k ]; LM[3*k+1] = sLM[3*k+1]; LM[3*k+2] = sLM[3*k+2]; } for (int k=0; k<nmeln; ++k) { LM[3*(k+nseln) ] = mLM[3*k ]; LM[3*(k+nseln)+1] = mLM[3*k+1]; LM[3*(k+nseln)+2] = mLM[3*k+2]; } } // build the en vector en.resize(nseln+nmeln); for (int k=0; k<nseln; ++k) en[k ] = se.m_node[k]; for (int k=0; k<nmeln; ++k) en[k+nseln] = me.m_node[k]; // primary shape functions Hs = se.H(j); // secondary shape functions double r = pt.m_rs[0]; double s = pt.m_rs[1]; me.shape_fnc(Hm, r, s); // get primary normal vector vec3d nu = pt.m_nu; // gap function double g = pt.m_gap; // penalty double eps = m_epsn*pt.m_epsn*psf; // only evaluate stiffness matrix if contact traction is non-zero if (pn > 0) { // if stick if (pt.m_bstick) { double dtn = eps; // create the stiffness matrix ke.resize(ndof, ndof); ke.zero(); // evaluate basis vectors on primary surface vec3d gscov[2]; ss.CoBaseVectors(se, j, gscov); // identity tensor mat3d I = mat3dd(1); // evaluate Mc and Ac and combine them into As double* Gsr = se.Gr(j); double* Gss = se.Gs(j); mat3d Ac[MN], As[MN]; mat3d gscovh[2]; gscovh[0].skew(gscov[0]); gscovh[1].skew(gscov[1]); for (int k=0; k<nseln; ++k) { Ac[k] = (gscovh[1]*Gsr[k] - gscovh[0]*Gss[k])/detJ[j]; As[k] = t & (Ac[k]*nu); } // --- S O L I D - S O L I D C O N T A C T --- // a. I-term //------------------------------------ for (int k=0; k<nseln; ++k) N[k ] = Hs[k]; for (int k=0; k<nmeln; ++k) N[k+nseln] = -Hm[k]; double tmp = dtn*detJ[j]*w[j]; for (int l=0; l<nseln+nmeln; ++l) { for (int k=0; k<nseln+nmeln; ++k) { ke[k*ndpn ][l*ndpn ] -= -tmp*N[k]*N[l]*I[0][0]; ke[k*ndpn ][l*ndpn+1] -= -tmp*N[k]*N[l]*I[0][1]; ke[k*ndpn ][l*ndpn+2] -= -tmp*N[k]*N[l]*I[0][2]; ke[k*ndpn+1][l*ndpn ] -= -tmp*N[k]*N[l]*I[1][0]; ke[k*ndpn+1][l*ndpn+1] -= -tmp*N[k]*N[l]*I[1][1]; ke[k*ndpn+1][l*ndpn+2] -= -tmp*N[k]*N[l]*I[1][2]; ke[k*ndpn+2][l*ndpn ] -= -tmp*N[k]*N[l]*I[2][0]; ke[k*ndpn+2][l*ndpn+1] -= -tmp*N[k]*N[l]*I[2][1]; ke[k*ndpn+2][l*ndpn+2] -= -tmp*N[k]*N[l]*I[2][2]; } } // b. A-term //------------------------------------- tmp = detJ[j]*w[j]; // non-symmetric for (int l=0; l<nseln; ++l) { for (int k=0; k<nseln+nmeln; ++k) { ke[k*ndpn ][l*ndpn ] -= tmp*N[k]*As[l][0][0]; ke[k*ndpn ][l*ndpn+1] -= tmp*N[k]*As[l][0][1]; ke[k*ndpn ][l*ndpn+2] -= tmp*N[k]*As[l][0][2]; ke[k*ndpn+1][l*ndpn ] -= tmp*N[k]*As[l][1][0]; ke[k*ndpn+1][l*ndpn+1] -= tmp*N[k]*As[l][1][1]; ke[k*ndpn+1][l*ndpn+2] -= tmp*N[k]*As[l][1][2]; ke[k*ndpn+2][l*ndpn ] -= tmp*N[k]*As[l][2][0]; ke[k*ndpn+2][l*ndpn+1] -= tmp*N[k]*As[l][2][1]; ke[k*ndpn+2][l*ndpn+2] -= tmp*N[k]*As[l][2][2]; } } // --- B I P H A S I C S T I F F N E S S --- if (sporo && mporo) { // need to multiply biphasic stiffness entries by the timestep double dt = fem.GetTime().timeIncrement; double tmp = dt*w[j]*detJ[j]; double epsp = m_epsp*pt.m_epsp*psf; double wn = pt.m_Lmp + epsp*pt.m_pg; // --- S O L I D - P R E S S U R E C O N T A C T --- // b. A-term //------------------------------------- for (int l=0; l<nseln; ++l) { vec3d Acn = Ac[l]*nu; for (int k=0; k<nseln+nmeln; ++k) { ke[4*k + 3][4*l ] -= tmp*wn*N[k]*Acn.x; ke[4*k + 3][4*l+1] -= tmp*wn*N[k]*Acn.y; ke[4*k + 3][4*l+2] -= tmp*wn*N[k]*Acn.z; } } // --- P R E S S U R E - P R E S S U R E C O N T A C T --- // calculate the N-vector for (int k=0; k<nseln; ++k) { N[ndpn*k ] = 0; N[ndpn*k+1] = 0; N[ndpn*k+2] = 0; N[ndpn*k+3] = Hs[k]; } for (int k=0; k<nmeln; ++k) { N[ndpn*(k+nseln) ] = 0; N[ndpn*(k+nseln)+1] = 0; N[ndpn*(k+nseln)+2] = 0; N[ndpn*(k+nseln)+3] = -Hm[k]; } for (int k=0; k<ndof; ++k) for (int l=0; l<ndof; ++l) ke[k][l] -= tmp*epsp*N[k]*N[l]; } // assemble the global stiffness ke.SetNodes(en); ke.SetIndices(LM); LS.Assemble(ke); } // if slip else { // create the stiffness matrix ke.resize(ndof, ndof); ke.zero(); double tn = -pn; // obtain the slip direction s1 and inverse of spatial increment dh double dh = 0, hd = 0; vec3d dr(0,0,0); vec3d s1 = SlipTangent(ss, i, j, ms, dh, dr); if (dh != 0) { hd = 1.0 / dh; } // evaluate basis vectors on both surfaces vec3d gscov[2], gmcov[2]; ss.CoBaseVectors(se, j, gscov); ms.CoBaseVectors(me, r, s, gmcov); mat2d A; A[0][0] = gscov[0]*gmcov[0]; A[0][1] = gscov[0]*gmcov[1]; A[1][0] = gscov[1]*gmcov[0]; A[1][1] = gscov[1]*gmcov[1]; mat2d a = A.inverse(); // evaluate covariant basis vectors on primary surface at previous time step vec3d gscovp[2]; ss.CoBaseVectorsP(se, j, gscovp); // calculate delta gscov vec3d dgscov[2]; dgscov[0] = gscov[0] - gscovp[0]; dgscov[1] = gscov[1] - gscovp[1]; // evaluate approximate contravariant basis vectors when gap != 0 vec3d gscnt[2], gmcnt[2]; gmcnt[0] = gscov[0]*a[0][0] + gscov[1]*a[0][1]; gmcnt[1] = gscov[0]*a[1][0] + gscov[1]*a[1][1]; gscnt[0] = gmcov[0]*a[0][0] + gmcov[1]*a[1][0]; gscnt[1] = gmcov[0]*a[0][1] + gmcov[1]*a[1][1]; // evaluate N and S tensors and approximations when gap != 0 mat3ds N1 = dyad(nu); mat3d Nh1 = mat3dd(1) - (nu & nu); mat3d Nb1 = mat3dd(1) - (gscov[0] & gscnt[0]) - (gscov[1] & gscnt[1]); mat3d Nt1 = nu & (Nb1*nu); mat3d S1 = s1 & nu; mat3d Sh1 = (mat3dd(1) - (s1 & s1))*hd; mat3d Sb1 = s1 & (Nb1*nu); // evaluate m, c, Mg, and R // evaluate L1 from Mg and R // NOTE: Mg has the 1/detJ included in its definition vec3d m = ((dgscov[0] ^ gscov[1]) + (gscov[0] ^ dgscov[1])); vec3d c = Sh1*Nh1*m*(1/detJ[j]); mat3d Mg = (mat3dd(1)*(nu * m) + (nu & m))*(1/detJ[j]); mat3d B = (c & (Nb1*nu)) - Sh1*Nh1; mat3d R = mat3dd(1)*(nu * dr) + (nu & dr); mat3d L1 = Sh1*((Nh1*Mg - mat3dd(1))*(-g) + R)*Nh1; // evaluate Mc and Ac and combine them into As // evaluate Fc from Ac_bar (Ab) // evaluate Jc as L1*Ac-Fc double* Gsr = se.Gr(j); double* Gss = se.Gs(j); mat3d Ac[MN], As[MN], Pc[MN], Jc[MN]; mat3d gscovh[2]; mat3d dgscovh[2]; gscovh[0].skew(gscov[0]); gscovh[1].skew(gscov[1]); dgscovh[0].skew(dgscov[0]); dgscovh[1].skew(dgscov[1]); for (int k=0; k<nseln; ++k) { vec3d mc = gscnt[0]*Gsr[k] + gscnt[1]*Gss[k]; mat3d Mc = nu & mc; Ac[k] = (gscovh[1]*Gsr[k] - gscovh[0]*Gss[k])/detJ[j]; mat3d Ab = (dgscovh[1]*Gsr[k] - dgscovh[0]*Gss[k])/detJ[j]; vec3d hcp = (N1*mc + Ac[k]*nu)*pt.m_mueff*(-g); vec3d hcm = (N1*mc*m_mu - Ac[k]*nu*pt.m_mueff); As[k] = (Ac[k] + Mc*N1); mat3d Jc = (L1*Ac[k]) - Sh1*Nh1*Ab*(-g); Pc[k] = (s1 & hcm) + (c & hcp) - Jc*pt.m_mueff; } // evaluate mb and Mb // evaluate s1 dyad mb and combine as Pb double Gmr[MN], Gms[MN]; me.shape_deriv(Gmr, Gms, r, s); vec3d mb[MN]; mat3d Pb[MN]; for (int k=0; k<nmeln; ++k) { mb[k] = gmcnt[0]*Gmr[k] + gmcnt[1]*Gms[k]; Pb[k] = ((-nu) & mb[k]) - (s1 & mb[k])*pt.m_mueff; } // evaluate Gbc matrix Gbc(nmeln,nseln); for (int b=0; b<nmeln; ++b) { for (int c=0; c<nseln; ++c) { Gbc(b,c) = (a[0][0]*Gmr[b]*Gsr[c] + a[0][1]*Gmr[b]*Gss[c] + a[1][0]*Gms[b]*Gsr[c] + a[1][1]*Gms[b]*Gss[c])*(-g); } } // define T, Ttb mat3d T = N1 + S1*pt.m_mueff; mat3d Ttb = Nt1 + Sb1*m_mu; // --- S O L I D - S O L I D C O N T A C T --- // a. NxN-term //------------------------------------ for (int k=0; k<nseln; ++k) N[k ] = Hs[k]; for (int k=0; k<nmeln; ++k) N[k+nseln] = -Hm[k]; double tmp = detJ[j]*w[j]; for (int l=0; l<nseln+nmeln; ++l) { for (int k=0; k<nseln+nmeln; ++k) { ke[k*ndpn ][l*ndpn ] -= -tmp*N[k]*N[l]*(eps*Ttb[0][0] + pt.m_mueff*tn*B[0][0]); ke[k*ndpn ][l*ndpn+1] -= -tmp*N[k]*N[l]*(eps*Ttb[0][1] + pt.m_mueff*tn*B[0][1]); ke[k*ndpn ][l*ndpn+2] -= -tmp*N[k]*N[l]*(eps*Ttb[0][2] + pt.m_mueff*tn*B[0][2]); ke[k*ndpn+1][l*ndpn ] -= -tmp*N[k]*N[l]*(eps*Ttb[1][0] + pt.m_mueff*tn*B[1][0]); ke[k*ndpn+1][l*ndpn+1] -= -tmp*N[k]*N[l]*(eps*Ttb[1][1] + pt.m_mueff*tn*B[1][1]); ke[k*ndpn+1][l*ndpn+2] -= -tmp*N[k]*N[l]*(eps*Ttb[1][2] + pt.m_mueff*tn*B[1][2]); ke[k*ndpn+2][l*ndpn ] -= -tmp*N[k]*N[l]*(eps*Ttb[2][0] + pt.m_mueff*tn*B[2][0]); ke[k*ndpn+2][l*ndpn+1] -= -tmp*N[k]*N[l]*(eps*Ttb[2][1] + pt.m_mueff*tn*B[2][1]); ke[k*ndpn+2][l*ndpn+2] -= -tmp*N[k]*N[l]*(eps*Ttb[2][2] + pt.m_mueff*tn*B[2][2]); } } // b. Na,Nb-term //------------------------------------- tmp = detJ[j]*w[j]; // non-symmetric for (int l=0; l<nseln; ++l) { for (int k=0; k<nseln+nmeln; ++k) { ke[k*ndpn ][l*ndpn ] -= -tmp*N[k]*(tn*(As[l][0][0] + Pc[l][0][0])); ke[k*ndpn ][l*ndpn+1] -= -tmp*N[k]*(tn*(As[l][0][1] + Pc[l][0][1])); ke[k*ndpn ][l*ndpn+2] -= -tmp*N[k]*(tn*(As[l][0][2] + Pc[l][0][2])); ke[k*ndpn+1][l*ndpn ] -= -tmp*N[k]*(tn*(As[l][1][0] + Pc[l][1][0])); ke[k*ndpn+1][l*ndpn+1] -= -tmp*N[k]*(tn*(As[l][1][1] + Pc[l][1][1])); ke[k*ndpn+1][l*ndpn+2] -= -tmp*N[k]*(tn*(As[l][1][2] + Pc[l][1][2])); ke[k*ndpn+2][l*ndpn ] -= -tmp*N[k]*(tn*(As[l][2][0] + Pc[l][2][0])); ke[k*ndpn+2][l*ndpn+1] -= -tmp*N[k]*(tn*(As[l][2][1] + Pc[l][2][1])); ke[k*ndpn+2][l*ndpn+2] -= -tmp*N[k]*(tn*(As[l][2][2] + Pc[l][2][2])); } } // c. Nc,Nd-term //--------------------------------------- tmp = detJ[j]*w[j]; // non-symmetric for (int k=0; k<nmeln; ++k) { for (int l=0; l<nseln+nmeln; ++l) { ke[(k+nseln)*ndpn ][l*ndpn ] -= tmp*N[l]*tn*Pb[k][0][0]; ke[(k+nseln)*ndpn ][l*ndpn+1] -= tmp*N[l]*tn*Pb[k][0][1]; ke[(k+nseln)*ndpn ][l*ndpn+2] -= tmp*N[l]*tn*Pb[k][0][2]; ke[(k+nseln)*ndpn+1][l*ndpn ] -= tmp*N[l]*tn*Pb[k][1][0]; ke[(k+nseln)*ndpn+1][l*ndpn+1] -= tmp*N[l]*tn*Pb[k][1][1]; ke[(k+nseln)*ndpn+1][l*ndpn+2] -= tmp*N[l]*tn*Pb[k][1][2]; ke[(k+nseln)*ndpn+2][l*ndpn ] -= tmp*N[l]*tn*Pb[k][2][0]; ke[(k+nseln)*ndpn+2][l*ndpn+1] -= tmp*N[l]*tn*Pb[k][2][1]; ke[(k+nseln)*ndpn+2][l*ndpn+2] -= tmp*N[l]*tn*Pb[k][2][2]; } } // c. Gbc-term //--------------------------------------- tmp = tn*detJ[j]*w[j]; for (int k=0; k<nmeln; ++k) { for (int l=0; l<nseln; ++l) { mat3d gT = T*(Gbc[k][l]*tmp); ke[(k+nseln)*ndpn ][l*ndpn ] -= gT[0][0]; ke[(k+nseln)*ndpn ][l*ndpn+1] -= gT[0][1]; ke[(k+nseln)*ndpn ][l*ndpn+2] -= gT[0][2]; ke[(k+nseln)*ndpn+1][l*ndpn ] -= gT[1][0]; ke[(k+nseln)*ndpn+1][l*ndpn+1] -= gT[1][1]; ke[(k+nseln)*ndpn+1][l*ndpn+2] -= gT[1][2]; ke[(k+nseln)*ndpn+2][l*ndpn ] -= gT[2][0]; ke[(k+nseln)*ndpn+2][l*ndpn+1] -= gT[2][1]; ke[(k+nseln)*ndpn+2][l*ndpn+2] -= gT[2][2]; } } // --- B I P H A S I C S T I F F N E S S --- if (sporo && mporo) { // need to multiply biphasic stiffness entries by the timestep double dt = fem.GetTime().timeIncrement; double dpr = 0, dps = 0; dpr = me.eval_deriv1(pm, r, s); dps = me.eval_deriv2(pm, r, s); vec3d q2 = gmcnt[0]*dpr + gmcnt[1]*dps; // evaluate gc vector<double> gc(nseln); for (int k=0; k<nseln; ++k) { gc[k] = (a[0][0]*dpr*Gsr[k] + a[0][1]*dpr*Gss[k] + a[1][0]*dps*Gsr[k] + a[1][1]*dps*Gss[k])*(-g); } tmp = dt*w[j]*detJ[j]; double epsp = m_epsp*pt.m_epsp*psf; vec3d r = s1*m_mu*(1.0 - m_phi); // --- S O L I D - P R E S S U R E C O N T A C T --- // a. q-term //------------------------------------- for (int k=0; k<nseln+nmeln; ++k) for (int l=0; l<nseln+nmeln; ++l) { ke[4*k + 3][4*l ] += tmp*epsp*N[k]*N[l]*q2.x; ke[4*k + 3][4*l+1] += tmp*epsp*N[k]*N[l]*q2.y; ke[4*k + 3][4*l+2] += tmp*epsp*N[k]*N[l]*q2.z; } double wn = pt.m_Lmp + epsp*pt.m_pg; // b. A-term //------------------------------------- for (int l=0; l<nseln; ++l) { vec3d Acn = Ac[l]*nu; for (int k=0; k<nseln+nmeln; ++k) { ke[4*k + 3][4*l ] -= tmp*wn*N[k]*Acn.x; ke[4*k + 3][4*l+1] -= tmp*wn*N[k]*Acn.y; ke[4*k + 3][4*l+2] -= tmp*wn*N[k]*Acn.z; } } // c. s-term //------------------------------------- for (int l=0; l<nseln; ++l) { for (int k=0; k<nseln+nmeln; ++k) { ke[4*k ][4*l+3] -= tmp*N[k]*N[l]*r.x; ke[4*k + 1][4*l+3] -= tmp*N[k]*N[l]*r.y; ke[4*k + 2][4*l+3] -= tmp*N[k]*N[l]*r.z; } } // d. m-term //--------------------------------------- for (int k=0; k<nmeln; ++k) { for (int l=0; l<nseln+nmeln; ++l) { ke[4*(k+nseln) + 3][4*l ] += tmp*wn*N[l]*mb[k].x; ke[4*(k+nseln) + 3][4*l+1] += tmp*wn*N[l]*mb[k].y; ke[4*(k+nseln) + 3][4*l+2] += tmp*wn*N[l]*mb[k].z; } } // e. gc-term //------------------------------------- for (int k=0; k<nseln+nmeln; ++k) for (int l=0; l<nseln; ++l) { ke[4*k + 3][4*l ] -= tmp*epsp*N[k]*gc[l]*nu.x; ke[4*k + 3][4*l+1] -= tmp*epsp*N[k]*gc[l]*nu.y; ke[4*k + 3][4*l+2] -= tmp*epsp*N[k]*gc[l]*nu.z; } // f. Gbc-term //--------------------------------------- for (int k=0; k<nmeln; ++k) { for (int l=0; l<nseln; ++l) { ke[4*(k+nseln) + 3][4*l ] -= tmp*wn*Gbc[k][l]*nu.x; ke[4*(k+nseln) + 3][4*l+1] -= tmp*wn*Gbc[k][l]*nu.y; ke[4*(k+nseln) + 3][4*l+2] -= tmp*wn*Gbc[k][l]*nu.z; } } // --- P R E S S U R E - P R E S S U R E C O N T A C T --- // calculate the N-vector for (int k=0; k<nseln; ++k) { N[ndpn*k ] = 0; N[ndpn*k+1] = 0; N[ndpn*k+2] = 0; N[ndpn*k+3] = Hs[k]; } for (int k=0; k<nmeln; ++k) { N[ndpn*(k+nseln) ] = 0; N[ndpn*(k+nseln)+1] = 0; N[ndpn*(k+nseln)+2] = 0; N[ndpn*(k+nseln)+3] = -Hm[k]; } for (int k=0; k<ndof; ++k) for (int l=0; l<ndof; ++l) ke[k][l] -= tmp*epsp*N[k]*N[l]; } // assemble the global stiffness ke.SetNodes(en); ke.SetIndices(LM); LS.Assemble(ke); } } } } } } } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::UpdateContactPressures() { int npass = (m_btwo_pass?2:1); const int MN = FEElement::MAX_NODES; const int MI = FEElement::MAX_INTPOINTS; double psf = GetPenaltyScaleFactor(); for (int np=0; np<npass; ++np) { FESlidingSurfaceBiphasic& ss = (np == 0? m_ss : m_ms); FESlidingSurfaceBiphasic& ms = (np == 0? m_ms : m_ss); // loop over all elements of the primary surface for (int n=0; n<ss.Elements(); ++n) { FESurfaceElement& el = ss.Element(n); int nint = el.GaussPoints(); // get the normal tractions at the integration points for (int i=0; i<nint; ++i) { // get integration point data FEBiphasicContactPoint& sd = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(i)); // evaluate traction on primary surface double eps = m_epsn*sd.m_epsn*psf; if (sd.m_bstick) { // if stick, evaluate total traction sd.m_tr = sd.m_Lmt + sd.m_dg*eps; // then derive normal component sd.m_Ln = -sd.m_tr*sd.m_nu; } else { // if slip, evaluate normal traction double Ln = sd.m_Lmd + eps*sd.m_gap; sd.m_Ln = MBRACKET(Ln); // then derive total traction sd.m_tr = -(sd.m_nu*sd.m_Ln + sd.m_s1*sd.m_Ln*sd.m_mueff); } FESurfaceElement* pme = sd.m_pme; if (m_btwo_pass && pme) { // get secondary element data int mint = pme->GaussPoints(); double pi[MI]; vec3d ti[MI]; for (int j=0; j<mint; ++j) { FEBiphasicContactPoint& md = static_cast<FEBiphasicContactPoint&>(*pme->GetMaterialPoint(j)); // evaluate traction on secondary surface double eps = m_epsn*md.m_epsn*psf; if (md.m_bstick) { // if stick, evaluate total traction ti[j] = md.m_Lmt + md.m_dg*eps; // then derive normal component pi[j] = -ti[j]*md.m_nu; } else { // if slip, evaluate normal traction double Ln = md.m_Lmd + eps*md.m_gap; pi[j] = MBRACKET(Ln); // then derive total traction ti[j] = -(md.m_nu*pi[j] + md.m_s1*md.m_mueff*pi[j]); } } // project the data to the nodes double pn[MN]; vec3d tn[MN]; pme->FEElement::project_to_nodes(pi, pn); pme->project_to_nodes(ti, tn); // now evaluate the traction at the intersection point double Ln = pme->eval(pn, sd.m_rs[0], sd.m_rs[1]); vec3d trac = pme->eval(tn, sd.m_rs[0], sd.m_rs[1]); sd.m_Ln += MBRACKET(Ln); // tractions on primary-secondary are opposite, so subtract sd.m_tr -= trac; } } } ss.EvaluateNodalContactPressures(); ss.EvaluateNodalContactTractions(); } } //----------------------------------------------------------------------------- bool FESlidingInterfaceBiphasic::Augment(int naug, const FETimeInfo& tp) { // make sure we need to augment if (m_laugon != FECore::AUGLAG_METHOD) return true; int i; double Ln, Lp; bool bconv = true; double psf = GetPenaltyScaleFactor(); bool bporo = (m_ss.m_bporo && m_ms.m_bporo); int NS = m_ss.Elements(); int NM = m_ms.Elements(); // --- c a l c u l a t e i n i t i a l n o r m s --- // a. normal component double normL0 = 0, normP = 0, normDP = 0; for (int i=0; i<NS; ++i) { FESurfaceElement& el = m_ss.Element(i); for (int j=0; j<el.GaussPoints(); ++j) { FEBiphasicContactPoint& ds = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); if (ds.m_bstick) normL0 += ds.m_Lmt*ds.m_Lmt; else normL0 += ds.m_Lmd*ds.m_Lmd; } } for (int i=0; i<NM; ++i) { FESurfaceElement& el = m_ms.Element(i); for (int j=0; j<el.GaussPoints(); ++j) { FEBiphasicContactPoint& dm = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); if (dm.m_bstick) normL0 += dm.m_Lmt*dm.m_Lmt; else normL0 += dm.m_Lmd*dm.m_Lmd; } } // b. gap component // (is calculated during update) double maxgap = 0; double maxpg = 0; // update Lagrange multipliers double normL1 = 0, epsp; for (i=0; i<NS; ++i) { FESurfaceElement& el = m_ss.Element(i); vec3d tn[FEElement::MAX_INTPOINTS]; if (m_bsmaug) m_ss.GetGPSurfaceTraction(i, tn); for (int j=0; j<el.GaussPoints(); ++j) { FEBiphasicContactPoint& ds = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); // update Lagrange multipliers on primary surface double eps = m_epsn*ds.m_epsn*psf; if (ds.m_bstick) { // if stick, augment total traction if (m_bsmaug) { ds.m_Lmt = tn[j]; if (m_btwo_pass) ds.m_Lmt /= 2; } else { ds.m_Lmt += ds.m_dg*eps; } // then derive normal component ds.m_Lmd = -ds.m_Lmt*ds.m_nu; Ln = ds.m_Lmd; normL1 += ds.m_Lmt*ds.m_Lmt; if (Ln > 0) maxgap = max(maxgap, fabs(ds.m_dg.norm())); } else { // if slip, augment normal traction if (m_bsmaug) { Ln = -(tn[j]*ds.m_nu); ds.m_Lmd = MBRACKET(Ln); if (m_btwo_pass) ds.m_Lmd /= 2; } else { Ln = ds.m_Lmd + eps*ds.m_gap; ds.m_Lmd = MBRACKET(Ln); } // then derive total traction double mueff = m_mu*(1.0-(1.0-m_phi)*ds.m_p1/ds.m_Lmd); if ( ds.m_Lmd < (1-m_phi)*ds.m_p1 ) { mueff = 0.0; } ds.m_Lmt = -(ds.m_nu*ds.m_Lmd + ds.m_s1*ds.m_Lmd*mueff); normL1 += ds.m_Lmd*ds.m_Lmd; if (Ln > 0) maxgap = max(maxgap, fabs(ds.m_gap)); } if (m_ss.m_bporo) { Lp = 0; if (Ln > 0) { epsp = m_epsp*ds.m_epsp*psf; Lp = ds.m_Lmp + epsp*ds.m_pg; maxpg = max(maxpg,fabs(ds.m_pg)); normDP += ds.m_pg*ds.m_pg; } ds.m_Lmp = Lp; } } } for (i=0; i<NM; ++i) { FESurfaceElement& el = m_ms.Element(i); vec3d tn[FEElement::MAX_INTPOINTS]; if (m_bsmaug) m_ms.GetGPSurfaceTraction(i, tn); for (int j=0; j<el.GaussPoints(); ++j) { FEBiphasicContactPoint& dm = static_cast<FEBiphasicContactPoint&>(*el.GetMaterialPoint(j)); // update Lagrange multipliers on secondary surface double eps = m_epsn*dm.m_epsn*psf; if (dm.m_bstick) { // if stick, augment total traction if (m_bsmaug) { dm.m_Lmt = tn[j]; if (m_btwo_pass) dm.m_Lmt /= 2; } else { dm.m_Lmt += dm.m_dg*eps; } // then derive normal component dm.m_Lmd = -dm.m_Lmt*dm.m_nu; Ln = dm.m_Lmd; normL1 += dm.m_Lmt*dm.m_Lmt; if (Ln > 0) maxgap = max(maxgap, fabs(dm.m_dg.norm())); } else { // if slip, augment normal traction if (m_bsmaug) { Ln = -(tn[j]*dm.m_nu); dm.m_Lmd = MBRACKET(Ln); if (m_btwo_pass) dm.m_Lmd /= 2; } else { Ln = dm.m_Lmd + eps*dm.m_gap; dm.m_Lmd = MBRACKET(Ln); } // then derive total traction double mueff = m_mu*(1.0-(1.0-m_phi)*dm.m_p1/dm.m_Lmd); if ( dm.m_Lmd < (1-m_phi)*dm.m_p1 ) { mueff = 0.0; } dm.m_Lmt = -(dm.m_nu*dm.m_Lmd + dm.m_s1*dm.m_Lmd*mueff); normL1 += dm.m_Lmd*dm.m_Lmd; if (Ln > 0) maxgap = max(maxgap, fabs(dm.m_gap)); } if (m_ms.m_bporo) { Lp = 0; if (Ln > 0) { epsp = m_epsp*dm.m_epsp*psf; Lp = dm.m_Lmp + epsp*dm.m_pg; maxpg = max(maxpg,fabs(dm.m_pg)); normDP += dm.m_pg*dm.m_pg; } dm.m_Lmp = Lp; } } } // normP should be a measure of the fluid pressure at the // contact interface. However, since it could be zero, // use an average measure of the contact traction instead. normP = normL1; // calculate relative norms double lnorm = (normL1 != 0 ? fabs((normL1 - normL0) / normL1) : fabs(normL1 - normL0)); double pnorm = (normP != 0 ? (normDP/normP) : normDP); // check convergence if ((m_gtol > 0) && (maxgap > m_gtol)) bconv = false; if ((m_ptol > 0) && (bporo && maxpg > m_ptol)) bconv = false; if ((m_atol > 0) && (lnorm > m_atol)) bconv = false; if ((m_atol > 0) && (pnorm > m_atol)) bconv = false; if (naug < m_naugmin ) bconv = false; if (naug >= m_naugmax) bconv = true; feLog(" sliding interface # %d\n", GetID()); feLog(" CURRENT REQUIRED\n"); feLog(" D multiplier : %15le", lnorm); if (m_atol > 0) feLog("%15le\n", m_atol); else feLog(" ***\n"); if (bporo) { feLog(" P gap : %15le", pnorm); if (m_atol > 0) feLog("%15le\n", m_atol); else feLog(" ***\n"); } feLog(" maximum gap : %15le", maxgap); if (m_gtol > 0) feLog("%15le\n", m_gtol); else feLog(" ***\n"); if (bporo) { feLog(" maximum pgap : %15le", maxpg); if (m_ptol > 0) feLog("%15le\n", m_ptol); else feLog(" ***\n"); } ProjectSurface(m_ss, m_ms, true); if (m_btwo_pass) ProjectSurface(m_ms, m_ss, true); m_bfreeze = true; return bconv; } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::Serialize(DumpStream &ar) { // serialize contact data FEContactInterface::Serialize(ar); // serialize contact surface data m_ms.Serialize(ar); m_ss.Serialize(ar); // serialize element pointers SerializeElementPointers(m_ss, m_ms, ar); SerializeElementPointers(m_ms, m_ss, ar); } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::MarkFreeDraining() { int i, id, np; // Mark all nodes as free-draining. This needs to be done for ALL // contact interfaces prior to executing Update(), where nodes that are // in contact are subsequently marked as non free-draining. This ensures // that for surfaces involved in more than one contact interface, nodes // that have been marked as non free-draining are not reset to // free-draining. for (np=0; np<2; ++np) { FESlidingSurfaceBiphasic& s = (np == 0? m_ss : m_ms); if (s.m_bporo) { // first, mark all nodes as free-draining (= neg. ID) // this is done by setting the dof's equation number // to a negative number for (i=0; i<s.Nodes(); ++i) { id = s.Node(i).m_ID[m_dofP]; if (id >= 0) { FENode& node = s.Node(i); // mark node as free-draining node.m_ID[m_dofP] = -id-2; } } } } } //----------------------------------------------------------------------------- void FESlidingInterfaceBiphasic::SetFreeDraining() { int i, np; // Set the pressure to zero for the free-draining nodes for (np=0; np<2; ++np) { FESlidingSurfaceBiphasic& s = (np == 0? m_ss : m_ms); if (s.m_bporo) { // loop over all nodes for (i=0; i<s.Nodes(); ++i) { if (s.Node(i).m_ID[m_dofP] < -1) { FENode& node = s.Node(i); // set the fluid pressure to zero node.set(m_dofP, 0); } } } } }
C++
3D
febiosoftware/FEBio
FEBioMix/FEMembraneReactionRateConst.h
.h
2,710
62
/*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 "FEMultiphasic.h" //----------------------------------------------------------------------------- //! constant membrane reaction rate //! class FEBIOMIX_API FEMembraneReactionRateConst : public FEMembraneReactionRate { public: //! constructor FEMembraneReactionRateConst(FEModel* pfem) : FEMembraneReactionRate(pfem) { m_k = 0; } //! reaction rate at material point double ReactionRate(FEMaterialPoint& pt) override { return m_k; } //! tangent of reaction rate with strain at material point double Tangent_ReactionRate_Strain(FEMaterialPoint& pt) override { return 0; } //! tangent of reaction rate with effective fluid pressure at material point double Tangent_ReactionRate_Pressure(FEMaterialPoint& pt) override {return 0; } double Tangent_ReactionRate_Pe(FEMaterialPoint& pt) override { return 0; } double Tangent_ReactionRate_Pi(FEMaterialPoint& pt) override { return 0; } //! tangent of reaction rate with effective solute concentration at material point double Tangent_ReactionRate_Concentration(FEMaterialPoint& pt, const int isol) override {return 0; } double Tangent_ReactionRate_Ce(FEMaterialPoint& pt, const int isol) override { return 0; } double Tangent_ReactionRate_Ci(FEMaterialPoint& pt, const int isol) override { return 0; }; public: double m_k; //!< reaction rate DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FESupplyConst.h
.h
2,515
71
/*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 "FEBiphasicSolute.h" //----------------------------------------------------------------------------- // This class implements a material that has a constant solute supply class FEBIOMIX_API FESupplyConst : public FESoluteSupply { public: //! constructor FESupplyConst(FEModel* pfem); //! Solute supply double Supply(FEMaterialPoint& pt) override; //! Tangent of supply with respect to strain double Tangent_Supply_Strain(FEMaterialPoint& mp) override; //! Tangent of supply with respect to concentration double Tangent_Supply_Concentration(FEMaterialPoint& mp) override; //! receptor-ligand complex supply double ReceptorLigandSupply(FEMaterialPoint& mp) override; //! Solute supply at steady-state double SupplySS(FEMaterialPoint& pt) override; //! receptor-ligand complex concentration at steady-state double ReceptorLigandConcentrationSS(FEMaterialPoint& mp) override; //! referential solid supply double SolidSupply(FEMaterialPoint& pt) override; //! referential solid volume fraction under steady-state conditions double SolidConcentrationSS(FEMaterialPoint& pt) override; public: double m_supp; //!< solute supply // declare parameter list DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FEBiphasicSolver.h
.h
4,769
153
/*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/FENewtonSolver.h> #include <FECore/FEElementTraits.h> #include <FECore/FEDofList.h> #include <FEBioMech/FERigidSolver.h> #include "febiomix_api.h" //----------------------------------------------------------------------------- // This class adds additional functionality to the FESolidSolver to solve // biphasic problems. class FEBIOMIX_API FEBiphasicSolver : public FENewtonSolver { public: //! constructor FEBiphasicSolver(FEModel* pfem); virtual ~FEBiphasicSolver(); //! Initialize data structures bool Init() override; //! Initialize linear equation system bool InitEquations() override; //! prepares the data for the first QN iteration void PrepStep() override; //! Performs a Newton-Raphson iteration bool Quasin() override; //! serialize data to/from dump file void Serialize(DumpStream& ar) override; //! Generate warnings if needed void SolverWarnings(); public: void Update(vector<double>& ui) override; //! update contact void UpdateModel() override; //! update kinematics virtual void UpdateKinematics(vector<double>& ui); //! Update EAS void UpdateEAS(vector<double>& ui); void UpdateIncrementsEAS(vector<double>& ui, const bool binc); //! Update poroelastic data void UpdatePoro(vector<double>& ui); public: //! Calculates residual (overridden from FESolidSolver2) bool Residual(vector<double>& R) override; //! calculates the global stiffness matrix (overridden from FESolidSolver2) bool StiffnessMatrix() override; //! Internal forces void InternalForces(FEGlobalVector& R); //! external forces void ExternalForces(FEGlobalVector& R); void ContactForces(FEGlobalVector& R); void ContactStiffness(FELinearSystem& LS); void NonLinearConstraintForces(FEGlobalVector& R, const FETimeInfo& tp); void NonLinearConstraintStiffness(FELinearSystem& LS, const FETimeInfo& tp); protected: void GetDisplacementData(vector<double>& di, vector<double>& ui); void GetPressureData(vector<double>& pi, vector<double>& ui); Matrix_Type PreferredMatrixType() const override { return REAL_UNSYMMETRIC; }; public: // additional convergence norms double m_Dtol; //!< displacement tolerance double m_Ptol; //!< pressure tolerance double m_Ctol; //!< needed only for biphasic-solute analyses // biphasic formulation int m_biphasicFormulation; // = 0: standard, =1: mixed (linear pressure) // equation numbers int m_ndeq; //!< number of equations related to displacement dofs int m_npeq; //!< number of equations related to pressure dofs int m_nreq; //!< start of rigid body equations vector<int> m_nceq; //!< number of equations related to concentration dofs vector<double> m_Fr; //!< nodal reaction forces // poro data vector<double> m_di; //!< displacement increment vector vector<double> m_Di; //!< total displacement vector for iteration vector<double> m_pi; //!< pressure increment vector vector<double> m_Pi; //!< Total pressure vector for iteration protected: FEDofList m_dofU, m_dofV; FEDofList m_dofRQ; FEDofList m_dofSU, m_dofSV, m_dofSA; FEDofList m_dofP; //!< pressure dof index FEDofList m_dofSP; //!< shell pressure dof index // obsolete parameters double m_rhoi = -2; double m_alpha = 1; double m_beta = 0.25; double m_gamma = 0.5; bool m_logSolve = false; int m_arcLength = 0; double m_al_scale = 0; protected: FERigidSolverNew m_rigidSolver; // declare the parameter list DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioMix/FEActiveConstantSupply.h
.h
1,953
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 #include "FEActiveMomentumSupply.h" //----------------------------------------------------------------------------- // This class implements a constant active momentum supply class FEBIOMIX_API FEActiveConstantSupply : public FEActiveMomentumSupply { public: //! constructor FEActiveConstantSupply(FEModel* pfem); //! active momentum supply vec3d ActiveSupply(FEMaterialPoint& pt) override; //! Tangent of active momentum supply vec3d Tangent_ActiveSupply_Strain(FEMaterialPoint& mp) override; public: double m_asupp; //!< active momentum supply // declare parameter list DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEImgLib/ImageMap.cpp
.cpp
12,377
414
//#include "stdafx.h" #include "ImageMap.h" #include "math.h" #include "algorithm" #include "iostream" ImageMap::ImageMap(Image& img) : m_img(img) { m_r0 = vec3d(0,0,0); m_r1 = vec3d(0,0,0); } ImageMap::~ImageMap(void) { } void ImageMap::SetRange(vec3d r0, vec3d r1) { m_r0 = r0; m_r1 = r1; } ImageMap::POINT ImageMap::map(const vec3d& p) { int nx = m_img.width (); int ny = m_img.height(); int nz = m_img.depth (); double x = (p.x - m_r0.x)/(m_r1.x - m_r0.x); double y = (p.y - m_r0.y)/(m_r1.y - m_r0.y); double z = (nz==1?0:(p.z - m_r0.z)/(m_r1.z - m_r0.z)); double dx = 1.0 / (double) (nx - 1); double dy = 1.0 / (double) (ny - 1); double dz = (nz>1?1.0 / (double) (nz - 1):1.0); int i = (int) std::max(floor(x * (nx - 1)), 0.0); int j = (int) std::max(floor(y * (ny - 1)), 0.0); int k = (int) std::max(floor(z * (nz - 1)), 0.0); if (i == nx-1) i--; if (j == ny-1) j--; if ((k == nz-1)&&(nz>1)) k--; double r = (x - i*dx)/dx; double s = (y - j*dy)/dy; double t = (z - k*dz)/dz; POINT pt; pt.i = i; pt.j = j; pt.k = k; if (nz == 1) { pt.h[0] = (1-r)*(1-s); pt.h[1] = r*(1-s); pt.h[2] = r*s; pt.h[3] = s*(1-r); pt.h[4] = pt.h[5] = pt.h[6] = pt.h[7] = 0.0; } else { pt.h[0] = (1-r)*(1-s)*(1-t); pt.h[1] = r*(1-s)*(1-t); pt.h[2] = r*s*(1-t); pt.h[3] = s*(1-r)*(1-t); pt.h[4] = (1-r)*(1-s)*t; pt.h[5] = r*(1-s)*t; pt.h[6] = r*s*t; pt.h[7] = s*(1-r)*t; } return pt; } double ImageMap::value(const POINT& p) { int nx = m_img.width (); int ny = m_img.height(); int nz = m_img.depth (); if (nz == 1) { if ((p.i<0) || (p.i >= nx-1)) return 0.0; if ((p.j<0) || (p.j >= ny-1)) return 0.0; double v[4]; v[0] = m_img.value(p.i , p.j , 0); v[1] = m_img.value(p.i+1, p.j , 0); v[2] = m_img.value(p.i+1, p.j+1, 0); v[3] = m_img.value(p.i , p.j+1, 0); return (p.h[0]*v[0] + p.h[1]*v[1] + p.h[2]*v[2] + p.h[3]*v[3]); } else { if ((p.i<0) || (p.i >= nx-1)) return 0.0; if ((p.j<0) || (p.j >= ny-1)) return 0.0; if ((p.k<0) || (p.k >= nz-1)) return 0.0; double v[8]; v[0] = m_img.value(p.i , p.j , p.k ); v[1] = m_img.value(p.i+1, p.j , p.k ); v[2] = m_img.value(p.i+1, p.j+1, p.k ); v[3] = m_img.value(p.i , p.j+1, p.k ); v[4] = m_img.value(p.i , p.j , p.k+1); v[5] = m_img.value(p.i+1, p.j , p.k+1); v[6] = m_img.value(p.i+1, p.j+1, p.k+1); v[7] = m_img.value(p.i , p.j+1, p.k+1); return (p.h[0]*v[0] + p.h[1]*v[1] + p.h[2]*v[2] + p.h[3]*v[3] + p.h[4]*v[4] + p.h[5]*v[5] + p.h[6]*v[6] + p.h[7]*v[7]); } } bool ImageMap::valid(const vec3d& p) { int nz = m_img.depth(); bool r_valid = true; r_valid &= (p.x >= m_r0.x && p.x <= m_r1.x); r_valid &= (p.y >= m_r0.y && p.y <= m_r1.y); r_valid &= (nz == 1) ? true : (p.z >= m_r0.z && p.z <= m_r1.z); return r_valid; } vec3d ImageMap::gradient(const vec3d& r) { POINT p = map(r); if (m_img.depth() == 1) { // get the x-gradient values double gx[4]; gx[0] = grad_x(p.i , p.j , 0); gx[1] = grad_x(p.i+1, p.j , 0); gx[2] = grad_x(p.i+1, p.j+1, 0); gx[3] = grad_x(p.i , p.j+1, 0); // get the y-gradient values double gy[4]; gy[0] = grad_y(p.i , p.j , 0); gy[1] = grad_y(p.i+1, p.j , 0); gy[2] = grad_y(p.i+1, p.j+1, 0); gy[3] = grad_y(p.i , p.j+1, 0); // get the gradient at point r double hx = (p.h[0]*gx[0]+p.h[1]*gx[1]+p.h[2]*gx[2]+p.h[3]*gx[3]); double hy = (p.h[0]*gy[0]+p.h[1]*gy[1]+p.h[2]*gy[2]+p.h[3]*gy[3]); double Dx = dx(); double Dy = dy(); return vec3d(hx/Dx, hy/Dy, 0.0); } else { int nx = m_img.width(); int ny = m_img.height(); int nz = m_img.depth(); if ((p.i < 0) || (p.i >= nx - 1)) return vec3d(0,0,0); if ((p.j < 0) || (p.j >= ny - 1)) return vec3d(0,0,0); if ((p.k < 0) || (p.k >= nz - 1)) return vec3d(0,0,0); // get the x-gradient values double gx[8]; gx[0] = grad_x(p.i , p.j , p.k ); gx[1] = grad_x(p.i+1, p.j , p.k ); gx[2] = grad_x(p.i+1, p.j+1, p.k ); gx[3] = grad_x(p.i , p.j+1, p.k ); gx[4] = grad_x(p.i , p.j , p.k+1); gx[5] = grad_x(p.i+1, p.j , p.k+1); gx[6] = grad_x(p.i+1, p.j+1, p.k+1); gx[7] = grad_x(p.i , p.j+1, p.k+1); // get the y-gradient values double gy[8]; gy[0] = grad_y(p.i , p.j , p.k ); gy[1] = grad_y(p.i+1, p.j , p.k ); gy[2] = grad_y(p.i+1, p.j+1, p.k ); gy[3] = grad_y(p.i , p.j+1, p.k ); gy[4] = grad_y(p.i , p.j , p.k+1); gy[5] = grad_y(p.i+1, p.j , p.k+1); gy[6] = grad_y(p.i+1, p.j+1, p.k+1); gy[7] = grad_y(p.i , p.j+1, p.k+1); // get the z-gradient values double gz[8]; gz[0] = grad_z(p.i , p.j , p.k ); gz[1] = grad_z(p.i+1, p.j , p.k ); gz[2] = grad_z(p.i+1, p.j+1, p.k ); gz[3] = grad_z(p.i , p.j+1, p.k ); gz[4] = grad_z(p.i , p.j , p.k+1); gz[5] = grad_z(p.i+1, p.j , p.k+1); gz[6] = grad_z(p.i+1, p.j+1, p.k+1); gz[7] = grad_z(p.i , p.j+1, p.k+1); // get the gradient at point r double hx = (p.h[0]*gx[0]+p.h[1]*gx[1]+p.h[2]*gx[2]+p.h[3]*gx[3]+p.h[4]*gx[4]+p.h[5]*gx[5]+p.h[6]*gx[6]+p.h[7]*gx[7]); double hy = (p.h[0]*gy[0]+p.h[1]*gy[1]+p.h[2]*gy[2]+p.h[3]*gy[3]+p.h[4]*gy[4]+p.h[5]*gy[5]+p.h[6]*gy[6]+p.h[7]*gy[7]); double hz = (p.h[0]*gz[0]+p.h[1]*gz[1]+p.h[2]*gz[2]+p.h[3]*gz[3]+p.h[4]*gz[4]+p.h[5]*gz[5]+p.h[6]*gz[6]+p.h[7]*gz[7]); double Dx = dx(); double Dy = dy(); double Dz = dz(); return vec3d(hx/Dx, hy/Dy, hz/Dz); } } double ImageMap::grad_x(int i, int j, int k) { int nx = m_img.width(); if (i == 0 ) return m_img.value(i+1, j, k) - m_img.value(i , j, k); if (i == nx-1) return m_img.value(i , j, k) - m_img.value(i-1, j, k); return 0.5*(m_img.value(i+1, j, k) - m_img.value(i-1, j, k)); } double ImageMap::grad_y(int i, int j, int k) { int ny = m_img.height(); if (j == 0 ) return m_img.value(i, j+1, k) - m_img.value(i, j , k); if (j == ny-1) return m_img.value(i, j , k) - m_img.value(i, j-1, k); return 0.5*(m_img.value(i, j+1, k) - m_img.value(i, j-1, k)); } double ImageMap::grad_z(int i, int j, int k) { int nz = m_img.depth(); if (nz == 1) return 0.0; if (k == 0 ) return m_img.value(i, j, k+1) - m_img.value(i, j, k ); if (k == nz-1) return m_img.value(i, j, k ) - m_img.value(i, j, k-1); return 0.5*(m_img.value(i, j, k+1) - m_img.value(i, j, k-1)); } mat3ds ImageMap::hessian(const vec3d& r) { POINT p = map(r); if (m_img.depth() == 1) { // get the xx-hessian values double hxx[4]; hxx[0] = hessian_xx(p.i , p.j , 0); hxx[1] = hessian_xx(p.i+1, p.j , 0); hxx[2] = hessian_xx(p.i+1, p.j+1, 0); hxx[3] = hessian_xx(p.i , p.j+1, 0); // get the yy-hessian values double hyy[4]; hyy[0] = hessian_yy(p.i , p.j , 0); hyy[1] = hessian_yy(p.i+1, p.j , 0); hyy[2] = hessian_yy(p.i+1, p.j+1, 0); hyy[3] = hessian_yy(p.i , p.j+1, 0); // get the xy-hessian values double hxy[4]; hxy[0] = hessian_xy(p.i , p.j , 0); hxy[1] = hessian_xy(p.i+1, p.j , 0); hxy[2] = hessian_xy(p.i+1, p.j+1, 0); hxy[3] = hessian_xy(p.i , p.j+1, 0); // get the hessian at point r double Hxx = (p.h[0]*hxx[0]+p.h[1]*hxx[1]+p.h[2]*hxx[2]+p.h[3]*hxx[3]); double Hyy = (p.h[0]*hyy[0]+p.h[1]*hyy[1]+p.h[2]*hyy[2]+p.h[3]*hyy[3]); double Hxy = (p.h[0]*hxy[0]+p.h[1]*hxy[1]+p.h[2]*hxy[2]+p.h[3]*hxy[3]); double Dxx = dx()*dx(); double Dyy = dy()*dy(); double Dxy = dx()*dy(); return mat3ds(Hxx/Dxx, Hyy/Dyy, 0, Hxy/Dxy, 0.0, 0.0); } else { // get the xx-hessian values double hxx[8]; hxx[0] = hessian_xx(p.i , p.j , p.k); hxx[1] = hessian_xx(p.i+1, p.j , p.k); hxx[2] = hessian_xx(p.i+1, p.j+1, p.k); hxx[3] = hessian_xx(p.i , p.j+1, p.k); hxx[4] = hessian_xx(p.i , p.j , p.k+1); hxx[5] = hessian_xx(p.i+1, p.j , p.k+1); hxx[6] = hessian_xx(p.i+1, p.j+1, p.k+1); hxx[7] = hessian_xx(p.i , p.j+1, p.k+1); // get the yy-hessian values double hyy[8]; hyy[0] = hessian_yy(p.i , p.j , p.k); hyy[1] = hessian_yy(p.i+1, p.j , p.k); hyy[2] = hessian_yy(p.i+1, p.j+1, p.k); hyy[3] = hessian_yy(p.i , p.j+1, p.k); hyy[4] = hessian_yy(p.i , p.j , p.k+1); hyy[5] = hessian_yy(p.i+1, p.j , p.k+1); hyy[6] = hessian_yy(p.i+1, p.j+1, p.k+1); hyy[7] = hessian_yy(p.i , p.j+1, p.k+1); // get the zz-hessian values double hzz[8]; hzz[0] = hessian_zz(p.i , p.j , p.k); hzz[1] = hessian_zz(p.i+1, p.j , p.k); hzz[2] = hessian_zz(p.i+1, p.j+1, p.k); hzz[3] = hessian_zz(p.i , p.j+1, p.k); hzz[4] = hessian_zz(p.i , p.j , p.k+1); hzz[5] = hessian_zz(p.i+1, p.j , p.k+1); hzz[6] = hessian_zz(p.i+1, p.j+1, p.k+1); hzz[7] = hessian_zz(p.i , p.j+1, p.k+1); // get the xy-hessian values double hxy[8]; hxy[0] = hessian_xy(p.i , p.j , p.k); hxy[1] = hessian_xy(p.i+1, p.j , p.k); hxy[2] = hessian_xy(p.i+1, p.j+1, p.k); hxy[3] = hessian_xy(p.i , p.j+1, p.k); hxy[4] = hessian_xy(p.i , p.j , p.k+1); hxy[5] = hessian_xy(p.i+1, p.j , p.k+1); hxy[6] = hessian_xy(p.i+1, p.j+1, p.k+1); hxy[7] = hessian_xy(p.i , p.j+1, p.k+1); // get the yz-hessian values double hyz[8]; hyz[0] = hessian_yz(p.i , p.j , p.k); hyz[1] = hessian_yz(p.i+1, p.j , p.k); hyz[2] = hessian_yz(p.i+1, p.j+1, p.k); hyz[3] = hessian_yz(p.i , p.j+1, p.k); hyz[4] = hessian_yz(p.i , p.j , p.k+1); hyz[5] = hessian_yz(p.i+1, p.j , p.k+1); hyz[6] = hessian_yz(p.i+1, p.j+1, p.k+1); hyz[7] = hessian_yz(p.i , p.j+1, p.k+1); // get the xz-hessian values double hxz[8]; hxz[0] = hessian_xz(p.i , p.j , p.k); hxz[1] = hessian_xz(p.i+1, p.j , p.k); hxz[2] = hessian_xz(p.i+1, p.j+1, p.k); hxz[3] = hessian_xz(p.i , p.j+1, p.k); hxz[4] = hessian_xz(p.i , p.j , p.k+1); hxz[5] = hessian_xz(p.i+1, p.j , p.k+1); hxz[6] = hessian_xz(p.i+1, p.j+1, p.k+1); hxz[7] = hessian_xz(p.i , p.j+1, p.k+1); // get the hessian at point r double Hxx = (p.h[0]*hxx[0]+p.h[1]*hxx[1]+p.h[2]*hxx[2]+p.h[3]*hxx[3]+p.h[4]*hxx[4]+p.h[5]*hxx[5]+p.h[6]*hxx[6]+p.h[7]*hxx[7]); double Hyy = (p.h[0]*hyy[0]+p.h[1]*hyy[1]+p.h[2]*hyy[2]+p.h[3]*hyy[3]+p.h[4]*hyy[4]+p.h[5]*hyy[5]+p.h[6]*hyy[6]+p.h[7]*hyy[7]); double Hzz = (p.h[0]*hzz[0]+p.h[1]*hzz[1]+p.h[2]*hzz[2]+p.h[3]*hzz[3]+p.h[4]*hzz[4]+p.h[5]*hzz[5]+p.h[6]*hzz[6]+p.h[7]*hzz[7]); double Hxy = (p.h[0]*hxy[0]+p.h[1]*hxy[1]+p.h[2]*hxy[2]+p.h[3]*hxy[3]+p.h[4]*hxy[4]+p.h[5]*hxy[5]+p.h[6]*hxy[6]+p.h[7]*hxy[7]); double Hyz = (p.h[0]*hyz[0]+p.h[1]*hyz[1]+p.h[2]*hyz[2]+p.h[3]*hyz[3]+p.h[4]*hyz[4]+p.h[5]*hyz[5]+p.h[6]*hyz[6]+p.h[7]*hyz[7]); double Hxz = (p.h[0]*hxz[0]+p.h[1]*hxz[1]+p.h[2]*hxz[2]+p.h[3]*hxz[3]+p.h[4]*hxz[4]+p.h[5]*hxz[5]+p.h[6]*hxz[6]+p.h[7]*hxz[7]); double Dxx = dx()*dx(); double Dyy = dy()*dy(); double Dzz = dz()*dz(); double Dxy = dx()*dy(); double Dyz = dy()*dz(); double Dxz = dx()*dz(); return mat3ds(Hxx/Dxx, Hyy/Dyy, Hzz/Dzz, Hxy/Dxy, Hyz/Dyz, Hxz/Dxz); } } double ImageMap::hessian_xx(int i, int j, int k) { int nx = m_img.width(); if (nx <= 2) return 0.0; if (i==0 ) return (grad_x(i+1,j,k) - grad_x(i ,j,k)); if (i==nx-1) return (grad_x(i ,j,k) - grad_x(i-1,j,k)); return 0.5*(grad_x(i+1,j,k) - grad_x(i-1,j,k)); } double ImageMap::hessian_yy(int i, int j, int k) { int ny = m_img.height(); if (ny <= 2) return 0.0; if (j==0 ) return (grad_y(i,j+1,k) - grad_y(i ,j,k)); if (j==ny-1) return (grad_y(i ,j,k) - grad_y(i,j-1,k)); return 0.5*(grad_y(i,j+1,k) - grad_y(i,j-1,k)); } double ImageMap::hessian_zz(int i, int j, int k) { int nz = m_img.depth(); if (nz <= 2) return 0.0; if (k==0 ) return (grad_z(i,j,k+1) - grad_z(i ,j,k)); if (k==nz-1) return (grad_z(i ,j,k) - grad_z(i,j,k-1)); return 0.5*(grad_z(i,j,k+1) - grad_z(i,j,k-1)); } double ImageMap::hessian_xy(int i, int j, int k) { int nx = m_img.width(); if (nx <= 2) return 0.0; if (i==0 ) return (grad_y(i+1,j,k) - grad_y(i ,j,k)); if (i==nx-1) return (grad_y(i ,j,k) - grad_y(i-1,j,k)); return 0.5*(grad_y(i+1,j,k) - grad_y(i-1,j,k)); } double ImageMap::hessian_yz(int i, int j, int k) { int ny = m_img.height(); if (ny <= 2) return 0.0; if (j==0 ) return (grad_z(i,j+1,k) - grad_z(i ,j,k)); if (j==ny-1) return (grad_z(i ,j,k) - grad_z(i,j-1,k)); return 0.5*(grad_z(i,j+1,k) - grad_z(i,j-1,k)); } double ImageMap::hessian_xz(int i, int j, int k) { int nx = m_img.width(); if (nx <= 2) return 0.0; if (i==0 ) return (grad_z(i+1,j,k) - grad_z(i ,j,k)); if (i==nx-1) return (grad_z(i ,j,k) - grad_z(i-1,j,k)); return 0.5*(grad_z(i+1,j,k) - grad_z(i-1,j,k)); }
C++
3D
febiosoftware/FEBio
FEImgLib/FEImageValuator.h
.h
1,797
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.*/ #pragma once #include <FECore/FEScalarValuator.h> #include <FECore/FEFunction1D.h> #include "FEImageSource.h" #include "ImageMap.h" #include "feimglib_api.h" class FEIMGLIB_API FEImageValuator : public FEScalarValuator { public: FEImageValuator(FEModel* fem); bool Init() override; double operator()(const FEMaterialPoint& pt) override; FEScalarValuator* copy() override; private: vec3d m_r0, m_r1; FEImageSource* m_imSrc; FEFunction1D* m_transform; Image m_im; ImageMap m_map; DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEImgLib/FEImageSource.h
.h
2,663
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 "Image.h" #include <FECore/FECoreClass.h> #include "feimglib_api.h" //--------------------------------------------------------------------------- // Base class for image sources. class FEIMGLIB_API FEImageSource : public FECoreClass { FECORE_BASE_CLASS(FEImageSource) public: FEImageSource(FEModel* fem); virtual bool GetImage3D(Image& im) = 0; std::string GetFileName() { return m_file; } protected: std::string m_file; }; //--------------------------------------------------------------------------- // Class for reading raw images class FEIMGLIB_API FERawImage : public FEImageSource { public: FERawImage(FEModel* fem); bool GetImage3D(Image& im) override; private: // load raw data from file bool Load(const char* szfile, Image& im, Image::ImageFormat fmt, bool endianess = false); protected: int m_dim[3]; int m_format; bool m_bend; DECLARE_FECORE_CLASS(); }; //--------------------------------------------------------------------------- // Class for reading NRRD images class FEIMGLIB_API FENRRDImage : public FEImageSource { enum NRRD_TYPE { NRRD_INVALID, NRRD_FLOAT }; enum NRRD_ENCODING { NRRD_RAW, NRRD_ASCII }; public: FENRRDImage(FEModel* fem); bool GetImage3D(Image& im) override; private: // load image data from file bool Load(const char* szfile, Image& im); private: DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEImgLib/FEImageDataMap.cpp
.cpp
2,901
102
/*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 "FEImageDataMap.h" #include <FECore/FEDomainMap.h> #include <FECore/FEMesh.h> #include "image_tools.h" BEGIN_FECORE_CLASS(FEImageDataMap, FEElemDataGenerator) ADD_PARAMETER(m_r0, "range_min"); ADD_PARAMETER(m_r1, "range_max"); ADD_PARAMETER(m_blur, "blur"); ADD_PROPERTY(m_imgSrc, "image"); END_FECORE_CLASS(); FEImageDataMap::FEImageDataMap(FEModel* fem) : FEElemDataGenerator(fem), m_map(m_im) { m_imgSrc = nullptr; m_blur = 0.0; m_data = nullptr; } bool FEImageDataMap::Init() { if (m_imgSrc == nullptr) return false; if (m_imgSrc->GetImage3D(m_im0) == false) { return false; } m_im = m_im0; m_map.SetRange(m_r0, m_r1); return FEElemDataGenerator::Init(); } FEDataMap* FEImageDataMap::Generate() { FEElementSet* elset = GetElementSet(); if (elset == nullptr) return nullptr; // TODO: Can I use FMT_NODE? if (m_data == nullptr) m_data = new FEDomainMap(FEDataType::FE_DOUBLE, Storage_Fmt::FMT_MULT); m_data->Create(elset); GenerateData(); return m_data; } void FEImageDataMap::GenerateData() { assert(m_data); FEElementSet& set = *GetElementSet(); FEMesh& mesh = *set.GetMesh(); int N = set.Elements(); for (int i = 0; i < N; ++i) { FEElement& el = set.Element(i); int ne = el.Nodes(); for (int j = 0; j < ne; ++j) { vec3d ri = mesh.Node(el.m_node[j]).m_r0; double d = m_map.value(m_map.map(ri)); m_data->setValue(i, j, d); } } } void FEImageDataMap::Evaluate(double time) { if (m_blur > 0) { if (m_im0.depth() == 1) blur_image_2d(m_im, m_im0, (float)m_blur); else blur_image_3d(m_im, m_im0, (float)m_blur); } else m_im = m_im0; GenerateData(); }
C++
3D
febiosoftware/FEBio
FEImgLib/FEImageSource.cpp
.cpp
6,360
250
/*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 "FEImageSource.h" #include <FECore/log.h> FEImageSource::FEImageSource(FEModel* fem) : FECoreClass(fem) { } //======================================================================== BEGIN_FECORE_CLASS(FERawImage, FEImageSource) ADD_PARAMETER(m_file, "file", FE_PARAM_ATTRIBUTE); ADD_PARAMETER(m_format, "format", 0, "RAW8\0RAW16U\0"); ADD_PARAMETER(m_dim, 3, "size"); ADD_PARAMETER(m_bend, "endianess"); END_FECORE_CLASS(); FERawImage::FERawImage(FEModel* fem) : FEImageSource(fem) { m_dim[0] = m_dim[1] = m_dim[2] = 0; m_bend = false; m_format = 0; } bool FERawImage::GetImage3D(Image& im) { // get the file name const char* szfile = m_file.c_str(); int* n = m_dim; im.Create(n[0], n[1], n[2]); // Try to load the image file Image::ImageFormat fmt; switch (m_format) { case 0: fmt = Image::RAW8; break; case 1: fmt = Image::RAW16U; break; default: assert(false); return false; } return Load(szfile, im, fmt, m_bend); } //----------------------------------------------------------------------------- bool FERawImage::Load(const char* szfile, Image& im, Image::ImageFormat fmt, bool endianess) { // check the format int m = -1; switch (fmt) { case Image::RAW8: m = 1; break; case Image::RAW16U: m = 2; break; default: return false; break; } // open the file FILE* fp = fopen(szfile, "rb"); if (fp == 0) return false; // read the data int nx = im.width(); int ny = im.height(); int nz = im.depth(); int voxels = nx * ny * nz; int nsize = voxels * m; unsigned char* pb = new unsigned char[nsize]; fread(pb, nsize, 1, fp); float* pf = im.data(); if (fmt == Image::RAW8) { for (int k = 0; k < nz; ++k) for (int j = 0; j < ny; ++j) for (int i = 0; i < nx; ++i) { float f = (float)pb[(k * ny + j) * nx + i] / 255.f; pf[(k * ny + (ny - j - 1)) * nx + i] = f; } } else if (fmt == Image::RAW16U) { for (int k = 0; k < nz; ++k) for (int j = 0; j < ny; ++j) for (int i = 0; i < nx; ++i) { unsigned char* d = pb + 2 * ((k * ny + j) * nx + i); unsigned short n = *((unsigned short*)d); if (endianess) { unsigned int n1 = (unsigned int)d[0]; unsigned int n2 = (unsigned int)d[1]; n = (n1 << 8) + n2; } float f = (float)n / 65535.f; pf[(k * ny + (ny - j - 1)) * nx + i] = f; } } // all done delete[] pb; fclose(fp); return true; } //============================================================================= BEGIN_FECORE_CLASS(FENRRDImage, FEImageSource) ADD_PARAMETER(m_file, "file"); END_FECORE_CLASS(); FENRRDImage::FENRRDImage(FEModel* fem) : FEImageSource(fem) { } bool FENRRDImage::GetImage3D(Image& im) { if (m_file.empty()) return false; const char* szfile = m_file.c_str(); return Load(szfile, im); } bool nrrd_read_line(FILE* fp, char* buf) { char c; while (fread(&c, 1, 1, fp)) { if ((c != '\r') && (c != '\n')) *buf++ = c; if (c == '\n') { *buf = 0; return true; } } return false; } bool nrrd_read_key_value(const char* szline, char* key, char* val) { const char* c = szline; char* d = key; bool skip_space = true; while (*c) { if (*c == ':') { *d = 0; d = val; skip_space = true; } else if (skip_space) { if (isspace(*c) == 0) { *d++ = *c; skip_space = false; } } else *d++ = *c; c++; } *d = 0; return true; } bool FENRRDImage::Load(const char* szfile, Image& im) { if (szfile == nullptr) return false; FILE* fp = fopen(szfile, "rb"); if (fp == nullptr) return false; // read the header char buf[1024] = { 0 }, key[256] = { 0 }, val[256] = { 0 }; nrrd_read_line(fp, buf); if (strncmp(buf, "NRRD", 4) != 0) { fclose(fp); return false; } NRRD_TYPE imType = NRRD_INVALID; int dim = 0; int sizes[3] = { 0 }; NRRD_ENCODING enc = NRRD_RAW; while (nrrd_read_line(fp, buf)) { if (buf[0] == 0) break; // read key-value if (buf[0] != '#') { if (nrrd_read_key_value(buf, key, val) == false) { fclose(fp); return false; } if (strcmp(key, "type") == 0) { if (strcmp(val, "float") == 0) imType = NRRD_FLOAT; } else if (strcmp(key, "dimension") == 0) dim = atoi(val); else if (strcmp(key, "sizes") == 0) sscanf(val, "%d %d %d", sizes, sizes + 1, sizes + 2); else if (strcmp(key, "encoding") == 0) { if (strcmp(val, "raw") == 0) enc = NRRD_RAW; if (strcmp(val, "ascii") == 0) enc = NRRD_ASCII; } } } // read the image if (imType != NRRD_FLOAT) { feLog("Invalid image format (only float supported)"); fclose(fp); return false; } if (dim != 3) { feLog("Invalid image dimensions (must be 3)"); fclose(fp); return false; } if (enc != NRRD_RAW) { feLog("Invalid encoding (only raw supported)"); fclose(fp); return false; } int nsize = sizes[0] * sizes[1] * sizes[2]; if (nsize <= 0) { feLog("Invalid image sizes"); fclose(fp); return false; } im.Create(sizes[0], sizes[1], sizes[2]); float* pf = im.data(); int nread = fread(pf, sizeof(float), nsize, fp); if (nread != nsize) { feLog("Failed reading image data"); fclose(fp); return false; } fclose(fp); return true; }
C++
3D
febiosoftware/FEBio
FEImgLib/ImageFilter.cpp
.cpp
6,787
261
#include "Image.h" #include "ImageFilter.h" #include <FECore/log.h> #include <vector> #include "image_tools.h" #ifdef HAVE_FFTW #include <fftw3.h> #endif // HAVE_FFTW ImageFilter::ImageFilter(FEModel* fem) : FECoreClass(fem) { } //================================================================================================= // IterativeBlur //================================================================================================= BEGIN_FECORE_CLASS(IterativeBlur, ImageFilter) ADD_PARAMETER(m_blur, "blur"); ADD_PARAMETER(m_norm_flag, "normalize_values"); END_FECORE_CLASS(); IterativeBlur::IterativeBlur(FEModel* fem) : ImageFilter(fem) { m_blur = 0.0; m_norm_flag = false; } bool IterativeBlur::Init() { return true; } //sequential 1D approach void IterativeBlur::Update(Image& trg, Image& src) { if (m_blur <= 0) { trg = src; return; } feLog("Blurring images, blur factor %lg\n", m_blur); int K = (int)m_blur; float w = float(m_blur) - (float)K; int nx = src.width(); int ny = src.height(); int nz = src.depth(); trg = src; Image tmp(src); for (int k = 0; k < K; ++k) { for (int m = 0; m < 3; ++m) { #ifdef NDEBUG #pragma omp parallel for #endif for (int z = 0; z < nz; ++z) for (int y = 0; y < ny; ++y) for (int x = 0; x < nx; ++x) { int m_pos[] = { x, y, z }; int m_range[] = { nx, ny, nz }; trg.value(x, y, z) = Apply(tmp, m_pos, m_range, m); } tmp = trg; } } if (w > 0.0) { for (int m = 0; m < 3; ++m) { #ifdef NDEBUG #pragma omp parallel for #endif for (int z = 0; z < nz; ++z) for (int y = 0; y < ny; ++y) for (int x = 0; x < nx; ++x) { int m_pos[] = { x, y, z }; int m_range[] = { nx, ny, nz }; float f1 = Apply(tmp, m_pos, m_range, m); float f2 = trg.value(x, y, z); trg.value(x, y, z) = Apply(tmp, m_pos, m_range, m); trg.value(x, y, z) = f1 * w + f2 * (1.f - w); } tmp = trg; } } } float IterativeBlur::Apply(Image& img, int m_pos[3], int m_range[3], int m_dir) { int x = m_pos[0]; int y = m_pos[1]; int z = m_pos[2]; int nx = m_range[0]; int ny = m_range[1]; int nz = m_range[2]; float f = 0.0; if (x > 0) f += img.value(x - 1, y, z); else f += img.value(x, y, z); if (x < nx - 1) f += img.value(x + 1, y, z); else f += img.value(x, y, z); if (y > 0) f += img.value(x, y - 1, z); else f += img.value(x, y, z); if (y < ny - 1) f += img.value(x, y + 1, z); else f += img.value(x, y, z); if (z > 0) f += img.value(x, y, z - 1); else f += img.value(x, y, z); if (z < nz - 1) f += img.value(x, y, z + 1); else f += img.value(x, y, z); return float(0.1666667f) * f; } //================================================================================================= // BoxBlur //================================================================================================= BEGIN_FECORE_CLASS(BoxBlur, ImageFilter) ADD_PARAMETER(m_blur, "blur"); // blur radius ADD_PARAMETER(m_K, "iterations"); ADD_PARAMETER(m_norm_flag, "normalize_values"); ADD_PARAMETER(m_res, 3, "voxel_resolution"); END_FECORE_CLASS(); BoxBlur::BoxBlur(FEModel* fem) : ImageFilter(fem) { m_blur = 0.0; m_K = 0; m_norm_flag = false; m_res[0] = 1.0; m_res[1] = 1.0; m_res[2] = 1.0; m_ri[0] = 1; m_ri[1] = 1; m_ri[2] = 1; m_rp = 0.0; m_tp = -1.0; } bool BoxBlur::Init() { return true; } void BoxBlur::Update(Image& trg, Image& src) { if (m_blur < 1) { trg = src; return; } // approximate gaussian blur from https://www.ipol.im/pub/art/2013/87/?utm_source=doi double r_eff = (int)floor(0.5 * sqrt(((12.0 * m_blur * m_blur / m_K) + 1.0))); double sigma_i[3] = { 0.0, 0.0, 0.0 }; for (int i = 0; i < 3; ++i) { sigma_i[i] = m_blur / m_res[i]; // (units of px) m_ri[i] = (int)floor(0.5 * sqrt(((12.0 * sigma_i[i] * sigma_i[i] / m_K) + 1.0))); } feLog("Blurring images\n"); feLog("blur radius = %lg px, rx = %d px, ry = %d px, rz = %d px,\n", r_eff, m_ri[0], m_ri[1], m_ri[2]); feLog("blur std = %lg, stdx = %lg, stdy = %lg, stdz = %lg\n", m_blur, sigma_i[0], sigma_i[1], sigma_i[2]); int nx = src.width(); int ny = src.height(); int nz = src.depth(); trg = src; Image tmp(src); // for each iteration for (int k = 0; k < m_K; ++k) { // perform 1D blur along each dimension for (int m = 0; m < 3; ++m) { #ifdef NDEBUG #pragma omp parallel for #endif for (int z = 0; z < nz; ++z) for (int y = 0; y < ny; ++y) for (int x = 0; x < nx; ++x) { int m_pos[] = { x, y, z }; int m_range[] = { nx, ny, nz }; trg.value(x, y, z) = Apply(tmp, m_pos, m_range, m); } tmp = trg; } } } float BoxBlur::Apply(Image& img, int m_pos[3], int m_range[3], int m_dir) { //naive implementation int x = m_pos[0]; int y = m_pos[1]; int z = m_pos[2]; int nx = m_range[0]; int ny = m_range[1]; int nz = m_range[2]; float f = 0.0; switch (m_dir) { case 0: { for (int i_r = -m_ri[0]; i_r <= m_ri[0]; ++i_r) { int xr = symmetric_extension(x + i_r, nx); f += img.value(xr, y, z); } f /= (2.f * m_ri[0] + 1.f); break; } case 1: { for (int i_r = -m_ri[1]; i_r <= m_ri[1]; ++i_r) { int yr = symmetric_extension(y + i_r, ny); f += img.value(x, yr, z); } f /= (2.f * m_ri[1] + 1.f); break; } case 2: { for (int i_r = -m_ri[2]; i_r <= m_ri[2]; ++i_r) { int zr = symmetric_extension(z + i_r, nz); f += img.value(x, y, zr); } f /= (2.f * m_ri[2] + 1.f); break; } } return f; } //================================================================================================= // Fastest Fourier Transform in the West (FFTW) Blur //================================================================================================= #ifdef HAVE_FFTW BEGIN_FECORE_CLASS(FFTWBlur, ImageFilter) ADD_PARAMETER(m_blur, "blur"); ADD_PARAMETER(m_norm_flag, "normalize_values"); ADD_PARAMETER(m_res, 3, "voxel_resolution"); END_FECORE_CLASS(); FFTWBlur::FFTWBlur(FEModel* fem) : ImageFilter(fem) { m_blur = 0.0; m_norm_flag = false; m_res[0] = 1.0; m_res[1] = 1.0; m_res[2] = 1.0; m_sigma[0] = 1.0; m_sigma[1] = 1.0; m_sigma[2] = 1.0; } bool FFTWBlur::Init() { return true; } void FFTWBlur::Update(Image& trg, Image& src) { if (m_blur < 1) { trg = src; return; } // scale blur in each direction for voxel resolution for (int i = 0; i < 3; ++i) m_sigma[i] = m_blur / m_res[i]; // (units of px) feLog("Blurring images\n"); feLog("blur std = %lg, stdx = %lg, stdy = %lg, stdz = %lg\n", m_blur, m_sigma[0], m_sigma[1], m_sigma[2]); float d[3] = { float(m_sigma[0]), float(m_sigma[1]), float(m_sigma[2]) }; fftw_blur_3d(trg, src, d); } // SL: Does nothing for now. float FFTWBlur::Apply(Image& img, int m_pos[3], int m_range[3], int m_dir) { return 0.f; } #endif // HAVE_FFTW
C++
3D
febiosoftware/FEBio
FEImgLib/image_tools.h
.h
941
29
#pragma once #include <FECore/FECoreClass.h> #include "feimglib_api.h" class Image; // iterative stencil-based blur enum class BlurMethod { BLUR_AVERAGE, BLUR_FFT, }; FEIMGLIB_API void blur_image_2d(Image& trg, Image& src, float d, BlurMethod blurMethod = BlurMethod::BLUR_AVERAGE); FEIMGLIB_API void blur_image_3d(Image& trg, Image& src, float d, BlurMethod blurMethod = BlurMethod::BLUR_AVERAGE); // FFT-based blurs (rely on MKL library. Incompatible with pardiso/dss) FEIMGLIB_API void fftblur_2d(Image& trg, Image& src, float d); FEIMGLIB_API void fftblur_3d(Image& trg, Image& src, float d); // FFT-based blurs (rely on FFTW library) FEIMGLIB_API void fftw_blur_2d(Image& trg, Image& src, float sigma[2]); FEIMGLIB_API void fftw_blur_3d(Image& trg, Image& src, float sigma[3]); // Extension functions for image filter edges FEIMGLIB_API int constant_extension(int N, int n); FEIMGLIB_API int symmetric_extension(int N, int n);
Unknown
3D
febiosoftware/FEBio
FEImgLib/Image.h
.h
2,446
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.*/ #pragma once #include "feimglib_api.h" //----------------------------------------------------------------------------- // This class implements a simple single precision grayscale 3D-image class FEIMGLIB_API Image { public: enum ImageFormat { RAW8, RAW16U }; public: // constructor Image(void); // destructor ~Image(void); //! copy constructor Image(Image& im); //! assignment operator Image& operator = (Image& im); // allocate storage for image data void Create(int nx, int ny, int nz); // return size attributes int width () { return m_nx; } int height() { return m_ny; } int depth () { return m_nz; } // get a particular data value float& value(int x, int y, int z) { return m_pf[(z*m_ny + (m_ny-y-1))*m_nx+x]; } // zero image data void zero(); // get the data pointer float* data(); protected: float* m_pf; // image data int m_nx, m_ny, m_nz; // image dimensions }; //----------------------------------------------------------------------------- // helper functions for calculating image derivatives void image_derive_x(Image& s, Image& d); void image_derive_y(Image& s, Image& d); void image_derive_z(Image& s, Image& d);
Unknown
3D
febiosoftware/FEBio
FEImgLib/Image.cpp
.cpp
4,101
135
/*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 "Image.h" #include <memory.h> //----------------------------------------------------------------------------- Image::Image(void) { m_pf = 0; m_nx = m_ny = m_nz = 0; } //----------------------------------------------------------------------------- Image::~Image(void) { delete [] m_pf; m_pf = 0; } //----------------------------------------------------------------------------- void Image::Create(int nx, int ny, int nz) { if (m_pf) delete [] m_pf; m_nx = nx; m_ny = ny; m_nz = nz; m_pf = new float[m_nx*m_ny*m_nz]; } //----------------------------------------------------------------------------- Image::Image(Image& im) { m_pf = 0; Create(im.width(), im.height(), im.depth()); memcpy(m_pf, im.m_pf, m_nx*m_ny*m_nz*sizeof(float)); } //----------------------------------------------------------------------------- Image& Image::operator = (Image& im) { if ((m_nx != im.m_nx)||(m_ny != im.m_ny)||(m_nz != im.m_nz)) Create(im.width(), im.height(), im.depth()); memcpy(m_pf, im.m_pf, m_nx*m_ny*m_nz*sizeof(float)); return (*this); } //----------------------------------------------------------------------------- void Image::zero() { int n = m_nx*m_ny*m_nz; for (int i=0; i<n; ++i) m_pf[i] = 0.f; } //----------------------------------------------------------------------------- float* Image::data() { return m_pf; } //----------------------------------------------------------------------------- void image_derive_x(Image& s, Image& d) { int nx = s.width(); int ny = s.height(); int nz = s.depth(); for (int k=0; k<nz; ++k) { for (int j=0; j<ny; ++j) { d.value(0, j, k) = s.value(1, j, k) - s.value(0, j, k); for (int i=1; i<nx-1; ++i) d.value(i, j, k) = (s.value(i+1, j, k) - s.value(i-1, j, k))*0.5f; d.value(nx-1, j, k) = s.value(nx-1, j, k) - s.value(nx-2, j, k); } } } //----------------------------------------------------------------------------- void image_derive_y(Image& s, Image& d) { int nx = s.width(); int ny = s.height(); int nz = s.depth(); for (int k=0; k<nz; ++k) { for (int i=0; i<nx; ++i) { d.value(i, 0, k) = s.value(i, 1, k) - s.value(i, 0, k); for (int j=1; j<ny-1; ++j) d.value(i, j, k) = (s.value(i, j+1, k) - s.value(i, j-1, k)) *0.5f; d.value(i, ny-1, k) = s.value(i, ny-1, k) - s.value(i, ny-2, k); } } } //----------------------------------------------------------------------------- void image_derive_z(Image& s, Image& d) { int nx = s.width(); int ny = s.height(); int nz = s.depth(); if (nz == 1) { d.zero(); return; } for (int j=0; j<ny; ++j) { for (int i=0; i<nx; ++i) { d.value(i, j, 0) = s.value(i, j, 1) - s.value(i, j, 0); for (int k=1; k<nz-1; ++k) d.value(i, j, k) = (s.value(i, j, k+1) - s.value(i, j, k-1)) *0.5f; d.value(i, j, nz-1) = s.value(i, j, nz-1) - s.value(i, j, nz-2); } } }
C++
3D
febiosoftware/FEBio
FEImgLib/image_tools.cpp
.cpp
13,033
467
#include "image_tools.h" #include "Image.h" #include <math.h> #include <iostream> #ifdef HAVE_MKL #include <mkl.h> #endif #ifdef HAVE_FFTW #include <fftw3.h> #endif // HAVE_FFTW void blur_avg_2d(Image& trg, Image& src, float d) { if (d <= 0) { trg = src; return; } int n = (int)d; float w = d - (float)n; int nx = src.width(); int ny = src.height(); int nz = src.depth(); trg = src; Image tmp(src); float f[4]; for (int l = 0; l < n; ++l) { #ifdef NDEBUG #pragma omp parallel for #endif for (int k = 0; k < nz; ++k) for (int j = 0; j < ny; ++j) for (int i = 0; i < nx; ++i) { if (i > 0) f[0] = tmp.value(i - 1, j, k); else f[0] = tmp.value(i, j, k); if (i < nx - 1) f[1] = tmp.value(i + 1, j, k); else f[1] = tmp.value(i, j, k); if (j > 0) f[2] = tmp.value(i, j - 1, k); else f[2] = tmp.value(i, j, k); if (j < ny - 1) f[3] = tmp.value(i, j + 1, k); else f[3] = tmp.value(i, j, k); trg.value(i, j, k) = 0.25f * (f[0] + f[1] + f[2] + f[3]); } tmp = trg; } if (w > 0.0) { #ifdef NDEBUG #pragma omp parallel for #endif for (int k = 0; k < nz; ++k) for (int j = 0; j < ny; ++j) for (int i = 0; i < nx; ++i) { if (i > 0) f[0] = tmp.value(i - 1, j, k); else f[0] = tmp.value(i, j, k); if (i < nx - 1) f[1] = tmp.value(i + 1, j, k); else f[1] = tmp.value(i, j, k); if (j > 0) f[2] = tmp.value(i, j - 1, k); else f[2] = tmp.value(i, j, k); if (j < ny - 1) f[3] = tmp.value(i, j + 1, k); else f[3] = tmp.value(i, j, k); float f1 = 0.25f * (f[0] + f[1] + f[2] + f[3]); float f2 = trg.value(i, j, k); trg.value(i, j, k) = f1 * w + f2 * (1.f - w); } } } void blur_avg_3d(Image& trg, Image& src, float d) { if (d <= 0) { trg = src; return; } int n = (int)d; float w = d - (float)n; int nx = src.width(); int ny = src.height(); int nz = src.depth(); trg = src; Image tmp(src); float f[6]; for (int l = 0; l < n; ++l) { #ifdef NDEBUG #pragma omp parallel for #endif for (int k = 0; k < nz; ++k) for (int j = 0; j < ny; ++j) for (int i = 0; i < nx; ++i) { if (i > 0) f[0] = tmp.value(i - 1, j, k); else f[0] = tmp.value(i, j, k); if (i < nx - 1) f[1] = tmp.value(i + 1, j, k); else f[1] = tmp.value(i, j, k); if (j > 0) f[2] = tmp.value(i, j - 1, k); else f[2] = tmp.value(i, j, k); if (j < ny - 1) f[3] = tmp.value(i, j + 1, k); else f[3] = tmp.value(i, j, k); if (k > 0) f[4] = tmp.value(i, j, k - 1); else f[4] = tmp.value(i, j, k); if (k < nz - 1) f[5] = tmp.value(i, j, k + 1); else f[5] = tmp.value(i, j, k); trg.value(i, j, k) = 0.1666667f * (f[0] + f[1] + f[2] + f[3] + f[4] + f[5]); } tmp = trg; } if (w > 0.0) { #ifdef NDEBUG #pragma omp parallel for #endif for (int k = 0; k < nz; ++k) for (int j = 0; j < ny; ++j) for (int i = 0; i < nx; ++i) { if (i > 0) f[0] = tmp.value(i - 1, j, k); else f[0] = tmp.value(i, j, k); if (i < nx - 1) f[1] = tmp.value(i + 1, j, k); else f[1] = tmp.value(i, j, k); if (j > 0) f[2] = tmp.value(i, j - 1, k); else f[2] = tmp.value(i, j, k); if (j < ny - 1) f[3] = tmp.value(i, j + 1, k); else f[3] = tmp.value(i, j, k); if (k > 0) f[4] = tmp.value(i, j, k - 1); else f[4] = tmp.value(i, j, k); if (k < nz - 1) f[5] = tmp.value(i, j, k + 1); else f[5] = tmp.value(i, j, k); float f1 = 0.1666667f * (f[0] + f[1] + f[2] + f[3] + f[4] + f[5]); float f2 = trg.value(i, j, k); trg.value(i, j, k) = f1 * w + f2 * (1.f - w); } } } //----------------------------------------------------------------------------- // FFT-based blurs (rely on MKL library. Incompatible with pardiso/dss) #ifdef HAVE_MKL // in fft.cpp bool mkl_dft2(int nx, int ny, float* x, MKL_Complex8* c); bool mkl_idft2(int nx, int ny, MKL_Complex8* c, float* y); FEIMGLIB_API void mkl_blur_2d(Image& trg, Image& src, float d) { int nx = src.width(); int ny = src.height(); float* x = src.data(); float* y = trg.data(); // for zero blur radius, we just copy the image if (d <= 0.f) { for (int i = 0; i < nx * ny; ++i) y[i] = x[i]; return; } // since the blurring is done in Fourier space, // we need to invert the blur radius float sigmax = nx / d; float sigmay = ny / d; // calculate the DFT MKL_Complex8* c = new MKL_Complex8[nx * ny]; mkl_dft2(nx, ny, x, c); // multiply the DFT with blur mask for (int j = 0; j <= ny / 2; ++j) for (int i = 0; i < nx; ++i) { double wx = (i < nx / 2 ? i : i - nx) / sigmax; double wy = j / sigmay; float v = (float)exp(-(wx * wx + wy * wy)); c[j * nx + i].real *= v; c[j * nx + i].imag *= v; } // calculate the inverse DFT mkl_idft2(nx, ny, c, y); // clean up delete[] c; } // in fft.cpp bool mkl_dft3(int nx, int ny, int nz, float* x, MKL_Complex8* c); bool mkl_idft3(int nx, int ny, int nz, MKL_Complex8* c, float* y); FEIMGLIB_API void mkl_blur_3d(Image& trg, Image& src, float d) { int nx = src.width(); int ny = src.height(); int nz = src.depth(); float* x = src.data(); float* y = trg.data(); // for zero blur radius, we just copy the image // SL: Why not copy i.e. if (d <= 0) { trg = src; return; }? if (d <= 0.f) { for (int i = 0; i < nx * ny * nz; ++i) y[i] = x[i]; return; } // since the blurring is done in Fourier space, // we need to invert the blur radius float sigmax = nx / d; float sigmay = ny / d; float sigmaz = nz / d; // calculate the DFT MKL_Complex8* c = new MKL_Complex8[nx * ny * nz]; mkl_dft3(nx, ny, nz, x, c); // multiply the DFT with blur mask for (int k = 0; k <= nz / 2; ++k) for (int j = 0; j < ny; ++j) for (int i = 0; i < nx; ++i) { double wx = (i < nx / 2 ? i : i - nx) / sigmax; double wy = (j < ny / 2 ? j : j - ny) / sigmay; double wz = k / sigmaz; float v = (float)exp(-(wx * wx + wy * wy + wz * wz)); c[k * nx * ny + j * nx + i].real *= v; c[k * nx * ny + j * nx + i].imag *= v; } // calculate the inverse DFT mkl_idft3(nx, ny, nz, c, y); // clean up delete[] c; } #else // HAVE_MKL void mkl_blur_2d(Image& trg, Image& src, float d) {} void mkl_blur_3d(Image& trg, Image& src, float d) {} #endif // HAVE_MKL //----------------------------------------------------------------------------- // FFT-based blurs (rely on FFTW library) #ifdef HAVE_FFTW void create_gaussian_2d(double* kernel, int rows, int cols, float sigma[2]) { double sum = 0.0; for (int y = 0; y < rows; ++y) { int dy = (y <= rows / 2) ? y : (rows - y); // wrap-around distance for (int x = 0; x < cols; ++x) { int dx = (x <= cols / 2) ? x : (cols - x); double gx = (double)(dx * dx / (sigma[0] * sigma[0])); double gy = (double)(dy * dy / (sigma[1] * sigma[1])); double g = exp(-0.5 * (gx + gy)); kernel[y * cols + x] = g; sum += g; } } // Normalize for (int i = 0; i < rows * cols; ++i) { kernel[i] /= sum; } } // Create 3D Gaussian kernel (centered) void create_gaussian_3d(double* kernel, int nz, int ny, int nx, float sigma[3]) { double sum = 0.0; for (int z = 0; z < nz; ++z) { int dz = (z <= nz / 2) ? z : (nz - z); // wrap-around distance for (int y = 0; y < ny; ++y) { int dy = (y <= ny / 2) ? y : (ny - y); for (int x = 0; x < nx; ++x) { int dx = (x <= nx / 2) ? x : (nx - x); double gx = double(dx * dx / (sigma[0] * sigma[0])); double gy = double(dy * dy / (sigma[1] * sigma[1])); double gz = double(dz * dz / (sigma[2] * sigma[2])); double g = exp(-0.5 * (gx + gy + gz)); kernel[(z * ny + y) * nx + x] = g; sum += g; } } } // Normalize for (int i = 0; i < nx * ny * nz; ++i) { kernel[i] /= sum; } } void fftw_blur_2d(Image& trg, Image& src, float sigma[2]) { int width = src.width(); int height = src.height(); float* img_data = src.data(); // Allocate FFTW arrays double* img_spatial = (double*) fftw_malloc(sizeof(double) * width * height); double* kernel_spatial = (double*) fftw_malloc(sizeof(double) * width * height); fftw_complex* img_freq = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * height * (width / 2 + 1)); fftw_complex* kernel_freq = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * height * (width / 2 + 1)); // Copy image to double buffer for (int i = 0; i < width * height; ++i) { img_spatial[i] = (double)img_data[i]; } // Create Gaussian kernel create_gaussian_2d(kernel_spatial, height, width, sigma); // Create FFT plans fftw_plan plan_fwd_img = fftw_plan_dft_r2c_2d(height, width, img_spatial, img_freq, FFTW_ESTIMATE); fftw_plan plan_fwd_kernel = fftw_plan_dft_r2c_2d(height, width, kernel_spatial, kernel_freq, FFTW_ESTIMATE); fftw_plan plan_inv = fftw_plan_dft_c2r_2d(height, width, img_freq, img_spatial, FFTW_ESTIMATE); // Forward FFTs fftw_execute(plan_fwd_img); fftw_execute(plan_fwd_kernel); // Multiply in frequency domain int nfreq = height * (width / 2 + 1); for (int i = 0; i < nfreq; ++i) { double a = img_freq[i][0], b = img_freq[i][1]; double c = kernel_freq[i][0], d = kernel_freq[i][1]; img_freq[i][0] = a * c - b * d; img_freq[i][1] = a * d + b * c; } // Inverse FFT fftw_execute(plan_inv); // Normalize and convert back to float float* out_data = trg.data(); for (int i = 0; i < width * height; ++i) { double val = img_spatial[i] / (width * height); out_data[i] = (float)(val); } // Cleanup fftw_destroy_plan(plan_fwd_img); fftw_destroy_plan(plan_fwd_kernel); fftw_destroy_plan(plan_inv); fftw_free(img_spatial); fftw_free(kernel_spatial); fftw_free(img_freq); fftw_free(kernel_freq); } void fftw_blur_3d(Image& trg, Image& src, float sigma[3]) { int nx = src.width(); int ny = src.height(); int nz = src.depth(); float* img_data = src.data(); // Allocate FFTW buffers double* img_spatial = (double*)fftw_malloc(sizeof(double) * nx * ny * nz); double* kernel_spatial = (double*)fftw_malloc(sizeof(double) * nx * ny * nz); fftw_complex* img_freq = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * nz * ny * (nx / 2 + 1)); fftw_complex* kernel_freq = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * nz * ny * (nx / 2 + 1)); // Copy image to double buffer for (int i = 0; i < nx*ny*nz; ++i) { img_spatial[i] = (double)img_data[i]; } // Create Gaussian kernel create_gaussian_3d(kernel_spatial, nz, ny, nx, sigma); // Plans fftw_plan plan_fwd_img = fftw_plan_dft_r2c_3d(nz, ny, nx, img_spatial, img_freq, FFTW_ESTIMATE); fftw_plan plan_fwd_kernel = fftw_plan_dft_r2c_3d(nz, ny, nx, kernel_spatial, kernel_freq, FFTW_ESTIMATE); fftw_plan plan_inv = fftw_plan_dft_c2r_3d(nz, ny, nx, img_freq, img_spatial, FFTW_ESTIMATE); // Forward FFTs fftw_execute(plan_fwd_img); fftw_execute(plan_fwd_kernel); // Multiply in frequency domain int nfreq = nz * ny * (nx / 2 + 1); for (int i = 0; i < nfreq; ++i) { double a = img_freq[i][0]; // real part double b = img_freq[i][1]; // complex part double c = kernel_freq[i][0]; // real part double d = kernel_freq[i][1]; // complex part img_freq[i][0] = a * c - b * d; // real part img_freq[i][1] = a * d + b * c; // complex part } // Inverse FFT fftw_execute(plan_inv); // Normalize and convert back to float float* out_data = trg.data(); double norm_factor = (double)(nx * ny * nz); for (int i = 0; i < nx * ny * nz; ++i) { double val = img_spatial[i] / norm_factor; out_data[i] = (float)(val); } // Cleanup fftw_destroy_plan(plan_fwd_img); fftw_destroy_plan(plan_fwd_kernel); fftw_destroy_plan(plan_inv); fftw_free(img_spatial); fftw_free(kernel_spatial); fftw_free(img_freq); fftw_free(kernel_freq); } #else void fftw_blur_2d(Image& trg, Image& src, float sigma[2]) {} void fftw_blur_3d(Image& trg, Image& src, float sigma[3]) {} #endif // HAVE_FFTW void blur_image_2d(Image& trg, Image& src, float d, BlurMethod blurMethod) { switch (blurMethod) { case BlurMethod::BLUR_AVERAGE: blur_avg_2d(trg, src, d); break; case BlurMethod::BLUR_FFT: { #ifdef HAVE_FFTW // currently this function will assume the voxels are isotropic float d2[2] = { d, d }; fftw_blur_2d(trg, src, d2); break; #elif HAVE_MKL mkl_blur_2d(trg, src, d); break; #endif } default: break; } } void blur_image_3d(Image& trg, Image& src, float d, BlurMethod blurMethod) { switch (blurMethod) { case BlurMethod::BLUR_AVERAGE: blur_avg_3d(trg, src, d); break; case BlurMethod::BLUR_FFT: { #ifdef HAVE_FFTW // currently this function will assume the voxels are isotropic float d3[3] = { d, d, d }; fftw_blur_3d(trg, src, d3); break; #elif HAVE_MKL mkl_blur_3d(trg, src, d); break; #endif } default: break; } } //----------------------------------------------------------------------------- // Extension functions for image filter edges // return integer for constant border extension int constant_extension(int n, int N) { if (n < 0) n = 0; else if (n >= N) n = N - 1; return n; } // return integer for symmetric border extension int symmetric_extension(int n, int N) { while (1) { if (n < 0) n = -1 - n; else if (n >= N) n = (2 * N) - 1 - n; else break; } return n; }
C++
3D
febiosoftware/FEBio
FEImgLib/ImageFilter.h
.h
2,296
101
#pragma once #include "Image.h" #include <FECore/FECoreClass.h> #include <FECore/mat3d.h> #include "feimglib_api.h" #include "image_tools.h" #ifdef HAVE_FFTW #include <fftw3.h> #endif // HAVE_FFTW class FEIMGLIB_API ImageFilter : public FECoreClass { FECORE_BASE_CLASS(ImageFilter) public: //! default constructor ImageFilter(FEModel* fem); //! initialize filter virtual bool Init() = 0; //! evaluate the filter at the current position virtual void Update(Image& trg, Image& src) = 0; //! evaluate the filter at the current position virtual float Apply(Image& img, int m_pos[3], int m_range[3], int m_dir) = 0; //! return blur value virtual double GetBlur() = 0; protected: }; class FEIMGLIB_API IterativeBlur : public ImageFilter { public: IterativeBlur(FEModel* fem); bool Init() override; void Update(Image& trg, Image& src) override; float Apply(Image& img, int m_pos[3], int m_range[3], int m_dir) override; double GetBlur() override { return m_blur; }; protected: //! flag to normalize data so that blur units coincide with physical dimensions rather than img dimensions bool m_norm_flag; double m_blur; DECLARE_FECORE_CLASS(); }; class FEIMGLIB_API BoxBlur : public ImageFilter { public: BoxBlur(FEModel* fem); bool Init() override; void Update(Image& trg, Image& src) override; float Apply(Image& img, int m_pos[3], int m_range[3], int m_dir) override; //! return the current blur value double GetBlur() override { return m_blur; }; public: bool m_norm_flag = false; double m_blur; // sigma (units of length) double m_rp; // previous modulus double m_tp; // previous time int m_K; // iterations of box blur to apply double m_res[3]; // voxel resolution (L / px) int m_ri[3]; // effective radii along each direction DECLARE_FECORE_CLASS(); }; #ifdef HAVE_FFTW class FEIMGLIB_API FFTWBlur : public ImageFilter { public: FFTWBlur(FEModel* fem); bool Init() override; void Update(Image& trg, Image& src) override; float Apply(Image& img, int m_pos[3], int m_range[3], int m_dir) override; double GetBlur() override { return m_blur; }; public: bool m_norm_flag = false; double m_blur; // sigma (units of length) double m_res[3]; // voxel resolution (L / px) double m_sigma[3]; DECLARE_FECORE_CLASS(); }; #endif // HAVE_FFTW
Unknown
3D
febiosoftware/FEBio
FEImgLib/FEImageValuator.cpp
.cpp
2,080
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 "FEImageValuator.h" #include <FECore/FEMaterialPoint.h> BEGIN_FECORE_CLASS(FEImageValuator, FEScalarValuator) ADD_PARAMETER(m_r0, "range_min"); ADD_PARAMETER(m_r1, "range_max"); ADD_PROPERTY(m_imSrc, "image")->SetDefaultType("raw"); ADD_PROPERTY(m_transform, "transform"); END_FECORE_CLASS(); FEImageValuator::FEImageValuator(FEModel* fem) : FEScalarValuator(fem), m_map(m_im) { m_imSrc = nullptr; } bool FEImageValuator::Init() { if (m_imSrc == nullptr) return false; if (m_imSrc->GetImage3D(m_im) == false) return false; m_map.SetRange(m_r0, m_r1); return FEScalarValuator::Init(); } double FEImageValuator::operator()(const FEMaterialPoint& pt) { return m_transform->value(m_map.value(pt.m_r0)); } FEScalarValuator* FEImageValuator::copy() { assert(false); return nullptr; }
C++
3D
febiosoftware/FEBio
FEImgLib/FEImgLib.cpp
.cpp
645
27
#include "FEImgLib.h" #include <FECore/FECoreKernel.h> #include "FEImageSource.h" #include "FEImageDataMap.h" #include "FEImageValuator.h" #include "ImageFilter.h" void FEImgLib::InitModule() { // image sources REGISTER_FECORE_CLASS(FERawImage, "raw"); REGISTER_FECORE_CLASS(FENRRDImage, "nrrd"); // data maps REGISTER_FECORE_CLASS(FEImageDataMap, "image map"); // valuator REGISTER_FECORE_CLASS(FEImageValuator, "image map"); // filter classes REGISTER_FECORE_CLASS(IterativeBlur, "iterative blur"); REGISTER_FECORE_CLASS(BoxBlur, "box blur"); #ifdef HAVE_FFTW REGISTER_FECORE_CLASS(FFTWBlur, "FFTW blur"); #endif // HAVE_FFTW }
C++
3D
febiosoftware/FEBio
FEImgLib/FEImgLib.h
.h
1,370
33
/*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 "feimglib_api.h" namespace FEImgLib { FEIMGLIB_API void InitModule(); }
Unknown
3D
febiosoftware/FEBio
FEImgLib/feimglib_api.h
.h
1,531
44
/*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 feimglib_EXPORTS #define FEIMGLIB_API __declspec(dllexport) #else #define FEIMGLIB_API __declspec(dllimport) #endif #else #define FEIMGLIB_API #endif #else #define FEIMGLIB_API #endif
Unknown
3D
febiosoftware/FEBio
FEImgLib/fft.cpp
.cpp
5,043
106
#ifdef HAVE_MKL #include <mkl.h> #include <complex> //--------------------------------------------------------------------------------------- // calculate the DFT of a source image x. The source image is assumed to be stored // in row-major order, indexed by (x,y), where x is the column index, and y the row index. // The complex Fourier coefficients are returned in c. The buffer must be pre-allocated and must have // the size (nx,ny), the same as the source image. bool mkl_dft2(int nx, int ny, float* x, MKL_Complex8* c) { DFTI_DESCRIPTOR_HANDLE my_desc_handle; MKL_LONG status; MKL_LONG sizes[2] = { nx, ny }; MKL_LONG is[3] = { 0, 1, nx }; MKL_LONG os[3] = { 0, 1, nx }; // { 0, 1, N2/2+1} status = DftiCreateDescriptor(&my_desc_handle, DFTI_SINGLE, DFTI_REAL, 2, sizes); status = DftiSetValue(my_desc_handle, DFTI_PLACEMENT, DFTI_NOT_INPLACE); status = DftiSetValue(my_desc_handle, DFTI_CONJUGATE_EVEN_STORAGE, DFTI_COMPLEX_COMPLEX); status = DftiSetValue(my_desc_handle, DFTI_INPUT_STRIDES, is); status = DftiSetValue(my_desc_handle, DFTI_OUTPUT_STRIDES, os); status = DftiCommitDescriptor(my_desc_handle); status = DftiComputeForward(my_desc_handle, x, c); status = DftiFreeDescriptor(&my_desc_handle); return true; } //--------------------------------------------------------------------------------------- // calculate the inverse DFT. The fourier coefficients are passed and assumed to be stored // in row-major order, indexed by (x,y), where x is the column index, and y the row index. // The reconstructed image is returned in x, which must have the same size and storage. bool mkl_idft2(int nx, int ny, MKL_Complex8* c, float* x) { DFTI_DESCRIPTOR_HANDLE my_desc_handle; MKL_LONG status; MKL_LONG sizes[2] = { nx, ny }; MKL_LONG is[3] = { 0, 1, nx }; // { 0, 1, Nx/2+1} MKL_LONG os[3] = { 0, 1, nx }; status = DftiCreateDescriptor(&my_desc_handle, DFTI_SINGLE, DFTI_REAL, 2, sizes); status = DftiSetValue(my_desc_handle, DFTI_PLACEMENT, DFTI_NOT_INPLACE); status = DftiSetValue(my_desc_handle, DFTI_CONJUGATE_EVEN_STORAGE, DFTI_COMPLEX_COMPLEX); status = DftiSetValue(my_desc_handle, DFTI_INPUT_STRIDES, is); status = DftiSetValue(my_desc_handle, DFTI_OUTPUT_STRIDES, os); status = DftiSetValue(my_desc_handle, DFTI_BACKWARD_SCALE, 1.f / ((float)nx * (float)ny)); status = DftiCommitDescriptor(my_desc_handle); status = DftiComputeBackward(my_desc_handle, c, x); status = DftiFreeDescriptor(&my_desc_handle); return true; } //--------------------------------------------------------------------------------------- // calculate the DFT of a source image x. The source image is assumed to be stored // in row-major order, indexed by (x,y,z), where x is the column index, y the row index, z is the plane index. // The complex Fourier coefficients are returned in c. The buffer must be pre-allocated and must have // the size (nx,ny,nz), the same as the source image. bool mkl_dft3(int nx, int ny, int nz, float* x, MKL_Complex8* c) { DFTI_DESCRIPTOR_HANDLE my_desc_handle; MKL_LONG status; MKL_LONG sizes[3] = { nx, ny, nz }; MKL_LONG is[4] = { 0, 1, nx, nx*ny }; MKL_LONG os[4] = { 0, 1, nx, nx*ny }; // { 0, 1, nx, ny, nz/2+1} status = DftiCreateDescriptor(&my_desc_handle, DFTI_SINGLE, DFTI_REAL, 3, sizes); status = DftiSetValue(my_desc_handle, DFTI_PLACEMENT, DFTI_NOT_INPLACE); status = DftiSetValue(my_desc_handle, DFTI_CONJUGATE_EVEN_STORAGE, DFTI_COMPLEX_COMPLEX); status = DftiSetValue(my_desc_handle, DFTI_INPUT_STRIDES, is); status = DftiSetValue(my_desc_handle, DFTI_OUTPUT_STRIDES, os); status = DftiCommitDescriptor(my_desc_handle); status = DftiComputeForward(my_desc_handle, x, c); status = DftiFreeDescriptor(&my_desc_handle); return true; } //--------------------------------------------------------------------------------------- // calculate the inverse DFT. The fourier coefficients are passed and assumed to be stored // in row-major order, indexed by (x,y,z), where x is the column index, y the row index, and z the plane index. // The reconstructed image is returned in y, which must have the same size and storage. bool mkl_idft3(int nx, int ny, int nz, MKL_Complex8* c, float* y) { DFTI_DESCRIPTOR_HANDLE my_desc_handle; MKL_LONG status; MKL_LONG sizes[3] = { nx, ny, nz }; MKL_LONG is[4] = { 0, 1, nx, nx * ny }; // { 0, 1, nx, ny, nz/2+1} MKL_LONG os[4] = { 0, 1, nx, nx * ny }; status = DftiCreateDescriptor(&my_desc_handle, DFTI_SINGLE, DFTI_REAL, 3, sizes); status = DftiSetValue(my_desc_handle, DFTI_PLACEMENT, DFTI_NOT_INPLACE); status = DftiSetValue(my_desc_handle, DFTI_CONJUGATE_EVEN_STORAGE, DFTI_COMPLEX_COMPLEX); status = DftiSetValue(my_desc_handle, DFTI_INPUT_STRIDES, is); status = DftiSetValue(my_desc_handle, DFTI_OUTPUT_STRIDES, os); status = DftiSetValue(my_desc_handle, DFTI_BACKWARD_SCALE, 1.f / ((float)nx * (float)ny * (float) nz)); status = DftiCommitDescriptor(my_desc_handle); status = DftiComputeBackward(my_desc_handle, c, y); status = DftiFreeDescriptor(&my_desc_handle); return true; } #endif
C++
3D
febiosoftware/FEBio
FEImgLib/FEImageDataMap.h
.h
1,830
62
/*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/FEDataGenerator.h> #include "FEImageSource.h" #include "ImageMap.h" #include "feimglib_api.h" class FEDomainMap; class FEIMGLIB_API FEImageDataMap : public FEElemDataGenerator { public: FEImageDataMap(FEModel* fem); bool Init() override; FEDataMap* Generate() override; void Evaluate(double time) override; private: void GenerateData(); private: vec3d m_r0; vec3d m_r1; double m_blur; FEImageSource* m_imgSrc; private: Image m_im0, m_im; ImageMap m_map; FEDomainMap* m_data; DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEImgLib/ImageMap.h
.h
1,398
62
#pragma once #include "Image.h" #include <FECore/vec3d.h> #include <FECore/mat3d.h> #include "feimglib_api.h" class FEIMGLIB_API ImageMap { public: struct POINT { int i, j, k; double h[8]; }; public: ImageMap(Image& img); ~ImageMap(void); void SetRange(vec3d r0, vec3d r1); // map a vector to the image domain POINT map(const vec3d& p); // evaluate image double value(const POINT& p); double value(const vec3d& r) { return value(map(r)); } // determine if a point is in bounds bool valid(const vec3d& p); // image gradient vec3d gradient(const vec3d& r); // image hessian mat3ds hessian(const vec3d& r); // pixel dimensions double dx() { return (m_r1.x - m_r0.x)/(double) (m_img.width () - 1); } double dy() { return (m_r1.y - m_r0.y)/(double) (m_img.height() - 1); } double dz() { int nz = m_img.depth(); if (nz == 1) return 1.0; else return (m_r1.z - m_r0.z)/(double) (m_img.depth () - 1); } Image& GetImage() { return m_img; } protected: double grad_x(int i, int j, int k); double grad_y(int i, int j, int k); double grad_z(int i, int j, int k); double hessian_xx(int i, int j, int k); double hessian_yy(int i, int j, int k); double hessian_zz(int i, int j, int k); double hessian_xy(int i, int j, int k); double hessian_yz(int i, int j, int k); double hessian_xz(int i, int j, int k); protected: Image& m_img; vec3d m_r0; vec3d m_r1; };
Unknown
3D
febiosoftware/FEBio
ci/gather-plugins.py
.py
1,971
64
import os, shutil, json os.mkdir("plugins") for dirName in os.listdir("pluginRepos"): dirPath = os.path.join("pluginRepos", dirName) if os.path.isdir(dirPath): newDir = os.path.join("plugins", dirName) os.mkdir(newDir) for root, dirs, files in os.walk(dirPath, followlinks=True): for name in files: if name.endswith(".dll") or name.endswith(".dylib") or name.endswith(".so"): filename = name.split("/")[-1].split("\\")[-1] shutil.copy2(os.path.join(root,name), os.path.join(newDir, filename)) def getVersion(path): if not path: return None major = minor = patch = None with open(path, "r") as f: for line in f: if "#define VERSION" in line: major = line.split()[-1].strip() elif "#define SUBVERSION" in line: minor = line.split()[-1].strip() elif "#define SUBSUBVERSION" in line: patch = line.split()[-1].strip() if major and minor and patch: return f"{major}.{minor}.{patch}" return None versionInfo = {} # FEBio version versionInfo["febio"] = getVersion("febio4-sdk/include/FEBioLib/version.h") # Find version for each plugin for dirName in os.listdir("pluginRepos"): dirPath = os.path.join("pluginRepos", dirName) if os.path.isdir(dirPath): versionHeader = None for root, dirs, files in os.walk(dirPath): for name in files: if name.endswith("version.h"): versionHeader = os.path.join(root, name) break if versionHeader: break if versionHeader: versionInfo[dirName] = getVersion(versionHeader) else: print(f"Unable to find version header for {dirPath}") with open("plugins/versions.json", "w") as f: json.dump(versionInfo, f)
Python
3D
febiosoftware/FEBio
ci/repo-plugins.py
.py
807
27
import os, json HOMEPATH = "/root" try: with open("plugins/versions.json", "r") as file: versionInfo = json.load(file) febioVersion = versionInfo["febio"] del versionInfo["febio"] platform = os.environ["OS"] if platform == "Windows": osFlag = "-w" elif platform == "macOS": osFlag = "-m" else: osFlag = "-l" for name in versionInfo: os.system(f"scp plugins/{name}/* repo:{HOMEPATH}/pluginRepo/files/{name}/develop/stage/") os.system(f'ssh repo "python3 {HOMEPATH}/modelServer/plugins.py -d {name} {versionInfo[name]} {febioVersion} {osFlag}"') except FileNotFoundError: print("Error: 'plugins/versions.json not found. ") except json.JSONDecodeError: print("Error: Invalid JSON format in 'plugins/versions.json'.")
Python
3D
febiosoftware/FEBio
ci/Linux/build.sh
.sh
380
18
#! /bin/bash # Uncomment next line if not global on target machine set -e #git config --global --add safe.directory /FEBio source "/opt/intel/oneapi/setvars.sh" --force cmake . -B cmbuild -LA \ -DSET_DEVCOMMIT=ON \ -DUSE_FFTW=ON \ -DUSE_HYPRE=ON \ -DUSE_LEVMAR=ON \ -DUSE_MKL=ON \ -DUSE_MMG=ON \ -DUSE_STATIC_STDLIBS=ON \ -DUSE_ZLIB=ON pushd cmbuild make -j $(nproc) popd
Shell
3D
febiosoftware/FEBio
ci/Linux/create-sdk.sh
.sh
1,038
53
#! /bin/bash set -e TARGET_DIR="${TARGET_DIR:-febio4-sdk}" FEBIO_REPO="${FEBIO_REPO:-.}" mkdir -p ${TARGET_DIR}/{include,lib} # Copy in FEBioConfig.cmake mkdir -p ${TARGET_DIR}/lib/cmake/FEBio cp $FEBIO_REPO/FEBioConfig.cmake ${TARGET_DIR}/lib/cmake/FEBio sdkDirs=( FECore FEBioMech FEBioMix FEBioFluid FEBioRVE FEBioPlot FEBioXML FEBioLib FEAMR FEBioOpt FEImgLib ) sdkLibs=( libfecore.so libfebiomech.so libfebiomix.so libfebiofluid.so libfebiorve.so libfebioplot.so libfebioxml.so libfebiolib.so libfeamr.so libfebioopt.so libfeimglib.so ) for item in ${sdkDirs[@]}; do mkdir ${TARGET_DIR}/include/$item cp $FEBIO_REPO/$item/*.h ${TARGET_DIR}/include/$item # don't exit if there aren't .hpp files if ls "$FEBIO_REPO/$item"/*.hpp >/dev/null 2>&1; then cp "$FEBIO_REPO/$item"/*.hpp "${TARGET_DIR}/include/$item" fi done for item in ${sdkLibs[@]}; do cp $FEBIO_REPO/cmbuild/lib/$item ${TARGET_DIR}/lib done
Shell
3D
febiosoftware/FEBio
ci/Linux/publish-to-s3.sh
.sh
149
6
#! /bin/bash set -e chmod +x artifacts/febio4/bin/febio4 ci/common/publish-to-s3.sh artifacts/febio4 ci/common/publish-to-s3.sh artifacts/febio4-sdk
Shell
3D
febiosoftware/FEBio
ci/Linux/publish-docker-images.sh
.sh
145
4
#! /bin/bash docker build -t $REGISTRY/$REPOSITORY:$IMAGE_TAG -f infrastructure/DockerfileRuntime . docker push $REGISTRY/$REPOSITORY:$IMAGE_TAG
Shell
3D
febiosoftware/FEBio
ci/Linux/scp-to-repo.sh
.sh
523
23
#! /bin/bash REMOTE_PATH="update2/FEBioStudio2Dev/Linux/stage" if [ $# == 1 ] && [ "$1" != "develop" ]; then REMOTE_PATH="update2/FEBioStudio2Dev/branches/$1/Linux/stage" fi set -e scp cmbuild/bin/* repo:~/$REMOTE_PATH/bin scp cmbuild/lib/* repo:~/$REMOTE_PATH/lib ssh repo "chmod +x $REMOTE_PATH/bin/febio4" # package and upload sdk pushd sdk zip -r sdk.zip include zip -r sdk.zip lib scp sdk.zip repo:~/$REMOTE_PATH/ popd if [ -f testLogs/Logs/* ]; then scp testLogs/Logs/* repo:~/TestSuite/Logs/linux.txt fi
Shell
3D
febiosoftware/FEBio
ci/Linux/test.sh
.sh
630
28
#! /bin/bash # Uncomment next line if not global on target machine set -e FEBIO_XML=$(realpath ./ci/febio.xml) PLUGIN_DIR=$(realpath ./plugins) FEBIO_DIR=$(realpath ./cmbuild/bin) FEBIO_LIB=$(realpath ./cmbuild/lib) FEBIO_BIN="${FEBIO_DIR}/febio4" chmod +x $FEBIO_BIN # Copy the plugins from their subdirectories directly to # the root of the plugin dir cp $PLUGIN_DIR/*/*.so $PLUGIN_DIR ls $PLUGIN_DIR cat $FEBIO_XML # Set the plugin dir in the FEBio XML sed -i 's@PLUGINS_FOLDER@'$PLUGIN_DIR'@' $FEBIO_XML cat $FEBIO_XML # Copy febio xml into febio dir cp $FEBIO_XML $FEBIO_DIR ./TestSuite/code/tools.py -r $FEBIO_BIN -n
Shell
3D
febiosoftware/FEBio
ci/macOS/cmake.sh
.sh
298
12
cmake . -B cmbuild -L \ -DCMAKE_OSX_ARCHITECTURES="x86_64" \ -DCMAKE_OSX_DEPLOYMENT_TARGET=10.15 \ -DSET_DEVCOMMIT=ON \ -DUSE_FFTW=ON \ -DUSE_HYPRE=ON \ -DUSE_LEVMAR=ON \ -DUSE_MKL=ON \ -DUSE_MMG=ON \ -DUSE_ZLIB=ON \ -DOMP_INC=/Users/gitRunner/local/x86_64/homebrew/opt/libomp/include
Shell
3D
febiosoftware/FEBio
ci/macOS/build.sh
.sh
237
10
#! /bin/bash # Uncomment next line if not global on target machine # git config --global --add safe.directory /FEBio source "/opt/intel/oneapi/setvars.sh" --force . $(dirname $0)/cmake.sh pushd cmbuild make -j $(sysctl -n hw.ncpu) popd
Shell
3D
febiosoftware/FEBio
ci/macOS/create-sdk.sh
.sh
1,070
52
#! /bin/bash set -e TARGET_DIR="${TARGET_DIR:-febio4-sdk}" FEBIO_REPO="${FEBIO_REPO:-.}" mkdir -p ${TARGET_DIR}/{include,lib} # Copy in FEBioConfig.cmake mkdir -p ${TARGET_DIR}/lib/cmake/FEBio cp $FEBIO_REPO/FEBioConfig.cmake ${TARGET_DIR}/lib/cmake/FEBio sdkDirs=( FECore FEBioMech FEBioMix FEBioFluid FEBioRVE FEBioPlot FEBioXML FEBioLib FEAMR FEBioOpt FEImgLib ) sdkLibs=( libfecore.dylib libfebiomech.dylib libfebiomix.dylib libfebiofluid.dylib libfebiorve.dylib libfebioplot.dylib libfebioxml.dylib libfebiolib.dylib libfeamr.dylib libfebioopt.dylib libfeimglib.dylib ) for item in ${sdkDirs[@]}; do mkdir ${TARGET_DIR}/include/$item cp $FEBIO_REPO/$item/*.h ${TARGET_DIR}/include/$item # don't exit if there aren't .hpp files if ls "$FEBIO_REPO/$item"/*.hpp >/dev/null 2>&1; then cp "$FEBIO_REPO/$item"/*.hpp "${TARGET_DIR}/include/$item" fi done for item in ${sdkLibs[@]}; do cp $FEBIO_REPO/cmbuild/lib/$item ${TARGET_DIR}/lib done
Shell
3D
febiosoftware/FEBio
ci/macOS/publish-to-s3.sh
.sh
143
6
#! /bin/bash chmod +x artifacts/febio4/bin/febio4 ci/common/publish-to-s3.sh artifacts/febio4 ci/common/publish-to-s3.sh artifacts/febio4-sdk
Shell
3D
febiosoftware/FEBio
ci/macOS/publish-docker-images.sh
.sh
145
4
#! /bin/bash docker build -t $REGISTRY/$REPOSITORY:$IMAGE_TAG -f infrastructure/DockerfileRuntime . docker push $REGISTRY/$REPOSITORY:$IMAGE_TAG
Shell
3D
febiosoftware/FEBio
ci/macOS/scp-to-repo.sh
.sh
601
21
#! /bin/bash REMOTE_PATH="update2/FEBioStudio2Dev/macOS/stage" if [ $# == 1 ] && [ "$1" != "develop" ]; then REMOTE_PATH="update2/FEBioStudio2Dev/branches/$1/macOS/stage" fi scp cmbuild/bin/* repo:~/$REMOTE_PATH/FEBioStudio.app/Contents/MacOS scp cmbuild/lib/* repo:~/$REMOTE_PATH/FEBioStudio.app/Contents/Frameworks ssh repo "chmod +x $REMOTE_PATH/FEBioStudio.app/Contents/MacOS/febio4" # package and upload sdk pushd sdk zip -r sdk.zip include zip -r sdk.zip lib scp sdk.zip repo:~/$REMOTE_PATH/ popd if [ -f testLogs/Logs/* ]; then scp testLogs/Logs/* repo:~/TestSuite/Logs/macOS.txt fi
Shell
3D
febiosoftware/FEBio
ci/macOS/test.sh
.sh
614
25
#! /bin/bash # Uncomment next line if not global on target machine set -e FEBIO_XML=$(realpath ./ci/febio.xml) PLUGIN_DIR=$(realpath ./plugins) FEBIO_DIR=$(realpath ./cmbuild/bin) FEBIO_LIB=$(realpath ./cmbuild/lib) FEBIO_BIN="${FEBIO_DIR}/febio4" chmod +x $FEBIO_BIN # Copy the plugins from their subdirectories directly to # the root of the plugin dir cp $PLUGIN_DIR/*/*.dylib $PLUGIN_DIR # Set the plugin dir in the FEBio XML sed -i '' "s@PLUGINS_FOLDER@${PLUGIN_DIR}@g" "$FEBIO_XML" # Copy febio xml into febio dir cp $FEBIO_XML $FEBIO_DIR # Run the test suite ./TestSuite/code/tools.py -r $FEBIO_BIN -n
Shell
3D
febiosoftware/FEBio
ci/Windows/create-sdk.sh
.sh
1,079
43
#! /bin/bash set -e TARGET_DIR="${TARGET_DIR:-febio4-sdk}" FEBIO_REPO="${FEBIO_REPO:-.}" mkdir -p ${TARGET_DIR}/{include,lib,bin} mkdir ${TARGET_DIR}/lib/{Release,Debug} mkdir ${TARGET_DIR}/bin/Debug # Copy in FEBioConfig.cmake mkdir -p ${TARGET_DIR}/lib/cmake/FEBio cp $FEBIO_REPO/FEBioConfig.cmake ${TARGET_DIR}/lib/cmake/FEBio sdkDirs=( FECore FEBioMech FEBioMix FEBioFluid FEBioRVE FEBioPlot FEBioXML FEBioLib FEAMR FEBioOpt FEImgLib ) for item in ${sdkDirs[@]}; do mkdir ${TARGET_DIR}/include/$item cp $FEBIO_REPO/$item/*.h ${TARGET_DIR}/include/$item # don't exit if there aren't .hpp files if ls "$FEBIO_REPO/$item"/*.hpp >/dev/null 2>&1; then cp "$FEBIO_REPO/$item"/*.hpp "${TARGET_DIR}/include/$item" fi cp $FEBIO_REPO/cmbuild/lib/Release/$item.lib ${TARGET_DIR}/lib/Release cp $FEBIO_REPO/cmbuild/lib/Debug/$item.lib ${TARGET_DIR}/lib/Debug done cp $FEBIO_REPO/cmbuild/bin/Debug/febio4.exe ${TARGET_DIR}/bin/Debug cp $FEBIO_REPO/cmbuild/bin/Debug/*.dll ${TARGET_DIR}/bin/Debug
Shell
3D
febiosoftware/FEBio
ci/Windows/publish-to-s3.sh
.sh
106
5
#! /bin/bash ci/common/publish-to-s3.sh artifacts/febio4 ci/common/publish-to-s3.sh artifacts/febio4-sdk
Shell
3D
febiosoftware/FEBio
ci/Windows/scp-to-repo.sh
.sh
462
20
#! /bin/bash REMOTE_PATH="update2/FEBioStudio2Dev/Windows/stage" if [ $# == 1 ] && [ "$1" != "develop" ]; then REMOTE_PATH="update2/FEBioStudio2Dev/branches/$1/Windows/stage" fi scp cmbuild/bin/Release/* repo:~/$REMOTE_PATH/bin # package and upload sdk pushd sdk zip -r sdk.zip include zip -r sdk.zip lib zip -r sdk.zip bin scp sdk.zip repo:~/$REMOTE_PATH/ popd if [ -f testLogs/Logs/* ]; then scp testLogs/Logs/* repo:~/TestSuite/Logs/windows.txt fi
Shell
3D
febiosoftware/FEBio
ci/Windows/test.sh
.sh
1,228
39
#! /usr/bin/bash # Uncomment next line if not global on target machine set -e set -x FEBIO_XML=$(realpath ./ci/febio.xml) PLUGIN_DIR=$(realpath ./plugins) FEBIO_DIR=$(realpath ./cmbuild/bin/Release) FEBIO_LIB=$(realpath ./cmbuild/bin/Release) FEBIO_BIN="${FEBIO_DIR}/febio4.exe" # Convert plugin dir to Windows style PLUGIN_DIR_WIN=$(cygpath -w "$PLUGIN_DIR" | sed 's|\\|/|g') # Copy the plugins from their subdirectories directly to # the root of the plugin dir cp $PLUGIN_DIR/*/*.dll $PLUGIN_DIR # Set the plugin dir in the FEBio XML sed -i "s@PLUGINS_FOLDER@${PLUGIN_DIR_WIN}@g" "$FEBIO_XML" # Copy febio xml into febio dir cp $FEBIO_XML $FEBIO_DIR # Copy iomp lib into febio dir ONEAPI=$(cygpath -u "$ONEAPI_ROOT") #Convert $ONEAPI_ROOT to posix path IOMP_LIB="${ONEAPI}compiler/latest/windows/redist/intel64_win/compiler/libiomp5md.dll" cp -a "$IOMP_LIB" "$FEBIO_LIB" # Copy fftw lib into febio dir FFTW_LIB="/c/usr/local/febio/vcpkg_installed/x64-windows/bin/fftw3.dll" cp -a "$FFTW_LIB" "$FEBIO_LIB" ZLIB="/c/usr/local/febio/vcpkg_installed/x64-windows/bin/zlib1.dll" cp -a "$ZLIB" "$FEBIO_LIB" # Run the test suite PYTHON="${ONEAPI}intelpython/latest/python" "$PYTHON" ./TestSuite/code/tools.py -r $FEBIO_BIN -n
Shell
3D
febiosoftware/FEBio
FEBioLib/FEBioRestart.cpp
.cpp
4,292
129
/*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 "FEBioRestart.h" #include <FEBioLib/FEBioModel.h> #include <FECore/log.h> #include <FEBioXML/FERestartImport.h> #include <FECore/DumpFile.h> #include <FECore/FEAnalysis.h> #include "FEBioModelBuilder.h" //----------------------------------------------------------------------------- FEBioRestart::FEBioRestart(FEModel* pfem) : FECoreTask(pfem) {} //----------------------------------------------------------------------------- bool FEBioRestart::Init(const char* szfile) { FEBioModel& fem = static_cast<FEBioModel&>(*GetFEModel()); // check the extension of the file // if the extension is .dmp or not given it is assumed the file // is a bindary archive (dump file). Otherwise it is assumed the // file is a restart input file. const char* ch = strrchr(szfile, '.'); if ((ch == 0) || (strcmp(ch, ".dmp") == 0) || (strcmp(ch, ".DMP") == 0)) { // the file is binary so just read the dump file and return // open the archive DumpFile ar(fem); if (ar.Open(szfile) == false) { fprintf(stderr, "FATAL ERROR: failed opening restart archive\n"); return false; } // read the archive try { fem.Serialize(ar); } catch (std::exception e) { fprintf(stderr, "FATAL ERROR: Exception occured while reading restart archive %s\n%s\n", szfile, e.what()); return false; } catch (...) { fprintf(stderr, "FATAL ERROR: failed reading restart data from archive %s\n", szfile); return false; } } else { // the file is assumed to be a xml-text input file FERestartImport file; file.SetModelBuilder(new FEBioModelBuilder(fem)); if (file.Load(fem, szfile) == false) { char szerr[256]; file.GetErrorMessage(szerr); fprintf(stderr, "%s", szerr); return false; } // get the number of new steps added int newSteps = file.StepsAdded(); int step = fem.Steps() - newSteps; // Any additional steps that were created must be initialized for (int i = step; i < fem.Steps(); ++i) { FEAnalysis* step = fem.GetStep(i); if (step->Init() == false) return false; // also initialize all the model components for (int j = 0; j < step->StepComponents(); ++j) { FEStepComponent* pc = step->GetStepComponent(j); if (pc->Init() == false) return false; } } // see if user redefined restart file name if (file.m_szdmp[0]) fem.SetDumpFilename(file.m_szdmp); } // Open the log file for appending const std::string& slog = fem.GetLogfileName(); Logfile& felog = fem.GetLogFile(); if (felog.append(slog.c_str()) == false) { printf("WARNING: Could not reopen log file. A new log file is created\n"); felog.open(slog.c_str()); return false; } // inform the user from where the problem is restarted felog.printbox(" - R E S T A R T -", "Restarting from time %lg.\n", fem.GetCurrentTime()); return true; } //----------------------------------------------------------------------------- bool FEBioRestart::Run() { // continue the analysis return (GetFEModel() ? GetFEModel()->Solve() : false); }
C++
3D
febiosoftware/FEBio
FEBioLib/LogFileStream.cpp
.cpp
2,605
88
/*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 "LogFileStream.h" //----------------------------------------------------------------------------- LogFileStream::LogFileStream() { m_fp = 0; } //----------------------------------------------------------------------------- LogFileStream::~LogFileStream() { close(); } //----------------------------------------------------------------------------- void LogFileStream::close() { if (m_fp) fclose(m_fp); m_fp = 0; } //----------------------------------------------------------------------------- void LogFileStream::flush() { if (m_fp) fflush(m_fp); } //----------------------------------------------------------------------------- bool LogFileStream::open(const char* szfile) { m_fileName = szfile; if (m_fp) close(); m_fp = fopen(szfile, "wt"); return (m_fp != NULL); } //----------------------------------------------------------------------------- bool LogFileStream::append(const char* szfile) { // make sure we don't have a log file already open if (m_fp) { fseek(m_fp, SEEK_END, 0); return true; } // create the log file m_fileName = szfile; m_fp = fopen(szfile, "a+t"); return (m_fp != NULL); } //----------------------------------------------------------------------------- void LogFileStream::print(const char* sztxt) { if (m_fp) fprintf(m_fp, "%s", sztxt); }
C++
3D
febiosoftware/FEBio
FEBioLib/plugin.h
.h
3,674
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.*/ #pragma once #include <vector> #include <string> #ifdef WIN32 #include <Windows.h> #undef RegisterClass #undef GetFileTitle #endif #include "febiolib_api.h" #ifdef WIN32 typedef HMODULE FEBIO_PLUGIN_HANDLE; #endif #ifdef LINUX typedef void* FEBIO_PLUGIN_HANDLE; #endif #ifdef __APPLE__ typedef void* FEBIO_PLUGIN_HANDLE; #endif class FECoreFactory; //----------------------------------------------------------------------------- struct PLUGIN_INFO { bool bloaded; // loaded successfully int major; // major version number int minor; // minor version number int patch; // patch versin number }; //----------------------------------------------------------------------------- //! This class defines a FEBio plugin class FEBIOLIB_API FEBioPlugin { public: struct Version { int major; // major version number int minor; // minor version number int patch; // patch versin number }; public: FEBioPlugin(); ~FEBioPlugin(); //! Try to load the library int Load(const char* szfile); //! Unload the library void UnLoad(); //! get the plugin name const char* GetName() const { return m_szname; } //! return the version info Version GetVersion() const { return m_version; } //! get the plugin's path std::string GetFilePath() const { return m_filepath; } //! Get the allocator ID int GetAllocatorID() const { return m_allocater_id; } protected: void SetNameFromFilePath(const char* szfile); private: std::string m_filepath; char m_szname[1024]; int m_allocater_id; Version m_version; FEBIO_PLUGIN_HANDLE m_ph; }; //----------------------------------------------------------------------------- //! This class manages all the plugins class FEBIOLIB_API FEBioPluginManager { public: //! Get the plugin manager static FEBioPluginManager* GetInstance(); //! Load a plugin into memory int LoadPlugin(const char* szfile, PLUGIN_INFO& info); //! unload a plugin from memory bool UnloadPlugin(int n); bool UnloadPlugin(const std::string& name); void UnloadAllPlugins(); //! Clean up void DeleteThis(); //! return the number of plugins loaded int Plugins(); //! return an instance of a plugin const FEBioPlugin& GetPlugin(int i); private: std::vector<FEBioPlugin*> m_Plugin; private: FEBioPluginManager(){} ~FEBioPluginManager(); FEBioPluginManager(const FEBioPluginManager&){} static FEBioPluginManager* m_pThis; };
Unknown
3D
febiosoftware/FEBio
FEBioLib/LogStream.h
.h
1,732
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 "febiolib_api.h" //----------------------------------------------------------------------------- // class used to create an abstract interface to a screen class FEBIOLIB_API LogStream { public: LogStream() {} virtual ~LogStream() {} // override function to print virtual void print(const char* sz) = 0; // function to print variable output void printf(const char* sz, ...); // flush the stream virtual void flush() {} };
Unknown
3D
febiosoftware/FEBio
FEBioLib/Logfile.cpp
.cpp
5,173
193
/*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 "Logfile.h" #include <stdarg.h> #include <cstring> //----------------------------------------------------------------------------- // constructor for the Logfile class Logfile::Logfile() { m_fp = 0; m_ps = 0; m_mode = LOG_FILE_AND_SCREEN; } //----------------------------------------------------------------------------- // destructor for the Logfile class // Logfile::~Logfile() { close(); } //----------------------------------------------------------------------------- // open a file // bool Logfile::open(const char* szfile) { if (m_fp == 0) m_fp = new LogFileStream; return m_fp->open(szfile); } //----------------------------------------------------------------------------- // opens a file and prepares for appending // bool Logfile::append(const char* szfile) { // store a copy of the filename if (m_fp == 0) m_fp = new LogFileStream; return m_fp->append(szfile); } //----------------------------------------------------------------------------- //! flush the logfile void Logfile::flush() { if (m_fp) m_fp->flush(); if (m_ps) m_ps->flush(); } //----------------------------------------------------------------------------- //! close the logfile void Logfile::close() { if (m_fp) { m_fp->close(); delete m_fp; m_fp = 0; } } //----------------------------------------------------------------------------- // This function works like all other printf functions // with the exception that everything that is output to the file // is (optionally) also output to the screen. // void Logfile::printf(const char* sz, ...) { // get a pointer to the argument list va_list args; // make the message char sztxt[2048] = {0}; va_start(args, sz); vsnprintf(sztxt, sizeof(sztxt), sz, args); va_end(args); // print to file if (m_fp && (m_mode & LOG_FILE)) m_fp->print(sztxt); // print to screen if (m_ps && (m_mode & LOG_SCREEN)) m_ps->print(sztxt); } //----------------------------------------------------------------------------- // FUNCTION: Logfile::printbox // This function prints a message insided a box // void Logfile::printbox(const char* sztitle, const char* sz, ...) { // get a pointer to the argument list va_list args; // make the message char sztxt[1024] = {0}; va_start(args, sz); vsnprintf(sztxt, 1024, sz, args); va_end(args); // print the box char szmsg[1024] = {0}; char* ch = szmsg; snprintf(szmsg,sizeof(szmsg), "\n *************************************************************************\n"); ch += strlen(ch); // print the title if (sztitle) { int l = (int)strlen(sztitle); char left[60] = {0}; char right[60] = {0}; strncpy(left, sztitle, l/2); strncpy(right, sztitle+l/2, l - l/2); snprintf(ch,1024, " * %33s", left); ch += strlen(ch); snprintf(ch,1024, "%-36s *\n", right); ch += strlen(ch); // snprintf(ch,1024, " *%71s*\n", ""); ch += strlen(ch); } // print the message char* ct = sztxt, *cn; char tmp; do { cn = strchr(ct,'\n'); if (cn) *cn = 0; int l = (int)strlen(ct); bool wrap = false; int n = 69; if (l > 69) { while ((n > 0) && (ct[n] != ' ')) n--; if (n == 0) n = 69; tmp = ct[n]; ct[n] = 0; wrap = true; if (cn) *cn = '\n'; cn = ct + n; } snprintf(ch,1024," * %-69s *\n", ct); ch += strlen(ch); if (wrap) { ct[n] = tmp; } if (cn) ct = cn+1; } while (cn); // sprintf(ch," * *\n"); ch += strlen(ch); snprintf(ch,1024," *************************************************************************\n"); // print the message printf(szmsg); } //----------------------------------------------------------------------------- // Sets the Logfile mode. // Logfile::MODE Logfile::SetMode(Logfile::MODE mode) { MODE old = m_mode; m_mode = mode; return old; } //! get the loggin mode Logfile::MODE Logfile::GetMode() { return m_mode; }
C++
3D
febiosoftware/FEBio
FEBioLib/plugin.cpp
.cpp
11,885
399
/*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 "plugin.h" #include "FECore/FECoreKernel.h" #include "FECore/log.h" #ifdef WIN32 #include <direct.h> #endif #ifdef LINUX #include <dlfcn.h> #endif #ifdef __APPLE__ #include <dlfcn.h> #endif //============================================================================= // Typedefs of the plugin functions. // These are the functions that the plugin must implement extern "C" { typedef unsigned int (*PLUGIN_GETSDKVERSION)(); typedef void (*PLUGIN_INIT_FNC)(FECoreKernel&); typedef void (*PLUGIN_CLEANUP_FNC)(); typedef int (*PLUGIN_NUMCLASSES_FNC)(); typedef FECoreFactory* (*PLUGIN_GETFACTORY_FNC)(int i); typedef void (*PLUGIN_VERSION_FNC)(int&,int&,int&); } //============================================================================= // Wrappers for system calls #ifdef WIN32 FEBIO_PLUGIN_HANDLE LoadPlugin(const char* szfile) { return LoadLibraryA(szfile); } void* FindPluginFunc(FEBIO_PLUGIN_HANDLE ph, const char* szfunc) { return GetProcAddress(ph, szfunc); } bool UnloadPlugin(FEBIO_PLUGIN_HANDLE ph) { return (FreeLibrary(ph) == TRUE); } #endif #ifdef LINUX FEBIO_PLUGIN_HANDLE LoadPlugin(const char* szfile) { return dlopen(szfile, RTLD_NOW); } void* FindPluginFunc(FEBIO_PLUGIN_HANDLE ph, const char* szfunc) { return dlsym(ph, szfunc); } bool UnloadPlugin(FEBIO_PLUGIN_HANDLE ph) { return dlclose(ph) == 0; } #endif #ifdef __APPLE__ FEBIO_PLUGIN_HANDLE LoadPlugin(const char* szfile) { return dlopen(szfile, RTLD_NOW); } void* FindPluginFunc(FEBIO_PLUGIN_HANDLE ph, const char* szfunc) { return dlsym(ph, szfunc); } bool UnloadPlugin(FEBIO_PLUGIN_HANDLE ph) { return dlclose(ph) == 0; } #endif //============================================================================= // FEBioPlugin //============================================================================= FEBioPlugin::FEBioPlugin() { m_ph = 0; m_szname[0] = 0; m_version.major = 0; m_version.minor = 0; m_version.patch = 0; m_allocater_id = FECoreKernel::GetInstance().GenerateAllocatorID(); } //----------------------------------------------------------------------------- FEBioPlugin::~FEBioPlugin() { if (m_ph) UnLoad(); } //----------------------------------------------------------------------------- void FEBioPlugin::SetNameFromFilePath(const char* szfile) { const char* ch = strrchr(szfile, '\\'); if (ch==0) { ch = strrchr(szfile, '/'); if (ch==0) ch = szfile; else ch++; } else ch++; if (ch) strcpy(m_szname, ch); } //----------------------------------------------------------------------------- //! This function tries to load a plugin from file. //! \return Return values are: //! (0) success, //! (1) Failed to load the file, //! (2) Required plugin function PluginNumClasses not found (NOTE: as of 2.5 this error is not returned anymore since PluginNumClasses is obsolete) //! (3) Required plugin function PluginGetFactory not found, //! (4) Invalid number of classes returned by PluginNumClasses. //! (5) Required plugin function GetSDKVersion not found. //! (6) Invalid SDK version. int FEBioPlugin::Load(const char* szfile) { // Make sure the plugin is not loaded already assert(m_ph == 0); if (m_ph) return 0; // set the file name as the plugin name SetNameFromFilePath(szfile); // load the library FEBIO_PLUGIN_HANDLE ph = LoadPlugin(szfile); if (ph == NULL) return 1; // get the GetSDKVersion function PLUGIN_GETSDKVERSION pf_sdk = (PLUGIN_GETSDKVERSION) FindPluginFunc(ph, "GetSDKVersion"); if (pf_sdk == 0) { UnloadPlugin(ph); m_ph = 0; return 5; } // get the SDK version of the plugin unsigned int n = FE_SDK_VERSION; unsigned int version = pf_sdk(); if (version != FE_SDK_VERSION) { UnloadPlugin(ph); m_ph = 0; return 6; } // find the numclasses function PLUGIN_NUMCLASSES_FNC pfnc_cnt = (PLUGIN_NUMCLASSES_FNC) FindPluginFunc(ph, "PluginNumClasses"); // NOTE: As of 2.5, the PluginNumClasses is no longer required. // If it is not defined, the PluginGetFactory will be called until null is returned. // If it is defined, the behavior is as usual. // if (pfnc_cnt == 0) return 2; // find the GetFactory function PLUGIN_GETFACTORY_FNC pfnc_get = (PLUGIN_GETFACTORY_FNC) FindPluginFunc(ph, "PluginGetFactory"); // NOTE: As of 2.6, the PluginGetFactory function is optional. This is because the // REGISTER_FECORE_CLASS can be used to register a new plugin class in PluginInitialize. // if (pfnc_get == 0) return 3; // find the plugin's initialization function PLUGIN_INIT_FNC pfnc_init = (PLUGIN_INIT_FNC) FindPluginFunc(ph, "PluginInitialize"); // find the optional plugin version function PLUGIN_VERSION_FNC pfnc_version = (PLUGIN_VERSION_FNC) FindPluginFunc(ph, "GetPluginVersion"); if (pfnc_version) pfnc_version(m_version.major, m_version.minor, m_version.patch); // get the kernel FECoreKernel& febio = FECoreKernel::GetInstance(); // set the current allocater id febio.SetAllocatorID(m_allocater_id); // call the (optional) initialization function if (pfnc_init) { pfnc_init(febio); febio.SetActiveModule(0); } // find out how many classes there are in this plugin // This is only called when the PluginGetFactory function was found. // (As of 2.6, this is no longer a required function) if (pfnc_get) { if (pfnc_cnt) { int NC = pfnc_cnt(); // call the get factory functions for (int i=0; i<NC; ++i) { FECoreFactory* pfac = pfnc_get(i); if (pfac) { febio.RegisterFactory(pfac); } } } else { // As of 2.5, the PluginNumClasses is no longer required. // In this case, the PluginGetFactory is called until null is returned. FECoreFactory* pfac = 0; int i = 0; do { pfac = pfnc_get(i); if (pfac) { febio.RegisterFactory(pfac); i++; } } while (pfac); } } febio.SetAllocatorID(0); // If we get here everything seems okay so let's store the handle m_ph = ph; m_filepath = szfile; // a-ok! return 0; } //----------------------------------------------------------------------------- void FEBioPlugin::UnLoad() { if (m_ph) { // find the plugin's cleanup function PLUGIN_CLEANUP_FNC pfnc = (PLUGIN_CLEANUP_FNC) FindPluginFunc(m_ph, "PluginCleanup"); if (pfnc) pfnc(); // remove all features from the kernel that were added by the plugin FECoreKernel& febio = FECoreKernel::GetInstance(); febio.UnregisterFactories(m_allocater_id); // unregister the modules from the kernel that were added by the plugin febio.UnregisterModules(m_allocater_id); // unload the plugin from memory bool b = UnloadPlugin(m_ph); if (b == false) fprintf(stderr, "ERROR: Failed unloading plugin %s\n", m_szname); m_ph = 0; } } //============================================================================= // FEBioPluginManager //============================================================================= FEBioPluginManager* FEBioPluginManager::m_pThis = 0; FEBioPluginManager* FEBioPluginManager::GetInstance() { if (m_pThis == 0) m_pThis = new FEBioPluginManager; return m_pThis; } //----------------------------------------------------------------------------- FEBioPluginManager::~FEBioPluginManager() { // NOTE: I (S.M.) commented this out since for very small problems that run // very quickly, FEBio can crash when it unloads the plugins on Windows. // It looks like this is caused by some kind of race condition with Windows // dll management. // UnloadAllPlugins(); } //----------------------------------------------------------------------------- void FEBioPluginManager::DeleteThis() { delete m_pThis; m_pThis = 0; } //----------------------------------------------------------------------------- int FEBioPluginManager::Plugins() { return (int) m_Plugin.size(); } //----------------------------------------------------------------------------- const FEBioPlugin& FEBioPluginManager::GetPlugin(int i) { return *(m_Plugin[i]); } //----------------------------------------------------------------------------- //! This function tries to load a plugin and returns the error code from the //! FEBioPlugin::Load function. //! \return Returns zero on success, nonzero on failure. //! \sa FEBioPlugin::Load int FEBioPluginManager::LoadPlugin(const char* szfile, PLUGIN_INFO& info) { std::string sfile = szfile; // First, make sure this plugin does not exist yet for (int i=0; i<Plugins(); ++i) { const FEBioPlugin& pi = GetPlugin(i); if (pi.GetFilePath() == sfile) return 7; } // create a new plugin object FEBioPlugin* pdll = new FEBioPlugin; info.bloaded = false; info.major = 0; info.minor = 0; info.patch = 0; // try to load the plugin int nerr = pdll->Load(szfile); // add it to the list or delete it if error if (nerr == 0) { FEBioPlugin::Version version = pdll->GetVersion(); info.bloaded = true; info.major = version.major; info.minor = version.minor; info.patch = version.patch; m_Plugin.push_back(pdll); } else delete pdll; // pass error code to caller return nerr; } //----------------------------------------------------------------------------- bool FEBioPluginManager::UnloadPlugin(int n) { if ((n<0) || (n >= Plugins())) return false; std::vector<FEBioPlugin*>::iterator it = m_Plugin.begin() + n; (*it)->UnLoad(); m_Plugin.erase(it); return true; } //----------------------------------------------------------------------------- bool FEBioPluginManager::UnloadPlugin(const std::string& name) { const char* szname = name.c_str(); for (std::vector<FEBioPlugin*>::iterator it = m_Plugin.begin(); it != m_Plugin.end(); ++it) { if (strcmp((*it)->GetName(), szname) == 0) { (*it)->UnLoad(); delete *it; m_Plugin.erase(it); return true; } } return false; } //----------------------------------------------------------------------------- void FEBioPluginManager::UnloadAllPlugins() { for (size_t i = 0; i < m_Plugin.size(); ++i) delete m_Plugin[i]; m_Plugin.clear(); } /* //----------------------------------------------------------------------------- // Import all the plugins from a folder. The szdir is actually a folder name // plus a wildcard file reference (e.g. C:\folder\*.dll) bool LoadPluginFolder(const char* szdir) { WIN32_FIND_DATAA FileData; HANDLE hFind = FindFirstFileA(szdir, &FileData); LoadPlugin(FileData.cFileName); printf("Plugin \"%s\" loaded successfully\n", FileData.cFileName); while (FindNextFileA(hFind, &FileData)) { LoadPlugin(FileData.cFileName); printf("Plugin \"%s\" loaded successfully\n", FileData.cFileName); } return true; } */
C++
3D
febiosoftware/FEBio
FEBioLib/hello.cpp
.cpp
3,407
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.*/ #include "stdafx.h" #include "version.h" #include "LogStream.h" #include "febio.h" #include <stdio.h> int febio::Hello(LogStream& log) { char szversion[128] = { 0 }; char* szvernum = getVersionString(); snprintf(szversion, sizeof(szversion), " version %s\n", szvernum); log.print("===========================================================================\n"); log.print(" ________ _________ _______ __ _________ \n"); log.print(" | |\\ | |\\ | \\\\ | |\\ / \\\\ \n"); log.print(" | ____|| | ____|| | __ || |__|| | ___ || \n"); log.print(" | |\\___\\| | |\\___\\| | |\\_| || \\_\\| | // \\ || \n"); log.print(" | ||__ | ||__ | ||_| || | |\\ | || | || \n"); log.print(" | |\\ | |\\ | \\\\ | || | || | || \n"); log.print(" | ___|| | ___|| | ___ || | || | || | || \n"); log.print(" | |\\__\\| | |\\__\\| | |\\__| || | || | || | || \n"); log.print(" | || | ||___ | ||__| || | || | \\\\__/ || \n"); log.print(" | || | |\\ | || | || | || \n"); log.print(" |___|| |________|| |_________// |__|| \\_________// \n"); log.print(" \n"); log.print(" F I N I T E E L E M E N T S F O R B I O M E C H A N I C S \n"); log.print(" \n"); log.print(szversion); log.print(" FEBio is a registered trademark. \n"); log.print(" copyright (c) 2006-2026 - All rights reserved \n"); log.print(" \n"); log.print("===========================================================================\n"); log.print("\n"); return 0; }
C++
3D
febiosoftware/FEBio
FEBioLib/targetver.h
.h
2,029
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 // 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 _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
Unknown
3D
febiosoftware/FEBio
FEBioLib/febiolib_api.h
.h
1,531
44
/*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 febiolib_EXPORTS #define FEBIOLIB_API __declspec(dllexport) #else #define FEBIOLIB_API __declspec(dllimport) #endif #else #define FEBIOLIB_API #endif #else #define FEBIOLIB_API #endif
Unknown
3D
febiosoftware/FEBio
FEBioLib/cmdoptions.cpp
.cpp
7,784
296
/*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 "cmdoptions.h" #include "febio.h" #include <stdlib.h> std::vector< std::string > split_string(const std::string& s) { std::vector< std::string > args; std::string t; bool inquote = false; for (int n = 0; n < s.size(); ++n) { char c = s[n]; if (isspace(c) && (inquote== false)) { if (t.empty() == false) { args.push_back(t); t.clear(); } } else if (c == '\"') { if (inquote == false) inquote = true; else inquote = false; } else t.push_back(c); } if (t.empty() == false) { args.push_back(t); } return args; } bool febio::ProcessOptionsString(const std::string& s, CMDOPTIONS& ops) { // split the string std::vector< std::string > args = split_string(s); // set default options ops.ndebug = 0; ops.bsplash = true; ops.bsilent = false; ops.binteractive = true; // these flags indicate whether the corresponding file name // was defined on the command line. Otherwise, a default name will be generated. bool blog = false; bool bplt = false; bool bdmp = false; bool brun = true; // initialize file names ops.szfile[0] = 0; ops.szplt[0] = 0; ops.szlog[0] = 0; ops.szdmp[0] = 0; ops.sztask[0] = 0; ops.szctrl[0] = 0; ops.szimp[0] = 0; // set initial configuration file name if (ops.szcnf[0] == 0) { char szpath[1024] = { 0 }; febio::get_app_path(szpath, 1023); snprintf(ops.szcnf, sizeof(ops.szcnf), "%sfebio.xml", szpath); } // loop over the arguments int nargs = args.size(); for (int i = 1; i < nargs; ++i) { const char* sz = args[i].c_str(); if (strcmp(sz, "-r") == 0) { if (ops.sztask[0] != 0) { fprintf(stderr, "-r is incompatible with other command line option.\n"); return false; } strcpy(ops.sztask, "restart"); strcpy(ops.szctrl, args[++i].c_str()); ops.binteractive = false; } else if (strcmp(sz, "-noappend") == 0) { ops.bappendFiles = false; } else if (strcmp(sz, "-d") == 0) { if (ops.sztask[0] != 0) { fprintf(stderr, "-d is incompatible with other command line option.\n"); return false; } strcpy(ops.sztask, "diagnose"); strcpy(ops.szctrl, args[++i].c_str()); ops.binteractive = false; } else if (strcmp(sz, "-p") == 0) { bplt = true; strcpy(ops.szplt, args[++i].c_str()); } else if (strncmp(sz, "-dump", 5) == 0) { ops.dumpLevel = FE_DUMP_MAJOR_ITRS; if (sz[5] == '=') ops.dumpLevel = atoi(sz + 6); if ((ops.dumpLevel < 0) || (ops.dumpLevel > 3)) { fprintf(stderr, "FATAL ERROR: invalid restart level.\n"); return false; } if (i < nargs - 1) { const char* szi = args[i + 1].c_str(); if (szi[0] != '-') { // assume this is the name of the dump file strcpy(ops.szdmp, args[++i].c_str()); bdmp = true; } } } else if (strcmp(sz, "-o") == 0) { blog = true; strcpy(ops.szlog, args[++i].c_str()); } else if (strcmp(sz, "-i") == 0) { ++i; const char* szext = strrchr(sz, '.'); if (szext == 0) { // we assume a default extension of .feb if none is provided snprintf(ops.szfile, sizeof(ops.szfile), "%s.feb", sz); } else strcpy(ops.szfile, sz); ops.binteractive = false; } else if (strcmp(sz, "-s") == 0) { if (ops.sztask[0] != 0) { fprintf(stderr, "-s is incompatible with other command line option.\n"); return false; } strcpy(ops.sztask, "optimize"); strcpy(ops.szctrl, args[++i].c_str()); } else if ((strcmp(sz, "-g") == 0) || (strcmp(sz, "-g1") == 0)) { ops.ndebug = 1; } else if (strcmp(sz, "-g2") == 0) { ops.ndebug = 2; } else if (strcmp(sz, "-nosplash") == 0) { // don't show the welcome message ops.bsplash = false; } else if (strcmp(sz, "-silent") == 0) { // no output to screen ops.bsilent = true; } else if (strcmp(sz, "-cnf") == 0) // obsolete: use -config instead { strcpy(ops.szcnf, args[++i].c_str()); } else if (strcmp(sz, "-config") == 0) { strcpy(ops.szcnf, args[++i].c_str()); } else if (strcmp(sz, "-noconfig") == 0) { ops.szcnf[0] = 0; } else if (strncmp(sz, "-task", 5) == 0) { if (sz[5] != '=') { fprintf(stderr, "command line error when parsing task\n"); return false; } strcpy(ops.sztask, sz + 6); if (i < nargs - 1) { const char* szi = args[i + 1].c_str(); if (szi[0] != '-') { // assume this is a control file for the specified task strcpy(ops.szctrl, args[++i].c_str()); } } } else if (strcmp(sz, "-import") == 0) { strcpy(ops.szimp, args[++i].c_str()); } else if (sz[0] == '-') { fprintf(stderr, "FATAL ERROR: Invalid command line option '%s'.\n", sz); return false; } else { // if no input file is given yet, we'll assume this is the input file if (ops.szfile[0] == 0) { const char* szext = strrchr(sz, '.'); if (szext == 0) { // we assume a default extension of .feb if none is provided snprintf(ops.szfile, sizeof(ops.szfile), "%s.feb", sz); } else { strcpy(ops.szfile, sz); } ops.binteractive = false; } else { fprintf(stderr, "FATAL ERROR: Invalid command line option '%s'\n", sz); return false; } } } // do some sanity checks if (strcmp(ops.sztask, "optimize") == 0) { // make sure we have an input file if (ops.szfile[0] == 0) { fprintf(stderr, "FATAL ERROR: no model input file was defined (use -i to define the model input file)\n\n"); return false; } } // if no task is defined, we assume a std solve is wanted if (ops.sztask[0] == 0) strcpy(ops.sztask, "solve"); // derive the other filenames if (ops.szfile[0]) { char szbase[256]; strcpy(szbase, ops.szfile); char* ch = strrchr(szbase, '.'); if (ch) *ch = 0; char szlogbase[256]; if (ops.szctrl[0]) { strcpy(szlogbase, ops.szctrl); ch = strrchr(szlogbase, '.'); if (ch) *ch = 0; } else strcpy(szlogbase, szbase); if (!blog) snprintf(ops.szlog, sizeof(ops.szlog), "%s.log", szlogbase); if (!bplt) snprintf(ops.szplt, sizeof(ops.szplt), "%s.xplt", szbase); if (!bdmp) snprintf(ops.szdmp, sizeof(ops.szdmp), "%s.dmp", szbase); } else if (ops.szctrl[0]) { char szbase[256]; strcpy(szbase, ops.szfile); strcpy(szbase, ops.szctrl); char* ch = strrchr(szbase, '.'); if (ch) *ch = 0; if (!blog) snprintf(ops.szlog, sizeof(ops.szlog), "%s.log", szbase); if (!bplt) snprintf(ops.szplt, sizeof(ops.szplt), "%s.xplt", szbase); if (!bdmp) snprintf(ops.szdmp, sizeof(ops.szdmp), "%s.dmp", szbase); } return true; }
C++
3D
febiosoftware/FEBio
FEBioLib/cmdoptions.h
.h
2,815
88
/*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 "febiolib_api.h" #include <string> namespace febio { //! This structures stores the command line options that were input by the user struct FEBIOLIB_API CMDOPTIONS { enum { MAXFILE = 512 }; int ndebug; //!< debug flag bool bsplash; //!< show splash screen or not bool bsilent; //!< run FEBio in silent mode (no output to screen) bool binteractive; //!< start FEBio interactively bool bappendFiles; //!< append plot and log files on restart? bool bupdateTitle; //!< update the console title with progress info bool boutputLog; //!< write a log file int dumpLevel; //!< requested restart level int dumpStride; //!< (cold) restart file stride char szfile[MAXFILE]; //!< model input file name char szlog[MAXFILE]; //!< log file name char szplt[MAXFILE]; //!< plot file name char szdmp[MAXFILE]; //!< dump file name char szcnf[MAXFILE]; //!< configuration file char sztask[MAXFILE]; //!< task name char szctrl[MAXFILE]; //!< control file for tasks char szimp[MAXFILE]; //!< import file CMDOPTIONS() { defaults(); } void defaults() { ndebug = 0; bsplash = true; bsilent = false; binteractive = false; dumpLevel = 0; dumpStride = 1; bappendFiles = true; bupdateTitle = true; boutputLog = true; szfile[0] = 0; szlog[0] = 0; szplt[0] = 0; szdmp[0] = 0; szcnf[0] = 0; sztask[0] = 0; szctrl[0] = 0; szimp[0] = 0; } }; // process string for command line options FEBIOLIB_API bool ProcessOptionsString(const std::string& s, CMDOPTIONS& ops); }
Unknown
3D
febiosoftware/FEBio
FEBioLib/stdafx.h
.h
1,492
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 #ifdef WIN32 #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #endif // TODO: reference additional headers your program requires here
Unknown
3D
febiosoftware/FEBio
FEBioLib/input.cpp
.cpp
18,590
587
/*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 "FEBioModel.h" #include <FECore/FEAnalysis.h> #include <FECore/tens3d.h> #include <FEBioMech/FERigidJoint.h> #include <FEBioMech/FERigidSphericalJoint.h> #include <FEBioPlot/FEBioPlotFile.h> #include <FECore/FEMaterial.h> #include <FEBioMech/FERigidBody.h> #include <FECore/FEBoundaryCondition.h> #include <FECore/FEInitialCondition.h> #include <FECore/FENodalLoad.h> #include <FECore/FESurfaceLoad.h> #include <FECore/FEBodyLoad.h> #include <FECore/FEModelParam.h> #include <FECore/FELoadCurve.h> #include <FECore/FEMeshAdaptor.h> #include <FECore/FESurfacePairConstraint.h> #include <FECore/FETimeStepController.h> #include <FECore/log.h> #include <string.h> //----------------------------------------------------------------------------- // helper function to print a parameter to the logfile void FEBioModel::print_parameter(FEParam& p, int level) { char sz[512] = {0}; int l = (int)strlen(p.name()) + 2*level; snprintf(sz, sizeof(sz), "\t%*s %.*s", l, p.name(), 50-l, ".................................................."); if (p.dim() == 1) { switch (p.type()) { case FE_PARAM_DOUBLE : feLog("%s : %lg\n", sz, p.value<double>()); break; case FE_PARAM_INT : { if (p.enums()) { int n = p.value<int>(); const char* szkey = p.enumKey(); if (szkey) { feLog("%s : %s (%d)\n", sz, szkey, n); } else feLog("%s : %d\n", sz, n); } else feLog("%s : %d\n", sz, p.value<int >()); } break; case FE_PARAM_BOOL : feLog("%s : %s\n" , sz, (p.value<bool>() ? "yes (1)" : "no (0)")); break; case FE_PARAM_STRING : feLog("%s : %s\n" , sz, p.cvalue()); break; case FE_PARAM_STD_STRING: feLog("%s : %s\n", sz, p.value<string>().c_str()); break; case FE_PARAM_VEC3D : { vec3d v = p.value<vec3d>(); feLog("%s : %lg,%lg,%lg\n", sz, v.x, v.y, v.z); } break; case FE_PARAM_MAT3DS : { mat3ds m = p.value<mat3ds>(); feLog("%s : %lg,%lg,%lg,%lg,%lg,%lg\n", sz, m.xx(), m.yy(), m.zz(), m.xy(), m.yz(), m.xz()); } break; case FE_PARAM_MAT3D: { mat3d m = p.value<mat3d>(); feLog("%s : %lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg\n", sz, m(0,0), m(0,1), m(0,2), m(1,0), m(1,1), m(1,2), m(2,0), m(2,1), m(2,2)); } break; case FE_PARAM_TENS3DRS: { tens3drs m = p.value<tens3drs>(); double* d = m.d; feLog("%s : %lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg\n", sz,d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7],d[8],d[9],d[10],d[11],d[12],d[13],d[14],d[15],d[16],d[17]); } break; case FE_PARAM_DOUBLE_MAPPED: { FEParamDouble& v = p.value<FEParamDouble>(); if (v.isConst()) { double a = v.constValue(); feLog("%s : %lg\n", sz, a); } else feLog("%s : (not constant)\n", sz); } break; case FE_PARAM_VEC3D_MAPPED: { FEParamVec3& v = p.value<FEParamVec3>(); if (v.isConst()) { vec3d a = v.constValue(); feLog("%s : %lg, %lg, %lg\n", sz, a.x, a.y, a.z); } else feLog("%s : (not constant)\n", sz); } break; case FE_PARAM_STD_VECTOR_INT: { std::vector<int>& v = p.value<std::vector<int> >(); int nsize = (int)v.size(); int n = (nsize <= 5 ? nsize : 5); feLog("%s : ", sz); for (int i = 0; i < n; ++i) { feLog("%d", v[i]); if (i != n - 1) feLog(", "); } if (nsize > n) feLog(", ...\n"); else feLog("\n"); } break; default: feLog("%s : (can't display value)\n", sz); break; } } else { switch (p.type()) { case FE_PARAM_INT: case FE_PARAM_DOUBLE: { int n = p.dim(); feLog("%s : ", sz); for (int k=0; k<n; ++k) { switch (p.type()) { case FE_PARAM_INT : feLog("%d" , p.pvalue<int >()[k]); break; case FE_PARAM_DOUBLE: feLog("%lg", p.pvalue<double>()[k]); break; default: break; } if (k!=n-1) feLog(","); else feLog("\n"); } } break; case FE_PARAM_DOUBLE_MAPPED: { int n = p.dim(); feLog("%s : ", sz); for (int k = 0; k < n; ++k) { FEParamDouble& v = p.value<FEParamDouble>(k); if (v.isConst()) feLog("%lg", v.constValue()); else feLog("???"); if (k != n - 1) feLog(","); else feLog("\n"); } } break; default: break; } } } //----------------------------------------------------------------------------- // print the parameter list to the log file void FEBioModel::print_parameter_list(FEParameterList& pl, int level) { int n = pl.Parameters(); if (n > 0) { FEParamIterator it = pl.first(); for (int j = 0; j < n; ++j, ++it) { if (it->IsHidden() == false) { print_parameter(*it, level); } } } } //------------------------------------------------------------------------------ void FEBioModel::print_parameter_list(FECoreBase* pc, int level) { print_parameter_list(pc->GetParameterList(), level); for (int i=0; i<pc->PropertyClasses(); ++i) { FEProperty* prop = pc->PropertyClass(i); int n = prop->size(); for (int j=0; j<n; ++j) { feLog("\t%s: ", prop->GetName()); FECoreBase* pcj = prop->get(j); if (pcj) { feLog("(type: %s)\n", pcj->GetTypeStr()); print_parameter_list(pcj, level + 1); } else feLog("(unspecified)\n"); } } } //------------------------------------------------------------------------------ //! This function outputs the input data to the felog file. void FEBioModel::echo_input() { // get the FE mesh FEBioModel& fem = *this; FEMesh& mesh = GetMesh(); // print title feLog("%s\n\n", fem.GetTitle().c_str()); // print file info feLog(" FILES USED\n"); feLog("===========================================================================\n"); feLog("\tInput file : %s\n", fem.GetInputFileName().c_str()); feLog("\tPlot file : %s\n", fem.GetPlotFileName().c_str()); feLog("\tLog file : %s\n", fem.GetLogfileName().c_str()); feLog("\n\n"); // print mesh info feLog(" MESH INFO\n"); feLog("===========================================================================\n"); feLog("\tNumber of materials ............................ : %d\n", fem.Materials()); feLog("\tNumber of domains .............................. : %d\n", mesh.Domains()); feLog("\tNumber of nodes ................................ : %d\n", mesh.Nodes()); int nsolid = mesh.Elements(FE_DOMAIN_SOLID ); if (nsolid > 0) feLog("\tNumber of solid elements ....................... : %d\n", nsolid); int nshell = mesh.Elements(FE_DOMAIN_SHELL ); if (nshell > 0) feLog("\tNumber of shell elements ....................... : %d\n", nshell); int nbeam = mesh.Elements(FE_DOMAIN_BEAM ); if (nbeam > 0) feLog("\tNumber of beam elements ........................ : %d\n", nbeam ); int nelm2d = mesh.Elements(FE_DOMAIN_2D ); if (nelm2d > 0) feLog("\tNumber of 2D elements .......................... : %d\n", nelm2d); feLog("\n\n"); feLog(" MODULE\n"); feLog("===========================================================================\n"); string modName = fem.GetModuleName(); const char* szmod = modName.c_str(); if (szmod == 0) { szmod = "unknown"; assert(false); } feLog("\tModule type ....................................... : %s\n", szmod); feLog("\n\n"); // print control info if (fem.Steps() == 1) { // get the analysis step FEAnalysis& step = *fem.GetStep(0); feLog(" CONTROL DATA\n"); feLog("===========================================================================\n"); print_parameter_list(step.GetParameterList()); feLog("\tAuto time stepper activated ....................... : %s\n", (step.m_timeController ? "yes" : "no")); if (step.m_timeController) { FETimeStepController& tc = *step.m_timeController; print_parameter_list(tc.GetParameterList(), 1); } // output solver data feLog(" SOLVER PARAMETERS\n"); feLog("===========================================================================\n"); FESolver* psolver = step.GetFESolver(); if (psolver) { print_parameter_list(psolver->GetParameterList()); feLog("\n\n"); } } else { feLog(" STEP DATA\n"); feLog("===========================================================================\n"); for (int i = 0; i < fem.Steps(); ++i) { if (i > 0) feLog("---------------------------------------------------------------------------\n"); feLog("step %3d - ", i + 1); // get the step FEAnalysis* pstep = fem.GetStep(i); // get the name and type string const char* szname = pstep->GetName().c_str(); const char* sztype = pstep->GetTypeStr(); if (szname[0] == 0) szname = 0; // print type and name feLog("%s", (szname ? szname : "(noname)")); feLog(" (type: %s)", sztype); feLog("\n"); // print the parameter list print_parameter_list(pstep); } } feLog("\n\n"); // material data feLog("\n\n"); feLog(" MATERIAL DATA\n"); feLog("===========================================================================\n"); for (int i=0; i<fem.Materials(); ++i) { if (i>0) feLog("---------------------------------------------------------------------------\n"); feLog("%3d - ", i+1); // get the material FEMaterial* pmat = fem.GetMaterial(i); // get the material name and type string const char* szname = pmat->GetName().c_str(); const char* sztype = pmat->GetTypeStr(); if (szname[0] == 0) szname = 0; // print type and name feLog("%s", (szname?szname:"unknown")); feLog(" (type: %s)", sztype); feLog("\n"); // print the parameter list print_parameter_list(pmat); } feLog("\n\n"); if (fem.RigidBodies()) { feLog(" RIGID BODY DATA\n"); feLog("===========================================================================\n"); for (int i=0; i<fem.RigidBodies(); ++i) { FERigidBody& rb = *fem.GetRigidBody(i); if (i>0) feLog("---------------------------------------------------------------------------\n"); feLog("Rigid Body %d:\n", rb.m_nID+1); feLog("\tmaterial id : %d\n", rb.m_mat+1); feLog("\tname : %s\n", rb.GetName().c_str()); feLog("\tcenter of mass : %lg, %lg, %lg\n", rb.m_r0.x, rb.m_r0.y, rb.m_r0.z); feLog("\tmass : %lg\n", rb.m_mass); feLog("\tIxx Ixy Ixz : %lg, %lg, %lg\n", rb.m_moi.xx(), rb.m_moi.xy(), rb.m_moi.xz()); feLog("\tIxy Iyy Iyz : %lg, %lg, %lg\n", rb.m_moi.xy(), rb.m_moi.yy(), rb.m_moi.yz()); feLog("\tIxz Iyz Izz : %lg, %lg, %lg\n", rb.m_moi.xz(), rb.m_moi.yz(), rb.m_moi.zz()); } feLog("\n\n"); } if (fem.InitialConditions()) { feLog(" INITIAL CONDITION DATA\n"); feLog("===========================================================================\n"); for (int i = 0; i < fem.InitialConditions(); ++i) { if (i > 0) feLog("---------------------------------------------------------------------------\n"); feLog("%3d - ", i + 1); // get the initial condition FEInitialCondition* pic = fem.InitialCondition(i); // get the type string const char* sztype = pic->GetTypeStr(); if (sztype == 0) sztype = "unknown"; feLog(" Type: %s\n", sztype); // print the parameter list FEParameterList& pl = pic->GetParameterList(); print_parameter_list(pl); } feLog("\n\n"); } if (fem.BoundaryConditions()) { feLog(" BOUNDARY CONDITION DATA\n"); feLog("===========================================================================\n"); for (int i = 0; i < fem.BoundaryConditions(); ++i) { if (i > 0) feLog("---------------------------------------------------------------------------\n"); feLog("%3d - ", i + 1); // get the bc FEBoundaryCondition* pbc = fem.BoundaryCondition(i); // get the type string const char* sztype = pbc->GetTypeStr(); if (sztype == 0) sztype = "unknown"; feLog(" Type: %s\n", sztype); // print the parameter list FEParameterList& pl = pbc->GetParameterList(); print_parameter_list(pl); } feLog("\n\n"); } if (fem.ModelLoads()) { feLog(" MODEL LOAD DATA\n"); feLog("===========================================================================\n"); for (int i = 0; i < fem.ModelLoads(); ++i) { if (i > 0) feLog("---------------------------------------------------------------------------\n"); feLog("%3d - ", i + 1); // get the model load FEModelLoad* pml = fem.ModelLoad(i); // get the type string const char* sztype = pml->GetTypeStr(); if (sztype == 0) sztype = "unknown"; feLog(" Type: %s\n", sztype); // print the parameter list FEParameterList& pl = pml->GetParameterList(); print_parameter_list(pl); } feLog("\n\n"); } if (fem.SurfacePairConstraints() > 0) { feLog(" CONTACT INTERFACE DATA\n"); feLog("===========================================================================\n"); for (int i = 0; i<fem.SurfacePairConstraints(); ++i) { if (i>0) feLog("---------------------------------------------------------------------------\n"); FESurfacePairConstraint* pi = fem.SurfacePairConstraint(i); const char* sztype = pi->GetTypeStr(); if (sztype == 0) sztype = "unknown"; feLog("contact interface %d - Type: %s\n", i+1, sztype); FEParameterList& pl = pi->GetParameterList(); print_parameter_list(pl); } feLog("\n\n"); } if (fem.NonlinearConstraints() != 0) { feLog(" NONLINEAR CONSTRAINT DATA\n"); feLog("===========================================================================\n"); int NC = fem.NonlinearConstraints(); for (int i = 0; i<NC; ++i) { FENLConstraint* plc = fem.NonlinearConstraint(i); assert(plc); const char* sztype = plc->GetTypeStr(); if (sztype == 0) sztype = "unknown"; feLog("\nnonlinear constraint %d - Type: %s\n", i + 1, sztype); FEParameterList& pl = plc->GetParameterList(); print_parameter_list(pl); } feLog("\n\n"); } if (fem.MeshAdaptors()) { feLog(" MESH ADAPTOR DATA\n"); feLog("===========================================================================\n"); int NMA = fem.MeshAdaptors(); for (int i = 0; i < NMA; ++i) { if (i > 0) feLog("---------------------------------------------------------------------------\n"); FEMeshAdaptor* pma = fem.MeshAdaptor(i); assert(pma); const char* sztype = pma->GetTypeStr(); if (sztype == 0) sztype = "unknown"; feLog("\nmesh adaptor %d - Type: %s\n", i + 1, sztype); FEParameterList& pl = pma->GetParameterList(); print_parameter_list(pl); } feLog("\n\n"); } feLog(" LOAD CONTROLLER DATA\n"); feLog("===========================================================================\n"); for (int i = 0; i < fem.LoadControllers(); ++i) { if (i > 0) feLog("---------------------------------------------------------------------------\n"); feLog("load controller %3d - ", i + 1); // get the load controller FELoadController* plc = fem.GetLoadController(i); // get the name and type string const char* szname = plc->GetName().c_str(); const char* sztype = plc->GetTypeStr(); if (szname[0] == 0) szname = 0; // print type and name feLog("%s", (szname ? szname : "(noname)")); feLog(" (type: %s)", sztype); feLog("\n"); // print the parameter list print_parameter_list(plc); } feLog("\n\n"); // print output data feLog(" OUTPUT DATA\n"); feLog("===========================================================================\n"); PlotFile* pplt = fem.GetPlotFile(); if (dynamic_cast<FEBioPlotFile*>(pplt)) { FEBioPlotFile* pf = dynamic_cast<FEBioPlotFile*>(pplt); feLog("\tplotfile format ........................... : FEBIO\n"); FEBioPlotFile::Dictionary& dic = pf->GetDictionary(); for (int i = 0; i < 5; ++i) { list<FEBioPlotFile::DICTIONARY_ITEM>* pl = 0; const char* szn = 0; switch (i) { case 0: pl = &dic.GlobalVariableList(); szn = "Global Variables"; break; case 1: pl = &dic.MaterialVariableList(); szn = "Material Variables"; break; case 2: pl = &dic.NodalVariableList(); szn = "Nodal Variables"; break; case 3: pl = &dic.DomainVariableList(); szn = "Domain Variables"; break; case 4: pl = &dic.SurfaceVariableList(); szn = "Surface Variables"; break; } if (!pl->empty()) { feLog("\t\t%s:\n", szn); list<FEBioPlotFile::DICTIONARY_ITEM>::const_iterator it; for (it = pl->begin(); it != pl->end(); ++it) { const char* szt = 0; switch (it->m_ntype) { case PLT_FLOAT: szt = "float"; break; case PLT_VEC3F: szt = "vec3f"; break; case PLT_MAT3FS: szt = "mat3fs"; break; case PLT_MAT3FD: szt = "mat3fd"; break; case PLT_TENS4FS: szt = "tens4fs"; break; case PLT_MAT3F: szt = "mat3f"; break; } const char* szf = 0; switch (it->m_nfmt) { case FMT_NODE: szf = "NODE"; break; case FMT_ITEM: szf = "ITEM"; break; case FMT_MULT: szf = "COMP"; break; case FMT_REGION: szf = "REGION"; break; } feLog("\t\t\t%-20s (type = %5s, format = %4s)\n", it->m_szname, szt, szf); } } } } FECoreKernel& fecore = FECoreKernel::GetInstance(); feLog(" LINEAR SOLVER DATA\n"); feLog("===========================================================================\n"); feLog("\tDefault linear solver ............................. : %s\n", fecore.GetLinearSolverType()); FECoreFactory* fac = fecore.FindFactoryClass(FELINEARSOLVER_ID, fecore.GetLinearSolverType()); if (fac) print_parameter_list(fac->GetParameterList()); feLog("\n"); }
C++
3D
febiosoftware/FEBio
FEBioLib/config.cpp
.cpp
15,591
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 "febio.h" #include <FEBioXML/XMLReader.h> #include <FEBioXML/xmltool.h> #include <FECore/FEModel.h> #include <FECore/FECoreTask.h> #include <FECore/FEMaterial.h> #include <NumCore/MatrixTools.h> #include <FECore/LinearSolver.h> #include <FEBioTest/FEMaterialTest.h> #include "plugin.h" #include <map> #include <iostream> #ifndef WIN32 #include <dlfcn.h> #endif #ifdef HAS_STD_FILESYSTEM #include <filesystem> namespace fs = std::filesystem; #endif namespace febio { //----------------------------------------------------------------------------- bool parse_tags(XMLTag& tag, bool readPlugins); bool parse_default_linear_solver(XMLTag& tag); bool parse_import(XMLTag& tag); bool parse_import_folder(XMLTag& tag); bool parse_repo_plugins(XMLTag& tag); bool parse_set(XMLTag& tag); bool parse_output_negative_jacobians(XMLTag& tag); // create a map for the variables (defined with set) static std::map<string, string> vars; static bool boutput = true; //----------------------------------------------------------------------------- // configure FEBio bool Configure(const char* szfile, FEBioConfig& config) { vars.clear(); boutput = (config.m_noutput != 0); // open the configuration file XMLReader xml; if (xml.Open(szfile) == false) { fprintf(stderr, "FATAL ERROR: Failed reading FEBio configuration file %s.", szfile); return false; } bool readPlugins = config.readPlugins; if (readPlugins) { // unload all plugins before reading new ones FEBioPluginManager& pm = *FEBioPluginManager::GetInstance(); pm.UnloadAllPlugins(); } // loop over all child tags try { // Find the root element XMLTag tag; if (xml.FindTag("febio_config", tag) == false) return false; const char* szversion = tag.AttributeValue("version"); if (strcmp(szversion, "3.0") == 0) { if (!tag.isleaf()) { // Read version 1.0 ++tag; do { // parse the tags if (tag == "if_debug") { #ifndef NDEBUG ++tag; if (parse_tags(tag, readPlugins) == false) return false; ++tag; #else tag.skip(); #endif // NDEBUG } else if (tag == "if_release") { #ifdef NDEBUG ++tag; if (parse_tags(tag, readPlugins) == false) return false; ++tag; #else tag.skip(); #endif // NDEBUG } else if (tag == "print_model_params") { tag.value(config.m_printParams); } else if (tag == "show_warnings_and_errors") { tag.value(config.m_bshowErrors); } else { if (parse_tags(tag, readPlugins) == false) return false; } ++tag; } while (!tag.isend()); } } else { fprintf(stderr, "FATAL ERROR: Invalid version for FEBio configuration file."); return false; } } catch (XMLReader::Error& e) { fprintf(stderr, "FATAL ERROR: %s\n", e.what()); return false; } catch (...) { fprintf(stderr, "FATAL ERROR: unrecoverable error (line %d)", xml.GetCurrentLine()); return false; } xml.Close(); return true; } //----------------------------------------------------------------------------- bool parse_tags(XMLTag& tag, bool readPlugins) { if (tag == "set") { if (parse_set(tag) == false) return false; } else if (tag == "default_linear_solver") { if (parse_default_linear_solver(tag) == false) return false; } else if (tag == "import") { if (readPlugins) { if (parse_import(tag) == false) return false; } else tag.skip(); } else if (tag == "import_folder") { if (readPlugins) { if (parse_import_folder(tag) == false) return false; } else tag.skip(); } else if (tag == "repo_plugin_xml") { if (readPlugins) { if (parse_repo_plugins(tag) == false) return false; } else tag.skip(); } else if (tag == "output_negative_jacobians") { if (parse_output_negative_jacobians(tag) == false) return false; } else throw XMLReader::InvalidTag(tag); return true; } //----------------------------------------------------------------------------- bool parse_set(XMLTag& tag) { char szname[256] = { 0 }; strcpy(szname, tag.AttributeValue("name")); string key(szname); string val(tag.szvalue()); vars[key] = val; return true; } //----------------------------------------------------------------------------- bool parse_output_negative_jacobians(XMLTag& tag) { int n; tag.value(n); NegativeJacobian::m_maxout = n; return true; } //----------------------------------------------------------------------------- bool parse_default_linear_solver(XMLTag& tag) { const char* szt = tag.AttributeValue("type"); // read the solver parameters FEClassDescriptor* cd = fexml::readParameterList(tag); if (cd == nullptr) { delete cd; return false; } else { // set this as the default solver FECoreKernel& fecore = FECoreKernel::GetInstance(); fecore.SetDefaultSolver(cd); } return true; } //----------------------------------------------------------------------------- bool process_aliases(char* szout, const char* szbuf) { bool bok = true; char sztmp[64] = { 0 }; const char* ch = szbuf; char* s = szout; while (*ch) { if (*ch == '$') { ++ch; if (*ch++ == '(') { const char* ch2 = strchr(ch, ')'); if (ch2) { int l = (int)(ch2 - ch); strncpy(sztmp, ch, l); sztmp[l] = 0; string key(sztmp); ch = ch2 + 1; std::map<string, string>::iterator it = vars.find(key); if (it != vars.end()) { string v = it->second; const char* sz = v.c_str(); while (*sz) *s++ = *sz++; } else { bok = false; break; } } else { bok = false; break; } } else { bok = false; break; } } else *s++ = *ch++; } return bok; } //----------------------------------------------------------------------------- bool parse_import(XMLTag& tag) { // get the file name const char* szfile = tag.szvalue(); // process any aliases char szbuf[1024] = { 0 }; bool bok = process_aliases(szbuf, szfile); // load the plugin if (bok) febio::ImportPlugin(szbuf); return bok; } //----------------------------------------------------------------------------- bool parse_import_folder(XMLTag& tag) { // get the folder name const char* szfolder = tag.szvalue(); // process any aliases char szbuf[1024] = { 0 }; bool bok = process_aliases(szbuf, szfolder); // load the plugin if (bok) bok = febio::ImportPluginFolder(szbuf); return bok; } //----------------------------------------------------------------------------- bool parse_repo_plugins(XMLTag& tag) { // get the file name const char* szfile = tag.szvalue(); // process any aliases char szbuf[1024] = { 0 }; bool bok = process_aliases(szbuf, szfile); // load the plugin if (bok) febio::ImportRepoPlugins(szbuf); return bok; } //----------------------------------------------------------------------------- const char* GetFileTitle(const char* szfile) { const char* ch = strrchr(szfile, '\\'); if (ch == 0) { ch = strrchr(szfile, '/'); if (ch == 0) ch = szfile; else ch++; } else ch++; return ch; } //----------------------------------------------------------------------------- bool ImportPlugin(const char* szfile) { const char* sztitle = GetFileTitle(szfile); FEBioPluginManager* pPM = FEBioPluginManager::GetInstance(); PLUGIN_INFO info; int nerr = pPM->LoadPlugin(szfile, info); switch (nerr) { case 0: if (boutput) fprintf(stderr, "Success loading plugin %s (version %d.%d.%d)\n", sztitle, info.major, info.minor, info.patch); return true; break; case 1: fprintf(stderr, "Failed loading plugin %s\n Reason: Failed to load the file.\n\n", szfile); #ifndef WIN32 fprintf(stderr, "dlopen failed: %s\n\n", dlerror()); #endif break; case 2: fprintf(stderr, "Failed loading plugin %s\n Reason: Required plugin function PluginNumClasses not found.\n\n", szfile); break; case 3: fprintf(stderr, "Failed loading plugin %s\n Reason: Required plugin function PluginGetFactory not found.\n\n", szfile); break; case 4: fprintf(stderr, "Failed loading plugin %s\n Reason: Invalid number of classes returned by PluginNumClasses.\n\n", szfile); break; case 5: fprintf(stderr, "Failed loading plugin %s\n Reason: Required plugin function GetSDKVersion not found.\n\n", szfile); break; case 6: fprintf(stderr, "Failed loading plugin %s\n Reason: Invalid SDK version.\n\n", szfile); break; case 7: fprintf(stderr, "Failed loading plugin %s\n Reason: Plugin is already loaded.\n\n", szfile); break; default: fprintf(stderr, "Failed loading plugin %s\n Reason: unspecified.\n\n", szfile); break; } return false; } //----------------------------------------------------------------------------- bool ImportPluginFolder(const char* szfolder) { #ifdef HAS_STD_FILESYSTEM // get the default (system-dependant) extension #ifdef WIN32 std::string extension = ".dll"; #elif __APPLE__ std::string extension = ".dylib"; #else std::string extension = ".so"; #endif for (const auto& entry : fs::directory_iterator(szfolder)) { if (entry.is_regular_file() && entry.path().extension() == extension) { // try to load the plugin bool ok = ImportPlugin(entry.path().string().c_str()); if(!ok) return false; } } return true; #else fprintf(stderr, "This version of FEBio does not support the import_folder tag.\n"); return false; #endif } void ImportRepoPlugins(const char* szxmlFile) { XMLReader xml; if (xml.Open(szxmlFile)) { XMLTag tag; if(!xml.FindTag("plugins", tag)) return; if(!tag.isleaf()) { ++tag; do { if(tag == "plugin") { int ID = tag.AttributeValue("ID", 0); if(!tag.isleaf()) { ++tag; do { if (tag == "file") { int main = tag.AttributeValue("main", 1); std::string filePath; tag.value(filePath); if(main == 1) { ImportPlugin(filePath.c_str()); } } ++tag; } while(!tag.isend()); } } ++tag; } while(!tag.isend()); } } } //----------------------------------------------------------------------------- FEBIOLIB_API const char* GetPluginName(int allocId) { FEBioPluginManager& pm = *FEBioPluginManager::GetInstance(); for (int i = 0; i < pm.Plugins(); ++i) { const FEBioPlugin& pi = pm.GetPlugin(i); if (pi.GetAllocatorID() == allocId) { return pi.GetName(); } } return nullptr; } //----------------------------------------------------------------------------- // run an FEBioModel FEBIOLIB_API bool SolveModel(FEBioModel& fem, const char* sztask, const char* szctrl) { // Make sure we have a task if (sztask == nullptr) sztask = "solve"; // find a task FECoreTask* ptask = fecore_new<FECoreTask>(sztask, &fem); if (ptask == 0) { fprintf(stderr, "Don't know how to do task: %s\n", sztask); return false; } // initialize the task if (ptask->Init(szctrl) == false) { fprintf(stderr, "Failed initializing the task: %s\n", sztask); return false; } // run the task bool bret = true; try { bret = ptask->Run(); } catch (std::exception e) { fprintf(stderr, "\nException detected: %s\n\n", e.what()); bret = false; } return bret; } //----------------------------------------------------------------------------- // run an FEBioModel FEBIOLIB_API int RunModel(FEBioModel& fem, CMDOPTIONS* ops) { // set options that were passed on the command line if (ops) { fem.SetDebugLevel(ops->ndebug); fem.SetDumpLevel(ops->dumpLevel); // set the output filenames fem.SetLogFilename(ops->szlog); fem.SetPlotFilename(ops->szplt); fem.SetDumpFilename(ops->szdmp); } // read the input file if specified int nret = 0; if (ops && ops->szfile[0]) { // read the input file if (fem.Input(ops->szfile) == false) nret = 1; } // solve the model with the task and control file if (nret == 0) { const char* sztask = (ops && ops->sztask[0] ? ops->sztask : nullptr); const char* szctrl = (ops && ops->szctrl[0] ? ops->szctrl : nullptr); bool b = febio::SolveModel(fem, sztask, szctrl); nret = (b ? 0 : 1); } return nret; } // write a matrix to file bool write_hb(CompactMatrix& K, const char* szfile, int mode) { return NumCore::write_hb(K, szfile, mode); } // print matrix sparsity pattern to svn file void print_svg(CompactMatrix* m, std::ostream &out, int i0, int j0, int i1, int j1) { NumCore::print_svg(m, out, i0, j0, i1, j1); } // write a vector to file bool write_vector(const vector<double>& a, const char* szfile, int mode) { return NumCore::write_vector(a, szfile, mode); } bool RunMaterialTest(FEMaterial* mat, double simtime, int steps, double strain, const char* sztest, std::vector<pair<double, double> >& out) { FEModel fem; FEMaterial* matcopy = dynamic_cast<FEMaterial*>(CopyFEBioClass(mat, &fem)); if (matcopy == nullptr) return false; fem.AddMaterial(matcopy); FECoreKernel& febio = FECoreKernel::GetInstance(); FEMaterialTest diag(&fem); diag.SetOutputFileName(nullptr); FEDiagnosticScenario* s = diag.CreateScenario(sztest); s->GetParameterList(); s->SetParameter<double>("strain", strain); FEAnalysis* step = fem.GetStep(0); step->m_ntime = steps; step->m_dt0 = simtime / steps; fem.SetCurrentStepIndex(0); if (diag.Init() == false) return false; if (fem.Init() == false) return false; bool b = diag.Run(); if (b) { out = diag.GetOutputData(); } return b; } } // namespace febio
C++
3D
febiosoftware/FEBio
FEBioLib/febio.h
.h
3,370
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.*/ #pragma once #include <cstddef> #include "febiolib_api.h" #include "FEBioModel.h" #include "FEBioConfig.h" #include "cmdoptions.h" #include <ostream> class CompactMatrix; class LogStream; //----------------------------------------------------------------------------- // Defines the FEBio namespace namespace febio { // get the kernel FEBIOLIB_API FECoreKernel* GetFECoreKernel(); // Initialize all the FEBio modules FEBIOLIB_API void InitLibrary(); // read the configuration file FEBIOLIB_API bool Configure(const char* szfile, FEBioConfig& config); // load a plugin FEBIOLIB_API bool ImportPlugin(const char* szfile); // load all the plugins in a folder FEBIOLIB_API bool ImportPluginFolder(const char* szfolder); // load the plugins as defined in the repo's XML file FEBIOLIB_API void ImportRepoPlugins(const char* szxmlFile); // get the name of the plugin from its allocator Id FEBIOLIB_API const char* GetPluginName(int allocId); // call this to clean up all FEBio data FEBIOLIB_API void FinishLibrary(); // helper function for retrieving the executable's path FEBIOLIB_API int get_app_path(char *pname, size_t pathsize); // print hello message FEBIOLIB_API int Hello(LogStream& log); // set the number of OMP threads FEBIOLIB_API void SetOMPThreads(int n); // run an FEBioModel FEBIOLIB_API bool SolveModel(FEBioModel& fem, const char* sztask = nullptr, const char* szctrl = nullptr); // run an FEBioModel FEBIOLIB_API int RunModel(FEBioModel& fem, CMDOPTIONS* ops); // write a matrix to file FEBIOLIB_API bool write_hb(CompactMatrix& K, const char* szfile, int mode = 0); // print matrix sparsity pattern to svn file FEBIOLIB_API void print_svg(CompactMatrix* m, std::ostream &out, int i0 = 0, int j0 = 0, int i1 = -1, int j1 = -1); // write a vector to file FEBIOLIB_API bool write_vector(const vector<double>& a, const char* szfile, int mode = 0); // run a material test FEBIOLIB_API bool RunMaterialTest(FEMaterial* mat, double simtime, int steps, double strain, const char* sztest, std::vector<pair<double, double> >& out); }
Unknown
3D
febiosoftware/FEBio
FEBioLib/LogStream.cpp
.cpp
1,607
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.*/ #include "stdafx.h" #include "LogStream.h" #include <stdarg.h> #include <stdio.h> void LogStream::printf(const char* sz, ...) { // get a pointer to the argument list va_list args; // make the message char sztxt[1024] = { 0 }; va_start(args, sz); vsnprintf(sztxt, sizeof(sztxt), sz, args); va_end(args); print(sztxt); }
C++
3D
febiosoftware/FEBio
FEBioLib/FEBox.cpp
.cpp
3,257
119
/*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 "FEBox.h" #include "FEBioMech/FEElasticSolidDomain.h" #include <FECore/FEModel.h> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// FEBoxMesh::FEBoxMesh(FEModel* fem) : FEMesh(fem) { } FEBoxMesh::~FEBoxMesh() { } void FEBoxMesh::Create(int nx, int ny, int nz, vec3d r0, vec3d r1, FE_Element_Type nhex) { int i, j, k, n; // make sure the parameters make sense assert((nx > 0) && (ny > 0) && (nz > 0)); // count items int nodes = (nx+1)*(ny+1)*(nz+1); int elems = nx*ny*nz; // allocate data FEMesh::CreateNodes(nodes); FEModel* fem = GetFEModel(); int MAX_DOFS = fem->GetDOFS().GetTotalDOFS(); FEMesh::SetDOFS(MAX_DOFS); // create the nodes double x, y, z; n = 0; for (i=0; i<=nx; ++i) { x = r0.x + ((r1.x - r0.x)*i)/nx; for (j=0; j<=ny; ++j) { y = r0.y + ((r1.y - r0.y)*j)/ny; for (k=0; k<=nz; ++k, ++n) { z = r0.z + ((r1.z - r0.z)*k)/nz; FENode& node = Node(n); node.m_r0 = vec3d(x, y, z); node.m_rt = node.m_r0; } } } // create the elements int *en; n = 0; FEElasticSolidDomain* pbd = new FEElasticSolidDomain(fem); pbd->Create(elems, FEElementLibrary::GetElementSpecFromType(nhex)); pbd->SetMatID(-1); AddDomain(pbd); for (i=0; i<nx; ++i) { for (j=0; j<ny; ++j) { for (k=0; k<nz; ++k, ++n) { FESolidElement& el = pbd->Element(n); el.SetID(n+1); en = &el.m_node[0]; en[0] = (i )*(ny+1)*(nz+1) + (j )*(nz+1) + (k ); en[1] = (i+1)*(ny+1)*(nz+1) + (j )*(nz+1) + (k ); en[2] = (i+1)*(ny+1)*(nz+1) + (j+1)*(nz+1) + (k ); en[3] = (i )*(ny+1)*(nz+1) + (j+1)*(nz+1) + (k ); en[4] = (i )*(ny+1)*(nz+1) + (j )*(nz+1) + (k+1); en[5] = (i+1)*(ny+1)*(nz+1) + (j )*(nz+1) + (k+1); en[6] = (i+1)*(ny+1)*(nz+1) + (j+1)*(nz+1) + (k+1); en[7] = (i )*(ny+1)*(nz+1) + (j+1)*(nz+1) + (k+1); } } } }
C++
3D
febiosoftware/FEBio
FEBioLib/FEBioModel.cpp
.cpp
61,476
1,992
/*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 "FEBioModel.h" #include "FEBioPlot/FEBioPlotFile.h" #include "FEBioPlot/VTKPlotFile.h" #include "FEBioXML/FEBioImport.h" #include "FEBioXML/FERestartImport.h" #include <FECore/NodeDataRecord.h> #include <FECore/FaceDataRecord.h> #include <FECore/ElementDataRecord.h> #include <FECore/SurfaceDataRecord.h> #include <FECore/DomainDataRecord.h> #include <FECore/FEModelDataRecord.h> #include <FEBioMech/ObjectDataRecord.h> #include <FECore/NLConstraintDataRecord.h> #include <FEBioMech/FERigidConnector.h> #include <FEBioMech/FEGenericRigidJoint.h> #include <FEBioMech/FERigidSphericalJoint.h> #include <FEBioMech/FERigidPrismaticJoint.h> #include <FEBioMech/FERigidRevoluteJoint.h> #include <FEBioMech/FERigidCylindricalJoint.h> #include <FEBioMech/FERigidPlanarJoint.h> #include <FEBioMech/FERigidDamper.h> #include <FEBioMech/FERigidSpring.h> #include <FEBioMech/FERigidAngularDamper.h> #include <FEBioMech/FERigidContractileForce.h> #include "FEBioModelBuilder.h" #include "FECore/log.h" #include "FECore/FECoreKernel.h" #include "FECore/DumpFile.h" #include "FECore/DOFS.h" #include <FECore/FEAnalysis.h> #include <NumCore/MatrixTools.h> #include <FECore/LinearSolver.h> #include <FECore/FEDomain.h> #include <FECore/FEMaterial.h> #include <FECore/FEPlotDataStore.h> #include <FECore/FETimeStepController.h> #include "febio.h" #include "version.h" #include <iostream> #include <sstream> #include <fstream> #include <functional> #ifdef WIN32 size_t FEBIOLIB_API GetPeakMemory(); // in memory.cpp #endif //----------------------------------------------------------------------------- BEGIN_FECORE_CLASS(FEBioModel, FEMechModel) ADD_PARAMETER(m_title , "title" ); ADD_PARAMETER(m_logLevel, "log_level"); END_FECORE_CLASS(); //----------------------------------------------------------------------------- // echo the input data to the log file extern void echo_input(FEBioModel& fem); bool FEBioModel::handleCB(FEModel* fem, int unsigned nwhen, void* pd) { FEBioModel* febioModel = (FEBioModel*)pd; return febioModel->processEvent(nwhen); } //----------------------------------------------------------------------------- bool FEBioModel::processEvent(int nevent) { // write output files (but not while serializing) if ((nevent == CB_SERIALIZE_LOAD) || (nevent == CB_SERIALIZE_SAVE)) return true; Write(nevent); // process event handlers switch (nevent) { case CB_STEP_SOLVED: on_cb_stepSolved(); break; case CB_SOLVED : on_cb_solved(); break; case CB_MAJOR_ITERS: case CB_TIMESTEP_FAILED: { FEAnalysis* step = GetCurrentStep(); FESolver* solver = step->GetFESolver(); TimeStepStats stats = {solver->m_niter, solver->m_nrhs, solver->m_nref, (nevent== CB_MAJOR_ITERS?1:0)}; m_timestepStats.push_back(stats); } break; } return true; } //----------------------------------------------------------------------------- // Constructor of FEBioModel class. FEBioModel::FEBioModel() { m_logLevel = 1; m_dumpLevel = FE_DUMP_NEVER; m_dumpStride = 1; // --- I/O-Data --- m_ndebug = 0; m_becho = true; m_plot = nullptr; m_writeMesh = false; m_createReport = false; m_pltAppendOnRestart = true; m_lastUpdate = -1; m_bshowErrors = true; // Add the output callback // We call this function always since we want to flush the logfile for each event. AddCallback(handleCB, CB_ALWAYS, this); } //----------------------------------------------------------------------------- FEBioModel::~FEBioModel() { // close the plot file if (m_plot) { delete m_plot; m_plot = 0; } m_log.close(); } //----------------------------------------------------------------------------- void FEBioModel::ShowWarningsAndErrors(bool b) { m_bshowErrors = b; } //----------------------------------------------------------------------------- bool FEBioModel::ShowWarningsAndErrors() const { return m_bshowErrors; } //----------------------------------------------------------------------------- Timer& FEBioModel::GetSolveTimer() { return *GetTimer(Timer_ModelSolve); } //----------------------------------------------------------------------------- //! set the debug level void FEBioModel::SetDebugLevel(int debugLvl) { m_ndebug = debugLvl; } //! get the debug level int FEBioModel::GetDebugLevel() { return m_ndebug; } //! set the dump level (for cold restarts) void FEBioModel::SetDumpLevel(int dumpLevel) { m_dumpLevel = dumpLevel; } //! get the dump level int FEBioModel::GetDumpLevel() const { return m_dumpLevel; } //! Set the dump stride void FEBioModel::SetDumpStride(int n) { m_dumpStride = n; } //! get the dump stride int FEBioModel::GetDumpStride() const { return m_dumpStride; } //! Set the log level void FEBioModel::SetLogLevel(int logLevel) { m_logLevel = logLevel; } //! Get the stats ModelStats FEBioModel::GetModelStats() const { return m_modelStats; } ModelStats FEBioModel::GetStepStats(size_t n) const { return m_stepStats[n]; } std::vector<ModelStats> FEBioModel::GetStepStats() const { return m_stepStats; } std::vector<TimeStepStats> FEBioModel::GetTimeStepStats() const { return m_timestepStats; } //----------------------------------------------------------------------------- //! Set the title of the model void FEBioModel::SetTitle(const char* sz) { m_title = sz; } //----------------------------------------------------------------------------- //! Return the title of the model const std::string& FEBioModel::GetTitle() const { return m_title; } //----------------------------------------------------------------------------- double FEBioModel::GetEndTime() const { return GetCurrentStep()->m_tend; } //============================================================================= // // FEBioModel: I-O Functions // //============================================================================= //----------------------------------------------------------------------------- //! Add a data record to the data store void FEBioModel::AddDataRecord(DataRecord* pd) { DataStore& dataStore = GetDataStore(); dataStore.AddRecord(pd); } //----------------------------------------------------------------------------- //! Get the plot file PlotFile* FEBioModel::GetPlotFile() { return m_plot; } //----------------------------------------------------------------------------- //! Sets the name of the FEBio input file void FEBioModel::SetInputFilename(const std::string& sfile) { m_sfile = sfile; size_t npos = sfile.rfind('/'); if (npos != string::npos) m_sfile_title = sfile.substr(npos+1, std::string::npos); if (m_sfile_title.empty()) { npos = sfile.rfind('\\'); if (npos != string::npos) m_sfile_title = sfile.substr(npos, string::npos); if (m_sfile_title.empty()) m_sfile_title = m_sfile; } } //----------------------------------------------------------------------------- //! Set the name of the log file void FEBioModel::SetLogFilename(const std::string& sfile) { m_slog = sfile; } //----------------------------------------------------------------------------- //! Set the name of the plot file void FEBioModel::SetPlotFilename(const std::string& sfile) { m_splot = sfile; } //----------------------------------------------------------------------------- //! Set the name of the restart archive (i.e. the dump file) void FEBioModel::SetDumpFilename(const std::string& sfile) { m_sdump = sfile; } //----------------------------------------------------------------------------- //! Return the name of the input file const std::string& FEBioModel::GetInputFileName() { return m_sfile; } //----------------------------------------------------------------------------- //! Return the name of the log file const std::string& FEBioModel::GetLogfileName() { return m_slog; } //----------------------------------------------------------------------------- //! Return the name of the plot file const std::string& FEBioModel::GetPlotFileName() { return m_splot; } //----------------------------------------------------------------------------- //! Return the dump file name. const std::string& FEBioModel::GetDumpFileName() { return m_sdump; } //----------------------------------------------------------------------------- //! get the file title (i.e. name of input file without the path) const std::string& FEBioModel::GetFileTitle() { return m_sfile_title; } //----------------------------------------------------------------------------- // set append-on-restart flag void FEBioModel::SetAppendOnRestart(bool b) { m_pltAppendOnRestart = b; } //----------------------------------------------------------------------------- bool FEBioModel::AppendOnRestart() const { return m_pltAppendOnRestart; } //============================================================================= // I N P U T //============================================================================= //----------------------------------------------------------------------------- //! This routine reads in an input file and performs some initialization stuff. //! The rest of the initialization is done in Init bool FEBioModel::Input(const char* szfile) { // start the total timer (assumes that this is the first function we'll hit) m_TotalTime.start(); // start the timer TimerTracker t(&m_InputTime); // create file reader FEBioImport fim; // override the default model builder fim.SetModelBuilder(new FEBioModelBuilder(*this)); feLog("Reading file %s ...", szfile); // Load the file if (fim.Load(*this, szfile) == false) { feLog("FAILED!\n"); char szerr[256]; fim.GetErrorMessage(szerr); feLogError(szerr); return false; } else feLog("SUCCESS!\n"); // set the input file name SetInputFilename(szfile); // see if user redefined output filenames if (fim.m_szdmp[0]) SetDumpFilename(fim.m_szdmp); if (fim.m_szlog[0]) SetLogFilename (fim.m_szlog); if (fim.m_szplt[0]) SetPlotFilename(fim.m_szplt); // add the data records int ND = (int)fim.m_data.size(); for (int i=0; i<ND; ++i) AddDataRecord(fim.m_data[i]); // we're done reading return true; } //----------------------------------------------------------------------------- //! This function finds all the domains that have a certain material void FEBioModel::DomainListFromMaterial(vector<int>& lmat, vector<int>& ldom) { FEMesh& mesh = GetMesh(); // make sure the list is empty if (ldom.empty() == false) ldom.clear(); // loop over all domains int ND = mesh.Domains(); int NM = (int)lmat.size(); for (int i = 0; i<ND; ++i) { FEDomain& di = mesh.Domain(i); int dmat = di.GetMaterial()->GetID(); for (int j = 0; j<NM; ++j) { if (dmat == lmat[j]) { ldom.push_back(i); break; } } } } //============================================================================= // O U T P U T //============================================================================= //----------------------------------------------------------------------------- //! Export state to plot file. void FEBioModel::Write(unsigned int nevent) { TimerTracker t(&m_IOTimer); // get the current step FEAnalysis* pstep = GetCurrentStep(); // echo fem data to the logfile // we do this here (and not e.g. directly after input) // since the data can be changed after input, which is the case, // for instance, in the parameter optimization module if ((nevent == CB_INIT) && m_becho) { Logfile::MODE old_mode = m_log.GetMode(); // don't output when no output is requested if (old_mode != Logfile::LOG_NEVER) { // we only output this data to the log file and not the screen m_log.SetMode(Logfile::LOG_FILE); // write output echo_input(); // reset log mode m_log.SetMode(old_mode); } } // update plot file WritePlot(nevent); // Dump converged state to the archive DumpData(nevent); // write the output data WriteData(nevent); } //----------------------------------------------------------------------------- void FEBioModel::WritePlot(unsigned int nevent) { // get the current step FEAnalysis* pstep = GetCurrentStep(); // get the plot level int nplt = pstep->GetPlotLevel(); // if we don't want to plot anything we return if (nplt != FE_PLOT_NEVER) { // try to open the plot file if ((nevent == CB_INIT) || (nevent == CB_STEP_ACTIVE)) { // If the first step did not request output, m_plot can still be null if (m_plot == nullptr) { if (InitPlotFile() == false) { feLogError("Failed to initialize plot file."); return; } } if (m_plot->IsValid() == false) { // Add the plot objects UpdatePlotObjects(); if (m_plot->Open(m_splot.c_str()) == false) { feLog("ERROR : Failed creating PLOT database\n"); delete m_plot; m_plot = 0; } // Since it is assumed that for the first timestep // there are no loads or initial displacements, the case n=0 is skipped. // Therefor we can output those results here. // TODO: Offcourse we should actually check if this is indeed // the case, otherwise we should also solve for t=0 // Only output the initial state if requested if (m_plot) { bool bout = true; // if we're using the fixed time stepper, we check the plot range and zero state flag if (pstep->m_timeController == nullptr) bout = (pstep->m_nplotRange[0] == 0) || (pstep->m_bplotZero); // for multi-step analyses, some plot variables can't be plot until the first step // is activated. So, in that case, we'll wait. if ((nevent == CB_INIT) && (Steps() > 1)) bout = false; // store initial time step (i.e. time step zero) if (bout) { double time = GetTime().currentTime; m_plot->Write((float)time); } } } else { // for multi-step analyses, we did not write the initial time step during CB_INIT // so we'll do it during the activation of the first step. if ((nevent == CB_STEP_ACTIVE) && (Steps() > 1) && (GetCurrentStepIndex() == 0)) { double time = GetTime().currentTime; m_plot->Write((float)time); } } } else { // assume we won't be writing anything bool bout = false; // see if we need to output something int ndebug = GetDebugLevel(); // write a new mesh section if needed if (nevent == CB_REMESH) { m_writeMesh = true; m_lastUpdate = -1; } if (ndebug == 1) { if ((nevent == CB_INIT) || (nevent == CB_MODEL_UPDATE) || (nevent == CB_MINOR_ITERS) || (nevent == CB_SOLVED) || (nevent == CB_REMESH) || (nevent == CB_TIMESTEP_FAILED)) { bout = true; } if (nevent == CB_MAJOR_ITERS) { bout = true; m_lastUpdate = -1; } } else { int currentStep = pstep->m_ntimesteps; int lastStep = pstep->m_ntime; int nmin = pstep->m_nplotRange[0]; if (nmin < 0) nmin = lastStep + nmin + 1; int nmax = pstep->m_nplotRange[1]; if (nmax < -1) nmax = lastStep + nmax + 1; bool inRange = true; bool isStride = true; if (pstep->m_timeController == nullptr) { inRange = false; if ((currentStep >= nmin) && ((currentStep <= nmax) || (nmax == -1))) inRange = true; } isStride = ((pstep->m_ntimesteps - nmin) % pstep->m_nplot_stride) == 0; bool isMustPoint = (pstep->m_timeController && (pstep->m_timeController->m_nmust >= 0)); switch (nevent) { case CB_MINOR_ITERS: { if (nplt == FE_PLOT_MINOR_ITRS) bout = true; if ((ndebug == 2) && (NegativeJacobian::IsThrown())) { bout = true; NegativeJacobian::clearFlag(); } } break; case CB_MAJOR_ITERS: if ((nplt == FE_PLOT_MAJOR_ITRS) && inRange && (isStride || isMustPoint)) bout = true; if ((nplt == FE_PLOT_MUST_POINTS) && isMustPoint) bout = true; if (nplt == FE_PLOT_AUGMENTATIONS) bout = true; break; case CB_AUGMENT: if (nplt == FE_PLOT_AUGMENTATIONS) { // Note that this is called before the augmentations. // The reason we store the state prior to the augmentations // is because the augmentations are going to change things such that // the system no longer in equilibrium. Since the model has to be converged // before we do augmentations, storing the model now will store an actual converged state. bout = true; } break; case CB_SOLVED: if (nplt == FE_PLOT_FINAL) bout = true; if (nplt == FE_PLOT_MAJOR_ITRS) { // we want to force storing the final time step, but we have to make sure // it hasn't been stored already during the CB_MAJOR_ITERS callback. if ((inRange == false) || (isStride == false)) bout = true; } break; case CB_STEP_SOLVED: if (nplt == FE_PLOT_STEP_FINAL) bout = true; break; case CB_USER1: if ((nplt == FE_PLOT_USER1) && inRange && isStride) bout = true; break; } } // output the state if requested if (bout && (m_lastUpdate != UpdateCounter())) { m_lastUpdate = UpdateCounter(); // update the plot objects UpdatePlotObjects(); // see if we need to write a new mesh section if (m_writeMesh) { FEBioPlotFile* plt = dynamic_cast<FEBioPlotFile*>(m_plot); feLogDebug("writing mesh section to plot file"); plt->WriteMeshSection(*this); } // set the status flag int statusFlag = 0; if (m_writeMesh) statusFlag = 1; else if (nevent != CB_MAJOR_ITERS) { statusFlag = 2; } // write the state section double time = GetTime().currentTime; if (m_plot) { m_plot->Write((float)time, statusFlag); } // make sure to reset write mesh flag m_writeMesh = false; } } } } //----------------------------------------------------------------------------- //! Write user data to the logfile void FEBioModel::WriteData(unsigned int nevent) { // get the current step FEAnalysis* pstep = GetCurrentStep(); int nout = pstep->GetOutputLevel(); if (nout == FE_OUTPUT_NEVER) return; // see if we need to output bool bout = false; switch (nevent) { case CB_INIT: if (nout == FE_OUTPUT_MAJOR_ITRS) bout = true; break; case CB_MINOR_ITERS: if (nout == FE_OUTPUT_MINOR_ITRS) bout = true; break; case CB_MAJOR_ITERS: { if (nout == FE_OUTPUT_MAJOR_ITRS) { bout = ((pstep->m_ntimesteps % pstep->m_noutput_stride) == 0); } if ((nout == FE_OUTPUT_MUST_POINTS) && (pstep->m_timeController) && (pstep->m_timeController->m_nmust >= 0)) bout = true; } break; case CB_SOLVED: if (nout == FE_OUTPUT_FINAL) bout = true; // make sure that the final solve data is output if (nout == FE_OUTPUT_MAJOR_ITRS) { bout = !((pstep->m_ntimesteps % pstep->m_noutput_stride) == 0); } break; } // output data if (bout) { DataStore& dataStore = GetDataStore(); dataStore.Write(); } } //----------------------------------------------------------------------------- //! Dump state to archive for restarts void FEBioModel::DumpData(int nevent) { // get the current step FEAnalysis* pstep = GetCurrentStep(); int ndump = GetDumpLevel(); int stride = GetDumpStride(); if (ndump == FE_DUMP_NEVER) return; bool bdump = false; switch (nevent) { case CB_MAJOR_ITERS: if (ndump == FE_DUMP_MAJOR_ITRS) { if (stride <= 1) bdump = true; else { int niter = pstep->m_ntimesteps; bdump = ((niter % stride) == 0); } } if ((ndump == FE_DUMP_MUST_POINTS) && (pstep->m_timeController) && (pstep->m_timeController->m_nmust >= 0)) bdump = true; break; case CB_STEP_SOLVED: if (ndump == FE_DUMP_STEP) bdump = true; break; } if (bdump) { DumpFile ar(*this); if (ar.Create(m_sdump.c_str()) == false) { feLogWarning("Failed creating restart file (%s).\n", m_sdump.c_str()); } else { Serialize(ar); feLogInfo("\nRestart point created. Archive name is %s.", m_sdump.c_str()); } } } string removeNewLines(const char* sz) { string tmp; tmp.reserve(128); const char* c = sz; while ((c != 0) && (*c != 0)) { if ((*c != '\n') && (*c != '\r')) tmp.push_back(*c); else tmp.push_back(' '); c++; } return tmp; } //----------------------------------------------------------------------------- void FEBioModel::Log(int ntag, const char* szmsg) { TimerTracker t(&m_IOTimer); if (ntag == 0) m_log.printf(szmsg); else if ((ntag == 1) && m_bshowErrors) m_log.printbox("WARNING", szmsg); else if ((ntag == 2) && m_bshowErrors) m_log.printbox("ERROR", szmsg); else if (ntag == 3) m_log.printbox(nullptr, szmsg); else if (ntag == 4) { if (GetDebugLevel() > 0) m_log.printf("debug>%s\n", szmsg); } if (m_createReport) { string msg = removeNewLines(szmsg); double t = GetCurrentTime(); stringstream ss; ss << msg << " (t = " << t << ")\n"; msg = ss.str(); if (ntag == 1) m_report += "Warning: " + msg; if (ntag == 2) m_report += "Error: " + msg; } // Flushing the logfile each time we get here might be a bit overkill. // For now, I'm flushing the log file in the output_cb method. // m_log.flush(); } //----------------------------------------------------------------------------- class FEPlotRigidBodyData : public FEPlotObjectData { public: FEPlotRigidBodyData(FEModel* fem, FERigidBody* rb, std::function<vec3d (const FERigidBody& rb)> f) : FEPlotObjectData(fem), m_rb(rb), m_f(f) {} bool Save(FEBioPlotFile::PlotObject* po, FEDataStream& ar) { assert(m_rb); ar << m_f(*m_rb); return true; } private: FERigidBody* m_rb; std::function<vec3d(const FERigidBody& rb)> m_f; }; class FEPlotRigidBodyPosition : public FEPlotRigidBodyData { public: FEPlotRigidBodyPosition(FEModel* fem, FERigidBody* prb) : FEPlotRigidBodyData(fem, prb, [](const FERigidBody& rb) { return rb.m_rt; }) {} }; class FEPlotRigidBodyVelocity : public FEPlotRigidBodyData { public: FEPlotRigidBodyVelocity(FEModel* fem, FERigidBody* prb) : FEPlotRigidBodyData(fem, prb, [](const FERigidBody& rb) { return rb.m_vt; }) {} }; class FEPlotRigidBodyAcceleration : public FEPlotRigidBodyData { public: FEPlotRigidBodyAcceleration(FEModel* fem, FERigidBody* prb) : FEPlotRigidBodyData(fem, prb, [](const FERigidBody& rb) { return rb.m_at; }) {} }; class FEPlotRigidBodyAngularVelocity : public FEPlotRigidBodyData { public: FEPlotRigidBodyAngularVelocity(FEModel* fem, FERigidBody* prb) : FEPlotRigidBodyData(fem, prb, [](const FERigidBody& rb) { return rb.m_wt; }) {} }; class FEPlotRigidBodyAngularAcceleration : public FEPlotRigidBodyData { public: FEPlotRigidBodyAngularAcceleration(FEModel* fem, FERigidBody* prb) : FEPlotRigidBodyData(fem, prb, [](const FERigidBody& rb) { return rb.m_alt; }) {} }; class FEPlotRigidBodyEuler : public FEPlotRigidBodyData { public: FEPlotRigidBodyEuler(FEModel* fem, FERigidBody* prb) : FEPlotRigidBodyData(fem, prb, [](const FERigidBody& rb) { quatd q = rb.GetRotation(); vec3d e; q.GetEuler(e.x, e.y, e.z); e *= RAD2DEG; return e; }) {} }; class FEPlotRigidBodyForce : public FEPlotRigidBodyData { public: FEPlotRigidBodyForce(FEModel* fem, FERigidBody* prb) : FEPlotRigidBodyData(fem, prb, [](const FERigidBody& rb) { return rb.m_Fr; }) {} }; class FEPlotRigidBodyMoment : public FEPlotRigidBodyData { public: FEPlotRigidBodyMoment(FEModel* fem, FERigidBody* prb) : FEPlotRigidBodyData(fem, prb, [](const FERigidBody& rb) { return rb.m_Mr; }) {} }; //----------------------------------------------------------------------------- class FEPlotRigidConnectorTranslationLCS : public FEPlotObjectData { public: FEPlotRigidConnectorTranslationLCS(FEModel* fem, FERigidConnector* prb) : FEPlotObjectData(fem), m_rc(prb) {} bool Save(FEBioPlotFile::PlotObject* po, FEDataStream& ar) { assert(m_rc); ar << m_rc->RelativeTranslation(false); return true; } private: FERigidConnector* m_rc; }; class FEPlotRigidConnectorRotationLCS : public FEPlotObjectData { public: FEPlotRigidConnectorRotationLCS(FEModel* fem, FERigidConnector* prb) : FEPlotObjectData(fem), m_rc(prb) {} bool Save(FEBioPlotFile::PlotObject* po, FEDataStream& ar) { assert(m_rc); ar << m_rc->RelativeRotation(false); return true; } private: FERigidConnector* m_rc; }; class FEPlotRigidConnectorTranslationGCS : public FEPlotObjectData { public: FEPlotRigidConnectorTranslationGCS(FEModel* fem, FERigidConnector* prb) : FEPlotObjectData(fem), m_rc(prb) {} bool Save(FEBioPlotFile::PlotObject* po, FEDataStream& ar) { assert(m_rc); ar << m_rc->RelativeTranslation(true); return true; } private: FERigidConnector* m_rc; }; class FEPlotRigidConnectorRotationGCS : public FEPlotObjectData { public: FEPlotRigidConnectorRotationGCS(FEModel* fem, FERigidConnector* prb) : FEPlotObjectData(fem), m_rc(prb) {} bool Save(FEBioPlotFile::PlotObject* po, FEDataStream& ar) { assert(m_rc); ar << m_rc->RelativeRotation(true); return true; } private: FERigidConnector* m_rc; }; class FEPlotRigidConnectorForce : public FEPlotObjectData { public: FEPlotRigidConnectorForce(FEModel* fem, FERigidConnector* prb) : FEPlotObjectData(fem), m_rc(prb) {} bool Save(FEBioPlotFile::PlotObject* po, FEDataStream& ar) { assert(m_rc); ar << m_rc->m_F; return true; } private: FERigidConnector* m_rc; }; class FEPlotRigidConnectorMoment : public FEPlotObjectData { public: FEPlotRigidConnectorMoment(FEModel* fem, FERigidConnector* prb) : FEPlotObjectData(fem), m_rc(prb) {} bool Save(FEBioPlotFile::PlotObject* po, FEDataStream& ar) { assert(m_rc); ar << m_rc->m_M; return true; } private: FERigidConnector* m_rc; }; //----------------------------------------------------------------------------- void FEBioModel::UpdatePlotObjects() { FEBioPlotFile* plt = dynamic_cast<FEBioPlotFile*>(m_plot); if (plt == nullptr) return; int nrb = RigidBodies(); if (nrb == 0) return; FEModel& fem = *GetFEModel(); int nid = 1; if (plt->PointObjects() == 0) { for (int i = 0; i < nrb; ++i) { FERigidBody* rb = GetRigidBody(i); string name = rb->GetName(); if (name.empty()) { stringstream ss; ss << "Object" << nid; name = ss.str(); } FEBioPlotFile::PointObject* po = plt->AddPointObject(name); po->m_tag = OBJ_RIGID_BODY; po->m_pos = rb->m_r0; po->m_rot = quatd(0, vec3d(1,0,0)); po->AddData("Position" , PLT_VEC3F, new FEPlotRigidBodyPosition(this, rb)); po->AddData("Velocity" , PLT_VEC3F, new FEPlotRigidBodyVelocity(this, rb)); po->AddData("Acceleration" , PLT_VEC3F, new FEPlotRigidBodyAcceleration(this, rb)); po->AddData("Euler angles (deg)" , PLT_VEC3F, new FEPlotRigidBodyEuler(this, rb)); po->AddData("Angular velocity" , PLT_VEC3F, new FEPlotRigidBodyAngularVelocity(this, rb)); po->AddData("Angular acceleration", PLT_VEC3F, new FEPlotRigidBodyAngularAcceleration(this, rb)); po->AddData("Force" , PLT_VEC3F, new FEPlotRigidBodyForce(this, rb)); po->AddData("Moment" , PLT_VEC3F, new FEPlotRigidBodyMoment(this, rb)); nid++; } // check rigid connectors for (int i = 0; i < fem.NonlinearConstraints(); ++i) { FENLConstraint* pc = fem.NonlinearConstraint(i); string name = pc->GetName(); if (name.empty()) { stringstream ss; ss << "Object" << nid; name = ss.str(); } FEGenericRigidJoint* rj = dynamic_cast<FEGenericRigidJoint*>(pc); if (rj) { FEBioPlotFile::PointObject* po = plt->AddPointObject(name); po->m_tag = OBJ_GENERIC_JOINT; po->m_pos = rj->InitialPosition(); po->m_rot = quatd(0, vec3d(1, 0, 0)); po->AddData("Relative translation (LCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationLCS(this, rj)); po->AddData("Relative rotation (LCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationLCS(this, rj)); po->AddData("Relative translation (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationGCS(this, rj)); po->AddData("Relative rotation (GCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationGCS(this, rj)); po->AddData("Reaction force (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorForce(this, rj)); po->AddData("Reaction moment (GCS)", PLT_VEC3F, new FEPlotRigidConnectorMoment(this, rj)); } FERigidSphericalJoint* rsj = dynamic_cast<FERigidSphericalJoint*>(pc); if (rsj) { FEBioPlotFile::PointObject* po = plt->AddPointObject(name); po->m_tag = OBJ_SPHERICAL_JOINT; po->m_pos = rsj->InitialPosition(); po->m_rot = quatd(0, vec3d(1, 0, 0)); po->AddData("Relative translation (LCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationLCS(this, rsj)); po->AddData("Relative rotation (LCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationLCS(this, rsj)); po->AddData("Relative translation (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationGCS(this, rsj)); po->AddData("Relative rotation (GCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationGCS(this, rsj)); po->AddData("Reaction force (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorForce(this, rsj)); po->AddData("Reaction moment (GCS)", PLT_VEC3F, new FEPlotRigidConnectorMoment(this, rsj)); } FERigidPrismaticJoint* rpj = dynamic_cast<FERigidPrismaticJoint*>(pc); if (rpj) { FEBioPlotFile::PointObject* po = plt->AddPointObject(name); po->m_tag = OBJ_PRISMATIC_JOINT; po->m_pos = rpj->InitialPosition(); po->m_rot = rpj->Orientation(); po->AddData("Relative translation (LCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationLCS(this, rpj)); po->AddData("Relative rotation (LCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationLCS(this, rpj)); po->AddData("Relative translation (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationGCS(this, rpj)); po->AddData("Relative rotation (GCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationGCS(this, rpj)); po->AddData("Reaction force (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorForce(this, rpj)); po->AddData("Reaction moment (GCS)", PLT_VEC3F, new FEPlotRigidConnectorMoment(this, rpj)); } FERigidRevoluteJoint* rrj = dynamic_cast<FERigidRevoluteJoint*>(pc); if (rrj) { FEBioPlotFile::PointObject* po = plt->AddPointObject(name); po->m_tag = OBJ_REVOLUTE_JOINT; po->m_pos = rrj->InitialPosition(); po->m_rot = rrj->Orientation(); po->AddData("Relative translation (LCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationLCS(this, rrj)); po->AddData("Relative rotation (LCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationLCS(this, rrj)); po->AddData("Relative translation (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationGCS(this, rrj)); po->AddData("Relative rotation (GCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationGCS(this, rrj)); po->AddData("Reaction force (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorForce(this, rrj)); po->AddData("Reaction moment (GCS)", PLT_VEC3F, new FEPlotRigidConnectorMoment(this, rrj)); } FERigidCylindricalJoint* rcj = dynamic_cast<FERigidCylindricalJoint*>(pc); if (rcj) { FEBioPlotFile::PointObject* po = plt->AddPointObject(name); po->m_tag = OBJ_CYLINDRICAL_JOINT; po->m_pos = rcj->InitialPosition(); po->m_rot = rcj->Orientation(); po->AddData("Relative translation (LCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationLCS(this, rcj)); po->AddData("Relative rotation (LCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationLCS(this, rcj)); po->AddData("Relative translation (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationGCS(this, rcj)); po->AddData("Relative rotation (GCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationGCS(this, rcj)); po->AddData("Reaction force (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorForce(this, rcj)); po->AddData("Reaction moment (GCS)", PLT_VEC3F, new FEPlotRigidConnectorMoment(this, rcj)); } FERigidPlanarJoint* rlj = dynamic_cast<FERigidPlanarJoint*>(pc); if (rlj) { FEBioPlotFile::PointObject* po = plt->AddPointObject(name); po->m_tag = OBJ_PLANAR_JOINT; po->m_pos = rlj->InitialPosition(); po->m_rot = rlj->Orientation(); po->AddData("Relative translation (LCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationLCS(this, rlj)); po->AddData("Relative rotation (LCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationLCS(this, rlj)); po->AddData("Relative translation (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationGCS(this, rlj)); po->AddData("Relative rotation (GCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationGCS(this, rlj)); po->AddData("Reaction force (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorForce(this, rlj)); po->AddData("Reaction moment (GCS)", PLT_VEC3F, new FEPlotRigidConnectorMoment(this, rlj)); } nid++; } } else { for (int i = 0; i < nrb; ++i) { FERigidBody* rb = GetRigidBody(i); FEBioPlotFile::PointObject* po = plt->GetPointObject(i); po->m_pos = rb->m_rt; po->m_rot = rb->GetRotation(); } // check rigid connectors int n = nrb; for (int i = 0; i < fem.NonlinearConstraints(); ++i) { FENLConstraint* pc = fem.NonlinearConstraint(i); FEGenericRigidJoint* rj = dynamic_cast<FEGenericRigidJoint*>(pc); if (rj) { FEBioPlotFile::PointObject* po = plt->GetPointObject(n++); po->m_pos = rj->Position(); po->m_rot = quatd(0, vec3d(1, 0, 0)); } FERigidSphericalJoint* rsj = dynamic_cast<FERigidSphericalJoint*>(pc); if (rsj) { FEBioPlotFile::PointObject* po = plt->GetPointObject(n++); po->m_pos = rsj->Position(); po->m_rot = quatd(0, vec3d(1, 0, 0)); } FERigidPrismaticJoint* rpj = dynamic_cast<FERigidPrismaticJoint*>(pc); if (rpj) { FEBioPlotFile::PointObject* po = plt->GetPointObject(n++); po->m_pos = rpj->Position(); po->m_rot = rpj->Orientation(); } FERigidRevoluteJoint* rrj = dynamic_cast<FERigidRevoluteJoint*>(pc); if (rrj) { FEBioPlotFile::PointObject* po = plt->GetPointObject(n++); po->m_pos = rrj->Position(); po->m_rot = rrj->Orientation(); } FERigidCylindricalJoint* rcj = dynamic_cast<FERigidCylindricalJoint*>(pc); if (rcj) { FEBioPlotFile::PointObject* po = plt->GetPointObject(n++); po->m_pos = rcj->Position(); po->m_rot = rcj->Orientation(); } FERigidPlanarJoint* rlj = dynamic_cast<FERigidPlanarJoint*>(pc); if (rlj) { FEBioPlotFile::PointObject* po = plt->GetPointObject(n++); po->m_pos = rlj->Position(); po->m_rot = rlj->Orientation(); } } } if (plt->LineObjects() == 0) { // check rigid connectors for (int i = 0; i < fem.NonlinearConstraints(); ++i) { FERigidConnector* prc = dynamic_cast<FERigidConnector*>(fem.NonlinearConstraint(i)); if (prc) { string name = prc->GetName(); if (name.empty()) { stringstream ss; ss << "LineObject" << nid; name = ss.str(); } vec3d ra = GetRigidBody(prc->m_nRBa)->m_r0; vec3d rb = GetRigidBody(prc->m_nRBb)->m_r0; FERigidSpring* rs = dynamic_cast<FERigidSpring*>(prc); if (rs) { FEBioPlotFile::LineObject* po = plt->AddLineObject(name); po->m_tag = 1; po->m_rot = quatd(0, vec3d(1, 0, 0)); po->m_r1 = rs->m_at; po->m_r2 = rs->m_bt; po->AddData("Relative translation (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationGCS(this, rs)); po->AddData("Relative rotation (GCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationGCS(this, rs)); po->AddData("Reaction force (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorForce(this, rs)); po->AddData("Reaction moment (GCS)", PLT_VEC3F, new FEPlotRigidConnectorMoment(this, rs)); } FERigidDamper* rd = dynamic_cast<FERigidDamper*>(prc); if (rd) { FEBioPlotFile::LineObject* po = plt->AddLineObject(name); po->m_tag = 2; po->m_rot = quatd(0, vec3d(1, 0, 0)); po->m_r1 = rd->m_at; po->m_r2 = rd->m_bt; po->AddData("Relative translation (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationGCS(this, rd)); po->AddData("Relative rotation (GCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationGCS(this, rd)); po->AddData("Reaction force (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorForce(this, rd)); po->AddData("Reaction moment (GCS)", PLT_VEC3F, new FEPlotRigidConnectorMoment(this, rd)); } FERigidAngularDamper* rad = dynamic_cast<FERigidAngularDamper*>(prc); if (rad) { FEBioPlotFile::LineObject* po = plt->AddLineObject(name); po->m_tag = 3; po->m_r1 = ra; po->m_r2 = rb; po->AddData("Relative translation (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationGCS(this, rad)); po->AddData("Relative rotation (GCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationGCS(this, rad)); po->AddData("Reaction force (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorForce(this, rad)); po->AddData("Reaction moment (GCS)", PLT_VEC3F, new FEPlotRigidConnectorMoment(this, rad)); } FERigidContractileForce* rcf = dynamic_cast<FERigidContractileForce*>(prc); if (rcf) { FEBioPlotFile::LineObject* po = plt->AddLineObject(name); po->m_tag = 4; po->m_rot = quatd(0, vec3d(1, 0, 0)); po->m_r1 = rcf->m_at; po->m_r2 = rcf->m_bt; po->AddData("Relative translation (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorTranslationGCS(this, rcf)); po->AddData("Relative rotation (GCS)", PLT_VEC3F, new FEPlotRigidConnectorRotationGCS(this, rcf)); po->AddData("Reaction force (GCS)" , PLT_VEC3F, new FEPlotRigidConnectorForce(this, rcf)); po->AddData("Reaction moment (GCS)", PLT_VEC3F, new FEPlotRigidConnectorMoment(this, rcf)); } } nid++; } } else { // check rigid connectors int n = 0; for (int i = 0; i < fem.NonlinearConstraints(); ++i) { FERigidConnector* prc = dynamic_cast<FERigidConnector*>(fem.NonlinearConstraint(i)); if (prc) { vec3d ra = GetRigidBody(prc->m_nRBa)->m_rt; vec3d rb = GetRigidBody(prc->m_nRBb)->m_rt; FERigidSpring* rs = dynamic_cast<FERigidSpring*>(prc); if (rs) { FEBioPlotFile::LineObject* po = plt->GetLineObject(n++); po->m_r1 = rs->m_at; po->m_r2 = rs->m_bt; } FERigidDamper* rd = dynamic_cast<FERigidDamper*>(prc); if (rd) { FEBioPlotFile::LineObject* po = plt->GetLineObject(n++); po->m_r1 = ra; po->m_r2 = rb; } FERigidAngularDamper* rad = dynamic_cast<FERigidAngularDamper*>(prc); if (rad) { FEBioPlotFile::LineObject* po = plt->GetLineObject(n++); po->m_r1 = ra; po->m_r2 = rb; } FERigidContractileForce* rcf = dynamic_cast<FERigidContractileForce*>(prc); if (rcf) { FEBioPlotFile::LineObject* po = plt->GetLineObject(n++); po->m_r1 = rcf->m_at; po->m_r2 = rcf->m_bt; } } } } } //============================================================================= // R E S T A R T //============================================================================= class restart_exception : public std::runtime_error { public: restart_exception() : std::runtime_error("restart error") {} restart_exception(const char* msg) : std::runtime_error(msg) {} }; //----------------------------------------------------------------------------- //! Reads or writes the current state to/from a binary file //! This is used to restart the solution from a saved position //! or to create a restart point. //! A version number is written to file to make sure the same //! format is used for reading and writing. //! \param[in] ar the archive to which the data is serialized //! \sa DumpFile void FEBioModel::Serialize(DumpStream& ar) { // don't need to do anything for running restarts if (ar.IsShallow()) { // serialize model data FEMechModel::Serialize(ar); } else { if (ar.IsSaving()) { // --- version number --- ar << (int) RSTRTVERSION; } else { // --- version --- int nversion; ar >> nversion; // make sure it is the right version if (nversion != RSTRTVERSION) throw restart_exception("incorrect version number"); } // serialize model data FEMechModel::Serialize(ar); // --- Save IO Data SerializeIOData(ar); if (ar.IsSaving()) { int n = (int)m_stepStats.size(); ar << n; for (ModelStats& s : m_stepStats) { ar << s.ntimeSteps << s.ntotalIters << s.ntotalReforms << s.ntotalRHS; } n = (int)m_timestepStats.size(); ar << n; for (TimeStepStats& s : m_timestepStats) { ar << s.iters << s.nrhs << s.refs << s.status; } } else { m_stepStats.clear(); int n = 0; ar >> n; for (int i = 0; i < n; ++i) { ModelStats s; ar >> s.ntimeSteps >> s.ntotalIters >> s.ntotalReforms >> s.ntotalRHS; m_stepStats.push_back(s); } m_timestepStats.clear(); n = 0; ar >> n; for (int i = 0; i < n; ++i) { TimeStepStats s; ar >> s.iters >> s.nrhs >> s.refs >> s.status; m_timestepStats.push_back(s); } } } } //----------------------------------------------------------------------------- //! Serialization of FEBioModel data void FEBioModel::SerializeIOData(DumpStream &ar) { if (ar.IsSaving()) { // file names ar << m_sfile << m_splot << m_slog << m_sdump; // plot file int npltfmt = 2; ar << npltfmt; SerializePlotData(ar); if (m_plot) m_plot->Serialize(ar); // data records SerializeDataStore(ar); } else { // file names string splot, slog, sdmp; ar >> m_sfile >> splot >> slog >> sdmp; // don't forget to call store the input file name so // that m_szfile_title gets initialized SetInputFilename(m_sfile); // If we append, use the original names // otherwise we use the names as was initialized by the command line parser if (m_pltAppendOnRestart) { m_splot = splot; m_slog = slog; m_sdump = sdmp; } // get the plot file format (should be 2) int npltfmt = 0; ar >> npltfmt; assert(npltfmt == 2); SerializePlotData(ar); // remove the plot file (if any) if (m_plot) { delete m_plot; m_plot = 0; } // create the plot file FEPlotDataStore& data = GetPlotDataStore(); if (data.GetPlotFileType() == "febio") { FEBioPlotFile* xplt = new FEBioPlotFile(this); // set the software string const char* szver = febio::getVersionString(); char szbuf[256] = { 0 }; snprintf(szbuf, sizeof(szbuf), "FEBio %s", szver); xplt->SetSoftwareString(szbuf); m_plot = xplt; } else if (data.GetPlotFileType() == "vtk") m_plot = new VTKPlotFile(this); if (m_plot) m_plot->Serialize(ar); if (m_pltAppendOnRestart) { // Open for appending if (m_plot->Append(m_splot.c_str()) == false) { printf("FATAL ERROR: Failed reopening plot database %s\n", m_splot.c_str()); throw "FATAL ERROR"; } } else { if (m_plot->Open(m_splot.c_str()) == false) { printf("FATAL ERROR: Failed creating plot database %s\n", m_splot.c_str()); throw "FATAL ERROR"; } } // data records SerializeDataStore(ar); } } //----------------------------------------------------------------------------- void FEBioModel::SerializePlotData(DumpStream& ar) { GetPlotDataStore().Serialize(ar); } //----------------------------------------------------------------------------- void FEBioModel::SerializeDataStore(DumpStream& ar) { DataStore& dataStore = GetDataStore(); if (ar.IsSaving()) { int N = dataStore.Size(); ar << N; for (int i=0; i<N; ++i) { DataRecord* pd = dataStore.GetDataRecord(i); int ntype = pd->m_type; ar << ntype; pd->Serialize(ar); } } else { int N; dataStore.Clear(); ar >> N; for (int i=0; i<N; ++i) { int ntype; ar >> ntype; DataRecord* pd = 0; switch(ntype) { case FE_DATA_NODE : pd = new NodeDataRecord (this); break; case FE_DATA_FACE : pd = new FaceDataRecord (this); break; case FE_DATA_ELEM : pd = new ElementDataRecord (this); break; case FE_DATA_RB : pd = new ObjectDataRecord (this); break; case FE_DATA_NLC : pd = new NLConstraintDataRecord(this); break; case FE_DATA_SURFACE: pd = new FESurfaceDataRecord (this); break; case FE_DATA_DOMAIN : pd = new FEDomainDataRecord (this); break; case FE_DATA_MODEL : pd = new FEModelDataRecord (this); break; } assert(pd); pd->Serialize(ar); dataStore.AddRecord(pd); } } } //============================================================================= // I N I T I A L I Z A T I O N //============================================================================= //----------------------------------------------------------------------------- // Initialize plot file bool FEBioModel::InitPlotFile() { FEPlotDataStore& data = GetPlotDataStore(); if (data.GetPlotFileType() == "febio") { FEBioPlotFile* xplt = new FEBioPlotFile(this); // set the software string const char* szver = febio::getVersionString(); char szbuf[256] = { 0 }; snprintf(szbuf, sizeof(szbuf), "FEBio %s", szver); xplt->SetSoftwareString(szbuf); m_plot = xplt; // see if a valid plot file name is defined. const std::string& splt = GetPlotFileName(); if (splt.empty()) { // if not, we take the input file name and set the extension to .xplt char sz[1024] = { 0 }; strcpy(sz, GetInputFileName().c_str()); char* ch = strrchr(sz, '.'); if (ch) *ch = 0; strcat(sz, ".xplt"); SetPlotFilename(sz); } } else if (data.GetPlotFileType() == "vtk") { VTKPlotFile* vtk = new VTKPlotFile(this); m_plot = vtk; // see if a valid plot file name is defined. const std::string& splt = GetPlotFileName(); if (splt.empty()) { // if not, we take the input file name and set the extension to .vtk char sz[1024] = { 0 }; strcpy(sz, GetInputFileName().c_str()); char* ch = strrchr(sz, '.'); if (ch) *ch = 0; strcat(sz, ".vtk"); SetPlotFilename(sz); } } else return false; return true; } //----------------------------------------------------------------------------- //! This function performs one-time-initialization stuff. All the different //! modules are initialized here as well. This routine also performs some //! data checks bool FEBioModel::Init() { TRACK_TIME(TimerID::Timer_Init); // Open the logfile if (m_logLevel != 0) { if (InitLogFile() == false) return false; } m_report.clear(); m_stepStats.clear(); m_timestepStats.clear(); FEBioPlotFile* pplt = nullptr; m_lastUpdate = -1; // see if a valid dump file name is defined. const std::string& sdmp = GetDumpFileName(); if (sdmp.empty()) { // if not, we take the input file name and set the extension to .dmp char sz[1024] = { 0 }; strcpy(sz, GetInputFileName().c_str()); char* ch = strrchr(sz, '.'); if (ch) *ch = 0; strcat(sz, ".dmp"); SetDumpFilename(sz); } // initialize data records DataStore& dataStore = GetDataStore(); for (int i = 0; i < dataStore.Size(); ++i) { if (dataStore.GetDataRecord(i)->Initialize() == false) return false; } // initialize model data if (FEMechModel::Init() == false) { feLogError("Model initialization failed"); return false; } // open plot database file FEAnalysis* step = GetCurrentStep(); if (step->GetPlotLevel() != FE_PLOT_NEVER) { if (m_plot == nullptr) { if (InitPlotFile() == false) { feLogError("Failed to initialize plot file."); return false; } } } // Alright, all initialization is done, so let's get busy ! return true; } //----------------------------------------------------------------------------- // Opens the log file bool FEBioModel::InitLogFile() { // Only do this if the log file is not valid if (!m_log.is_valid()) { // see if a valid log file name is defined. const std::string& slog = GetLogfileName(); if (slog.empty()) { // if not, we take the input file name and set the extension to .log char sz[1024] = {0}; strcpy(sz, GetInputFileName().c_str()); char *ch = strrchr(sz, '.'); if (ch) *ch = 0; strcat(sz, ".log"); SetLogFilename(sz); } // create a log stream LogFileStream* fp = new LogFileStream; m_log.SetFileStream(fp); if (fp->open(m_slog.c_str()) == false) { feLogError("Failed creating log file"); return false; } // make sure we have a step FEAnalysis* step = GetCurrentStep(); if (step == 0) { feLogError("No step defined."); return false; } // print welcome message to file Logfile::MODE m = m_log.SetMode(Logfile::LOG_FILE); febio::Hello(*fp); m_log.SetMode(m); } return true; } bool FEBioModel::Solve() { // The total time is usually started on calling Input, // however, in a restart Input is not called, so we start it here. if (!m_TotalTime.isRunning()) m_TotalTime.start(); bool b = FEModel::Solve(); m_TotalTime.stop(); return b; } //! This function resets the FEM data so that a new run can be done. //! This routine is called from the optimization routine. bool FEBioModel::Reset() { // Reset model data FEMechModel::Reset(); m_TotalTime.reset(); // re-initialize the log file if (m_logLevel != 0) { // TODO: I added this so that log files can be compared using the reset_test // but this messes up the output for optimization problems. // I want the optimization create its own log file, so it is decoupled from the model's // log file. But since all the logging stuff lives in FEBioLib, I can't do this yet. // if (m_log.is_valid()) m_log.close(); if (InitLogFile() == false) return false; } // open plot database file FEAnalysis* step = GetCurrentStep(); if (step->GetPlotLevel() != FE_PLOT_NEVER) { int hint = step->GetPlotHint(); if (m_plot == 0) { FEPlotDataStore& data = GetPlotDataStore(); if (data.GetPlotFileType() == "febio") m_plot = new FEBioPlotFile(this); else if (data.GetPlotFileType() == "vtk" ) m_plot = new VTKPlotFile(this); hint = 0; } if (hint != FE_PLOT_APPEND) { if (m_plot->Open(m_splot.c_str()) == false) { feLogError("Failed creating PLOT database."); return false; } } } // reset stats m_modelStats.ntimeSteps = 0; m_modelStats.ntotalIters = 0; m_modelStats.ntotalRHS = 0; m_modelStats.ntotalReforms = 0; m_stepStats.clear(); m_timestepStats.clear(); // do the callback DoCallback(CB_INIT); // All data is reset successfully return true; } TimingInfo FEBioModel::GetTimingInfo() { double tot = m_TotalTime.GetTime(); TimingInfo ti; ti.total_time = m_TotalTime.GetTime(); ti.solve_time = GetSolveTimer().GetTime(); double total = 0; ti.input_time = m_InputTime.GetExclusiveTime(); total += ti.input_time; ti.init_time = GetTimer(TimerID::Timer_Init)->GetExclusiveTime(); total += ti.init_time; ti.io_time = m_IOTimer.GetExclusiveTime(); total += ti.io_time; ti.total_ls_factor = GetTimer(TimerID::Timer_LinSol_Factor )->GetExclusiveTime(); total += ti.total_ls_factor; ti.total_ls_backsolve = GetTimer(TimerID::Timer_LinSol_Backsolve)->GetExclusiveTime(); total += ti.total_ls_backsolve; ti.total_reform = GetTimer(TimerID::Timer_Reform )->GetExclusiveTime(); total += ti.total_reform; ti.total_stiff = GetTimer(TimerID::Timer_Stiffness )->GetExclusiveTime(); total += ti.total_stiff; ti.total_rhs = GetTimer(TimerID::Timer_Residual )->GetExclusiveTime(); total += ti.total_rhs; ti.total_update = GetTimer(TimerID::Timer_Update )->GetExclusiveTime(); total += ti.total_update; ti.total_qn = GetTimer(TimerID::Timer_QNUpdate )->GetExclusiveTime(); total += ti.total_qn; ti.total_serialize = GetTimer(TimerID::Timer_Serialize )->GetExclusiveTime(); total += ti.total_serialize; ti.total_callback = GetTimer(TimerID::Timer_Callback )->GetExclusiveTime(); total += ti.total_callback; ti.total_other = ti.total_time - total; // assert(ti.total_other >= 0); return ti; } //============================================================================= // S O L V E //============================================================================= void FEBioModel::on_cb_solved() { FEAnalysis* step = GetCurrentStep(); if (step == nullptr) return; // for multistep analysis we'll print a grand total if (Steps() > 1) { feLog("\n\n N O N L I N E A R I T E R A T I O N S U M M A R Y\n\n"); feLog("\tNumber of time steps completed .................... : %d\n\n", m_modelStats.ntimeSteps); feLog("\tTotal number of equilibrium iterations ............ : %d\n\n", m_modelStats.ntotalIters); feLog("\tTotal number of right hand evaluations ............ : %d\n\n", m_modelStats.ntotalRHS); feLog("\tTotal number of stiffness reformations ............ : %d\n\n", m_modelStats.ntotalReforms); } // get timing info TimingInfo ti = GetTimingInfo(); // get and print elapsed time double linsol_time = ti.total_ls_factor + ti.total_ls_backsolve; char sztime[64]; Timer::time_str(linsol_time, sztime); feLog("\tTime in linear solver: %s\n\n", sztime); // always flush the log m_log.flush(); // get peak memory usage #ifdef WIN32 size_t memsize = GetPeakMemory(); if (memsize != 0) { double mb = (double)memsize / 1048576.0; feLog(" Peak memory : %.1lf MB\n", mb); } #endif // print the elapsed time GetSolveTimer().time_str(sztime); feLog("\n Elapsed time : %s\n\n", sztime); // print additional stats to the log file only if (m_log.GetMode() & Logfile::LOG_FILE) { // print more detailed timing info to the log file Logfile::MODE old_mode = m_log.SetMode(Logfile::LOG_FILE); // sum up all the times spend in the linear solvers feLog(" T I M I N G I N F O R M A T I O N\n\n"); Timer::time_str(ti.input_time , sztime); feLog("\tInput time ...................... : %s (%lg sec)\n\n", sztime, ti.input_time); Timer::time_str(ti.init_time , sztime); feLog("\tInitialization time ............. : %s (%lg sec)\n\n", sztime, ti.init_time); Timer::time_str(ti.solve_time , sztime); feLog("\tSolve time ...................... : %s (%lg sec)\n\n", sztime, ti.solve_time); Timer::time_str(ti.io_time , sztime); feLog("\t IO-time (plot, dmp, data) .... : %s (%lg sec)\n\n", sztime, ti.io_time); Timer::time_str(ti.total_reform, sztime); feLog("\t reforming stiffness .......... : %s (%lg sec)\n\n", sztime, ti.total_reform); Timer::time_str(ti.total_stiff , sztime); feLog("\t evaluating stiffness ......... : %s (%lg sec)\n\n", sztime, ti.total_stiff); Timer::time_str(ti.total_rhs , sztime); feLog("\t evaluating residual .......... : %s (%lg sec)\n\n", sztime, ti.total_rhs); Timer::time_str(ti.total_update, sztime); feLog("\t model update ................. : %s (%lg sec)\n\n", sztime, ti.total_update); Timer::time_str(ti.total_qn , sztime); feLog("\t QN updates ................... : %s (%lg sec)\n\n", sztime, ti.total_qn); Timer::time_str(linsol_time , sztime); feLog("\t time in linear solver ........ : %s (%lg sec)\n\n", sztime, linsol_time); Timer::time_str(ti.total_time , sztime); feLog("\tTotal elapsed time .............. : %s (%lg sec)\n\n", sztime, ti.total_time); m_log.SetMode(old_mode); bool bconv = IsSolved(); if (bconv) { feLog("\n N O R M A L T E R M I N A T I O N\n\n"); } else { feLog("\n E R R O R T E R M I N A T I O N\n\n"); } // flush the log file m_log.flush(); } // close the plot file int hint = GetStep(Steps() - 1)->GetPlotHint(); if (hint != FE_PLOT_APPEND) if (m_plot) m_plot->Close(); } //----------------------------------------------------------------------------- void FEBioModel::on_cb_stepSolved() { FEAnalysis* step = GetCurrentStep(); if (step == nullptr) return; // output report feLog("\n\n N O N L I N E A R I T E R A T I O N I N F O R M A T I O N\n\n"); feLog("\tNumber of time steps completed .................... : %d\n\n", step->m_ntimesteps); feLog("\tTotal number of equilibrium iterations ............ : %d\n\n", step->m_ntotiter); feLog("\tAverage number of equilibrium iterations .......... : %lg\n\n", (step->m_ntimesteps != 0 ? (double)step->m_ntotiter / (double)step->m_ntimesteps : 0)); feLog("\tTotal number of right hand evaluations ............ : %d\n\n", step->m_ntotrhs); feLog("\tTotal number of stiffness reformations ............ : %d\n\n", step->m_ntotref); // print linear solver stats FESolver* ps = step->GetFESolver(); if (ps) { LinearSolver* ls = step->GetFESolver()->GetLinearSolver(); if (ls) { LinearSolverStats stats = ls->GetStats(); int nsolves = stats.backsolves; int niters = stats.iterations; double avgiters = (nsolves != 0 ? (double)niters / (double)nsolves : (double)niters); feLog("\n L I N E A R S O L V E R S T A T S\n\n"); feLog("\tTotal calls to linear solver ........ : %d\n\n", nsolves); feLog("\tAvg iterations per solve ............ : %lg\n\n", avgiters); } } // add to stats ModelStats stats; stats.ntimeSteps = step->m_ntimesteps; stats.ntotalIters = step->m_ntotiter; stats.ntotalRHS = step->m_ntotrhs; stats.ntotalReforms = step->m_ntotref; m_stepStats.push_back(stats); m_modelStats.ntimeSteps += stats.ntimeSteps; m_modelStats.ntotalIters += stats.ntotalIters; m_modelStats.ntotalRHS += stats.ntotalRHS; m_modelStats.ntotalReforms += stats.ntotalReforms; } bool FEBioModel::Restart(const char* szfile) { // check the extension of the file const char* szext = strrchr(szfile, '.'); if (strcmp(szext, ".feb") == 0) { // process restart input file FERestartImport file; if (file.Load(*this, szfile) == false) { char szerr[256]; file.GetErrorMessage(szerr); fprintf(stderr, "%s", szerr); return false; } // get the number of new steps added int newSteps = file.StepsAdded(); int step = Steps() - newSteps; // Any additional steps that were created must be initialized for (int i = step; i < Steps(); ++i) { FEAnalysis* step = GetStep(i); if (step->Init() == false) return false; // also initialize all the step components for (int j = 0; j < step->StepComponents(); ++j) { FEStepComponent* pc = step->GetStepComponent(j); if (pc->Init() == false) return false; } } } else { // Open the dump file DumpFile ar(*this); if (ar.Open(szfile) == false) { return false; } // try reading the file Serialize(ar); } // Open the log file for appending const std::string& slog = GetLogfileName(); Logfile& felog = GetLogFile(); if (felog.append(slog.c_str()) == false) { printf("WARNING: Could not reopen log file. A new log file is created\n"); felog.open(slog.c_str()); return false; } // inform the user from where the problem is restarted felog.printbox(" - R E S T A R T -", "Restarting from time %lg.\n", GetCurrentTime()); return true; }
C++
3D
febiosoftware/FEBio
FEBioLib/febiolib.cpp
.cpp
3,089
97
/*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/FECore.h" #include "NumCore/NumCore.h" #include "FEAMR/FEAMR.h" #include "FEBioMech/FEBioMechModule.h" #ifndef MECH_ONLY #include "FEBioMix/FEBioMix.h" #include "FEBioOpt/FEBioOpt.h" #include "FEBioFluid/FEBioFluid.h" #include <FEBioFluid/FEBioFSI.h> #include <FEBioFluid/FEBioMultiphasicFSI.h> #include <FEBioFluid/FEBioFluidSolutes.h> #include <FEBioFluid/FEBioThermoFluid.h> #include <FEBioFluid/FEBioPolarFluid.h> #include <FEBioTest/FEBioTest.h> #include <FEBioRVE/FEBioRVE.h> #include <FEImgLib/FEImgLib.h> #endif #include "febio.h" #include "plugin.h" #include "FEBioStdSolver.h" #include "FEBioRestart.h" namespace febio { //----------------------------------------------------------------------------- FECoreKernel* GetFECoreKernel() { return &FECoreKernel::GetInstance(); } //----------------------------------------------------------------------------- // import all modules void InitLibrary() { REGISTER_FECORE_CLASS(FEBioStdSolver, "solve"); REGISTER_FECORE_CLASS(FEBioRestart , "restart"); REGISTER_FECORE_CLASS(FEBioRCISolver, "rci_solve"); REGISTER_FECORE_CLASS(FEBioTestSuiteTask, "test"); FECore::InitModule(); FEAMR::InitModule(); NumCore::InitModule(); FEBioMech::InitModule(); #ifndef MECH_ONLY FEBioMix::InitModule(); FEBioOpt::InitModule(); FEBioFluid::InitModule(); FEBioFSI::InitModule(); FEBioMultiphasicFSI::InitModule(); FEBioFluidSolutes::InitModule(); FEBioThermoFluid::InitModule(); FEBioPolarFluid::InitModule(); FEBioTest::InitModule(); FEBioRVE::InitModule(); FEImgLib::InitModule(); #endif } //----------------------------------------------------------------------------- void FinishLibrary() { FEBioPluginManager* pPM = FEBioPluginManager::GetInstance(); pPM->DeleteThis(); } } // namespace febio
C++
3D
febiosoftware/FEBio
FEBioLib/FEBioStdSolver.h
.h
2,453
75
/*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/FECoreKernel.h> //----------------------------------------------------------------------------- // This is the most commenly used task which will run a user-specified input // file. The results are stored in the logfile and the plotfile. class FEBioStdSolver : public FECoreTask { public: FEBioStdSolver(FEModel* pfem); //! initialization bool Init(const char* szfile) override; //! Run the FE model bool Run() override; }; //----------------------------------------------------------------------------- // class for testing reverse communication interface of FEModel class FEBioRCISolver : public FECoreTask { public: FEBioRCISolver(FEModel* fem); //! initialization bool Init(const char* szfile) override; //! Run the FE model bool Run() override; }; //----------------------------------------------------------------------------- // Configures the model for running in the nightly test suite. class FEBioTestSuiteTask : public FECoreTask { public: FEBioTestSuiteTask(FEModel* fem); //! initialization bool Init(const char* szfile) override; //! Run the FE model bool Run() override; };
Unknown
3D
febiosoftware/FEBio
FEBioLib/febiolib_types.h
.h
2,132
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 struct ModelStats { int ntimeSteps = 0; //!< total nr of time steps int ntotalIters = 0; //!< total nr of equilibrium iterations int ntotalRHS = 0; //!< total nr of right hand side evaluations int ntotalReforms = 0; //!< total nr of stiffness reformations double solutionNorm = 0.0; //!< norm of solution }; struct TimingInfo { double total_time = 0; double input_time = 0; double init_time = 0; double solve_time = 0; double io_time = 0; double total_ls_factor = 0; double total_ls_backsolve = 0; double total_reform = 0; double total_stiff = 0; double total_rhs = 0; double total_update = 0; double total_qn = 0; double total_serialize = 0; double total_callback = 0; double total_other = 0; }; struct TimeStepStats { int iters = 0; int nrhs = 0; int refs = 0; int status = 0; // 0 = failed, 1 = converged };
Unknown
3D
febiosoftware/FEBio
FEBioLib/Logfile.h
.h
3,078
105
/*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 <stdio.h> #include <string> #include "LogFileStream.h" //----------------------------------------------------------------------------- //! Class that is used for logging purposes //! This class can output to different //! files at the same time. //! At this time it outputs data to the screen (stdout) and to an external text file. //! Note that this class is implemented as a singleton, in other words, only one //! instance can be created. class FEBIOLIB_API Logfile { public: enum MODE { LOG_NEVER = 0, LOG_FILE = 1, LOG_SCREEN, LOG_FILE_AND_SCREEN }; public: //! constructor Logfile(); //! destructor ~Logfile(); //! open a new logfile bool open(const char* szfile); //! append to existing file bool append(const char* szfile); //! formatted printing void printf(const char* sz, ...); //! print a nice box void printbox(const char* sztitle, const char* sz, ...); //! set the loggin mode MODE SetMode(MODE mode); //! get the loggin mode MODE GetMode(); //! flush the logfile void flush(); //! close the logfile void close(); //! return the file name const std::string& FileName() { return m_fp->GetFileName(); } //! returns if the logfile is ready to be written to bool is_valid() { return (m_fp != 0); } // set the log stream void SetLogStream(LogStream* ps) { m_ps = ps; } // set the file log stream void SetFileStream(LogFileStream* fp) { m_fp = fp; } // return the file handle operator FILE* () { return (m_fp ? m_fp->GetFileHandle() : 0); } private: //! copy constructor is private so that you cannot create it directly Logfile(const Logfile& log){} protected: LogFileStream* m_fp; //!< the actual log file LogStream* m_ps; //!< This stream is used to output to the screen MODE m_mode; //!< mode of log file };
Unknown
3D
febiosoftware/FEBio
FEBioLib/FEBioConfig.h
.h
1,593
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 "febiolib_api.h" class FEBIOLIB_API FEBioConfig { public: FEBioConfig(); void Defaults(); void SetOutputLevel(int n); public: // input parameters bool readPlugins; public: // output parameters (set by reading the config file) int m_printParams; int m_noutput; bool m_bshowErrors; };
Unknown
3D
febiosoftware/FEBio
FEBioLib/getapppath.cpp
.cpp
4,118
131
/*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 "febio.h" #ifdef WIN32 #include "windows.h" #endif #ifdef LINUX #include <unistd.h> #include <string.h> #endif // LINUX #ifdef __APPLE__ #include <sys/param.h> #include <mach-o/dyld.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #endif //----------------------------------------------------------------------------- // This function determines *where* the exe actually lives // This code is from Ian MacArthur from the FLTK forum: fltk.general // int febio::get_app_path (char *pname, size_t pathsize) { long result; int status = -1; #ifdef LINUX /* Oddly, the readlink(2) man page says no NULL is appended. */ /* So you have to do it yourself, based on the return value: */ pathsize --; /* Preserve a space to add the trailing NULL */ result = readlink("/proc/self/exe", pname, pathsize); if (result > 0) { pname[result] = 0; /* add the #@!%ing NULL */ if ((access(pname, 0) == 0)) status = 0; /* file exists, return OK */ /*else name doesn't seem to exist, return FAIL (falls through) */ } #endif /* LINUX */ #ifdef WIN32 result = GetModuleFileNameA(GetModuleHandle(NULL), (LPCH) pname, pathsize); if (result > 0) { /* fix up the dir slashes... */ int len = strlen(pname); int idx; for (idx = 0; idx < len; idx++) { if (pname[idx] == '\\') pname[idx] = '/'; } status = 0; /* file exists, return OK */ /*else name doesn't seem to exist, return FAIL (falls through) */ } #endif /* WIN32 */ #ifdef __APPLE__ /* assume this is OSX */ /* from http://www.hmug.org/man/3/NSModule.html extern int _NSGetExecutablePath(char *buf, unsigned long *bufsize); _NSGetExecutablePath copies the path of the executable into the buffer and returns 0 if the path was successfully copied in the provided buffer. If the buffer is not large enough, -1 is returned and the expected buffer size is copied in *bufsize. Note that _NSGetExecutablePath will return "a path" to the executable not a "real path" to the executable. That is the path may be a symbolic link and not the real file. And with deep directories the total bufsize needed could be more than MAXPATHLEN. */ char given_path[MAXPATHLEN * 2]; pathsize = MAXPATHLEN * 2; uint32_t nsize = (uint32_t) (pathsize); result = _NSGetExecutablePath(given_path, &nsize); if (result == 0) { /* OK, we got something - now try and resolve the real path...*/ if (realpath(given_path, pname) != NULL) { if ((access(pname, 0) == 0)) status = 0; /* file exists, return OK */ } } #endif /* APPLE */ if (status == 0) { // remove the application's name char* ch = strrchr(pname, '\\'); if (ch == 0) ch = strrchr(pname, '/'); if (ch) ch[1] = 0; } return status; }
C++
3D
febiosoftware/FEBio
FEBioLib/memory.cpp
.cpp
1,643
44
/*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 "febiolib_api.h" #include <stddef.h> #ifdef WIN32 #include <windows.h> #include <psapi.h> #endif size_t FEBIOLIB_API GetPeakMemory() { #ifdef WIN32 PROCESS_MEMORY_COUNTERS memCounters; GetProcessMemoryInfo(GetCurrentProcess(), &memCounters, sizeof(memCounters)); return (size_t)memCounters.PeakWorkingSetSize; #else return 0; #endif }
C++
3D
febiosoftware/FEBio
FEBioLib/FEBioModel.h
.h
7,257
265
/*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 <FEBioMech/FEMechModel.h> #include <FECore/Timer.h> #include <FECore/DataStore.h> #include <FEBioPlot/PlotFile.h> #include <FECore/FECoreKernel.h> #include <FEBioLib/Logfile.h> #include "febiolib_api.h" #include "febiolib_types.h" //----------------------------------------------------------------------------- // Dump level determines the times the restart file is written enum FE_Dump_Level { FE_DUMP_NEVER, // never write a dump file FE_DUMP_MAJOR_ITRS, // create a dump file at the end of each converged time step FE_DUMP_STEP, // create a dump file at the end of an analysis step FE_DUMP_MUST_POINTS // create a dump file only on must-points }; enum PlotObjectType { OBJ_UNKNOWN = 0, OBJ_RIGID_BODY = 1, OBJ_GENERIC_JOINT = 2, OBJ_SPHERICAL_JOINT = 3, OBJ_PRISMATIC_JOINT = 4, OBJ_REVOLUTE_JOINT = 5, OBJ_CYLINDRICAL_JOINT = 6, OBJ_PLANAR_JOINT = 7 }; //----------------------------------------------------------------------------- //! The FEBio model specializes the FEModel class to implement FEBio specific //! functionality. //! //! In addition it adds support for all I/O capabilities. //! class FEBIOLIB_API FEBioModel : public FEMechModel { public: //! constructor FEBioModel(); //! destructor ~FEBioModel(); //! Initializes data structures bool Init() override; //! Resets data structures bool Reset() override; //! solve the model bool Solve() override; TimingInfo GetTimingInfo(); public: // --- I/O functions --- //! input data from file bool Input(const char* szfile); //! handle output void Write(unsigned int nwhen); // write to plot file void WritePlot(unsigned int nevent); //! write data to log file void WriteData(unsigned int nevent); //! dump data to archive for restart void DumpData(int nevent); //! add to log void Log(int ntag, const char* szmsg) override; // get the log file Logfile& GetLogFile() { return m_log; } // get the report std::string GetReport() const { return m_report; } void CreateReport(bool b) { m_createReport = b; } public: //! set the problem title void SetTitle(const char* sz); //! get the problem title const std::string& GetTitle() const; public: //! --- serialization for restarts --- //! Write or read data from archive void Serialize(DumpStream& ar) override; //! restart from dump file or restart input file bool Restart(const char* szfile); private: static bool handleCB(FEModel* fem, unsigned int nwhen, void* pd); bool processEvent(int nevent); void on_cb_solved(); void on_cb_stepSolved(); protected: // helper functions for serialization void SerializeIOData (DumpStream& ar); void SerializeDataStore(DumpStream& ar); void SerializePlotData (DumpStream& ar); bool InitLogFile(); bool InitPlotFile(); //! get a list of domains that belong to a specific material void DomainListFromMaterial(vector<int>& lmat, vector<int>& ldom); public: // --- I/O functions --- //! Add data record void AddDataRecord(DataRecord* pd); //! Get the plot file PlotFile* GetPlotFile(); // set the i/o files void SetInputFilename(const std::string& sfile); void SetLogFilename (const std::string& sfile); void SetPlotFilename (const std::string& sfile); void SetDumpFilename (const std::string& sfile); //! Get the I/O file names const std::string& GetInputFileName(); const std::string& GetLogfileName (); const std::string& GetPlotFileName (); const std::string& GetDumpFileName (); //! get the file title const std::string& GetFileTitle(); // set append-on-restart flag void SetAppendOnRestart(bool b); bool AppendOnRestart() const; public: double GetEndTime() const; public: // Timers //! Return the total timer Timer& GetSolveTimer(); public: //! set the debug level void SetDebugLevel(int debugLvl); //! get the debug level int GetDebugLevel(); //! set the dump level (for cold restarts) void SetDumpLevel(int dumpLevel); //! get the dump level int GetDumpLevel() const; //! Set the dump stride void SetDumpStride(int n); //! get the dump stride int GetDumpStride() const; //! Set the log level void SetLogLevel(int logLevel); //! Get the stats ModelStats GetModelStats() const; ModelStats GetStepStats(size_t n) const; std::vector<ModelStats> GetStepStats() const; std::vector<TimeStepStats> GetTimeStepStats() const; // flag to show warnings and errors void ShowWarningsAndErrors(bool b); bool ShowWarningsAndErrors() const; private: void print_parameter(FEParam& p, int level = 0); void print_parameter_list(FEParameterList& pl, int level = 0); void print_parameter_list(FECoreBase* pc, int level = 0); void echo_input(); private: void UpdatePlotObjects(); private: Timer m_TotalTime; //!< timer to track total time Timer m_InputTime; //!< timer to track time to read model Timer m_IOTimer; //!< timer to track output (include plot, dump, and data) PlotFile* m_plot; //!< the plot file bool m_becho; //!< echo input to logfile int m_ndebug; //!< debug level flag bool m_writeMesh; //!< write a new mesh section bool m_bshowErrors; //!< print warnings and errors int m_logLevel; //!< output level for log file int m_dumpLevel; //!< level or writing restart file int m_dumpStride; //!< write dump file every nth iterations private: // accumulative statistics ModelStats m_modelStats; std::vector<ModelStats> m_stepStats; std::vector<TimeStepStats> m_timestepStats; protected: // file names std::string m_sfile_title; //!< input file title std::string m_sfile; //!< input file name (= path + title) std::string m_splot; //!< plot output file name std::string m_slog ; //!< log output file name std::string m_sdump; //!< dump file name std::string m_title; //!< model title protected: bool m_pltAppendOnRestart; int m_lastUpdate; private: Logfile m_log; std::string m_report; bool m_createReport; DECLARE_FECORE_CLASS(); };
Unknown
3D
febiosoftware/FEBio
FEBioLib/FEBioStdSolver.cpp
.cpp
3,794
124
/*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 "FEBioStdSolver.h" #include <FEBioLib/FEBioModel.h> #include <FECore/log.h> #include <FEBioXML/FERestartImport.h> #include <FECore/DumpFile.h> #include <FECore/FEAnalysis.h> #include <FECore/FEModelDataRecord.h> //----------------------------------------------------------------------------- FEBioStdSolver::FEBioStdSolver(FEModel* pfem) : FECoreTask(pfem) {} //----------------------------------------------------------------------------- // This simply calls the FEModel::Init bool FEBioStdSolver::Init(const char* szfile) { return (GetFEModel() ? GetFEModel()->Init() : false); } //----------------------------------------------------------------------------- // This simply calls the FEM::Solve function which will solve the FE problem. bool FEBioStdSolver::Run() { // Solve the problem and return error code return (GetFEModel() ? GetFEModel()->Solve() : false); } //============================================================================= FEBioRCISolver::FEBioRCISolver(FEModel* fem) : FECoreTask(fem) {} //! initialization bool FEBioRCISolver::Init(const char* szfile) { return (GetFEModel() ? GetFEModel()->Init() : false); } //! Run the FE model bool FEBioRCISolver::Run() { // get the model FEModel* fem = GetFEModel(); if (fem == nullptr) return false; // initialize RCI solver if (fem->RCI_Init() == false) return false; // loop until solved while (fem->IsSolved() == false) { // try to advance the solution if (fem->RCI_Advance() == false) { // if we were unable to advance the solution, we do a rewind and try again if (fem->RCI_Rewind() == false) { // couldn't rewind, so we're done break; } } } // finalize the solver if (fem->RCI_Finish() == false) return false; return true; } //========================================================================== FEBioTestSuiteTask::FEBioTestSuiteTask(FEModel* fem) : FECoreTask(fem) {} //! initialization bool FEBioTestSuiteTask::Init(const char* szfile) { FEModel* fem = GetFEModel(); assert(fem); if (fem == nullptr) return false; // See if the model defines any data records DataStore& data = fem->GetDataStore(); if (data.Size() == 0) { FEModelDataRecord* rec = new FEModelDataRecord(fem); rec->SetData("solution_norm"); rec->SetName("solution_norm"); data.AddRecord(rec); } return (GetFEModel() ? GetFEModel()->Init() : false); } //! Run the FE model bool FEBioTestSuiteTask::Run() { return (GetFEModel() ? GetFEModel()->Solve() : false); }
C++
3D
febiosoftware/FEBio
FEBioLib/FEBioModelBuilder.cpp
.cpp
3,856
119
/*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.*/ #include "stdafx.h" #include "FEBioModelBuilder.h" #include "FEBioModel.h" #include <FEBioMech/FEUncoupledMaterial.h> #include <FEBioMech/FEUDGHexDomain.h> #include <FEBioMech/FEUT4Domain.h> #include <FEBioMech/FESSIShellDomain.h> #include <FEBioMech/RigidBC.h> #include <FEBioMech/FERigidForce.h> #include <FEBioMech/FEMechModel.h> // In FEBio 3, the bulk modulus k must be defined at the top - level. // However, this could break backward compatibility, so for older file version // we apply this hack that collects the child moduli and assigns it to the top-level void FixUncoupledMaterial(FEUncoupledMaterial* mat) { double K = mat->m_K; for (int i = 0; i < mat->Properties(); ++i) { FEUncoupledMaterial* mati = dynamic_cast<FEUncoupledMaterial*>(mat->GetProperty(i)); if (mati) { FixUncoupledMaterial(mati); K += mati->m_K; mati->m_K = 0.0; } } mat->m_K = K; } FEBioModelBuilder::FEBioModelBuilder(FEBioModel& fem) : FEModelBuilder(fem) { } void FEBioModelBuilder::AddMaterial(FEMaterial* mat) { FEModel& fem = GetFEModel(); fem.AddMaterial(mat); // For uncoupled materials, we collect the bulk moduli of child materials // and assign it to the top-level material (this one) FEUncoupledMaterial* pucm = dynamic_cast<FEUncoupledMaterial*>(mat); if (pucm) FixUncoupledMaterial(pucm); } FEDomain* FEBioModelBuilder::CreateDomain(FE_Element_Spec espec, FEMaterial* mat) { FEModel& fem = GetFEModel(); FECoreKernel& febio = FECoreKernel::GetInstance(); FEDomain* pdom = febio.CreateDomain(espec, &fem.GetMesh(), mat); // Handle dome special cases // TODO: Find a better way of dealing with these special cases FEUDGHexDomain* udg = dynamic_cast<FEUDGHexDomain*>(pdom); if (udg) { udg->SetHourGlassParameter(m_udghex_hg); } FEUT4Domain* ut4 = dynamic_cast<FEUT4Domain*>(pdom); if (ut4) { ut4->SetUT4Parameters(m_ut4_alpha, m_ut4_bdev); } FESSIShellDomain* ssi = dynamic_cast<FESSIShellDomain*>(pdom); if (ssi) { ssi->m_bnodalnormals = espec.m_shell_norm_nodal; } return pdom; } //----------------------------------------------------------------------------- void FEBioModelBuilder::AddRigidComponent(FEStepComponent* pmc) { FEMechModel& fem = static_cast<FEMechModel&>(GetFEModel()); AddComponent(pmc); FERigidBC* prc = dynamic_cast<FERigidBC*>(pmc); if (prc) { fem.AddRigidBC(prc); return; } FERigidIC* ric = dynamic_cast<FERigidIC*>(pmc); if (ric) { fem.AddRigidInitialCondition(ric); return; } FEModelLoad* pml = dynamic_cast<FEModelLoad*>(pmc); if (pml) { AddModelLoad(pml); return; } assert(false); }
C++
3D
febiosoftware/FEBio
FEBioLib/stdafx.cpp
.cpp
1,385
33
/*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" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
C++