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 | FEBioLib/FEBox.h | .h | 1,507 | 40 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FECore/FEMesh.h"
class FEBoxMesh : public FEMesh
{
public:
FEBoxMesh(FEModel* fem);
virtual ~FEBoxMesh();
void Create(int nx, int ny, int nz, vec3d r0, vec3d r1, FE_Element_Type nhex = FE_HEX8G8);
};
| Unknown |
3D | febiosoftware/FEBio | FEBioLib/FEBioRestart.h | .h | 1,656 | 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/FECoreTask.h>
#include <FECore/FECoreKernel.h>
//-----------------------------------------------------------------------------
// Task that does a cold restart.
class FEBioRestart : public FECoreTask
{
public:
FEBioRestart(FEModel* pfem);
//! initialization
bool Init(const char* szfile) override;
//! Run the FE model
bool Run() override;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioLib/FEBioModelBuilder.h | .h | 1,627 | 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) 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 <FEBioXML/FEModelBuilder.h>
class FEBioModel;
class FEBioModelBuilder : public FEModelBuilder
{
public:
FEBioModelBuilder(FEBioModel& fem);
public:
FEDomain* CreateDomain(FE_Element_Spec espec, FEMaterial* mat) override;
void AddMaterial(FEMaterial* mat) override;
void AddRigidComponent(FEStepComponent* prc) override;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioLib/version.cpp | .cpp | 1,623 | 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.*/
#include <cstdio>
#include "version.h"
char* febio::getVersionString()
{
static char version[32];
#ifndef DEVCOMMIT
snprintf(version, sizeof(version), "%d.%d.%d", VERSION, SUBVERSION, SUBSUBVERSION);
#else
snprintf(version, sizeof(version), "%d.%d.%d.%s", VERSION, SUBVERSION, SUBSUBVERSION, DEVCOMMIT);
#endif
return version;
}
| C++ |
3D | febiosoftware/FEBio | FEBioLib/version.h | .h | 2,104 | 55 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "febiolib_api.h"
///////////////////////////////////////////////////////////////////////////////
// FEBio version numbers
// VERSION is the main version number. This number is only incremented when
// major modifications or additions where added to the code
// SUBVERSION is only incremented when minor modifications or
// additions where added to the code.
// SUBSUBVERSION is incremented when bugs are fixed.
#define VERSION 4
#define SUBVERSION 11
#define SUBSUBVERSION 0
///////////////////////////////////////////////////////////////////////////////
// Restart file version
// This is the version number of the restart dump file format.
// It is incremented when the structure of this file is modified.
//
#define RSTRTVERSION 0x06
namespace febio
{
FEBIOLIB_API char* getVersionString();
}
| Unknown |
3D | febiosoftware/FEBio | FEBioLib/LogFileStream.h | .h | 2,053 | 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 "LogStream.h"
#include "stdio.h"
#include <string>
//-----------------------------------------------------------------------------
// A stream that outputs to a file
class FEBIOLIB_API LogFileStream : public LogStream
{
public:
// constructor
LogFileStream();
// destructor
~LogFileStream();
// open the file
bool open(const char* szfile);
// open for appending
bool append(const char* szfile);
// close the file stream
void close();
// get the file handle
FILE* GetFileHandle() { return m_fp; }
// get the file name
const std::string& GetFileName() const { return m_fileName; }
public:
// print text to the file
void print(const char* sz);
// flush the stream
void flush();
private:
FILE* m_fp;
std::string m_fileName;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioLib/FEBioConfig.cpp | .cpp | 1,520 | 45 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "FEBioConfig.h"
FEBioConfig::FEBioConfig()
{
m_noutput = 1;
Defaults();
}
void FEBioConfig::SetOutputLevel(int n)
{
m_noutput = n;
}
void FEBioConfig::Defaults()
{
m_printParams = -1;
m_bshowErrors = true;
readPlugins = true;
}
| C++ |
3D | febiosoftware/FEBio | NumCore/StrategySolver.h | .h | 2,517 | 82 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/LinearSolver.h>
// This class implements a linear solver that can switch between linear solvers
class StrategySolver : public LinearSolver
{
// the persist strategy determines when to switch back from solver2 to solver1
// after solver1 fails.
// DONT_PERSIST (0) = switch back immediately.
// PERSIST = switch back on the next Destroy()
// PERSIST_FOREVER = switch to solver2 permanently
enum PersistStrategy
{
DONT_PERSIST,
PERSIST,
PERSIST_FOREVER
};
public:
StrategySolver(FEModel* fem);
~StrategySolver();
public:
//! Preprocess
bool PreProcess() override;
//! Factor matrix
bool Factor() override;
//! Backsolve the linear system
bool BackSolve(double* x, double* b) override;
//! Clean up
void Destroy() override;
//! Create a sparse matrix
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
//! set the sparse matrix
bool SetSparseMatrix(SparseMatrix* A) override;
private:
int m_strategy;
double m_ctol;
bool m_print_cn; // print the condition number
LinearSolver* m_solver1; // the primary solver
LinearSolver* m_solver2; // the seoncdary solver
LinearSolver* m_activeSolver;
SparseMatrix* m_pA;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/FGMRESSolver.h | .h | 4,421 | 130 | /*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/Preconditioner.h>
#include <FECore/SparseMatrix.h>
//-----------------------------------------------------------------------------
//! This class implements an interface to the MKL FGMRES iterative solver for
//! nonsymmetric indefinite matrices (without pre-conditioning).
class FGMRESSolver : public IterativeLinearSolver
{
public:
//! constructor
FGMRESSolver(FEModel* fem);
//! do any pre-processing (allocates temp storage)
bool PreProcess() override;
//! Factor the matrix
bool Factor() override;
//! Calculate the solution of RHS b and store solution in x
bool BackSolve(double* x, double* b) override;
//! Clean up
void Destroy() override;
//! Return a sparse matrix compatible with this solver
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
//! Set the sparse matrix
bool SetSparseMatrix(SparseMatrix* pA) override;
//! Set max nr of iterations
void SetMaxIterations(int n);
//! Get the max nr of iterations
int GetMaxIterations() const;
//! Set the nr of non-restarted iterations
void SetNonRestartedIterations(int n);
// Set the print level
void SetPrintLevel(int n) override;
// set residual stopping test flag
void DoResidualStoppingTest(bool b);
// set zero norm stopping test flag
void DoZeroNormStoppingTest(bool b);
// set the relative convergence tolerance for the residual stopping test
void SetRelativeResidualTolerance(double tol);
// set the absolute convergence tolerance for the residual stopping test
void SetAbsoluteResidualTolerance(double tol);
//! This solver does not use a preconditioner
bool HasPreconditioner() const override;
//! convenience function for solving linear system Ax = b
bool Solve(SparseMatrix* A, vector<double>& x, vector<double>& b);
//! fail if max iterations reached
void FailOnMaxIterations(bool b);
//! print the condition number
void PrintConditionNumber(bool b);
// do jacobi preconditioning
void DoJacobiPreconditioning(bool b);
public:
// set the preconditioner
void SetLeftPreconditioner(LinearSolver* P) override;
void SetRightPreconditioner(LinearSolver* P) override;
// get the preconditioner
LinearSolver* GetLeftPreconditioner() override;
LinearSolver* GetRightPreconditioner() override;
protected:
SparseMatrix* GetSparseMatrix() { return m_pA; }
private:
int m_maxiter; // max nr of iterations
int m_nrestart; // max nr of non-restarted iterations
int m_print_level; // output level
bool m_doResidualTest; // do the residual stopping test
bool m_doZeroNormTest; // do the zero-norm stopping test
double m_reltol; // relative residual convergence tolerance
double m_abstol; // absolute residual tolerance
bool m_maxIterFail;
bool m_print_cn; // Calculate and print the condition number
bool m_do_jacobi;
private:
SparseMatrix* m_pA; //!< the sparse matrix format
Preconditioner* m_P; //!< the left preconditioner
Preconditioner* m_R; //!< the right preconditioner
vector<double> m_tmp;
vector<double> m_Rv; //!< used when a right preconditioner is ued
vector<double> m_W; //!< Jacobi preconditioner
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/ILUT_Preconditioner.cpp | .cpp | 3,662 | 128 | /*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 "ILUT_Preconditioner.h"
#include <FECore/CompactUnSymmMatrix.h>
// We must undef PARDISO since it is defined as a function in mkl_solver.h
#ifdef MKL_ISS
#ifdef PARDISO
#undef PARDISO
#endif
#include "mkl_rci.h"
#include "mkl_blas.h"
#include "mkl_spblas.h"
#endif // MKL_ISS
BEGIN_FECORE_CLASS(ILUT_Preconditioner, Preconditioner)
ADD_PARAMETER(m_maxfill, "maxfill");
ADD_PARAMETER(m_fillTol, "filltol");
ADD_PARAMETER(m_checkZeroDiagonal, "replace_zero_diagonal");
ADD_PARAMETER(m_zeroThreshold , "zero_threshold");
ADD_PARAMETER(m_zeroReplace , "zero_replace");
END_FECORE_CLASS();
ILUT_Preconditioner::ILUT_Preconditioner(FEModel* fem) : Preconditioner(fem)
{
m_maxfill = 1;
m_fillTol = 1e-16;
m_checkZeroDiagonal = true;
m_zeroThreshold = 1e-16;
m_zeroReplace = 1e-10;
}
SparseMatrix* ILUT_Preconditioner::CreateSparseMatrix(Matrix_Type ntype)
{
if (ntype != REAL_UNSYMMETRIC) return nullptr;
m_K = new CRSSparseMatrix(1);
SetSparseMatrix(m_K);
return m_K;
}
#ifdef MKL_ISS
bool ILUT_Preconditioner::Factor()
{
if (m_K == 0) return false;
assert(m_K->Offset() == 1);
int N = m_K->Rows();
int ivar = N;
double* pa = m_K->Values();
int* ia = m_K->Pointers();
int* ja = m_K->Indices();
MKL_INT ipar[128] = { 0 };
double dpar[128] = { 0.0 };
if (m_checkZeroDiagonal)
{
ipar[30] = 1;
dpar[30] = m_zeroThreshold;
}
else
{
// do this to avoid a warning from the preconditioner
dpar[30] = m_fillTol;
}
const int PCsize = (2 * m_maxfill + 1)*N - m_maxfill*(m_maxfill + 1) + 1;
m_bilut.resize(PCsize, 0.0);
m_jbilut.resize(PCsize, 0);
m_ibilut.resize(N + 1, 0);
m_tmp.resize(N, 0.0);
int ierr;
dcsrilut(&ivar, pa, ia, ja, &m_bilut[0], &m_ibilut[0], &m_jbilut[0], &m_fillTol, &m_maxfill, ipar, dpar, &ierr);
if (ierr != 0) return false;
return true;
}
bool ILUT_Preconditioner::BackSolve(double* x, double* y)
{
int ivar = m_K->Rows();
char cvar1 = 'L';
char cvar = 'N';
char cvar2 = 'U';
mkl_dcsrtrsv(&cvar1, &cvar, &cvar2, &ivar, &m_bilut[0], &m_ibilut[0], &m_jbilut[0], y, &m_tmp[0]);
cvar1 = 'U';
cvar = 'N';
cvar2 = 'N';
mkl_dcsrtrsv(&cvar1, &cvar, &cvar2, &ivar, &m_bilut[0], &m_ibilut[0], &m_jbilut[0], &m_tmp[0], x);
return true;
}
#else
bool ILUT_Preconditioner::Factor() { return false; }
bool ILUT_Preconditioner::BackSolve(double* x, double* y) { return false; }
#endif | C++ |
3D | febiosoftware/FEBio | NumCore/BoomerAMGSolver.h | .h | 5,173 | 128 | /*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/LinearSolver.h>
class BoomerAMGSolver : public LinearSolver
{
class Implementation;
public:
enum InterpolationType {
INTERPOL_OP_0 = 0, // classicial modified interpolation
INTERPOL_OP_1 = 1, // LS interpolation (for use with GSMG)
INTERPOL_OP_2 = 2, // classical modified interpolation for hyperbolic PDEs
INTERPOL_OP_3 = 3, // direct interpolation (with separation of weights)
INTERPOL_OP_4 = 4, // multipass interpolation
INTERPOL_OP_5 = 5, // multipass interpolation (with separation of weights)
INTERPOL_OP_6 = 6, // extended+i interpolation
INTERPOL_OP_7 = 7, // extended+i (if no common C neighbor) interpolation
INTERPOL_OP_8 = 8, // standard interpolation
INTERPOL_OP_9 = 9, // standard interpolation (with separation of weights)
INTERPOL_OP_10 = 10, // classical block interpolation (for use with nodal systems version only)
INTERPOL_OP_11 = 11, // like 10, with diagonalized blocks
INTERPOL_OP_12 = 12, // FF interpolation
INTERPOL_OP_13 = 13, // FF1 interpolation
INTERPOL_OP_14 = 14, // extended interpolation
};
enum RelaxationType {
JACOBI = 0, // Jacobi
GAUSS_SEIDEL_SEQ = 1, // Gauss-Seidel, sequential (very slow!)
GAUSS_SEIDEL_PAR = 2, // Gauss-Seidel, interior points in parallel, boundary sequential (slow!)
SOR_FORWARD = 3, // hybrid Gauss-Seidel or SOR, forward solve
SOR_BACKWARD = 4, // hybrid Gauss-Seidel or SOR, backward solve
CHAOTIC_GUASS_SEIDEL = 5, // hybrid chaotic Gauss-Seidel (works only with OpenMP)
SYMMETRIC_GAUSS_SEIDEL = 6, // hybrid symmetric Gauss-Seidel or SSOR
SYMMETRIC_GAUSS_SEIDEL_L1 = 8, // l1-scaled hybrid symmetric Gauss-Seidel
GAUSSIAN_ELIMINATION = 9, // Gaussian elimination (only on coarsest level)
CG = 15, // CG (warning - not a fixed smoother - may require RGMRES)
CHEBYSHEV = 16, // Chebyshev
FCF_JACOBI = 17, // FCF-Jacobi
JACOBI_L1 = 18 // l1-scaled Jacobi
};
enum CoarsenType {
COARSE_OP_0 = 0, // CLJP-coarsening (a parallel coarsening algorithm using independent sets)
COARSE_OP_1 = 1, // classical Ruge-Stueben coarsening, no boundary treatment (not recommended!)
COARSE_OP_3 = 3, // classical Ruge-Stueben coarsening, with boundary treatment
COARSE_OP_6 = 6, // Falgout coarsening
COARSE_OP_7 = 7, // CLJP-coarsening (using fix random vector, for debugging purposes only)
COARSE_OP_8 = 8, // PMIS-coarsening (might lead to slower convergence)
COARSE_OP_9 = 9, // PMIS-coarsening (using a fixed random vector ,for debugging purposes only)
COARSE_OP_10 = 10, // HMIS-coarsening
COARSE_OP_11 = 11, // one-pass Ruge-Stueben coarsening (not recommended!)
COARSE_OP_21 = 21, // CGC coarsening
COARSE_OP_22 = 22, // CGC-E coarsening
};
enum AggInterpType {
AGG_IT_0 = 0,
AGG_IT_5 = 5,
AGG_IT_7 = 7,
};
public:
BoomerAMGSolver(FEModel* fem);
~BoomerAMGSolver();
public:
void SetPrintLevel(int printLevel) override;
void SetMaxIterations(int maxIter);
void SetConvergenceTolerance(double tol);
void SetMaxLevels(int levels);
void SetCoarsenType(int coarsenType);
void SetUseNumFunctions(bool b);
void SetRelaxType(int rlxtyp);
void SetInterpType(int inptyp);
void SetStrongThreshold(double thresh);
void SetPMaxElmts(int pmax);
void SetNumSweeps(int nswp);
void SetAggInterpType(int aggit);
void SetAggNumLevels(int anlv);
void SetNodal(int nodal);
void SetJacobiPC(bool b);
void SetFailOnMaxIterations(bool b);
bool GetJacobiPC();
public:
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
bool SetSparseMatrix(SparseMatrix* pA) override;
bool PreProcess() override;
bool Factor() override;
bool BackSolve(double* x, double* y) override;
void Destroy() override;
private:
Implementation* imp;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/FEASTEigenSolver.h | .h | 1,696 | 48 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/SparseMatrix.h>
#include <FECore/matrix.h>
#include <FECore/EigenSolver.h>
class FEASTEigenSolver : public EigenSolver
{
public:
FEASTEigenSolver(FEModel* fem);
bool Init() override;
bool EigenSolve(SparseMatrix* A, SparseMatrix* B, vector<double>& eigenValues, matrix& eigenVectors) override;
private:
int m_fpm[128];
double m_emin, m_emax;
int m_m0;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/RCICGSolver.h | .h | 2,337 | 65 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/Preconditioner.h>
#include <FECore/CompactSymmMatrix.h>
// This class implements an interface to the RCI CG iterative solver from the MKL math library.
class RCICGSolver : public IterativeLinearSolver
{
public:
RCICGSolver(FEModel* fem);
bool PreProcess() override;
bool Factor() override;
bool BackSolve(double* x, double* b) override;
void Destroy() override;
public:
bool HasPreconditioner() const override;
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
bool SetSparseMatrix(SparseMatrix* A) override;
void SetLeftPreconditioner(LinearSolver* P) override;
LinearSolver* GetLeftPreconditioner() override;
void SetMaxIterations(int n) { m_maxiter = n; }
void SetTolerance(double tol) { m_tol = tol; }
void SetPrintLevel(int n) override { m_print_level = n; }
protected:
SparseMatrix* m_pA;
Preconditioner* m_P;
int m_maxiter; // max nr of iterations
double m_tol; // residual relative tolerance
int m_print_level; // output level
bool m_fail_max_iters;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/targetver.h | .h | 1,583 | 37 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
// Including SDKDDKVer.h defines the highest available Windows platform.
// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
#include <SDKDDKVer.h>
| Unknown |
3D | febiosoftware/FEBio | NumCore/PardisoProjectSolver.cpp | .cpp | 11,640 | 333 | /*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 <stdio.h>
#include <stdlib.h>
#include "PardisoProjectSolver.h"
#include "MatrixTools.h"
#include <FECore/log.h>
//! This implementation of the Pardiso solver is for the version
//! available in the Intel MKL.
#ifdef PARDISODL
#include <thread>
/* PARDISO prototype. */
extern "C" void pardisoinit (void *, int *, int *, int *, double *, int *);
extern "C" void pardiso (void *, int *, int *, int *, int *, int *,
double *, int *, int *, int *, int *, int *,
int *, double *, double *, int *, double *);
//-----------------------------------------------------------------------------
// print pardiso error message
void print_err_pdl(int nerror)
{
switch (-nerror)
{
case 1: fprintf(stderr, "Inconsistent input\n"); break;
case 2: fprintf(stderr, "Not enough memory\n"); break;
case 3: fprintf(stderr, "Reordering problem\n"); break;
case 4: fprintf(stderr, "Zero pivot, numerical fact. or iterative refinement problem\n"); break;
case 5: fprintf(stderr, "Unclassified (internal) error\n"); break;
case 6: fprintf(stderr, "Preordering failed\n"); break;
case 7: fprintf(stderr, "Diagonal matrix problem\n"); break;
case 8: fprintf(stderr, "32-bit integer overflow problem\n"); break;
default:
fprintf(stderr, " Unknown\n");
}
}
//////////////////////////////////////////////////////////////
// PardisoProjectSolver
//////////////////////////////////////////////////////////////
BEGIN_FECORE_CLASS(PardisoProjectSolver, LinearSolver)
ADD_PARAMETER(m_print_cn, "print_condition_number");
ADD_PARAMETER(m_iparm3 , "precondition");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
PardisoProjectSolver::PardisoProjectSolver(FEModel* fem) : LinearSolver(fem), m_pA(0)
{
m_print_cn = false;
m_mtype = -2;
m_iparm3 = false;
m_isFactored = false;
/* If both PARDISO AND PARDISODL are defined, print a warning */
#ifdef PARDISO
fprintf(stderr, "WARNING: The pardiso-project version of the Pardiso solver is being used\n\n");
exit(1);
#endif
}
//-----------------------------------------------------------------------------
PardisoProjectSolver::~PardisoProjectSolver()
{
}
//-----------------------------------------------------------------------------
void PardisoProjectSolver::PrintConditionNumber(bool b)
{
m_print_cn = b;
}
//-----------------------------------------------------------------------------
void PardisoProjectSolver::UseIterativeFactorization(bool b)
{
m_iparm3 = b;
}
//-----------------------------------------------------------------------------
SparseMatrix* PardisoProjectSolver::CreateSparseMatrix(Matrix_Type ntype)
{
// allocate the correct matrix format depending on matrix symmetry type
switch (ntype)
{
case REAL_SYMMETRIC : m_mtype = -2; m_pA = new CompactSymmMatrix(1); break;
case REAL_UNSYMMETRIC : m_mtype = 11; m_pA = new CRSSparseMatrix(1); break;
case REAL_SYMM_STRUCTURE: m_mtype = 1; m_pA = new CRSSparseMatrix(1); break;
default:
assert(false);
m_pA = nullptr;
}
return m_pA;
}
//-----------------------------------------------------------------------------
bool PardisoProjectSolver::SetSparseMatrix(SparseMatrix* pA)
{
if (m_pA && m_isFactored) Destroy();
m_pA = dynamic_cast<CompactMatrix*>(pA);
m_mtype = -2;
if (dynamic_cast<CRSSparseMatrix*>(pA)) m_mtype = 11;
return (m_pA != nullptr);
}
//-----------------------------------------------------------------------------
bool PardisoProjectSolver::PreProcess()
{
m_iparm[0] = 0; /* Use default values for parameters */
// for (int i=0; i<64; ++i) m_pt[i] = nullptr;
//fprintf(stderr, "In PreProcess\n");
assert(m_isFactored == false);
int error = 0;
int solver = 0; /* use sparse direct solver */
pardisoinit(m_pt, &m_mtype, &solver, m_iparm, m_dparm, &error);
m_n = m_pA->Rows();
m_nnz = m_pA->NonZeroes();
m_nrhs = 1;
/* Numbers of processors, value of OMP_NUM_THREADS (if available) or
total number of processors on machine */
const auto processor_count = std::thread::hardware_concurrency();
int num_procs = processor_count;
char* var = getenv("OMP_NUM_THREADS");
if (var != NULL)
sscanf( var, "%d", &num_procs );
feLog("Number of processors: %d\n",num_procs);
if (num_procs == 0) {
feLogError("Specify number of processors in environmental variable OMP_NUM_THREADS!");
return false;
}
m_iparm[2] = num_procs;
m_maxfct = 1; /* Maximum number of numerical factorizations */
m_mnum = 1; /* Which factorization to use */
m_msglvl = 0; /* 0 Suppress printing, 1 Print statistical information */
return LinearSolver::PreProcess();
}
//-----------------------------------------------------------------------------
bool PardisoProjectSolver::Factor()
{
// make sure we have work to do
if (m_pA->Rows() == 0) return true;
// ------------------------------------------------------------------------------
// Reordering and Symbolic Factorization. This step also allocates all memory
// that is necessary for the factorization.
// ------------------------------------------------------------------------------
int phase = 11;
int error = 0;
pardiso(m_pt, &m_maxfct, &m_mnum, &m_mtype, &phase, &m_n, m_pA->Values(), m_pA->Pointers(), m_pA->Indices(),
NULL, &m_nrhs, m_iparm, &m_msglvl, NULL, NULL, &error, m_dparm);
if (error)
{
fprintf(stderr, "\nERROR during symbolic factorization: ");
print_err_pdl(error);
exit(2);
}
// ------------------------------------------------------------------------------
// This step does the factorization
// ------------------------------------------------------------------------------
phase = 22;
m_iparm[3] = (m_iparm3 ? 61 : 0);
error = 0;
pardiso(m_pt, &m_maxfct, &m_mnum, &m_mtype, &phase, &m_n, m_pA->Values(), m_pA->Pointers(), m_pA->Indices(),
NULL, &m_nrhs, m_iparm, &m_msglvl, NULL, NULL, &error, m_dparm);
if (error)
{
fprintf(stderr, "\nERROR during factorization: ");
print_err_pdl(error);
return false;
}
// calculate and print the condition number
if (m_print_cn)
{
double c = condition_number();
feLog("\tcondition number (est.) ................... : %lg\n\n", c);
}
m_isFactored = true;
return true;
}
//-----------------------------------------------------------------------------
bool PardisoProjectSolver::BackSolve(double* x, double* b)
{
// make sure we have work to do
if (m_pA->Rows() == 0) return true;
int phase = 33;
m_iparm[7] = 1; /* Maximum number of iterative refinement steps */
int error = 0;
pardiso(m_pt, &m_maxfct, &m_mnum, &m_mtype, &phase, &m_n, m_pA->Values(), m_pA->Pointers(), m_pA->Indices(),
NULL, &m_nrhs, m_iparm, &m_msglvl, b, x, &error, m_dparm);
if (error)
{
fprintf(stderr, "\nERROR during solution: ");
print_err_pdl(error);
exit(3);
}
// update stats
UpdateStats(1);
return true;
}
//-----------------------------------------------------------------------------
// This algorithm (naively) estimates the condition number. It is based on the observation that
// for a linear system of equations A.x = b, the following holds
// || A^-1 || >= ||x||.||b||
// Thus the condition number can be estimated by
// c = ||A||.||A^-1|| >= ||A|| . ||x|| / ||b||
// This algorithm tries for some random b vectors with norm ||b||=1 to maxize the ||x||.
// The returned value will be an underestimate of the condition number
double PardisoProjectSolver::condition_number()
{
// This assumes that the factorization is already done!
int N = m_pA->Rows();
// get the norm of the matrix
double normA = m_pA->infNorm();
// estimate the norm of the inverse of A
double normAi = 0.0;
// choose max iterations
int iters = (N < 50 ? N : 50);
vector<double> b(N, 0), x(N, 0);
for (int i = 0; i < iters; ++i)
{
// create a random vector
NumCore::randomVector(b, -1.0, 1.0);
for (int j = 0; j < N; ++j) b[j] = (b[j] >= 0.0 ? 1.0 : -1.0);
// calculate solution
BackSolve(&x[0], &b[0]);
double normb = NumCore::infNorm(b);
double normx = NumCore::infNorm(x);
if (normx > normAi) normAi = normx;
int pct = (100 * i) / (iters - 1);
fprintf(stderr, "calculating condition number: %d%%\r", pct);
}
double c = normA*normAi;
return c;
}
//-----------------------------------------------------------------------------
void PardisoProjectSolver::Destroy()
{
int phase = -1;
int error = 0;
if (m_pA && m_pA->Pointers() && m_isFactored)
{
pardiso(m_pt, &m_maxfct, &m_mnum, &m_mtype, &phase, &m_n, NULL, m_pA->Pointers(), m_pA->Indices(),
NULL, &m_nrhs, m_iparm, &m_msglvl, NULL, NULL, &error, m_dparm);
}
m_isFactored = false;
}
#else
BEGIN_FECORE_CLASS(PardisoProjectSolver, LinearSolver)
ADD_PARAMETER(m_print_cn, "print_condition_number");
ADD_PARAMETER(m_iparm3, "precondition");
END_FECORE_CLASS();
PardisoProjectSolver::PardisoProjectSolver(FEModel* fem) : LinearSolver(fem) {}
PardisoProjectSolver::~PardisoProjectSolver() {}
bool PardisoProjectSolver::PreProcess() { return false; }
bool PardisoProjectSolver::Factor() { return false; }
bool PardisoProjectSolver::BackSolve(double* x, double* y) { return false; }
void PardisoProjectSolver::Destroy() {}
SparseMatrix* PardisoProjectSolver::CreateSparseMatrix(Matrix_Type ntype) { return nullptr; }
bool PardisoProjectSolver::SetSparseMatrix(SparseMatrix* pA) { return false; }
void PardisoProjectSolver::PrintConditionNumber(bool b) {}
double PardisoProjectSolver::condition_number() { return 0; }
void PardisoProjectSolver::UseIterativeFactorization(bool b) {}
#endif
| C++ |
3D | febiosoftware/FEBio | NumCore/PardisoSolver.cpp | .cpp | 10,831 | 383 | /*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 <stdio.h>
#include <stdlib.h>
#include "PardisoSolver.h"
#include "MatrixTools.h"
#include <FECore/log.h>
//! This implementation of the Pardiso solver is for the version
//! available in the Intel MKL.
#ifdef PARDISO
#undef PARDISO
#include <mkl.h>
#include <mkl_pardiso.h>
#define PARDISO
#else
/* Pardiso prototypes for shared object library version */
#ifdef WIN32
#define pardisoinit_ PARDISOINIT
#define pardiso_ PARDISO
#endif
extern "C"
{
int pardisoinit_(void *, int *, int *, int *, double*, int*);
int pardiso_(void *, int *, int *, int *, int *, int *,
double *, int *, int *, int *, int *, int *,
int *, double *, double *, int *, double*);
}
#endif
#ifdef PARDISO
//-----------------------------------------------------------------------------
// print pardiso error message
void print_err(int nerror)
{
switch (-nerror)
{
case 1: fprintf(stderr, "Inconsistent input\n"); break;
case 2: fprintf(stderr, "Not enough memory\n"); break;
case 3: fprintf(stderr, "Reordering problem\n"); break;
case 4: fprintf(stderr, "Zero pivot, numerical fact. or iterative refinement problem\n"); break;
case 5: fprintf(stderr, "Unclassified (internal) error\n"); break;
case 6: fprintf(stderr, "Preordering failed\n"); break;
case 7: fprintf(stderr, "Diagonal matrix problem\n"); break;
case 8: fprintf(stderr, "32-bit integer overflow problem\n"); break;
default:
fprintf(stderr, " Unknown\n");
}
}
//////////////////////////////////////////////////////////////
// PardisoSolver
//////////////////////////////////////////////////////////////
BEGIN_FECORE_CLASS(PardisoSolver, LinearSolver)
ADD_PARAMETER(m_print_cn, "print_condition_number");
ADD_PARAMETER(m_iparm3 , "precondition");
ADD_PARAMETER(m_msglvl , "msglvl");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
PardisoSolver::PardisoSolver(FEModel* fem) : LinearSolver(fem), m_pA(0)
{
m_print_cn = false;
m_mtype = -2;
m_iparm3 = false;
m_isFactored = false;
m_msglvl = 0; /* 0 Suppress printing, 1 Print statistical information */
}
//-----------------------------------------------------------------------------
PardisoSolver::~PardisoSolver()
{
#ifdef PARDISO
MKL_Free_Buffers();
#endif
}
//-----------------------------------------------------------------------------
void PardisoSolver::PrintConditionNumber(bool b)
{
m_print_cn = b;
}
//-----------------------------------------------------------------------------
void PardisoSolver::UseIterativeFactorization(bool b)
{
m_iparm3 = b;
}
//-----------------------------------------------------------------------------
SparseMatrix* PardisoSolver::CreateSparseMatrix(Matrix_Type ntype)
{
// allocate the correct matrix format depending on matrix symmetry type
switch (ntype)
{
case REAL_SYMMETRIC : m_mtype = -2; m_pA = new CompactSymmMatrix(1); break;
case REAL_UNSYMMETRIC : m_mtype = 11; m_pA = new CRSSparseMatrix(1); break;
case REAL_SYMM_STRUCTURE: m_mtype = 1; m_pA = new CRSSparseMatrix(1); break;
default:
assert(false);
m_pA = nullptr;
}
return m_pA;
}
//-----------------------------------------------------------------------------
bool PardisoSolver::SetSparseMatrix(SparseMatrix* pA)
{
if (m_pA && m_isFactored) Destroy();
m_pA = dynamic_cast<CompactMatrix*>(pA);
m_mtype = -2;
if (dynamic_cast<CRSSparseMatrix*>(pA)) m_mtype = 11;
return (m_pA != nullptr);
}
//-----------------------------------------------------------------------------
bool PardisoSolver::PreProcess()
{
m_iparm[0] = 0; /* Use default values for parameters */
//fprintf(stderr, "In PreProcess\n");
assert(m_isFactored == false);
pardisoinit(m_pt, &m_mtype, m_iparm);
// Turn off reporting the number of non-zero elements in the factors.
// According to the documentation turning this on (set to -1) will
// increase the reordering time.
m_iparm[18] = 0;
// check the matrix offset
m_iparm[34] = 0;
if (m_pA->Offset() == 0) m_iparm[34] = 1;
m_n = m_pA->Rows();
m_nnz = m_pA->NonZeroes();
m_nrhs = 1;
// number of processors: This parameter is no longer used.
// Use OMP_NUM_THREADS
// m_iparm[2] = m_numthreads;
m_maxfct = 1; /* Maximum number of numerical factorizations */
m_mnum = 1; /* Which factorization to use */
return LinearSolver::PreProcess();
}
//-----------------------------------------------------------------------------
bool PardisoSolver::Factor()
{
// make sure we have work to do
if (m_pA->Rows() == 0) return true;
// ------------------------------------------------------------------------------
// Reordering and Symbolic Factorization. This step also allocates all memory
// that is necessary for the factorization.
// ------------------------------------------------------------------------------
int phase = 11;
int error = 0;
pardiso(m_pt, &m_maxfct, &m_mnum, &m_mtype, &phase, &m_n, m_pA->Values(), m_pA->Pointers(), m_pA->Indices(),
NULL, &m_nrhs, m_iparm, &m_msglvl, NULL, NULL, &error);
if (error)
{
fprintf(stderr, "\nERROR during symbolic factorization: ");
print_err(error);
exit(2);
}
if (m_msglvl == 1)
{
int* ip = m_iparm;
fprintf(stdout, "\nMemory info:\n");
fprintf(stdout, "============\n");
fprintf(stdout, "Peak memory on symbolic factorization ............. : %d KB\n", ip[14]);
fprintf(stdout, "Permanent memory on symbolic factorization ........ : %d KB\n", ip[15]);
fprintf(stdout, "Peak memory on numerical factorization and solution : %d KB\n", ip[16]);
fprintf(stdout, "Total peak memory ................................. : %d KB\n\n", max(ip[14], ip[15]+ip[16]));
}
// ------------------------------------------------------------------------------
// This step does the factorization
// ------------------------------------------------------------------------------
phase = 22;
m_iparm[3] = (m_iparm3 ? 61 : 0);
error = 0;
pardiso(m_pt, &m_maxfct, &m_mnum, &m_mtype, &phase, &m_n, m_pA->Values(), m_pA->Pointers(), m_pA->Indices(),
NULL, &m_nrhs, m_iparm, &m_msglvl, NULL, NULL, &error);
if (error)
{
fprintf(stderr, "\nERROR during factorization: ");
print_err(error);
return false;
}
m_isFactored = true;
// calculate and print the condition number
if (m_print_cn)
{
double c = ConditionNumber();
feLog("\tcondition number (est.) ................... : %lg\n\n", c);
}
return true;
}
//-----------------------------------------------------------------------------
bool PardisoSolver::BackSolve(double* x, double* b)
{
// make sure we have work to do
if (m_pA->Rows() == 0) return true;
int phase = 33;
m_iparm[7] = 1; /* Maximum number of iterative refinement steps */
int error = 0;
pardiso(m_pt, &m_maxfct, &m_mnum, &m_mtype, &phase, &m_n, m_pA->Values(), m_pA->Pointers(), m_pA->Indices(),
NULL, &m_nrhs, m_iparm, &m_msglvl, b, x, &error);
if (error)
{
fprintf(stderr, "\nERROR during solution: ");
print_err(error);
exit(3);
}
// update stats
UpdateStats(1);
return true;
}
double PardisoSolver::ConditionNumber()
{
if (m_isFactored == false) return 0.0;
// This assumes that the factorization is already done!
int N = m_pA->Rows();
// get the norm of the matrix
double normA = m_pA->oneNorm();
// estimate the norm of the inverse of A
double normAi = 0.0;
// choose max iterations
// this method should converge, but just in case
int iters = 50;
int steps = 3;
vector<double> b(N, 0), y(N, 0), z(N,0), x(N, 0), v(N, 1);
for (int n = 0; n < steps; ++n)
{
// initialize x
double m = 0.0;
for (int i = 0; i < N; ++i)
{
x[i] = v[i];
m += v[i];
}
for (int i = 0; i < N; ++i) x[i] /= m;
for (int i = 0; i < iters; ++i)
{
BackSolve(&y[0], &x[0]);
for (int j = 0; j < N; ++j)
{
if (y[j] >= 0) b[j] = 1;
else b[j] = -1;
}
// Solve transpose
m_iparm[11] = 2;
BackSolve(&z[0], &b[0]);
m_iparm[11] = 0;
double zmax = 0.0;
int jmax = 0;
double z_dot_x = 0.0;
for (int j = 0; j < N; ++j)
{
if (fabs(z[j]) > zmax)
{
zmax = fabs(z[j]);
jmax = j;
}
z_dot_x += z[j] * x[j];
}
v[jmax] = 0;
if (zmax <= z_dot_x) break;
for (int j = 0; j < N; ++j)
x[j] = (j == jmax ? 1.0 : 0.0);
}
double normAi_n = NumCore::oneNorm(y);
if (normAi_n > normAi) normAi = normAi_n;
else break;
}
double c = normA * normAi;
return c;
}
//-----------------------------------------------------------------------------
void PardisoSolver::Destroy()
{
int phase = -1;
int error = 0;
if (m_pA && m_isFactored)
{
pardiso(m_pt, &m_maxfct, &m_mnum, &m_mtype, &phase, &m_n, NULL, m_pA->Pointers(), m_pA->Indices(),
NULL, &m_nrhs, m_iparm, &m_msglvl, NULL, NULL, &error);
}
m_isFactored = false;
}
#else
BEGIN_FECORE_CLASS(PardisoSolver, LinearSolver)
ADD_PARAMETER(m_print_cn, "print_condition_number");
ADD_PARAMETER(m_iparm3, "precondition");
END_FECORE_CLASS();
PardisoSolver::PardisoSolver(FEModel* fem) : LinearSolver(fem) {}
PardisoSolver::~PardisoSolver() {}
bool PardisoSolver::PreProcess() { return false; }
bool PardisoSolver::Factor() { return false; }
bool PardisoSolver::BackSolve(double* x, double* y) { return false; }
void PardisoSolver::Destroy() {}
SparseMatrix* PardisoSolver::CreateSparseMatrix(Matrix_Type ntype) { return nullptr; }
bool PardisoSolver::SetSparseMatrix(SparseMatrix* pA) { return false; }
void PardisoSolver::PrintConditionNumber(bool b) {}
double PardisoSolver::ConditionNumber() { return 0; }
void PardisoSolver::UseIterativeFactorization(bool b) {}
#endif
| C++ |
3D | febiosoftware/FEBio | NumCore/MKLDSSolver.h | .h | 1,722 | 50 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/LinearSolver.h>
class MKLDSSolver : public LinearSolver
{
class Imp;
public:
MKLDSSolver(FEModel* fem);
~MKLDSSolver();
bool PreProcess() override;
bool Factor() override;
bool BackSolve(double* x, double* y) override;
void Destroy() override;
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
bool SetSparseMatrix(SparseMatrix* pA) override;
protected:
Imp* m;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/SchurSolver.h | .h | 3,588 | 114 | /*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/LinearSolver.h>
#include "BlockMatrix.h"
//-----------------------------------------------------------------------------
// This class implements a solution strategy for solving a linear system that is structured
// as a 2x2 block matrix. It makes no assumption on the symmetry of the global matrix or its blocks.
class SchurSolver : public LinearSolver
{
public:
// options for Schur complement preconditioner
enum Schur_PC {
Schur_PC_NONE,
Schur_PC_DIAGONAL_MASS,
Schur_PC_ICHOL_MASS
};
public:
//! constructor
SchurSolver(FEModel* fem);
//! destructor
~SchurSolver();
public:
//! Preprocess
bool PreProcess() override;
//! Factor matrix
bool Factor() override;
//! Backsolve the linear system
bool BackSolve(double* x, double* b) override;
//! Clean up
void Destroy() override;
//! Create a sparse matrix
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
//! set the sparse matrix
bool SetSparseMatrix(SparseMatrix* A) override;
public:
// get the iteration count
int GetIterations() const;
// set the print level
void SetPrintLevel(int n) override;
void SetSchurPreconditioner(int n);
void ZeroDBlock(bool b);
void DoJacobiPreconditioning(bool b);
void SetSchurBlock(int n);
protected:
// allocate the preconditioner for the Schur complement solver
LinearSolver* BuildSchurPreconditioner(int nopt);
private:
int m_printLevel; //!< set print level
int m_nSchurPreC; //!< Schur preconditioner : 0 = none
bool m_bzeroDBlock;
bool m_doJacobi; //!< apply Jacobi preconditioner to global system
int m_schurBlock; //!< which diagonal block to use for Schur solver? (0 = S\A (default), 1 = S\D)
private:
BlockMatrix* m_pK; //!< block matrix
LinearSolver* m_Asolver; //!< solver for solving A block
LinearSolver* m_SchurAsolver; //!< solver for solving A block inside Schur solver
IterativeLinearSolver* m_schurSolver; //!< solver of Schur complement
LinearSolver* m_PS; //!< preconditioner for the Schur system
CRSSparseMatrix* m_Acopy; //!< A copy of the A-block, needed for some solution strategies
vector<double> m_Wu, m_Wp; //!< inverse of diagonals of global system (used by Jacobi preconditioner)
int m_iter; //!< nr of iterations of last solve
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/IncompleteCholesky.cpp | .cpp | 4,684 | 183 | /*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 "IncompleteCholesky.h"
#include <FECore/CompactSymmMatrix.h>
#include <FECore/log.h>
// We must undef PARDISO since it is defined as a function in mkl_solver.h
#ifdef MKL_ISS
#ifdef PARDISO
#undef PARDISO
#endif
#include "mkl_rci.h"
#include "mkl_blas.h"
#include "mkl_spblas.h"
#endif // MKL_ISS
IncompleteCholesky::IncompleteCholesky(FEModel* fem) : Preconditioner(fem)
{
m_L = nullptr;
}
CompactSymmMatrix* IncompleteCholesky::getMatrix()
{
return m_L;
}
// create a preconditioner for a sparse matrix
bool IncompleteCholesky::Factor()
{
// make sure it's the correct format
CompactSymmMatrix* K = dynamic_cast<CompactSymmMatrix*>(GetSparseMatrix());
if (K == nullptr) return false;
if (K->Offset() != 1) return false;
int N = K->Rows();
int nnz = K->NonZeroes();
z.resize(N, 0.0);
// create the preconditioner
if (m_L) delete m_L;
m_L = new CompactSymmMatrix(K->Offset());
double* val = new double[nnz];
int* row = new int[nnz];
int* col = new int[N + 1];
m_L->alloc(N, N, nnz, val, row, col);
// copy the matrix
double* aval = K->Values();
int* arow = K->Indices();
int* acol = K->Pointers();
for (int i = 0; i < nnz; ++i)
{
val[i] = aval[i];
row[i] = arow[i];
}
for (int i = 0; i <= N; ++i) col[i] = acol[i];
CompactSymmMatrix& L = *m_L;
vector<double> tmp(N, 0.0);
// fill in the values
int offset = m_L->Offset();
for (int k = 0; k < N; ++k)
{
// get the values for column k
double* ak = val + (col[k] - offset);
int* rowk = row + (col[k] - offset);
int Lk = col[k + 1] - col[k];
// sanity check
if (rowk[0] - offset != k)
{
feLogError("Fatal error in incomplete Cholesky preconditioner:\nMatrix format error at row %d.", k);
return false;
}
// make sure the diagonal element is not zero
if (ak[0] == 0.0)
{
feLogError("Fatal error in incomplete Cholesky preconditioner:\nZero diagonal element at row %d.", k);
return false;
}
// make sure the diagonal element is not negative either
if (ak[0] < 0.0)
{
feLogError("Fatal error in incomplete Cholesky preconditioner:\nNegative diagonal element at row %d (value = %lg).", k, ak[0]);
return false;
}
// set the diagonal element
double akk = sqrt(ak[0]);
ak[0] = akk;
tmp[rowk[0] - offset] = akk;
// divide column by akk
for (int j = 1; j < Lk; ++j)
{
ak[j] /= akk;
tmp[rowk[j] - offset] = ak[j];
}
// loop over all other columns
for (int _j = 1; _j < Lk; ++_j)
{
int j = rowk[_j] - offset;
double tjk = tmp[j];
if (tjk != 0.0)
{
double* aj = val + col[j] - offset;
int Lj = col[j + 1] - col[j];
int* rowj = row + col[j] - offset;
for (int i = 0; i < Lj; i ++) aj[i] -= tmp[rowj[i] - offset] * tjk;
}
}
// reset temp buffer
for (int j = 0; j < Lk; ++j) tmp[rowk[j] - offset] = 0.0;
}
for (int i = 0; i < N; ++i)
{
double Lii = L.diag(i);
assert(Lii != 0.0);
}
return true;
}
bool IncompleteCholesky::BackSolve(double* x, double* y)
{
#ifdef MKL_ISS
int ivar = m_L->Rows();
double* pa = m_L->Values();
int* ia = m_L->Pointers();
int* ja = m_L->Indices();
char cvar1 = 'U';
char cvar = 'T';
char cvar2 = 'N';
mkl_dcsrtrsv(&cvar1, &cvar, &cvar2, &ivar, pa, ia, ja, &y[0], &z[0]);
cvar1 = 'U';
cvar = 'N';
cvar2 = 'N';
mkl_dcsrtrsv(&cvar1, &cvar, &cvar2, &ivar, pa, ia, ja, &z[0], &x[0]);
return true;
#else
return true;
#endif
}
| C++ |
3D | febiosoftware/FEBio | NumCore/BlockMatrix.h | .h | 3,928 | 127 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/SparseMatrix.h>
#include <FECore/LinearSolver.h>
#include <FECore/CompactSymmMatrix.h>
#include <FECore/CompactUnSymmMatrix.h>
//-----------------------------------------------------------------------------
// This class implements a diagonally symmetric block-structured matrix. That is
// A matrix for which the diagonal blocks are symmetric, but the off-diagonal
// matrices can be unsymmetric.
class BlockMatrix : public SparseMatrix
{
public:
struct BLOCK
{
int nstart_row, nend_row;
int nstart_col, nend_col;
CompactMatrix* pA;
int Rows() { return nend_row - nstart_row + 1; }
int Cols() { return nend_col - nstart_col + 1; }
bool vmult(vector<double>& x, vector<double>& y)
{
if (pA) return pA->mult_vector(&x[0], &y[0]);
else for (size_t i = 0; i < x.size(); ++i) y[i] = 0.0;
return true;
}
};
public:
BlockMatrix();
~BlockMatrix();
public:
//! Partition the matrix into blocks
void Partition(const vector<int>& part, Matrix_Type mtype, int offset = 1);
public:
//! Create a sparse matrix from a sparse-matrix profile
void Create(SparseMatrixProfile& MP) override;
//! assemble a matrix into the sparse matrix
void Assemble(const matrix& ke, const std::vector<int>& lm) override;
//! assemble a matrix into the sparse matrix
void Assemble(const matrix& ke, const std::vector<int>& lmi, const std::vector<int>& lmj) override;
//! check if a matrix entry was allocated
bool check(int i, int j) override;
//! set entry to value
void set(int i, int j, double v) override;
//! add value to entry
void add(int i, int j, double v) override;
//! retrieve value
double get(int i, int j) override;
//! get the diagonal value
double diag(int i) override;
//! release memory for storing data
void Clear() override;
//! zero matrix elements
void Zero() override;
//! multiply with vector
bool mult_vector(double* x, double* r) override;
//! row and column scale
void scale(const vector<double>& L, const vector<double>& R) override;
public:
//! return number of blocks
int Blocks() const { return (int) m_Block.size(); }
//! get a block
BLOCK& Block(int i, int j);
//! find the partition index of an equation number i
int find_partition(int i);
//! return number of partitions
int Partitions() const { return (int) m_part.size() - 1; }
//! Start equation index of partition i
int StartEquationIndex(int i) { return m_part[i]; }
//! number of equations in partition i
int PartitionEquations(int i) { return m_part[i+1]-m_part[i]; }
protected:
vector<int> m_part; //!< partition list
vector<BLOCK> m_Block; //!< block matrices
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/RCICGSolver.cpp | .cpp | 6,001 | 220 | /*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 "RCICGSolver.h"
#include "IncompleteCholesky.h"
//-----------------------------------------------------------------------------
// We must undef PARDISO since it is defined as a function in mkl_solver.h
#ifdef MKL_ISS
#ifdef PARDISO
#undef PARDISO
#endif
#include "mkl_rci.h"
#include "mkl_blas.h"
#include "mkl_spblas.h"
#endif // MKL_ISS
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(RCICGSolver, IterativeLinearSolver)
ADD_PARAMETER(m_print_level, "print_level");
ADD_PARAMETER(m_tol, "tol");
ADD_PARAMETER(m_maxiter, "max_iter");
ADD_PARAMETER(m_fail_max_iters, "fail_max_iters");
ADD_PROPERTY(m_P, "pc_left")->SetFlags(FEProperty::Optional);
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
RCICGSolver::RCICGSolver(FEModel* fem) : IterativeLinearSolver(fem), m_pA(0), m_P(0)
{
m_maxiter = 0;
m_tol = 1e-5;
m_print_level = 0;
m_fail_max_iters = true;
}
//-----------------------------------------------------------------------------
SparseMatrix* RCICGSolver::CreateSparseMatrix(Matrix_Type ntype)
{
#ifdef MKL_ISS
if (ntype != REAL_SYMMETRIC) return 0;
m_pA = new CompactSymmMatrix(1);
if (m_P) m_P->SetSparseMatrix(m_pA);
return m_pA;
#else
return 0;
#endif
}
//-----------------------------------------------------------------------------
bool RCICGSolver::SetSparseMatrix(SparseMatrix* A)
{
m_pA = A;
return (m_pA != 0);
}
//-----------------------------------------------------------------------------
void RCICGSolver::SetLeftPreconditioner(LinearSolver* P)
{
m_P = dynamic_cast<Preconditioner*>(P);
}
//-----------------------------------------------------------------------------
LinearSolver* RCICGSolver::GetLeftPreconditioner()
{
return m_P;
}
//-----------------------------------------------------------------------------
bool RCICGSolver::HasPreconditioner() const
{
return (m_P != nullptr);
}
//-----------------------------------------------------------------------------
bool RCICGSolver::PreProcess()
{
return true;
}
//-----------------------------------------------------------------------------
bool RCICGSolver::Factor()
{
if (m_pA == 0) return false;
return (m_P ? m_P->Factor() : true);
}
//-----------------------------------------------------------------------------
bool RCICGSolver::BackSolve(double* x, double* b)
{
#ifdef MKL_ISS
// make sure we have a matrix
if (m_pA == 0) return false;
// get number of equations
MKL_INT n = m_pA->Rows();
// zero solution vector
for (int i=0; i<n; ++i) x[i] = 0.0;
// get pointers to solution and RHS vector
double* px = &x[0];
double* pb = &b[0];
// output parameters
MKL_INT rci_request;
MKL_INT ipar[128];
double dpar[128];
vector<double> tmp(n*4);
double* ptmp = &tmp[0];
// initialize parameters
dcg_init(&n, px, pb, &rci_request, ipar, dpar, ptmp);
if (rci_request != 0) return false;
// set the desired parameters:
if (m_maxiter > 0) ipar[4] = m_maxiter; // max nr of iterations
ipar[8] = 1; // do residual stopping test
ipar[9] = 0; // do not request for the user defined stopping test
ipar[10] = (m_P ? 1 : 0); // preconditioning
dpar[0] = m_tol; // set the relative tolerance
// check the consistency of the newly set parameters
dcg_check(&n, px, pb, &rci_request, ipar, dpar, ptmp);
if (rci_request != 0) return false;
// loop until converged
bool bsuccess = false;
bool bdone = false;
do
{
// compute the solution by RCI
dcg(&n, px, pb, &rci_request, ipar, dpar, ptmp);
switch (rci_request)
{
case 0: // solution converged!
bsuccess = true;
bdone = true;
break;
case 1: // compute vector A*tmp[0] and store in tmp[n]
{
bool bret = m_pA->mult_vector(ptmp, ptmp+n);
if (bret == false)
{
bsuccess = false;
bdone = true;
break;
}
if (m_print_level == 1)
{
fprintf(stderr, "%3d = %lg (%lg), %lg (%lg)\n", ipar[3], dpar[4], dpar[3], dpar[6], dpar[7]);
}
}
break;
case 3:
{
assert(m_P);
m_P->mult_vector(ptmp + n*2, ptmp + n*3);
}
break;
default:
bsuccess = false;
bdone = true;
break;
}
}
while (!bdone);
// get convergence information
int niter;
dcg_get(&n, px, pb, &rci_request, ipar, dpar, ptmp, &niter);
if (m_print_level > 0)
{
fprintf(stderr, "%3d = %lg (%lg), %lg (%lg)\n", ipar[3], dpar[4], dpar[3], dpar[6], dpar[7]);
}
UpdateStats(niter);
// release internal MKL buffers
// MKL_Free_Buffers();
return (m_fail_max_iters ? bsuccess : true);
#else
return false;
#endif // MKL_ISS
}
//-----------------------------------------------------------------------------
void RCICGSolver::Destroy()
{
}
| C++ |
3D | febiosoftware/FEBio | NumCore/MatrixTools.cpp | .cpp | 10,024 | 380 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include <FECore/CompactMatrix.h>
#include "MatrixTools.h"
#include "PardisoSolver.h"
#include <stdlib.h>
#include <ostream>
bool NumCore::write_hb(CompactMatrix& K, const char* szfile, int mode)
{
// This currently assumes a CRS matrix
if (mode == 0)
{
FILE* fp = fopen(szfile, "wb");
if (fp == 0) return false;
int symmFlag = K.isSymmetric();
int offset = K.Offset();
int rowFlag = K.isRowBased();
int nrow = K.Rows();
int ncol = K.Columns();
int nsize = nrow; // this is the reason we currently assume CRS
int nnz = K.NonZeroes();
fwrite(&symmFlag, sizeof(symmFlag), 1, fp);
fwrite(&offset, sizeof(offset), 1, fp);
fwrite(&rowFlag, sizeof(rowFlag), 1, fp);
fwrite(&nrow, sizeof(nrow), 1, fp);
fwrite(&ncol, sizeof(ncol), 1, fp);
fwrite(&nnz, sizeof(nnz), 1, fp);
fwrite(K.Pointers(), sizeof(int), nsize + 1, fp);
fwrite(K.Indices(), sizeof(int), nnz, fp);
fwrite(K.Values(), sizeof(double), nnz, fp);
fclose(fp);
}
else
{
FILE* fp = fopen(szfile, "wt");
if (fp == 0) return false;
int symmFlag = K.isSymmetric();
int offset = K.Offset();
int rowFlag = K.isRowBased();
int nrow = K.Rows();
int ncol = K.Columns();
int nsize = nrow; // this is the reason we currently assume CRS
int nnz = K.NonZeroes();
fprintf(fp, "%d // symmetry flag\n", symmFlag);
fprintf(fp, "%d // offset\n", offset);
fprintf(fp, "%d // row flag\n", rowFlag);
fprintf(fp, "%d // number of rows\n", nrow);
fprintf(fp, "%d // number of columns\n", ncol);
fprintf(fp, "%d // nonzeroes\n", nnz);
double* d = K.Values();
for (int i = 0; i < nnz; ++i)
{
fprintf(fp, "%.12lg\n", d[i]);
}
fclose(fp);
}
return true;
}
// write a vector to file
bool NumCore::write_vector(const vector<double>& a, const char* szfile, int mode)
{
if (mode == 0)
{
FILE* fp = fopen(szfile, "wb");
if (fp == 0) return false;
int N = (int)a.size();
fwrite(&N, sizeof(int), 1, fp);
fwrite(&a[0], sizeof(double), N, fp);
fclose(fp);
}
else
{
FILE* fp = fopen(szfile, "wt");
if (fp == 0) return false;
int N = (int)a.size();
fprintf(fp, "%d // size\n", N);
for (int i=0; i<N; ++i)
fprintf(fp, "%lg\n", a[i]);
fclose(fp);
}
return true;
}
CompactMatrix* NumCore::read_hb(const char* szfile)
{
// try to open the file
if (szfile == nullptr) return nullptr;
FILE* fp = fopen(szfile, "rb");
if (fp == nullptr) return nullptr;
int symmFlag, offset, rowFlag;
int nrow = 0, ncol = 0, nnz = 0;
if (fread(&symmFlag, sizeof(int), 1, fp) != 1) return nullptr;
if (fread(&offset , sizeof(int), 1, fp) != 1) return nullptr;
if (fread(&rowFlag , sizeof(int), 1, fp) != 1) return nullptr;
if (fread(&nrow , sizeof(int), 1, fp) != 1) return nullptr;
if (fread(&ncol , sizeof(int), 1, fp) != 1) return nullptr;
if (fread(&nnz , sizeof(int), 1, fp) != 1) return nullptr;
// allocate matrix
int nsize = 0;
CompactMatrix* K = 0;
if (symmFlag == 1)
{
K = new CompactSymmMatrix(offset);
nsize = nrow;
}
else
{
K = new CRSSparseMatrix(offset);
nsize = ncol;
}
// allocate data
double* pa = new double[nnz];
int* pi = new int[nnz];
int* pp = new int[nsize + 1];
K->alloc(nrow, ncol, nnz, pa, pi, pp);
// read in the data
if (fread(pp, sizeof(int) , nsize + 1, fp) != nsize + 1) { fclose(fp); delete K; return 0; }
if (fread(pi, sizeof(int) , nnz , fp) != nnz ) { fclose(fp); delete K; return 0; }
if (fread(pa, sizeof(double), nnz , fp) != nnz ) { fclose(fp); delete K; return 0; }
fclose(fp);
return K;
}
// read vector<double> from file
bool NumCore::read_vector(std::vector<double>& a, const char* szfile)
{
if (szfile == nullptr) return false;
FILE* fp = fopen(szfile, "rb");
if (fp == nullptr) return false;
int N;
fread(&N, sizeof(int), 1, fp);
a.resize(N);
if (fread(&a[0], sizeof(double), N, fp) != N)
{
fclose(fp);
return false;
}
fclose(fp);
return true;
}
// calculate inf-norm of inverse matrix (only works with CRSSparsMatrix(1))
double NumCore::inverse_infnorm(CompactMatrix* A)
{
PardisoSolver solver(0);
if (solver.SetSparseMatrix(A) == false) return 0.0;
if (solver.PreProcess() == false) return 0.0;
if (solver.Factor() == false) return 0.0;
int N = A->Rows();
vector<double> e(N, 0.0), x(N, 0.0);
vector<double> s(N, 0.0);
for (int i = 0; i < N; ++i)
{
// get the i-th column of the inverse matrix
e[i] = 1.0;
solver.BackSolve(&x[0], &e[0]);
// add to net row sums
for (int j = 0; j < N; ++j) s[j] += fabs(x[j]);
// reset e
e[i] = 0.0;
if (i % 100 == 0)
fprintf(stderr, "%.2lg%%\r", 100.0 *i / N);
}
// get the max row sum
double smax = s[0];
for (int i = 1; i < N; ++i) if (s[i] > smax) smax = s[i];
return smax;
}
// calculate condition number of a CRSSparseMatrix(1)
double NumCore::conditionNumber(CRSSparseMatrix* A)
{
double norm = A->infNorm();
double inorm = inverse_infnorm(A);
double c = norm*inorm;
return c;
}
// This algorithm (naively) estimates the condition number. It is based on the observation that
// for a linear system of equations A.x = b, the following holds
// || A^-1 || >= ||x||.||b||
// Thus the condition number can be estimated by
// c = ||A||.||A^-1|| >= ||A|| . ||x|| / ||b||
// This algorithm tries for some random b vectors with norm ||b||=1 to maxize the ||x||.
// The returned value will be an underestimate of the condition number
double NumCore::estimateConditionNumber(SparseMatrix* K)
{
CompactMatrix* A = dynamic_cast<CompactMatrix*>(K);
if (A == nullptr) return 0.0;
double normA = A->infNorm();
PardisoSolver solver(0);
if (solver.SetSparseMatrix(A) == false) return 0.0;
if (solver.PreProcess() == false) return 0.0;
if (solver.Factor() == false) return 0.0;
int N = A->Rows();
double normAi = 0.0;
vector<double> b(N, 0), x(N, 0);
int iters = (N < 50 ? N : 50);
for (int i = 0; i < iters; ++i)
{
// create a random vector
NumCore::randomVector(b, -1.0, 1.0);
for (int j = 0; j < N; ++j) b[j] = (b[j] >= 0.0 ? 1.0 : -1.0);
// calculate solution
solver.BackSolve(&x[0], &b[0]);
double normb = infNorm(b);
double normx = infNorm(x);
if (normx > normAi) normAi = normx;
// int pct = (100 * i) / (iters - 1);
// fprintf(stderr, "calculating condition number: %d%%\r", pct);
}
return normA*normAi;
}
inline double frand() { return rand() / (double)RAND_MAX; }
void NumCore::randomVector(vector<double>& R, double vmin, double vmax)
{
int neq = (int)R.size();
for (int i = 0; i<neq; ++i)
{
R[i] = vmin + frand()*(vmax - vmin);
}
}
// inf-norm of a vector
double NumCore::infNorm(const std::vector<double>& x)
{
double m = 0.0;
for (size_t i = 0; i < x.size(); ++i)
{
double xi = fabs(x[i]);
if (xi > m) m = xi;
}
return m;
}
// 1-norm of a vector
double NumCore::oneNorm(const std::vector<double>& x)
{
double m = 0.0;
for (double xi : x)
{
m += fabs(xi);
}
return m;
}
// print compact matrix pattern to svn file
void NumCore::print_svg(CompactMatrix* m, std::ostream &out, int i0, int j0, int i1, int j1)
{
int rows = m->Rows();
int cols = m->Columns();
if (i0 < 0) i0 = 0;
if (j0 < 0) j0 = 0;
if (i1 == -1) i1 = rows - 1;
if (j1 == -1) j1 = cols - 1;
if (i1 >= rows) i1 = rows - 1;
if (j1 >= cols) j1 = cols - 1;
int rowSpan = i1 - i0 + 1;
int colSpan = j1 - j0 + 1;
out << "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 " << colSpan + 2
<< " " << rowSpan + 2 << " \">\n"
"<style type=\"text/css\" >\n"
" <![CDATA[\n"
" rect.pixel1 {\n"
" fill: #ff0000;\n"
" }\n"
" rect.pixel2 {\n"
" fill: #0000ff;\n"
" }\n"
" ]]>\n"
" </style>\n\n"
" <rect width=\"" << colSpan + 2 << "\" height=\"" << rowSpan + 2 << "\" fill=\"rgb(128, 128, 128)\"/>\n"
" <rect x=\"1\" y=\"1\" width=\"" << colSpan + 0.1 << "\" height=\"" << rowSpan + 0.1
<< "\" fill=\"rgb(255, 255, 255)\"/>\n\n";
double* pd = m->Values();
int* pp = m->Pointers();
int* pi = m->Indices();
int offset = m->Offset();
if (m->isRowBased())
{
int R = m->Rows();
for (int i = i0; i <= i1; ++i)
{
int* pc = pi + (pp[i] - offset);
double* pv = pd + (pp[i] - offset);
int n = pp[i + 1] - pp[i];
for (int k = 0; k < n; ++k)
{
int j = pc[k] - offset;
if ((j >= j0) && (j <= j1))
{
double v = pv[k];
if (v == 0.0)
{
out << " <rect class=\"pixel2\" x=\"" << j - j0 + 1
<< "\" y=\"" << i - i0 + 1
<< "\" width=\".9\" height=\".9\"/>\n";
}
else
{
out << " <rect class=\"pixel1\" x=\"" << j - j0 + 1
<< "\" y=\"" << i + i0 + 1
<< "\" width=\".9\" height=\".9\"/>\n";
}
}
}
}
}
out << "</svg>" << std::endl;
}
| C++ |
3D | febiosoftware/FEBio | NumCore/StrategySolver.cpp | .cpp | 4,188 | 144 | /*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 "StrategySolver.h"
#include "MatrixTools.h"
#include <FECore/log.h>
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(StrategySolver, LinearSolver)
ADD_PARAMETER(m_strategy, "strategy");
ADD_PARAMETER(m_ctol, "max_condition_number");
ADD_PARAMETER(m_print_cn, "print_condition_number");
ADD_PROPERTY(m_solver1, "solver1");
ADD_PROPERTY(m_solver2, "solver2");
END_FECORE_CLASS();
StrategySolver::StrategySolver(FEModel* fem) : LinearSolver(fem)
{
m_strategy = DONT_PERSIST;
m_print_cn = false;
m_ctol = 0;
m_solver1 = nullptr;
m_solver2 = nullptr;
m_activeSolver = nullptr;
m_pA = nullptr;
}
StrategySolver::~StrategySolver()
{
Destroy();
delete m_solver1;
delete m_solver2;
}
//! Preprocess
bool StrategySolver::PreProcess()
{
if (m_solver1->PreProcess() == false) return false;
if (m_solver2->PreProcess() == false) return false;
return true;
}
//! Factor matrix
bool StrategySolver::Factor()
{
if ((m_activeSolver == nullptr) || (m_strategy != PERSIST_FOREVER)) m_activeSolver = m_solver1;
if (m_pA && (m_print_cn || ((m_ctol > 0.0) && (m_activeSolver == m_solver1))))
{
double c = NumCore::estimateConditionNumber(m_pA);
if (m_print_cn) feLog("\nEst. condition number: %lg\n\n", c);
if ((m_ctol > 0.0) && (c >= m_ctol))
{
feLogWarning("Condition number too large: %lg\nSwitching to secondary solver.", c);
m_activeSolver = m_solver2;
}
}
return m_activeSolver->Factor();
}
//! Backsolve the linear system
bool StrategySolver::BackSolve(double* x, double* b)
{
assert(m_activeSolver);
bool success = m_activeSolver->BackSolve(x, b);
if ((success == false) && (m_activeSolver != m_solver2))
{
feLogError("Primary linear solver failed. Trying secondary linear solver ...");
m_activeSolver = m_solver2;
m_solver2->Factor();
success = m_solver2->BackSolve(x, b);
if (m_strategy == DONT_PERSIST)
{
m_solver2->Destroy();
m_activeSolver = m_solver1;
}
}
return success;
}
//! Clean up
void StrategySolver::Destroy()
{
m_solver1->Destroy();
m_solver2->Destroy();
if (m_strategy != PERSIST_FOREVER) m_activeSolver = nullptr;
}
//! Create a sparse matrix
SparseMatrix* StrategySolver::CreateSparseMatrix(Matrix_Type ntype)
{
// let solver1 create the sparse system
if (m_solver1 == nullptr) return nullptr;
SparseMatrix* A = m_solver1->CreateSparseMatrix(ntype);
if (A == nullptr) return nullptr;
// see if this format works for the second solver
if ((m_solver2 == nullptr) || (m_solver2->SetSparseMatrix(A) == false)) {
delete A;
return nullptr;
}
m_pA = A;
return A;
}
//! set the sparse matrix
bool StrategySolver::SetSparseMatrix(SparseMatrix* A)
{
if ((m_solver1 == nullptr) || (m_solver1->SetSparseMatrix(A) == false)) return false;
if ((m_solver2 == nullptr) || (m_solver2->SetSparseMatrix(A) == false)) return false;
return true;
}
| C++ |
3D | febiosoftware/FEBio | NumCore/stdafx.h | .h | 1,510 | 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
#include <stdio.h> | Unknown |
3D | febiosoftware/FEBio | NumCore/TestSolver.h | .h | 1,949 | 55 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/LinearSolver.h>
#include <FECore/CompactUnSymmMatrix.h>
#include <FECore/CompactSymmMatrix.h>
// Test solver. Doesn't actually solve anything. Just returns 0 as solution.
class TestSolver : public LinearSolver
{
public:
TestSolver(FEModel* fem);
~TestSolver();
bool PreProcess() override;
bool Factor() override;
bool BackSolve(double* x, double* y) override;
void Destroy() override;
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
bool SetSparseMatrix(SparseMatrix* pA) override;
protected:
CompactMatrix* m_pA;
int m_mtype; // matrix type
// Matrix data
int m_n, m_nnz, m_nrhs;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/ILU0_Preconditioner.cpp | .cpp | 3,468 | 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 "ILU0_Preconditioner.h"
#include <FECore/CompactUnSymmMatrix.h>
// We must undef PARDISO since it is defined as a function in mkl_solver.h
#ifdef MKL_ISS
#ifdef PARDISO
#undef PARDISO
#endif
#include "mkl_rci.h"
#include "mkl_blas.h"
#include "mkl_spblas.h"
#endif // MKL_ISS
BEGIN_FECORE_CLASS(ILU0_Preconditioner, Preconditioner)
ADD_PARAMETER(m_checkZeroDiagonal, "replace_zero_diagonal");
ADD_PARAMETER(m_zeroThreshold , "zero_threshold");
ADD_PARAMETER(m_zeroReplace , "zero_replace");
END_FECORE_CLASS();
//=================================================================================================
ILU0_Preconditioner::ILU0_Preconditioner(FEModel* fem) : Preconditioner(fem)
{
m_checkZeroDiagonal = true;
m_zeroThreshold = 1e-16;
m_zeroReplace = 1e-10;
m_K = 0;
}
SparseMatrix* ILU0_Preconditioner::CreateSparseMatrix(Matrix_Type ntype)
{
if (ntype != REAL_UNSYMMETRIC) return nullptr;
m_K = new CRSSparseMatrix(1);
return m_K;
}
#ifdef MKL_ISS
bool ILU0_Preconditioner::Factor()
{
if (m_K == 0) return false;
assert(m_K->Offset() == 1);
int N = m_K->Rows();
int NNZ = m_K->NonZeroes();
double* pa = m_K->Values();
int* ia = m_K->Pointers();
int* ja = m_K->Indices();
MKL_INT ipar[128] = { 0 };
double dpar[128] = { 0.0 };
// parameters affecting the pre-conditioner
if (m_checkZeroDiagonal)
{
ipar[30] = 1;
dpar[30] = m_zeroThreshold;
dpar[31] = m_zeroReplace;
}
m_tmp.resize(N, 0.0);
m_bilu0.resize(NNZ);
int ierr = 0;
dcsrilu0(&N, pa, ia, ja, &m_bilu0[0], ipar, dpar, &ierr);
if (ierr != 0) return false;
return true;
}
bool ILU0_Preconditioner::BackSolve(double* x, double* y)
{
int ivar = m_K->Rows();
int* ia = m_K->Pointers();
int* ja = m_K->Indices();
char cvar1 = 'L';
char cvar = 'N';
char cvar2 = 'U';
mkl_dcsrtrsv(&cvar1, &cvar, &cvar2, &ivar, &m_bilu0[0], ia, ja, &y[0], &m_tmp[0]);
cvar1 = 'U';
cvar = 'N';
cvar2 = 'N';
mkl_dcsrtrsv(&cvar1, &cvar, &cvar2, &ivar, &m_bilu0[0], ia, ja, &m_tmp[0], &x[0]);
return true;
}
#else
bool ILU0_Preconditioner::Factor() { return false; }
bool ILU0_Preconditioner::BackSolve(double* x, double* y) { return false; }
#endif
| C++ |
3D | febiosoftware/FEBio | NumCore/PardisoSolver64.h | .h | 1,775 | 51 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/LinearSolver.h>
class PardisoSolver64 : public LinearSolver
{
class Imp;
public:
PardisoSolver64(FEModel* fem);
~PardisoSolver64();
bool PreProcess() override;
bool Factor() override;
bool BackSolve(double* x, double* y) override;
void Destroy() override;
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
bool SetSparseMatrix(SparseMatrix* pA) override;
void UseIterativeFactorization(bool b);
protected:
Imp& m;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/AccelerateSparseSolver.cpp | .cpp | 20,622 | 537 | /*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 <stdio.h>
#include <stdlib.h>
#include "AccelerateSparseSolver.h"
#include "MatrixTools.h"
#include <FECore/log.h>
#ifdef HAS_ACCEL
class AccelerateSparseSolver::Implementation
{
public:
FEModel* m_fem;
CompactMatrix* m_pA;
int m_mtype; // matrix type
#ifdef __APPLE__
SparseMatrixStructure SMS;
SparseMatrix_Double A;
SparseOpaqueSymbolicFactorization ASS;
SparseSymbolicFactorOptions SSFO;
SparseOpaqueFactorization_Double ASF;
long* colS;
std::vector<long> pointers;
SparseIterativeStatus_t SStatus;
#endif
// solver control parameters
// Matrix data
int m_n, m_nnz, m_nrhs;
bool m_print_cn; // estimate and print the condition number
bool m_iparm3; // use direct-iterative method
bool m_isFactored;
int m_ftype; // factorization type
int m_ordmthd; // order method
int m_itrmthd; // iterative method
int m_maxiter; // max number of iterations
int m_rtol; // absolute tolerance
int m_atol; // relative tolerance
int m_print_level; // print level for status updates
public:
Implementation()
{
m_print_cn = false;
m_mtype = -2;
m_iparm3 = false;
m_isFactored = false;
m_ftype = -1;
m_ordmthd = -1;
m_itrmthd = ITSparseLSMR;
m_pA = nullptr;
m_maxiter = 1000;
m_rtol = 1e-3;
m_atol = 1e-12;
m_print_level = 0;
}
};
//////////////////////////////////////////////////////////////
// AccelerateSparseSolver
//////////////////////////////////////////////////////////////
BEGIN_FECORE_CLASS(AccelerateSparseSolver, LinearSolver)
ADD_PARAMETER(imp->m_print_cn, "print_condition_number");
ADD_PARAMETER(imp->m_iparm3 , "iterative");
ADD_PARAMETER(imp->m_ftype , "factorization");
ADD_PARAMETER(imp->m_ordmthd , "order_method");
ADD_PARAMETER(imp->m_itrmthd , "iterative_method");
ADD_PARAMETER(imp->m_maxiter , "max_iter");
ADD_PARAMETER(imp->m_print_level, "print_level");
ADD_PARAMETER(imp->m_rtol , "rtol");
ADD_PARAMETER(imp->m_atol , "atol");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
AccelerateSparseSolver::AccelerateSparseSolver(FEModel* fem) : LinearSolver(fem), imp(new AccelerateSparseSolver::Implementation)
{
imp->m_fem = fem;
}
//-----------------------------------------------------------------------------
AccelerateSparseSolver::~AccelerateSparseSolver()
{
Destroy();
}
//-----------------------------------------------------------------------------
void AccelerateSparseSolver::PrintConditionNumber(bool b)
{
imp->m_print_cn = b;
}
//-----------------------------------------------------------------------------
void AccelerateSparseSolver::UseIterativeFactorization(bool b)
{
imp->m_iparm3 = b;
}
//-----------------------------------------------------------------------------
void AccelerateSparseSolver::SetFactorizationType(int ftype)
{
imp->m_ftype = ftype;
}
void AccelerateSparseSolver::SetPrintLevel(int printlevel)
{
imp->m_print_level = printlevel;
}
//-----------------------------------------------------------------------------
void AccelerateSparseSolver::SetOrderMethod(int order)
{
imp->m_ordmthd = order;
}
//-----------------------------------------------------------------------------
bool AccelerateSparseSolver::IsIterative() const
{
return imp->m_iparm3;
}
//-----------------------------------------------------------------------------
void AccelerateSparseSolver::MyReportError(const char* message) {
fprintf(stderr, "\n\tERROR during iterative solve: %s\n",message);
}
//-----------------------------------------------------------------------------
void AccelerateSparseSolver::MyReportStatus(const char* message) {
fprintf(stdout, "iterative solver status: %s",message);
return;
}
//-----------------------------------------------------------------------------
SparseMatrix* AccelerateSparseSolver::CreateSparseMatrix(Matrix_Type ntype)
{
// allocate the correct matrix format depending on matrix symmetry type
switch (ntype)
{
case REAL_SYMMETRIC : imp->m_mtype = -2; imp->m_pA = new CCSSparseMatrix(0); break;
case REAL_UNSYMMETRIC : imp->m_mtype = 11; imp->m_pA = new CCSSparseMatrix(0); break;
case REAL_SYMM_STRUCTURE: imp->m_mtype = 1; imp->m_pA = new CCSSparseMatrix(0); break;
default:
assert(false);
imp->m_pA = nullptr;
}
return imp->m_pA;
}
//-----------------------------------------------------------------------------
bool AccelerateSparseSolver::SetSparseMatrix(SparseMatrix* pA)
{
if (imp->m_pA && imp->m_isFactored) Destroy();
imp->m_pA = dynamic_cast<CompactMatrix*>(pA);
imp->m_mtype = -2;
if (dynamic_cast<CCSSparseMatrix*>(pA)) imp->m_mtype = 11;
return (imp->m_pA != nullptr);
}
//-----------------------------------------------------------------------------
bool AccelerateSparseSolver::PreProcess()
{
assert(imp->m_isFactored == false);
imp->m_n = imp->m_pA->Rows();
imp->m_nnz = imp->m_pA->NonZeroes();
imp->m_nrhs = 1;
imp->pointers.resize(imp->m_nnz);
for (int i=0; i<imp->m_nnz; ++i) imp->pointers[i] = imp->m_pA->Pointers()[i];
imp->colS = &imp->pointers[0];
if (__builtin_available(macOS 10.13, *)) {
imp->SMS.columnCount = imp->m_pA->Columns();
imp->SMS.rowCount = imp->m_pA->Rows();
imp->SMS.rowIndices = imp->m_pA->Indices();
imp->SMS.columnStarts = imp->colS;
imp->SMS.blockSize = 1;
if (!imp->m_iparm3) {
imp->SSFO.control = SparseDefaultControl;
imp->SSFO.order = nullptr;
imp->SSFO.ignoreRowsAndColumns = nullptr;
imp->SSFO.malloc = malloc;
imp->SSFO.free = free;
imp->SSFO.reportError = MyReportError;
if (imp->m_mtype == 11) {
// Use QR factorization as default for non-symmetric matrix
imp->SMS.attributes.kind = SparseOrdinary;
switch (imp->m_ordmthd) {
case OMSparseOrderAMD:
imp->SSFO.orderMethod = SparseOrderAMD;
break;
case OMSparseOrderMetis:
imp->SSFO.orderMethod = SparseOrderMetis;
break;
case OMSparseOrderCOLAMD:
imp->SSFO.orderMethod = SparseOrderCOLAMD;
break;
default:
imp->SSFO.orderMethod = SparseOrderCOLAMD;
break;
}
switch (imp->m_ftype) {
case -1:
case FTSparseFactorizationQR:
imp->ASS = SparseFactor(SparseFactorizationQR, imp->SMS, imp->SSFO);
break;
case FTSparseFactorizationCholeskyAtA:
imp->ASS = SparseFactor(SparseFactorizationCholeskyAtA, imp->SMS, imp->SSFO);
break;
default:
fprintf(stderr, "\nIncorrect factorization type for non-symmetric matrix!");
return false;
break;
}
}
else {
// Use LDLT as default factorization for symmetric matrix
// (Cholesky factorization does not seem to work)
imp->SMS.attributes.kind = SparseSymmetric;
switch (imp->m_ordmthd) {
case -1:
case OMSparseOrderAMD:
imp->SSFO.orderMethod = SparseOrderAMD;
break;
case OMSparseOrderMetis:
imp->SSFO.orderMethod = SparseOrderMetis;
break;
default:
fprintf(stderr, "\nIncorrect order method for symmetric matrix!");
return false;
break;
}
switch (imp->m_ftype) {
case FTSparseFactorizationCholesky:
imp->ASS = SparseFactor(SparseFactorizationCholesky, imp->SMS, imp->SSFO);
break;
case FTSparseFactorizationLDLT:
imp->ASS = SparseFactor(SparseFactorizationLDLT, imp->SMS, imp->SSFO);
break;
case FTSparseFactorizationLDLTUnpivoted:
imp->ASS = SparseFactor(SparseFactorizationLDLTUnpivoted, imp->SMS, imp->SSFO);
break;
case FTSparseFactorizationLDLTSBK:
imp->ASS = SparseFactor(SparseFactorizationLDLTSBK, imp->SMS, imp->SSFO);
break;
case -1: // default factorization
case FTSparseFactorizationLDLTTPP:
imp->ASS = SparseFactor(SparseFactorizationLDLTTPP, imp->SMS, imp->SSFO);
break;
default:
fprintf(stderr, "\nIncorrect factorization type for symmetric matrix!");
return false;
break;
}
}
}
else {
// for iterative solving we don't need to factorize
return true;
}
}
else {
// Fallback on earlier versions
fprintf(stderr, "\nERROR during preprocessing: ");
fprintf(stderr, "\naccelerate solver not available for macOS earlier than 10.13!");
return false;
}
return LinearSolver::PreProcess();
}
//-----------------------------------------------------------------------------
bool AccelerateSparseSolver::Factor()
{
// make sure we have work to do
if (imp->m_pA->Rows() == 0) return true;
// ------------------------------------------------------------------------------
// This step does the factorization
// ------------------------------------------------------------------------------
if (__builtin_available(macOS 10.13, *)) {
// create the sparse matrix
imp->A.data = imp->m_pA->Values();
imp->A.structure = imp->SMS;
// for iterative solves we don't factor
if (imp->m_iparm3) {
return true;
}
else {
imp->ASF = SparseFactor(imp->ASS,imp->A);
if (imp->ASF.status != SparseStatusOK) {
fprintf(stderr, "\n\tERROR during factorization:");
switch (imp->ASF.status) {
case SparseFactorizationFailed:
fprintf(stderr, "\n\tFactorization failed!");
break;
case SparseMatrixIsSingular:
fprintf(stderr, "\n\tSparse matrix is singular!");
break;
case SparseInternalError:
fprintf(stderr, "\n\tSolver called internal error!");
break;
case SparseParameterError:
fprintf(stderr, "\n\tSolver called parameter error!");
break;
default:
fprintf(stderr, "\n\tUnknown error!");
}
return false;
}
}
}
else {
// Fallback on earlier versions
fprintf(stderr, "\nERROR during factorization: ");
fprintf(stderr, "\nAccelerate solver not available for macOS earlier than 10.13!");
return false;
}
// calculate and print the condition number
if (imp->m_print_cn)
{
double c = condition_number();
feLog("\tcondition number (est.) ................... : %lg\n\n", c);
}
imp->m_isFactored = true;
return true;
}
//-----------------------------------------------------------------------------
bool AccelerateSparseSolver::BackSolve(double* x, double* b)
{
// make sure we have work to do
if (imp->m_pA->Rows() == 0) return true;
if ((!imp->m_iparm3) && (imp->m_isFactored == false)) return true;
DenseVector_Double X, B;
X.count = B.count = imp->m_n;
X.data = x; B.data = b;
// solve the system
if (__builtin_available(macOS 10.13, *)) {
if (!imp->m_iparm3) {
SparseSolve(imp->ASF,B,X);
}
else {
switch (imp->m_itrmthd) {
case ITSparseConjugateGradient:
SparseCGOptions cg_opt;
cg_opt.maxIterations = imp->m_maxiter;
cg_opt.rtol = imp->m_rtol;
cg_opt.atol = imp->m_atol;
cg_opt.reportError = MyReportError;
cg_opt.reportStatus = (imp->m_print_level>0) ? MyReportStatus : nullptr;
imp->SStatus = SparseSolve(SparseConjugateGradient(cg_opt),imp->A,B,X,SparsePreconditionerDiagonal);
break;
case ITSparseGMRES:
case ITSparseDQGMRES:
case ITSparseFGMRES:
SparseGMRESOptions gmres_opt;
gmres_opt.maxIterations = imp->m_maxiter;
gmres_opt.reportError = MyReportError;
gmres_opt.reportStatus = (imp->m_print_level>0) ? MyReportStatus : nullptr;
gmres_opt.nvec = 0;
gmres_opt.rtol = imp->m_rtol;
gmres_opt.atol = imp->m_atol;
switch (imp->m_itrmthd) {
case ITSparseGMRES:
gmres_opt.variant = SparseVariantGMRES;
imp->SStatus = SparseSolve(SparseGMRES(gmres_opt),imp->A,B,X,SparsePreconditionerDiagonal);
break;
case ITSparseDQGMRES:
gmres_opt.variant = SparseVariantDQGMRES;
imp->SStatus = SparseSolve(SparseGMRES(gmres_opt),imp->A,B,X,SparsePreconditionerNone);
break;
case ITSparseFGMRES:
gmres_opt.variant = SparseVariantFGMRES;
imp->SStatus = SparseSolve(SparseGMRES(gmres_opt),imp->A,B,X,SparsePreconditionerDiagScaling);
break;
}
break;
case ITSparseLSMR:
SparseLSMROptions lsmr_opt;
lsmr_opt.rtol = imp->m_rtol;
lsmr_opt.atol = imp->m_atol;
lsmr_opt.reportError = MyReportError;
lsmr_opt.reportStatus = (imp->m_print_level>0) ? MyReportStatus : nullptr;
imp->SStatus = SparseSolve(SparseLSMR(lsmr_opt),imp->A,B,X,SparsePreconditionerDiagScaling);
break;
}
if (imp->SStatus != SparseIterativeConverged) {
fprintf(stderr, "\n\tERROR during iterative solution:\n");
switch (imp->SStatus) {
case SparseIterativeIllConditioned:
fprintf(stderr, "\n\tIll-conditioned system!\n");
break;
case SparseIterativeInternalError:
fprintf(stderr, "\n\tInternal failure!\n");
break;
case SparseIterativeMaxIterations:
fprintf(stderr, "\n\tExceeded maximum iteration limit!\n");
break;
case SparseIterativeParameterError:
fprintf(stderr, "\n\tError with one or more parameters!\n");
break;
default:
fprintf(stderr, "\n\tUnknown error!\n");
}
return false;
}
}
} else {
// Fallback on earlier versions
fprintf(stderr, "\nERROR during back solve: ");
fprintf(stderr, "\nAccelerate solver not available for macOS earlier than 10.13!");
return false;
}
// update stats
UpdateStats(1);
return true;
}
//-----------------------------------------------------------------------------
// This algorithm (naively) estimates the condition number. It is based on the observation that
// for a linear system of equations A.x = b, the following holds
// || A^-1 || >= ||x||.||b||
// Thus the condition number can be estimated by
// c = ||A||.||A^-1|| >= ||A|| . ||x|| / ||b||
// This algorithm tries for some random b vectors with norm ||b||=1 to maxize the ||x||.
// The returned value will be an underestimate of the condition number
double AccelerateSparseSolver::condition_number()
{
// This assumes that the factorization is already done!
int N = imp->m_pA->Rows();
// get the norm of the matrix
double normA = imp->m_pA->infNorm();
// estimate the norm of the inverse of A
double normAi = 0.0;
// choose max iterations
int iters = (N < 50 ? N : 50);
vector<double> b(N, 0), x(N, 0);
for (int i = 0; i < iters; ++i)
{
// create a random vector
NumCore::randomVector(b, -1.0, 1.0);
for (int j = 0; j < N; ++j) b[j] = (b[j] >= 0.0 ? 1.0 : -1.0);
// calculate solution
BackSolve(&x[0], &b[0]);
double normx = NumCore::infNorm(x);
if (normx > normAi) normAi = normx;
int pct = (100 * i) / (iters - 1);
fprintf(stderr, "calculating condition number: %d%%\r", pct);
}
double c = normA*normAi;
return c;
}
//-----------------------------------------------------------------------------
void AccelerateSparseSolver::Destroy()
{
if (imp->m_pA && imp->m_isFactored)
{
SparseCleanup(imp->ASS);
SparseCleanup(imp->ASF);
}
imp->m_isFactored = false;
}
#else
BEGIN_FECORE_CLASS(AccelerateSparseSolver, LinearSolver)
END_FECORE_CLASS();
AccelerateSparseSolver::AccelerateSparseSolver(FEModel* fem) : LinearSolver(fem) {}
AccelerateSparseSolver::~AccelerateSparseSolver() {}
bool AccelerateSparseSolver::PreProcess() { return false; }
bool AccelerateSparseSolver::Factor() { return false; }
bool AccelerateSparseSolver::BackSolve(double* x, double* y) { return false; }
void AccelerateSparseSolver::Destroy() {}
SparseMatrix* AccelerateSparseSolver::CreateSparseMatrix(Matrix_Type ntype) { return nullptr; }
bool AccelerateSparseSolver::SetSparseMatrix(SparseMatrix* pA) { return false; }
void AccelerateSparseSolver::PrintConditionNumber(bool b) {}
double AccelerateSparseSolver::condition_number() { return 0; }
void AccelerateSparseSolver::UseIterativeFactorization(bool b) {}
void AccelerateSparseSolver::SetFactorizationType(int ftype) {}
void AccelerateSparseSolver::SetPrintLevel(int printlevel) {}
bool AccelerateSparseSolver::IsIterative() const { return false; }
#endif
| C++ |
3D | febiosoftware/FEBio | NumCore/BlockSolver.h | .h | 3,292 | 111 | /*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/LinearSolver.h>
#include "BlockMatrix.h"
#include "PardisoSolver.h"
//-----------------------------------------------------------------------------
// This class implements an iterative block solution strategy for solving linear
// systems.
class BlockIterativeSolver : public IterativeLinearSolver
{
public:
enum SOLUTION_METHOD {
JACOBI,
GAUSS_SEIDEL
};
public:
//! constructor
BlockIterativeSolver(FEModel* fem);
//! destructor
~BlockIterativeSolver();
//! Preprocess
bool PreProcess() override;
//! Factor matrix
bool Factor() override;
//! Backsolve the linear system
bool BackSolve(double* x, double* y) override;
//! Clean up
void Destroy() override;
//! Create a sparse matrix
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
//! set the sparse matrix
bool SetSparseMatrix(SparseMatrix* m) override;
// return whether the iterative solver has a preconditioner or not
bool HasPreconditioner() const override;
public:
// Set the relative convergence tolerance
void SetRelativeTolerance(double tol);
// set the max nr of iterations
void SetMaxIterations(int maxiter);
// get the iteration count
int GetIterations() const;
// set fail on max iterations flag
void SetFailMaxIters(bool b);
// set the print level
void SetPrintLevel(int n) override;
// set the solution method
void SetSolutionMethod(int method);
// set the zero-initial-guess flag
void SetZeroInitialGuess(bool b);
private:
BlockMatrix* m_pA; //!< block matrices
vector<PardisoSolver*> m_solver; //!< solvers for solving diagonal blocks
private:
int m_method; //!< 0 = Jacobi, 1 = Gauss-Seidel
double m_tol; //!< convergence tolerance
int m_maxiter; //!< max number of iterations
int m_iter; //!< nr of iterations of last solve
int m_printLevel; //!< set print level
bool m_failMaxIter; //!< fail on max iterations reached
bool m_zeroInitGuess; //!< always use zero as the initial guess
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/HypreGMRESsolver.cpp | .cpp | 10,104 | 387 | /*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 "HypreGMRESsolver.h"
#ifdef HYPRE
#include <HYPRE.h>
#include <HYPRE_IJ_mv.h>
#include <HYPRE_parcsr_mv.h>
#include <HYPRE_parcsr_ls.h>
#include <_hypre_utilities.h>
#include <_hypre_IJ_mv.h>
#include <HYPRE_krylov.h>
class HypreGMRESsolver::Implementation
{
public:
CRSSparseMatrix* A; // global matrix
vector<int> ind; // indices array
// Hypre stuff
HYPRE_IJMatrix ij_A;
HYPRE_ParCSRMatrix par_A;
HYPRE_Solver solver;
HYPRE_Solver precond;
HYPRE_IJVector ij_b, ij_x;
HYPRE_ParVector par_b, par_x;
public:
// control parameters
int m_maxiter;
double m_tol;
int m_print_level;
public:
Implementation() : A(0)
{
m_print_level = 0;
m_maxiter = 1000;
m_tol = 1e-7;
}
bool isValid() const
{
return (A != 0);
}
int equations() const { return (A ? A->Rows() : 0); }
// Allocate stiffness matrix
void allocMatrix()
{
int neq = equations();
// Create an empty matrix object
int ret = 0;
ret = HYPRE_IJMatrixCreate(MPI_COMM_WORLD, 0, neq - 1, 0, neq - 1, &ij_A);
// set the matrix object type
ret = HYPRE_IJMatrixSetObjectType(ij_A, HYPRE_PARCSR);
}
// destroy stiffness matrix
void destroyMatrix()
{
HYPRE_IJMatrixDestroy(ij_A);
}
// Allocate vectors for rhs and solution
void allocVectors()
{
int neq = equations();
ind.resize(neq, 0);
for (int i = 0; i<neq; ++i) ind[i] = i;
// create the vector object for the rhs
HYPRE_IJVectorCreate(MPI_COMM_WORLD, 0, neq - 1, &ij_b);
HYPRE_IJVectorSetObjectType(ij_b, HYPRE_PARCSR);
// create the vector object for the solution
HYPRE_IJVectorCreate(MPI_COMM_WORLD, 0, neq - 1, &ij_x);
HYPRE_IJVectorSetObjectType(ij_x, HYPRE_PARCSR);
}
// destroy vectors
void destroyVectors()
{
HYPRE_IJVectorDestroy(ij_b);
HYPRE_IJVectorDestroy(ij_x);
}
// update vectors
void updateVectors(double* x, double* b)
{
// initialize vectors for changing coefficient values
HYPRE_IJVectorInitialize(ij_b);
HYPRE_IJVectorInitialize(ij_x);
// set the values
int neq = equations();
HYPRE_IJVectorSetValues(ij_b, neq, (HYPRE_Int*)&ind[0], b);
HYPRE_IJVectorSetValues(ij_x, neq, (HYPRE_Int*)&ind[0], x);
// finialize assembly
HYPRE_IJVectorAssemble(ij_b);
HYPRE_IJVectorAssemble(ij_x);
HYPRE_IJVectorGetObject(ij_b, (void**)&par_b);
HYPRE_IJVectorGetObject(ij_x, (void**)&par_x);
}
// update coefficient matrix
void updateMatrix()
{
int neq = equations();
// call initialize, after which we can set the matrix coefficients
HYPRE_Int ret = HYPRE_IJMatrixInitialize(ij_A);
// set the matrix coefficients
double* values = A->Values();
int* indices = A->Indices();
int* pointers = A->Pointers();
for (int i = 0; i<neq; ++i)
{
const int* cols = indices + pointers[i];
int ncols = pointers[i + 1] - pointers[i];
double* vals = values + pointers[i];
HYPRE_Int nrows = 1;
ret = HYPRE_IJMatrixSetValues(ij_A, nrows, (HYPRE_Int*)&ncols, (HYPRE_Int*)&i, (HYPRE_Int*)cols, vals);
}
// Finalize the matrix assembly
ret = HYPRE_IJMatrixAssemble(ij_A);
// get the matrix object for later use
ret = HYPRE_IJMatrixGetObject(ij_A, (void**)&par_A);
}
// allocate preconditioner
void allocPrecond()
{
// Now set up the AMG preconditioner and specify any parameters
HYPRE_BoomerAMGCreate(&precond);
// HYPRE_BoomerAMGSetPrintLevel(imp->precond, 1); /* print amg solution info */
// HYPRE_BoomerAMGSetCoarsenType(imp->precond, 6);
HYPRE_BoomerAMGSetCoarsenType(precond, 10); /* HMIS-coarsening */
HYPRE_BoomerAMGSetInterpType(precond, 6); /* extended+i interpolation */
HYPRE_BoomerAMGSetPMaxElmts(precond, 4);
HYPRE_BoomerAMGSetAggNumLevels(precond, 2);
// HYPRE_BoomerAMGSetOldDefault(precond);
// HYPRE_BoomerAMGSetRelaxType(precond, 6); /* Sym G.S./Jacobi hybrid */
HYPRE_BoomerAMGSetRelaxType(precond, 3); /* hybrid Gauss-Seidel or SOR, forward solve */
HYPRE_BoomerAMGSetStrongThreshold(precond, 0.5);
HYPRE_BoomerAMGSetNumSweeps(precond, 1);
// HYPRE_BoomerAMGSetTol(precond, 0.0); /* conv. tolerance zero */
// HYPRE_BoomerAMGSetMaxIter(precond, 1); /* do only one iteration! */
}
// destroy preconditioner
void destroyPrecond()
{
if (precond) HYPRE_BoomerAMGDestroy(precond);
}
// allocate solver
void allocSolver()
{
// Create the solver object
HYPRE_ParCSRFlexGMRESCreate(MPI_COMM_WORLD, &solver);
/* Set some parameters (See Reference Manual for more parameters) */
int restart = 30;
HYPRE_FlexGMRESSetKDim(solver, restart);
HYPRE_FlexGMRESSetMaxIter(solver, m_maxiter); /* max iterations */
HYPRE_FlexGMRESSetTol(solver, m_tol); /* conv. tolerance */
// HYPRE_FlexGMRESSetPrintLevel(imp->solver, 2); /* print solve info */
HYPRE_FlexGMRESSetLogging(solver, 1); /* needed to get run info later */
// Set the preconditioner
HYPRE_FlexGMRESSetPrecond(solver, (HYPRE_PtrToSolverFcn)HYPRE_BoomerAMGSolve,
(HYPRE_PtrToSolverFcn)HYPRE_BoomerAMGSetup, precond);
}
// destroy the solver
void destroySolver()
{
HYPRE_ParCSRFlexGMRESDestroy(solver);
}
// calculate the preconditioner
void doPrecond()
{
HYPRE_ParCSRFlexGMRESSetup(solver, par_A, par_b, par_x);
}
// solve the linear system
void doSolve(double* x)
{
HYPRE_ParCSRFlexGMRESSolve(solver, par_A, par_b, par_x);
/* Run info - needed logging turned on */
int num_iterations;
double final_res_norm;
HYPRE_FlexGMRESGetNumIterations(solver, (HYPRE_Int*)&num_iterations);
HYPRE_FlexGMRESGetFinalRelativeResidualNorm(solver, &final_res_norm);
if (m_print_level != 0)
{
printf("\n");
printf("Iterations = %d\n", num_iterations);
printf("Final Relative Residual Norm = %e\n", final_res_norm);
printf("\n");
}
/* get the local solution */
int neq = equations();
HYPRE_IJVectorGetValues(ij_x, neq, (HYPRE_Int*)&ind[0], &x[0]);
}
};
BEGIN_FECORE_CLASS(HypreGMRESsolver, LinearSolver)
ADD_PARAMETER(imp->m_print_level, "print_level");
ADD_PARAMETER(imp->m_maxiter , "maxiter" );
ADD_PARAMETER(imp->m_tol , "tol" );
END_FECORE_CLASS();
HypreGMRESsolver::HypreGMRESsolver(FEModel* fem) : LinearSolver(fem), imp(new HypreGMRESsolver::Implementation)
{
}
HypreGMRESsolver::~HypreGMRESsolver()
{
delete imp; imp = 0;
}
void HypreGMRESsolver::SetPrintLevel(int n)
{
imp->m_print_level = n;
}
void HypreGMRESsolver::SetMaxIterations(int n)
{
imp->m_maxiter = n;
}
void HypreGMRESsolver::SetConvergencTolerance(double tol)
{
imp->m_tol = tol;
}
SparseMatrix* HypreGMRESsolver::CreateSparseMatrix(Matrix_Type ntype)
{
if (ntype == Matrix_Type::REAL_UNSYMMETRIC)
return (imp->A = new CRSSparseMatrix(0));
else
return 0;
}
bool HypreGMRESsolver::SetSparseMatrix(SparseMatrix* A)
{
CRSSparseMatrix* K = dynamic_cast<CRSSparseMatrix*>(A);
if (K == 0) return false;
if (K->isRowBased() == false) return false;
if (K->Offset() != 0) return false;
imp->A = K;
return true;
}
//! clean up
void HypreGMRESsolver::Destroy()
{
// cleanup
imp->destroyPrecond();
imp->destroySolver();
// destroy matrix
imp->destroyMatrix();
// Destroy vectors
imp->destroyVectors();
}
bool HypreGMRESsolver::PreProcess()
{
// make sure data is valid
if (imp->isValid() == false) return false;
// create coefficient matrix
imp->allocMatrix();
// allocate rhs and solution vectors
imp->allocVectors();
return true;
}
bool HypreGMRESsolver::Factor()
{
// make sure data is valid
if (imp->isValid() == false) return false;
// copy matrix values
imp->updateMatrix();
// initialize vectors
int neq = imp->equations();
vector<double> zero(neq, 0.0);
imp->updateVectors(&zero[0], &zero[0]);
// allocate preconditioner (always call before creating solver!)
imp->allocPrecond();
// allocate solver
imp->allocSolver();
// apply preconditioner
imp->doPrecond();
return true;
}
bool HypreGMRESsolver::BackSolve(double* x, double* b)
{
// make sure data is valid
if (imp->isValid() == false) return false;
// nr of equations
int neq = imp->equations();
// update the vectors
imp->updateVectors(x, b);
// solve
imp->doSolve(x);
return true;
}
#else
BEGIN_FECORE_CLASS(HypreGMRESsolver, LinearSolver)
END_FECORE_CLASS();
HypreGMRESsolver::HypreGMRESsolver(FEModel* fem) : LinearSolver(fem) {}
HypreGMRESsolver::~HypreGMRESsolver() {}
void HypreGMRESsolver::Destroy() {}
void HypreGMRESsolver::SetPrintLevel(int n) {}
void HypreGMRESsolver::SetMaxIterations(int n) {}
void HypreGMRESsolver::SetConvergencTolerance(double tol) {}
bool HypreGMRESsolver::PreProcess() { return false; }
bool HypreGMRESsolver::Factor() { return false; }
bool HypreGMRESsolver::BackSolve(double* x, double* b) { return false; }
SparseMatrix* HypreGMRESsolver::CreateSparseMatrix(Matrix_Type ntype) { return 0; }
bool HypreGMRESsolver::SetSparseMatrix(SparseMatrix* A) { return false; }
#endif // HYPRE
| C++ |
3D | febiosoftware/FEBio | NumCore/AccelerateSparseSolver.h | .h | 3,134 | 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) 2022 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/LinearSolver.h>
#include <FECore/CompactUnSymmMatrix.h>
#include <FECore/CompactSymmMatrix.h>
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#endif
// This sparse linear solver uses the Accelerate framework on MAC.
class AccelerateSparseSolver : public LinearSolver
{
class Implementation;
public:
enum FactorizationType {
FTSparseFactorizationCholesky = 0,
FTSparseFactorizationLDLT = 1,
FTSparseFactorizationLDLTUnpivoted = 2,
FTSparseFactorizationLDLTSBK = 3,
FTSparseFactorizationLDLTTPP = 4,
FTSparseFactorizationQR = 5,
FTSparseFactorizationCholeskyAtA = 6,
};
enum OrderMethod {
OMSparseOrderAMD = 0,
OMSparseOrderMetis = 1,
OMSparseOrderCOLAMD = 2,
};
enum IterativeMethod {
ITSparseConjugateGradient = 0,
ITSparseGMRES = 1,
ITSparseDQGMRES = 2,
ITSparseFGMRES = 3,
ITSparseLSMR = 4,
};
public:
AccelerateSparseSolver(FEModel* fem);
~AccelerateSparseSolver();
public:
void PrintConditionNumber(bool b);
void UseIterativeFactorization(bool b);
void SetFactorizationType(int ftype);
void SetOrderMethod(int order);
void SetPrintLevel(int printlevel) override;
double condition_number();
static void MyReportError(const char* message);
static void MyReportStatus(const char* message);
public:
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
bool SetSparseMatrix(SparseMatrix* pA) override;
bool PreProcess() override;
bool Factor() override;
bool BackSolve(double* x, double* y) override;
void Destroy() override;
bool IsIterative() const override;
private:
Implementation* imp;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/PardisoSolver.h | .h | 2,460 | 81 | /*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/LinearSolver.h>
#include <FECore/CompactUnSymmMatrix.h>
#include <FECore/CompactSymmMatrix.h>
//! The Pardiso solver is included in the Intel Math Kernel Library (MKL).
//! It can also be installed as a shared object library from
//! http://www.pardiso-project.org
class PardisoSolver : public LinearSolver
{
public:
PardisoSolver(FEModel* fem);
~PardisoSolver();
bool PreProcess() override;
bool Factor() override;
bool BackSolve(double* x, double* y) override;
void Destroy() override;
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
bool SetSparseMatrix(SparseMatrix* pA) override;
void PrintConditionNumber(bool b);
double ConditionNumber() override;
void UseIterativeFactorization(bool b);
protected:
CompactMatrix* m_pA;
int m_mtype; // matrix type
// Pardiso control parameters
int m_iparm[64];
int m_maxfct, m_mnum, m_msglvl;
double m_dparm[64];
bool m_iparm3; // use direct-iterative method
// Matrix data
int m_n, m_nnz, m_nrhs;
bool m_print_cn; // estimate and print the condition number
bool m_isFactored;
void* m_pt[64]; // Internal solver memory pointer
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/BiCGStabSolver.cpp | .cpp | 5,983 | 231 | /*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 "BiCGStabSolver.h"
#include <FECore/CompactUnSymmMatrix.h>
#include <FECore/log.h>
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(BiCGStabSolver, IterativeLinearSolver)
ADD_PARAMETER(m_print_level, "print_level");
ADD_PARAMETER(m_tol, "tol");
ADD_PARAMETER(m_maxiter, "max_iter");
ADD_PARAMETER(m_fail_max_iter, "fail_max_iters");
ADD_PROPERTY(m_P, "pc_left")->SetFlags(FEProperty::Optional);
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
BiCGStabSolver::BiCGStabSolver(FEModel* fem) : IterativeLinearSolver(fem), m_pA(0), m_P(0)
{
m_maxiter = 0;
m_tol = 1e-5;
m_abstol = 0.0;
m_print_level = 0;
m_fail_max_iter = true;
}
//-----------------------------------------------------------------------------
SparseMatrix* BiCGStabSolver::CreateSparseMatrix(Matrix_Type ntype)
{
// let the preconditioner decide
m_pA = nullptr;
if (m_P)
{
m_P->SetPartitions(m_part);
m_pA = m_P->CreateSparseMatrix(ntype);
}
else
{
if (ntype == REAL_SYMMETRIC) m_pA = new CompactSymmMatrix;
else m_pA = new CRSSparseMatrix(1);
}
return m_pA;
}
//-----------------------------------------------------------------------------
bool BiCGStabSolver::SetSparseMatrix(SparseMatrix* A)
{
m_pA = A;
return (m_pA != 0);
}
//-----------------------------------------------------------------------------
void BiCGStabSolver::SetLeftPreconditioner(LinearSolver* P)
{
m_P = dynamic_cast<Preconditioner*>(P);
}
//-----------------------------------------------------------------------------
LinearSolver* BiCGStabSolver::GetLeftPreconditioner()
{
return m_P;
}
//-----------------------------------------------------------------------------
bool BiCGStabSolver::HasPreconditioner() const
{
return (m_P != nullptr);
}
//-----------------------------------------------------------------------------
bool BiCGStabSolver::PreProcess()
{
return true;
}
//-----------------------------------------------------------------------------
bool BiCGStabSolver::Factor()
{
if (m_pA == 0) return false;
if (m_P)
{
if (m_P->PreProcess() == false) return false;
if (m_P->Factor() == false) return false;
}
return true;
}
//-----------------------------------------------------------------------------
bool BiCGStabSolver::BackSolve(double* x, double* b)
{
if (m_pA == nullptr) return false;
SparseMatrix& A = *m_pA;
int neq = A.Rows();
// assume initial guess is zero
for (int i = 0; i < neq; ++i) x[i] = 0.0;
// calculate initial norm
// r0 = b - A*x0
vector<double> r_i(neq); double norm0 = 0.0, normi = 0.0;
for (int j = 0; j < neq; ++j)
{
r_i[j] = b[j];
norm0 += r_i[j] * r_i[j];
}
norm0 = sqrt(norm0);
// if the norm is zero, there is nothing to do
if (norm0 == 0.0) return true;
// Choose an arbitrary vector rt such that(rt, r0) != 0, e.g., rt = r0
vector<double> rt(r_i);
// initialize some stuff
double rho_p = 1, alpha = 1, w_p = 1;
vector<double> v_p(neq, 0.0), p_p(neq, 0.0), p_i(neq), y(neq, 0.0), h(neq), s(neq), z(neq), t(neq), q(neq);
int max_iter = m_maxiter;
if (max_iter == 0) max_iter = (neq < 150 ? neq : 150);
int iter = 0;
bool converged = false;
do
{
double rho_i = rt*r_i;
double beta = (rho_i / rho_p)*(alpha / w_p);
for (int j = 0; j < neq; ++j) p_i[j] = r_i[j] + beta*(p_p[j] - w_p*v_p[j]);
// apply preconditioner
if (m_P)
{
m_P->BackSolve(y, p_i);
}
else y = p_i;
A.mult_vector(&y[0], &v_p[0]);
alpha = rho_i / (rt*v_p);
for (int j = 0; j < neq; ++j) h[j] = x[j] + alpha*y[j];
for (int j = 0; j < neq; ++j) s[j] = r_i[j] - alpha*v_p[j];
// If h is accurate enough then xi = h and quit
if (m_P)
{
m_P->BackSolve(z, s);
}
else z = s;
A.mult_vector(&z[0], &t[0]);
if (m_P)
{
m_P->BackSolve(q, t);
}
else q = t;
w_p = (q*z) / (q*q);
for (int j = 0; j < neq; ++j) x[j] = h[j] + w_p*z[j];
normi = 0.0;
for (int j = 0; j < neq; ++j)
{
r_i[j] = s[j] - w_p*t[j];
normi += r_i[j] * r_i[j];
}
normi = sqrt(normi);
// see if we have converged
double tol = norm0*m_tol + m_abstol;
if (normi <= tol) converged = true;
else
{
// prepare for next iteration
rho_p = rho_i;
p_p = p_i;
}
// check max iterations
iter++;
if (iter > max_iter) break;
if (m_print_level > 1)
{
feLog("%d:%lg, %lg\n", iter, normi, tol);
}
}
while (!converged);
if (m_print_level == 1)
{
feLog("%d:%lg, %lg\n", iter, normi, norm0);
}
UpdateStats(iter);
return (m_fail_max_iter ? converged : true);
}
//-----------------------------------------------------------------------------
void BiCGStabSolver::Destroy()
{
}
| C++ |
3D | febiosoftware/FEBio | NumCore/SuperLU_MT.h | .h | 1,840 | 52 | /*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/LinearSolver.h>
#include <FECore/CompactUnSymmMatrix.h>
#include <FECore/CompactSymmMatrix.h>
class SuperLU_MT_Solver: public LinearSolver
{
class Impl;
public:
SuperLU_MT_Solver(FEModel* fem);
~SuperLU_MT_Solver();
bool PreProcess() override;
bool Factor() override;
bool BackSolve(double* x, double* y) override;
void Destroy() override;
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
bool SetSparseMatrix(SparseMatrix* pA) override;
protected:
CompactMatrix* m_pA;
Impl* m;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/BIPNSolver.h | .h | 4,607 | 142 | /*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/LinearSolver.h>
#include "BlockMatrix.h"
class FGMRESSolver;
//-----------------------------------------------------------------------------
// This class implements the bi-partitioned iterative solver, by:
// Esmaily-Moghadam, Bazilevs, Marsden, Comput. Methods Appl. Mech. Engrg. 286(2015) 40-62
//
class BIPNSolver : public LinearSolver
{
public:
// constructor
BIPNSolver(FEModel* fem);
// set the output level
void SetPrintLevel(int n) override;
// set the max nr of BIPN iterations
void SetMaxIterations(int n);
// Set the BIPN convergence tolerance
void SetTolerance(double eps);
// Use CG for step 2 or not
void UseConjugateGradient(bool b);
// set the CG convergence parameters
void SetCGParameters(int maxiter, double tolerance, bool doResidualStoppingTest);
// set the GMRES convergence parameters
void SetGMRESParameters(int maxiter, double tolerance, bool doResidualStoppingTest, int precondition);
// Do Jacobi preconditioner
void DoJacobiPreconditioner(bool b);
// set the schur preconditioner option
void SetSchurPreconditioner(int n);
public:
// allocate storage
bool PreProcess() override;
//! Factor the matrix (for iterative solvers, this can be used for creating pre-conditioner)
bool Factor() override;
//! Calculate the solution of RHS b and store solution in x
bool BackSolve(double* x, double* y) override;
//! Return a sparse matrix compatible with this solver
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
// set the sparse matrix
bool SetSparseMatrix(SparseMatrix* A) override;
private:
int cgsolve(SparseMatrix* K, LinearSolver* PC, vector<double>& x, vector<double>& b);
int gmressolve(SparseMatrix* K, LinearSolver* PC, vector<double>& x, vector<double>& b);
private:
BlockMatrix* m_A; //!< the block matrix
FGMRESSolver* m_Asolver; //!< the solver for the A - block
LinearSolver* m_PS; //!< Schur complement preconditioner
std::vector<double> Kd;
std::vector<double> Wm, Wc;
std::vector<double> Rm0, Rc0;
std::vector<double> Rm_n, Rc_n;
std::vector<double> yu, yp;
std::vector<double> yu_n, yp_n;
std::vector< std::vector<double> > Yu, Yp;
std::vector<double> au, ap;
std::vector<double> du, dp;
vector<double> RM;
vector<double> RC;
vector< vector<double> > Rmu;
vector< vector<double> > Rmp;
vector< vector<double> > Rcu;
vector< vector<double> > Rcp;
int m_print_level; //!< level of output (0 is no output)
int m_maxiter; //!< max nr of BIPN iterations
double m_tol; //!< BPIN convergence tolerance
bool m_use_cg; //!< use CG for step 2, otherwise GMRES is used
bool m_do_jacobi; //!< do Jacobi precondition
int m_precondition_schur; //!< preconditioner the Schur solver (0 = none, 1 = diag(M), 2 = ICHOL(M))
// CG data
int m_cg_maxiter; //!< max CG iterations
double m_cg_tol; //!< CG tolerance
bool m_cg_doResidualTest; //!< do the residual stopping test
int m_cg_iters; //!< iterations of CG solve
vector<double> cg_tmp;
// GMRES data
int m_gmres_maxiter; //!< max GMRES iterations
double m_gmres_tol; //!< GMRES tolerance
bool m_gmres_doResidualTest; //!< do the residual stopping test
int m_gmres_pc; //!< preconditioner?
int m_gmres1_iters, m_gmres2_iters;
vector<double> gmres_tmp;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/IncompleteCholesky.h | .h | 1,697 | 52 | /*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/Preconditioner.h>
class CompactSymmMatrix;
class IncompleteCholesky : public Preconditioner
{
public:
IncompleteCholesky(FEModel* fem);
// create a preconditioner for a sparse matrix
bool Factor() override;
// apply to vector P x = y
bool BackSolve(double* x, double* y) override;
public:
CompactSymmMatrix* getMatrix();
private:
CompactSymmMatrix* m_L;
vector<double> z;
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/BoomerAMGSolver.cpp | .cpp | 14,342 | 536 | /*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 "BoomerAMGSolver.h"
#include <FECore/CompactUnSymmMatrix.h>
#include <FECore/log.h>
#include <FECore/FEModel.h>
#include <FECore/FESolver.h>
#include <FECore/FEAnalysis.h>
#ifdef HYPRE
#include <HYPRE.h>
#include <HYPRE_IJ_mv.h>
#include <HYPRE_parcsr_mv.h>
#include <HYPRE_parcsr_ls.h>
#include <_hypre_utilities.h>
#include <_hypre_IJ_mv.h>
class BoomerAMGSolver::Implementation
{
public:
FEModel* m_fem;
CRSSparseMatrix* m_A;
HYPRE_IJMatrix ij_A;
HYPRE_ParCSRMatrix par_A;
vector<int> m_ind;
HYPRE_IJVector ij_b, ij_x;
HYPRE_ParVector par_b, par_x;
vector<double> W; // Jacobi preconditioner
vector<double> rhs; // right-hand side
HYPRE_Solver m_solver;
HYPRE_Int m_num_iterations;
double m_final_res_norm;
int m_print_level;
int m_maxIter;
int m_maxLevels;
double m_tol;
int m_coarsenType;
bool m_set_num_funcs;
int m_relaxType;
int m_interpType;
int m_PMaxElmts;
int m_NumSweeps;
int m_AggInterpType;
int m_AggNumLevels;
double m_strong_threshold;
int m_nodal;
bool m_jacobi_pc;
bool m_failMaxIters;
HYPRE_Int* m_dofMap;
public:
Implementation()
{
m_print_level = 0;
m_maxLevels = 25;
m_maxIter = 20;
m_tol = 1.e-7;
m_coarsenType = -1; // don't set
m_set_num_funcs = false;
m_relaxType = 3;
m_interpType = 6;
m_strong_threshold = 0.5;
m_PMaxElmts = 4;
m_NumSweeps = 1;
m_AggInterpType = 0;
m_AggNumLevels = 0;
m_nodal = 0;
m_jacobi_pc = false;
m_failMaxIters = true;
m_A = nullptr;
m_solver = nullptr;
ij_A = nullptr;
ij_b = nullptr;
ij_x = nullptr;
}
int equations() const { return (m_A ? m_A->Rows() : 0); }
// Allocate stiffness matrix
void allocMatrix()
{
int neq = equations();
rhs.assign(neq, 0.0);
// Create an empty matrix object
int ret = 0;
ret = HYPRE_IJMatrixCreate(MPI_COMM_WORLD, 0, neq - 1, 0, neq - 1, &ij_A);
// set the matrix object type
ret = HYPRE_IJMatrixSetObjectType(ij_A, HYPRE_PARCSR);
}
// destroy stiffness matrix
void destroyMatrix()
{
if (ij_A) HYPRE_IJMatrixDestroy(ij_A);
ij_A = nullptr;
}
// update coefficient matrix
bool updateMatrix()
{
int neq = equations();
SparseMatrix* A = m_A;
W.resize(neq, 1.0);
if (m_jacobi_pc)
{
for (int i = 0; i < neq; ++i)
{
double dii = fabs(A->diag(i));
if (dii == 0.0) return false;
W[i] = 1.0 / sqrt(dii);
}
}
if (m_jacobi_pc)
A->scale(W, W);
// call initialize, after which we can set the matrix coefficients
HYPRE_Int ret = HYPRE_IJMatrixInitialize(ij_A);
// set the matrix coefficients
double* values = m_A->Values();
int* indices = m_A->Indices();
int* pointers = m_A->Pointers();
for (int i = 0; i<neq; ++i)
{
const int* cols = indices + pointers[i];
int ncols = pointers[i + 1] - pointers[i];
double* vals = values + pointers[i];
HYPRE_Int nrows = 1;
ret = HYPRE_IJMatrixSetValues(ij_A, nrows, (HYPRE_Int*)&ncols, (HYPRE_Int*)&i, (HYPRE_Int*)cols, vals);
}
// Finalize the matrix assembly
ret = HYPRE_IJMatrixAssemble(ij_A);
// get the matrix object for later use
ret = HYPRE_IJMatrixGetObject(ij_A, (void**)&par_A);
return true;
}
// Allocate vectors for rhs and solution
void allocVectors()
{
int neq = equations();
m_ind.resize(neq, 0);
for (int i = 0; i<neq; ++i) m_ind[i] = i;
// create the vector object for the rhs
HYPRE_IJVectorCreate(MPI_COMM_WORLD, 0, neq - 1, &ij_b);
HYPRE_IJVectorSetObjectType(ij_b, HYPRE_PARCSR);
// create the vector object for the solution
HYPRE_IJVectorCreate(MPI_COMM_WORLD, 0, neq - 1, &ij_x);
HYPRE_IJVectorSetObjectType(ij_x, HYPRE_PARCSR);
}
// destroy vectors
void destroyVectors()
{
if (ij_b) HYPRE_IJVectorDestroy(ij_b); ij_b = nullptr;
if (ij_x) HYPRE_IJVectorDestroy(ij_x); ij_x = nullptr;
}
// update vectors
void updateVectors(double* x, double* b)
{
// initialize vectors for changing coefficient values
HYPRE_IJVectorInitialize(ij_b);
HYPRE_IJVectorInitialize(ij_x);
// scale by Jacobi PC
int neq = equations();
for (int i = 0; i < neq; ++i) rhs[i] = W[i] * b[i];
// set the values
HYPRE_IJVectorSetValues(ij_b, neq, (HYPRE_Int*)&m_ind[0], &rhs[0]);
HYPRE_IJVectorSetValues(ij_x, neq, (HYPRE_Int*)&m_ind[0], x);
// finialize assembly
HYPRE_IJVectorAssemble(ij_b);
HYPRE_IJVectorAssemble(ij_x);
HYPRE_IJVectorGetObject(ij_b, (void**)&par_b);
HYPRE_IJVectorGetObject(ij_x, (void**)&par_x);
}
bool allocSolver()
{
// create solver
HYPRE_BoomerAMGCreate(&m_solver);
int printLevel = m_print_level;
if (printLevel > 3) printLevel = 0;
/* Set some parameters (See Reference Manual for more parameters) */
HYPRE_BoomerAMGSetPrintLevel(m_solver, printLevel); // print solve info
// HYPRE_BoomerAMGSetOldDefault(m_solver); /* Falgout coarsening with modified classical interpolation */
if (m_coarsenType >= 0) HYPRE_BoomerAMGSetCoarsenType(m_solver, m_coarsenType);
if (m_relaxType >= 0) HYPRE_BoomerAMGSetRelaxType(m_solver, m_relaxType);
HYPRE_BoomerAMGSetRelaxOrder(m_solver, 1); // uses C/F relaxation
HYPRE_BoomerAMGSetInterpType(m_solver, m_interpType);
HYPRE_BoomerAMGSetPMaxElmts(m_solver, m_PMaxElmts);
HYPRE_BoomerAMGSetNumSweeps(m_solver, m_NumSweeps); /* Sweeps on each level */
HYPRE_BoomerAMGSetMaxLevels(m_solver, m_maxLevels); /* maximum number of levels */
HYPRE_BoomerAMGSetStrongThreshold(m_solver, m_strong_threshold);
HYPRE_BoomerAMGSetAggInterpType(m_solver, m_AggInterpType);
HYPRE_BoomerAMGSetAggNumLevels(m_solver, m_AggNumLevels);
HYPRE_BoomerAMGSetMaxIter(m_solver, m_maxIter);
HYPRE_BoomerAMGSetTol(m_solver, m_tol); /* conv. tolerance */
// sets the number of funtions, which I think means the dofs per variable
// For 3D mechanics this would be 3.
// I think this also requires the staggered equation numbering.
// NOTE: when set to 3, this definitely seems to help with (some) mechanics problems!
if (m_set_num_funcs)
{
// we need the FESolver so we can get the dof mapping
FESolver* fesolve = m_fem->GetCurrentStep()->GetFESolver();
// get the dof map
vector<int> dofMap;
int nfunc = fesolve->GetActiveDofMap(dofMap);
if (nfunc == -1) return false;
// allocate dof map
// (We need to copy it here since Hypre will deallocate it)
int neq = (int)dofMap.size();
m_dofMap = (HYPRE_Int*)malloc(neq * sizeof(HYPRE_Int));
for (size_t i = 0; i < neq; ++i) m_dofMap[i] = dofMap[i];
printf("\tNumber of functions : %d\n", nfunc);
// assign to BoomerAMG
HYPRE_BoomerAMGSetNumFunctions(m_solver, nfunc);
// set the dof map
HYPRE_BoomerAMGSetDofFunc(m_solver, m_dofMap);
}
// NOTE: Turning this option on seems to worsen convergence!
if (m_nodal > 0) HYPRE_BoomerAMGSetNodal(m_solver, m_nodal);
return true;
}
void destroySolver()
{
if (m_solver) HYPRE_BoomerAMGDestroy(m_solver);
m_solver = nullptr;
}
void doSetup()
{
HYPRE_BoomerAMGSetup(m_solver, par_A, par_b, par_x);
}
bool doSolve(double* x)
{
HYPRE_BoomerAMGSolve(m_solver, par_A, par_b, par_x);
/* Run info - needed logging turned on */
HYPRE_BoomerAMGGetNumIterations(m_solver, &m_num_iterations);
HYPRE_BoomerAMGGetFinalRelativeResidualNorm(m_solver, &m_final_res_norm);
// see if we converged
bool bok = false;
if ((m_num_iterations <= m_maxIter) && (m_final_res_norm < m_tol)) bok = true;
/* get the local solution */
int neq = equations();
HYPRE_IJVectorGetValues(ij_x, neq, (HYPRE_Int*)&m_ind[0], &x[0]);
// scale by Jacobi PC
for (int i = 0; i < neq; ++i) x[i] *= W[i];
return bok;
}
};
BEGIN_FECORE_CLASS(BoomerAMGSolver, LinearSolver)
ADD_PARAMETER(imp->m_maxIter , "max_iter");
ADD_PARAMETER(imp->m_print_level , "print_level");
ADD_PARAMETER(imp->m_tol , "tol");
ADD_PARAMETER(imp->m_maxLevels , "max_levels");
ADD_PARAMETER(imp->m_coarsenType , "coarsen_type");
ADD_PARAMETER(imp->m_set_num_funcs , "use_num_funcs");
ADD_PARAMETER(imp->m_relaxType , "relax_type");
ADD_PARAMETER(imp->m_interpType , "interp_type");
ADD_PARAMETER(imp->m_strong_threshold, "strong_threshold");
ADD_PARAMETER(imp->m_PMaxElmts , "p_max_elmts");
ADD_PARAMETER(imp->m_NumSweeps , "num_sweeps");
ADD_PARAMETER(imp->m_AggInterpType , "agg_interp_type");
ADD_PARAMETER(imp->m_AggNumLevels , "agg_num_levels");
ADD_PARAMETER(imp->m_nodal , "nodal");
ADD_PARAMETER(imp->m_jacobi_pc , "do_jacobi");
ADD_PARAMETER(imp->m_failMaxIters , "fail_max_iters");
END_FECORE_CLASS();
BoomerAMGSolver::BoomerAMGSolver(FEModel* fem) : LinearSolver(fem), imp(new BoomerAMGSolver::Implementation)
{
imp->m_fem = fem;
}
BoomerAMGSolver::~BoomerAMGSolver()
{
Destroy();
delete imp;
}
void BoomerAMGSolver::SetPrintLevel(int printLevel)
{
imp->m_print_level = printLevel;
}
void BoomerAMGSolver::SetMaxIterations(int maxIter)
{
imp->m_maxIter = maxIter;
}
void BoomerAMGSolver::SetMaxLevels(int levels)
{
imp->m_maxLevels = levels;
}
void BoomerAMGSolver::SetConvergenceTolerance(double tol)
{
imp->m_tol = tol;
}
void BoomerAMGSolver::SetCoarsenType(int coarsenType)
{
imp->m_coarsenType = coarsenType;
}
void BoomerAMGSolver::SetUseNumFunctions(bool b)
{
imp->m_set_num_funcs = b;
}
void BoomerAMGSolver::SetRelaxType(int rlxtyp)
{
imp->m_relaxType = rlxtyp;
}
void BoomerAMGSolver::SetInterpType(int inptyp)
{
imp->m_interpType = inptyp;
}
void BoomerAMGSolver::SetStrongThreshold(double thresh)
{
imp->m_strong_threshold = thresh;
}
void BoomerAMGSolver::SetPMaxElmts(int pmax)
{
imp->m_PMaxElmts = pmax;
}
void BoomerAMGSolver::SetNumSweeps(int nswp)
{
imp->m_NumSweeps = nswp;
}
void BoomerAMGSolver::SetAggInterpType(int aggit)
{
imp->m_AggInterpType = aggit;
}
void BoomerAMGSolver::SetAggNumLevels(int anlv)
{
imp->m_AggNumLevels = anlv;
}
void BoomerAMGSolver::SetNodal(int nodal)
{
imp->m_nodal = nodal;
}
void BoomerAMGSolver::SetJacobiPC(bool b)
{
imp->m_jacobi_pc = b;
}
bool BoomerAMGSolver::GetJacobiPC()
{
return imp->m_jacobi_pc;
}
void BoomerAMGSolver::SetFailOnMaxIterations(bool b)
{
imp->m_failMaxIters = b;
}
SparseMatrix* BoomerAMGSolver::CreateSparseMatrix(Matrix_Type ntype)
{
// allocate the correct matrix format depending on matrix symmetry type
switch (ntype)
{
case REAL_SYMMETRIC: imp->m_A = nullptr; break;
case REAL_UNSYMMETRIC:
case REAL_SYMM_STRUCTURE:
imp->m_A = new CRSSparseMatrix(0); break;
default:
assert(false);
imp->m_A = nullptr;
}
return imp->m_A;
}
bool BoomerAMGSolver::SetSparseMatrix(SparseMatrix* pA)
{
if (pA == imp->m_A) return true;
if (imp->m_A) delete imp->m_A;
imp->m_A = dynamic_cast<CRSSparseMatrix*>(pA);
if (imp->m_A == nullptr) return false;
if (imp->m_A->Offset() != 0)
{
imp->m_A = nullptr;
return false;
}
return true;
}
bool BoomerAMGSolver::PreProcess()
{
imp->m_fem = GetFEModel();
imp->allocMatrix();
imp->allocVectors();
// create solver
return imp->allocSolver();
}
bool BoomerAMGSolver::Factor()
{
if (imp->updateMatrix() == false) return false;
vector<double> zero(imp->equations(), 0.0);
imp->updateVectors(&zero[0], &zero[0]);
imp->doSetup();
return true;
}
bool BoomerAMGSolver::BackSolve(double* x, double* b)
{
imp->updateVectors(x, b);
bool bok = imp->doSolve(x);
if (imp->m_print_level > 3)
{
feLog("AMG: %d iterations, %lg residual norm\n", imp->m_num_iterations, imp->m_final_res_norm);
}
UpdateStats(imp->m_num_iterations);
return (bok || (imp->m_failMaxIters == false));
}
void BoomerAMGSolver::Destroy()
{
// Destroy solver
imp->destroySolver();
imp->destroyMatrix();
imp->destroyVectors();
}
#else
BEGIN_FECORE_CLASS(BoomerAMGSolver, LinearSolver)
END_FECORE_CLASS();
BoomerAMGSolver::BoomerAMGSolver(FEModel* fem) : LinearSolver(fem) {}
BoomerAMGSolver::~BoomerAMGSolver() {}
void BoomerAMGSolver::SetPrintLevel(int printLevel) {}
void BoomerAMGSolver::SetMaxIterations(int maxIter) {}
void BoomerAMGSolver::SetConvergenceTolerance(double tol) {}
void BoomerAMGSolver::SetMaxLevels(int levels) {}
void BoomerAMGSolver::SetCoarsenType(int coarsenType) {}
void BoomerAMGSolver::SetRelaxType(int rlxtyp) {}
void BoomerAMGSolver::SetInterpType(int inptyp) {}
void BoomerAMGSolver::SetStrongThreshold(double thresh) {}
void BoomerAMGSolver::SetPMaxElmts(int pmax) {}
void BoomerAMGSolver::SetNumSweeps(int nswp) {}
void BoomerAMGSolver::SetAggInterpType(int aggit) {}
void BoomerAMGSolver::SetAggNumLevels(int anlv) {}
SparseMatrix* BoomerAMGSolver::CreateSparseMatrix(Matrix_Type ntype) { return nullptr; }
bool BoomerAMGSolver::SetSparseMatrix(SparseMatrix* pA) { return false; }
bool BoomerAMGSolver::PreProcess() { return false; }
bool BoomerAMGSolver::Factor() { return false; }
bool BoomerAMGSolver::BackSolve(double* x, double* y) { return false; }
void BoomerAMGSolver::Destroy() {}
#endif
| C++ |
3D | febiosoftware/FEBio | NumCore/MatrixTools.h | .h | 2,723 | 73 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <ostream>
#include <FECore/CompactUnSymmMatrix.h>
#include "numcore_api.h"
namespace NumCore
{
// write a matrix to file
// mode:
// - 0 = binary mode
// - 1 = text mode
NUMCORE_API bool write_hb(CompactMatrix& K, const char* szfile, int mode = 0);
// write a vector to file
NUMCORE_API bool write_vector(const std::vector<double>& a, const char* szfile, int mode = 0);
// read compact matrix (binary mode only)
NUMCORE_API CompactMatrix* read_hb(const char* szfile);
// read vector<double> from file
NUMCORE_API bool read_vector(std::vector<double>& a, const char* szfile);
// calculate inf-norm of inverse matrix (only works with CRSSparsMatrix(1))
NUMCORE_API double inverse_infnorm(CompactMatrix* A);
// calculate condition number of a CRSSparseMatrix(1) (Very expensive!)
NUMCORE_API double conditionNumber(CRSSparseMatrix* A);
// estimate condition number
NUMCORE_API double estimateConditionNumber(SparseMatrix* A);
// create a random vector
NUMCORE_API void randomVector(std::vector<double>& R, double vmin = 0.0, double vmax = 1.0);
// inf-norm of a vector
NUMCORE_API double infNorm(const std::vector<double>& x);
// 1-norm of a vector
NUMCORE_API double oneNorm(const std::vector<double>& x);
// print matrix sparsity pattern to svn file
NUMCORE_API void print_svg(CompactMatrix* m, std::ostream &out, int i0 = 0, int j0 = 0, int i1 = -1, int j1 = -1);
} // namespace NumCore
| Unknown |
3D | febiosoftware/FEBio | NumCore/NumCore.cpp | .cpp | 3,826 | 98 | /*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 "NumCore.h"
#include "PardisoSolver.h"
#include "PardisoSolver64.h"
#include "PardisoProjectSolver.h"
#include "RCICGSolver.h"
#include "FGMRESSolver.h"
#include "ILU0_Preconditioner.h"
#include "ILUT_Preconditioner.h"
#include "BIPNSolver.h"
#include "HypreGMRESsolver.h"
#include "Hypre_PCG_AMG.h"
#include "SchurSolver.h"
#include "IncompleteCholesky.h"
#include "BoomerAMGSolver.h"
#include "BlockSolver.h"
#include "BiCGStabSolver.h"
#include "StrategySolver.h"
#include <FECore/fecore_enum.h>
#include <FECore/FECoreFactory.h>
#include <FECore/FECoreKernel.h>
#include "FEASTEigenSolver.h"
#include "TestSolver.h"
#include "AccelerateSparseSolver.h"
#include "SuperLU_MT.h"
#include "MKLDSSolver.h"
#include "numcore_api.h"
//=============================================================================
// Call this to initialize the NumCore module
NUMCORE_API void NumCore::InitModule()
{
// register linear solvers
#ifdef PARDISO
REGISTER_FECORE_CLASS(PardisoSolver , "pardiso");
REGISTER_FECORE_CLASS(PardisoSolver64, "pardiso_64");
REGISTER_FECORE_CLASS(MKLDSSolver, "mkl_dss");
#endif
REGISTER_FECORE_CLASS(PardisoProjectSolver, "pardiso-project");
REGISTER_FECORE_CLASS(FGMRESSolver , "fgmres" );
REGISTER_FECORE_CLASS(BoomerAMGSolver , "boomeramg");
REGISTER_FECORE_CLASS(RCICGSolver , "cg" );
REGISTER_FECORE_CLASS(SchurSolver , "schur" );
REGISTER_FECORE_CLASS(HypreGMRESsolver , "hypre_gmres");
REGISTER_FECORE_CLASS(Hypre_PCG_AMG , "hypre_pcg_amg");
REGISTER_FECORE_CLASS(BlockIterativeSolver, "block");
REGISTER_FECORE_CLASS(BIPNSolver , "bipn");
REGISTER_FECORE_CLASS(BiCGStabSolver , "bicgstab");
REGISTER_FECORE_CLASS(StrategySolver , "strategy");
REGISTER_FECORE_CLASS(TestSolver , "test");
REGISTER_FECORE_CLASS(AccelerateSparseSolver, "accelerate");
REGISTER_FECORE_CLASS(SuperLU_MT_Solver , "superlu_mt");
// register preconditioners
REGISTER_FECORE_CLASS(ILU0_Preconditioner, "ilu0");
REGISTER_FECORE_CLASS(ILUT_Preconditioner, "ilut");
REGISTER_FECORE_CLASS(IncompleteCholesky , "ichol");
// register eigen solvers
REGISTER_FECORE_CLASS(FEASTEigenSolver, "feast");
// set default linear solver
// (Set this before the configuration is read in because
// the configuration can change the default linear solver.)
FECoreKernel& fecore = FECoreKernel::GetInstance();
#ifdef PARDISO
fecore.SetDefaultSolverType("pardiso");
#else
fecore.SetDefaultSolverType("skyline");
#endif
}
| C++ |
3D | febiosoftware/FEBio | NumCore/TestSolver.cpp | .cpp | 3,317 | 109 | /*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 <stdio.h>
#include <stdlib.h>
#include "TestSolver.h"
#include <FECore/log.h>
BEGIN_FECORE_CLASS(TestSolver, LinearSolver)
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
TestSolver::TestSolver(FEModel* fem) : LinearSolver(fem), m_pA(0)
{
m_mtype = -2;
}
//-----------------------------------------------------------------------------
TestSolver::~TestSolver()
{
Destroy();
}
//-----------------------------------------------------------------------------
SparseMatrix* TestSolver::CreateSparseMatrix(Matrix_Type ntype)
{
// allocate the correct matrix format depending on matrix symmetry type
switch (ntype)
{
case REAL_SYMMETRIC: m_mtype = -2; m_pA = new CompactSymmMatrix(1); break;
case REAL_UNSYMMETRIC: m_mtype = 11; m_pA = new CRSSparseMatrix(1); break;
case REAL_SYMM_STRUCTURE: m_mtype = 1; m_pA = new CRSSparseMatrix(1); break;
default:
assert(false);
m_pA = nullptr;
}
return m_pA;
}
//-----------------------------------------------------------------------------
bool TestSolver::SetSparseMatrix(SparseMatrix* pA)
{
if (m_pA) Destroy();
m_pA = dynamic_cast<CompactMatrix*>(pA);
m_mtype = -2;
if (dynamic_cast<CRSSparseMatrix*>(pA)) m_mtype = 11;
return (m_pA != nullptr);
}
//-----------------------------------------------------------------------------
bool TestSolver::PreProcess()
{
m_n = m_pA->Rows();
m_nnz = m_pA->NonZeroes();
m_nrhs = 1;
return LinearSolver::PreProcess();
}
//-----------------------------------------------------------------------------
bool TestSolver::Factor()
{
return true;
}
//-----------------------------------------------------------------------------
bool TestSolver::BackSolve(double* x, double* b)
{
// make sure we have work to do
if (m_pA->Rows() == 0) return true;
for (int i = 0; i < m_n; ++i) x[i] = 0.0;
// update stats
UpdateStats(1);
return true;
}
//-----------------------------------------------------------------------------
void TestSolver::Destroy()
{
}
| C++ |
3D | febiosoftware/FEBio | NumCore/Hypre_PCG_AMG.h | .h | 2,316 | 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 <FECore/LinearSolver.h>
#include <FECore/CompactUnSymmMatrix.h>
//-----------------------------------------------------------------------------
// This class implements the HYPRE GMRES solver
class Hypre_PCG_AMG : public LinearSolver
{
class Implementation;
public:
Hypre_PCG_AMG(FEModel* fem);
~Hypre_PCG_AMG();
void SetPrintLevel(int n) override;
void SetMaxIterations(int n);
void SetConvergencTolerance(double tol);
public:
// allocate storage
bool PreProcess() override;
//! Factor the matrix (for iterative solvers, this can be used for creating pre-conditioner)
bool Factor() override;
//! Calculate the solution of RHS b and store solution in x
bool BackSolve(double* x, double* b) override;
//! Return a sparse matrix compatible with this solver
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
//! set the sparse matrix
bool SetSparseMatrix(SparseMatrix* A) override;
//! clean up
void Destroy() override;
private:
Implementation* imp;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/FGMRESSolver.cpp | .cpp | 12,356 | 458 | /*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 "FGMRESSolver.h"
#include <FECore/CompactSymmMatrix.h>
#include <FECore/CompactUnSymmMatrix.h>
#include <FECore/log.h>
#include "MatrixTools.h"
//-----------------------------------------------------------------------------
// We must undef PARDISO since it is defined as a function in mkl_solver.h
#ifdef MKL_ISS
#ifdef PARDISO
#undef PARDISO
#endif
#include "mkl_rci.h"
#include "mkl_blas.h"
#include "mkl_spblas.h"
#endif // MKL_ISS
BEGIN_FECORE_CLASS(FGMRESSolver, IterativeLinearSolver)
ADD_PARAMETER(m_maxiter , "max_iter");
ADD_PARAMETER(m_print_level , "print_level");
ADD_PARAMETER(m_doResidualTest, "check_residual");
ADD_PARAMETER(m_nrestart , "max_restart");
ADD_PARAMETER(m_reltol , "tol");
ADD_PARAMETER(m_abstol , "abs_tol");
ADD_PARAMETER(m_maxIterFail , "fail_max_iters");
ADD_PROPERTY(m_P, "pc_left")->SetFlags(FEProperty::Optional);
ADD_PROPERTY(m_R, "pc_right")->SetFlags(FEProperty::Optional);
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
FGMRESSolver::FGMRESSolver(FEModel* fem) : IterativeLinearSolver(fem), m_pA(0)
{
m_maxiter = 0; // use default min(N, 150)
m_print_level = 0;
m_doResidualTest = true;
m_doZeroNormTest = true;
m_reltol = 0.0;
m_abstol = 0.0;
m_nrestart = 0; // use default = maxiter
m_print_cn = false;
m_do_jacobi = false;
m_P = 0; // we don't use a preconditioner for this solver
m_R = 0; // no right preconditioner
m_maxIterFail = true;
}
//-----------------------------------------------------------------------------
// set the preconditioner
void FGMRESSolver::SetLeftPreconditioner(LinearSolver* P)
{
m_P = dynamic_cast<Preconditioner*>(P);
}
//-----------------------------------------------------------------------------
//! Set the right preconditioner
void FGMRESSolver::SetRightPreconditioner(LinearSolver* R)
{
m_R = dynamic_cast<Preconditioner*>(R);
}
//-----------------------------------------------------------------------------
// get the preconditioner
LinearSolver* FGMRESSolver::GetLeftPreconditioner()
{
return m_P;
}
//-----------------------------------------------------------------------------
// get the preconditioner
LinearSolver* FGMRESSolver::GetRightPreconditioner()
{
return m_R;
}
//-----------------------------------------------------------------------------
//! Set max nr of iterations
void FGMRESSolver::SetMaxIterations(int n)
{
m_maxiter = n;
}
//-----------------------------------------------------------------------------
//! Get the max nr of iterations
int FGMRESSolver::GetMaxIterations() const
{
return m_maxiter;
}
//-----------------------------------------------------------------------------
//! Set the nr of non-restarted iterations
void FGMRESSolver::SetNonRestartedIterations(int n)
{
m_nrestart = n;
}
//-----------------------------------------------------------------------------
// Set the print level
void FGMRESSolver::SetPrintLevel(int n)
{
m_print_level = n;
}
//-----------------------------------------------------------------------------
// set residual stopping test flag
void FGMRESSolver::DoResidualStoppingTest(bool b)
{
m_doResidualTest = b;
}
//-----------------------------------------------------------------------------
// set zero norm stopping test flag
void FGMRESSolver::DoZeroNormStoppingTest(bool b)
{
m_doZeroNormTest = b;
}
//-----------------------------------------------------------------------------
// set the convergence tolerance for the residual stopping test
void FGMRESSolver::SetRelativeResidualTolerance(double tol)
{
m_reltol = tol;
}
//-----------------------------------------------------------------------------
// set the absolute convergence tolerance for the residual stopping test
void FGMRESSolver::SetAbsoluteResidualTolerance(double tol)
{
m_abstol = tol;
}
//-----------------------------------------------------------------------------
//! This solver does not use a preconditioner
bool FGMRESSolver::HasPreconditioner() const
{
return ((m_P != 0) || (m_R != 0));
}
//-----------------------------------------------------------------------------
void FGMRESSolver::FailOnMaxIterations(bool b)
{
m_maxIterFail = b;
}
//-----------------------------------------------------------------------------
void FGMRESSolver::PrintConditionNumber(bool b)
{
m_print_cn = b;
}
//-----------------------------------------------------------------------------
// do jacobi preconditioning
void FGMRESSolver::DoJacobiPreconditioning(bool b)
{
m_do_jacobi = b;
}
//-----------------------------------------------------------------------------
SparseMatrix* FGMRESSolver::CreateSparseMatrix(Matrix_Type ntype)
{
#ifdef MKL_ISS
// Cleanup if necessary
if (m_pA) delete m_pA;
m_pA = nullptr;
// since FMGRES doesn't really care what matrix is requested,
// see if the preconditioner cares.
if (m_P)
{
m_P->SetPartitions(m_part);
m_pA = m_P->CreateSparseMatrix(ntype);
return m_pA;
}
else if (m_R)
{
m_R->SetPartitions(m_part);
m_pA = m_R->CreateSparseMatrix(ntype);
return m_pA;
}
// if the matrix is still zero, let's just allocate one
if (m_pA == nullptr)
{
// allocate new matrix
switch (ntype)
{
case REAL_SYMMETRIC: m_pA = new CompactSymmMatrix(1); break;
case REAL_UNSYMMETRIC: m_pA = new CRSSparseMatrix(1); break;
case REAL_SYMM_STRUCTURE: m_pA = new CRSSparseMatrix(1); break;
}
}
// return the matrix (Can be null if matrix format not supported!)
return m_pA;
#else
return 0;
#endif
}
//-----------------------------------------------------------------------------
bool FGMRESSolver::SetSparseMatrix(SparseMatrix* pA)
{
m_pA = pA;
return (m_pA != 0);
}
//-----------------------------------------------------------------------------
//! Clean up
void FGMRESSolver::Destroy()
{
m_tmp.clear();
m_tmp.shrink_to_fit();
}
//-----------------------------------------------------------------------------
bool FGMRESSolver::PreProcess()
{
#ifdef MKL_ISS
// number of equations
MKL_INT N = m_pA->Rows();
int M = (N < 150 ? N : 150); // this is the default value of ipar[14]
if (m_nrestart > 0) M = m_nrestart;
else if (m_maxiter > 0) M = m_maxiter;
// allocate temp storage
m_tmp.resize((N*(2 * M + 1) + (M*(M + 9)) / 2 + 1));
m_Rv.resize(N);
m_W.resize(N, 1.0);
return true;
#else
return false;
#endif
}
//! Factor the matrix
bool FGMRESSolver::Factor()
{
int neq = m_pA->Rows();
if (m_do_jacobi)
{
for (int i = 0; i < neq; ++i)
{
double dii = fabs(m_pA->diag(i));
if (dii == 0.0) return false;
m_W[i] = 1.0 / sqrt(dii);
}
}
if (m_do_jacobi)
m_pA->scale(m_W, m_W);
if (m_print_cn)
{
double c = NumCore::estimateConditionNumber(GetSparseMatrix());
feLog("\tcondition number (est.) ................... : %lg\n\n", c);
}
// call the preconditioner
if (m_P)
{
m_P->SetFEModel(GetFEModel());
if (m_P->PreProcess() == false) return false;
if (m_P->Factor() == false) return false;
}
if (m_R)
{
m_R->SetFEModel(GetFEModel());
if (m_R->PreProcess() == false) return false;
if (m_R->Factor() == false) return false;
}
return true;
}
//-----------------------------------------------------------------------------
bool FGMRESSolver::BackSolve(double* x, double* b)
{
#ifdef MKL_ISS
// make sure we have a matrix
if (m_pA == 0) return false;
// number of equations
MKL_INT N = m_pA->Rows();
// data allocation
int M = (N < 150 ? N : 150); // this is the default value of ipar[4] and ipar[14]
int nrestart = M;
if (m_nrestart > 0) nrestart = m_nrestart;
else if (m_maxiter > 0) nrestart = m_maxiter;
int maxIter = M;
if (m_maxiter > 0) maxIter = m_maxiter;
// scale rhs
vector<double> F(N);
for (int i = 0; i < N; ++i) F[i] = m_W[i] * b[i];
// initialize the solver
MKL_INT ipar[128] = { 0 };
double dpar[128] = { 0.0 };
MKL_INT ivar = N;
MKL_INT RCI_request;
dfgmres_init(&ivar, &x[0], &F[0], &RCI_request, ipar, dpar, &m_tmp[0]);
if (RCI_request != 0) { MKL_Free_Buffers(); return false; }
// Set the desired parameters:
ipar[ 4] = maxIter; // max number of iterations
ipar[ 7] = 1; // do the stopping test for maximal number of iterations
ipar[ 8] = (m_doResidualTest ? 1 : 0); // do residual stopping test
ipar[ 9] = 0; // do not request for the user defined stopping test
ipar[10] = (m_P != 0 ? 1 : 0); // do the pre-conditioned version of the FGMRES iterative solver
ipar[11] = (m_doZeroNormTest ? 1 : 0); // do the check of the norm of the next generated vector automatically
ipar[14] = nrestart; // number of non-restarted iterations
if (m_reltol > 0) dpar[0] = m_reltol; // set the relative tolerance
if (m_abstol > 0) dpar[1] = m_abstol; // set the absolute tolerance
// Check the correctness and consistency of the newly set parameters
dfgmres_check(&ivar, &x[0], &F[0], &RCI_request, ipar, dpar, &m_tmp[0]);
if (RCI_request != 0) { MKL_Free_Buffers(); return false; }
// zero solution vector
for (int i = 0; i < N; ++i) x[i] = 0.0;
if (m_print_level > 0) feLog("FGMRES:\n");
// solve the problem
bool bdone = false;
bool bconverged = !m_maxIterFail;
while (!bdone)
{
// compute the solution via FGMRES
dfgmres(&ivar, &x[0], &F[0], &RCI_request, ipar, dpar, &m_tmp[0]);
switch (RCI_request)
{
case 0: // solution converged.
bdone = true;
bconverged = true;
break;
case 1:
{
// do matrix-vector multiplication
if (m_R)
{
// first apply the right preconditioner
m_R->mult_vector(&m_tmp[ipar[21] - 1], &m_Rv[0]);
// then multiply with matrix
m_pA->mult_vector(&m_Rv[0], &m_tmp[ipar[22] - 1]);
}
else m_pA->mult_vector(&m_tmp[ipar[21] - 1], &m_tmp[ipar[22] - 1]);
if (m_print_level > 1)
{
feLog("%3d = %lg (%lg), %lg (%lg)\n", ipar[3], dpar[4], dpar[3], dpar[6], dpar[7]);
}
}
break;
case 3: // do the pre-conditioning step
{
assert(m_P);
if (m_P->mult_vector(&m_tmp[ipar[21] - 1], &m_tmp[ipar[22] - 1]) == false)
{
bdone = true;
bconverged = false;
}
}
break;
case 4:
break;
default: // something went wrong
bdone = true;
bconverged = !m_maxIterFail;
}
}
// get the solution.
MKL_INT itercount;
dfgmres_get(&ivar, &x[0], &F[0], &RCI_request, ipar, dpar, &m_tmp[0], &itercount);
if (m_do_jacobi)
{
for (int i = 0; i < N; ++i) x[i] *= m_W[i];
}
if (m_R)
{
m_R->mult_vector(&x[0], &m_Rv[0]);
for (int i = 0; i < N; ++i) x[i] = m_Rv[i];
}
if (m_print_level > 0)
{
feLog("%3d = %lg (%lg), %lg (%lg)\n", ipar[3]+1, dpar[4], dpar[3], dpar[6], dpar[7]);
}
// MKL_Free_Buffers();
// update stats
UpdateStats(itercount);
return bconverged;
#else
return false;
#endif // MKL_ISS
}
//! convenience function for solving linear system Ax = b
bool FGMRESSolver::Solve(SparseMatrix* A, vector<double>& x, vector<double>& b)
{
SetSparseMatrix(A);
if (PreProcess() == false) return false;
if (Factor() == false) return false;
return BackSolve(&x[0], &b[0]);
}
| C++ |
3D | febiosoftware/FEBio | NumCore/NumCore.h | .h | 1,427 | 39 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FECore/LinearSolver.h"
#include "numcore_api.h"
namespace NumCore {
NUMCORE_API void InitModule();
} // namespace NumCore
| Unknown |
3D | febiosoftware/FEBio | NumCore/PardisoSolver64.cpp | .cpp | 7,486 | 266 | /*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 <stdio.h>
#include <stdlib.h>
#include "PardisoSolver64.h"
#include "MatrixTools.h"
#include <FECore/CompactSymmMatrix64.h>
#include <FECore/log.h>
#ifdef PARDISO
#undef PARDISO
#include <mkl.h>
#include <mkl_pardiso.h>
#define PARDISO
#endif
class PardisoSolver64::Imp
{
public:
CompactSymmMatrix64* pA = nullptr;
long long mtype = -2; // matrix type
// Pardiso control parameters
long long iparm[64] = { 0 };
long long maxfct = 0, mnum = 0;
int msglvl = 0;
double dparm[64] = { 0 };
bool iparm3 = false; // use direct-iterative method
// Matrix data
long long n = 0, nnz = 0, nrhs = 0;
bool isFactored = false;
void* pt[64] = { nullptr }; // Internal solver memory pointer
void print_err(long long nerror);
};
//-----------------------------------------------------------------------------
// print pardiso error message
void PardisoSolver64::Imp::print_err(long long nerror)
{
switch (-nerror)
{
case 1: fprintf(stderr, "Inconsistent input\n"); break;
case 2: fprintf(stderr, "Not enough memory\n"); break;
case 3: fprintf(stderr, "Reordering problem\n"); break;
case 4: fprintf(stderr, "Zero pivot, numerical fact. or iterative refinement problem\n"); break;
case 5: fprintf(stderr, "Unclassified (internal) error\n"); break;
case 6: fprintf(stderr, "Preordering failed\n"); break;
case 7: fprintf(stderr, "Diagonal matrix problem\n"); break;
case 8: fprintf(stderr, "32-bit integer overflow problem\n"); break;
default:
fprintf(stderr, " Unknown\n");
}
}
BEGIN_FECORE_CLASS(PardisoSolver64, LinearSolver)
ADD_PARAMETER(m.iparm3 , "precondition");
ADD_PARAMETER(m.msglvl , "msglvl");
END_FECORE_CLASS();
PardisoSolver64::PardisoSolver64(FEModel* fem) : LinearSolver(fem), m(*(new Imp))
{
}
PardisoSolver64::~PardisoSolver64()
{
#ifdef PARDISO
MKL_Free_Buffers();
#endif
}
void PardisoSolver64::UseIterativeFactorization(bool b)
{
m.iparm3 = b;
}
SparseMatrix* PardisoSolver64::CreateSparseMatrix(Matrix_Type ntype)
{
#ifdef PARDISO
// allocate the correct matrix format depending on matrix symmetry type
switch (ntype)
{
case REAL_SYMMETRIC : m.mtype = -2; m.pA = new CompactSymmMatrix64(1); break;
default:
assert(false);
m.pA = nullptr;
}
return m.pA;
#else
return nullptr;
#endif
}
bool PardisoSolver64::SetSparseMatrix(SparseMatrix* pA)
{
#ifdef PARDISO
if (m.pA && m.isFactored) Destroy();
m.pA = dynamic_cast<CompactSymmMatrix64*>(pA);
m.mtype = -2;
return (m.pA != nullptr);
#else
return false;
#endif
}
bool PardisoSolver64::PreProcess()
{
#ifdef PARDISO
assert(m.isFactored == false);
m.iparm[0] = 1; // supply all values
m.iparm[1] = 2; // nested dissection algorithm from METIS
m.iparm[9] = 8; // The default value for symmetric indefinite matrices (mtype =-2, mtype=-4, mtype=6), eps = 1e-8
m.iparm[17] = 0; // Report the number of non-zero elements in the factors.(disable)
m.iparm[18] = 0; // Disable report.
m.iparm[20] = 1; // Pivoting for symmetric indefinite matrices. ( for matrices of mtype=-2, mtype=-4, or mtype=6.)
m.n = m.pA->Rows();
m.nnz = m.pA->NonZeroes();
m.nrhs = 1;
m.maxfct = 1; /* Maximum number of numerical factorizations */
m.mnum = 1; /* Which factorization to use */
return LinearSolver::PreProcess();
#else
return false;
#endif
}
bool PardisoSolver64::Factor()
{
#ifdef PARDISO
// make sure we have work to do
if (m.pA->Rows() == 0) return true;
// ------------------------------------------------------------------------------
// Reordering and Symbolic Factorization. This step also allocates all memory
// that is necessary for the factorization.
// ------------------------------------------------------------------------------
long long phase = 11;
long long error = 0;
long long msglvl = m.msglvl;
pardiso_64(m.pt, &m.maxfct, &m.mnum, &m.mtype, &phase, &m.n, m.pA->Values(), m.pA->Pointers64(), m.pA->Indices64(),
NULL, &m.nrhs, m.iparm, &msglvl, NULL, NULL, &error);
if (error)
{
fprintf(stderr, "\nERROR during symbolic factorization: ");
m.print_err(error);
exit(2);
}
if (m.msglvl == 1)
{
long long* ip = m.iparm;
fprintf(stdout, "\nMemory info:\n");
fprintf(stdout, "============\n");
fprintf(stdout, "Peak memory on symbolic factorization ............. : %d KB\n", (int)ip[14]);
fprintf(stdout, "Permanent memory on symbolic factorization ........ : %d KB\n", (int)ip[15]);
fprintf(stdout, "Peak memory on numerical factorization and solution : %d KB\n", (int)ip[16]);
fprintf(stdout, "Total peak memory ................................. : %d KB\n\n", (int)max(ip[14], ip[15]+ip[16]));
}
// ------------------------------------------------------------------------------
// This step does the factorization
// ------------------------------------------------------------------------------
m.iparm[3] = (m.iparm3 ? 61 : 0);
phase = 22;
error = 0;
pardiso_64(m.pt, &m.maxfct, &m.mnum, &m.mtype, &phase, &m.n, m.pA->Values(), m.pA->Pointers64(), m.pA->Indices64(),
NULL, &m.nrhs, m.iparm, &msglvl, NULL, NULL, &error);
if (error)
{
fprintf(stderr, "\nERROR during factorization: ");
m.print_err(error);
return false;
}
m.isFactored = true;
return true;
#else
return false;
#endif
}
bool PardisoSolver64::BackSolve(double* x, double* b)
{
#ifdef PARDISO
// make sure we have work to do
if (m.pA->Rows() == 0) return true;
long long phase = 33;
m.iparm[7] = 1; /* Maximum number of iterative refinement steps */
long long error = 0;
long long msglvl = m.msglvl;
pardiso_64(m.pt, &m.maxfct, &m.mnum, &m.mtype, &phase, &m.n, m.pA->Values(), m.pA->Pointers64(), m.pA->Indices64(),
NULL, &m.nrhs, m.iparm, &msglvl, b, x, &error);
if (error)
{
fprintf(stderr, "\nERROR during solution: ");
m.print_err(error);
exit(3);
}
// update stats
UpdateStats(1);
return true;
#else
return false;
#endif
}
void PardisoSolver64::Destroy()
{
#ifdef PARDISO
if (m.pA && m.isFactored)
{
long long phase = -1;
long long error = 0;
long long msglvl = m.msglvl;
pardiso_64(m.pt, &m.maxfct, &m.mnum, &m.mtype, &phase, &m.n, NULL, m.pA->Pointers64(), m.pA->Indices64(),
NULL, &m.nrhs, m.iparm, &msglvl, NULL, NULL, &error);
}
m.isFactored = false;
#endif
}
| C++ |
3D | febiosoftware/FEBio | NumCore/numcore_api.h | .h | 1,528 | 45 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#ifdef WIN32
#ifdef FECORE_DLL
#ifdef numcore_EXPORTS
#define NUMCORE_API __declspec(dllexport)
#else
#define NUMCORE_API __declspec(dllimport)
#endif
#else
#define NUMCORE_API
#endif
#else
#define NUMCORE_API
#endif
| Unknown |
3D | febiosoftware/FEBio | NumCore/MKLDSSolver.cpp | .cpp | 6,093 | 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 <stdio.h>
#include <stdlib.h>
#include "MKLDSSolver.h"
#include <FECore/CompactUnSymmMatrix.h>
#include <FECore/CompactSymmMatrix.h>
#ifdef PARDISO
#undef PARDISO
#include "mkl_dss.h"
#include "mkl_types.h"
#define PARDISO
#endif
#ifdef PARDISO
class MKLDSSolver::Imp
{
public:
CompactMatrix* A = nullptr;
_MKL_DSS_HANDLE_t handle = nullptr;
MKL_INT opt = MKL_DSS_DEFAULTS;
MKL_INT sym = MKL_DSS_SYMMETRIC;
int msglvl = 0;
};
BEGIN_FECORE_CLASS(MKLDSSolver, LinearSolver)
ADD_PARAMETER(m->msglvl, "msglvl");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
MKLDSSolver::MKLDSSolver(FEModel* fem) : LinearSolver(fem), m(new MKLDSSolver::Imp)
{
}
//-----------------------------------------------------------------------------
MKLDSSolver::~MKLDSSolver()
{
Destroy();
delete m;
}
//-----------------------------------------------------------------------------
SparseMatrix* MKLDSSolver::CreateSparseMatrix(Matrix_Type ntype)
{
// allocate the correct matrix format depending on matrix symmetry type
switch (ntype)
{
case REAL_SYMMETRIC : m->A = new CompactSymmMatrix(1); m->sym = MKL_DSS_SYMMETRIC; break;
case REAL_UNSYMMETRIC : m->A = new CRSSparseMatrix(1); m->sym = MKL_DSS_NON_SYMMETRIC; break;
case REAL_SYMM_STRUCTURE: m->A = new CRSSparseMatrix(1); m->sym = MKL_DSS_SYMMETRIC_STRUCTURE; break;
default:
assert(false);
m->A = nullptr;
}
return m->A;
}
//-----------------------------------------------------------------------------
bool MKLDSSolver::SetSparseMatrix(SparseMatrix* pA)
{
return (m->A != nullptr);
}
//-----------------------------------------------------------------------------
bool MKLDSSolver::PreProcess()
{
SparseMatrix& A = *m->A;
int nRows = A.Rows();
int nCols = A.Columns();
int nnz = A.NonZeroes();
// create handle
if (m->handle == nullptr)
{
m->opt = MKL_DSS_DEFAULTS;
MKL_INT error = dss_create(m->handle, m->opt);
if (error != MKL_DSS_SUCCESS) return false;
}
// define the structure
MKL_INT error = dss_define_structure(m->handle, m->sym, A.Pointers(), nRows, nCols, A.Indices(), nnz);
if (error != MKL_DSS_SUCCESS) return false;
// reorder
// m->opt = MKL_DSS_AUTO_ORDER;
// m->opt = MKL_DSS_METIS_ORDER;
m->opt = MKL_DSS_METIS_OPENMP_ORDER;
error = dss_reorder(m->handle, m->opt, 0);
if (error != MKL_DSS_SUCCESS) return false;
if (m->msglvl != 0)
{
m->opt = MKL_DSS_DEFAULTS;
const char* szstat = "PeakMem,FactorMem";
double ret[2];
dss_statistics(m->handle, m->opt, szstat, ret);
fprintf(stdout, "\nMKLDSS Memory info:\n");
fprintf(stdout, "===================\n");
fprintf(stdout, "Peak memory of symbolic factorization phase ........... : %lg KB\n", ret[0]);
fprintf(stdout, "Permanent memory for the factorization and solve phases : %lg KB\n", ret[1]);
fprintf(stdout, "\n");
}
return LinearSolver::PreProcess();
}
//-----------------------------------------------------------------------------
bool MKLDSSolver::Factor()
{
// make sure we have work to do
if ((m->A == nullptr) || (m->A->Rows() == 0)) return true;
SparseMatrix& A = *m->A;
// MKL_INT type = MKL_DSS_POSITIVE_DEFINITE;
MKL_INT type = MKL_DSS_INDEFINITE;
MKL_INT error = dss_factor_real(m->handle, type, A.Values());
if (error != MKL_DSS_SUCCESS) return false;
return true;
}
//-----------------------------------------------------------------------------
bool MKLDSSolver::BackSolve(double* x, double* b)
{
// make sure we have work to do
if ((m->A == nullptr) || (m->A->Rows() == 0)) return true;
int nRhs = 1;
m->opt = MKL_DSS_DEFAULTS;
MKL_INT error = dss_solve_real(m->handle, m->opt, b, nRhs, x);
if (error != MKL_DSS_SUCCESS) return false;
// update stats
UpdateStats(1);
return true;
}
//-----------------------------------------------------------------------------
void MKLDSSolver::Destroy()
{
if (m->handle)
{
m->opt = MKL_DSS_DEFAULTS;
MKL_INT error = dss_delete(m->handle, m->opt);
assert(error == MKL_DSS_SUCCESS);
m->handle = nullptr;
}
}
#else
//-----------------------------------------------------------------------------
class MKLDSSolver::Imp
{
public:
CompactMatrix* A = nullptr;
int msglvl = 0;
};
BEGIN_FECORE_CLASS(MKLDSSolver, LinearSolver)
ADD_PARAMETER(m->msglvl, "msglvl");
END_FECORE_CLASS();
MKLDSSolver::MKLDSSolver(FEModel* fem) : LinearSolver(fem), m(new MKLDSSolver::Imp) {}
MKLDSSolver::~MKLDSSolver() {}
SparseMatrix* MKLDSSolver::CreateSparseMatrix(Matrix_Type ntype) { return nullptr; }
bool MKLDSSolver::SetSparseMatrix(SparseMatrix* pA) { return false; }
bool MKLDSSolver::PreProcess() { return false; }
bool MKLDSSolver::Factor() { return false; }
bool MKLDSSolver::BackSolve(double* x, double* b) { return false; }
void MKLDSSolver::Destroy() {}
#endif
| C++ |
3D | febiosoftware/FEBio | NumCore/HypreGMRESsolver.h | .h | 2,327 | 73 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/LinearSolver.h>
#include <FECore/CompactUnSymmMatrix.h>
//-----------------------------------------------------------------------------
// This class implements the HYPRE GMRES solver
class HypreGMRESsolver : public LinearSolver
{
class Implementation;
public:
HypreGMRESsolver(FEModel* fem);
~HypreGMRESsolver();
void SetPrintLevel(int n) override;
void SetMaxIterations(int n);
void SetConvergencTolerance(double tol);
public:
// allocate storage
bool PreProcess() override;
//! Factor the matrix (for iterative solvers, this can be used for creating pre-conditioner)
bool Factor() override;
//! Calculate the solution of RHS b and store solution in x
bool BackSolve(double* x, double* b) override;
//! Return a sparse matrix compatible with this solver
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
//! set the sparse matrix
bool SetSparseMatrix(SparseMatrix* A) override;
//! clean up
void Destroy() override;
private:
Implementation* imp;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/BlockSolver.cpp | .cpp | 8,472 | 322 | /*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 "BlockSolver.h"
#include <FECore/log.h>
BEGIN_FECORE_CLASS(BlockIterativeSolver, IterativeLinearSolver)
ADD_PARAMETER(m_maxiter , "max_iter");
ADD_PARAMETER(m_printLevel, "print_level");
ADD_PARAMETER(m_tol , "tol");
ADD_PARAMETER(m_failMaxIter, "fail_max_iter");
ADD_PARAMETER(m_method , "solution_method");
ADD_PARAMETER(m_zeroInitGuess, "zero_initial_guess");
END_FECORE_CLASS()
//-----------------------------------------------------------------------------
//! constructor
BlockIterativeSolver::BlockIterativeSolver(FEModel* fem) : IterativeLinearSolver(fem)
{
m_pA = 0;
m_tol = 1e-8;
m_maxiter = 150;
m_iter = 0;
m_printLevel = 0;
m_failMaxIter = true;
m_method = JACOBI;
m_zeroInitGuess = true;
}
//-----------------------------------------------------------------------------
//! constructor
BlockIterativeSolver::~BlockIterativeSolver()
{
}
//-----------------------------------------------------------------------------
// return whether the iterative solver has a preconditioner or not
bool BlockIterativeSolver::HasPreconditioner() const
{
return false;
}
//-----------------------------------------------------------------------------
void BlockIterativeSolver::SetRelativeTolerance(double tol)
{
m_tol = tol;
}
//-----------------------------------------------------------------------------
// set the max nr of iterations
void BlockIterativeSolver::SetMaxIterations(int maxiter)
{
m_maxiter = maxiter;
}
//-----------------------------------------------------------------------------
// get the iteration count
int BlockIterativeSolver::GetIterations() const
{
return m_iter;
}
//-----------------------------------------------------------------------------
// set the print level
void BlockIterativeSolver::SetPrintLevel(int n)
{
m_printLevel = n;
}
//-----------------------------------------------------------------------------
// set the solution method
void BlockIterativeSolver::SetSolutionMethod(int method)
{
m_method = method;
}
//-----------------------------------------------------------------------------
// set fail on max iterations flag
void BlockIterativeSolver::SetFailMaxIters(bool b)
{
m_failMaxIter = b;
}
//-----------------------------------------------------------------------------
// set the zero-initial-guess flag
void BlockIterativeSolver::SetZeroInitialGuess(bool b)
{
m_zeroInitGuess = b;
}
//-----------------------------------------------------------------------------
//! Create a sparse matrix
SparseMatrix* BlockIterativeSolver::CreateSparseMatrix(Matrix_Type ntype)
{
m_pA = new BlockMatrix();
m_pA->Partition(m_part, ntype);
return m_pA;
}
//-----------------------------------------------------------------------------
//! set the sparse matrix
bool BlockIterativeSolver::SetSparseMatrix(SparseMatrix* m)
{
m_pA = dynamic_cast<BlockMatrix*>(m);
if (m_pA)
{
vector<int> p(m_pA->Partitions());
for (int i = 0; i < m_pA->Partitions(); ++i) p[i] = m_pA->PartitionEquations(i);
SetPartitions(p);
}
return (m_pA != nullptr);
}
//-----------------------------------------------------------------------------
//! Preprocess
bool BlockIterativeSolver::PreProcess()
{
// make sure we have a matrix
if (m_pA == 0) return false;
// get the number of partitions
int NP = m_pA->Partitions();
// allocate solvers for diagonal blocks
m_solver.resize(NP);
for (int i=0; i<NP; ++i)
{
m_solver[i] = new PardisoSolver(GetFEModel());
BlockMatrix::BLOCK& Bi = m_pA->Block(i,i);
m_solver[i]->SetSparseMatrix(Bi.pA);
if (m_solver[i]->PreProcess() == false) return false;
}
m_iter = 0;
return true;
}
//-----------------------------------------------------------------------------
//! Factor matrix
bool BlockIterativeSolver::Factor()
{
// factor the diagonal matrices
int N = (int) m_solver.size();
for (int i=0; i<N; ++i) m_solver[i]->Factor();
return true;
}
//-----------------------------------------------------------------------------
//! Backsolve the linear system
bool BlockIterativeSolver::BackSolve(double* x, double* b)
{
// get partitions
int NP = m_pA->Partitions();
assert(NP == Partitions());
// split right-hand-side and solution vector in partitions
vector< vector<double> > R(NP);
vector< vector<double> > X(NP);
int neq0 = 0;
for (int i=0; i<NP; ++i)
{
int neq = m_pA->PartitionEquations(i);
vector<double>& Ri = R[i];
Ri.resize(neq);
for (int j=0; j<neq; ++j) Ri[j] = b[j + neq0];
// also allocate and initialize solution vectors
// we assume that the passed x is an initial guess
X[i].resize(neq);
if (m_zeroInitGuess)
{
zero(X[i]);
}
else
{
for (int j = 0; j < neq; ++j) X[i][j] = x[j + neq0];
}
neq0 += neq;
}
assert(neq0 == m_pA->Rows());
// residual vector
vector<double> res(neq0);
// calculate initial norm
m_pA->mult_vector(x, &res[0]);
for (int i = 0; i<neq0; ++i) res[i] -= b[i];
double norm0 = l2_norm(res);
if (m_printLevel == 1) feLog("%d: %lg\n", 0, norm0);
// temp storage for RHS
vector< vector<double> > T(R.size());
// solve the linear system iteratively
bool bconv = false;
m_iter = 0;
double norm = 0.0;
for (int n=0; n<m_maxiter; ++n)
{
// loop over rows
for (int i=0; i<NP; ++i)
{
T[i].assign(R[i].size(), 0.0);
// loop over columns
for (int j=0; j<NP; ++j)
{
if (i != j)
{
// get the off-diagonal matrix
CompactMatrix& Cij = *(m_pA->Block(i,j).pA);
// multiply with X[j] and add to T[i]
vector<double>& Xj = X[j];
vector<double>& Ti = T[i];
if (l2_sqrnorm(Xj) != 0.0)
Cij.mult_vector(&Xj[0], &Ti[0]);
}
}
// subtract temp from RHS
int neq = m_pA->PartitionEquations(i);
for (int j=0; j<neq; ++j) T[i][j] = R[i][j] - T[i][j];
if (m_method == GAUSS_SEIDEL)
{
if (l2_sqrnorm(T[i]) != 0.0)
{
if (m_solver[i]->BackSolve(&X[i][0], &T[i][0]) == false)
return false;
}
else zero(X[i]);
}
}
// backsolve the equations
if (m_method == JACOBI)
{
for (int i = 0; i < NP; ++i)
{
if (m_solver[i]->BackSolve(&X[i][0], &T[i][0]) == false)
return false;
}
}
// combine solution into single solution vector
neq0 = 0;
for (int i = 0; i<NP; ++i)
{
int neq = m_pA->PartitionEquations(i);
vector<double>& Xi = X[i];
for (int j = 0; j<neq; ++j) x[neq0 + j] = Xi[j];
neq0 += neq;
}
// increment iteration count
m_iter++;
// calculate residual
m_pA->mult_vector(&x[0], &res[0]);
for (int i=0; i<neq0; ++i) res[i] -= b[i];
norm = l2_norm(res);
if (m_printLevel == 1) feLog("%d: %lg\n", m_iter, norm);
if (norm <= norm0*m_tol)
{
bconv = true;
break;
}
}
if (m_printLevel == 2) feLog("%d: %lg\n", m_iter, norm);
if ((bconv == false) && (m_failMaxIter == false))
{
if (m_printLevel != 0)
feLogWarning("Iterative solver reached max iterations, but convergence is forced.");
bconv = true;
}
UpdateStats(m_iter);
return bconv;
}
//-----------------------------------------------------------------------------
//! Clean up
void BlockIterativeSolver::Destroy()
{
int N = (int) m_solver.size();
for (int i=0; i<N; ++i) m_solver[i]->Destroy();
}
| C++ |
3D | febiosoftware/FEBio | NumCore/ILU0_Preconditioner.h | .h | 2,045 | 59 | /*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/Preconditioner.h>
//-----------------------------------------------------------------------------
class ILU0_Preconditioner : public Preconditioner
{
public:
ILU0_Preconditioner(FEModel* fem);
// create a preconditioner for a sparse matrix
bool Factor() override;
// apply to vector P x = y
bool BackSolve(double* x, double* y) override;
// create sparse matrix
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
public:
bool m_checkZeroDiagonal; // check for zero diagonals
double m_zeroThreshold; // threshold for zero diagonal check
double m_zeroReplace; // replacement value for zero diagonal
private:
vector<double> m_bilu0;
vector<double> m_tmp;
CRSSparseMatrix* m_K;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/BiCGStabSolver.h | .h | 2,298 | 65 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/Preconditioner.h>
#include <FECore/CompactSymmMatrix.h>
class BiCGStabSolver : public IterativeLinearSolver
{
public:
BiCGStabSolver(FEModel* fem);
bool PreProcess() override;
bool Factor() override;
bool BackSolve(double* x, double* b) override;
void Destroy() override;
public:
bool HasPreconditioner() const override;
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
bool SetSparseMatrix(SparseMatrix* A) override;
void SetLeftPreconditioner(LinearSolver* P) override;
LinearSolver* GetLeftPreconditioner() override;
void SetMaxIterations(int n) { m_maxiter = n; }
void SetTolerance(double tol) { m_tol = tol; }
void SetPrintLevel(int n) override { m_print_level = n; }
protected:
SparseMatrix* m_pA;
Preconditioner* m_P;
int m_maxiter; // max nr of iterations
double m_tol; // residual relative tolerance
double m_abstol; // absolute residual tolerance
int m_print_level; // output level
double m_fail_max_iter;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/SuperLU_MT.cpp | .cpp | 6,913 | 218 | /*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 <stdio.h>
#include <stdlib.h>
#include "SuperLU_MT.h"
#include "MatrixTools.h"
#include <FECore/log.h>
#ifdef HAVE_SUPERLU_MT
#define __OPENMP
#undef MAX
#undef MIN
#include <slu_mt_ddefs.h>
#endif // HAVE_SUPERLU_MT
#ifdef HAVE_SUPERLU_MT
//-----------------------------------------------------------------------------
class SuperLU_MT_Solver::Impl
{
public:
SuperMatrix A, L, U;
SuperMatrix B, X;
SuperMatrix AC;
vector<int> perm_c;
vector<int> perm_r;
bool isFactored = false;
superlumt_options_t options;
Gstat_t Gstat;
int nprocs = 1;
/*
* Get column permutation vector perm_c[], according to permc_spec:
* permc_spec = 0: natural ordering
* permc_spec = 1: minimum degree ordering on structure of A'*A
* permc_spec = 2: minimum degree ordering on structure of A'+A
* permc_spec = 3: approximate minimum degree for unsymmetric matrices
*/
int permc_spec = 3;
};
BEGIN_FECORE_CLASS(SuperLU_MT_Solver, LinearSolver)
ADD_PARAMETER(m->nprocs, "nprocs");
ADD_PARAMETER(m->permc_spec, "permc_spec");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
SuperLU_MT_Solver::SuperLU_MT_Solver(FEModel* fem) : LinearSolver(fem), m_pA(nullptr)
{
m = new SuperLU_MT_Solver::Impl;
}
//-----------------------------------------------------------------------------
SuperLU_MT_Solver::~SuperLU_MT_Solver()
{
Destroy();
}
//-----------------------------------------------------------------------------
SparseMatrix* SuperLU_MT_Solver::CreateSparseMatrix(Matrix_Type ntype)
{
// allocate the correct matrix format depending on matrix symmetry type
switch (ntype)
{
case REAL_SYMMETRIC:
case REAL_UNSYMMETRIC:
case REAL_SYMM_STRUCTURE:
m_pA = new CCSSparseMatrix;
break;
default:
assert(false);
m_pA = nullptr;
}
return m_pA;
}
//-----------------------------------------------------------------------------
bool SuperLU_MT_Solver::SetSparseMatrix(SparseMatrix* pA)
{
return (m_pA != nullptr);
}
//-----------------------------------------------------------------------------
bool SuperLU_MT_Solver::PreProcess()
{
if (m_pA == nullptr) return false;
int n = m_pA->Rows();
int nnz = m_pA->NonZeroes();
dCreate_CompCol_Matrix(&m->A, n, n, nnz, m_pA->Values(), m_pA->Indices(), m_pA->Pointers(), SLU_NC, SLU_D, SLU_GE);
m->perm_c.resize(n);
m->perm_r.resize(n);
return LinearSolver::PreProcess();
}
//-----------------------------------------------------------------------------
bool SuperLU_MT_Solver::Factor()
{
// make sure we have work to do
if (m_pA->Rows() == 0) return true;
if (m->isFactored)
{
Destroy_SuperNode_SCP(&m->L);
Destroy_CompCol_NCP(&m->U);
m->isFactored = false;
}
int n = m_pA->Rows();
int nnz = m_pA->NonZeroes();
int panel_size = sp_ienv(1);
int relax = sp_ienv(2);
StatAlloc(n, m->nprocs, panel_size, relax, &m->Gstat);
StatInit(n, m->nprocs, &m->Gstat);
get_perm_c(m->permc_spec, &m->A, m->perm_c.data());
/* ------------------------------------------------------------
Initialize the option structure pdgstrf_options using the
user-input parameters;
Apply perm_c to the columns of original A to form AC.
------------------------------------------------------------*/
fact_t fact = fact_t::DOFACT;
trans_t trans = trans_t::NOTRANS;
yes_no_t refact = yes_no_t::NO;
double diag_pivot_thresh = 1.0;
yes_no_t usepr = NO;
double drop_tol = 0.0;
pdgstrf_init(m->nprocs, fact, trans, refact, panel_size, relax,
diag_pivot_thresh, usepr, drop_tol, m->perm_c.data(), m->perm_r.data(),
NULL, 0, &m->A, &m->AC, &m->options, &m->Gstat);
/* ------------------------------------------------------------
Compute the LU factorization of A.
The following routine will create nprocs threads.
------------------------------------------------------------*/
int info = 0;
pdgstrf(&m->options, &m->AC, m->perm_r.data(), &m->L, &m->U, &m->Gstat, &info);
m->isFactored = true;
return (info == 0);
}
//-----------------------------------------------------------------------------
bool SuperLU_MT_Solver::BackSolve(double* x, double* b)
{
// make sure we have work to do
if (m_pA->Rows() == 0) return true;
int n = m_pA->Rows();
memcpy(x, b, n * sizeof(double));
dCreate_Dense_Matrix(&m->B, n, 1, x, n, SLU_DN, SLU_D, SLU_GE);
/* ------------------------------------------------------------
Solve the system A*X=B, overwriting B with X.
------------------------------------------------------------*/
int info = 0;
dgstrs(trans_t::NOTRANS, &m->L, &m->U, m->perm_r.data(), m->perm_c.data(), &m->B, &m->Gstat, &info);
// update stats
UpdateStats(1);
return true;
}
//-----------------------------------------------------------------------------
void SuperLU_MT_Solver::Destroy()
{
// pdgstrf_finalize(&m->options, &m->AC);
// StatFree(&m->Gstat);
if (m->isFactored)
{
Destroy_SuperNode_SCP(&m->L);
Destroy_CompCol_NCP(&m->U);
m->isFactored = false;
}
}
#else // HAVE_SUPERLU_MT
BEGIN_FECORE_CLASS(SuperLU_MT_Solver, LinearSolver)
END_FECORE_CLASS();
SuperLU_MT_Solver::SuperLU_MT_Solver(FEModel* fem) : LinearSolver(fem), m_pA(nullptr), m(nullptr) {}
SuperLU_MT_Solver::~SuperLU_MT_Solver() {}
bool SuperLU_MT_Solver::PreProcess() { return false; }
bool SuperLU_MT_Solver::Factor() { return false; }
bool SuperLU_MT_Solver::BackSolve(double* x, double* y) { return false; }
void SuperLU_MT_Solver::Destroy() {}
SparseMatrix* SuperLU_MT_Solver::CreateSparseMatrix(Matrix_Type ntype) { return nullptr; }
bool SuperLU_MT_Solver::SetSparseMatrix(SparseMatrix* pA) { return false; }
#endif // HAVE_SUPERLU_MT
| C++ |
3D | febiosoftware/FEBio | NumCore/Hypre_PCG_AMG.cpp | .cpp | 11,176 | 432 | /*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 "Hypre_PCG_AMG.h"
#include <FECore/FEModel.h>
#include <FECore/FESolver.h>
#include <FECore/FEAnalysis.h>
#include <FECore/log.h>
#ifdef HYPRE
#include <HYPRE.h>
#include <HYPRE_IJ_mv.h>
#include <HYPRE_parcsr_mv.h>
#include <HYPRE_parcsr_ls.h>
#include <_hypre_utilities.h>
#include <_hypre_IJ_mv.h>
#include <HYPRE_krylov.h>
class Hypre_PCG_AMG::Implementation
{
public:
CRSSparseMatrix* A; // global matrix
vector<int> ind; // indices array
// Hypre stuff
HYPRE_IJMatrix ij_A;
HYPRE_ParCSRMatrix par_A;
HYPRE_Solver solver;
HYPRE_Solver precond;
HYPRE_IJVector ij_b, ij_x;
HYPRE_ParVector par_b, par_x;
FEModel* m_fem;
int m_iters;
public:
// control parameters
int m_maxiter;
double m_tol;
int m_print_level;
double m_amg_tol;
public:
Implementation() : A(0)
{
m_print_level = 0;
m_maxiter = 1000;
m_tol = 1e-7;
m_amg_tol = 1e-7;
m_iters = 0;
ij_A = nullptr;
ij_b = nullptr;
ij_x = nullptr;
solver = nullptr;
precond = nullptr;
par_A = nullptr;
par_b = nullptr;
par_x = nullptr;
}
bool isValid() const
{
return (A != 0);
}
int equations() const { return (A ? A->Rows() : 0); }
// Allocate stiffness matrix
void allocMatrix()
{
int neq = equations();
// Create an empty matrix object
int ret = 0;
ret = HYPRE_IJMatrixCreate(MPI_COMM_WORLD, 0, neq - 1, 0, neq - 1, &ij_A);
// set the matrix object type
ret = HYPRE_IJMatrixSetObjectType(ij_A, HYPRE_PARCSR);
}
// destroy stiffness matrix
void destroyMatrix()
{
if (ij_A) HYPRE_IJMatrixDestroy(ij_A);
ij_A = nullptr;
}
// Allocate vectors for rhs and solution
void allocVectors()
{
int neq = equations();
ind.resize(neq, 0);
for (int i = 0; i<neq; ++i) ind[i] = i;
// create the vector object for the rhs
HYPRE_IJVectorCreate(MPI_COMM_WORLD, 0, neq - 1, &ij_b);
HYPRE_IJVectorSetObjectType(ij_b, HYPRE_PARCSR);
// create the vector object for the solution
HYPRE_IJVectorCreate(MPI_COMM_WORLD, 0, neq - 1, &ij_x);
HYPRE_IJVectorSetObjectType(ij_x, HYPRE_PARCSR);
}
// destroy vectors
void destroyVectors()
{
if (ij_b) HYPRE_IJVectorDestroy(ij_b); ij_b = nullptr;
if (ij_x) HYPRE_IJVectorDestroy(ij_x); ij_x = nullptr;
}
// update vectors
void updateVectors(double* x, double* b)
{
// initialize vectors for changing coefficient values
HYPRE_IJVectorInitialize(ij_b);
HYPRE_IJVectorInitialize(ij_x);
// set the values
int neq = equations();
HYPRE_IJVectorSetValues(ij_b, neq, (HYPRE_Int*)&ind[0], b);
HYPRE_IJVectorSetValues(ij_x, neq, (HYPRE_Int*)&ind[0], x);
// finialize assembly
HYPRE_IJVectorAssemble(ij_b);
HYPRE_IJVectorAssemble(ij_x);
HYPRE_IJVectorGetObject(ij_b, (void**)&par_b);
HYPRE_IJVectorGetObject(ij_x, (void**)&par_x);
}
// update coefficient matrix
void updateMatrix()
{
int neq = equations();
// call initialize, after which we can set the matrix coefficients
HYPRE_Int ret = HYPRE_IJMatrixInitialize(ij_A);
// set the matrix coefficients
double* values = A->Values();
int* indices = A->Indices();
int* pointers = A->Pointers();
for (int i = 0; i<neq; ++i)
{
const int* cols = indices + pointers[i];
int ncols = pointers[i + 1] - pointers[i];
double* vals = values + pointers[i];
HYPRE_Int nrows = 1;
ret = HYPRE_IJMatrixSetValues(ij_A, nrows, (HYPRE_Int*)&ncols, (HYPRE_Int*)&i, (HYPRE_Int*)cols, vals);
}
// Finalize the matrix assembly
ret = HYPRE_IJMatrixAssemble(ij_A);
// get the matrix object for later use
ret = HYPRE_IJMatrixGetObject(ij_A, (void**)&par_A);
}
// allocate preconditioner
bool allocPrecond()
{
// Now set up the AMG preconditioner and specify any parameters
HYPRE_BoomerAMGCreate(&precond);
// HYPRE_BoomerAMGSetPrintLevel(precond, 2); // print solve info
HYPRE_BoomerAMGSetCoarsenType(precond, 10); // HMIS-coarsening
HYPRE_BoomerAMGSetStrongThreshold(precond, 0.5); // Threshold for choosing weak/strong connections
HYPRE_BoomerAMGSetMaxRowSum(precond, 1.0); // Disable dependency weakening based on maximum row sum.
HYPRE_BoomerAMGSetCycleRelaxType(precond, 13, 1); // Pre-smoother: forward L1-Gauss-Seidel
HYPRE_BoomerAMGSetCycleRelaxType(precond, 14, 2); // Post-smoother: backward L1-Gauss-Seidel
HYPRE_BoomerAMGSetCycleRelaxType(precond, 9, 3); // Coarsest grid solver: Gauss elimination
HYPRE_BoomerAMGSetAggNumLevels(precond, 1); // One level of aggressive coarsening
HYPRE_BoomerAMGSetNumPaths(precond, 1); // Number of paths of length 2 for aggressive coarsening
HYPRE_BoomerAMGSetInterpType(precond, 6); // Extended+i interpolation
HYPRE_BoomerAMGSetMaxIter(precond, m_maxiter); // Set maximum iterations
HYPRE_BoomerAMGSetTol(precond, m_amg_tol); // conv. tolerance
FESolver* fesolve = m_fem->GetCurrentStep()->GetFESolver();
// get the dof map
vector<int> dofMap;
int nfunc = fesolve->GetActiveDofMap(dofMap);
if (nfunc == -1) return false;
// allocate dof map
// (We need to copy it here since Hypre will deallocate it)
int neq = (int)dofMap.size();
int* dof_func = (int*)malloc(neq * sizeof(int));
for (size_t i = 0; i < neq; ++i) dof_func[i] = dofMap[i];
printf("\tNumber of functions : %d\n", nfunc);
// assign to BoomerAMG
HYPRE_BoomerAMGSetNumFunctions(precond, nfunc);
// set the dof map
HYPRE_BoomerAMGSetDofFunc(precond, (HYPRE_Int*)dof_func);
return true;
}
// destroy preconditioner
void destroyPrecond()
{
if (precond) HYPRE_BoomerAMGDestroy(precond);
precond = nullptr;
}
// allocate solver
void allocSolver()
{
// Create the solver object
HYPRE_ParCSRPCGCreate(MPI_COMM_WORLD, &solver);
/* Set some parameters (See Reference Manual for more parameters) */
HYPRE_PCGSetTwoNorm(solver, 1);
HYPRE_PCGSetTol(solver, m_tol);
// Set the preconditioner
HYPRE_ParCSRPCGSetPrecond(solver, (HYPRE_PtrToParSolverFcn) HYPRE_BoomerAMGSolve,
(HYPRE_PtrToParSolverFcn) HYPRE_BoomerAMGSetup, precond);
}
// destroy the solver
void destroySolver()
{
if (solver) HYPRE_ParCSRPCGDestroy(solver);
solver = nullptr;
}
// calculate the preconditioner
void doPrecond()
{
HYPRE_ParCSRPCGSetup(solver, par_A, par_b, par_x);
}
// solve the linear system
void doSolve(double* x)
{
HYPRE_ParCSRPCGSolve(solver, par_A, par_b, par_x);
/* Run info - needed logging turned on */
double final_res_norm;
HYPRE_ParCSRPCGGetNumIterations(solver, (HYPRE_Int*)&m_iters);
HYPRE_ParCSRPCGGetFinalRelativeResidualNorm(solver, &final_res_norm);
if (m_print_level != 0)
{
feLogEx(m_fem, "\n");
feLogEx(m_fem, "Iterations = %d\n", m_iters);
feLogEx(m_fem, "Final Relative Residual Norm = %e\n", final_res_norm);
feLogEx(m_fem, "\n");
}
/* get the local solution */
int neq = equations();
HYPRE_IJVectorGetValues(ij_x, neq, (HYPRE_Int*)&ind[0], &x[0]);
}
};
BEGIN_FECORE_CLASS(Hypre_PCG_AMG, LinearSolver)
ADD_PARAMETER(imp->m_print_level, "print_level");
ADD_PARAMETER(imp->m_maxiter , "maxiter" );
ADD_PARAMETER(imp->m_tol , "tol" );
ADD_PARAMETER(imp->m_amg_tol , "amg_tol" );
END_FECORE_CLASS();
Hypre_PCG_AMG::Hypre_PCG_AMG(FEModel* fem) : LinearSolver(fem), imp(new Hypre_PCG_AMG::Implementation)
{
imp->m_fem = fem;
}
Hypre_PCG_AMG::~Hypre_PCG_AMG()
{
delete imp; imp = 0;
}
void Hypre_PCG_AMG::SetPrintLevel(int n)
{
imp->m_print_level = n;
}
void Hypre_PCG_AMG::SetMaxIterations(int n)
{
imp->m_maxiter = n;
}
void Hypre_PCG_AMG::SetConvergencTolerance(double tol)
{
imp->m_tol = tol;
}
SparseMatrix* Hypre_PCG_AMG::CreateSparseMatrix(Matrix_Type ntype)
{
if (ntype == Matrix_Type::REAL_UNSYMMETRIC)
return (imp->A = new CRSSparseMatrix(0));
else
return 0;
}
bool Hypre_PCG_AMG::SetSparseMatrix(SparseMatrix* A)
{
CRSSparseMatrix* K = dynamic_cast<CRSSparseMatrix*>(A);
if (K == 0) return false;
if (K->isRowBased() == false) return false;
if (K->Offset() != 0) return false;
imp->A = K;
return true;
}
//! clean up
void Hypre_PCG_AMG::Destroy()
{
// cleanup
imp->destroyPrecond();
imp->destroySolver();
// destroy matrix
imp->destroyMatrix();
// Destroy vectors
imp->destroyVectors();
}
bool Hypre_PCG_AMG::PreProcess()
{
// make sure data is valid
if (imp->isValid() == false) return false;
// create coefficient matrix
imp->allocMatrix();
// allocate rhs and solution vectors
imp->allocVectors();
return true;
}
bool Hypre_PCG_AMG::Factor()
{
// make sure data is valid
if (imp->isValid() == false) return false;
// copy matrix values
imp->updateMatrix();
// initialize vectors
int neq = imp->equations();
vector<double> zero(neq, 0.0);
imp->updateVectors(&zero[0], &zero[0]);
// allocate preconditioner (always call before creating solver!)
imp->allocPrecond();
// allocate solver
imp->allocSolver();
// apply preconditioner
imp->doPrecond();
return true;
}
bool Hypre_PCG_AMG::BackSolve(double* x, double* b)
{
// make sure data is valid
if (imp->isValid() == false) return false;
// nr of equations
int neq = imp->equations();
// update the vectors
imp->updateVectors(x, b);
// solve
imp->doSolve(x);
// update stats
UpdateStats(imp->m_iters);
return true;
}
#else
BEGIN_FECORE_CLASS(Hypre_PCG_AMG, LinearSolver)
END_FECORE_CLASS();
Hypre_PCG_AMG::Hypre_PCG_AMG(FEModel* fem) : LinearSolver(fem) {}
Hypre_PCG_AMG::~Hypre_PCG_AMG() {}
void Hypre_PCG_AMG::Destroy() {}
void Hypre_PCG_AMG::SetPrintLevel(int n) {}
void Hypre_PCG_AMG::SetMaxIterations(int n) {}
void Hypre_PCG_AMG::SetConvergencTolerance(double tol) {}
bool Hypre_PCG_AMG::PreProcess() { return false; }
bool Hypre_PCG_AMG::Factor() { return false; }
bool Hypre_PCG_AMG::BackSolve(double* x, double* b) { return false; }
SparseMatrix* Hypre_PCG_AMG::CreateSparseMatrix(Matrix_Type ntype) { return 0; }
bool Hypre_PCG_AMG::SetSparseMatrix(SparseMatrix* A) { return false; }
#endif // HYPRE
| C++ |
3D | febiosoftware/FEBio | NumCore/SchurSolver.cpp | .cpp | 16,158 | 612 | /*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 "SchurSolver.h"
#include "ILU0_Preconditioner.h"
#include <FECore/SchurComplement.h>
#include "IncompleteCholesky.h"
#include "HypreGMRESsolver.h"
#include "RCICGSolver.h"
#include <FECore/FEModel.h>
#include <FECore/FESolidDomain.h>
#include <FECore/FEGlobalMatrix.h>
#include "PardisoSolver.h"
#include "BoomerAMGSolver.h"
#include "FGMRESSolver.h"
#include <FECore/log.h>
//-----------------------------------------------------------------------------
bool BuildDiagonalMassMatrix(FEModel* fem, BlockMatrix* K, CompactSymmMatrix* M, double scale)
{
FEMesh& mesh = fem->GetMesh();
// get number of equations
int N0 = K->Block(0, 0).Rows();
int N = K->Block(1, 1).Rows();
// build the global matrix
SparseMatrixProfile MP(N, N);
MP.CreateDiagonal();
M->Create(MP);
M->Zero();
// build the mass matrix
matrix me;
double density = 1.0;
int n = 0;
for (int i = 0; i < mesh.Domains(); ++i)
{
FESolidDomain& dom = dynamic_cast<FESolidDomain&>(mesh.Domain(i));
int NE = dom.Elements();
for (int j = 0; j < NE; ++j, ++n)
{
FESolidElement& el = dom.Element(j);
// Get the current element's data
const int nint = el.GaussPoints();
const int neln = el.Nodes();
const int ndof = neln;
// weights at gauss points
const double *gw = el.GaussWeights();
matrix me(ndof, ndof);
me.zero();
// calculate element stiffness matrix
double Me = 0.0;
for (int n = 0; n<nint; ++n)
{
FEMaterialPoint& mp = *el.GetMaterialPoint(n);
double Dn = density;
// Jacobian
double Jw = dom.detJ0(el, n)*gw[n];
Me += Dn*Jw;
}
int lm = el.m_lm - N0;
M->set(lm, lm, Me);
}
}
return true;
}
//-----------------------------------------------------------------------------
bool BuildMassMatrix(FEModel* fem, BlockMatrix* K, CompactSymmMatrix* M, double scale)
{
FEMesh& mesh = fem->GetMesh();
// get number of equations
int N0 = K->Block(0, 0).Rows();
int N = K->Block(1, 1).Rows();
// this is the degree of freedom in the LM arrays that we need
// TODO: This is hard coded for fluid problems
const int edofs = 4; // nr of degrees per element node
const int dof = 3; // degree of freedom we need
// build the global matrix
vector<vector<int> > LM;
vector<int> lm, lme;
SparseMatrixProfile MP(N, N);
MP.CreateDiagonal();
int ND = mesh.Domains();
for (int i = 0; i < ND; ++i)
{
FESolidDomain& dom = dynamic_cast<FESolidDomain&>(mesh.Domain(i));
int NE = dom.Elements();
for (int j = 0; j < NE; ++j)
{
FESolidElement& el = dom.Element(j);
int neln = el.Nodes();
// get the equation numbers
dom.UnpackLM(el, lme);
// we don't want equation numbers below N0
lm.resize(neln);
for (int i = 0; i < neln; ++i)
{
lm[i] = lme[i*edofs + dof];
if (lm[i] >= 0) lm[i] -= N0;
else if (lm[i] < -1) lm[i] = -lm[i] - 2 - N0;
}
LM.push_back(lm);
MP.UpdateProfile(LM, 1);
LM.clear();
}
}
M->Create(MP);
M->Zero();
// build the mass matrix
matrix me;
double density = 1.0;
int n = 0;
for (int i = 0; i < ND; ++i)
{
FESolidDomain& dom = dynamic_cast<FESolidDomain&>(mesh.Domain(i));
int NE = dom.Elements();
for (int j = 0; j < NE; ++j, ++n)
{
FESolidElement& el = dom.Element(j);
// Get the current element's data
const int nint = el.GaussPoints();
const int neln = el.Nodes();
const int ndof = neln;
// weights at gauss points
const double *gw = el.GaussWeights();
matrix me(ndof, ndof);
me.zero();
// calculate element stiffness matrix
for (int n = 0; n<nint; ++n)
{
FEMaterialPoint& mp = *el.GetMaterialPoint(n);
double Dn = density;
// shape functions
double* H = el.H(n);
// Jacobian
double J0 = dom.detJ0(el, n)*gw[n];
for (int i = 0; i<neln; ++i)
for (int j = 0; j<neln; ++j)
{
double mab = Dn*H[i] * H[j] * J0;
me[i][j] += mab*scale;
}
}
// get the equation numbers
dom.UnpackLM(el, lme);
// we don't want equation numbers below N0
lm.resize(neln);
for (int i = 0; i < neln; ++i)
{
lm[i] = lme[i*edofs + dof];
if (lm[i] >= 0) lm[i] -= N0;
else if (lm[i] < -1) lm[i] = -lm[i] - 2 - N0;
}
M->Assemble(me, lm);
}
}
return true;
}
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(SchurSolver, LinearSolver)
ADD_PARAMETER(m_printLevel , "print_level");
ADD_PARAMETER(m_schurBlock , "schur_block");
ADD_PARAMETER(m_doJacobi , "do_jacobi");
ADD_PARAMETER(m_bzeroDBlock , "zero_D_block");
ADD_PARAMETER(m_nSchurPreC , "schur_pc");
ADD_PROPERTY(m_Asolver, "A_solver");
ADD_PROPERTY(m_schurSolver, "schur_solver");
ADD_PROPERTY(m_SchurAsolver, "schur_A_solver");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! constructor
SchurSolver::SchurSolver(FEModel* fem) : LinearSolver(fem)
{
// default parameters
m_printLevel = 0;
m_bzeroDBlock = false;
m_schurBlock = 0; // Use Schur complement S\A
// default solution strategy
m_nSchurPreC = 0; // no preconditioner
m_iter = 0;
m_doJacobi = false;
// initialize pointers
m_pK = nullptr;
m_Asolver = nullptr;
m_PS = nullptr;
m_schurSolver = nullptr;
m_SchurAsolver = nullptr;
m_Acopy = nullptr;
}
//-----------------------------------------------------------------------------
//! constructor
SchurSolver::~SchurSolver()
{
if (m_Acopy) delete m_Acopy;
}
//-----------------------------------------------------------------------------
// get the iteration count
int SchurSolver::GetIterations() const
{
return m_iter;
}
//-----------------------------------------------------------------------------
// set the print level
void SchurSolver::SetPrintLevel(int n)
{
m_printLevel = n;
}
//-----------------------------------------------------------------------------
void SchurSolver::SetSchurPreconditioner(int n)
{
m_nSchurPreC = n;
}
//-----------------------------------------------------------------------------
void SchurSolver::ZeroDBlock(bool b)
{
m_bzeroDBlock = b;
}
//-----------------------------------------------------------------------------
// Sets which Schur complement to use
// n = 0: use S\A
// n = 1: use S\D
void SchurSolver::SetSchurBlock(int n)
{
assert((n == 0) || (n == 1));
m_schurBlock = n;
}
//-----------------------------------------------------------------------------
void SchurSolver::DoJacobiPreconditioning(bool b)
{
m_doJacobi = b;
}
//-----------------------------------------------------------------------------
//! Create a sparse matrix
SparseMatrix* SchurSolver::CreateSparseMatrix(Matrix_Type ntype)
{
if (m_part.size() != 2) return 0;
m_pK = new BlockMatrix();
m_pK->Partition(m_part, ntype, 1);
// we want the A solver to define the blocks
SparseMatrix* K11 = m_Asolver->CreateSparseMatrix(ntype);
if (K11)
{
CompactMatrix* A = dynamic_cast<CompactMatrix*>(K11);
if (A == nullptr) { delete K11; delete m_pK; return nullptr; }
delete m_pK->Block(0, 0).pA; m_pK->Block(0, 0).pA = A;
}
else
{
delete m_pK;
m_pK = nullptr;
}
return m_pK;
}
//-----------------------------------------------------------------------------
//! set the sparse matrix
bool SchurSolver::SetSparseMatrix(SparseMatrix* A)
{
m_pK = dynamic_cast<BlockMatrix*>(A);
if (m_pK == 0) return false;
return true;
}
//-----------------------------------------------------------------------------
// allocate Schur complement solver
LinearSolver* SchurSolver::BuildSchurPreconditioner(int nopt)
{
switch (nopt)
{
case Schur_PC_NONE:
// no preconditioner selected
return nullptr;
break;
case Schur_PC_DIAGONAL_MASS:
{
// diagonal mass matrix
CompactSymmMatrix* M = new CompactSymmMatrix(1);
if (BuildDiagonalMassMatrix(GetFEModel(), m_pK, M, 1.0) == false) return nullptr;
DiagonalPreconditioner* PS = new DiagonalPreconditioner(GetFEModel());
if (PS->Create(M) == false) return nullptr;
return PS;
}
break;
case Schur_PC_ICHOL_MASS:
{
// mass matrix
CompactSymmMatrix* M = new CompactSymmMatrix(1);
if (BuildMassMatrix(GetFEModel(), m_pK, M, 1.0) == false) return nullptr;
// We do an incomplete cholesky factorization
IncompleteCholesky* PS = new IncompleteCholesky(GetFEModel());
if (PS->Create(M) == false) return nullptr;
return PS;
}
break;
default:
assert(false);
};
return nullptr;
}
//-----------------------------------------------------------------------------
//! Preprocess
bool SchurSolver::PreProcess()
{
// make sure we have a matrix
if (m_pK == 0) return false;
// Get the blocks
BlockMatrix::BLOCK& A = m_pK->Block(0, 0);
BlockMatrix::BLOCK& B = m_pK->Block(0, 1);
BlockMatrix::BLOCK& C = m_pK->Block(1, 0);
BlockMatrix::BLOCK& D = m_pK->Block(1, 1);
// get the number of partitions
// and make sure we have two
int NP = m_pK->Partitions();
if (NP != 2) return false;
// check the A solver
if (m_Asolver == nullptr) return false;
m_Asolver->SetFEModel(GetFEModel());
// check the schur solver
if (m_schurSolver == nullptr) return false;
m_schurSolver->SetFEModel(GetFEModel());
// build solver for A block in Schur solver
if (m_SchurAsolver == nullptr) m_SchurAsolver = m_Asolver;
else m_SchurAsolver->SetFEModel(GetFEModel());
if (m_schurBlock == 0)
{
// Use the Schur complement of A
m_Asolver->SetSparseMatrix(A.pA);
if (m_SchurAsolver != m_Asolver)
{
SparseMatrix* AforSchur = A.pA;
m_SchurAsolver->SetSparseMatrix(AforSchur);
}
SchurComplementA* S_A = new SchurComplementA(m_SchurAsolver, B.pA, C.pA, (m_bzeroDBlock ? nullptr : D.pA));
if (m_schurSolver->SetSparseMatrix(S_A) == false) { delete S_A; return false; }
}
else
{
// Use the Schur complement of D
m_Asolver->SetSparseMatrix(D.pA);
if (m_SchurAsolver != m_Asolver)
{
SparseMatrix* DforSchur = D.pA;
m_SchurAsolver->SetSparseMatrix(DforSchur);
}
SchurComplementD* S_D = new SchurComplementD(A.pA, B.pA, C.pA, m_SchurAsolver);
if (m_schurSolver->SetSparseMatrix(S_D) == false) { delete S_D; return false; }
}
if (m_SchurAsolver != m_Asolver)
{
if (m_SchurAsolver->PreProcess() == false) return false;
}
if (m_Asolver->PreProcess() == false) return false;
// build a preconditioner for the schur complement solver
m_PS = BuildSchurPreconditioner(m_nSchurPreC);
if (m_PS) m_schurSolver->SetLeftPreconditioner(m_PS);
if (m_schurSolver->PreProcess() == false) return false;
// reset iteration counter
m_iter = 0;
return true;
}
//-----------------------------------------------------------------------------
//! Factor matrix
bool SchurSolver::Factor()
{
// Get the blocks
BlockMatrix::BLOCK& A = m_pK->Block(0, 0);
BlockMatrix::BLOCK& B = m_pK->Block(0, 1);
BlockMatrix::BLOCK& C = m_pK->Block(1, 0);
BlockMatrix::BLOCK& D = m_pK->Block(1, 1);
// Get the block matrices
CRSSparseMatrix* MA = dynamic_cast<CRSSparseMatrix*>(A.pA);
CRSSparseMatrix* MB = dynamic_cast<CRSSparseMatrix*>(B.pA);
CRSSparseMatrix* MC = dynamic_cast<CRSSparseMatrix*>(C.pA);
CRSSparseMatrix* MD = dynamic_cast<CRSSparseMatrix*>(D.pA);
// get the number of partitions
// and make sure we have two
int NP = m_pK->Partitions();
if (NP != 2) return false;
// get the partition sizes
int n0 = m_pK->PartitionEquations(0);
int n1 = m_pK->PartitionEquations(1);
// calculate the diagonal
m_Wu.assign(n0, 1.0);
m_Wp.assign(n1, 1.0);
if (m_doJacobi)
{
for (int i = 0; i < n0; ++i)
{
double dii = fabs(MA->diag(i));
// if (dii < 0) return false;
if (dii != 0.0) m_Wu[i] = 1.0 / sqrt(dii);
}
if (MD)
{
for (int i = 0; i < n1; ++i)
{
double dii = fabs(MD->diag(i));
// if (dii < 0) return false;
if (dii != 0.0) m_Wp[i] = 1.0 / sqrt(dii);
}
}
// scale the matrices
MA->scale(m_Wu, m_Wu);
MB->scale(m_Wu, m_Wp);
MC->scale(m_Wp, m_Wu);
if (MD) MD->scale(m_Wp, m_Wp);
}
// See if we need to copy the A (or D) block
if (m_Acopy)
{
if (m_schurBlock == 0) m_Acopy->CopyValues(A.pA);
else m_Acopy->CopyValues(D.pA);
}
// factor the A block solver
if (m_Asolver->Factor() == false) return false;
// factor the A block solver of the Schur complement (if necessary)
if (m_SchurAsolver && (m_SchurAsolver != m_Asolver))
{
if (m_SchurAsolver->Factor() == false) return false;
}
// factor the schur complement solver
if (m_schurSolver->Factor() == false) return false;
return true;
}
//-----------------------------------------------------------------------------
//! Backsolve the linear system
bool SchurSolver::BackSolve(double* x, double* b)
{
// get the partition sizes
int n0 = m_pK->PartitionEquations(0);
int n1 = m_pK->PartitionEquations(1);
// Get the blocks
BlockMatrix::BLOCK& A = m_pK->Block(0, 0);
BlockMatrix::BLOCK& B = m_pK->Block(0, 1);
BlockMatrix::BLOCK& C = m_pK->Block(1, 0);
BlockMatrix::BLOCK& D = m_pK->Block(1, 1);
// split right hand side in two
vector<double> F(n0), G(n1);
for (int i = 0; i<n0; ++i) F[i] = m_Wu[i]*b[i];
for (int i = 0; i<n1; ++i) G[i] = m_Wp[i]*b[i + n0];
// solution vectors
vector<double> u(n0, 0.0);
vector<double> v(n1, 0.0);
if (m_schurBlock == 0)
{
// step 1: solve Ay = F
vector<double> y(n0);
if (m_printLevel != 0) feLog("----------------------\nstep 1:\n");
if (m_Asolver->BackSolve(y, F) == false) return false;
// step 2: Solve Sv = H, where H = Cy - G
if (m_printLevel != 0) feLog("step 2:\n");
vector<double> H(n1);
C.vmult(y, H);
H -= G;
if (m_schurSolver->BackSolve(v, H) == false) return false;
// step 3: solve Au = L , where L = F - Bv
if (m_printLevel != 0) feLog("step 3:\n");
vector<double> tmp(n0);
B.vmult(v, tmp);
vector<double> L = F - tmp;
if (m_Asolver->BackSolve(u, L) == false) return false;
}
else
{
// step 1: solve Dy = G
vector<double> y(n1);
if (m_printLevel != 0) feLog("----------------------\nstep 1:\n");
if (m_Asolver->BackSolve(y, G) == false) return false;
// step 2: Solve Su = H, where H = By - F
if (m_printLevel != 0) feLog("step 2:\n");
vector<double> H(n0);
B.vmult(y, H);
H -= F;
if (m_schurSolver->BackSolve(u, H) == false) return false;
// step 3: solve Dv = L , where L = G - Cu
if (m_printLevel != 0) feLog("step 3:\n");
vector<double> tmp(n1);
C.vmult(u, tmp);
vector<double> L = G - tmp;
if (m_Asolver->BackSolve(v, L) == false) return false;
}
// put it back together
for (int i = 0; i<n0; ++i) x[i ] = m_Wu[i]*u[i];
for (int i = 0; i<n1; ++i) x[i + n0] = m_Wp[i]*v[i];
return true;
}
//-----------------------------------------------------------------------------
//! Clean up
void SchurSolver::Destroy()
{
if (m_SchurAsolver != m_Asolver) m_SchurAsolver->Destroy();
if (m_Asolver) m_Asolver->Destroy();
if (m_schurSolver) m_schurSolver->Destroy();
m_Asolver = nullptr;
m_SchurAsolver = nullptr;
m_schurSolver = nullptr;
}
| C++ |
3D | febiosoftware/FEBio | NumCore/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++ |
3D | febiosoftware/FEBio | NumCore/BIPNSolver.cpp | .cpp | 16,381 | 626 | /*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 "BIPNSolver.h"
#include <FECore/vector.h>
#include "RCICGSolver.h"
#include <FECore/SchurComplement.h>
#include <FECore/log.h>
#include "ILU0_Preconditioner.h"
#include "IncompleteCholesky.h"
#include "FGMRESSolver.h"
#include "BoomerAMGSolver.h"
#include <FECore/Preconditioner.h>
#ifdef MKL_ISS
// We must undef PARDISO since it is defined as a function in mkl_solver.h
#ifdef PARDISO
#undef PARDISO
#endif
#include "mkl_rci.h"
#include "mkl_blas.h"
#include "mkl_spblas.h"
// in SchurSolver.cpp
bool BuildDiagonalMassMatrix(FEModel* fem, BlockMatrix* K, CompactSymmMatrix* M, double scale);
bool BuildMassMatrix(FEModel* fem, BlockMatrix* K, CompactSymmMatrix* M, double scale);
BEGIN_FECORE_CLASS(BIPNSolver, LinearSolver)
ADD_PARAMETER(m_maxiter , "maxiter" );
ADD_PARAMETER(m_tol , "tol" );
ADD_PARAMETER(m_print_level , "print_level");
ADD_PARAMETER(m_use_cg , "use_cg");
ADD_PARAMETER(m_cg_maxiter , "cg_maxiter" );
ADD_PARAMETER(m_cg_tol , "cg_tol" );
ADD_PARAMETER(m_cg_doResidualTest , "cg_check_residual");
ADD_PARAMETER(m_gmres_maxiter , "gmres_maxiter");
ADD_PARAMETER(m_gmres_tol , "gmres_tol" );
ADD_PARAMETER(m_gmres_doResidualTest, "gmres_check_residual");
ADD_PARAMETER(m_gmres_pc , "gmres_precondition");
ADD_PARAMETER(m_do_jacobi , "do_jacobi");
ADD_PARAMETER(m_precondition_schur , "precondition_schur");
END_FECORE_CLASS();
// constructor
BIPNSolver::BIPNSolver(FEModel* fem) : LinearSolver(fem), m_A(0)
{
m_print_level = 0;
m_maxiter = 10;
m_tol = 1e-6;
m_cg_maxiter = 0;
m_cg_tol = 0.0;
m_cg_doResidualTest = true;
m_gmres_maxiter = 0;
m_gmres_tol = 0.0;
m_gmres_doResidualTest = true;
m_gmres_pc = 0;
m_do_jacobi = true;
m_precondition_schur = 0;
m_use_cg = true;
m_Asolver = nullptr;
m_PS = nullptr;
}
// set the max nr of BIPN iterations
void BIPNSolver::SetMaxIterations(int n)
{
m_maxiter = n;
}
// set the output level
void BIPNSolver::SetPrintLevel(int n)
{
m_print_level = n;
}
// Set the BIPN convergence tolerance
void BIPNSolver::SetTolerance(double eps)
{
m_tol = eps;
}
// Use CG for step 2 or not
void BIPNSolver::UseConjugateGradient(bool b)
{
m_use_cg = b;
}
// set the CG convergence parameters
void BIPNSolver::SetCGParameters(int maxiter, double tolerance, bool doResidualStoppingTest)
{
m_cg_maxiter = maxiter;
m_cg_tol = tolerance;
m_cg_doResidualTest = doResidualStoppingTest;
}
// set the GMRES convergence parameters
void BIPNSolver::SetGMRESParameters(int maxiter, double tolerance, bool doResidualStoppingTest, int precondition)
{
m_gmres_maxiter = maxiter;
m_gmres_tol = tolerance;
m_gmres_doResidualTest = doResidualStoppingTest;
m_gmres_pc = precondition;
}
// Do Jacobi preconditioner
void BIPNSolver::DoJacobiPreconditioner(bool b)
{
m_do_jacobi = b;
}
// set the schur preconditioner option
void BIPNSolver::SetSchurPreconditioner(int n)
{
m_precondition_schur = n;
}
//! Return a sparse matrix compatible with this solver
SparseMatrix* BIPNSolver::CreateSparseMatrix(Matrix_Type ntype)
{
// make sure we can support this matrix
if (ntype != Matrix_Type::REAL_UNSYMMETRIC) return 0;
// make sure we have two partitions
if (m_part.size() != 2) return 0;
int noffset = 1;
if (m_gmres_pc == 2) noffset = 0;
// allocate new matrix
if (m_A) delete m_A;
m_A = new BlockMatrix();
m_A->Partition(m_part, ntype, noffset);
// and return
return m_A;
}
// set the sparse matrix
bool BIPNSolver::SetSparseMatrix(SparseMatrix* A)
{
m_A = dynamic_cast<BlockMatrix*>(A);
if (m_A == nullptr) return false;
return true;
}
// allocate storage
bool BIPNSolver::PreProcess()
{
// make sure we have a matrix
if (m_A == 0) return false;
BlockMatrix& A = *m_A;
// get the number of equations
int N = A.Rows();
// make sure the partition is valid
if (m_part.size() != 2) return false;
int Nu = m_part[0];
int Np = m_part[1];
assert((Nu + Np) == N);
// allocate pre-conditioners
Kd.resize(Nu);
Wm.resize(Nu);
Wc.resize(Np);
// allocate temp storage
yu.resize(Nu);
yp.resize(Np);
yu_n.resize(Nu);
yp_n.resize(Np);
Rm0.resize(Nu);
Rc0.resize(Np);
Rm_n.resize(Nu);
Rc_n.resize(Np);
Yu.resize(m_maxiter, std::vector<double>(Nu));
Yp.resize(m_maxiter, std::vector<double>(Np));
RM.resize(Nu);
RC.resize(Np);
Rmu.resize(m_maxiter, std::vector<double>(Nu));
Rmp.resize(m_maxiter, std::vector<double>(Nu));
Rcu.resize(m_maxiter, std::vector<double>(Np));
Rcp.resize(m_maxiter, std::vector<double>(Np));
au.resize(m_maxiter+1);
ap.resize(m_maxiter+1);
du.resize(Nu);
dp.resize(Np);
// CG temp buffers
if (m_use_cg)
cg_tmp.resize(4* Np);
else
{
// GMRES buffer
int M = (Np < 150 ? Np : 150); // this is the default value of par[15] (i.e. par[14] in C)
if (m_gmres_maxiter > 0) M = m_gmres_maxiter;
// allocate temp storage
cg_tmp.resize((Np*(2 * M + 1) + (M*(M + 9)) / 2 + 1));
}
// GMRES buffer
int M = (Nu < 150 ? Nu : 150); // this is the default value of par[15] (i.e. par[14] in C)
if (m_gmres_maxiter > 0) M = m_gmres_maxiter;
// allocate temp storage
gmres_tmp.resize((Nu*(2 * M + 1) + (M*(M + 9)) / 2 + 1));
m_Asolver = new FGMRESSolver(GetFEModel());
// initialize solver for A block
LinearSolver* PC = nullptr;
switch (m_gmres_pc)
{
case 0: PC = nullptr; break;
case 1: PC = new ILU0_Preconditioner(GetFEModel()); break;
case 2: PC = new BoomerAMGSolver(GetFEModel()); break;
default:
return false;
}
m_Asolver->SetMaxIterations(m_gmres_maxiter);
m_Asolver->SetRelativeResidualTolerance(m_gmres_tol);
if (m_Asolver->SetSparseMatrix(A.Block(0, 0).pA) == false) return false;
if (m_Asolver->GetLeftPreconditioner())
{
m_Asolver->GetLeftPreconditioner()->SetSparseMatrix(A.Block(0, 0).pA);
}
if (m_Asolver->PreProcess() == false) return false;
// preconditioner of Schur solver
if ((m_precondition_schur > 0) && (m_PS == nullptr))
{
if (m_precondition_schur == 1)
{
// diagonal mass matrix
CompactSymmMatrix* M = new CompactSymmMatrix(1);
if (BuildDiagonalMassMatrix(GetFEModel(), m_A, M, 1.0) == false) return false;
DiagonalPreconditioner* PS = new DiagonalPreconditioner(GetFEModel());
if (PS->SetSparseMatrix(M) == false) return false;
if (PS->PreProcess() == false) return false;
if (PS->Factor() == false) return false;
m_PS = PS;
}
else
{
// mass matrix
CompactSymmMatrix* M = new CompactSymmMatrix(1);
if (BuildMassMatrix(GetFEModel(), m_A, M, 1.0) == false) return false;
// We do an incomplete cholesky factorization
IncompleteCholesky* PS = new IncompleteCholesky(GetFEModel());
if (PS->SetSparseMatrix(M) == false) return false;
if (PS->PreProcess() == false) return false;
if (PS->Factor() == false) return false;
m_PS = PS;
}
}
return true;
}
//! Pre-condition the matrix
bool BIPNSolver::Factor()
{
// make sure we have a matrix
if (m_A == 0) return false;
BlockMatrix& A = *m_A;
// get the number of equations
int N = A.Rows();
int Nu = m_part[0];
int Np = m_part[1];
// get the blocks
//
// | K | G |
// A = |---+---|
// | D | L |
//
BlockMatrix::BLOCK& K = m_A->Block(0, 0);
BlockMatrix::BLOCK& G = m_A->Block(0, 1);
BlockMatrix::BLOCK& D = m_A->Block(1, 0);
BlockMatrix::BLOCK& L = m_A->Block(1, 1);
// calculate preconditioner
Wm.assign(Nu, 1.0);
Wc.assign(Np, 1.0);
if (m_do_jacobi)
{
for (int i = 0; i < Nu; ++i)
{
double ki = fabs(K.pA->diag(i));
if (ki > 0.0)
Wm[i] = 1.0 / sqrt(ki);
}
if (L.pA)
{
for (int i = 0; i < Np; ++i)
{
double li = fabs(L.pA->diag(i));
if (li > 0.0)
Wc[i] = 1.0 / sqrt(li);
}
}
}
// normalize the matrix
K.pA->scale(Wm, Wm);
G.pA->scale(Wm, Wc);
D.pA->scale(Wc, Wm);
if (L.pA) L.pA->scale(Wc, Wc);
// Now calculate diagonal matrix of K
if (m_do_jacobi) Kd.assign(Nu, 1.0);
else
{
for (int i = 0; i < Nu; ++i)
{
double ki = K.pA->diag(i);
if (ki == 0.0) return false;
Kd[i] = 1.0 / ki;
}
}
if (m_Asolver->Factor() == false) return false;
return true;
}
//! Calculate the solution of RHS b and store solution in x
bool BIPNSolver::BackSolve(double* x, double* b)
{
// make sure we have a matrix
if (m_A == 0) return false;
BlockMatrix& A = *m_A;
BlockMatrix::BLOCK& K = m_A->Block(0, 0);
BlockMatrix::BLOCK& G = m_A->Block(0, 1);
BlockMatrix::BLOCK& D = m_A->Block(1, 0);
BlockMatrix::BLOCK& L = m_A->Block(1, 1);
// number of equations
int N = A.Rows();
int Nu = m_part[0];
int Np = m_part[1];
// normalize RHS
for (int i = 0; i<Nu; ++i) Rm0[i] = Wm[i]*b[i ];
for (int i = 0; i<Np; ++i) Rc0[i] = Wc[i]*b[i + Nu];
// initialize
RM = Rm0;
RC = Rc0;
// calculate initial error
double err_0 = Rm0*Rm0 + Rc0*Rc0, err_n = 0.0;
// setup the Schur complement
DiagonalPreconditioner DPC(nullptr);
if (DPC.Create(K.pA) == false) return false;
SchurComplementA S(&DPC, G.pA, D.pA, L.pA);
S.NegateSchur(true);
if (m_print_level != 0) feLog("--- Starting BIPN:\n");
int MI = m_maxiter;
int M = 2 * m_maxiter;
matrix QM(M, M);
QM.zero();
// do the BIPN iterations
int niter = 0;
for (int n=0; n<m_maxiter; ++n)
{
niter++;
if (m_print_level != 0) feLog("BIPN %d: ", niter);
// solve for yu_n (use GMRES): K*yu_n = RM[n]
m_Asolver->ResetStats();
m_Asolver->BackSolve(&yu_n[0], &(RM[0]));
m_gmres1_iters = m_Asolver->GetStats().iterations;
if (m_print_level != 0) feLog("%d, ", m_gmres1_iters);
// compute the corrected residual Rc_n = RC[n] - D*yu_n
D.vmult(yu_n, Rc_n);
vsub(Rc_n, RC, Rc_n);
// solve for yp_n (use CG): (L - D*G) * yp_n = Rc_n
if (m_use_cg)
m_cg_iters = cgsolve(&S, m_PS, yp_n, Rc_n);
else
m_cg_iters = gmressolve(&S, m_PS, yp_n, Rc_n);
if (m_print_level != 0) feLog("%d, ", m_cg_iters);
// compute corrected residual: Rm_n = RM[n] - G*yp_n
G.vmult(yp_n, Rm_n);
vsub(Rm_n, RM, Rm_n);
// solve for yu_n (use GMRES): K*yu_n = Rm_n
m_Asolver->ResetStats();
m_Asolver->BackSolve(&yu_n[0], &Rm_n[0]);
m_gmres2_iters = m_Asolver->GetStats().iterations;
if (m_print_level != 0) feLog("%d, ", m_gmres2_iters);
// calculate temp vectors
K.vmult(yu_n, Rmu[n]); // Rmu[n] = K*yu_n;
G.vmult(yp_n, Rmp[n]); // Rmp[n] = G*yp_n;
D.vmult(yu_n, Rcu[n]); // Rcu[n] = D*yu_n;
L.vmult(yp_n, Rcp[n]); // Rcp[n] = L*yp_n;
// store solution candidates
Yu[n] = yu_n;
Yp[n] = yp_n;
// update QM
for (int j = 0; j <= n; ++j)
{
QM(n , j ) = Rmu[n] * Rmu[j] + Rcu[n] * Rcu[j];
QM(n , j + MI) = Rmu[n] * Rmp[j] + Rcu[n] * Rcp[j];
QM(n + MI, j ) = Rmp[n] * Rmu[j] + Rcp[n] * Rcu[j];
QM(n + MI, j + MI) = Rmp[n] * Rmp[j] + Rcp[n] * Rcp[j];
QM(j , n ) = QM( n, j );
QM(j + MI, n ) = QM( n, j + MI);
QM(j , n + MI) = QM(n + MI, j );
QM(j + MI, n + MI) = QM(n + MI, j + MI);
}
// number of coefficients to determine
const int m = 2 * (n + 1);
// setup Q matrix
matrix Q(m, m);
vector<double> q(m);
// fill in the blocks of Q and q
for (int i = 0; i <= n; ++i)
{
for (int j = 0; j <= n; ++j)
{
Q(i , j ) = QM(i, j);
Q(i , j + n + 1) = QM(i, j+ MI);
Q(i + n + 1, j ) = QM(i+ MI, j);
Q(i + n + 1, j + n + 1) = QM(i+ MI, j+ MI);
}
q[i ] = Rm0*Rmu[i] + Rc0*Rcu[i];
q[i + n + 1] = Rm0*Rmp[i] + Rc0*Rcp[i];
}
// solve for the coefficients
vector<double> a(m);
Q.solve(a, q);
for (int i = 0; i <= n; ++i)
{
au[i] = a[i];
ap[i] = a[i + n + 1];
}
// calculate error
err_n = err_0 - a*q;
if (m_print_level != 0)
{
feLog("%lg (%lg)\n", sqrt(fabs(err_n)), m_tol*sqrt(err_0));
}
// check for convergence
if (sqrt(fabs(err_n)) < m_tol*sqrt(err_0)) break;
// Update R vectors
if (n < m_maxiter - 1)
{
// update R vectors
RM = Rm0;
RC = Rc0;
for (int i = 0; i <= n; ++i)
{
vsubs(RM, Rmu[i], au[i]);
vsubs(RM, Rmp[i], ap[i]);
vsubs(RC, Rcu[i], au[i]);
vsubs(RC, Rcp[i], ap[i]);
}
}
}
if (m_print_level != 0) feLog("---\n");
// calculate final solution vector
yu.assign(Nu, 0.0);
yp.assign(Np, 0.0);
for (int i = 0; i<niter; ++i)
{
vadds(yu, Yu[i], au[i]);
vadds(yp, Yp[i], ap[i]);
}
// de-normalize the solution
vscale(yu, Wm);
vscale(yp, Wc);
// put it all together
for (int i = 0; i<Nu; ++i) x[i ] = yu[i];
for (int i = 0; i<Np; ++i) x[i + Nu] = yp[i];
// and ... scene!
return true;
}
int BIPNSolver::cgsolve(SparseMatrix* K, LinearSolver* PC, std::vector<double>& x, std::vector<double>& b)
{
m_cg_iters = 0;
RCICGSolver cg(nullptr);
if (cg.SetSparseMatrix(K) == false) return -1;
if (PC) cg.SetLeftPreconditioner(PC);
cg.SetMaxIterations(m_cg_maxiter);
cg.SetTolerance(m_cg_tol);
// cg.SetPrintLevel(1);
if (cg.PreProcess() == false) return -1;
if (cg.Factor() == false) return -1;
cg.BackSolve(&x[0], &b[0]);
return cg.GetStats().iterations;
}
int BIPNSolver::gmressolve(SparseMatrix* K, LinearSolver* PC, vector<double>& x, vector<double>& b)
{
FGMRESSolver gmres(nullptr);
if (gmres.SetSparseMatrix(K) == false) return -1;
if (PC) gmres.SetLeftPreconditioner(PC);
gmres.SetMaxIterations(m_gmres_maxiter);
gmres.SetRelativeResidualTolerance(m_gmres_tol);
if (gmres.PreProcess() == false) return -1;
if (gmres.Factor() == false) return -1;
gmres.BackSolve(&x[0], &b[0]);
return gmres.GetStats().iterations;
}
#else // ifdef MKL_ISS
BEGIN_FECORE_CLASS(BIPNSolver, LinearSolver)
ADD_PARAMETER(m_maxiter, "maxiter");
ADD_PARAMETER(m_tol, "tol");
ADD_PARAMETER(m_print_level, "print_level");
ADD_PARAMETER(m_use_cg, "use_cg");
ADD_PARAMETER(m_cg_maxiter, "cg_maxiter");
ADD_PARAMETER(m_cg_tol, "cg_tol");
ADD_PARAMETER(m_cg_doResidualTest, "cg_check_residual");
ADD_PARAMETER(m_gmres_maxiter, "gmres_maxiter");
ADD_PARAMETER(m_gmres_tol, "gmres_tol");
ADD_PARAMETER(m_gmres_doResidualTest, "gmres_check_residual");
ADD_PARAMETER(m_gmres_pc, "gmres_precondition");
ADD_PARAMETER(m_do_jacobi, "do_jacobi");
ADD_PARAMETER(m_precondition_schur, "precondition_schur");
END_FECORE_CLASS();
BIPNSolver::BIPNSolver(FEModel* fem) : LinearSolver(fem), m_A(0) {}
bool BIPNSolver::PreProcess() { return false; }
bool BIPNSolver::Factor() { return false; }
bool BIPNSolver::BackSolve(double* x, double* b) { return false; }
SparseMatrix* BIPNSolver::CreateSparseMatrix(Matrix_Type ntype) { return 0; }
void BIPNSolver::SetPrintLevel(int n) {}
void BIPNSolver::SetMaxIterations(int n) {}
void BIPNSolver::SetTolerance(double eps) {}
void BIPNSolver::UseConjugateGradient(bool b) {}
void BIPNSolver::SetCGParameters(int maxiter, double tolerance, bool doResidualStoppingTest) {}
void BIPNSolver::SetGMRESParameters(int maxiter, double tolerance, bool doResidualStoppingTest, int precondition) {}
void BIPNSolver::DoJacobiPreconditioner(bool b) {}
void BIPNSolver::SetSchurPreconditioner(int n) {}
bool BIPNSolver::SetSparseMatrix(SparseMatrix* A) { return false; }
#endif
| C++ |
3D | febiosoftware/FEBio | NumCore/PardisoProjectSolver.h | .h | 2,410 | 80 | /*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/LinearSolver.h>
#include <FECore/CompactUnSymmMatrix.h>
#include <FECore/CompactSymmMatrix.h>
//! This Pardiso solver can be installed as a shared object library from
//! http://www.pardiso-project.org
class PardisoProjectSolver : public LinearSolver
{
public:
PardisoProjectSolver(FEModel* fem);
~PardisoProjectSolver();
bool PreProcess() override;
bool Factor() override;
bool BackSolve(double* x, double* y) override;
void Destroy() override;
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
bool SetSparseMatrix(SparseMatrix* pA) override;
void PrintConditionNumber(bool b);
double condition_number();
void UseIterativeFactorization(bool b);
protected:
CompactMatrix* m_pA;
int m_mtype; // matrix type
// Pardiso control parameters
int m_iparm[64];
int m_maxfct, m_mnum, m_msglvl;
double m_dparm[64];
bool m_iparm3; // use direct-iterative method
// Matrix data
int m_n, m_nnz, m_nrhs;
bool m_print_cn; // estimate and print the condition number
bool m_isFactored;
void* m_pt[64]; // Internal solver memory pointer
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/ILUT_Preconditioner.h | .h | 2,102 | 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/Preconditioner.h>
//-----------------------------------------------------------------------------
class ILUT_Preconditioner : public Preconditioner
{
public:
ILUT_Preconditioner(FEModel* fem);
// create a preconditioner for a sparse matrix
bool Factor() override;
// apply to vector P x = y
bool BackSolve(double* x, double* y) override;
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype) override;
public:
int m_maxfill;
double m_fillTol;
bool m_checkZeroDiagonal; // check for zero diagonals
double m_zeroThreshold; // threshold for zero diagonal check
double m_zeroReplace; // replacement value for zero diagonal
private:
CRSSparseMatrix* m_K;
vector<double> m_bilut;
vector<int> m_jbilut;
vector<int> m_ibilut;
vector<double> m_tmp;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | NumCore/BlockMatrix.cpp | .cpp | 7,900 | 283 | /*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 "BlockMatrix.h"
#include <assert.h>
//-----------------------------------------------------------------------------
BlockMatrix::BlockMatrix()
{
}
//-----------------------------------------------------------------------------
BlockMatrix::~BlockMatrix()
{
// clear memory allocations
Clear();
// delete blocks
const int n = (int) m_Block.size();
for (int i=0; i<n; ++i) delete m_Block[i].pA;
}
//-----------------------------------------------------------------------------
//! This function sets the partitions for the blocks.
//! The partition list contains the number of rows (and cols) for each partition.
//! So for instance, if part = {10,10}, a 2x2=4 partition is created, where
//! each block is a 10x10 matrix.
//
//! TODO: I want to put the partition information in the matrix profile structure
//! so that the Create function can be used to create all the blocks.
void BlockMatrix::Partition(const vector<int>& part, Matrix_Type mtype, int offset)
{
// copy the partitions, but store equation numbers instead of number of equations
const int n = (int)part.size();
m_part.resize(n+1);
m_part[0] = 0;
for (int i=0; i<n; ++i) m_part[i+1] = m_part[i] + part[i];
// create the block structure for all the partitions
m_Block.resize(n*n);
int nrow = 0;
for (int i=0; i<n; ++i) // loop over rows
{
int ncol = 0;
for (int j=0; j<n; ++j) // loop over cols
{
BLOCK& Bij = m_Block[i*n+j];
Bij.nstart_row = nrow;
Bij.nend_row = Bij.nstart_row + part[i] - 1;
Bij.nstart_col = ncol;
Bij.nend_col = Bij.nstart_col + part[j] - 1;
// Note the parameters in the constructors.
// This is because we are using Pardiso for this
if (i==j)
{
if (mtype == REAL_SYMMETRIC)
Bij.pA = new CompactSymmMatrix(offset);
else
Bij.pA = new CRSSparseMatrix(offset);
}
else
Bij.pA = new CRSSparseMatrix(offset);
ncol += part[j];
}
nrow += part[i];
}
}
//-----------------------------------------------------------------------------
//! Create a sparse matrix from a sparse-matrix profile
void BlockMatrix::Create(SparseMatrixProfile& MP)
{
m_nrow = MP.Rows();
m_ncol = MP.Columns();
m_nsize = 0;
const int N = (int) m_Block.size();
for (int i=0; i<N; ++i)
{
BLOCK& Bi = m_Block[i];
SparseMatrixProfile MPi = MP.GetBlockProfile(Bi.nstart_row, Bi.nstart_col, Bi.nend_row, Bi.nend_col);
Bi.pA->Create(MPi);
m_nsize += Bi.pA->NonZeroes();
}
}
//-----------------------------------------------------------------------------
//! assemble a matrix into the sparse matrix
void BlockMatrix::Assemble(const matrix& ke, const std::vector<int>& lm)
{
int I, J;
const int N = ke.rows();
for (int i=0; i<N; ++i)
{
if ((I = lm[i])>=0)
{
for (int j=0; j<N; ++j)
{
if ((J = lm[j]) >= 0) add(I,J, ke[i][j]);
}
}
}
}
//-----------------------------------------------------------------------------
//! assemble a matrix into the sparse matrix
void BlockMatrix::Assemble(const matrix& ke, const std::vector<int>& lmi, const std::vector<int>& lmj)
{
int I, J;
const int N = ke.rows();
const int M = ke.columns();
for (int i=0; i<N; ++i)
{
if ((I = lmi[i])>=0)
{
for (int j=0; j<M; ++j)
{
if ((J = lmj[j]) >= 0) add(I,J, ke[i][j]);
}
}
}
}
//-----------------------------------------------------------------------------
// helper function for finding partitions
int BlockMatrix::find_partition(int i)
{
const int N = (int)m_part.size() - 1;
int n = 0;
for (; n<N; ++n)
if (m_part[n+1] > i) break;
assert(n<N);
return n;
}
//-----------------------------------------------------------------------------
// helper function for finding a block
BlockMatrix::BLOCK& BlockMatrix::Block(int i, int j)
{
const int N = (int)m_part.size() - 1;
return m_Block[i*N+j];
}
//-----------------------------------------------------------------------------
//! set entry to value
bool BlockMatrix::check(int i, int j)
{
int nr = find_partition(i);
int nc = find_partition(j);
return Block(nr, nc).pA->check(i - m_part[nr], j - m_part[nc]);
}
//-----------------------------------------------------------------------------
//! set entry to value
void BlockMatrix::set(int i, int j, double v)
{
int nr = find_partition(i);
int nc = find_partition(j);
Block(nr, nc).pA->set(i - m_part[nr], j - m_part[nc], v);
}
//-----------------------------------------------------------------------------
//! add value to entry
void BlockMatrix::add(int i, int j, double v)
{
int nr = find_partition(i);
int nc = find_partition(j);
Block(nr, nc).pA->add(i - m_part[nr], j - m_part[nc], v);
}
//-----------------------------------------------------------------------------
//! retrieve value
double BlockMatrix::get(int i, int j)
{
int nr = find_partition(i);
int nc = find_partition(j);
return Block(nr, nc).pA->get(i - m_part[nr], j - m_part[nc]);
}
//-----------------------------------------------------------------------------
//! get the diagonal value
double BlockMatrix::diag(int i)
{
int n = find_partition(i);
return Block(n, n).pA->diag(i - m_part[n]);
}
//-----------------------------------------------------------------------------
//! release memory for storing data
void BlockMatrix::Clear()
{
// clear the blocks
const int n = (int) m_Block.size();
for (int i=0; i<n; ++i) m_Block[i].pA->Clear();
}
//-----------------------------------------------------------------------------
//! Zero all matrix elements
void BlockMatrix::Zero()
{
// zero the blocks
const int n = (int) m_Block.size();
for (int i=0; i<n; ++i) m_Block[i].pA->Zero();
}
//-----------------------------------------------------------------------------
//! multiply with vector
bool BlockMatrix::mult_vector(double* x, double* r)
{
int nr = Rows();
vector<double> tmp(nr, 0);
for (int i=0; i<nr; ++i) r[i] = 0.0;
int NP = Partitions();
for (int i=0; i<NP; ++i)
{
int n0 = m_part[i];
for (int j=0; j<NP; ++j)
{
int m0 = m_part[j];
BLOCK& bij = Block(i, j);
bij.pA->mult_vector(x + m0, &tmp[0] + n0);
int nj = bij.Rows();
for (int k=0; k<nj; ++k) r[n0 + k] += tmp[n0 + k];
}
}
return true;
}
//! row and column scale
void BlockMatrix::scale(const vector<double>& L, const vector<double>& R)
{
vector<double> Li, Rj;
for (int n = 0; n < m_Block.size(); ++n)
{
BLOCK& bn = m_Block[n];
if (bn.pA)
{
int NR = bn.Rows();
int NC = bn.Cols();
Li.resize(NR);
Rj.resize(NC);
for (int i = 0; i < NR; ++i) Li[i] = L[i + bn.nstart_row];
for (int i = 0; i < NC; ++i) Rj[i] = R[i + bn.nstart_col];
bn.pA->scale(Li, Rj);
}
}
}
| C++ |
3D | febiosoftware/FEBio | NumCore/FEASTEigenSolver.cpp | .cpp | 5,795 | 142 | /*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 "FEASTEigenSolver.h"
#include <FECore/CompactSymmMatrix.h>
BEGIN_FECORE_CLASS(FEASTEigenSolver, EigenSolver)
ADD_PARAMETER(m_m0, "m0");
ADD_PARAMETER(m_emin, "emin");
ADD_PARAMETER(m_emax, "emax");
END_FECORE_CLASS();
#ifdef MKL_ISS
#undef PARDISO
#include <mkl.h>
FEASTEigenSolver::FEASTEigenSolver(FEModel* fem) : EigenSolver(fem)
{
m_emin = 0.0;
m_emax = 0.0;
m_m0 = 0;
}
bool FEASTEigenSolver::Init()
{
// initialize the FEAST solver
feastinit(m_fpm);
// fpm[0] = Specifies whether Extended Eigensolver routines print runtime status. (0 = no -default-, 1 = yes)
// fpm[1] = Number of contour points Ne = 8. Must be one of {3,4,5,6,8,10,12,16,20,24,32,40,48}
// fpm[2] = Error trace double precision stopping criteria eps = 10^-fpm[2] (default = 12)
// fpm[3] = Maximum number of Extended Eigensolver refinement loops allowed.
// If no convergence is reached within fpm[3] refinement loops, Extended Eigensolver routines return info=2
// fpm[4] = User initial subspace. If fpm[4]=0 then Extended Eigensolver routines generate initial subspace,
// if fpm[4]=1 the user supplied initial subspace is used.
// fpm[5] = Extended Eigensolver stopping test.
// fpm[5]=0 (default): Extended Eigensolvers are stopped if this residual stopping test is satisfied.
// fpm[5]=1 : Extended Eigensolvers are stopped if this trace stopping test is satisfied.
// fpm[6] = Error trace single precision stopping criteria(10 - fpm[6]) .(default = 5)
// fpm[13] = fpm[13] = 0: Standard use for Extended Eigensolver routines. (default)
// fpm[13] = 1: Non-standard use for Extended Eigensolver routines : return the computed eigenvectors subspace after one single contour integration.
// fpm[26] = Specifies whether Extended Eigensolver routines check input matrices(applies to CSR format only). (0 = no -default-, 1 = yes)
// fpm[27] = Check if matrix B is positive definite.Set fpm[27] = 1 to check if B is positive definite. (default = 0)
// fpm[63] = Use the Intel MKL PARDISO solver with the user - defined PARDISO iparm array settings.
// fpm[63]=0 (default): Extended Eigensolver routines use the Intel MKL PARDISO default iparm settings defined by calling the pardisoinit subroutine.
// fpm[63]=1 : The values from fpm[64] to fpm[127] correspond to iparm[0] to iparm[63] respectively according to the formula fpm[64 + i] = iparm[i] for i = 0, 1, ..., 63
#ifndef NDEBUG
m_fpm[0] = 1; // turn on FEAST output
#endif
return true;
}
bool FEASTEigenSolver::EigenSolve(SparseMatrix* A, SparseMatrix* B, vector<double>& eigenValues, matrix& eigenVectors)
{
CompactSymmMatrix* cmA = dynamic_cast<CompactSymmMatrix*>(A);
if (cmA == nullptr) return false;
CompactSymmMatrix* cmB = nullptr;
if (B)
{
cmB = dynamic_cast<CompactSymmMatrix*>(B);
if (cmB == nullptr) return false;
// make sure the matrices have the same size
if (cmA->Rows() != cmB->Rows()) return false;
}
// parameters to dfeast_scsrgv
// Input parameters:
const char* uplo = "U"; // the matrix is stored as lower triangular.
MKL_INT n = cmA->Rows();
double* a = cmA->Values(); // nonzero values of matrix A
MKL_INT* ai = cmA->Pointers();
MKL_INT* aj = cmA->Indices();
// Output parameters
MKL_INT m = 0; // number of eigenvalues found in [emin, emax], 0 <= m <= m0.
double epsout = 0; // relative error on the trace
MKL_INT loops = 0; // number of refinement loops executed.
eigenValues.resize(m_m0, 0.0);
double* e = &eigenValues[0];
eigenVectors.resize(n, m_m0);
double* x = eigenVectors[0];
vector<double> res(m_m0); // the first m entries contain the relative residual error.
MKL_INT info = 0; // return value. If 0, all is well.
if (B)
{
double* b = cmB->Values(); // nonzero values of matrix B
MKL_INT* bi = cmB->Pointers();
MKL_INT* bj = cmB->Indices();
dfeast_scsrgv(uplo, &n, a, ai, aj, b, bi, bj, m_fpm, &epsout, &loops, &m_emin, &m_emax, &m_m0, e, x, &m, &res[0], &info);
}
else
{
dfeast_scsrev(uplo, &n, a, ai, aj, m_fpm, &epsout, &loops, &m_emin, &m_emax, &m_m0, e, x, &m, &res[0], &info);
}
if (m == 0)
{
eigenValues.clear();
}
else if (m != m_m0) eigenValues.resize(m);
return (info == 0);
}
#else
FEASTEigenSolver::FEASTEigenSolver(FEModel* fem) : EigenSolver(fem) {}
bool FEASTEigenSolver::Init() { return false; }
bool FEASTEigenSolver::EigenSolve(SparseMatrix* A, SparseMatrix* B, vector<double>& eigenValues, matrix& eigenVectors) { return false; }
#endif | C++ |
3D | febiosoftware/FEBio | FEBioPlot/PlotFile.cpp | .cpp | 3,850 | 116 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "PlotFile.h"
#include <FECore/FEPlotDataStore.h>
#include <FECore/FEModel.h>
#include <FECore/log.h>
//-----------------------------------------------------------------------------
PlotFile::PlotFile(FEModel* fem) : m_pfem(fem)
{
}
//-----------------------------------------------------------------------------
PlotFile::~PlotFile()
{
Close();
// clear all arrays
list<DICTIONARY_ITEM>::iterator it = m_dic.m_Glob.begin();
for (int i = 0; i < (int)m_dic.m_Glob.size(); ++i, ++it) delete it->m_psave;
it = m_dic.m_Mat.begin();
for (int i = 0; i < (int)m_dic.m_Mat.size(); ++i, ++it) delete it->m_psave;
it = m_dic.m_Node.begin();
for (int i = 0; i < (int)m_dic.m_Node.size(); ++i, ++it) delete it->m_psave;
it = m_dic.m_Elem.begin();
for (int i = 0; i < (int)m_dic.m_Elem.size(); ++i, ++it) delete it->m_psave;
it = m_dic.m_Face.begin();
for (int i = 0; i < (int)m_dic.m_Face.size(); ++i, ++it) delete it->m_psave;
}
//-----------------------------------------------------------------------------
void PlotFile::Close()
{
}
//-----------------------------------------------------------------------------
bool PlotFile::AddVariable(FEPlotData* ps, const char* szname)
{
vector<int> dummy;
switch (ps->RegionType())
{
case FE_REGION_NODE: return m_dic.AddNodalVariable(ps, szname, dummy);
case FE_REGION_DOMAIN: return m_dic.AddDomainVariable(ps, szname, dummy);
case FE_REGION_SURFACE: return m_dic.AddSurfaceVariable(ps, szname, dummy);
default:
assert(false);
return false;
}
}
//-----------------------------------------------------------------------------
bool PlotFile::AddVariable(const char* sz)
{
vector<int> dummy;
return AddVariable(sz, dummy);
}
//-----------------------------------------------------------------------------
bool PlotFile::AddVariable(const char* sz, vector<int>& item, const char* szdom)
{
return m_dic.AddVariable(GetFEModel(), sz, item, szdom);
}
//-----------------------------------------------------------------------------
// build the dictionary
void PlotFile::BuildDictionary()
{
FEPlotDataStore& pltData = GetFEModel()->GetPlotDataStore();
for (int n = 0; n < pltData.PlotVariables(); ++n)
{
FEPlotVariable& vi = pltData.GetPlotVariable(n);
const std::string& varName = vi.Name();
const std::string& domName = vi.DomainName();
// add the plot output variable
if (AddVariable(varName.c_str(), vi.m_item, domName.c_str()) == false)
{
feLog("FATAL ERROR: Output variable \"%s\" is not defined\n", varName.c_str());
throw "FATAL ERROR";
}
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioPlot/FEBioPlotFile.h | .h | 11,051 | 359 | /*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 "PlotFile.h"
#include "PltArchive.h"
#include "FECore/FESolidDomain.h"
#include "FECore/FEShellDomain.h"
#include "FECore/FEBeamDomain.h"
#include "FECore/FEDiscreteDomain.h"
#include "FECore/FEDomain2D.h"
#include <list>
#include "febioplot_api.h"
//-----------------------------------------------------------------------------
//! This class implements the facilities to export FE data in the FEBio
//! plot file format (version 3).
//!
class FEBIOPLOT_API FEBioPlotFile : public PlotFile
{
public:
// file version
// 3.2: added PLT_ELEMENTSET_SECTION
// 3.3: node IDs are now stored in Node Section
// 3.4: added PLT_ELEM_LINE3
// 3.5: added PLT_EDGE_DATA
enum { PLT_VERSION = 0x0035 };
// file tags
enum {
PLT_ROOT = 0x01000000,
PLT_HEADER = 0x01010000,
PLT_HDR_VERSION = 0x01010001,
// PLT_HDR_NODES = 0x01010002,
// PLT_HDR_MAX_FACET_NODES = 0x01010003, // removed (redefined in seach SURFACE section)
PLT_HDR_COMPRESSION = 0x01010004,
PLT_HDR_AUTHOR = 0x01010005, // new in 2.0
PLT_HDR_SOFTWARE = 0x01010006, // new in 2.0
PLT_HDR_UNITS = 0x01010007, // new in 4.0
PLT_DICTIONARY = 0x01020000,
PLT_DIC_ITEM = 0x01020001,
PLT_DIC_ITEM_TYPE = 0x01020002,
PLT_DIC_ITEM_FMT = 0x01020003,
PLT_DIC_ITEM_NAME = 0x01020004,
PLT_DIC_ITEM_ARRAYSIZE = 0x01020005, // added in version 0x05
PLT_DIC_ITEM_ARRAYNAME = 0x01020006, // added in version 0x05
PLT_DIC_ITEM_UNITS = 0x01020007, // added in version 4.0
PLT_DIC_GLOBAL = 0x01021000,
// PLT_DIC_MATERIAL = 0x01022000, // this was removed
PLT_DIC_NODAL = 0x01023000,
PLT_DIC_DOMAIN = 0x01024000,
PLT_DIC_SURFACE = 0x01025000,
PLT_DIC_EDGE = 0x01026000,
// PLT_MATERIALS = 0x01030000, // This was removed
// PLT_MATERIAL = 0x01030001,
// PLT_MAT_ID = 0x01030002,
// PLT_MAT_NAME = 0x01030003,
PLT_MESH = 0x01040000, // this was PLT_GEOMETRY
PLT_NODE_SECTION = 0x01041000,
PLT_NODE_HEADER = 0x01041100, // new in 2.0
PLT_NODE_SIZE = 0x01041101, // new in 2.0
PLT_NODE_DIM = 0x01041102, // new in 2.0
PLT_NODE_NAME = 0x01041103, // new in 2.0
PLT_NODE_COORDS = 0x01041200, // new in 2.0
PLT_DOMAIN_SECTION = 0x01042000,
PLT_DOMAIN = 0x01042100,
PLT_DOMAIN_HDR = 0x01042101,
PLT_DOM_ELEM_TYPE = 0x01042102,
PLT_DOM_PART_ID = 0x01042103, // this was PLT_DOM_MAT_ID
PLT_DOM_ELEMS = 0x01032104,
PLT_DOM_NAME = 0x01032105,
PLT_DOM_ELEM_LIST = 0x01042200,
PLT_ELEMENT = 0x01042201,
PLT_SURFACE_SECTION = 0x01043000,
PLT_SURFACE = 0x01043100,
PLT_SURFACE_HDR = 0x01043101,
PLT_SURFACE_ID = 0x01043102,
PLT_SURFACE_FACES = 0x01043103,
PLT_SURFACE_NAME = 0x01043104,
PLT_SURFACE_MAX_FACET_NODES = 0x01043105, // new in 2.0 (max number of nodes per facet)
PLT_FACE_LIST = 0x01043200,
PLT_FACE = 0x01043201,
PLT_NODESET_SECTION = 0x01044000,
PLT_NODESET = 0x01044100,
PLT_NODESET_HDR = 0x01044101,
PLT_NODESET_ID = 0x01044102,
PLT_NODESET_NAME = 0x01044103,
PLT_NODESET_SIZE = 0x01044104,
PLT_NODESET_LIST = 0x01044200,
PLT_PARTS_SECTION = 0x01045000, // new in 2.0
PLT_PART = 0x01045100,
PLT_PART_ID = 0x01045101,
PLT_PART_NAME = 0x01045102,
// element set section was added in 4.1
PLT_ELEMENTSET_SECTION = 0x01046000,
PLT_ELEMENTSET = 0x01046100,
PLT_ELEMENTSET_HDR = 0x01046101,
PLT_ELEMENTSET_ID = 0x01046102,
PLT_ELEMENTSET_NAME = 0x01046103,
PLT_ELEMENTSET_SIZE = 0x01046104,
PLT_ELEMENTSET_LIST = 0x01046200,
// facet set section was added in 4.1
PLT_FACETSET_SECTION = 0x01047000,
PLT_FACETSET = 0x01047100,
PLT_FACETSET_HDR = 0x01047101,
PLT_FACETSET_ID = 0x01047102,
PLT_FACETSET_NAME = 0x01047103,
PLT_FACETSET_SIZE = 0x01047104,
PLT_FACETSET_MAXNODES = 0x01047105,
PLT_FACETSET_LIST = 0x01047200,
PLT_FACET = 0x01047201,
PLT_EDGE_SECTION = 0x01048000,
PLT_EDGE = 0x01048100,
PLT_EDGE_HDR = 0x01048101,
PLT_EDGE_ID = 0x01048102,
PLT_EDGE_LINES = 0x01048103,
PLT_EDGE_NAME = 0x01048104,
PLT_EDGE_MAX_NODES = 0x01048105,
PLT_EDGE_LIST = 0x01048200,
PLT_LINE = 0x01048201,
// plot objects were added in 3.0
PLT_OBJECTS_SECTION = 0x01050000,
PLT_OBJECT_ID = 0x01050001,
PLT_OBJECT_NAME = 0x01050002,
PLT_OBJECT_TAG = 0x01050003,
PLT_OBJECT_POS = 0x01050004,
PLT_OBJECT_ROT = 0x01050005,
PLT_OBJECT_DATA = 0x01050006,
PLT_POINT_OBJECT = 0x01051000,
PLT_POINT_COORD = 0x01051001,
PLT_LINE_OBJECT = 0x01052000,
PLT_LINE_COORDS = 0x01052001,
PLT_STATE = 0x02000000,
PLT_STATE_HEADER = 0x02010000,
PLT_STATE_HDR_ID = 0x02010001,
PLT_STATE_HDR_TIME = 0x02010002,
PLT_STATE_STATUS = 0x02010003, // new in 3.1
PLT_STATE_DATA = 0x02020000,
PLT_STATE_VARIABLE = 0x02020001,
PLT_STATE_VAR_ID = 0x02020002,
PLT_STATE_VAR_DATA = 0x02020003,
PLT_GLOBAL_DATA = 0x02020100,
// PLT_MATERIAL_DATA = 0x02020200, // this was removed
PLT_NODE_DATA = 0x02020300,
PLT_ELEMENT_DATA = 0x02020400,
PLT_FACE_DATA = 0x02020500,
PLT_EDGE_DATA = 0x02020600,
PLT_MESH_STATE = 0x02030000,
PLT_ELEMENT_STATE = 0x02030001,
PLT_OBJECTS_STATE = 0x02040000
};
// --- element types ---
enum Elem_Type {
PLT_ELEM_HEX,
PLT_ELEM_PENTA,
PLT_ELEM_TET4,
PLT_ELEM_QUAD,
PLT_ELEM_TRI,
PLT_ELEM_LINE2,
PLT_ELEM_HEX20,
PLT_ELEM_TET10,
PLT_ELEM_TET15,
PLT_ELEM_HEX27,
PLT_ELEM_TRI6,
PLT_ELEM_QUAD8,
PLT_ELEM_QUAD9,
PLT_ELEM_PENTA15,
PLT_ELEM_TET20,
PLT_ELEM_TRI10,
PLT_ELEM_PYRA5,
PLT_ELEM_TET5,
PLT_ELEM_PYRA13,
PLT_ELEM_LINE3 // added in 3.4
};
struct Surface
{
int maxNodes;
FEFacetSet* surf;
};
class FEBIOPLOT_API PlotObject
{
public:
PlotObject() {}
virtual ~PlotObject() {}
void AddData(const char* szname, Var_Type type, FEPlotData* psave = nullptr);
public:
int m_id; // object ID
int m_tag; // user tag
vec3d m_pos; // object's position
quatd m_rot; // object's orientation
std::string m_name; // object's name
list<DICTIONARY_ITEM> m_data;
};
class PointObject : public PlotObject
{
public:
PointObject() {}
public:
vec3d m_r; // point position
};
class LineObject : public PlotObject
{
public:
LineObject() {}
public:
vec3d m_r1; // point 1
vec3d m_r2; // point 2
};
public:
FEBioPlotFile(FEModel* fem);
//! Open the plot database
bool Open(const char* szfile) override;
//! Close the plot database
void Close() override;
//! Open for appending
bool Append(const char* szfile) override;
//! Write current FE state to plot database
bool Write(float ftime, int flag = 0) override;
//! see if the plot file is valid
bool IsValid() const override;
public:
//! Set the compression level
void SetCompression(int n);
// Write a mesh section
bool WriteMeshSection(FEModel& fem);
//! set the software variable
void SetSoftwareString(const std::string& softwareString);
public:
int PointObjects();
PointObject* GetPointObject(int i);
PointObject* AddPointObject(const std::string& name);
int LineObjects();
LineObject* GetLineObject(int i);
LineObject* AddLineObject(const std::string& name);
protected:
bool WriteRoot (FEModel& fem);
bool WriteHeader (FEModel& fem);
bool WriteDictionary(FEModel& fem);
void WriteDicList(list<DICTIONARY_ITEM>& dic);
void WriteDictionaryItem(DICTIONARY_ITEM& it);
void WriteNodeSection (FEMesh& m);
void WriteDomainSection (FEMesh& m);
void WriteSurfaceSection(FEMesh& m);
void WriteEdgeSection(FEMesh& m);
void WriteNodeSetSection(FEMesh& m);
void WriteElementSetSection(FEMesh& m);
void WriteFacetSetSection(FEMesh& m);
void WritePartsSection (FEModel& fem);
void WriteObjectsSection();
void WriteObject(PlotObject* po);
void WriteSolidDomain (FESolidDomain& dom);
void WriteShellDomain (FEShellDomain& dom);
void WriteBeamDomain (FEBeamDomain& dom);
void WriteDiscreteDomain(FEDiscreteDomain& dom);
void WriteDomain2D (FEDomain2D& dom);
void WriteGlobalData (FEModel& fem);
void WriteNodeData (FEModel& fem);
void WriteDomainData (FEModel& fem);
void WriteSurfaceData (FEModel& fem);
void WriteEdgeData (FEModel& fem);
void WriteObjectsState();
void WriteObjectData(PlotObject* po);
void WriteGlobalDataField(FEModel& fem, FEPlotData* pd);
void WriteNodeDataField(FEModel& fem, FEPlotData* pd);
void WriteDomainDataField(FEModel& fem, FEPlotData* pd);
void WriteSurfaceDataField(FEModel& fem, FEPlotData* pd);
void WriteEdgeDataField(FEModel& fem, FEPlotData* pd);
void WriteMeshState(FEMesh& mesh);
protected:
bool ReadDictionary();
bool ReadDicList();
void BuildSurfaceTable();
void Clear();
protected:
PltArchive m_ar; // the data archive
int m_ncompress; // compression level
int m_meshesWritten; // nr of meshes written
string m_softwareString; // the software string
bool m_exportUnitsFlag; // flag that indicates whether to write units
bool m_exportErodedElements; // export the eroded elements or not
std::vector<Surface> m_Surf;
std::vector<PointObject*> m_Points;
std::vector<LineObject*> m_Lines;
};
//-----------------------------------------------------------------------------
class FEPlotObjectData : public FEPlotData
{
FECORE_BASE_CLASS(FEPlotObjectData)
public:
FEPlotObjectData(FEModel* fem) : FEPlotData(fem) {}
virtual bool Save(FEBioPlotFile::PlotObject* po, FEDataStream& ar) = 0;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioPlot/targetver.h | .h | 1,583 | 37 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
// Including SDKDDKVer.h defines the highest available Windows platform.
// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
#include <SDKDDKVer.h>
| Unknown |
3D | febiosoftware/FEBio | FEBioPlot/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 | FEBioPlot/VTKPlotFile.h | .h | 2,613 | 72 | /*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 "PlotFile.h"
#include <stdio.h>
#include "febioplot_api.h"
//! This class stores the FEBio results to a family of VTK files.
class FEBIOPLOT_API VTKPlotFile : public PlotFile
{
public:
VTKPlotFile(FEModel* fem);
//! Open the plot database
bool Open(const char* szfile) override;
//! Open for appending
bool Append(const char* szfile) override;
//! Write current FE state to plot database
bool Write(float ftime, int flag = 0) override;
//! see if the plot file is valid
bool IsValid() const override;
void Serialize(DumpStream& ar) override;
private:
void WriteHeader();
void WritePoints();
void WriteCells();
void WritePointData();
void WriteCellData();
void WriteScalarData(std::vector<float>& val, const std::string& szname);
void WriteVectorData(std::vector<float>& val, const std::string& szname);
void WriteMat3FData (std::vector<float>& val, const std::string& szname);
void WriteMat3FSData(std::vector<float>& val, const std::string& szname);
void WriteMat3FDData(std::vector<float>& val, const std::string& szname);
void WriteArrayData (std::vector<float>& val, const std::string& name, FEPlotData* pd);
void WriteArrayVec3fData(std::vector<float>& val, const std::string& name, FEPlotData* pd);
private:
FILE* m_fp;
int m_count;
bool m_valid;
std::string m_filename;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioPlot/febioplot_api.h | .h | 1,536 | 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 febioplot_EXPORTS
#define FEBIOPLOT_API __declspec(dllexport)
#else
#define FEBIOPLOT_API __declspec(dllimport)
#endif
#else
#define FEBIOPLOT_API
#endif
#else
#define FEBIOPLOT_API
#endif
| Unknown |
3D | febiosoftware/FEBio | FEBioPlot/PltArchive.cpp | .cpp | 8,142 | 412 | /*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 "PltArchive.h"
#include <assert.h>
#ifdef HAVE_ZLIB
#include "zlib.h"
static z_stream strm;
#endif
//=============================================================================
// FileStream
//=============================================================================
FileStream::FileStream(FILE* fp, bool owner)
{
m_bufsize = 262144; // = 256K
m_current = 0;
m_buf = new unsigned char[m_bufsize];
m_pout = new unsigned char[m_bufsize];
m_ncompress = 0;
m_fp = fp;
m_fileOwner = owner;
}
FileStream::~FileStream()
{
Close();
delete [] m_buf;
delete [] m_pout;
m_buf = 0;
m_pout = 0;
}
bool FileStream::Open(const char* szfile)
{
m_fp = fopen(szfile, "rb");
if (m_fp == 0) return false;
return true;
}
bool FileStream::Append(const char* szfile)
{
m_fp = fopen(szfile, "a+b");
return (m_fp != 0);
}
bool FileStream::Create(const char* szfile)
{
m_fp = fopen(szfile, "wb");
return (m_fp != 0);
}
void FileStream::Close()
{
if (m_fp)
{
Flush();
if (m_fileOwner) fclose(m_fp);
}
m_fp = 0;
}
void FileStream::BeginStreaming()
{
#ifdef HAVE_ZLIB
if (m_ncompress)
{
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
deflateInit(&strm, -1);
}
#endif
}
void FileStream::EndStreaming()
{
Flush();
#ifdef HAVE_ZLIB
if (m_ncompress)
{
strm.avail_in = 0;
strm.next_in = 0;
/* run deflate() on input until output buffer not full, finish
compression if all of source has been read in */
do {
strm.avail_out = m_bufsize;
strm.next_out = m_pout;
int ret = deflate(&strm, Z_FINISH); /* no bad return value */
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
int have = m_bufsize - strm.avail_out;
fwrite(m_pout, 1, have, m_fp);
} while (strm.avail_out == 0);
assert(strm.avail_in == 0); /* all input will be used */
// all done
deflateEnd(&strm);
fflush(m_fp);
}
#endif
}
void FileStream::Write(void* pd, size_t Size, size_t Count)
{
unsigned char* pdata = (unsigned char*) pd;
size_t nsize = Size*Count;
while (nsize > 0)
{
if (m_current + nsize < m_bufsize)
{
memcpy(m_buf + m_current, pdata, nsize);
m_current += nsize;
nsize = 0;
}
else
{
int nblock = m_bufsize - m_current;
if (nblock>0) { memcpy(m_buf + m_current, pdata, nblock); m_current += nblock; }
Flush();
pdata += nblock;
nsize -= nblock;
}
}
}
void FileStream::Flush()
{
#ifdef HAVE_ZLIB
if (m_ncompress)
{
strm.avail_in = m_current;
strm.next_in = m_buf;
/* run deflate() on input until output buffer not full, finish
compression if all of source has been read in */
do {
strm.avail_out = m_bufsize;
strm.next_out = m_pout;
int ret = deflate(&strm, Z_NO_FLUSH); /* no bad return value */
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
int have = m_bufsize - strm.avail_out;
fwrite(m_pout, 1, have, m_fp);
} while (strm.avail_out == 0);
assert(strm.avail_in == 0); /* all input will be used */
}
else
{
if (m_fp) fwrite(m_buf, m_current, 1, m_fp);
}
#else
if (m_fp) fwrite(m_buf, m_current, 1, m_fp);
#endif
// flush the file
if (m_fp) fflush(m_fp);
// reset current data pointer
m_current = 0;
}
size_t FileStream::read(void* pd, size_t Size, size_t Count)
{
return fread(pd, Size, Count, m_fp);
}
long FileStream::tell()
{
return ftell(m_fp);
}
void FileStream::seek(long noff, int norigin)
{
fseek(m_fp, noff, norigin);
}
//=============================================================================
// PltArchive
//=============================================================================
PltArchive::PltArchive()
{
m_fp = 0;
m_pRoot = 0;
m_pChunk = 0;
m_bSaving = true;
}
PltArchive::~PltArchive()
{
Close();
}
void PltArchive::Close()
{
if (m_bSaving)
{
if (m_pRoot) Flush();
}
else
{
while (m_Chunk.empty() == false) CloseChunk();
m_bend = true;
}
// close the file
if (m_fp)
{
m_fp->Close();
delete m_fp;
m_fp = 0;
}
}
void PltArchive::SetCompression(int n)
{
if (m_fp) m_fp->SetCompression(n);
}
void PltArchive::Flush()
{
if (m_fp && m_pRoot)
{
m_fp->BeginStreaming();
m_pRoot->Write(m_fp);
m_fp->EndStreaming();
}
delete m_pRoot;
m_pRoot = 0;
m_pChunk = 0;
}
bool PltArchive::Create(const char* szfile)
{
// attempt to create the file
assert(m_fp == 0);
m_fp = new FileStream();
if (m_fp->Create(szfile) == false) return false;
// write the root tag
unsigned int ntag = 0x00464542;
m_fp->Write(&ntag, sizeof(int), 1);
m_bSaving = true;
return true;
}
void PltArchive::BeginChunk(unsigned int id)
{
if (m_pRoot == 0)
{
m_pRoot = new OBranch(id);
m_pChunk = m_pRoot;
}
else
{
// create a new branch
OBranch* pbranch = new OBranch(id);
// attach it to the current branch
m_pChunk->AddChild(pbranch);
// move the current branch pointer
m_pChunk = pbranch;
}
}
void PltArchive::EndChunk()
{
if (m_pChunk != m_pRoot)
m_pChunk = m_pChunk->GetParent();
else
{
Flush();
}
}
//-----------------------------------------------------------------------------
bool PltArchive::Open(const char* szfile)
{
// try to open the file
assert(m_fp == 0);
m_fp = new FileStream();
if (m_fp->Open(szfile) == false) return false;
// read the root tag
unsigned int ntag;
m_fp->read(&ntag, sizeof(int), 1);
if (ntag != 0x00464542) { Close(); return false; }
m_bSaving = false;
m_bend = false;
return true;
}
bool PltArchive::Append(const char* szfile)
{
// reopen the plot file for appending
assert(m_fp == 0);
m_fp = new FileStream();
if (m_fp->Append(szfile) == false) return false;
m_bSaving = true;
return true;
}
int PltArchive::OpenChunk()
{
// see if the end flag was set
// in that case we first need to clear the flag
if (m_bend)
{
m_bend = false;
return IO_END;
}
// create a new chunk
CHUNK* pc = new CHUNK;
// read the chunk ID
read(pc->id);
// read the chunk size
read(pc->nsize);
if (pc->nsize == 0) m_bend = true;
// record the position
pc->lpos = m_fp->tell();
// add it to the stack
m_Chunk.push(pc);
return IO_OK;
}
void PltArchive::CloseChunk()
{
// pop the last chunk
CHUNK* pc = m_Chunk.top(); m_Chunk.pop();
// get the current file position
long lpos = m_fp->tell();
// calculate the offset to the end of the chunk
int noff = pc->nsize - (lpos - pc->lpos);
// skip any remaining part in the chunk
// I wonder if this can really happen
if (noff != 0)
{
m_fp->seek(noff, SEEK_CUR);
lpos = m_fp->tell();
}
// delete this chunk
delete pc;
// take a peek at the parent
if (m_Chunk.empty())
{
// we just deleted the root chunk
m_bend = true;
}
else
{
pc = m_Chunk.top();
int noff = pc->nsize - (lpos - pc->lpos);
if (noff == 0) m_bend = true;
}
}
unsigned int PltArchive::GetChunkID()
{
CHUNK* pc = m_Chunk.top();
assert(pc);
return pc->id;
}
| C++ |
3D | febiosoftware/FEBio | FEBioPlot/PlotFile.h | .h | 4,822 | 147 | /*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/FEMesh.h"
#include "FECore/FEPlotData.h"
#include "febioplot_api.h"
//-----------------------------------------------------------------------------
class FEModel;
//-----------------------------------------------------------------------------
//! This class implements the facilities to write to a plot database.
//!
class FEBIOPLOT_API PlotFile
{
public:
// size of name variables
enum { STR_SIZE = 64 };
// Dictionary entry
class DICTIONARY_ITEM
{
public:
DICTIONARY_ITEM();
DICTIONARY_ITEM(const DICTIONARY_ITEM& item);
public:
FEPlotData* m_psave;
unsigned int m_ntype; // data type
unsigned int m_nfmt; // storage format
unsigned int m_arraySize; // size of arrays (only used by arrays)
std::vector<string> m_arrayNames; // names of array components (optional)
char m_szname[STR_SIZE];
char m_szunit[STR_SIZE];
};
class Dictionary
{
public:
bool AddVariable(FEModel* pfem, const char* szname, std::vector<int>& item, const char* szdom = "");
int GlobalVariables() { return (int)m_Glob.size(); }
int NodalVariables() { return (int)m_Node.size(); }
int DomainVariables() { return (int)m_Elem.size(); }
int SurfaceVariables() { return (int)m_Face.size(); }
int EdgeVariables() { return (int)m_Edge.size(); }
void Defaults(FEModel& fem);
void Clear();
public:
list<DICTIONARY_ITEM>& GlobalVariableList() { return m_Glob; }
list<DICTIONARY_ITEM>& MaterialVariableList() { return m_Mat; }
list<DICTIONARY_ITEM>& NodalVariableList() { return m_Node; }
list<DICTIONARY_ITEM>& DomainVariableList() { return m_Elem; }
list<DICTIONARY_ITEM>& SurfaceVariableList() { return m_Face; }
list<DICTIONARY_ITEM>& EdgeVariableList() { return m_Edge; }
protected:
bool AddGlobalVariable(FEPlotData* ps, const char* szname);
bool AddMaterialVariable(FEPlotData* ps, const char* szname);
bool AddNodalVariable(FEPlotData* ps, const char* szname, std::vector<int>& item);
bool AddDomainVariable(FEPlotData* ps, const char* szname, std::vector<int>& item);
bool AddSurfaceVariable(FEPlotData* ps, const char* szname, std::vector<int>& item);
bool AddEdgeVariable(FEPlotData* ps, const char* szname, std::vector<int>& item);
protected:
list<DICTIONARY_ITEM> m_Glob; // Global variables
list<DICTIONARY_ITEM> m_Mat; // Material variables
list<DICTIONARY_ITEM> m_Node; // Node variables
list<DICTIONARY_ITEM> m_Elem; // Domain variables
list<DICTIONARY_ITEM> m_Face; // Surface variables
list<DICTIONARY_ITEM> m_Edge; // Edge variables
friend class PlotFile;
};
public:
//! constructor
PlotFile(FEModel* fem);
//! descructor
virtual ~PlotFile();
//! close the plot database
virtual void Close();
//! Open the plot database
virtual bool Open(const char* szfile) = 0;
//! Open for appending
virtual bool Append(const char* szfile) = 0;
//! Write current FE state to plot database
virtual bool Write(float ftime, int flag = 0) = 0;
//! see if the plot file is valid
virtual bool IsValid() const = 0;
virtual void Serialize(DumpStream& ar) {}
public:
Dictionary& GetDictionary() { return m_dic; }
bool AddVariable(FEPlotData* ps, const char* szname);
protected:
FEModel* GetFEModel() { return m_pfem; }
// build the dictionary
void BuildDictionary();
//! Add a variable to the dictionary
bool AddVariable(const char* sz);
bool AddVariable(const char* sz, std::vector<int>& item, const char* szdom = "");
private:
Dictionary m_dic; //!< dictionary
FEModel* m_pfem; //!< pointer to FE model
};
| Unknown |
3D | febiosoftware/FEBio | FEBioPlot/VTKPlotFile.cpp | .cpp | 15,824 | 553 | /*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 "VTKPlotFile.h"
#include <FECore/FEModel.h>
#include <FECore/FEPlotDataStore.h>
#include <FECore/FEDomain.h>
#include <sstream>
enum VTK_CELLTYPE {
VTK_VERTEX = 1,
VTK_POLY_VERTEX = 2,
VTK_LINE = 3,
VTK_POLY_LINE = 4,
VTK_TRIANGLE = 5,
VTK_TRIANGLE_STRIP = 6,
VTK_POLYGON = 7,
VTK_PIXEL = 8,
VTK_QUAD = 9,
VTK_TETRA = 10,
VTK_VOXEL = 11,
VTK_HEXAHEDRON = 12,
VTK_WEDGE = 13,
VTK_PYRAMID = 14,
VTK_QUADRATIC_EDGE = 21,
VTK_QUADRATIC_TRIANGLE = 22,
VTK_QUADRATIC_QUAD = 23,
VTK_QUADRATIC_TETRA = 24,
VTK_QUADRATIC_HEXAHEDRON = 25,
VTK_QUADRATIC_WEDGE = 26,
VTK_QUADRATIC_PYRAMID = 27
};
VTKPlotFile::VTKPlotFile(FEModel* fem) : PlotFile(fem)
{
m_fp = nullptr;
m_count = 0;
m_valid = false;
}
//! Open the plot database
bool VTKPlotFile::Open(const char* szfile)
{
m_filename = szfile;
size_t n = m_filename.rfind('.');
if (n != std::string::npos) m_filename.erase(n, std::string::npos);
BuildDictionary();
m_valid = true;
return true;
}
//! Open for appending
bool VTKPlotFile::Append(const char* szfile)
{
m_filename = szfile;
size_t n = m_filename.rfind('.');
if (n != std::string::npos) m_filename.erase(n, std::string::npos);
BuildDictionary();
m_valid = true;
return true;
}
//! see if the plot file is valid
bool VTKPlotFile::IsValid() const
{
return m_valid;
}
void VTKPlotFile::Serialize(DumpStream& ar)
{
if (ar.IsShallow()) return;
ar& m_count;
}
//! Write current FE state to plot database
bool VTKPlotFile::Write(float ftime, int flag)
{
FEModel& fem = *GetFEModel();
std::stringstream ss;
ss << m_filename << "." << m_count++ << ".vtk";
string fileName = ss.str();
m_fp = fopen(fileName.c_str(), "wt");
if (m_fp == nullptr) return false;
WriteHeader();
WritePoints();
WriteCells();
WritePointData();
WriteCellData();
fclose(m_fp);
m_fp = nullptr;
return true;
}
//-----------------------------------------------------------------------------
void VTKPlotFile::WriteHeader()
{
FEModel& fem = *GetFEModel();
fprintf(m_fp, "%s\n", "# vtk DataFile Version 3.0");
fprintf(m_fp, "%s %g\n", "time", fem.GetCurrentTime());
fprintf(m_fp, "%s\n", "ASCII");
fprintf(m_fp, "%s\n", "DATASET UNSTRUCTURED_GRID");
}
//-----------------------------------------------------------------------------
void VTKPlotFile::WritePoints()
{
FEModel& fem = *GetFEModel();
FEMesh& m = fem.GetMesh();
int nodes = m.Nodes();
fprintf(m_fp, "POINTS %d float\n", nodes);
for (int j = 0; j < nodes; j += 3)
{
for (int k = 0; k < 3 && j + k < nodes; k++)
{
FENode& nd = m.Node(j + k);
vec3d& r = nd.m_r0;
fprintf(m_fp, "%lg %lg %lg ", r.x, r.y, r.z);
}
fprintf(m_fp, "\n");
}
fprintf(m_fp, "%s\n", "");
}
//-----------------------------------------------------------------------------
void VTKPlotFile::WriteCells()
{
FEModel& fem = *GetFEModel();
FEMesh& m = fem.GetMesh();
int NE = m.Elements();
int nsize = 0;
for (int j = 0; j<NE; ++j)
nsize += m.Element(j)->Nodes() + 1;
// Write CELLS
fprintf(m_fp, "CELLS %d %d\n", NE, nsize);
for (int j=0; j<NE; ++j)
{
FEElement& el = *m.Element(j);
fprintf(m_fp, "%d ", el.Nodes());
for (int k=0; k<el.Nodes(); ++k) fprintf(m_fp, "%d ", el.m_node[k]);
fprintf(m_fp, "\n");
}
// Write CELL_TYPES
fprintf(m_fp, "\nCELL_TYPES %d\n", NE);
for (int j = 0; j<m.Elements(); ++j)
{
FEElement& el = *m.Element(j);
int vtk_type;
switch (el.Shape()) {
case ET_HEX8 : vtk_type = VTK_HEXAHEDRON; break;
case ET_TET4 : vtk_type = VTK_TETRA; break;
case ET_PENTA6 : vtk_type = VTK_WEDGE; break;
case ET_PYRA5 : vtk_type = VTK_PYRAMID; break;
case ET_QUAD4 : vtk_type = VTK_QUAD; break;
case ET_TRI3 : vtk_type = VTK_TRIANGLE; break;
case ET_TRUSS2 : vtk_type = VTK_LINE; break;
case ET_HEX20 : vtk_type = VTK_QUADRATIC_HEXAHEDRON; break;
case ET_QUAD8 : vtk_type = VTK_QUADRATIC_QUAD; break;
// case ET_BEAM3 : vtk_type = VTK_QUADRATIC_EDGE; break;
case ET_TET10 : vtk_type = VTK_QUADRATIC_TETRA; break;
case ET_TET15 : vtk_type = VTK_QUADRATIC_TETRA; break;
case ET_PENTA15: vtk_type = VTK_QUADRATIC_WEDGE; break;
case ET_HEX27 : vtk_type = VTK_QUADRATIC_HEXAHEDRON; break;
case ET_PYRA13 : vtk_type = VTK_QUADRATIC_PYRAMID; break;
case ET_TRI6 : vtk_type = VTK_QUADRATIC_TRIANGLE; break;
case ET_QUAD9 : vtk_type = VTK_QUADRATIC_QUAD; break;
default: vtk_type = -1; break;
}
fprintf(m_fp, "%d\n", vtk_type);
}
}
void VTKPlotFile::WriteScalarData(std::vector<float>& val, const std::string& name)
{
fprintf(m_fp, "%s %s %s\n", "SCALARS", name.c_str(), "float");
fprintf(m_fp, "%s %s\n", "LOOKUP_TABLE", "default");
for (int i = 0; i < val.size(); ++i) fprintf(m_fp, "%g\n", val[i]);
}
void VTKPlotFile::WriteVectorData(std::vector<float>& val, const std::string& name)
{
fprintf(m_fp, "%s %s %s\n", "VECTORS", name.c_str(), "float");
for (int i = 0; i < val.size(); i += 3) fprintf(m_fp, "%g %g %g\n", val[i], val[i + 1], val[i + 2]);
}
void VTKPlotFile::WriteMat3FData(std::vector<float>& val, const std::string& name)
{
fprintf(m_fp, "%s %s %s\n", "TENSORS", name.c_str(), "float");
for (int i = 0; i < val.size(); i += 9)
fprintf(m_fp, "%g %g %g\n%g %g %g\n%g %g %g\n\n",
val[i ], val[i + 1], val[i + 2],
val[i + 3], val[i + 4], val[i + 5],
val[i + 6], val[i + 7], val[i + 8]);
}
void VTKPlotFile::WriteMat3FSData(std::vector<float>& val, const std::string& name)
{
fprintf(m_fp, "%s %s %s\n", "TENSORS", name.c_str(), "float");
for (int i = 0; i < val.size(); i += 6)
fprintf(m_fp, "%g %g %g\n%g %g %g\n%g %g %g\n\n",
val[i ], val[i + 3], val[i + 5],
val[i + 3], val[i + 1], val[i + 4],
val[i + 5], val[i + 4], val[i + 2]);
}
void VTKPlotFile::WriteMat3FDData(std::vector<float>& val, const std::string& name)
{
fprintf(m_fp, "%s %s %s\n", "TENSORS", name.c_str(), "float");
for (int i = 0; i < val.size(); i += 3)
fprintf(m_fp, "%g %g %g\n%g %g %g\n%g %g %g\n\n",
val[i], 0.f, 0.f,
0.f, val[i + 1], 0.f,
0.f, 0.f, val[i + 2]);
}
static void Space2_(string& s)
{
int n = (int)s.size();
for (int i = 0; i < n; ++i)
if (s[i] == ' ') s[i] = '_';
}
void VTKPlotFile::WriteArrayData(std::vector<float>& val, const std::string& name, FEPlotData* pd)
{
int arraySize = pd->GetArraysize();
fprintf(m_fp, "FIELD %s %d\n", name.c_str(), arraySize);
std::vector<string> arrayNames = pd->GetArrayNames();
int NE = val.size() / arraySize;
for (int j = 0; j < arraySize; ++j)
{
string name = arrayNames[j];
Space2_(name);
fprintf(m_fp, "%s %d %d float\n", name.c_str(), 1, NE);
for (int i = 0; i < NE; ++i)
{
float f = val[arraySize*i + j];
fprintf(m_fp, "%g\n", f);
}
}
}
void VTKPlotFile::WriteArrayVec3fData(std::vector<float>& val, const std::string& name, FEPlotData* pd)
{
int arraySize = pd->GetArraysize();
fprintf(m_fp, "FIELD %s %d\n", name.c_str(), arraySize);
std::vector<string> arrayNames = pd->GetArrayNames();
int NE = val.size() / (3*arraySize);
for (int j = 0; j < arraySize; ++j)
{
string name = arrayNames[j];
Space2_(name);
fprintf(m_fp, "%s %d %d float\n", name.c_str(), 3, NE);
float f[3];
for (int i = 0; i < NE; ++i)
{
f[0] = val[3*arraySize * i + 3*j ];
f[1] = val[3*arraySize * i + 3*j + 1];
f[2] = val[3*arraySize * i + 3*j + 2];
fprintf(m_fp, "%g %g %g\n", f[0], f[1], f[2]);
}
}
}
void VTKPlotFile::WritePointData()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int nodes = mesh.Nodes();
// we count nodal variables and element variables that use NODE format
PlotFile::Dictionary& dic = GetDictionary();
int nodalVars = dic.NodalVariables();
int domainVars = 0;
auto& domainData = dic.DomainVariableList();
list<DICTIONARY_ITEM>::iterator it = domainData.begin();
for (int i = 0; i < domainData.size(); ++i, ++it)
{
if (it->m_psave)
{
FEPlotData* pd = it->m_psave;
int format = pd->StorageFormat();
if ((format == Storage_Fmt::FMT_NODE) ||
(format == Storage_Fmt::FMT_MULT)) domainVars++;
}
}
if ((nodalVars + domainVars) == 0) return;
fprintf(m_fp, "\nPOINT_DATA %d\n", nodes);
auto& nodeData = dic.NodalVariableList();
it = nodeData.begin();
for (int n = 0; n < nodeData.size(); ++n, ++it)
{
if (it->m_psave)
{
FEPlotData* pd = it->m_psave;
int ndata = pd->VarSize(pd->DataType());
int N = fem.GetMesh().Nodes();
FEDataStream a; a.reserve(ndata * N);
if (pd->Save(fem.GetMesh(), a))
{
// pad mismatches
assert(a.size() == N * ndata);
if (a.size() != N * ndata) a.resize(N * ndata, 0.f);
// must remove all whitespace
string dataName = it->m_szname;
for (size_t i = 0; i < dataName.size(); ++i)
if (isspace(dataName[i])) dataName[i] = '_';
const char* szname = dataName.c_str();
// write the value array
std::vector<float>& val = a.data();
switch (pd->DataType())
{
case PLT_FLOAT : WriteScalarData(val, szname); break;
case PLT_VEC3F : WriteVectorData(val, szname); break;
case PLT_MAT3FS: WriteMat3FSData(val, szname); break;
case PLT_MAT3FD: WriteMat3FDData(val, szname); break;
default:
assert(false);
}
}
}
}
// export all domain data that uses NODE storage format
it = domainData.begin();
for (int i = 0; i < domainData.size(); ++i, ++it)
{
if (it->m_psave)
{
FEPlotData* pd = it->m_psave;
int format = pd->StorageFormat();
// must remove all whitespace
string dataName = it->m_szname;
Space2_(dataName);
const char* szname = dataName.c_str();
int ndata = pd->VarSize(pd->DataType());
// For now, we store all data in a global array
int N = fem.GetMesh().Nodes();
std::vector<float> val(ndata * N, 0.f);
if (format == Storage_Fmt::FMT_NODE)
{
// loop over all domains and fill global val array
for (int i = 0; i < mesh.Domains(); ++i)
{
FEDomain& dom = mesh.Domain(i);
int NN = dom.Nodes();
FEDataStream a; a.reserve(ndata * NN);
pd->Save(dom, a);
// pad mismatches
if (a.size() != NN * ndata) a.resize(NN * ndata, 0.f);
// copy to global array
for (int j = 0; j < NN; ++j)
{
int nj = dom.NodeIndex(j);
for (int k = 0; k < ndata; ++k) val[nj * ndata + k] = a[ndata * j + k];
}
}
}
else if (format == Storage_Fmt::FMT_MULT)
{
vector<int> tag(N, 0);
// loop over all domains and fill global val array
for (int i = 0; i < mesh.Domains(); ++i)
{
FEDomain& dom = mesh.Domain(i);
int NN = 0;
for (int j = 0; j < dom.Elements(); ++j) NN += dom.ElementRef(j).Nodes();
FEDataStream a; a.reserve(ndata * NN);
pd->Save(dom, a);
// pad mismatches
if (a.size() != NN * ndata) a.resize(NN * ndata, 0.f);
// copy to global array
NN = 0;
for (int j = 0; j < dom.Elements(); ++j)
{
FEElement& el = dom.ElementRef(j);
int ne = el.Nodes();
for (int k = 0; k < ne; ++k, ++NN)
{
int nk = el.m_node[k];
tag[nk]++;
for (int l = 0; l < ndata; ++l)
{
val[nk * ndata + l] += a[NN*ndata + l];
}
}
}
}
for (int i = 0; i < N; ++i)
{
if (tag[i] != 0)
{
float d = 1.f / (float)tag[i];
for (int j = 0; j < ndata; ++j) val[i * ndata + j] *= d;
}
}
}
else continue;
// write the value array
switch (pd->DataType())
{
case PLT_FLOAT : WriteScalarData(val, szname); break;
case PLT_VEC3F : WriteVectorData(val, szname); break;
case PLT_MAT3FS: WriteMat3FSData(val, szname); break;
case PLT_MAT3FD: WriteMat3FDData(val, szname); break;
case PLT_ARRAY : WriteArrayData (val, szname, pd); break;
case PLT_ARRAY_VEC3F: WriteArrayVec3fData(val, szname, pd); break;
default:
assert(false);
}
}
}
}
void VTKPlotFile::WriteCellData()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int totalElements = mesh.Elements();
PlotFile::Dictionary& dic = GetDictionary();
if (dic.DomainVariables() == 0) return;
// write cell data
fprintf(m_fp, "\nCELL_DATA %d\n", totalElements);
// write the part IDs first
fprintf(m_fp, "SCALARS part_id int\n");
fprintf(m_fp, "LOOKUP_TABLE default\n");
for (int i = 0; i < mesh.Domains(); ++i)
{
FEDomain& dom = mesh.Domain(i);
int NE = dom.Elements();
for (int n = 0; n < NE; ++n) fprintf(m_fp, "%d\n", i);
}
auto& elemData = dic.DomainVariableList();
list<DICTIONARY_ITEM>::iterator it = elemData.begin();
for (int n = 0; n < elemData.size(); ++n, ++it)
{
if (it->m_psave)
{
FEPlotData* pd = it->m_psave;
// For now, we can only store FE_REGION_DOMAIN/FMT_ITEM
int nregion = pd->RegionType();
int nformat = pd->StorageFormat();
if ((nregion == FE_REGION_DOMAIN) && (nformat == FMT_ITEM))
{
// get the number of floats per data value
int ndata = pd->VarSize(pd->DataType());
// For now, we store all data in a global array
std::vector<float> val(ndata * totalElements, 0.f);
// loop over all domains and fill global val array
int nc = 0;
for (int i = 0; i < mesh.Domains(); ++i)
{
FEDomain& dom = mesh.Domain(i);
int NE = dom.Elements();
FEDataStream a; a.reserve(ndata * NE);
pd->Save(dom, a);
// pad mismatches
if (a.size() != NE * ndata) a.resize(NE * ndata, 0.f);
// copy into global array
vector<float>& vi = a.data();
for (int iel = 0; iel < NE; ++iel)
{
for (int k = 0; k < ndata; ++k)
{
val[nc++] = vi[iel * ndata + k];
}
}
}
// must remove all whitespace
string dataName = it->m_szname;
for (size_t i = 0; i < dataName.size(); ++i)
if (isspace(dataName[i])) dataName[i] = '_';
const char* szname = dataName.c_str();
// write the value array
switch (pd->DataType())
{
case PLT_FLOAT : WriteScalarData(val, szname); break;
case PLT_VEC3F : WriteVectorData(val, szname); break;
case PLT_MAT3F : WriteMat3FData (val, szname); break;
case PLT_MAT3FS: WriteMat3FSData(val, szname); break;
case PLT_MAT3FD: WriteMat3FDData(val, szname); break;
case PLT_ARRAY : WriteArrayData (val, szname, pd); break;
case PLT_ARRAY_VEC3F: WriteArrayVec3fData(val, szname, pd); break;
default:
assert(false);
}
}
}
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioPlot/PltArchive.h | .h | 9,532 | 368 | /*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 <assert.h>
#include <string>
#include <string.h>
#include <stdio.h>
#include <list>
#include <vector>
#include <stack>
#include "febioplot_api.h"
//-----------------------------------------------------------------------------
enum IOResult { IO_ERROR, IO_OK, IO_END };
//-----------------------------------------------------------------------------
//! helper class for writing buffered data to file
class FEBIOPLOT_API FileStream
{
public:
FileStream(FILE* fp = nullptr, bool owner = true);
~FileStream();
bool Create(const char* szfile);
bool Open(const char* szfile);
bool Append(const char* szfile);
void Close();
void Write(void* pd, size_t Size, size_t Count);
void Flush();
// \todo temporary reading functions. Needs to be replaced with buffered functions
size_t read(void* pd, size_t Size, size_t Count);
long tell();
void seek(long noff, int norigin);
void BeginStreaming();
void EndStreaming();
void SetCompression(int n) { m_ncompress = n; }
FILE* FilePtr() { return m_fp; }
bool IsValid() { return (m_fp != nullptr); }
private:
FILE* m_fp;
bool m_fileOwner;
size_t m_bufsize; //!< buffer size
size_t m_current; //!< current index
unsigned char* m_buf; //!< buffer
unsigned char* m_pout; //!< temp buffer when writing
int m_ncompress; //!< compression level
};
class OBranch;
class OChunk
{
public:
OChunk(unsigned int nid) { m_nID = nid; m_pParent = 0; }
virtual ~OChunk(){}
unsigned int GetID() { return m_nID; }
virtual void Write(FileStream* fp) = 0;
virtual int Size() = 0;
void SetParent(OBranch* pparent) { m_pParent = pparent; }
OBranch* GetParent() { return m_pParent; }
protected:
int m_nID;
OBranch* m_pParent;
};
class OBranch : public OChunk
{
public:
OBranch(unsigned int nid) : OChunk(nid) {}
~OBranch()
{
std::list<OChunk*>::iterator pc;
for (pc = m_child.begin(); pc != m_child.end(); ++pc) delete (*pc);
m_child.clear();
}
int Size()
{
int nsize = 0;
std::list<OChunk*>::iterator pc;
for (pc = m_child.begin(); pc != m_child.end(); ++pc) nsize += (*pc)->Size() + 2*sizeof(unsigned int);
return nsize;
}
void Write(FileStream* fp)
{
fp->Write(&m_nID , sizeof(unsigned int), 1);
unsigned int nsize = Size();
fp->Write(&nsize, sizeof(unsigned int), 1);
std::list<OChunk*>::iterator pc;
for (pc = m_child.begin(); pc != m_child.end(); ++pc) (*pc)->Write(fp);
}
void AddChild(OChunk* pc) { m_child.push_back(pc); pc->SetParent(this); }
protected:
std::list<OChunk*> m_child;
};
template <typename T>
class OLeaf : public OChunk
{
public:
OLeaf(unsigned int nid, const T& d) : OChunk(nid) { m_d = d; }
int Size() { return sizeof(T); }
void Write(FileStream* fp)
{
fp->Write(&m_nID , sizeof(unsigned int), 1);
unsigned int nsize = sizeof(T);
fp->Write(&nsize, sizeof(unsigned int), 1);
fp->Write(&m_d, sizeof(T), 1);
}
protected:
T m_d;
};
template <typename T>
class OLeaf<T*> : public OChunk
{
public:
OLeaf(unsigned int nid, const T* pd, int nsize) : OChunk(nid)
{
assert(nsize > 0);
m_pd = new T[nsize];
memcpy(m_pd, pd, sizeof(T)*nsize);
m_nsize = nsize;
}
~OLeaf() { delete m_pd; }
int Size() { return sizeof(T)*m_nsize; }
void Write(FileStream* fp)
{
fp->Write(&m_nID , sizeof(unsigned int), 1);
unsigned int nsize = Size();
fp->Write(&nsize , sizeof(unsigned int), 1);
fp->Write(m_pd , sizeof(T), m_nsize);
}
protected:
T* m_pd;
int m_nsize;
};
template <>
class OLeaf<const char*> : public OChunk
{
public:
OLeaf(unsigned int nid, const char* sz) : OChunk(nid)
{
int l = (int)strlen(sz);
m_psz = new char[l+1];
memcpy(m_psz, sz, l+1);
}
~OLeaf() { delete m_psz; }
int Size() { return (int)strlen(m_psz)+sizeof(int); }
void Write(FileStream* fp)
{
fp->Write(&m_nID , sizeof(unsigned int), 1);
unsigned int nsize = Size();
fp->Write(&nsize , sizeof(unsigned int), 1);
int l = nsize - sizeof(int);
fp->Write(&l, sizeof(int), 1);
fp->Write(m_psz, sizeof(char), l);
}
protected:
char* m_psz;
};
template <typename T>
class OLeaf<std::vector<T> > : public OChunk
{
public:
OLeaf(unsigned int nid, const std::vector<T>& a) : OChunk(nid), m_pd(nullptr)
{
m_nsize = (int)a.size();
if (m_nsize > 0)
{
m_pd = new T[m_nsize];
memcpy(m_pd, &a[0], sizeof(T) * m_nsize);
}
}
~OLeaf() { delete m_pd; }
int Size() { return sizeof(T)*m_nsize; }
void Write(FileStream* fp)
{
fp->Write(&m_nID , sizeof(unsigned int), 1);
unsigned int nsize = Size();
fp->Write(&nsize , sizeof(unsigned int), 1);
if (m_pd && (nsize > 0)) fp->Write(m_pd , sizeof(T), m_nsize);
}
protected:
T* m_pd;
int m_nsize;
};
//-----------------------------------------------------------------------------
//! Implementation of an archiving class. Will be used by the FEBioPlotFile class.
class FEBIOPLOT_API PltArchive
{
protected:
// CHUNK data structure for reading
struct CHUNK
{
unsigned int id; // chunk ID
unsigned int lpos; // file position
unsigned int nsize; // size of chunk
};
public:
//! constructor
PltArchive();
//! destructor
~PltArchive();
// Close archive
void Close();
// flush data to file
void Flush();
public:
// --- Writing ---
// Open for writing
bool Create(const char* szfile);
// begin a chunk
void BeginChunk(unsigned int id);
// end a chunck
void EndChunk();
template <typename T> void WriteChunk(unsigned int nid, T& o)
{
m_pChunk->AddChild(new OLeaf<T>(nid, o));
}
void WriteChunk(unsigned int nid, const char* sz)
{
m_pChunk->AddChild(new OLeaf<const char*>(nid, sz));
}
void WriteChunk(unsigned int nid, const std::string& s)
{
m_pChunk->AddChild(new OLeaf<const char*>(nid, s.c_str()));
}
template <typename T> void WriteChunk(unsigned int nid, T* po, int n)
{
m_pChunk->AddChild(new OLeaf<T*>(nid, po, n));
}
template <typename T> void WriteChunk(unsigned int nid, std::vector<T>& a)
{
m_pChunk->AddChild(new OLeaf<std::vector<T> >(nid, a));
}
void WriteData(int nid, std::vector<float>& data)
{
WriteChunk(nid, data);
}
public:
// --- Reading ---
// Open for reading
bool Open(const char* sfile);
bool Append(const char* szfile);
// Open a chunk
int OpenChunk();
// Get the current chunk ID
unsigned int GetChunkID();
// Close a chunk
void CloseChunk();
// input functions
IOResult read(char& c) { size_t nr = m_fp->read(&c, sizeof(char ), 1); if (nr != 1) return IO_ERROR; return IO_OK; }
IOResult read(int& n) { size_t nr = m_fp->read(&n, sizeof(int ), 1); if (nr != 1) return IO_ERROR; return IO_OK; }
IOResult read(bool& b) { size_t nr = m_fp->read(&b, sizeof(bool ), 1); if (nr != 1) return IO_ERROR; return IO_OK; }
IOResult read(float& f) { size_t nr = m_fp->read(&f, sizeof(float ), 1); if (nr != 1) return IO_ERROR; return IO_OK; }
IOResult read(double& g) { size_t nr = m_fp->read(&g, sizeof(double), 1); if (nr != 1) return IO_ERROR; return IO_OK; }
IOResult read(unsigned int& n) { size_t nr = m_fp->read(&n, sizeof(unsigned int), 1); if (nr != 1) return IO_ERROR; return IO_OK; }
IOResult read(char* pc, int n) { size_t nr = m_fp->read(pc, sizeof(char ), n); if (nr != n) return IO_ERROR; return IO_OK; }
IOResult read(int* pi, int n) { size_t nr = m_fp->read(pi, sizeof(int ), n); if (nr != n) return IO_ERROR; return IO_OK; }
IOResult read(bool* pb, int n) { size_t nr = m_fp->read(pb, sizeof(bool ), n); if (nr != n) return IO_ERROR; return IO_OK; }
IOResult read(float* pf, int n) { size_t nr = m_fp->read(pf, sizeof(float ), n); if (nr != n) return IO_ERROR; return IO_OK; }
IOResult read(double* pg, int n) { size_t nr = m_fp->read(pg, sizeof(double), n); if (nr != n) return IO_ERROR; return IO_OK; }
IOResult read(char* sz)
{
IOResult ret;
int l;
ret = read(l); if (ret != IO_OK) return ret;
size_t nr = m_fp->read(sz, 1, l); if (nr != l) return IO_ERROR;
sz[l] = 0;
return IO_OK;
}
void SetCompression(int n);
bool IsValid() const { return (m_fp != 0); }
protected:
FileStream* m_fp; // pointer to file stream
bool m_bSaving; // read or write mode?
// write data
OBranch* m_pRoot; // chunk tree root
OBranch* m_pChunk; // current chunk
// read data
bool m_bend; // chunk end flag
std::stack<CHUNK*> m_Chunk;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioPlot/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++ |
3D | febiosoftware/FEBio | FEBioPlot/FEBioPlotFile.cpp | .cpp | 58,212 | 2,332 | /*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 "FEBioPlotFile.h"
#include "FECore/FECoreKernel.h"
#include "FECore/FEDataExport.h"
#include "FECore/FEModel.h"
#include "FECore/FEMaterial.h"
#include <FECore/FESurface.h>
#include <FECore/FEEdge.h>
#include <FECore/FEPlotDataStore.h>
#include <FECore/log.h>
#include <FECore/FEPIDController.h>
#include <sstream>
FEBioPlotFile::DICTIONARY_ITEM::DICTIONARY_ITEM()
{
m_psave = 0;
m_ntype = 0;
m_nfmt = 0;
m_arraySize = 0;
m_szname[0] = 0;
m_szunit[0] = 0;
}
FEBioPlotFile::DICTIONARY_ITEM::DICTIONARY_ITEM(const FEBioPlotFile::DICTIONARY_ITEM& item)
{
m_psave = item.m_psave;
m_ntype = item.m_ntype;
m_nfmt = item.m_nfmt;
m_arraySize = item.m_arraySize;
m_arrayNames = item.m_arrayNames;
m_szname[0] = 0;
m_szunit[0] = 0;
if (item.m_szname[0]) strcpy(m_szname, item.m_szname);
if (item.m_szunit[0]) strcpy(m_szunit, item.m_szunit);
}
class FEPlotSurfaceDataExport : public FEPlotData
{
public:
FEPlotSurfaceDataExport(FEModel* fem, const char* szname, Var_Type itype, Storage_Fmt fmt) : FEPlotData(fem, FE_REGION_SURFACE, itype, fmt) { m_szname = szname; }
void Save(FEModel& fem, PltArchive& ar)
{
FEMesh& mesh = fem.GetMesh();
int NS = mesh.Surfaces();
for (int i = 0; i<NS; ++i)
{
FESurface& s = mesh.Surface(i);
int ND = s.DataExports();
if (ND > 0)
{
for (int j = 0; j<ND; ++j)
{
FEDataExport* pd = s.GetDataExport(j);
if (strcmp(pd->m_szname, m_szname) == 0)
{
FEDataStream d;
pd->Serialize(d);
ar.WriteData(i + 1, d.data());
break;
}
}
}
}
}
private:
const char* m_szname;
};
class FEPlotDomainDataExport : public FEPlotData
{
public:
FEPlotDomainDataExport(FEModel* fem, const char* szname, Var_Type itype, Storage_Fmt fmt) : FEPlotData(fem, FE_REGION_DOMAIN, itype, fmt) { m_szname = szname; }
void Save(FEModel& fem, PltArchive& ar)
{
FEMesh& mesh = fem.GetMesh();
int NDOMS = mesh.Domains();
for (int i = 0; i<NDOMS; ++i)
{
FEDomain& dom = mesh.Domain(i);
int NDATA = dom.DataExports();
if (NDATA > 0)
{
for (int j = 0; j<NDATA; ++j)
{
FEDataExport* pd = dom.GetDataExport(j);
if (strcmp(pd->m_szname, m_szname) == 0)
{
FEDataStream d;
pd->Serialize(d);
ar.WriteData(i + 1, d.data());
break;
}
}
}
}
}
private:
const char* m_szname;
};
class FEBioPlotVariable : public FEPlotNodeData
{
public:
FEBioPlotVariable(FEModel* fem, const char* szname, Var_Type itype, Storage_Fmt fmt) : FEPlotNodeData(fem, itype, fmt) { strcpy(m_szname, szname); }
bool Save(FEMesh& mesh, FEDataStream& str)
{
// get the DOFS
FEModel& fem = *GetFEModel();
DOFS& dofs = fem.GetDOFS();
// see if this variable exists
int nvar = dofs.GetVariableIndex(m_szname);
if (nvar < 0) return false;
// get the size of the variable
int n = dofs.GetVariableSize(nvar);
if (n == 0) return false;
// get the start index of the DOFS
int ndof = dofs.GetDOF(nvar, 0);
if (ndof < 0) return false;
// store the nodal data
int NN = mesh.Nodes();
for (int i = 0; i<NN; ++i)
{
FENode& node = mesh.Node(i);
for (int j = 0; j<n; ++j) str << node.get(ndof + j);
}
return true;
}
private:
char m_szname[256];
};
class FEPlotArrayVariable : public FEPlotDomainData
{
public:
FEPlotArrayVariable(FEModel* fem, const char* szname, int index) : FEPlotDomainData(fem, PLT_FLOAT, FMT_NODE)
{
strcpy(m_szname, szname);
m_index = index;
if (index == -1)
{
// get the DOFS
FEModel& fem = *GetFEModel();
DOFS& dofs = fem.GetDOFS();
// see if this variable exists
int nvar = dofs.GetVariableIndex(m_szname);
if (nvar >= 0)
{
// get the size of the variable
int n = dofs.GetVariableSize(nvar);
if (n > 0)
{
SetVarType(PLT_ARRAY);
SetArraySize(n);
}
}
}
}
bool Save(FEDomain& D, FEDataStream& a)
{
// get the DOFS
FEModel& fem = *GetFEModel();
DOFS& dofs = fem.GetDOFS();
// see if this variable exists
int nvar = dofs.GetVariableIndex(m_szname);
if (nvar < 0) return false;
// get the size of the variable
int n = dofs.GetVariableSize(nvar);
if (n == 0) return false;
// get the start index of the DOFS
if (m_index >= 0)
{
int ndof = dofs.GetDOF(nvar, m_index);
if (ndof < 0) return false;
// see if this domain contains this dof
const FEDofList& domDofs = D.GetDOFList();
bool bfound = false;
for (int i = 0; i < (int)domDofs.Size(); ++i)
{
if (domDofs[i] == ndof)
{
bfound = true;
break;
}
}
if (bfound == false) return false;
// store the nodal data
int NN = D.Nodes();
for (int i = 0; i < NN; ++i)
{
FENode& node = D.Node(i);
a << node.get(ndof);
}
}
else
{
const FEDofList& domDofs = D.GetDOFList();
vector<int> dofList(n, -1);
for (int dof_i = 0; dof_i < n; dof_i++)
{
int ndof = dofs.GetDOF(nvar, dof_i);
// see if this domain contains this dof
bool bfound = false;
for (int i = 0; i < (int)domDofs.Size(); ++i)
{
if (domDofs[i] == ndof)
{
bfound = true;
dofList[dof_i] = i;
break;
}
}
}
// store the nodal data
int NN = D.Nodes();
for (int i = 0; i < NN; ++i)
{
FENode& node = D.Node(i);
for (int dof_i = 0; dof_i < n; dof_i++)
{
int ndof = dofList[dof_i];
if (ndof < 0)
{
a << 0.0;
}
else
{
// store the nodal data
a << node.get(ndof);
}
}
}
}
return true;
}
private:
char m_szname[256];
int m_index;
};
//-----------------------------------------------------------------------------
//! Adds a variable to the plot file.
//!
//! The name of the filter can be composed of three parts and in general takes on
//! the following format.
//!
//! szname = "field_name[filter]=alias".
//!
//! field_name = This is the actual filter naeme as it is registered with the framework.
//! filter = This is a filter that is used to resolve ambiguities.
//! alias = This is an alternative name for the field variable.
//!
//! The alias is optional but can be used by post-processing software to present an alternative
//! (often simpler) name for the field variable than the default field_name + filter combo.
//!
//! Whether a filter is required depends entirely on the field variable. Most field variables don't
//! require it, but some do in order to resolve an ambiguity. For instance, the "parameter" field
//! allows users to plot the spatially varying value of a material parameter. The filter is used to
//! specify the material and parameter name.
//!
//! The filter can be a numerical value or a string. If it's a string then it must be enclosed in
//! single quotes.
//!
//! szname = "field_name[12]" \\ example of a numerical filter
//! szname = "field_name['val'] \\ example of a string filter
//!
//! The interpretation of these filters is entirely left up to the field variable.
//!
bool FEBioPlotFile::Dictionary::AddVariable(FEModel* pfem, const char* szname, vector<int>& item, const char* szdom)
{
FECoreKernel& febio = FECoreKernel::GetInstance();
FEPlotFieldDescriptor PD(szname);
if (!PD.isValid()) return false;
const char* szfield = PD.fieldName.c_str();
// create the plot variable
FEPlotData* ps = fecore_new<FEPlotData>(szfield, pfem);
if (ps)
{
// set the optional item list and filter
ps->SetItemList(item);
if (PD.HasFilter())
{
if (PD.IsStringFilter())
{
if (ps->SetFilter(PD.strFilter.c_str()) == false) return false;
}
else if (PD.IsNumberFilter())
{
if (ps->SetFilter(PD.numFilter) == false) return false;
}
}
const char* sz = PD.alias.c_str();
// add the field to the plot file
ps->SetDomainName(szdom);
switch (ps->RegionType())
{
case FE_REGION_GLOBAL : return AddGlobalVariable(ps, sz);
case FE_REGION_NODE : return AddNodalVariable(ps, sz, item);
case FE_REGION_DOMAIN : return AddDomainVariable(ps, sz, item);
case FE_REGION_SURFACE: return AddSurfaceVariable(ps, sz, item);
case FE_REGION_EDGE : return AddEdgeVariable(ps, sz, item);
default:
assert(false);
return false;
}
}
else
{
// If we get here then this variable is not a plot field.
// But let's see if it is an export variable from a domain
// Check the surfaces first
FEMesh& mesh = pfem->GetMesh();
for (int i = 0; i<mesh.Surfaces(); ++i)
{
FESurface& s = mesh.Surface(i);
int ND = s.DataExports();
for (int j = 0; j<ND; ++j)
{
FEDataExport* pd = s.GetDataExport(j);
if (strcmp(pd->m_szname, szname) == 0)
{
// We have a match. Create a plot field for this export
ps = new FEPlotSurfaceDataExport(pfem, pd->m_szname, pd->m_type, pd->m_fmt);
return AddSurfaceVariable(ps, szname, item);
}
}
}
// now the domains.
for (int i = 0; i<mesh.Domains(); ++i)
{
FEDomain& dom = mesh.Domain(i);
int ND = dom.DataExports();
for (int j = 0; j<ND; ++j)
{
FEDataExport* pd = dom.GetDataExport(j);
if (strcmp(pd->m_szname, szname) == 0)
{
// We have a match. Create a plot field for this export
ps = new FEPlotDomainDataExport(pfem, pd->m_szname, pd->m_type, pd->m_fmt);
return AddDomainVariable(ps, szname, item);
}
}
}
// If we still didn't find it, maybe it's a model variable.
DOFS& dofs = pfem->GetDOFS();
int nvar = dofs.GetVariableIndex(szfield);
if (nvar >= 0)
{
int vartype = dofs.GetVariableType(nvar);
if (vartype == VAR_SCALAR)
{
ps = new FEBioPlotVariable(pfem, szfield, PLT_FLOAT, FMT_NODE);
return AddNodalVariable(ps, szname, item);
}
else if (vartype == VAR_VEC3)
{
ps = new FEBioPlotVariable(pfem, szfield, PLT_VEC3F, FMT_NODE);
return AddNodalVariable(ps, szname, item);
}
else if (vartype == VAR_ARRAY)
{
int ndofs = dofs.GetVariableSize(szfield);
int index = -1;
if (PD.IsNumberFilter()) index = PD.numFilter;
else if (PD.IsStringFilter())
{
const char* szflt = PD.strFilter.c_str();
index = dofs.GetIndex(szfield, szflt);
if (index < 0) index = pfem->GetDOFIndex(szflt);
}
if ((index < 0) || (index >= ndofs)) return false;
ps = new FEPlotArrayVariable(pfem, szfield, index);
return AddDomainVariable(ps, szname, item);
}
}
}
return false;
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::Dictionary::AddGlobalVariable(FEPlotData* ps, const char* szname)
{
assert(ps->RegionType() == FE_REGION_GLOBAL);
if (ps->RegionType() == FE_REGION_GLOBAL)
{
DICTIONARY_ITEM it;
it.m_ntype = ps->DataType();
it.m_nfmt = ps->StorageFormat();
it.m_psave = ps;
it.m_arraySize = ps->GetArraysize();
it.m_arrayNames = ps->GetArrayNames();
strcpy(it.m_szname, szname);
if (ps->GetUnits())
{
strcpy(it.m_szunit, ps->GetUnits());
}
m_Glob.push_back(it);
return true;
}
return false;
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::Dictionary::AddMaterialVariable(FEPlotData* ps, const char* szname)
{
return false;
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::Dictionary::AddNodalVariable(FEPlotData* ps, const char* szname, vector<int>& item)
{
assert(ps->RegionType()==FE_REGION_NODE);
if (ps->RegionType()==FE_REGION_NODE)
{
DICTIONARY_ITEM it;
it.m_ntype = ps->DataType();
it.m_nfmt = ps->StorageFormat();
it.m_psave = ps;
it.m_arraySize = ps->GetArraysize();
it.m_arrayNames = ps->GetArrayNames();
strcpy(it.m_szname, szname);
if (ps->GetUnits())
{
strcpy(it.m_szunit, ps->GetUnits());
}
m_Node.push_back(it);
return true;
}
return false;
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::Dictionary::AddDomainVariable(FEPlotData* ps, const char* szname, vector<int>& item)
{
assert(ps->RegionType()==FE_REGION_DOMAIN);
if (ps->RegionType()==FE_REGION_DOMAIN)
{
DICTIONARY_ITEM it;
it.m_ntype = ps->DataType();
it.m_nfmt = ps->StorageFormat();
it.m_psave = ps;
it.m_arraySize = ps->GetArraysize();
it.m_arrayNames = ps->GetArrayNames();
strcpy(it.m_szname, szname);
if (ps->GetUnits())
{
strcpy(it.m_szunit, ps->GetUnits());
}
m_Elem.push_back(it);
return true;
}
return false;
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::Dictionary::AddSurfaceVariable(FEPlotData* ps, const char* szname, vector<int>& item)
{
assert(ps->RegionType()==FE_REGION_SURFACE);
if (ps->RegionType()==FE_REGION_SURFACE)
{
DICTIONARY_ITEM it;
it.m_ntype = ps->DataType();
it.m_nfmt = ps->StorageFormat();
it.m_psave = ps;
it.m_arraySize = ps->GetArraysize();
it.m_arrayNames = ps->GetArrayNames();
strcpy(it.m_szname, szname);
if (ps->GetUnits())
{
strcpy(it.m_szunit, ps->GetUnits());
}
m_Face.push_back(it);
return true;
}
return false;
}
bool FEBioPlotFile::Dictionary::AddEdgeVariable(FEPlotData* ps, const char* szname, vector<int>& item)
{
assert(ps->RegionType() == FE_REGION_EDGE);
if (ps->RegionType() == FE_REGION_EDGE)
{
DICTIONARY_ITEM it;
it.m_ntype = ps->DataType();
it.m_nfmt = ps->StorageFormat();
it.m_psave = ps;
it.m_arraySize = ps->GetArraysize();
it.m_arrayNames = ps->GetArrayNames();
strcpy(it.m_szname, szname);
if (ps->GetUnits())
{
strcpy(it.m_szunit, ps->GetUnits());
}
m_Edge.push_back(it);
return true;
}
return false;
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::Dictionary::Defaults(FEModel& fem)
{
// First we build the dictionary
// get the mesh
FEMesh& m = fem.GetMesh();
// Define default variables
if (m_Node.empty() && m_Elem.empty() && m_Face.empty())
{
vector<int> l; // empty list
AddVariable(&fem, "displacement", l);
AddVariable(&fem, "stress", l);
}
// Define default global variables
if (m_Glob.empty())
{
// add all the PID controllers
std::vector<int> dummy;
for (int i = 0; i < fem.LoadControllers(); ++i)
{
FEPIDController* pid = dynamic_cast<FEPIDController*>(fem.GetLoadController(i));
if (pid)
{
stringstream ss;
ss << "pid controller['" << pid->GetName() << "']=" << pid->GetName();
string s = ss.str();
AddVariable(&fem, s.c_str(), dummy);
}
}
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::Dictionary::Clear()
{
list<DICTIONARY_ITEM>::iterator it = m_Glob.begin();
for (int i = 0; i < (int)m_Glob.size(); ++i, ++it) delete it->m_psave;
m_Glob.clear();
it = m_Mat.begin();
for (int i = 0; i < (int)m_Mat.size(); ++i, ++it) delete it->m_psave;
m_Mat.clear();
it = m_Node.begin();
for (int i = 0; i < (int)m_Node.size(); ++i, ++it) delete it->m_psave;
m_Node.clear();
it = m_Elem.begin();
for (int i = 0; i < (int)m_Elem.size(); ++i, ++it) delete it->m_psave;
m_Elem.clear();
it = m_Face.begin();
for (int i = 0; i < (int)m_Face.size(); ++i, ++it) delete it->m_psave;
m_Face.clear();
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::PlotObject::AddData(const char* szname, Var_Type type, FEPlotData* psave)
{
DICTIONARY_ITEM item;
item.m_psave = nullptr;
item.m_szname[0] = 0;
int l = strlen(szname);
if (l >= STR_SIZE) l = STR_SIZE - 1;
strncpy(item.m_szname, szname, l);
item.m_szname[l] = 0;
item.m_ntype = type;
item.m_nfmt = FMT_ITEM;
item.m_psave = psave;
m_data.push_back(item);
}
//=============================================================================
FEBioPlotFile::FEBioPlotFile(FEModel* fem) : PlotFile(fem)
{
m_ncompress = 0;
m_meshesWritten = 0;
m_exportUnitsFlag = false;
m_exportErodedElements = true;
}
//-----------------------------------------------------------------------------
int FEBioPlotFile::PointObjects()
{
return (int) m_Points.size();
}
//-----------------------------------------------------------------------------
FEBioPlotFile::PointObject* FEBioPlotFile::GetPointObject(int i)
{
if ((i >= 0) && (i < PointObjects())) return m_Points[i];
return nullptr;
}
//-----------------------------------------------------------------------------
FEBioPlotFile::PointObject* FEBioPlotFile::AddPointObject(const std::string& name)
{
PointObject* po = new PointObject;
m_Points.push_back(po);
po->m_name = name;
po->m_id = m_Points.size();
return po;
}
//-----------------------------------------------------------------------------
int FEBioPlotFile::LineObjects()
{
return (int)m_Lines.size();
}
//-----------------------------------------------------------------------------
FEBioPlotFile::LineObject* FEBioPlotFile::GetLineObject(int i)
{
if ((i >= 0) && (i < LineObjects())) return m_Lines[i];
return nullptr;
}
//-----------------------------------------------------------------------------
FEBioPlotFile::LineObject* FEBioPlotFile::AddLineObject(const std::string& name)
{
LineObject* po = new LineObject;
m_Lines.push_back(po);
po->m_name = name;
po->m_id = m_Lines.size();
return po;
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::SetCompression(int n)
{
#ifdef HAVE_ZLIB
m_ncompress = n;
#else
m_ncompress = 0;
#endif
}
//-----------------------------------------------------------------------------
//! set the version string
void FEBioPlotFile::SetSoftwareString(const std::string& softwareString)
{
m_softwareString = softwareString;
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::IsValid() const
{
return m_ar.IsValid();
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::Close()
{
m_ar.Close();
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::Clear()
{
PlotFile::Dictionary& dic = GetDictionary();
dic.Clear();
m_Surf.clear();
for (PointObject* p : m_Points) delete p; m_Points.clear();
for (LineObject* l : m_Lines) delete l; m_Lines.clear();
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::Open(const char *szfile)
{
FEModel* fem = GetFEModel();
m_meshesWritten = 0;
// open the archive
m_ar.Create(szfile);
// set compression
FEPlotDataStore& pltData = fem->GetPlotDataStore();
SetCompression(pltData.GetPlotCompression());
BuildDictionary();
try
{
// write the root element
if (WriteRoot(*fem) == false) return false;
// write the mesh section
if (WriteMeshSection(*fem) == false) return false;
}
catch (...)
{
return false;
}
return true;
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::WriteRoot(FEModel& fem)
{
// write the root element
// (don't compress this section)
m_ar.SetCompression(0);
m_ar.BeginChunk(PLT_ROOT);
{
// --- save the header file ---
m_ar.BeginChunk(PLT_HEADER);
{
if (WriteHeader(fem) == false) return false;
}
m_ar.EndChunk();
// --- save the dictionary ---
m_ar.BeginChunk(PLT_DICTIONARY);
{
if (WriteDictionary(fem) == false) return false;
}
m_ar.EndChunk();
}
m_ar.EndChunk();
return true;
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::WriteHeader(FEModel& fem)
{
// setup the header
unsigned int nversion = PLT_VERSION;
// output header
m_ar.WriteChunk(PLT_HDR_VERSION, nversion);
// compression flag
m_ar.WriteChunk(PLT_HDR_COMPRESSION, m_ncompress);
// software flag
if (m_softwareString.empty() == false)
{
const char* sz = m_softwareString.c_str();
m_ar.WriteChunk(PLT_HDR_SOFTWARE, sz);
}
// units flag
m_exportUnitsFlag = false;
const char* szunits = fem.GetUnits();
if (szunits != nullptr)
{
m_exportUnitsFlag = true;
m_ar.WriteChunk(PLT_HDR_UNITS, szunits);
}
return true;
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::WriteDictionary(FEModel& fem)
{
// setup defaults for the dictionary
PlotFile::Dictionary& dic = GetDictionary();
dic.Defaults(fem);
// Next, we save the dictionary
// Global variables
if (dic.GlobalVariables() > 0)
{
m_ar.BeginChunk(PLT_DIC_GLOBAL);
{
WriteDicList(dic.GlobalVariableList());
}
m_ar.EndChunk();
}
// store nodal variables
if (dic.NodalVariables() > 0)
{
m_ar.BeginChunk(PLT_DIC_NODAL);
{
WriteDicList(dic.NodalVariableList());
}
m_ar.EndChunk();
}
// store element variables
if (dic.DomainVariables())
{
m_ar.BeginChunk(PLT_DIC_DOMAIN);
{
WriteDicList(dic.DomainVariableList());
}
m_ar.EndChunk();
}
// store surface data
if (dic.SurfaceVariables())
{
m_ar.BeginChunk(PLT_DIC_SURFACE);
{
WriteDicList(dic.SurfaceVariableList());
}
m_ar.EndChunk();
}
// store edge variables
if (dic.EdgeVariables())
{
m_ar.BeginChunk(PLT_DIC_EDGE);
{
WriteDicList(dic.EdgeVariableList());
}
m_ar.EndChunk();
}
return true;
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteDicList(list<FEBioPlotFile::DICTIONARY_ITEM>& dic)
{
int N = (int) dic.size();
list<DICTIONARY_ITEM>::iterator pi = dic.begin();
for (int i=0; i<N; ++i, ++pi)
{
m_ar.BeginChunk(PLT_DIC_ITEM);
{
WriteDictionaryItem(*pi);
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteDictionaryItem(DICTIONARY_ITEM& it)
{
m_ar.WriteChunk(PLT_DIC_ITEM_TYPE, it.m_ntype);
m_ar.WriteChunk(PLT_DIC_ITEM_FMT, it.m_nfmt);
m_ar.WriteChunk(PLT_DIC_ITEM_ARRAYSIZE, it.m_arraySize);
if ((it.m_arraySize > 0) && (it.m_arrayNames.size() == it.m_arraySize))
{
for (int i = 0; i < (int)it.m_arraySize; ++i)
{
const string& si = it.m_arrayNames[i];
const char* c = si.c_str();
m_ar.WriteChunk(PLT_DIC_ITEM_ARRAYNAME, (char*)c, STR_SIZE);
}
}
m_ar.WriteChunk(PLT_DIC_ITEM_NAME, it.m_szname, STR_SIZE);
if (m_exportUnitsFlag && it.m_szunit && it.m_szunit[0])
{
m_ar.WriteChunk(PLT_DIC_ITEM_UNITS, it.m_szunit, STR_SIZE);
}
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::WriteMeshSection(FEModel& fem)
{
// get the mesh
FEMesh& m = fem.GetMesh();
m_ar.BeginChunk(PLT_MESH);
{
// node section
m_ar.BeginChunk(PLT_NODE_SECTION);
{
WriteNodeSection(m);
}
m_ar.EndChunk();
// domain section
m_ar.BeginChunk(PLT_DOMAIN_SECTION);
{
WriteDomainSection(m);
}
m_ar.EndChunk();
// surface section
if (m.FacetSets() > 0)
{
BuildSurfaceTable();
m_ar.BeginChunk(PLT_SURFACE_SECTION);
{
WriteSurfaceSection(m);
}
m_ar.EndChunk();
}
// edge section
if (m.Edges() > 0)
{
m_ar.BeginChunk(PLT_EDGE_SECTION);
{
WriteEdgeSection(m);
}
m_ar.EndChunk();
}
// node sets
if (m.NodeSets() > 0)
{
m_ar.BeginChunk(PLT_NODESET_SECTION);
{
WriteNodeSetSection(m);
}
m_ar.EndChunk();
}
// element sets
if (m.ElementSets() > 0)
{
m_ar.BeginChunk(PLT_ELEMENTSET_SECTION);
{
WriteElementSetSection(m);
}
m_ar.EndChunk();
}
// facet sets
if (m.FacetSets() > 0)
{
m_ar.BeginChunk(PLT_FACETSET_SECTION);
{
WriteFacetSetSection(m);
}
m_ar.EndChunk();
}
// parts
// (we write the materials as parts)
if (fem.Materials() > 0)
{
m_ar.BeginChunk(PLT_PARTS_SECTION);
{
WritePartsSection(fem);
}
m_ar.EndChunk();
}
// additional objects
if (m_meshesWritten == 0)
{
if ((m_Points.size() > 0) || (m_Lines.size() > 0))
{
m_ar.BeginChunk(PLT_OBJECTS_SECTION);
{
WriteObjectsSection();
}
m_ar.EndChunk();
}
}
}
m_ar.EndChunk();
m_meshesWritten++;
return true;
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteNodeSection(FEMesh& m)
{
// write the node header
m_ar.BeginChunk(PLT_NODE_HEADER);
{
int NN = m.Nodes();
int dim = 3;
m_ar.WriteChunk(PLT_NODE_SIZE, NN);
m_ar.WriteChunk(PLT_NODE_DIM , dim);
// m_ar.WriteChunk(PLT_NODE_NAME, "AllNodes");
}
m_ar.EndChunk();
// write the reference coordinates
int NN = m.Nodes();
vector<float> X(4*NN);
for (int i=0; i<m.Nodes(); ++i)
{
FENode& node = m.Node(i);
// as of 3.3 we store the node IDs. (Previously the node index was stored)
*((int*) (&X[0] + 4*i)) = node.GetID();
X[4*i+1] = (float) node.m_r0.x;
X[4*i+2] = (float) node.m_r0.y;
X[4*i+3] = (float) node.m_r0.z;
}
m_ar.WriteChunk(PLT_NODE_COORDS, X);
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteDomainSection(FEMesh& m)
{
// write all domains
for (int nd = 0; nd<m.Domains(); ++nd)
{
FEDomain& dom = m.Domain(nd);
m_ar.BeginChunk(PLT_DOMAIN);
{
switch (dom.Class())
{
case FE_DOMAIN_SOLID : WriteSolidDomain (static_cast<FESolidDomain& >(dom)); break;
case FE_DOMAIN_SHELL : WriteShellDomain (static_cast<FEShellDomain& >(dom)); break;
case FE_DOMAIN_BEAM : WriteBeamDomain (static_cast<FEBeamDomain& >(dom)); break;
case FE_DOMAIN_DISCRETE: WriteDiscreteDomain(static_cast<FEDiscreteDomain&>(dom)); break;
case FE_DOMAIN_2D : WriteDomain2D (static_cast<FEDomain2D& >(dom)); break;
}
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteSolidDomain(FESolidDomain& dom)
{
int mid = dom.GetMaterial()->GetID();
assert(mid > 0);
int eshape = dom.GetElementShape();
int NE = dom.Elements();
int elementCount = NE;
if (m_exportErodedElements == false)
{
elementCount = 0;
for (int i = 0; i < NE; ++i)
{
FESolidElement& el = dom.Element(i);
if (el.isActive()) elementCount++;
}
}
// figure out element type
int ne = 0;
int dtype = 0;
switch (eshape)
{
case ET_HEX8 : ne = 8; dtype = PLT_ELEM_HEX; break;
case ET_PENTA6 : ne = 6; dtype = PLT_ELEM_PENTA; break;
case ET_TET4 : ne = 4; dtype = PLT_ELEM_TET4; break;
case ET_TET5 : ne = 5; dtype = PLT_ELEM_TET5; break;
case ET_TET10 : ne = 10; dtype = PLT_ELEM_TET10; break;
case ET_TET15 : ne = 15; dtype = PLT_ELEM_TET15; break;
case ET_HEX20 : ne = 20; dtype = PLT_ELEM_HEX20; break;
case ET_HEX27 : ne = 27; dtype = PLT_ELEM_HEX27; break;
case ET_TET20 : ne = 20; dtype = PLT_ELEM_TET20; break;
case ET_PENTA15: ne = 15; dtype = PLT_ELEM_PENTA15; break;
case ET_PYRA5 : ne = 5; dtype = PLT_ELEM_PYRA5; break;
case ET_PYRA13 : ne = 13; dtype = PLT_ELEM_PYRA13; break;
default:
assert(false);
}
// write the header
m_ar.BeginChunk(PLT_DOMAIN_HDR);
{
m_ar.WriteChunk(PLT_DOM_ELEM_TYPE, dtype);
m_ar.WriteChunk(PLT_DOM_PART_ID , mid);
m_ar.WriteChunk(PLT_DOM_ELEMS , elementCount);
m_ar.WriteChunk(PLT_DOM_NAME , dom.GetName());
}
m_ar.EndChunk();
// write the element list
int n[FEElement::MAX_NODES + 1];
m_ar.BeginChunk(PLT_DOM_ELEM_LIST);
{
for (int i=0; i<NE; ++i)
{
FESolidElement& el = dom.Element(i);
if (m_exportErodedElements || el.isActive())
{
n[0] = el.GetID();
for (int j = 0; j < ne; ++j) n[j + 1] = el.m_node[j];
m_ar.WriteChunk(PLT_ELEMENT, n, ne + 1);
}
}
}
m_ar.EndChunk();
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteShellDomain(FEShellDomain& dom)
{
int mid = dom.GetMaterial()->GetID();
assert(mid > 0);
int etype = dom.GetElementType();
int NE = dom.Elements();
int elementCount = NE;
if (m_exportErodedElements == false)
{
elementCount = 0;
for (int i = 0; i < NE; ++i)
{
FEShellElement& el = dom.Element(i);
if (el.isActive()) elementCount++;
}
}
// figure out element type
int ne = 0;
int dtype = 0;
switch (etype)
{
case FE_SHELL_QUAD4G4 :
case FE_SHELL_QUAD4G8 :
case FE_SHELL_QUAD4G12 :
ne = 4; dtype = PLT_ELEM_QUAD; break;
case FE_SHELL_TRI3G3 :
case FE_SHELL_TRI3G6 :
case FE_SHELL_TRI3G9 :
ne = 3; dtype = PLT_ELEM_TRI; break;
case FE_SHELL_QUAD8G18:
case FE_SHELL_QUAD8G27:
ne = 8; dtype = PLT_ELEM_QUAD8; break;
case FE_SHELL_TRI6G14 :
case FE_SHELL_TRI6G21 :
ne = 6; dtype = PLT_ELEM_TRI6; break;
default:
assert(false);
}
// write the header
m_ar.BeginChunk(PLT_DOMAIN_HDR);
{
m_ar.WriteChunk(PLT_DOM_ELEM_TYPE, dtype);
m_ar.WriteChunk(PLT_DOM_PART_ID , mid);
m_ar.WriteChunk(PLT_DOM_ELEMS , elementCount);
}
m_ar.EndChunk();
// write the element list
int n[FEElement::MAX_NODES + 1] = { 0 };
m_ar.BeginChunk(PLT_DOM_ELEM_LIST);
{
for (int i=0; i<NE; ++i)
{
FEShellElement& el = dom.Element(i);
if (m_exportErodedElements || el.isActive())
{
n[0] = el.GetID();
for (int j = 0; j < ne; ++j) n[j + 1] = el.m_node[j];
m_ar.WriteChunk(PLT_ELEMENT, n, ne + 1);
}
}
}
m_ar.EndChunk();
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteBeamDomain(FEBeamDomain& dom)
{
int mid = dom.GetMaterial()->GetID();
assert(mid > 0);
int NE = dom.Elements();
int elementCount = NE;
if (m_exportErodedElements == false)
{
elementCount = 0;
for (int i = 0; i < NE; ++i)
{
FEElement& el = dom.ElementRef(i);
if (el.isActive()) elementCount++;
}
}
// figure out element type
int ne = 0;
int dtype = 0;
int etype = dom.GetElementType();
switch (etype)
{
case FE_TRUSS : ne = 2; dtype = PLT_ELEM_LINE2; break;
case FE_BEAM2G1: ne = 2; dtype = PLT_ELEM_LINE2; break;
case FE_BEAM2G2: ne = 2; dtype = PLT_ELEM_LINE2; break;
case FE_BEAM3G2: ne = 3; dtype = PLT_ELEM_LINE3; break;
default:
assert(false);
return;
}
// write the header
m_ar.BeginChunk(PLT_DOMAIN_HDR);
{
m_ar.WriteChunk(PLT_DOM_ELEM_TYPE, dtype);
m_ar.WriteChunk(PLT_DOM_PART_ID , mid);
m_ar.WriteChunk(PLT_DOM_ELEMS , elementCount);
}
m_ar.EndChunk();
// write the element list
int n[5];
m_ar.BeginChunk(PLT_DOM_ELEM_LIST);
{
for (int i=0; i<NE; ++i)
{
FEElement& el = dom.ElementRef(i);
if (m_exportErodedElements || el.isActive())
{
n[0] = el.GetID();
for (int j = 0; j < ne; ++j) n[j + 1] = el.m_node[j];
m_ar.WriteChunk(PLT_ELEMENT, n, ne + 1);
}
}
}
m_ar.EndChunk();
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteDiscreteDomain(FEDiscreteDomain& dom)
{
int mid = dom.GetMaterial()->GetID();
assert(mid > 0);
int NE = dom.Elements();
int elementCount = NE;
if (m_exportErodedElements == false)
{
elementCount = 0;
for (int i = 0; i < NE; ++i)
{
FEElement& el = dom.ElementRef(i);
if (el.isActive()) elementCount++;
}
}
// figure out element type
int ne = 2;
int dtype = PLT_ELEM_LINE2;
// write the header
m_ar.BeginChunk(PLT_DOMAIN_HDR);
{
m_ar.WriteChunk(PLT_DOM_ELEM_TYPE, dtype);
m_ar.WriteChunk(PLT_DOM_PART_ID , mid);
m_ar.WriteChunk(PLT_DOM_ELEMS , elementCount);
}
m_ar.EndChunk();
// write the element list
int n[5];
m_ar.BeginChunk(PLT_DOM_ELEM_LIST);
{
for (int i=0; i<NE; ++i)
{
FEElement& el = dom.ElementRef(i);
if (m_exportErodedElements || el.isActive())
{
n[0] = el.GetID();
for (int j = 0; j < ne; ++j) n[j + 1] = el.m_node[j];
m_ar.WriteChunk(PLT_ELEMENT, n, ne + 1);
}
}
}
m_ar.EndChunk();
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteDomain2D(FEDomain2D& dom)
{
int mid = dom.GetMaterial()->GetID();
assert(mid > 0);
int NE = dom.Elements();
int elementCount = NE;
if (m_exportErodedElements == false)
{
elementCount = 0;
for (int i = 0; i < NE; ++i)
{
FEElement& el = dom.ElementRef(i);
if (el.isActive()) elementCount++;
}
}
// figure out element type
int ne = 0;
int dtype = 0;
int etype = dom.GetElementType();
switch (etype)
{
case FE2D_TRI3G1 : ne = 3; dtype = PLT_ELEM_TRI; break;
case FE2D_TRI6G3 : ne = 6; dtype = PLT_ELEM_TRI6; break;
case FE2D_QUAD4G4: ne = 4; dtype = PLT_ELEM_QUAD; break;
case FE2D_QUAD8G9: ne = 8; dtype = PLT_ELEM_QUAD8; break;
case FE2D_QUAD9G9: ne = 9; dtype = PLT_ELEM_QUAD9; break;
default:
assert(false);
}
// write the header
m_ar.BeginChunk(PLT_DOMAIN_HDR);
{
m_ar.WriteChunk(PLT_DOM_ELEM_TYPE, dtype);
m_ar.WriteChunk(PLT_DOM_PART_ID , mid);
m_ar.WriteChunk(PLT_DOM_ELEMS , elementCount);
}
m_ar.EndChunk();
// write the element list
int n[10];
m_ar.BeginChunk(PLT_DOM_ELEM_LIST);
{
for (int i=0; i<NE; ++i)
{
FEElement2D& el = dom.Element(i);
if (m_exportErodedElements || el.isActive())
{
n[0] = el.GetID();
for (int j = 0; j < ne; ++j) n[j + 1] = el.m_node[j];
m_ar.WriteChunk(PLT_ELEMENT, n, ne + 1);
}
}
}
m_ar.EndChunk();
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::BuildSurfaceTable()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
m_Surf.clear();
for (int ns = 0; ns < mesh.FacetSets(); ++ns)
{
FEFacetSet& s = mesh.FacetSet(ns);
int NF = s.Faces();
// find the max nodes
int maxNodes = 0;
for (int i = 0; i < NF; ++i)
{
FEFacetSet::FACET& el = s.Face(i);
if (el.ntype > maxNodes) maxNodes = el.ntype;
}
Surface surf;
surf.maxNodes = maxNodes;
surf.surf = &s;
m_Surf.push_back(surf);
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteSurfaceSection(FEMesh& m)
{
for (int ns = 0; ns< m_Surf.size(); ++ns)
{
Surface& surf = m_Surf[ns];
FEFacetSet& s = *surf.surf;
int NF = s.Faces();
int maxNodes = surf.maxNodes;
m_ar.BeginChunk(PLT_SURFACE);
{
m_ar.BeginChunk(PLT_SURFACE_HDR);
{
int sid = ns+1;
m_ar.WriteChunk(PLT_SURFACE_ID, sid);
m_ar.WriteChunk(PLT_SURFACE_FACES, NF);
m_ar.WriteChunk(PLT_SURFACE_NAME, s.GetName());
m_ar.WriteChunk(PLT_SURFACE_MAX_FACET_NODES, maxNodes);
}
m_ar.EndChunk();
m_ar.BeginChunk(PLT_FACE_LIST);
{
int n[FEElement::MAX_NODES + 2];
for (int i=0; i<NF; ++i)
{
FEFacetSet::FACET& f = s.Face(i);
int nf = f.Nodes();
n[0] = i+1;
n[1] = nf;
for (int i=0; i<nf; ++i) n[i+2] = f.node[i];
m_ar.WriteChunk(PLT_FACE, n, maxNodes + 2);
}
}
m_ar.EndChunk();
}
m_ar.EndChunk();
}
}
void FEBioPlotFile::WriteEdgeSection(FEMesh& m)
{
for (int i = 0; i < m.Edges(); ++i)
{
FEEdge& edge = m.Edge(i);
int NE = edge.Elements();
int maxNodes = 3;
m_ar.BeginChunk(PLT_EDGE);
{
m_ar.BeginChunk(PLT_EDGE_HDR);
{
int id = i + 1;
m_ar.WriteChunk(PLT_EDGE_ID, id);
m_ar.WriteChunk(PLT_EDGE_LINES, NE);
m_ar.WriteChunk(PLT_EDGE_NAME, edge.GetName());
m_ar.WriteChunk(PLT_EDGE_MAX_NODES, maxNodes);
}
m_ar.EndChunk();
m_ar.BeginChunk(PLT_EDGE_LIST);
{
int n[FEElement::MAX_NODES + 2];
for (int j = 0; j < NE; ++j)
{
FELineElement& el = edge.Element(j);
int ne = el.Nodes();
n[0] = i + 1;
n[1] = ne;
for (int i = 0; i < ne; ++i) n[i + 2] = el.m_node[i];
m_ar.WriteChunk(PLT_LINE, n, maxNodes + 2);
}
}
m_ar.EndChunk();
}
m_ar.EndChunk();
}
}
void FEBioPlotFile::WriteNodeSetSection(FEMesh& m)
{
for (int ns = 0; ns < m.NodeSets(); ++ns)
{
FENodeSet& l = *m.NodeSet(ns);
int nodes = l.Size();
m_ar.BeginChunk(PLT_NODESET);
{
m_ar.BeginChunk(PLT_NODESET_HDR);
{
int nid = ns+1;
m_ar.WriteChunk(PLT_NODESET_ID, nid);
m_ar.WriteChunk(PLT_NODESET_SIZE, nodes);
m_ar.WriteChunk(PLT_NODESET_NAME, l.GetName());
}
m_ar.EndChunk();
std::vector<int> nodeList(nodes);
for (int i = 0; i < nodes; ++i) nodeList[i] = l[i];
m_ar.WriteChunk(PLT_NODESET_LIST, nodeList);
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteElementSetSection(FEMesh& m)
{
for (int n = 0; n < m.ElementSets(); ++n)
{
FEElementSet& l = m.ElementSet(n);
int elems = l.Elements();
m_ar.BeginChunk(PLT_ELEMENTSET);
{
m_ar.BeginChunk(PLT_ELEMENTSET_HDR);
{
int nid = n + 1;
m_ar.WriteChunk(PLT_ELEMENTSET_ID, nid);
m_ar.WriteChunk(PLT_ELEMENTSET_SIZE, elems);
m_ar.WriteChunk(PLT_ELEMENTSET_NAME, l.GetName());
}
m_ar.EndChunk();
std::vector<int> elemList(elems);
for (int i = 0; i < elems; ++i) elemList[i] = l[i];
m_ar.WriteChunk(PLT_ELEMENTSET_LIST, elemList);
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteFacetSetSection(FEMesh& m)
{
for (int ns = 0; ns < m.FacetSets(); ++ns)
{
FEFacetSet& surf = m.FacetSet(ns);
int NF = surf.Faces();
m_ar.BeginChunk(PLT_FACETSET);
{
int maxNodes = FEFacetSet::FACET::MAX_NODES;
m_ar.BeginChunk(PLT_FACETSET_HDR);
{
int sid = ns + 1;
m_ar.WriteChunk(PLT_FACETSET_ID, sid);
m_ar.WriteChunk(PLT_FACETSET_SIZE, NF);
m_ar.WriteChunk(PLT_FACETSET_NAME, surf.GetName());
m_ar.WriteChunk(PLT_FACETSET_MAXNODES, maxNodes);
}
m_ar.EndChunk();
m_ar.BeginChunk(PLT_FACETSET_LIST);
{
int n[FEElement::MAX_NODES + 2];
for (int i = 0; i < NF; ++i)
{
FEFacetSet::FACET& f = surf.Face(i);
int nf = f.ntype; // this is the type and the nr. of nodes!
n[0] = i + 1;
n[1] = nf;
for (int i = 0; i < nf; ++i) n[i + 2] = f.node[i];
m_ar.WriteChunk(PLT_FACET, n, maxNodes + 2);
}
}
m_ar.EndChunk();
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WritePartsSection(FEModel& fem)
{
int NMAT = fem.Materials();
for (int i=0; i<NMAT; ++i)
{
FEMaterial* pm = fem.GetMaterial(i);
m_ar.BeginChunk(PLT_PART);
{
unsigned int nid = (unsigned int) pm->GetID();
char szname[STR_SIZE] = {0};
// Make sure that the material name fits in the buffer
std::string name = pm->GetName();
const char* sz = name.c_str();
int l = (int)strlen(sz);
if (l >= STR_SIZE) l = STR_SIZE - 1;
strncpy(szname, sz, l);
// write the material data
m_ar.WriteChunk(PLT_PART_ID, nid);
m_ar.WriteChunk(PLT_PART_NAME, szname, STR_SIZE);
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteObjectsSection()
{
for (int i = 0; i < m_Points.size(); ++i)
{
PointObject* po = GetPointObject(i);
m_ar.BeginChunk(PLT_POINT_OBJECT);
{
WriteObject(po);
}
m_ar.EndChunk();
}
for (int i = 0; i < m_Lines.size(); ++i)
{
LineObject* po = GetLineObject(i);
m_ar.BeginChunk(PLT_LINE_OBJECT);
{
WriteObject(po);
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteObject(PlotObject* po)
{
m_ar.WriteChunk(PLT_OBJECT_ID, po->m_id);
m_ar.WriteChunk(PLT_OBJECT_NAME, po->m_name.c_str());
m_ar.WriteChunk(PLT_OBJECT_TAG, po->m_tag);
vec3d& r = po->m_pos;
float f[3] = { (float)r.x, (float)r.y, (float)r.z };
m_ar.WriteChunk(PLT_OBJECT_POS, f, 3);
quatd q = po->m_rot;
float a[4] = { (float)q.x, (float)q.y, (float)q.z, (float)q.w };
m_ar.WriteChunk(PLT_OBJECT_ROT, a, 4);
if (dynamic_cast<LineObject*>(po))
{
LineObject* pl = dynamic_cast<LineObject*>(po);
vec3d r1 = pl->m_r1;
vec3d r2 = pl->m_r2;
float c[6] = { (float)r1.x, (float)r1.y, (float)r1.z, (float)r2.x, (float)r2.y, (float)r2.z };
m_ar.WriteChunk(PLT_LINE_COORDS, c, 6);
}
list<DICTIONARY_ITEM>::iterator it = po->m_data.begin();
for (int j = 0; j < po->m_data.size(); ++j, ++it)
{
m_ar.BeginChunk(PLT_OBJECT_DATA);
{
WriteDictionaryItem(*it);
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::Write(float ftime, int flag)
{
feLogDebug("writing to plot file; time = %lg; flag = %d", ftime, flag);
FEModel& fem = *GetFEModel();
PlotFile::Dictionary& dic = GetDictionary();
// compress these sections if requested
m_ar.SetCompression(m_ncompress);
m_ar.BeginChunk(PLT_STATE);
{
// state header
m_ar.BeginChunk(PLT_STATE_HEADER);
{
m_ar.WriteChunk(PLT_STATE_HDR_TIME, ftime);
m_ar.WriteChunk(PLT_STATE_STATUS, flag);
}
m_ar.EndChunk();
// write the state flags of the mesh
m_ar.BeginChunk(PLT_MESH_STATE);
{
WriteMeshState(fem.GetMesh());
}
m_ar.EndChunk();
m_ar.BeginChunk(PLT_STATE_DATA);
{
// Global Data
if (dic.GlobalVariables() > 0)
{
m_ar.BeginChunk(PLT_GLOBAL_DATA);
{
WriteGlobalData(fem);
}
m_ar.EndChunk();
}
// Node Data
if (dic.NodalVariables() > 0)
{
m_ar.BeginChunk(PLT_NODE_DATA);
{
WriteNodeData(fem);
}
m_ar.EndChunk();
}
// Element Data
if (dic.DomainVariables() > 0)
{
m_ar.BeginChunk(PLT_ELEMENT_DATA);
{
WriteDomainData(fem);
}
m_ar.EndChunk();
}
// surface data
if (dic.SurfaceVariables() > 0)
{
m_ar.BeginChunk(PLT_FACE_DATA);
{
WriteSurfaceData(fem);
}
m_ar.EndChunk();
}
// edge data
if (dic.EdgeVariables() > 0)
{
m_ar.BeginChunk(PLT_EDGE_DATA);
{
WriteEdgeData(fem);
}
m_ar.EndChunk();
}
}
m_ar.EndChunk();
if (m_Points.size() > 0)
{
m_ar.BeginChunk(PLT_OBJECTS_STATE);
{
WriteObjectsState();
}
m_ar.EndChunk();
}
}
m_ar.EndChunk();
return true;
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteGlobalData(FEModel& fem)
{
PlotFile::Dictionary& dic = GetDictionary();
auto& globData = dic.GlobalVariableList();
list<DICTIONARY_ITEM>::iterator it = globData.begin();
for (int i = 0; i < (int)globData.size(); ++i, ++it)
{
m_ar.BeginChunk(PLT_STATE_VARIABLE);
{
unsigned int nid = i + 1;
m_ar.WriteChunk(PLT_STATE_VAR_ID, nid);
m_ar.BeginChunk(PLT_STATE_VAR_DATA);
{
if (it->m_psave) WriteGlobalDataField(fem, it->m_psave);
}
m_ar.EndChunk();
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteNodeData(FEModel& fem)
{
PlotFile::Dictionary& dic = GetDictionary();
auto& nodeData = dic.NodalVariableList();
list<DICTIONARY_ITEM>::iterator it = nodeData.begin();
for (int i=0; i<(int)nodeData.size(); ++i, ++it)
{
m_ar.BeginChunk(PLT_STATE_VARIABLE);
{
unsigned int nid = i+1;
m_ar.WriteChunk(PLT_STATE_VAR_ID, nid);
m_ar.BeginChunk(PLT_STATE_VAR_DATA);
{
if (it->m_psave) WriteNodeDataField(fem, it->m_psave);
}
m_ar.EndChunk();
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteDomainData(FEModel& fem)
{
PlotFile::Dictionary& dic = GetDictionary();
auto& elemData = dic.DomainVariableList();
list<DICTIONARY_ITEM>::iterator it = elemData.begin();
for (int i=0; i<(int)elemData.size(); ++i, ++it)
{
m_ar.BeginChunk(PLT_STATE_VARIABLE);
{
unsigned int nid = i+1;
m_ar.WriteChunk(PLT_STATE_VAR_ID, nid);
m_ar.BeginChunk(PLT_STATE_VAR_DATA);
{
if (it->m_psave) WriteDomainDataField(fem, it->m_psave);
}
m_ar.EndChunk();
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteSurfaceData(FEModel& fem)
{
PlotFile::Dictionary& dic = GetDictionary();
auto& surfData = dic.SurfaceVariableList();
list<DICTIONARY_ITEM>::iterator it = surfData.begin();
for (int i=0; i<(int)surfData.size(); ++i, ++it)
{
m_ar.BeginChunk(PLT_STATE_VARIABLE);
{
unsigned int nid = i+1;
m_ar.WriteChunk(PLT_STATE_VAR_ID, nid);
m_ar.BeginChunk(PLT_STATE_VAR_DATA);
{
if (it->m_psave) WriteSurfaceDataField(fem, it->m_psave);
}
m_ar.EndChunk();
}
m_ar.EndChunk();
}
}
void FEBioPlotFile::WriteEdgeData(FEModel& fem)
{
PlotFile::Dictionary& dic = GetDictionary();
auto& edgeData = dic.EdgeVariableList();
list<DICTIONARY_ITEM>::iterator it = edgeData.begin();
for (int i = 0; i < (int)edgeData.size(); ++i, ++it)
{
m_ar.BeginChunk(PLT_STATE_VARIABLE);
{
unsigned int nid = i + 1;
m_ar.WriteChunk(PLT_STATE_VAR_ID, nid);
m_ar.BeginChunk(PLT_STATE_VAR_DATA);
{
if (it->m_psave) WriteEdgeDataField(fem, it->m_psave);
}
m_ar.EndChunk();
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteGlobalDataField(FEModel& fem, FEPlotData* pd)
{
int ndata = pd->VarSize(pd->DataType());
FEDataStream a; a.reserve(ndata);
if (pd->Save(a))
{
// pad mismatches
assert(a.size() == ndata);
if (a.size() != ndata) a.resize(ndata, 0.f);
m_ar.WriteData(0, a.data());
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteNodeDataField(FEModel &fem, FEPlotData* pd)
{
// loop over all node sets
// right now there is only one, namely the node set of all mesh nodes
// so we just pass the mesh
int ndata = pd->VarSize(pd->DataType());
int N = fem.GetMesh().Nodes();
FEDataStream a; a.reserve(ndata*N);
if (pd->Save(fem.GetMesh(), a))
{
// pad mismatches
assert(a.size() == N*ndata);
if (a.size() != N * ndata) a.resize(N*ndata, 0.f);
m_ar.WriteData(0, a.data());
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteSurfaceDataField(FEModel& fem, FEPlotData* pd)
{
// get the domain name (if any)
string domName;
const char* szdom = pd->GetDomainName();
if (szdom) domName = szdom;
// loop over all surfaces
FEMesh& m = fem.GetMesh();
for (int i = 0; i<m_Surf.size(); ++i)
{
FEFacetSet& facetSet = *m_Surf[i].surf;
int maxNodes = m_Surf[i].maxNodes;
if (domName.empty() || (domName == facetSet.GetName()))
{
// Find the surface with the same name
FESurface* surf = m.FindSurface(facetSet.GetName());
if (surf)
{
FESurface& S = *surf;
// Determine data size.
// Note that for the FMT_MULT case we are
// assuming 9 data entries per facet
// regardless of the nr of nodes a facet really has
// this is because for surfaces, all elements are not
// necessarily of the same type
// TODO: Fix the assumption of the FMT_MULT
int datasize = pd->VarSize(pd->DataType());
int nsize = datasize;
switch (pd->StorageFormat())
{
case FMT_NODE: nsize *= S.Nodes(); break;
case FMT_ITEM: nsize *= S.Elements(); break;
case FMT_MULT: nsize *= maxNodes * S.Elements(); break;
case FMT_REGION:
// one value per surface so nsize remains unchanged
break;
default:
assert(false);
}
// save data
FEDataStream a; a.reserve(nsize);
if (pd->Save(S, a))
{
// in FEBio 3.0, the data streams are assumed to have no padding, but for now we still need to pad
// the data stream before we write it to the file
if (a.size() == nsize)
{
// assumed padding is already there, or not needed
m_ar.WriteData(i + 1, a.data());
}
else
{
// this is only needed for FMT_MULT storage
assert(pd->StorageFormat() == FMT_MULT);
// add padding
const int M = maxNodes;
int m = 0;
FEDataStream b; b.assign(nsize, 0.f);
for (int n = 0; n < S.Elements(); ++n)
{
FESurfaceElement& el = S.Element(n);
int ne = el.Nodes();
for (int j = 0; j < ne; ++j)
{
for (int k = 0; k < datasize; ++k) b[n * M * datasize + j * datasize + k] = a[m++];
}
}
// write the padded data
m_ar.WriteData(i + 1, b.data());
}
}
}
}
}
}
void FEBioPlotFile::WriteEdgeDataField(FEModel& fem, FEPlotData* pd)
{
// get the edge name (if any)
string domName;
const char* szdom = pd->GetDomainName();
if (szdom) domName = szdom;
// loop over all edges
FEMesh& m = fem.GetMesh();
for (int i = 0; i < m.Edges(); ++i)
{
FEEdge& edge = m.Edge(i);
int maxNodes = 3;
// Determine data size.
// Note that for the FMT_MULT case we are
// assuming 9 data entries per facet
// regardless of the nr of nodes a facet really has
// this is because for surfaces, all elements are not
// necessarily of the same type
// TODO: Fix the assumption of the FMT_MULT
int datasize = pd->VarSize(pd->DataType());
int nsize = datasize;
switch (pd->StorageFormat())
{
case FMT_NODE: nsize *= edge.Nodes(); break;
case FMT_ITEM: nsize *= edge.Elements(); break;
case FMT_MULT: nsize *= maxNodes * edge.Elements(); break;
case FMT_REGION:
// one value per edge so nsize remains unchanged
break;
default:
assert(false);
}
// save data
FEDataStream a; a.reserve(nsize);
if (pd->Save(edge, a))
{
// in FEBio 3.0, the data streams are assumed to have no padding, but for now we still need to pad
// the data stream before we write it to the file
if (a.size() == nsize)
{
// assumed padding is already there, or not needed
m_ar.WriteData(i + 1, a.data());
}
else
{
// this is only needed for FMT_MULT storage
assert(pd->StorageFormat() == FMT_MULT);
// add padding
const int M = maxNodes;
int m = 0;
FEDataStream b; b.assign(nsize, 0.f);
for (int n = 0; n < edge.Elements(); ++n)
{
FELineElement& el = edge.Element(n);
int ne = el.Nodes();
for (int j = 0; j < ne; ++j)
{
for (int k = 0; k < datasize; ++k) b[n * M * datasize + j * datasize + k] = a[m++];
}
}
// write the padded data
m_ar.WriteData(i + 1, b.data());
}
}
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteDomainDataField(FEModel &fem, FEPlotData* pd)
{
FEMesh& m = fem.GetMesh();
int ND = m.Domains();
// if the item list is empty, store all domains
vector<int> item = pd->GetItemList();
if (item.empty())
{
for (int i = 0; i<ND; ++i) item.push_back(i);
}
// allow plot data to prepare for save
if (pd->PreSave() == false)
{
assert(false);
return;
}
// get the domain name (if any)
string domName;
const char* szdom = pd->GetDomainName();
if (szdom) domName = szdom;
// loop over all domains in the item list
for (int i = 0; i<ND; ++i)
{
// get the domain
FEDomain& D = m.Domain(item[i]);
if (domName.empty() || (D.GetName() == domName))
{
// calculate the size of the data vector
int nsize = pd->VarSize(pd->DataType());
switch (pd->StorageFormat())
{
case FMT_NODE: nsize *= D.Nodes(); break;
case FMT_ITEM: nsize *= D.Elements(); break;
case FMT_MULT:
{
// since all elements have the same type within a domain
// we just grab the number of nodes of the first element
// to figure out how much storage we need
FEElement& e = D.ElementRef(0);
int n = e.Nodes();
nsize *= n * D.Elements();
}
break;
case FMT_REGION:
// one value for this domain so nsize remains unchanged
break;
default:
assert(false);
}
assert(nsize > 0);
// fill data vector and save
FEDataStream a;
a.reserve(nsize);
if (pd->Save(D, a))
{
assert(a.size() == nsize);
m_ar.WriteData(item[i] + 1, a.data());
}
}
}
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::Append(const char *szfile)
{
// try to open the file
if (m_ar.Open(szfile) == false) return false;
FEModel* fem = GetFEModel();
FEPlotDataStore& pltData = fem->GetPlotDataStore();
SetCompression(pltData.GetPlotCompression());
// add plot variables
for (int n = 0; n < pltData.PlotVariables(); ++n)
{
FEPlotVariable& vi = pltData.GetPlotVariable(n);
const std::string& varName = vi.Name();
const std::string& domName = vi.DomainName();
// add the plot output variable
if (AddVariable(varName.c_str(), vi.m_item, domName.c_str()) == false)
{
feLog("FATAL ERROR: Output variable \"%s\" is not defined\n", varName.c_str());
throw "FATAL ERROR";
}
}
// NOTE: Reading the dictionary rebuilds the plot variables too, but
// there is not enough data in the dictionary to do that correctly.
// So, we should probably rely on the data store, which gets serialized to the dump file.
// open the root element
bool bok = true;
/* m_ar.OpenChunk();
unsigned int nid = m_ar.GetChunkID();
if (nid != PLT_ROOT) return false;
bok = false;
while (m_ar.OpenChunk() == IO_OK)
{
nid = m_ar.GetChunkID();
if (nid == PLT_DICTIONARY)
{
// read the dictionary
bok = ReadDictionary();
break;
}
m_ar.CloseChunk();
}
*/
// close it again ...
m_ar.Close();
// rebuild the surface table
BuildSurfaceTable();
// ... and open for appending
if (bok) return m_ar.Append(szfile);
return false;
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::ReadDictionary()
{
PlotFile::Dictionary& dic = GetDictionary();
dic.Clear();
while (m_ar.OpenChunk() == IO_OK)
{
unsigned int nid = m_ar.GetChunkID();
switch (nid)
{
case PLT_DIC_GLOBAL: assert(false); return false;
case PLT_DIC_NODAL : ReadDicList(); break;
case PLT_DIC_DOMAIN : ReadDicList(); break;
case PLT_DIC_SURFACE: ReadDicList(); break;
default:
assert(false);
return false;
}
m_ar.CloseChunk();
}
return true;
}
//-----------------------------------------------------------------------------
bool FEBioPlotFile::ReadDicList()
{
vector<int> l; // empty item list
while (m_ar.OpenChunk() == IO_OK)
{
unsigned int nid = m_ar.GetChunkID();
if (nid == PLT_DIC_ITEM)
{
while (m_ar.OpenChunk() == IO_OK)
{
unsigned int nid = m_ar.GetChunkID();
if (nid == PLT_DIC_ITEM_NAME)
{
char sz[STR_SIZE];
m_ar.read(sz, STR_SIZE);
AddVariable(sz, l);
}
m_ar.CloseChunk();
}
}
else return false;
m_ar.CloseChunk();
}
return true;
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteMeshState(FEMesh& mesh)
{
vector<unsigned int> flags;
flags.reserve(mesh.Elements());
int NDOM = mesh.Domains();
for (int i = 0; i < NDOM; ++i)
{
FEDomain& dom = mesh.Domain(i);
int NE = dom.Elements();
for (int j = 0; j < NE; ++j)
{
FEElement& el = dom.ElementRef(j);
if (m_exportErodedElements || el.isActive())
{
unsigned int status = el.status();
flags.push_back(status);
}
}
}
m_ar.WriteChunk(PLT_ELEMENT_STATE, flags);
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteObjectsState()
{
for (int i = 0; i < PointObjects(); ++i)
{
PointObject* po = m_Points[i];
m_ar.BeginChunk(PLT_POINT_OBJECT);
{
m_ar.WriteChunk(PLT_OBJECT_ID, po->m_id);
vec3d r = po->m_pos;
float f[3] = { (float)r.x, (float)r.y, (float)r.z };
m_ar.WriteChunk(PLT_OBJECT_POS, f, 3);
quatd q = po->m_rot;
float a[4] = { (float)q.x, (float)q.y, (float)q.z, (float)q.w };
m_ar.WriteChunk(PLT_OBJECT_ROT, a, 4);
r = po->m_r;
float c[3] = { (float)r.x, (float)r.y, (float)r.z };
m_ar.WriteChunk(PLT_POINT_COORD, c, 3);
m_ar.BeginChunk(PLT_OBJECT_DATA);
{
WriteObjectData(po);
}
m_ar.EndChunk();
}
m_ar.EndChunk();
}
for (int i = 0; i < m_Lines.size(); ++i)
{
LineObject* po = GetLineObject(i);
m_ar.BeginChunk(PLT_LINE_OBJECT);
{
m_ar.WriteChunk(PLT_OBJECT_ID, po->m_id);
vec3d r = po->m_pos;
float f[3] = { (float)r.x, (float)r.y, (float)r.z };
m_ar.WriteChunk(PLT_OBJECT_POS, f, 3);
quatd q = po->m_rot;
float a[4] = { (float)q.x, (float)q.y, (float)q.z, (float)q.w };
m_ar.WriteChunk(PLT_OBJECT_ROT, a, 4);
vec3d r1 = po->m_r1;
vec3d r2 = po->m_r2;
float c[6] = { (float)r1.x, (float)r1.y, (float)r1.z, (float)r2.x, (float)r2.y, (float)r2.z };
m_ar.WriteChunk(PLT_LINE_COORDS, c, 6);
m_ar.BeginChunk(PLT_OBJECT_DATA);
{
WriteObjectData(po);
}
m_ar.EndChunk();
}
m_ar.EndChunk();
}
}
//-----------------------------------------------------------------------------
void FEBioPlotFile::WriteObjectData(PlotObject* po)
{
list<DICTIONARY_ITEM>::iterator it = po->m_data.begin();
for (int j = 0; j < po->m_data.size(); ++j, ++it)
{
assert(it->m_psave);
FEPlotObjectData* pd = dynamic_cast<FEPlotObjectData*>(it->m_psave); assert(pd);
FEDataStream a;
if (pd->Save(po, a))
{
m_ar.WriteData(j, a.data());
}
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioStepSection3.cpp | .cpp | 2,592 | 73 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEBioStepSection3.h"
#include "FEBioControlSection3.h"
#include "FEBioInitialSection3.h"
#include "FEBioBoundarySection3.h"
#include "FEBioLoadsSection.h"
#include "FEBioConstraintsSection.h"
#include "FEBioContactSection.h"
#include "FEBioRigidSection.h"
#include "FEBioMeshAdaptorSection.h"
//-----------------------------------------------------------------------------
FEBioStepSection3::FEBioStepSection3(FEFileImport* pim) : FEFileSection(pim) {}
//-----------------------------------------------------------------------------
void FEBioStepSection3::Parse(XMLTag& tag)
{
// Build the file section map
FEFileImport* imp = GetFileReader();
FEFileSectionMap Map;
Map["Control" ] = new FEBioControlSection3(imp);
Map["Initial" ] = new FEBioInitialSection3(imp);
Map["Boundary" ] = new FEBioBoundarySection3(imp);
Map["Loads" ] = new FEBioLoadsSection3(imp);
Map["Constraints"] = new FEBioConstraintsSection25(imp);
Map["Contact" ] = new FEBioContactSection25(imp);
Map["Rigid" ] = new FEBioRigidSection(imp);
Map["MeshAdaptor"] = new FEBioMeshAdaptorSection(imp);
++tag;
do
{
if (tag == "step")
{
// create next step
GetBuilder()->NextStep();
// parse the file sections
Map.Parse(tag);
}
++tag;
}
while (!tag.isend());
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/XMLReader.h | .h | 9,655 | 344 | /*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 <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <string>
#include <vector>
#include <stdexcept>
#include <assert.h>
#include "febioxml_api.h"
//-------------------------------------------------------------------------
// forward declaration
class XMLReader;
//-------------------------------------------------------------------------
//! This class represents a xml-attribute
class FEBIOXML_API XMLAtt
{
public:
//! constructor
XMLAtt();
//! comparison operators
bool operator == (const char* sz);
bool operator != (const char* szval);
//! Get the attribute name
const char* name() { return m_name.c_str(); }
//! Get the attribute value
const char* cvalue() { return m_val.c_str(); }
public:
void value(int& val) { val = atoi(m_val.c_str()); }
int value(int* v, int n);
int value(double* v, int n);
template <typename T> T value() { return T(0); }
public:
std::string m_name;
std::string m_val;
bool m_bvisited; //!< was the attribute processed or not?
};
template <> inline int XMLAtt::value<int>() { return atoi(m_val.c_str()); }
template <> inline double XMLAtt::value<double>() { return atof(m_val.c_str()); }
template <> inline std::string XMLAtt::value<std::string>() { return m_val; }
//-------------------------------------------------------------------------
//! This class implements a xml-tag. The value and attributes of this tag
//! can be queried.
//! \todo I would like to get rid of the m_szroot element and replace it with a
//! parent tag. The root element can then be identified by the tag that
//! does not have a parent
class FEBIOXML_API XMLTag
{
public:
std::string m_sztag; // tag name
std::string m_szval; // tag value
std::vector<XMLAtt> m_att; // attribute list
std::vector<std::string> m_path; // current path (name tags of parents)
XMLReader* m_preader; // pointer to reader
int64_t m_fpos; // file position of next tag
int m_nstart_line; // line number at beginning of tag
int m_ncurrent_line; // current line number
bool m_bend; // end tag flag
bool m_bleaf; // this is a leaf (i.e. has no child elements)
bool m_bempty; // empty tag (i.e. no value)
public:
XMLTag();
void clear();
int currentLine() const { return m_ncurrent_line; }
bool operator == (const char* sztag) { return (strcmp(sztag, m_sztag.c_str()) == 0); }
bool operator != (const char* sztag) { return (strcmp(sztag, m_sztag.c_str()) != 0); }
void operator ++ ();
void skip();
bool isend() { return m_bend; }
bool isleaf() { return m_bleaf; }
bool isempty() { return m_bempty; }
// count the number of children
int children();
const char* AttributeValue(const char* szat, bool bopt = false);
XMLAtt* AttributePtr(const char* szat);
XMLAtt* Attribute(const char* szat, bool bopt);
XMLAtt& Attribute(const char* szat);
template <typename T> T AttributeValue(const char* szatt, const T& def_val) { return def_val; }
bool AttributeValue(const char* szat, int& n, bool bopt = false);
bool AttributeValue(const char* szat, double& d, bool bopt = false);
const char* Name() { return m_sztag.c_str(); }
void value(double& val) { val = atof(m_szval.c_str()); }
void value(float& val) { val = (float) atof(m_szval.c_str()); }
void value(int& val) { val = atoi(m_szval.c_str()); }
void value(long& val) { val = (long) atoi(m_szval.c_str()); }
void value(short& val) { val = (short) atoi(m_szval.c_str()); }
int value(double* pf, int n);
int value(float* pf, int n);
int value(int* pi, int n);
int value(std::vector<std::string>& stringList, int n);
void value(std::vector<std::string>& stringList);
void value(bool& val);
void value(char* szstr);
void value(std::string& val);
void value(std::vector<int>& l);
void value2(std::vector<int>& l);
void value(std::vector<double>& l);
template <class T> void value(T& v);
const char* szvalue() { return m_szval.c_str(); }
std::string relpath(const char* szroot) const;
const std::string& comment();
const void clearComment();
};
template <> inline int XMLTag::AttributeValue<int>(const char* szatt, const int& def_val)
{
XMLAtt* pa = AttributePtr(szatt);
if (pa) return pa->value<int>();
else return def_val;
}
template <> inline double XMLTag::AttributeValue<double >(const char* szatt, const double& def_val)
{
XMLAtt* pa = AttributePtr(szatt);
if (pa) return pa->value<double>();
else return def_val;
}
template <> inline std::string XMLTag::AttributeValue<std::string>(const char* szatt, const std::string& def_val)
{
XMLAtt* pa = AttributePtr(szatt);
if (pa) return pa->value<std::string>();
else return def_val;
}
//-----------------------------------------------------------------------------
//! This class implements a reader for XML files
class FEBIOXML_API XMLReader
{
public:
enum {BUF_SIZE = 32768};
public:
// Base class for Exceptions
class Error : public std::runtime_error
{
public:
Error(const std::string& err) : std::runtime_error(err) {}
Error(XMLTag& tag, const std::string& err);
};
// the end of file was detected unexpectedly.
class UnexpectedEOF : public Error {
public:
UnexpectedEOF() : Error("Unexpected end of file") {}
};
// A syntax error was found
class FEBIOXML_API XMLSyntaxError : public Error
{
public:
XMLSyntaxError(int line_number = -1);
};
// an end tag was not matched
class FEBIOXML_API UnmatchedEndTag : public Error
{
public:
UnmatchedEndTag(XMLTag& t);
};
// an unknown tag was encountered
class FEBIOXML_API InvalidTag : public Error
{
public:
InvalidTag(XMLTag& t);
};
// The value of a tag was invald
class FEBIOXML_API InvalidValue : public Error
{
public:
InvalidValue(XMLTag& t);
};
// the value of an attribute was invalid
class FEBIOXML_API InvalidAttributeValue : public Error
{
public:
InvalidAttributeValue(XMLTag& t, const char* sza, const char* szv = 0);
InvalidAttributeValue(XMLTag& t, XMLAtt& att);
};
// an attribute is invalid
class FEBIOXML_API InvalidAttribute : public Error
{
public:
InvalidAttribute(XMLTag& t, const char* sza);
};
// an attribute was missing
class FEBIOXML_API MissingAttribute : public Error
{
public:
MissingAttribute(XMLTag& t, const char* sza);
};
class FEBIOXML_API MissingTag : public Error
{
public:
MissingTag(XMLTag& t, const char* szt);
};
//------------------------
public:
//! constructor/destructor
XMLReader();
virtual ~XMLReader();
std::ifstream* GetFileStream();
//! Open the xml file
bool Open(const char* szfile, bool checkForXMLTag = true);
//! Pass xml formatted string to reader
bool OpenString(std::string& xml, bool checkForXMLTag = true);
//! Close the xml file
void Close();
//! Find a tag
bool FindTag(const char* xpath, XMLTag& tag);
//! Get the next tag
void NextTag(XMLTag& tag);
//! return the current line
int GetCurrentLine();
//! Skip a tag
void SkipTag(XMLTag& tag);
const std::string& GetLastComment();
protected: // helper functions
//! Get the next character in the file
char GetChar();
//! Read a tag
void ReadTag(XMLTag& tag);
//! Read the value of a tag
void ReadValue(XMLTag& tag);
//! process end tag
void ReadEndTag(XMLTag& tag);
//! read the next character of the buffer
char readNextChar();
//! get the current position
int64_t currentPos();
//! move the file pointer
void rewind(int64_t nstep);
// only used for processing comments
char GetNextChar();
protected:
std::istream* m_stream;
int m_nline; //!< current line (used only as temp storage)
int64_t m_currentPos; //!< current file position
std::string m_comment; //!< last comment that was read
char* m_buf;
int64_t m_bufIndex, m_bufSize;
bool m_eof;
};
//-----------------------------------------------------------------------------
// some inline functions
inline void XMLTag::operator ++ () { m_preader->NextTag(*this); }
inline void XMLTag::skip() { m_preader->SkipTag(*this); }
inline const std::string& XMLTag::comment() { return m_preader->GetLastComment(); }
//-----------------------------------------------------------------------------
// mechanism for using custom types with XMLReader.
template <class T> void string_to_type(const std::string& s, T& v) { assert(false); }
template <class T> void XMLTag::value(T& v) { string_to_type(m_szval, v); }
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FEBioMeshSection4.h | .h | 2,196 | 56 | /*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 "FEBioImport.h"
#include "FEBModel.h"
//-----------------------------------------------------------------------------
// Mesh section
class FEBioMeshSection4 : public FEBioFileSection
{
public:
FEBioMeshSection4(FEBioImport* pim);
void Parse(XMLTag& tag);
protected:
void ParseNodeSection (XMLTag& tag, FEBModel::Part* part);
void ParseSurfaceSection (XMLTag& tag, FEBModel::Part* part);
void ParseElementSection (XMLTag& tag, FEBModel::Part* part);
void ParseNodeSetSection (XMLTag& tag, FEBModel::Part* part);
void ParseElementSetSection (XMLTag& tag, FEBModel::Part* part);
void ParsePartListSection (XMLTag& tag, FEBModel::Part* part);
void ParseEdgeSection (XMLTag& tag, FEBModel::Part* part);
void ParseSurfacePairSection(XMLTag& tag, FEBModel::Part* part);
void ParseDiscreteSetSection(XMLTag& tag, FEBModel::Part* part);
private:
int m_maxNodeId;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FEBioMeshSection.h | .h | 2,444 | 66 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEBioImport.h"
#include "FEBModel.h"
//-----------------------------------------------------------------------------
// Mesh section
class FEBioMeshSection : public FEBioFileSection
{
public:
FEBioMeshSection(FEBioImport* pim);
void Parse(XMLTag& tag);
protected:
void ParseNodeSection (XMLTag& tag, FEBModel::Part* part);
void ParseSurfaceSection (XMLTag& tag, FEBModel::Part* part);
void ParseElementSection (XMLTag& tag, FEBModel::Part* part);
void ParseNodeSetSection (XMLTag& tag, FEBModel::Part* part);
void ParseElementSetSection (XMLTag& tag, FEBModel::Part* part);
void ParseEdgeSection (XMLTag& tag, FEBModel::Part* part);
void ParseSurfacePairSection(XMLTag& tag, FEBModel::Part* part);
void ParseDiscreteSetSection(XMLTag& tag, FEBModel::Part* part);
};
//-----------------------------------------------------------------------------
// MeshDomains section
class FEBioMeshDomainsSection : public FEBioFileSection
{
public:
FEBioMeshDomainsSection(FEBioImport* pim);
void Parse(XMLTag& tag);
protected:
void ParseSolidDomainSection(XMLTag& tag);
void ParseShellDomainSection(XMLTag& tag);
};
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FERestartImport.h | .h | 2,056 | 60 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FileImport.h"
#include <FEBioXML/XMLReader.h>
//-----------------------------------------------------------------------------
class FERestartControlSection : public FEFileSection
{
public:
FERestartControlSection(FEFileImport* reader) : FEFileSection(reader) {}
void Parse(XMLTag& tag);
};
//-----------------------------------------------------------------------------
//! Restart input file reader.
class FEBIOXML_API FERestartImport : public FEFileImport
{
public:
FERestartImport();
virtual ~FERestartImport();
bool Load(FEModel& fem, const char* szfile);
int StepsAdded() const;
public:
char m_szdmp[256]; // user defined restart file name
protected:
XMLReader m_xml; // the file reader
int m_newSteps; // nr of new steps added
};
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FEBioInitialSection.h | .h | 1,821 | 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 "FEBioImport.h"
//-----------------------------------------------------------------------------
// Initial Section
class FEBioInitialSection : public FEFileSection
{
public:
FEBioInitialSection(FEFileImport* pim) : FEFileSection(pim){}
void Parse(XMLTag& tag);
};
//-----------------------------------------------------------------------------
// Initial Section
class FEBioInitialSection25 : public FEFileSection
{
public:
FEBioInitialSection25(FEFileImport* pim) : FEFileSection(pim){}
void Parse(XMLTag& tag);
};
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FEBioIncludeSection.h | .h | 1,592 | 40 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEBioImport.h"
//-----------------------------------------------------------------------------
// Include section (new in version 2.0)
class FEBioIncludeSection : public FEBioFileSection
{
public:
FEBioIncludeSection(FEBioImport* pim) : FEBioFileSection(pim){}
void Parse(XMLTag& tag);
};
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FEBioMeshDomainsSection4.cpp | .cpp | 12,537 | 441 | /*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 "FEBioMeshDomainsSection4.h"
#include <FECore/FESolidDomain.h>
#include <FECore/FEShellDomain.h>
#include <FECore/FETrussDomain.h>
#include <FECore/FEDomain2D.h>
#include <FECore/FEModel.h>
#include <FECore/FEMaterial.h>
#include <FECore/FECoreKernel.h>
#include <sstream>
FEBioMeshDomainsSection4::FEBioMeshDomainsSection4(FEBioImport* pim) : FEBioFileSection(pim)
{
m_noff = 0;
}
void FEBioMeshDomainsSection4::Parse(XMLTag& tag)
{
// build the node ID lookup table
BuildNLT();
// read all sections
if (tag.isleaf() == false)
{
++tag;
do
{
if (tag == "SolidDomain") ParseSolidDomainSection(tag);
else if (tag == "ShellDomain") ParseShellDomainSection(tag);
else if (tag == "BeamDomain" ) ParseBeamDomainSection(tag);
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
// let's build the part
FEBModel& feb = GetBuilder()->GetFEBModel();
FEBModel::Part* part = feb.GetPart(0); assert(part);
if (feb.BuildPart(*GetFEModel(), *part, false) == false)
{
throw XMLReader::Error("Failed building parts.");
}
// tell the file reader to rebuild the node ID table
GetBuilder()->BuildNodeList();
// At this point the mesh is completely read in.
// allocate material point data
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
for (int i = 0; i < mesh.Domains(); ++i)
{
FEDomain& dom = mesh.Domain(i);
dom.CreateMaterialPointData();
}
// Now we can allocate the degrees of freedom.
int MAX_DOFS = fem.GetDOFS().GetTotalDOFS();
fem.GetMesh().SetDOFS(MAX_DOFS);
}
void FEBioMeshDomainsSection4::BuildNLT()
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
FEBModel& feb = GetBuilder()->GetFEBModel();
FEBModel::Part* part = feb.GetPart(0); assert(part);
if (part == nullptr) return;
// build node-index lookup table
int noff = -1, maxID = 0;
int N0 = mesh.Nodes();
int NN = part->Nodes();
for (int i = 0; i < NN; ++i)
{
int nid = part->GetNode(i).id;
if ((noff < 0) || (nid < noff)) noff = nid;
if (nid > maxID) maxID = nid;
}
m_NLT.assign(maxID - noff + 1, -1);
for (int i = 0; i < NN; ++i)
{
int nid = part->GetNode(i).id - noff;
m_NLT[nid] = i + N0;
}
m_noff = noff;
}
void FEBioMeshDomainsSection4::ParseSolidDomainSection(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
FEBModel& feb = GetBuilder()->GetFEBModel();
FEBModel::Part* part = feb.GetPart(0); assert(part);
if (part == nullptr) throw XMLReader::InvalidTag(tag);
// get the domain name
const char* szname = tag.AttributeValue("name");
FEBModel::Domain* partDomain = part->FindDomain(szname);
if (partDomain == nullptr) throw XMLReader::InvalidAttributeValue(tag, "name", szname);
// get the material name
const char* szmat = tag.AttributeValue("mat");
FEMaterial* mat = fem.FindMaterial(szmat);
if (mat == nullptr) throw XMLReader::InvalidAttributeValue(tag, "mat", szmat);
// set the material name
partDomain->SetMaterialName(szmat);
// see if the element type is specified
const char* szelem = tag.AttributeValue("elem_type", true);
if (szelem && (strcmp(szelem, "default") != 0))
{
FE_Element_Spec elemSpec = partDomain->ElementSpec();
FE_Element_Spec newSpec = GetBuilder()->ElementSpec(szelem);
// make sure it's valid
if ((FEElementLibrary::IsValid(newSpec) == false) || (elemSpec.eshape != newSpec.eshape))
{
throw XMLReader::InvalidAttributeValue(tag, "elem_type", szelem);
}
partDomain->SetElementSpec(newSpec);
}
// get the (optional) type attribute
const char* sztype = tag.AttributeValue("type", true);
// --- build the domain ---
// we'll need the kernel for creating domains
FECoreKernel& febio = FECoreKernel::GetInstance();
// element count
int elems = partDomain->Elements();
// get the element spect
FE_Element_Spec spec = partDomain->ElementSpec();
// create the domain
FEDomain* dom = nullptr;
if (sztype)
{
// if the type attribute is defined, try to allocate the domain class directly.
dom = febio.CreateDomainExplicit(FESOLIDDOMAIN_ID, sztype, &fem);
if (dom == nullptr) throw XMLReader::InvalidAttributeValue(tag, sztype);
dom->SetMaterial(mat);
}
else
{
// if not, then use "old" logic, which tries to match the domain using the
// domain factories.
dom = febio.CreateDomain(spec, &mesh, mat);
if (dom == 0) throw XMLReader::InvalidTag(tag);
}
// add it to the mesh
mesh.AddDomain(dom);
// Allocate elements
if (dom->Create(elems, spec) == false)
{
throw XMLReader::InvalidTag(tag);
}
// assign the material
dom->SetMatID(mat->GetID() - 1);
// get the part name
string partName = part->Name();
if (partName.empty() == false) partName += ".";
string domName = partName + partDomain->Name();
dom->SetName(domName);
// read additional parameters
if (tag.isleaf() == false)
{
ReadParameterList(tag, dom);
}
// process element data
for (int j = 0; j < elems; ++j)
{
const FEBModel::ELEMENT& domElement = partDomain->GetElement(j);
FEElement& el = dom->ElementRef(j);
el.SetID(domElement.id);
int ne = el.Nodes();
for (int n = 0; n < ne; ++n) el.m_node[n] = m_NLT[domElement.node[n] - m_noff];
}
}
void FEBioMeshDomainsSection4::ParseShellDomainSection(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
FEBModel& feb = GetBuilder()->GetFEBModel();
FEBModel::Part* part = feb.GetPart(0); assert(part);
if (part == nullptr) throw XMLReader::InvalidTag(tag);
// get the domain name
const char* szname = tag.AttributeValue("name");
FEBModel::Domain* partDomain = part->FindDomain(szname);
if (partDomain == nullptr) throw XMLReader::InvalidAttributeValue(tag, "name", szname);
// get the material name
const char* szmat = tag.AttributeValue("mat");
FEMaterial* mat = fem.FindMaterial(szmat);
if (mat == nullptr) throw XMLReader::InvalidAttributeValue(tag, "mat", szmat);
// set the material name
partDomain->SetMaterialName(szmat);
// see if the element type is specified
const char* szelem = tag.AttributeValue("elem_type", true);
if (szelem)
{
FE_Element_Spec elemSpec = partDomain->ElementSpec();
FE_Element_Spec newSpec = GetBuilder()->ElementSpec(szelem);
// make sure it's valid
if ((FEElementLibrary::IsValid(newSpec) == false) || (elemSpec.eshape != newSpec.eshape))
{
throw XMLReader::InvalidAttributeValue(tag, "elem_type", szelem);
}
partDomain->SetElementSpec(newSpec);
}
// get the (optional) type attribute
const char* sztype = tag.AttributeValue("type", true);
// --- build the domain ---
// we'll need the kernel for creating domains
FECoreKernel& febio = FECoreKernel::GetInstance();
// element count
int elems = partDomain->Elements();
// get the element spect
FE_Element_Spec spec = partDomain->ElementSpec();
// create the domain
FEDomain* dom = nullptr;
if (sztype)
{
// if the type attribute is defined, try to allocate the domain class directly.
dom = febio.CreateDomainExplicit(FESHELLDOMAIN_ID, sztype, &fem);
if (dom == nullptr) throw XMLReader::InvalidAttributeValue(tag, sztype);
dom->SetMaterial(mat);
}
else
{
// if not, then use "old" logic, which tries to match the domain using the
// domain factories.
dom = febio.CreateDomain(spec, &mesh, mat);
if (dom == 0) throw XMLReader::InvalidTag(tag);
}
mesh.AddDomain(dom);
if (dom->Create(elems, spec) == false)
{
throw XMLReader::InvalidTag(tag);
}
// assign the material
dom->SetMatID(mat->GetID() - 1);
// get the part name
string partName = part->Name();
if (partName.empty() == false) partName += ".";
string domName = partName + partDomain->Name();
dom->SetName(domName);
// read additional parameters
if (tag.isleaf() == false)
{
ReadParameterList(tag, dom);
}
// process element data
FEShellDomain* shellDomain = dynamic_cast<FEShellDomain*>(dom);
if (shellDomain)
{
for (int j = 0; j < elems; ++j)
{
const FEBModel::ELEMENT& domElement = partDomain->GetElement(j);
FEShellElement& el = shellDomain->Element(j);
el.SetID(domElement.id);
int ne = el.Nodes();
for (int n = 0; n < ne; ++n)
{
el.m_node[n] = m_NLT[domElement.node[n] - m_noff];
el.m_h0[n] = 0.0;
}
}
shellDomain->AssignDefaultShellThickness();
}
}
void FEBioMeshDomainsSection4::ParseBeamDomainSection(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
FEBModel& feb = GetBuilder()->GetFEBModel();
FEBModel::Part* part = feb.GetPart(0); assert(part);
if (part == nullptr) throw XMLReader::InvalidTag(tag);
// get the domain name
const char* szname = tag.AttributeValue("name");
FEBModel::Domain* partDomain = part->FindDomain(szname);
if (partDomain == nullptr) throw XMLReader::InvalidAttributeValue(tag, "name", szname);
// get the material name
const char* szmat = tag.AttributeValue("mat");
FEMaterial* mat = fem.FindMaterial(szmat);
if (mat == nullptr) throw XMLReader::InvalidAttributeValue(tag, "mat", szmat);
// set the material name
partDomain->SetMaterialName(szmat);
// see if the element type is specified
const char* szelem = tag.AttributeValue("elem_type", true);
if (szelem)
{
FE_Element_Spec elemSpec = partDomain->ElementSpec();
FE_Element_Spec newSpec = GetBuilder()->ElementSpec(szelem);
// make sure it's valid
if ((FEElementLibrary::IsValid(newSpec) == false) || (elemSpec.eshape != newSpec.eshape))
{
throw XMLReader::InvalidAttributeValue(tag, "elem_type", szelem);
}
partDomain->SetElementSpec(newSpec);
}
// get the (optional) type attribute
const char* sztype = tag.AttributeValue("type", true);
// --- build the domain ---
// we'll need the kernel for creating domains
FECoreKernel& febio = FECoreKernel::GetInstance();
// element count
int elems = partDomain->Elements();
// get the element spect
FE_Element_Spec spec = partDomain->ElementSpec();
// create the domain
FEDomain* dom = nullptr;
if (sztype)
{
// if the type attribute is defined, try to allocate the domain class directly.
dom = febio.CreateDomainExplicit(FEBEAMDOMAIN_ID, sztype, &fem);
if (dom == nullptr) throw XMLReader::InvalidAttributeValue(tag, sztype);
dom->SetMaterial(mat);
}
else
{
// if not, then use "old" logic, which tries to match the domain using the
// domain factories.
dom = febio.CreateDomain(spec, &mesh, mat);
if (dom == 0) throw XMLReader::InvalidTag(tag);
}
// add it to the mesh
mesh.AddDomain(dom);
// Allocate elements
if (dom->Create(elems, spec) == false)
{
throw XMLReader::InvalidTag(tag);
}
// assign the material
dom->SetMatID(mat->GetID() - 1);
// get the part name
string partName = part->Name();
if (partName.empty() == false) partName += ".";
string domName = partName + partDomain->Name();
dom->SetName(domName);
// read additional parameters
if (tag.isleaf() == false)
{
ReadParameterList(tag, dom);
}
// process element data
for (int j = 0; j < elems; ++j)
{
const FEBModel::ELEMENT& domElement = partDomain->GetElement(j);
FEElement& el = dom->ElementRef(j);
el.SetID(domElement.id);
// TODO: This assumes one-based indexing of all nodes!
int ne = el.Nodes();
for (int n = 0; n < ne; ++n) el.m_node[n] = m_NLT[domElement.node[n] - m_noff];
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioLoadDataSection.cpp | .cpp | 4,690 | 148 | /*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 "FEBioLoadDataSection.h"
#include <FECore/FEModel.h>
#include <FECore/FELoadCurve.h>
//-----------------------------------------------------------------------------
FEBioLoadDataSection::FEBioLoadDataSection(FEFileImport* pim) : FEFileSection(pim)
{
m_redefineCurves = false;
}
//-----------------------------------------------------------------------------
//! This function reads the load data section from the xml file
//!
void FEBioLoadDataSection::Parse(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
++tag;
do
{
if (tag == "loadcurve")
{
// load curve ID
int nid;
tag.AttributeValue("id", nid);
// default type and extend mode
PointCurve::INTFUNC ntype = PointCurve::LINEAR;
PointCurve::EXTMODE nextm = PointCurve::CONSTANT;
// get the (optional) type
XMLAtt* patt = tag.Attribute("type", true);
if (patt)
{
XMLAtt& type = *patt;
if (type == "step" ) ntype = PointCurve::STEP;
else if (type == "linear") ntype = PointCurve::LINEAR;
else if (type == "smooth") ntype = PointCurve::SMOOTH;
else if (type == "cubic spline") ntype = PointCurve::CSPLINE;
else if (type == "control points") ntype = PointCurve::CPOINTS;
else if (type == "approximation" ) ntype = PointCurve::APPROX;
else if (type == "smooth step" ) ntype = PointCurve::SMOOTH_STEP;
else if (type == "C2-smooth" ) ntype = PointCurve::C2SMOOTH;
else throw XMLReader::InvalidAttributeValue(tag, "type", type.cvalue());
}
// get the optional extend mode
patt = tag.Attribute("extend", true);
if (patt)
{
XMLAtt& ext = *patt;
if (ext == "constant" ) nextm = PointCurve::CONSTANT;
else if (ext == "extrapolate" ) nextm = PointCurve::EXTRAPOLATE;
else if (ext == "repeat" ) nextm = PointCurve::REPEAT;
else if (ext == "repeat offset") nextm = PointCurve::REPEAT_OFFSET;
else throw XMLReader::InvalidAttributeValue(tag, "extend", ext.cvalue());
}
// get the number of load curves
int nlc = fem.LoadControllers();
// find or create the load curve
FELoadCurve* plc = 0;
// see if this refers to a valid curve
if (m_redefineCurves)
{
if ((nid > 0) && (nid <= nlc))
{
plc = dynamic_cast<FELoadCurve*>(fem.GetLoadController(nid - 1));
assert(plc);
// clear the curve since we're about to read in new data points
plc->Clear();
}
}
// if the ID does not refer to an existing curve, make sure it defines the next curve
if (plc == 0)
{
// check that the ID is one more than the number of load curves defined
// This is to make sure that the ID's are in numerical order and no values are skipped.
if (nid != nlc + 1) throw XMLReader::InvalidAttributeValue(tag, "id");
// create the loadcurve
plc = fecore_new<FELoadCurve>("loadcurve", &fem); assert(plc);
plc->SetID(nid - 1);
// add the loadcurve
fem.AddLoadController(plc);
}
// set the load curve attributes
plc->SetInterpolation(ntype);
plc->SetExtendMode(nextm);
// read the data points
double d[2];
++tag;
do
{
tag.value(d, 2);
plc->Add(d[0], d[1]);
++tag;
}
while (!tag.isend());
if (m_redefineCurves)
{
plc->Init();
}
}
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioControlSection4.h | .h | 1,545 | 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) 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 "FEBioImport.h"
//-----------------------------------------------------------------------------
// Control Section
class FEBioControlSection4 : public FEFileSection
{
public:
FEBioControlSection4(FEFileImport* pim);
void Parse(XMLTag& tag);
};
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FEBioModuleSection.cpp | .cpp | 2,541 | 78 | /*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 "FEBioModuleSection.h"
//-----------------------------------------------------------------------------
//! This function parses the Module section.
//! The Module defines the type of problem the user wants to solve (solid, heat, ...)
//! It is currently only used to allocate the FESolver.
void FEBioModuleSection::Parse(XMLTag &tag)
{
int nversion = GetFileReader()->GetFileVersion();
// For version 2.5 and up this tag can only be read in once and we
// determine that by inspecting the m_szmod member.
if (nversion >= 0x0205)
{
std::string moduleName = GetBuilder()->GetModuleName();
if (moduleName.empty() == false) throw XMLReader::InvalidTag(tag);
}
// get the type attribute
const char* szt = tag.AttributeValue("type");
// some special case
if (strcmp(szt, "explicit-solid") == 0)
{
szt = "solid";
GetBuilder()->SetDefaultSolver("explicit-solid");
}
else if (strcmp(szt, "CG-solid") == 0)
{
szt = "solid";
GetBuilder()->SetDefaultSolver("CG-solid");
}
GetBuilder()->SetActiveModule(szt);
if (tag.isempty() || tag.isleaf()) return;
++tag;
do {
if (tag == "units")
{
const char* szunits = tag.szvalue();
GetFEModel()->SetUnits(szunits);
}
++tag;
} while (!tag.isend());
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/XMLWriter.cpp | .cpp | 9,984 | 487 | /*This file is part of the FEBio Studio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio-Studio.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.*/
// XMLWriter.cpp: implementation of the XMLWriter class.
//
//////////////////////////////////////////////////////////////////////
#include "XMLWriter.h"
#include <sstream>
#include <fstream>
#include <iomanip>
using namespace std;
void XMLElement::value(int n) { stringstream ss; ss << n; m_val = ss.str(); }
void XMLElement::value(bool b) { int n = (b ? 1 : 0); stringstream ss; ss << n; m_val = ss.str(); }
void XMLElement::value(double g) { stringstream ss; ss << std::setprecision(7) << g; m_val = ss.str(); }
void XMLElement::value(int* pi, int n)
{
m_val.clear();
if (n==0) return;
stringstream ss;
ss << pi[0];
for (int i=1; i<n; ++i)
{
ss << "," << pi[i];
}
m_val = ss.str();
}
void XMLElement::value(double* pg, int n)
{
m_val.clear();
if (n==0) return;
stringstream ss;
ss << pg[0];
for (int i=1; i<n; ++i)
{
ss << "," << pg[i];
}
m_val = ss.str();
}
/*
void XMLElement::value(const vec3f& r)
{
stringstream ss;
ss << r.x << "," << r.y << "," << r.z;
m_val = ss.str();
}
void XMLElement::value(const vec3d& r)
{
stringstream ss;
ss << r.x << "," << r.y << "," << r.z;
m_val = ss.str();
}
void XMLElement::value(const vec2i& r)
{
stringstream ss;
ss << r.x << "," << r.y;
m_val = ss.str();
}
void XMLElement::value(const mat3d& a)
{
stringstream ss;
ss << a(0,0) << "," << a(0,1) << "," << a(0,2) << ",";
ss << a(1,0) << "," << a(1,1) << "," << a(1,2) << ",";
ss << a(2,0) << "," << a(2,1) << "," << a(2,2);
m_val = ss.str();
}
*/
void XMLElement::value(const std::vector<int>& v)
{
m_val.clear();
if (v.empty()) return;
stringstream ss;
ss << v[0];
for (int i = 1; i < v.size(); ++i)
{
ss << "," << v[i];
}
m_val = ss.str();
}
void XMLElement::value(const std::vector<double>& v)
{
m_val.clear();
if (v.empty()) return;
stringstream ss;
ss << v[0];
for (int i = 1; i < v.size(); ++i)
{
ss << "," << v[i];
}
m_val = ss.str();
}
int XMLElement::add_attribute(const char* szn, const char* szv)
{
m_att.push_back(XMLAtt(szn, szv));
return (int) m_att.size()-1;
}
int XMLElement::add_attribute(const char* szn, int n)
{
stringstream ss; ss << n;
m_att.push_back(XMLAtt(szn, ss.str()));
return (int)m_att.size() - 1;
}
int XMLElement::add_attribute(const char* szn, bool b)
{
int n = (b ? 1 : 0);
stringstream ss; ss << n;
m_att.push_back(XMLAtt(szn, ss.str()));
return (int)m_att.size() - 1;
}
int XMLElement::add_attribute(const char* szn, double g)
{
stringstream ss; ss << g;
m_att.push_back(XMLAtt(szn, ss.str()));
return (int)m_att.size() - 1;
}
int XMLElement::add_attribute(const char* szn, const std::string& s)
{
m_att.push_back(XMLAtt(szn, s));
return (int)m_att.size() - 1;
}
void XMLElement::set_attribute(int nid, const char* szv)
{
m_att[nid].m_val = szv;
}
void XMLElement::set_attribute(int nid, int n)
{
stringstream ss; ss << n;
m_att[nid].m_val = ss.str();
}
void XMLElement::set_attribute(int nid, bool b)
{
stringstream ss; ss << (b?(int)1:(int)0);
m_att[nid].m_val = ss.str();
}
void XMLElement::set_attribute(int nid, double g)
{
stringstream ss; ss << g;
m_att[nid].m_val = ss.str();
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
XMLWriter::XMLFloatFormat XMLWriter::m_floatFormat = XMLWriter::FixedFormat;
void XMLWriter::SetFloatFormat(XMLFloatFormat fmt)
{
m_floatFormat = fmt;
}
XMLWriter::XMLFloatFormat XMLWriter::GetFloatFormat()
{
return m_floatFormat;
}
XMLWriter::XMLWriter()
{
m_stream = nullptr;
m_level = 0;
m_sztab[0] = 0;
}
XMLWriter::~XMLWriter()
{
close();
}
bool XMLWriter::open(const char* szfile)
{
if (m_stream) return false;
if (szfile == nullptr) return false;
m_stream = new ofstream(szfile, std::ios_base::out);
if (m_stream && m_stream->fail()) return false;
// write the first line
if(m_stream)
{
init();
}
return (m_stream != nullptr);
}
bool XMLWriter::setStringstream(std::ostringstream* stream)
{
if (m_stream) return false;
if (!stream) return false;
m_stream = stream;
init();
return true;
}
void XMLWriter::init()
{
m_stream->precision(12);
*m_stream << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
}
void XMLWriter::close()
{
ofstream* fstrm = dynamic_cast<ofstream*>(m_stream);
if (fstrm)
{
fstrm->close();
delete m_stream;
m_stream = nullptr;
}
}
void XMLWriter::inc_level()
{
++m_level;
m_sztab[0] = 0;
int l=0;
for (int i=0; i<m_level; ++i)
{
snprintf(m_sztab+l, 256, "\t");
++l;
}
m_sztab[l] = 0;
}
void XMLWriter::dec_level()
{
if (m_level <= 0) return;
--m_level;
m_sztab[0] = 0;
int l=0;
for (int i=0; i<m_level; ++i)
{
snprintf(m_sztab+l, 256, "\t");
++l;
}
m_sztab[l] = 0;
}
void XMLWriter::add_branch(XMLElement& el, bool bclear)
{
*m_stream << m_sztab << "<" << el.m_tag;
for (int i=0; i<el.attributes(); ++i)
{
const XMLElement::XMLAtt& att = el.attribute(i);
*m_stream << " " << att.name() << "=\"" << att.value() << "\"";
}
*m_stream << ">" << el.m_val << "\n";
strcpy(m_tag[m_level], el.m_tag.c_str());
inc_level();
if (bclear) el.clear();
}
void XMLWriter::add_branch(const char* sz)
{
*m_stream << m_sztab << "<" << sz << ">\n";
strcpy(m_tag[m_level], sz);
inc_level();
}
void XMLWriter::add_empty(XMLElement& el, bool bclear)
{
*m_stream << m_sztab << "<" << el.m_tag;
for (int i=0; i<el.attributes(); ++i)
{
const XMLElement::XMLAtt& att = el.attribute(i);
*m_stream << " " << att.name() << "=\"" << att.value() << "\"";
}
*m_stream << "/>\n";
if (bclear) el.clear();
}
void XMLWriter::add_leaf(XMLElement& el, bool bclear)
{
*m_stream << m_sztab << "<" << el.m_tag;
for (int i=0; i<el.attributes(); ++i)
{
const XMLElement::XMLAtt& att = el.attribute(i);
*m_stream << " " << att.name() << "=\"" << att.value() << "\"";
}
*m_stream << ">" << el.m_val << "</" << el.m_tag << ">\n";
if (bclear) el.clear();
}
void XMLWriter::write_leaf(const char* sztag, const char* szval)
{
*m_stream << m_sztab << "<" << sztag;
*m_stream << ">";
if (m_encodeControlChars)
{
const char* ch = szval;
while (ch && *ch)
{
if (*ch == '\t') *m_stream << "	";
else if (*ch == '\n') *m_stream << "
";
else if (*ch == '\r') *m_stream << "
";
else *m_stream << *ch;
++ch;
}
}
else
{
*m_stream << szval;
}
*m_stream << "</" << sztag << ">\n";
}
void XMLWriter::add_leaf(const char* szn, const char* szv)
{
write_leaf(szn, szv);
}
void XMLWriter::add_leaf(const char* szn, const std::string& s)
{
write_leaf(szn, s.c_str());
}
void XMLWriter::add_leaf(const char* szn, double* pg, int n)
{
*m_stream << m_sztab << "<" << szn << ">";
if (n>0)
{
*m_stream << pg[0];
for (int i=1; i<n; ++i) *m_stream << "," << pg[i];
}
*m_stream << "</" << szn << ">\n";
}
void XMLWriter::add_leaf(const char* szn, float* pg, int n)
{
*m_stream << m_sztab << "<" << szn << ">";
if (n>0)
{
*m_stream << pg[0];
for (int i=1; i<n; ++i) *m_stream << "," << pg[i];
}
*m_stream << "</" << szn << ">\n";
}
void XMLWriter::add_leaf(const char* szn, int* pi, int n)
{
*m_stream << m_sztab << "<" << szn << ">";
if (n>0)
{
*m_stream << pi[0];
for (int i=1; i<n; ++i) *m_stream << "," << pi[i];
}
*m_stream << "</" << szn << ">\n";
}
void XMLWriter::add_leaf(XMLElement& el, const std::vector<int>& A)
{
*m_stream << m_sztab << "<" << el.m_tag;
for (int i=0; i<el.attributes(); ++i)
{
const XMLElement::XMLAtt& att = el.attribute(i);
*m_stream << " " << att.name() << "=\"" << att.value() << "\"";
}
inc_level();
*m_stream << ">\n" << m_sztab;
int n = (int) A.size(), l = 0;
streampos start;
for (int i=0; i<n; ++i)
{
start = m_stream->tellp();
*m_stream << A[i];
l += m_stream->tellp() - start;
if (i < n-1)
{
if ((i+1) % 8 == 0) { *m_stream << ",\n" << m_sztab; l=0; }
else *m_stream << ", ";
}
}
dec_level();
*m_stream << "\n" << m_sztab << "</" << el.m_tag << ">\n";
}
void XMLWriter::close_branch()
{
if (m_level > 0)
{
dec_level();
char szformat[256] = {0};
snprintf(szformat, sizeof(szformat), "%s</%%s>\n", m_sztab);
*m_stream << m_sztab << "</" << m_tag[m_level] << ">\n";
}
}
void XMLWriter::add_comment(const std::string& s, bool singleLine)
{
if (s.empty()) return;
if (singleLine)
{
*m_stream << "<!-- " << s << " -->\n";
}
else
{
*m_stream << "<!--\n" << s << "\n-->\n";
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioStepSection.cpp | .cpp | 3,517 | 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.*/
#include "stdafx.h"
#include "FEBioStepSection.h"
#include "FEBioModuleSection.h"
#include "FEBioControlSection.h"
#include "FEBioConstraintsSection.h"
#include "FEBioBoundarySection.h"
#include "FEBioLoadsSection.h"
#include "FEBioContactSection.h"
#include "FEBioInitialSection.h"
//-----------------------------------------------------------------------------
void FEBioStepSection::Parse(XMLTag& tag)
{
// create next step
FEBioImport* feb = GetFEBioImport();
feb->GetBuilder()->NextStep();
FEFileSectionMap Map;
Map["Module" ] = new FEBioModuleSection (feb);
Map["Control" ] = new FEBioControlSection (feb);
Map["Constraints"] = new FEBioConstraintsSection1x(feb);
Map["Boundary" ] = new FEBioBoundarySection1x (feb);
Map["Loads" ] = new FEBioLoadsSection1x (feb);
Map["Initial" ] = new FEBioInitialSection (feb);
// parse the file sections
Map.Parse(tag);
}
//-----------------------------------------------------------------------------
void FEBioStepSection2::Parse(XMLTag& tag)
{
// create next step
FEBioImport* feb = GetFEBioImport();
feb->GetBuilder()->NextStep();
FEFileSectionMap Map;
Map["Module" ] = new FEBioModuleSection (feb);
Map["Control" ] = new FEBioControlSection (feb);
Map["Constraints"] = new FEBioConstraintsSection2(feb);
Map["Boundary" ] = new FEBioBoundarySection2 (feb);
Map["Loads" ] = new FEBioLoadsSection2 (feb);
Map["Initial" ] = new FEBioInitialSection (feb);
Map["Contact" ] = new FEBioContactSection2 (feb);
// parse the file sections
Map.Parse(tag);
}
//-----------------------------------------------------------------------------
void FEBioStepSection25::Parse(XMLTag& tag)
{
// create next step
GetBuilder()->NextStep();
FEFileImport* imp = GetFileReader();
FEFileSectionMap Map;
Map["Control" ] = new FEStepControlSection (imp);
Map["Constraints"] = new FEBioConstraintsSection25(imp);
Map["Boundary" ] = new FEBioBoundarySection25 (imp);
Map["Loads" ] = new FEBioLoadsSection25 (imp);
Map["Initial" ] = new FEBioInitialSection25 (imp);
Map["Contact" ] = new FEBioContactSection25 (imp);
// parse the file sections
Map.Parse(tag);
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioContactSection.cpp | .cpp | 18,087 | 575 | /*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 "FEBioContactSection.h"
#include <FECore/FEAugLagLinearConstraint.h>
#include <FECore/FENodalBC.h>
#include <FECore/FECoreKernel.h>
#include <FECore/FEModel.h>
//-----------------------------------------------------------------------------
FEBioContactSection::MissingPrimarySurface::MissingPrimarySurface()
{
SetErrorString("Missing contact primary surface");
}
//-----------------------------------------------------------------------------
FEBioContactSection::MissingSecondarySurface::MissingSecondarySurface()
{
SetErrorString("Missing contact secondary surface");
}
//-----------------------------------------------------------------------------
//! Parse the Contact section (new in version 2.0)
void FEBioContactSection2::Parse(XMLTag& tag)
{
// make sure there are children
if (tag.isleaf()) return;
FEModel& fem = *GetFEModel();
// loop over tags
++tag;
do
{
if (tag == "contact")
{
// get the contact type
const char* sztype = tag.AttributeValue("type");
// Not all contact interfaces can be automated, so we first handle these special cases
if (strcmp(sztype, "rigid_wall" ) == 0) ParseRigidWall (tag);
else if (strcmp(sztype, "rigid" ) == 0) ParseRigidInterface (tag);
else if (strcmp(sztype, "linear constraint") == 0) ParseLinearConstraint(tag);
else
{
// If we get here, we try to create a contact interface
// using the FEBio kernel.
FESurfacePairConstraint* pci = fecore_new<FESurfacePairConstraint>(sztype, &fem);
if (pci)
{
GetBuilder()->AddContactInterface(pci);
ParseContactInterface(tag, pci);
}
else
{
FEModel& fem = *GetFEModel();
// Some constraints were initially defined in the Contact section, although
// now it is preferred that they are defined in the Constraints section. For backward
// compatibility we still allow constraints to be defined in this section.
FENLConstraint* pc = fecore_new<FENLConstraint>(sztype, &fem);
if (pc)
{
ReadParameterList(tag, pc);
GetBuilder()->AddNonlinearConstraint(pc);
}
else
{
// check for some older obsolete names
if (strcmp(sztype, "facet-to-facet sliding") == 0) pci = fecore_new_class<FESurfacePairConstraint>("FEFacet2FacetSliding", &fem);
else if (strcmp(sztype, "sliding_with_gaps" ) == 0) pci = fecore_new_class<FESurfacePairConstraint>("FESlidingInterface", &fem);
if (pci)
{
GetBuilder()->AddContactInterface(pci);
ParseContactInterface(tag, pci);
}
else throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
}
}
}
}
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
}
//-----------------------------------------------------------------------------
//! Parse the Contact section (new in version 2.0)
void FEBioContactSection25::Parse(XMLTag& tag)
{
// make sure there are children
if (tag.isleaf()) return;
FEModel& fem = *GetFEModel();
// loop over tags
++tag;
do
{
if (tag == "contact")
{
// get the contact type
const char* sztype = tag.AttributeValue("type");
// Not all contact interfaces can be automated, so we first handle these special cases
if (strcmp(sztype, "rigid_wall" ) == 0) ParseRigidWall (tag);
else if (strcmp(sztype, "rigid sliding" ) == 0) ParseRigidSliding (tag);
else if (strcmp(sztype, "linear constraint") == 0) ParseLinearConstraint(tag);
else
{
// If we get here, we try to create a contact interface
// using the FEBio kernel.
FESurfacePairConstraint* pci = fecore_new<FESurfacePairConstraint>(sztype, &fem);
if (pci == nullptr)
{
// check for some older obsolete names
if (strcmp(sztype, "facet-to-facet sliding") == 0) pci = fecore_new_class<FESurfacePairConstraint>("FEFacet2FacetSliding", &fem);
else if (strcmp(sztype, "sliding_with_gaps") == 0) pci = fecore_new_class<FESurfacePairConstraint>("FESlidingInterface", &fem);
}
if (pci)
{
GetBuilder()->AddContactInterface(pci);
ParseContactInterface(tag, pci);
}
else throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
}
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
//-----------------------------------------------------------------------------
void FEBioContactSection2::ParseContactInterface(XMLTag& tag, FESurfacePairConstraint* pci)
{
FEModel& fem = *GetFEModel();
FEMesh& m = fem.GetMesh();
// get the parameter list
FEParameterList& pl = pci->GetParameterList();
// read the parameters
++tag;
do
{
if (ReadParameter(tag, pl) == false)
{
if (tag == "surface")
{
const char* sztype = tag.AttributeValue("type");
int ntype = 0;
if (strcmp(sztype, "master") == 0) ntype = 1;
else if (strcmp(sztype, "slave") == 0) ntype = 2;
FESurface& s = *(ntype == 1? pci->GetSecondarySurface() : pci->GetPrimarySurface());
m.AddSurface(&s);
int nfmt = 0;
const char* szfmt = tag.AttributeValue("format", true);
if (szfmt)
{
if (strcmp(szfmt, "face nodes") == 0) nfmt = 0;
else if (strcmp(szfmt, "element face") == 0) nfmt = 1;
}
// see if the set attribute is defined
const char* szset = tag.AttributeValue("set", true);
if (szset)
{
// make sure this tag does not have any children
if (!tag.isleaf()) throw XMLReader::InvalidTag(tag);
// see if we can find the facet set
FEFacetSet* ps = m.FindFacetSet(szset);
// create a surface from the facet set
if (ps)
{
if (GetBuilder()->BuildSurface(s, *ps, pci->UseNodalIntegration()) == false) throw XMLReader::InvalidTag(tag);
}
else throw XMLReader::InvalidAttributeValue(tag, "set", szset);
}
else
{
// read the surface section
if (ParseSurfaceSection(tag, s, nfmt, pci->UseNodalIntegration()) == false) throw XMLReader::InvalidTag(tag);
}
}
else throw XMLReader::InvalidTag(tag);
}
++tag;
}
while (!tag.isend());
// Make sure we have a primary and secondary interface
FESurface* pss = pci->GetPrimarySurface (); if ((pss == 0) || (pss->Elements()==0)) throw MissingPrimarySurface ();
FESurface* pms = pci->GetSecondarySurface(); if ((pms == 0) || (pms->Elements()==0)) throw MissingSecondarySurface();
}
//-----------------------------------------------------------------------------
void FEBioContactSection25::ParseContactInterface(XMLTag& tag, FESurfacePairConstraint* pci)
{
FEModel& fem = *GetFEModel();
FEMesh& m = fem.GetMesh();
// get the surface pair
const char* szpair = tag.AttributeValue("surface_pair");
FESurfacePair* surfacePair =m.FindSurfacePair(szpair);
if (surfacePair == 0) throw XMLReader::InvalidAttributeValue(tag, "surface_pair", szpair);
// build the surfaces
if (GetBuilder()->BuildSurface(*pci->GetSecondarySurface(), *surfacePair->GetSecondarySurface(), pci->UseNodalIntegration()) == false) throw XMLReader::InvalidAttributeValue(tag, "surface_pair", szpair);
if (GetBuilder()->BuildSurface(*pci->GetPrimarySurface(), *surfacePair->GetPrimarySurface(), pci->UseNodalIntegration()) == false) throw XMLReader::InvalidAttributeValue(tag, "surface_pair", szpair);
// get the parameter list
ReadParameterList(tag, pci);
// Make sure we have both surfaces
FESurface* pss = pci->GetPrimarySurface (); if ((pss == 0) || (pss->Elements()==0)) throw MissingPrimarySurface ();
m.AddSurface(pss);
FESurface* pms = pci->GetSecondarySurface(); if ((pms == 0) || (pms->Elements()==0)) throw MissingSecondarySurface();
m.AddSurface(pms);
}
//-----------------------------------------------------------------------------
// --- R I G I D W A L L I N T E R F A C E ---
void FEBioContactSection2::ParseRigidWall(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FESurfacePairConstraint* ps = fecore_new<FESurfacePairConstraint>("rigid_wall", GetFEModel());
fem.AddSurfacePairConstraint(ps);
++tag;
do
{
if (ReadParameter(tag, ps) == false)
{
if (tag == "surface")
{
FESurface& s = *ps->GetPrimarySurface();
int nfmt = 0;
const char* szfmt = tag.AttributeValue("format", true);
if (szfmt)
{
if (strcmp(szfmt, "face nodes" ) == 0) nfmt = 0;
else if (strcmp(szfmt, "element face") == 0) nfmt = 1;
}
// read the surface section
ParseSurfaceSection(tag, s, nfmt, true);
}
else throw XMLReader::InvalidTag(tag);
}
++tag;
}
while (!tag.isend());
}
//-----------------------------------------------------------------------------
// --- R I G I D W A L L I N T E R F A C E ---
void FEBioContactSection25::ParseRigidWall(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
FESurfaceConstraint* ps = fecore_new<FESurfaceConstraint>("rigid_wall", GetFEModel());
fem.AddNonlinearConstraint(ps);
// get and build the surface
const char* sz = tag.AttributeValue("surface");
FEFacetSet* pface = mesh.FindFacetSet(sz);
if (pface == 0) throw XMLReader::InvalidAttributeValue(tag, "surface", sz);
if (GetBuilder()->BuildSurface(*ps->GetSurface(), *pface, true) == false) throw XMLReader::InvalidAttributeValue(tag, "surface", sz);
mesh.AddSurface(ps->GetSurface());
ReadParameterList(tag, ps);
}
//-----------------------------------------------------------------------------
void FEBioContactSection25::ParseRigidSliding(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
FESurfacePairConstraint* ps = fecore_new<FESurfacePairConstraint>("rigid sliding", GetFEModel());
fem.AddSurfacePairConstraint(ps);
// get and build the surface
const char* sz = tag.AttributeValue("surface");
FEFacetSet* pface = mesh.FindFacetSet(sz);
if (pface == 0) throw XMLReader::InvalidAttributeValue(tag, "surface", sz);
if (GetBuilder()->BuildSurface(*ps->GetPrimarySurface(), *pface, false) == false) throw XMLReader::InvalidAttributeValue(tag, "surface", sz);
mesh.AddSurface(ps->GetPrimarySurface());
ReadParameterList(tag, ps);
}
//-----------------------------------------------------------------------------
// --- R I G I D B O D Y I N T E R F A C E ---
void FEBioContactSection2::ParseRigidInterface(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEModelBuilder* feb = GetBuilder();
int NMAT = fem.Materials();
// count how many rigid nodes there are
int nrn= 0;
XMLTag t(tag); ++t;
while (!t.isend()) { nrn++; ++t; }
++tag;
int id, rb, rbp = -1;
FENodalBC* prn = 0;
FENodeSet* ns = nullptr;
for (int i=0; i<nrn; ++i)
{
id = atoi(tag.AttributeValue("id"))-1;
rb = atoi(tag.AttributeValue("rb"));
// make sure we have a valid rigid body reference
if ((rb <= 0)||(rb>NMAT)) throw XMLReader::InvalidAttributeValue(tag, "rb", tag.AttributeValue("rb"));
if ((prn == 0) || (rb != rbp))
{
prn = fecore_new_class<FENodalBC>("FERigidNodeSet", &fem);
ns = new FENodeSet(&fem);
prn->SetNodeSet(ns);
// the default shell bc depends on the shell formulation
// hinged shell = 0
// clamped shell = 1
prn->SetParameter("clamp_shells", feb->m_default_shell == OLD_SHELL ? 0 : 1);
prn->SetParameter("rb", rb);
GetBuilder()->AddBC(prn);
rbp = rb;
}
if (ns) ns->Add(id);
++tag;
}
}
//-----------------------------------------------------------------------------
// --- L I N E A R C O N S T R A I N T ---
void FEBioContactSection::ParseLinearConstraint(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
DOFS& dofs = fem.GetDOFS();
FEMesh& m = fem.GetMesh();
// make sure there is a constraint defined
if (tag.isleaf()) return;
// create a new linear constraint manager
FELinearConstraintSet* pLCS = dynamic_cast<FELinearConstraintSet*>(fecore_new<FENLConstraint>("linear constraint", GetFEModel()));
fem.AddNonlinearConstraint(pLCS);
// read the linear constraints
++tag;
do
{
if (tag == "linear_constraint")
{
FEAugLagLinearConstraint* pLC = fecore_alloc(FEAugLagLinearConstraint, &fem);
++tag;
do
{
int node, bc;
double val;
if (tag == "node")
{
tag.value(val);
const char* szid = tag.AttributeValue("id");
node = atoi(szid);
const char* szbc = tag.AttributeValue("bc");
int ndof = dofs.GetDOF(szbc);
if (ndof >= 0) bc = ndof;
else throw XMLReader::InvalidAttributeValue(tag, "bc", szbc);
pLC->AddDOF(node, bc, val);
}
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
// add the linear constraint to the system
pLCS->add(pLC);
}
else if (ReadParameter(tag, pLCS) == false)
{
throw XMLReader::InvalidTag(tag);
}
++tag;
}
while (!tag.isend());
}
//---------------------------------------------------------------------------------
// parse a surface section for contact definitions
//
bool FEBioContactSection::ParseSurfaceSection(XMLTag &tag, FESurface& s, int nfmt, bool bnodal)
{
FEModel& fem = *GetFEModel();
FEMesh& m = fem.GetMesh();
int NN = m.Nodes();
int N, nf[9];
// count nr of faces
int faces = tag.children();
// allocate storage for faces
s.Create(faces);
FEModelBuilder* feb = GetBuilder();
// read faces
++tag;
for (int i=0; i<faces; ++i)
{
FESurfaceElement& el = s.Element(i);
// set the element type/integration rule
if (bnodal)
{
if (tag == "quad4") el.SetType(FE_QUAD4NI);
else if (tag == "tri3" ) el.SetType(FE_TRI3NI );
else if (tag == "tri6" ) el.SetType(FE_TRI6NI );
else if (tag == "quad8" ) el.SetType(FE_QUAD8NI);
else if (tag == "quad9" ) el.SetType(FE_QUAD9NI);
else throw XMLReader::InvalidTag(tag);
}
else
{
if (tag == "quad4") el.SetType(FE_QUAD4G4);
else if (tag == "tri3" ) el.SetType(feb->m_ntri3);
else if (tag == "tri6" ) el.SetType(feb->m_ntri6);
else if (tag == "tri7" ) el.SetType(feb->m_ntri7);
else if (tag == "tri10") el.SetType(feb->m_ntri10);
else if (tag == "quad8") el.SetType(FE_QUAD8G9);
else if (tag == "quad9") el.SetType(FE_QUAD9G9);
else throw XMLReader::InvalidTag(tag);
}
N = el.Nodes();
if (nfmt == 0)
{
tag.value(nf, N);
for (int j=0; j<N; ++j)
{
int nid = nf[j]-1;
if ((nid<0)||(nid>= NN)) throw XMLReader::InvalidValue(tag);
el.m_node[j] = nid;
}
}
else if (nfmt == 1)
{
tag.value(nf, 2);
FEElement* pe = m.FindElementFromID(nf[0]);
if (pe)
{
int ne[4];
int nn = pe->GetFace(nf[1]-1, ne);
if (nn != N) throw XMLReader::InvalidValue(tag);
for (int j=0; j<N; ++j) el.m_node[j] = ne[j];
el.m_elem[0].pe = pe;
}
else throw XMLReader::InvalidValue(tag);
}
++tag;
}
s.InitSurface();
s.CreateMaterialPointData();
return true;
}
//-----------------------------------------------------------------------------
//! Parse the Contact section (new in version 2.0)
void FEBioContactSection4::Parse(XMLTag& tag)
{
// make sure there are children
if (tag.isleaf()) return;
FEModel& fem = *GetFEModel();
// loop over tags
++tag;
do
{
if (tag == "contact")
{
// get the contact type
const char* sztype = tag.AttributeValue("type");
// Try to create a contact interface using the FEBio kernel.
FESurfacePairConstraint* pci = fecore_new<FESurfacePairConstraint>(sztype, &fem);
if (pci == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
GetBuilder()->AddContactInterface(pci);
ParseContactInterface(tag, pci);
}
++tag;
} while (!tag.isend());
}
//-----------------------------------------------------------------------------
void FEBioContactSection4::ParseContactInterface(XMLTag& tag, FESurfacePairConstraint* pci)
{
FEModel& fem = *GetFEModel();
FEMesh& m = fem.GetMesh();
// get the surface pair
const char* szpair = tag.AttributeValue("surface_pair");
FESurfacePair* surfacePair = m.FindSurfacePair(szpair);
if (surfacePair == 0) throw XMLReader::InvalidAttributeValue(tag, "surface_pair", szpair);
// get the parameter list
ReadParameterList(tag, pci);
// build the surfaces
if (GetBuilder()->BuildSurface(*pci->GetSecondarySurface(), *surfacePair->GetSecondarySurface(), pci->UseNodalIntegration()) == false) throw XMLReader::InvalidAttributeValue(tag, "surface_pair", szpair);
if (GetBuilder()->BuildSurface(*pci->GetPrimarySurface(), *surfacePair->GetPrimarySurface(), pci->UseNodalIntegration()) == false) throw XMLReader::InvalidAttributeValue(tag, "surface_pair", szpair);
// Make sure we have both surfaces
FESurface* pss = pci->GetPrimarySurface(); if ((pss == 0) || (pss->Elements() == 0)) throw MissingPrimarySurface();
m.AddSurface(pss);
FESurface* pms = pci->GetSecondarySurface(); if ((pms == 0) || (pms->Elements() == 0)) throw MissingSecondarySurface();
m.AddSurface(pms);
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FERestartImport.cpp | .cpp | 7,625 | 251 | /*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 "FERestartImport.h"
#include "FECore/FESolver.h"
#include "FECore/FEAnalysis.h"
#include "FECore/FEModel.h"
#include "FECore/DumpFile.h"
#include <FECore/FETimeStepController.h>
#include "FEBioLoadDataSection.h"
#include "FEBioStepSection.h"
#include "FEBioStepSection3.h"
#include "FEBioStepSection4.h"
void FERestartControlSection::Parse(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEAnalysis* pstep = fem.GetCurrentStep();
++tag;
do
{
if (tag == "time_steps" ) tag.value(pstep->m_ntime);
else if (tag == "final_time" ) tag.value(pstep->m_final_time);
else if (tag == "step_size" ) tag.value(pstep->m_dt0);
else if (tag == "time_stepper")
{
if (pstep->m_timeController == nullptr) pstep->m_timeController = fecore_alloc(FETimeStepController, &fem);
FETimeStepController& tc = *pstep->m_timeController;
++tag;
do
{
if (tag == "max_retries") tag.value(tc.m_maxretries);
else if (tag == "opt_iter" ) tag.value(tc.m_iteopt);
else if (tag == "dtmin" ) tag.value(tc.m_dtmin);
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
}
else if (tag == "plot_level")
{
char szval[256];
tag.value(szval);
if (strcmp(szval, "PLOT_NEVER" ) == 0) pstep->SetPlotLevel(FE_PLOT_NEVER);
else if (strcmp(szval, "PLOT_MAJOR_ITRS" ) == 0) pstep->SetPlotLevel(FE_PLOT_MAJOR_ITRS);
else if (strcmp(szval, "PLOT_MINOR_ITRS" ) == 0) pstep->SetPlotLevel(FE_PLOT_MINOR_ITRS);
else if (strcmp(szval, "PLOT_MUST_POINTS" ) == 0) pstep->SetPlotLevel(FE_PLOT_MUST_POINTS);
else if (strcmp(szval, "PLOT_FINAL" ) == 0) pstep->SetPlotLevel(FE_PLOT_FINAL);
else if (strcmp(szval, "PLOT_STEP_FINAL" ) == 0) pstep->SetPlotLevel(FE_PLOT_STEP_FINAL);
else if (strcmp(szval, "PLOT_AUGMENTATIONS") == 0) pstep->SetPlotLevel(FE_PLOT_AUGMENTATIONS);
else throw XMLReader::InvalidValue(tag);
}
else if (tag == "plot_stride")
{
int n = 1;
tag.value(n);
if (n < 1) throw XMLReader::InvalidValue(tag);
pstep->SetPlotStride(n);
}
else if (tag == "solver")
{
FEAnalysis* step = fem.GetCurrentStep();
FESolver* solver = step->GetFESolver();
if (solver == nullptr) throw XMLReader::InvalidTag(tag);
++tag;
do
{
if (ReadParameter(tag, solver) == false)
{
throw XMLReader::InvalidTag(tag);
}
++tag;
} while (!tag.isend());
}
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
// we need to reevaluate the time step size and end time
pstep->m_dt = pstep->m_dt0;
// pstep->m_tend = pstep->m_tstart = pstep->m_ntime*pstep->m_dt0;
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
FERestartImport::FERestartImport()
{
m_newSteps = 0;
}
FERestartImport::~FERestartImport()
{
}
int FERestartImport::StepsAdded() const
{
return m_newSteps;
}
//-----------------------------------------------------------------------------
bool FERestartImport::Load(FEModel& fem, const char* szfile)
{
// open the XML file
if (m_xml.Open(szfile) == false) return errf("FATAL ERROR: Failed opening restart file %s\n", szfile);
if (m_builder == nullptr) SetModelBuilder(new FEModelBuilder(fem));
m_szdmp[0] = 0;
m_newSteps = 0;
m_map["Control" ] = new FERestartControlSection(this);
// loop over child tags
bool ret = true;
try
{
// find the root element
XMLTag tag;
if (m_xml.FindTag("febio_restart", tag) == false) return errf("FATAL ERROR: File does not contain restart data.\n");
// check the version number
const char* szversion = tag.AttributeValue("version");
int nversion = -1;
if (strcmp(szversion, "1.0") == 0) nversion = 1;
else if (strcmp(szversion, "2.0") == 0) nversion = 2;
else if (strcmp(szversion, "3.0") == 0) nversion = 3;
else if (strcmp(szversion, "4.0") == 0) nversion = 4;
if (nversion == -1) return errf("FATAL ERROR: Incorrect restart file version\n");
// Add the Step section for version 2
if (nversion == 2)
{
// set the file version to make sure we are using the correct format
SetFileVerion(0x0205);
// make sure we can redefine curves in the LoadData section
FEBioLoadDataSection* lcSection = new FEBioLoadDataSection(this);
lcSection->SetRedefineCurvesFlag(true);
m_map["LoadData"] = lcSection;
m_map["Step"] = new FEBioStepSection25(this);
}
// Add the Step section for version 3
if (nversion == 3)
{
// set the file version to make sure we are using the correct format
SetFileVerion(0x0300);
// make sure we can redefine curves in the LoadData section
FEBioLoadDataSection3* lcSection = new FEBioLoadDataSection3(this);
lcSection->SetRedefineCurvesFlag(true);
m_map["LoadData"] = lcSection;
m_map["Step"] = new FEBioStepSection3(this);
}
// Add the Step section for version 4
if (nversion == 4)
{
// set the file version to make sure we are using the correct format
SetFileVerion(0x0400);
// make sure we can redefine curves in the LoadData section
FEBioLoadDataSection3* lcSection = new FEBioLoadDataSection3(this);
lcSection->SetRedefineCurvesFlag(true);
m_map["LoadData"] = lcSection;
m_map["Step"] = new FEBioStepSection4(this);
}
// the first section has to be the archive
++tag;
if (tag != "Archive") return errf("FATAL ERROR: The first element must be the archive name\n");
char szar[256];
tag.value(szar);
// open the archive
DumpFile ar(fem);
if (ar.Open(szar) == false) return errf("FATAL ERROR: failed opening restart archive\n");
// read the archive
fem.Serialize(ar);
// set the module name
GetBuilder()->SetActiveModule(fem.GetModuleName());
// keep track of the number of steps
int steps0 = fem.Steps();
// read the rest of the restart input file
ret = ParseFile(tag);
// count nr of newly added steps
int steps1 = fem.Steps();
m_newSteps = steps1 - steps0;
}
catch (XMLReader::Error& e)
{
fprintf(stderr, "FATAL ERROR: %s\n", e.what());
ret = false;
}
catch (...)
{
fprintf(stderr, "FATAL ERROR: unrecoverable error (line %d)\n", m_xml.GetCurrentLine());
ret = false;
}
// close the XML file
m_xml.Close();
// we're done!
return ret;
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioOutputSection.cpp | .cpp | 11,503 | 405 | /*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 "FEBioOutputSection.h"
#include <FECore/SurfaceDataRecord.h>
#include <FECore/DomainDataRecord.h>
#include <FECore/FEModelDataRecord.h>
#include <FECore/FEModel.h>
#include <FECore/FSPath.h>
#include <FECore/FEPlotDataStore.h>
#include <FECore/FESurface.h>
bool string_to_int_vector(const char* szlist, std::vector<int>& list)
{
list.clear();
if (szlist == nullptr) return false;
if (szlist[0] == 0) return true;
char* ch = nullptr;
char* sz = (char*)szlist;
do
{
ch = strchr(sz, ',');
if (ch) *ch = 0;
int n0, n1, nn;
int nread = sscanf(sz, "%d:%d:%d", &n0, &n1, &nn);
switch (nread)
{
case 0: return false;
break;
case 1:
n1 = n0;
nn = 1;
break;
case 2:
nn = 1;
}
for (int i = n0; i <= n1; i += nn) list.push_back(i);
if (ch) *ch = ',';
sz = ch + 1;
}
while (ch != 0);
return true;
}
//-----------------------------------------------------------------------------
void FEBioOutputSection::Parse(XMLTag& tag)
{
if (tag.isleaf()) return;
++tag;
do
{
if (tag == "logfile" ) ParseLogfile(tag);
else if (tag == "plotfile") ParsePlotfile(tag);
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
}
//-----------------------------------------------------------------------------
void FEBioOutputSection::ParseLogfile(XMLTag &tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// Get the feb file path
const char* szpath = GetFileReader()->GetFilePath();
// see if the log file has any attributes
const char* szlog = tag.AttributeValue("file", true);
// If the log filename is not a path, but just a filename, make the filename
// relative to the input file, otherwise, leave the path alone.
if(szlog)
{
if(!FSPath::isPath(szlog))
{
char szfile[1024] = {0};
snprintf(szfile, sizeof(szfile), "%s%s", szpath, szlog);
GetFEBioImport()->SetLogfileName(szfile);
}
else
{
GetFEBioImport()->SetLogfileName(szlog);
}
}
if (tag.isleaf()) return;
++tag;
do
{
// get the (optional) file attribute
char szfilename[1024] = { 0 };
const char* szfile = tag.AttributeValue("file", true);
if (szfile)
{
// if we have a path, prepend the path's name
if (szpath && szpath[0])
{
snprintf(szfilename, sizeof(szfilename), "%s%s", szpath, szfile);
}
else strcpy(szfilename, szfile);
szfile = szfilename;
}
// get other attributes
const char* szdelim = tag.AttributeValue("delim", true);
const char* szformat = tag.AttributeValue("format", true);
bool bcomment = true;
const char* szcomment = tag.AttributeValue("comments", true);
if (szcomment != 0)
{
if (strcmp(szcomment, "on") == 0) bcomment = true;
else if (strcmp(szcomment, "off") == 0) bcomment = false;
}
// get the data attribute
const char* szdata = tag.AttributeValue("data");
// get the name attribute
const char* szname = tag.AttributeValue("name", true);
// allocate data record
DataRecord* pdr = nullptr;
if (tag == "node_data")
{
pdr = fecore_new<DataRecord>("node_data", &fem);
const char* sztmp = "set";
if (GetFileReader()->GetFileVersion() >= 0x0205) sztmp = "node_set";
const char* sz = tag.AttributeValue(sztmp, true);
if (sz)
{
FENodeSet* pns = mesh.FindNodeSet(sz);
if (pns == 0) throw XMLReader::InvalidAttributeValue(tag, sztmp, sz);
vector<int> items;
int n = pns->Size();
assert(n);
items.resize(n);
for (int i = 0; i < n; ++i) items[i] = (*pns)[i] + 1;
pdr->SetItemList(items);
}
else
{
std::vector<int> items;
string_to_int_vector(tag.szvalue(), items);
pdr->SetItemList(items);
}
}
else if (tag == "face_data")
{
pdr = fecore_new<DataRecord>("face_data", &fem);
const char* sz = tag.AttributeValue("surface");
FESurface* surf = mesh.FindSurface(sz);
if (surf == nullptr)
{
FEFacetSet* pfs = mesh.FindFacetSet(sz);
if (pfs == nullptr) throw XMLReader::InvalidAttributeValue(tag, "surface", sz);
surf = new FESurface(&fem);
surf->Create(*pfs);
surf->SetName(sz);
surf->Init();
mesh.AddSurface(surf);
}
std::vector<int> items;
string_to_int_vector(tag.szvalue(), items);
// TODO: This is a bit of a hack, because the face data record needs an FEItemList, but FESurface is derived from that.
FEFacetSet* fset = surf->GetFacetSet();
fset->SetSurface(surf);
pdr->SetItemList(fset, items);
}
else if (tag == "element_data")
{
pdr = fecore_new<DataRecord>("element_data", &fem);
const char* sztmp = "elset";
if (GetFileReader()->GetFileVersion() >= 0x0205) sztmp = "elem_set";
const char* sz = tag.AttributeValue(sztmp, true);
if (sz)
{
vector<int> dummy;
FEElementSet* pes = mesh.FindElementSet(sz);
if (pes == 0) throw XMLReader::InvalidAttributeValue(tag, sztmp, sz);
pdr->SetItemList(pes, dummy);
}
else
{
std::vector<int> items;
string_to_int_vector(tag.szvalue(), items);
pdr->SetItemList(items);
}
}
else if (tag == "rigid_body_data")
{
pdr = fecore_new<DataRecord>("rigid_body_data", &fem);
std::vector<int> items;
string_to_int_vector(tag.szvalue(), items);
pdr->SetItemList(items);
}
else if (tag == "rigid_connector_data")
{
pdr = fecore_new<DataRecord>("rigid_connector_data", &fem);
std::vector<int> items;
string_to_int_vector(tag.szvalue(), items);
pdr->SetItemList(items);
}
else if (tag == "surface_data")
{
FESurfaceDataRecord* prec = new FESurfaceDataRecord(&fem);
pdr = prec;
const char* sz = tag.AttributeValue("surface");
if (sz)
{
int surfIndex = mesh.FindSurfaceIndex(sz);
if (surfIndex == -1) throw XMLReader::InvalidAttributeValue(tag, "surface", sz);
prec->SetSurface(surfIndex);
}
}
else if (tag == "domain_data")
{
FEDomainDataRecord* prec = new FEDomainDataRecord(&fem);
pdr = prec;
const char* sz = tag.AttributeValue("domain", true);
if (sz)
{
int domainIndex = mesh.FindDomainIndex(sz);
if (domainIndex == -1) throw XMLReader::InvalidAttributeValue(tag, "domain", sz);
prec->SetDomain(domainIndex);
}
}
else if (tag == "model_data")
{
pdr = new FEModelDataRecord(&fem);
}
else throw XMLReader::InvalidTag(tag);
if (pdr)
{
pdr->SetData(szdata);
if (szname != 0) pdr->SetName(szname); else pdr->SetName(szdata);
if (szfile) pdr->SetFileName(szfile);
if (szdelim != 0) pdr->SetDelim(szdelim);
if (szformat != 0) pdr->SetFormat(szformat);
pdr->SetComments(bcomment);
GetFEBioImport()->AddDataRecord(pdr);
}
++tag;
}
while (!tag.isend());
}
//-----------------------------------------------------------------------------
void FEBioOutputSection::ParsePlotfile(XMLTag &tag)
{
FEModel& fem = *GetFEModel();
FEPlotDataStore& plotData = fem.GetPlotDataStore();
// get the plot file type. Must be "febio"!
const char* sz = tag.AttributeValue("type", true);
if (sz)
{
if ((strcmp(sz, "febio" ) != 0) &&
(strcmp(sz, "vtk" ) != 0)) throw XMLReader::InvalidAttributeValue(tag, "type", sz);
}
else sz = "febio";
plotData.SetPlotFileType(sz);
// get the optional plot file name
const char* szplt = tag.AttributeValue("file", true);
// If the plot filename is not a path, but just a filename, make the filename
// relative to the input file, otherwise, leave the path alone.
if(szplt)
{
if(!FSPath::isPath(szplt))
{
// Get the feb file path
const char* szpath = GetFileReader()->GetFilePath();
char szfile[1024] = {0};
snprintf(szfile, sizeof(szfile), "%s%s", szpath, szplt);
GetFEBioImport()->SetPlotfileName(szfile);
}
else
{
GetFEBioImport()->SetPlotfileName(szplt);
}
}
// read and store the plot variables
if (!tag.isleaf())
{
++tag;
do
{
if (tag == "var")
{
// get the variable name
const char* szt = tag.AttributeValue("type");
// get the item list
vector<int> item;
if (tag.isempty() == false) tag.value(item);
// see if a surface is referenced
const char* szsurf = tag.AttributeValue("surface", true);
const char* szeset = tag.AttributeValue("elem_set", true);
if (szsurf)
{
// make sure this tag does not have any children
if (!tag.isleaf()) throw XMLReader::InvalidTag(tag);
// see if we can find the facet set
FEMesh& m = GetFEModel()->GetMesh();
FEFacetSet* ps = m.FindFacetSet(szsurf);
// create a surface from the facet set
if (ps)
{
// create a new surface
FESurface* psurf = fecore_alloc(FESurface, &fem);
fem.GetMesh().AddSurface(psurf);
if (GetBuilder()->BuildSurface(*psurf, *ps) == false) throw XMLReader::InvalidTag(tag);
// Add the plot variable
const std::string& surfName = psurf->GetName();
plotData.AddPlotVariable(szt, item, surfName.c_str());
}
else throw XMLReader::InvalidAttributeValue(tag, "surface", szsurf);
}
else if (szeset)
{
// make sure this tag does not have any children
if (!tag.isleaf()) throw XMLReader::InvalidTag(tag);
// see if we can find the facet set
FEMesh& m = GetFEModel()->GetMesh();
FEElementSet* ps = m.FindElementSet(szeset);
// create a surface from the facet set
if (ps)
{
// Add the plot variable
plotData.AddPlotVariable(szt, item, szeset);
}
else throw XMLReader::InvalidAttributeValue(tag, "elem_set", szeset);
}
else
{
// Add the plot variable
plotData.AddPlotVariable(szt, item);
}
}
else if (tag=="compression")
{
int ncomp;
tag.value(ncomp);
plotData.SetPlotCompression(ncomp);
}
++tag;
}
while (!tag.isend());
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/stdafx.h | .h | 1,378 | 32 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
// this file is just here in case I decide to use precompiled headers for the library.
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FileImport.cpp | .cpp | 43,326 | 1,590 | /*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 "FileImport.h"
#include <FECore/FENodeDataMap.h>
#include <FECore/FESurfaceMap.h>
#include <FECore/FEModel.h>
#include <FECore/FEMaterial.h>
#include <FECore/FEModelParam.h>
#include <FECore/FESurface.h>
#include <FECore/FEEdge.h>
#include <FECore/FESurfaceLoad.h>
#include <FECore/FEPointFunction.h>
#include <FECore/FEGlobalData.h>
#include <FECore/log.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <sstream>
#include <iostream>
#include "FEBioImport.h"
#ifndef WIN32
#define strnicmp strncasecmp
#endif
//-----------------------------------------------------------------------------
// helper function to see if a string is a number
bool is_number(const char* sz)
{
char* cend;
double tmp = strtod(sz, &cend);
return ((cend == nullptr) || (cend[0] == 0));
}
//-----------------------------------------------------------------------------
FEObsoleteParamHandler::FEObsoleteParamHandler(XMLTag& tag, FECoreBase* pc) : m_pc(pc)
{
m_root = tag.Name();
}
void FEObsoleteParamHandler::AddParam(const char* oldName, const char* newName, FEParamType paramType)
{
FEObsoleteParam p = { oldName, newName, paramType };
m_param.push_back(p);
}
bool FEObsoleteParamHandler::ProcessTag(XMLTag& tag)
{
std::string path = tag.relpath(m_root.c_str());
for (int i = 0; i < m_param.size(); ++i)
{
if (path == m_param[i].oldName)
{
m_param[i].readIn = true;
switch (m_param[i].paramType)
{
case FE_PARAM_INVALID: break; // parameter will be ignored
case FE_PARAM_BOOL : tag.value(m_param[i].bVal); break;
case FE_PARAM_INT : tag.value(m_param[i].iVal); break;
case FE_PARAM_DOUBLE : tag.value(m_param[i].gVal); break;
default:
assert(false);
}
return true;
}
}
return false;
}
void FEObsoleteParamHandler::MapParameters()
{
FEModel* fem = m_pc->GetFEModel();
feLogEx(fem, "\n");
for (FEObsoleteParam& p : m_param)
{
if (p.readIn)
{
if (p.newName == nullptr)
{
feLogWarningEx(fem, "Obsolete parameter %s is ignored!", p.oldName);
}
else
{
ParamString ps(p.newName);
FEParam* pp = m_pc->FindParameter(ps);
if (pp == nullptr)
{
feLogErrorEx(fem, "Failed to map obsolete parameter %s. Could not find new parameter %s", p.oldName, p.newName);
}
else
{
if (pp->type() == p.paramType)
{
switch (pp->type())
{
case FE_PARAM_BOOL : pp->value<bool> () = p.bVal; break;
case FE_PARAM_INT : pp->value<int> () = p.iVal; break;
case FE_PARAM_DOUBLE: pp->value<double>() = p.gVal; break;
}
feLogEx(fem, "Successfully mapped obsolete parameter %s to %s\n", p.oldName, p.newName);
}
else if ((pp->type() == FE_PARAM_DOUBLE_MAPPED) && (p.paramType == FE_PARAM_DOUBLE))
{
FEParamDouble& v = pp->value<FEParamDouble>();
v = p.gVal;
feLogEx(fem, "Successfully mapped obsolete parameter %s to %s\n", p.oldName, p.newName);
}
else
{
feLogErrorEx(fem, "Failed to map obsolete parameter %s. New parameter %s has different type.", p.oldName, p.newName);
}
}
}
}
}
}
//-----------------------------------------------------------------------------
FEFileException::FEFileException()
{
m_szerr[0] = 0;
}
//-----------------------------------------------------------------------------
FEFileException::FEFileException(const char* sz, ...)
{
// get a pointer to the argument list
va_list args;
// make the message
va_start(args, sz);
vsnprintf(m_szerr, sizeof(m_szerr), sz, args);
va_end(args);
}
//-----------------------------------------------------------------------------
void FEFileException::SetErrorString(const char* sz, ...)
{
// get a pointer to the argument list
va_list args;
// make the message
va_start(args, sz);
vsnprintf(m_szerr, sizeof(m_szerr), sz, args);
va_end(args);
}
//-----------------------------------------------------------------------------
FEModel* FEFileSection::GetFEModel() { return &GetBuilder()->GetFEModel(); }
//-----------------------------------------------------------------------------
FEModelBuilder* FEFileSection::GetBuilder() { return m_pim->GetBuilder(); }
//-----------------------------------------------------------------------------
void FEFileSection::SetInvalidTagHandler(FEInvalidTagHandler* ith)
{
m_ith = ith;
}
//-----------------------------------------------------------------------------
void FEFileSection::value(XMLTag& tag, int& n)
{
const char* val = tag.szvalue();
if (is_number(val) == false) throw XMLReader::InvalidValue(tag);
n = atoi(val);
}
//-----------------------------------------------------------------------------
void FEFileSection::value(XMLTag& tag, double& g)
{
g = atof(tag.szvalue());
}
//-----------------------------------------------------------------------------
void FEFileSection::value(XMLTag& tag, bool& b)
{
const char* sz = tag.szvalue();
int n = 0;
sscanf(sz, "%d", &n);
b = (n != 0);
}
//-----------------------------------------------------------------------------
void FEFileSection::value(XMLTag& tag, vec2d& v)
{
const char* sz = tag.szvalue();
int n = sscanf(sz, "%lg,%lg", &v.r[0], &v.r[1]);
if (n != 3) throw XMLReader::XMLSyntaxError(tag.m_nstart_line);
}
void FEFileSection::value(XMLTag& tag, vec3d& v)
{
const char* sz = tag.szvalue();
int n = sscanf(sz, "%lg,%lg,%lg", &v.x, &v.y, &v.z);
if (n != 3) throw XMLReader::XMLSyntaxError(tag.m_nstart_line);
}
//-----------------------------------------------------------------------------
void FEFileSection::value(XMLTag& tag, mat3d& m)
{
const char* sz = tag.szvalue();
double xx, xy, xz, yx, yy, yz, zx, zy, zz;
int n = sscanf(sz, "%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg", &xx, &xy, &xz, &yx, &yy, &yz, &zx, &zy, &zz);
if (n != 9) throw XMLReader::XMLSyntaxError(tag.m_nstart_line);
m = mat3d(xx, xy, xz, yx, yy, yz, zx, zy, zz);
}
//-----------------------------------------------------------------------------
void FEFileSection::value(XMLTag& tag, mat3ds& m)
{
const char* sz = tag.szvalue();
double x, y, z, xy, yz, xz;
int n = sscanf(sz, "%lg,%lg,%lg,%lg,%lg,%lg", &x, &y, &z, &xy, &yz, &xz);
if (n != 6) throw XMLReader::XMLSyntaxError(tag.m_nstart_line);
m = mat3ds(x, y, z, xy, yz, xz);
}
//-----------------------------------------------------------------------------
void FEFileSection::value(XMLTag& tag, tens3drs& m)
{
double v[18];
int n = value(tag, v, 18);
if (n != 18) throw XMLReader::InvalidValue(tag);
for (int i = 0; i<18; ++i) m.d[i] = v[i];
}
//-----------------------------------------------------------------------------
void FEFileSection::value(XMLTag& tag, char* szstr)
{
const char* sz = tag.szvalue();
strcpy(szstr, sz);
}
//-----------------------------------------------------------------------------
void FEFileSection::value(XMLTag& tag, std::string& v)
{
v = tag.szvalue();
}
//-----------------------------------------------------------------------------
void FEFileSection::value(XMLTag& tag, std::vector<int>& v)
{
v.clear();
const char* sz = tag.szvalue();
do
{
const char* sze = strchr(sz, ',');
int d = atoi(sz);
v.push_back(d);
if (sze) sz = sze + 1;
else sz = nullptr;
}
while (sz);
}
//-----------------------------------------------------------------------------
void FEFileSection::value(XMLTag& tag, std::vector<double>& v)
{
v.clear();
const char* sz = tag.szvalue();
do
{
const char* sze = strchr(sz, ',');
const char* szc = strchr(sz, ':');
if ((szc == nullptr) || (sze && (szc > sze)))
{
double d = atof(sz);
v.push_back(d);
}
else
{
double d0 = atof(sz);
double d1 = atof(szc + 1);
double di = 1.0;
// see if there is a second colon
const char* szc2 = strchr(szc + 1, ':');
if (szc2 && ((sze == nullptr) || (szc2 < sze))) di = atof(szc2 + 1);
if (di > 0)
{
const double eps = 1e-12;
for (double d = d0; d <= d1 + eps; d += di)
{
v.push_back(d);
}
}
else throw XMLReader::InvalidValue(tag);
}
if (sze) sz = sze + 1;
else sz = nullptr;
}
while (sz);
}
//-----------------------------------------------------------------------------
int FEFileSection::value(XMLTag& tag, int* pi, int n)
{
const char* sz = tag.szvalue();
int nr = 0;
for (int i = 0; i<n; ++i)
{
const char* sze = strchr(sz, ',');
pi[i] = atoi(sz);
nr++;
if (sze) sz = sze + 1;
else break;
}
return nr;
}
//-----------------------------------------------------------------------------
int FEFileSection::value(XMLTag& tag, double* pf, int n)
{
const char* sz = tag.szvalue();
int nr = 0;
for (int i = 0; i < n; ++i)
{
const char* sze = strchr(sz, ',');
pf[i] = atof(sz);
nr++;
if (sze) sz = sze + 1;
else break;
}
return nr;
}
//-----------------------------------------------------------------------------
int FEFileSection::ReadNodeID(XMLTag& tag)
{
int n = atoi(tag.AttributeValue("id"));
int node = GetBuilder()->FindNodeFromID(n);
if (node == -1) throw FEFileException("Invalid node ID");
return node;
}
//-----------------------------------------------------------------------------
int enumValue(const char* val, const char* szenum)
{
if ((val == nullptr) || (szenum == nullptr)) return -1;
// get the string's length.
// there could be a comma, so correct for that.
size_t L = strlen(val);
const char* c = strchr(val, ',');
if (c) L = c - val;
const char* ch = szenum;
int n = 0;
while (ch && *ch)
{
size_t l = strlen(ch);
int nval = n;
// see if the value of the enum is overridden
const char* ce = strrchr(ch, '=');
if (ce)
{
l = ce - ch;
nval = atoi(ce + 1);
}
if ((L==l) && (strnicmp(ch, val, l) == 0))
{
return nval;
}
ch = strchr(ch, '\0');
if (ch) ch++;
n++;
}
return -1;
}
//-----------------------------------------------------------------------------
bool FEFileSection::parseEnumParam(FEParam* pp, const char* val)
{
// get the enums
const char* szenums = pp->enums();
if (szenums == nullptr) return false;
// special cases
if (szenums[0] == '$')
{
FEModel* fem = GetFEModel();
char var[256] = { 0 };
const char* chl = strchr(szenums, '('); assert(chl);
const char* chr = strchr(szenums, ')'); assert(chr);
strncpy(var, chl + 1, chr - chl - 1);
if (strncmp(var, "dof_list", 8) == 0)
{
DOFS& dofs = GetFEModel()->GetDOFS();
const char* szvar = nullptr;
if (var[8] == ':') szvar = var + 9;
if (pp->type() == FE_PARAM_INT)
{
int ndof = dofs.GetDOF(val, szvar);
if (ndof < 0) return false;
pp->value<int>() = ndof;
return true;
}
else if (pp->type() == FE_PARAM_STD_VECTOR_INT)
{
std::vector<int>& v = pp->value<std::vector<int> >();
return dofs.ParseDOFString(val, v, szvar);
}
else return false;
}
else if (strcmp(var, "solutes") == 0)
{
int n = -1;
if (is_number(val)) n = atoi(val);
else
{
FEGlobalData* pd = fem->FindGlobalData(val);
if (pd == nullptr) return false;
n = pd->GetID(); assert(n > 0);
}
pp->value<int>() = n;
return true;
}
else if (strcmp(var, "sbms") == 0)
{
int n = -1;
if (is_number(val)) n = atoi(val);
else
{
FEGlobalData* pd = fem->FindGlobalData(val);
if (pd == nullptr) return false;
n = pd->GetID(); assert(n > 0);
}
pp->value<int>() = n;
return true;
}
else if (strcmp(var, "species") == 0)
{
int n = -1;
if (is_number(val)) n = atoi(val);
else
{
// NOTE: This assumes that the solutes are defined before the SBMS!
int m = fem->FindGlobalDataIndex(val);
if (m == -1) return false;
n = m + 1;
}
pp->value<int>() = n;
return true;
}
else if (strcmp(var, "rigid_materials") == 0)
{
if (is_number(val))
{
int n = atoi(val);
pp->value<int>() = n;
}
else
{
FEMaterial* mat = fem->FindMaterial(val);
if (mat == nullptr) return false;
int n = mat->GetID();
pp->value<int>() = n;
}
return true;
}
else return false;
}
else if (strncmp(szenums, "@factory_list", 13) == 0)
{
int classID = atoi(szenums + 14);
FECoreKernel& fecore = FECoreKernel::GetInstance();
for (int i = 0; i < fecore.FactoryClasses(); ++i)
{
const FECoreFactory* fac = fecore.GetFactoryClass(i);
if (fac->GetSuperClassID() == classID)
{
if (strcmp(fac->GetTypeStr(), val) == 0)
{
pp->value<int>() = i;
return true;
}
}
}
return false;
}
switch (pp->type())
{
case FE_PARAM_INT:
{
int n = enumValue(val, szenums);
if (n != -1) pp->value<int>() = n;
else
{
// see if the value is an actual number
if (is_number(val))
{
n = atoi(val);
pp->value<int>() = n;
}
}
return (n != -1);
}
break;
case FE_PARAM_STD_VECTOR_INT:
{
std::vector<int>& v = pp->value<std::vector<int> >();
v.clear();
const char* tmp = val;
while (tmp)
{
int n = enumValue(tmp, szenums);
v.push_back(n);
tmp = strchr(tmp, ',');
if (tmp) tmp++;
}
return true;
}
break;
};
return false;
}
//-----------------------------------------------------------------------------
std::vector<std::string> split_string(const std::string& s, char delim)
{
std::stringstream ss(s);
std::string tmp;
std::vector<std::string> vs;
while (std::getline(ss, tmp, delim))
{
vs.push_back(tmp);
}
return vs;
}
std::string trim_string(const std::string& s) {
auto start = std::find_if_not(s.begin(), s.end(), ::isspace);
auto end = std::find_if_not(s.rbegin(), s.rend(), ::isspace).base();
if (start >= end) return ""; // All spaces or empty string
return std::string(start, end);
}
//-----------------------------------------------------------------------------
//! This function parses a parameter list
bool FEFileSection::ReadParameter(XMLTag& tag, FEParameterList& pl, const char* szparam, FECoreBase* pc, bool parseAttributes)
{
FEParam* pp = nullptr;
const char* szparamName = (szparam == 0 ? tag.Name() : szparam);
if (tag == "add_param")
{
// get the name and value
double v = 0.0; tag.value(v);
const char* szname = tag.AttributeValue("name");
// make sure this parameter does not exist yet
pp = pl.FindFromName(szname);
if (pp) throw XMLReader::InvalidTag(tag);
// add a new user parameter
pp = pl.AddParameter(new double(v), FE_PARAM_DOUBLE, 1, strdup(szname));
pp->SetFlags(FEParamFlag::FE_PARAM_USER);
}
else
{
// see if we can find this parameter
pp = pl.FindFromName(szparamName);
}
if (pp == 0) return false;
if (pp->IsObsolete())
{
feLogWarning("parameter '%s' is obsolete.", szparamName);
}
if (pp->dim() == 1)
{
switch (pp->type())
{
case FE_PARAM_DOUBLE:
{
// make sure the type attribute is not defined
// This most likely means a user thinks this parameter can be mapped
// but the corresponding parameter is not a FEModelParam
XMLAtt* att = tag.Attribute("type", true);
if (att)
throw XMLReader::InvalidAttribute(tag, "type");
value(tag, pp->value<double >());
}
break;
case FE_PARAM_INT:
{
const char* szenum = pp->enums();
if (szenum == 0)
{
value(tag, pp->value<int>());
}
else
{
bool bfound = parseEnumParam(pp, tag.szvalue());
if (bfound == false)
{
if ((m_ith == nullptr) || (m_ith->ProcessTag(tag) == false)) {
throw XMLReader::InvalidValue(tag);
}
}
}
}
break;
case FE_PARAM_STD_VECTOR_INT:
{
const char* szenum = pp->enums();
if (szenum == 0)
{
std::vector<int>& v = pp->value< std::vector<int> >();
value(tag, v);
}
else
{
bool bfound = parseEnumParam(pp, tag.szvalue());
if (bfound == false) throw XMLReader::InvalidValue(tag);
}
}
break;
case FE_PARAM_STD_VECTOR_DOUBLE:
{
std::vector<double>& v = pp->value< std::vector<double> >();
value(tag, v);
}
break;
case FE_PARAM_BOOL: value(tag, pp->value<bool >()); break;
case FE_PARAM_VEC3D:
{
// make sure the type attribute is not defined
// This most likely means a user thinks this parameter can be mapped
// but the corresponding parameter is not a FEModelParam
// const char* sztype = tag.AttributeValue("type", true);
// if (sztype) throw XMLReader::InvalidAttribute(tag, "type");
value(tag, pp->value<vec3d >());
}
break;
case FE_PARAM_MAT3D: value(tag, pp->value<mat3d >()); break;
case FE_PARAM_MAT3DS: value(tag, pp->value<mat3ds >()); break;
case FE_PARAM_TENS3DRS: value(tag, pp->value<tens3drs>()); break;
case FE_PARAM_STRING: value(tag, pp->cvalue()); break;
case FE_PARAM_STD_STRING: value(tag, pp->value<string>()); break;
case FE_PARAM_DATA_ARRAY:
{
// get the surface map
FEDataArray& map = pp->value<FEDataArray>();
// Make sure that the tag is a leaf
if (!tag.isleaf()) throw XMLReader::InvalidValue(tag);
// read the surface map data
const char* szmap = tag.AttributeValue("surface_data", true);
if (szmap)
{
FESurfaceMap* pmap = dynamic_cast<FESurfaceMap*>(&map);
if (pmap == 0) throw XMLReader::InvalidTag(tag);
FESurfaceMap* pdata = dynamic_cast<FESurfaceMap*>(GetFEModel()->GetMesh().FindDataMap(szmap));
if (pdata == 0) throw XMLReader::InvalidAttributeValue(tag, "surface_data");
// make sure the types match
if (map.DataSize() != pdata->DataSize()) throw XMLReader::InvalidAttributeValue(tag, "surface_data", szmap);
// copy data
*pmap = *pdata;
}
else
{
const char* szmap = tag.AttributeValue("node_data", true);
if (szmap)
{
FENodeDataMap* pmap = dynamic_cast<FENodeDataMap*>(&map);
if (pmap == 0) throw XMLReader::InvalidTag(tag);
FENodeDataMap* pdata = dynamic_cast<FENodeDataMap*>(GetFEModel()->GetMesh().FindDataMap(szmap));
if (pdata == 0) throw XMLReader::InvalidAttributeValue(tag, "node_data");
// make sure the types match
if (map.DataSize() != pdata->DataSize()) throw XMLReader::InvalidAttributeValue(tag, "node_data", szmap);
// copy data
*pmap = *pdata;
}
else
{
FEDataType dataType = map.DataType();
if (dataType == FE_DOUBLE)
{
double v;
tag.value(v);
map.fillValue(v);
}
else if (dataType == FE_VEC2D)
{
double v[2] = { 0 };
tag.value(v, 2);
map.fillValue(vec2d(v[0], v[1]));
}
else if (dataType == FE_VEC3D)
{
double v[3] = { 0 };
tag.value(v, 3);
map.fillValue(vec3d(v[0], v[1], v[2]));
}
}
}
};
break;
case FE_PARAM_STD_VECTOR_VEC2D:
{
std::vector<vec2d>& data = pp->value< std::vector<vec2d> >();
data.clear();
double d[2];
++tag;
do
{
int nread = tag.value(d, 2);
if (nread != 2) throw XMLReader::InvalidValue(tag);
data.push_back(vec2d(d[0], d[1]));
++tag;
}
while (!tag.isend());
}
break;
case FE_PARAM_STD_VECTOR_STRING:
{
// make sure this is leaf
if (tag.isempty()) throw XMLReader::InvalidValue(tag);
std::vector<string>& data = pp->value< std::vector<string> >();
// Note that this parameter is read in item per item, not all at once!
string s;
tag.value(s);
data.push_back(s);
}
break;
case FE_PARAM_DOUBLE_MAPPED:
{
// get the model parameter
FEParamDouble& p = pp->value<FEParamDouble>();
// get the type
const char* sztype = tag.AttributeValue("type", true);
// if the type is not specified, we'll try to determine if
// it's a math expression or a const
if (sztype == 0)
{
const char* szval = tag.szvalue();
sztype = (is_number(szval) ? "const" : "math");
}
// allocate valuator
FEScalarValuator* val = fecore_new<FEScalarValuator>(sztype, GetFEModel());
if (val == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
// Figure out the item list
FEItemList* itemList = nullptr;
if (dynamic_cast<FESurfaceLoad*>(pc))
{
FESurfaceLoad* psl = dynamic_cast<FESurfaceLoad*>(pc);
itemList = psl->GetSurface().GetFacetSet();
}
p.SetItemList(itemList);
// mapped values require special treatment
// The value is just the name of the map, but the problem is that
// these maps may not be defined yet.
// So, we add them to the FEBioModel, which will process mapped
// parameters after the rest of the file is processed
if (strcmp(sztype, "map") == 0)
{
string mapName = tag.szvalue();
string trimmedName = trim_string(mapName);
if (trimmedName.empty()) throw XMLReader::InvalidValue(tag);
GetBuilder()->AddMappedParameter(pp, pc, trimmedName.c_str());
}
else {
// read the parameter list
ReadParameterList(tag, val);
}
// assign the valuator to the parameter
p.setValuator(val);
}
break;
case FE_PARAM_VEC3D_MAPPED:
{
// get the model parameter
FEParamVec3& p = pp->value<FEParamVec3>();
// get the type
const char* sztype = tag.AttributeValue("type", true);
// ignore "user" types
if (sztype && strcmp(sztype, "user") == 0)
{
return true;
}
if (sztype == 0) sztype = "vector";
// allocate valuator
FEVec3dValuator* val = fecore_new<FEVec3dValuator>(sztype, GetFEModel());
if (val == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
// mapped values require special treatment
// The value is just the name of the map, but the problem is that
// these maps may not be defined yet.
// So, we add them to the FEBioModel, which will process mapped
// parameters after the rest of the file is processed
if (strcmp(sztype, "map") == 0)
{
string mapName = tag.szvalue();
string trimmedName = trim_string(mapName);
if (trimmedName.empty()) throw XMLReader::InvalidValue(tag);
GetBuilder()->AddMappedParameter(pp, pc, trimmedName.c_str());
}
else {
// read the parameter list
ReadParameterList(tag, val);
}
// assign the valuator to the parameter
p.setValuator(val);
}
break;
case FE_PARAM_MAT3D_MAPPED:
{
// get the model parameter
FEParamMat3d& p = pp->value<FEParamMat3d>();
// get the type
const char* sztype = tag.AttributeValue("type", true);
if (sztype == 0) sztype = "const";
// ignore user type
if (sztype && (strcmp(sztype, "user") == 0)) return true;
// allocate valuator
FEMat3dValuator* val = fecore_new<FEMat3dValuator>(sztype, GetFEModel());
if (val == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
// mapped values require special treatment
// The value is just the name of the map, but the problem is that
// these maps may not be defined yet.
// So, we add them to the FEBioModel, which will process mapped
// parameters after the rest of the file is processed
if (strcmp(sztype, "map") == 0)
{
string mapName = tag.szvalue();
string trimmedName = trim_string(mapName);
if (trimmedName.empty()) throw XMLReader::InvalidValue(tag);
GetBuilder()->AddMappedParameter(pp, pc, trimmedName.c_str());
}
else {
// read the parameter list
ReadParameterList(tag, val);
}
// assign the valuator to the parameter
p.setValuator(val);
}
break;
case FE_PARAM_MAT3DS_MAPPED:
{
// get the model parameter
FEParamMat3ds& p = pp->value<FEParamMat3ds>();
// get the type
const char* sztype = tag.AttributeValue("type", true);
if (sztype == 0) sztype = "const";
// allocate valuator
FEMat3dsValuator* val = fecore_new<FEMat3dsValuator>(sztype, GetFEModel());
if (val == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
// mapped values require special treatment
// The value is just the name of the map, but the problem is that
// these maps may not be defined yet.
// So, we add them to the FEBioModel, which will process mapped
// parameters after the rest of the file is processed
if (strcmp(sztype, "map") == 0)
{
string mapName = tag.szvalue();
string trimmedName = trim_string(mapName);
if (trimmedName.empty()) throw XMLReader::InvalidValue(tag);
GetBuilder()->AddMappedParameter(pp, pc, trimmedName.c_str());
}
else {
// read the parameter list
ReadParameterList(tag, val);
}
// assign the valuator to the parameter
p.setValuator(val);
// do the initialization.
// TODO: Is this a good place to do this?
if (val->Init() == false) throw XMLReader::InvalidTag(tag);
}
break; default:
assert(false);
return false;
}
}
else
{
switch (pp->type())
{
case FE_PARAM_INT: value(tag, pp->pvalue<int >(), pp->dim()); break;
case FE_PARAM_DOUBLE: value(tag, pp->pvalue<double>(), pp->dim()); break;
case FE_PARAM_DOUBLE_MAPPED:
{
if (tag.isleaf())
{
// find the type attribute
const char* sztype = tag.AttributeValue("type", true);
if (sztype == nullptr) sztype = "const";
if (strcmp(sztype, "const") == 0)
{
std::vector<double> v(pp->dim());
int m = tag.value(&v[0], pp->dim());
if (m != pp->dim()) throw XMLReader::InvalidValue(tag);
for (int i = 0; i < pp->dim(); ++i)
{
FEParamDouble& pi = pp->value<FEParamDouble>(i);
pi = v[i];
}
}
else if (strcmp(sztype, "math") == 0)
{
string sval = tag.szvalue();
vector<string> s = split_string(sval, ',');
if (s.size() != pp->dim()) throw XMLReader::InvalidValue(tag);
for (int i = 0; i < pp->dim(); ++i)
{
FEParamDouble& pi = pp->value<FEParamDouble>(i);
FEMathValue* v = fecore_alloc(FEMathValue, GetFEModel());
v->setMathString(s[i]);
pi.setValuator(v);
}
}
else if (strcmp(sztype, "map") == 0)
{
string sval = tag.szvalue();
vector<string> s = split_string(sval, ',');
if (s.size() != pp->dim()) throw XMLReader::InvalidValue(tag);
for (int i = 0; i < pp->dim(); ++i)
{
FEParamDouble& pi = pp->value<FEParamDouble>(i);
// allocate valuator
FEScalarValuator* val = fecore_alloc(FEMappedValue, GetFEModel());
// Figure out the item list
FEItemList* itemList = nullptr;
if (dynamic_cast<FESurfaceLoad*>(pc))
{
FESurfaceLoad* psl = dynamic_cast<FESurfaceLoad*>(pc);
itemList = psl->GetSurface().GetFacetSet();
}
pi.SetItemList(itemList);
// trim the string
std::string trimmedName = trim_string(s[i]);
// mapped values require special treatment
// The value is just the name of the map, but the problem is that
// these maps may not be defined yet.
// So, we add them to the FEBioModel, which will process mapped
// parameters after the rest of the file is processed
GetBuilder()->AddMappedParameter(pp, pc, trimmedName.c_str(), i);
// assign the valuator to the parameter
pi.setValuator(val);
}
}
else throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
}
else
{
int n = 0;
++tag;
do {
// find the type attribute
const char* sztype = tag.AttributeValue("type", true);
if (sztype == nullptr)
{
// if the type is not specified, we'll try to determine if
// it's a math expression or a const
const char* szval = tag.szvalue();
sztype = (is_number(szval) ? "const" : "math");
}
if (strcmp(sztype, "const") == 0)
{
double v = 0.0;
tag.value(v);
FEParamDouble& pi = pp->value<FEParamDouble>(n);
pi = v;
}
else if (strcmp(sztype, "math") == 0)
{
string sval = tag.szvalue();
FEParamDouble& pi = pp->value<FEParamDouble>(n);
FEMathValue* v = fecore_alloc(FEMathValue, GetFEModel());
v->setMathString(sval);
pi.setValuator(v);
// do the initialization.
// TODO: Is this a good place to do this?
if (v->Init() == false) throw XMLReader::InvalidTag(tag);
}
else throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
++tag;
n++;
if (n > pp->dim()) throw XMLReader::InvalidTag(tag);
}
while (!tag.isend());
}
}
break;
default:
assert(false);
throw XMLReader::InvalidValue(tag);
break;
}
}
if (parseAttributes)
{
for (XMLAtt& att : tag.m_att)
{
const char* szat = att.m_name.c_str();
// If we get here, the container did not understand the attribute.
// If the attribute is a "lc", we interpret it as a load curve
if (strcmp(szat, "lc") == 0)
{
int lc = atoi(att.m_val.c_str()) - 1;
if (lc < 0) throw XMLReader::InvalidAttributeValue(tag, szat, att.m_val.c_str());
// make sure the parameter is volatile
if (pp->IsVolatile() == false)
{
throw XMLReader::InvalidAttribute(tag, szat);
}
GetFEModel()->AttachLoadController(pp, lc);
}
/* else
{
throw XMLReader::InvalidAttributeValue(tag, szat, tag.m_att[i].m_szatv);
}
*/
// This is not true. Parameters can have attributes that are used for other purposes. E.g. The local fiber option.
// else felog.printf("WARNING: attribute \"%s\" of parameter \"%s\" ignored (line %d)\n", szat, tag.Name(), tag.m_ncurrent_line-1);
}
}
// Set the watch flag since the parameter was read in successfully
// (This requires that the parameter was declared with a watch variable)
pp->SetWatchFlag(true);
return true;
}
//-----------------------------------------------------------------------------
void FEFileSection::ReadAttributes(XMLTag& tag, FECoreBase* pc)
{
FEParameterList& pl = pc->GetParameterList();
// process all the other attributes
for (XMLAtt& att : tag.m_att)
{
const char* szatt = att.name();
const char* szval = att.cvalue();
if ((att.m_bvisited == false) && szatt && szval)
{
FEParam* param = pl.FindFromName(szatt);
if (param && (param->GetFlags() & FE_PARAM_ATTRIBUTE))
{
switch (param->type())
{
case FE_PARAM_INT:
{
if (param->enums() == nullptr)
param->value<int>() = atoi(szval);
else
{
if (parseEnumParam(param, szval) == false) throw XMLReader::InvalidAttributeValue(tag, szatt, szval);
}
break;
}
case FE_PARAM_DOUBLE: param->value<double>() = atof(szval); break;
case FE_PARAM_STD_STRING: param->value<std::string>() = szval; break;
default:
throw XMLReader::InvalidAttributeValue(tag, szatt, szval);
}
}
else if (strcmp("name", szatt) == 0) pc->SetName(szval);
else if (strcmp("id" , szatt) == 0) pc->SetID(atoi(szval));
else if (strcmp("lc" , szatt) == 0) { /* don't do anything. Loadcurves are processed elsewhere. */ }
else
{
if (m_pim->StopOnUnknownAttribute())
{
throw XMLReader::InvalidAttribute(tag, szatt);
}
else
{
fprintf(stderr, "WARNING: Unknown attribute %s in tag %s\n", szatt, tag.Name());
}
}
}
}
}
//-----------------------------------------------------------------------------
//! This function parses a parameter list
bool FEFileSection::ReadParameter(XMLTag& tag, FECoreBase* pc, const char* szparam, bool parseAttributes)
{
// get the parameter list
FEParameterList& pl = pc->GetParameterList();
// see if we can find this parameter
if (ReadParameter(tag, pl, szparam, pc, parseAttributes) == false)
{
// if we get here, the parameter is not found.
// See if the parameter container has defined a property of this name
int n = pc->FindPropertyIndex(tag.Name());
if (n >= 0)
{
FEProperty* prop = pc->PropertyClass(n);
if (prop->IsReference())
{
// get the reference. It is either defined by the ref attribute
// or the value of the tag.
if (tag.isleaf() == false) throw XMLReader::InvalidValue(tag);
const char* szref = tag.AttributeValue("ref", true);
if (szref == nullptr) szref = tag.szvalue();
const char* sztag = tag.Name();
FEMesh& mesh = GetFEModel()->GetMesh();
// This property should reference an existing class
SUPER_CLASS_ID classID = prop->GetSuperClassID();
/* if (classID == FEITEMLIST_ID)
{
FENodeSet* nodeSet = mesh.FindNodeSet(szref);
if (nodeSet == nullptr) throw XMLReader::InvalidValue(tag);
prop->SetProperty(nodeSet);
}
else */if (classID == FESURFACE_ID)
{
FEModelBuilder* builder = GetBuilder();
FEFacetSet* facetSet = mesh.FindFacetSet(szref);
if (facetSet == nullptr) throw XMLReader::InvalidValue(tag);
FESurface* surface = fecore_alloc(FESurface, GetFEModel());
GetBuilder()->BuildSurface(*surface, *facetSet);
mesh.AddSurface(surface);
prop->SetProperty(surface);
}
else if (classID == FEEDGE_ID)
{
FEModelBuilder* builder = GetBuilder();
FESegmentSet* edgeList = mesh.FindSegmentSet(szref);
if (edgeList == nullptr) throw XMLReader::InvalidValue(tag);
FEEdge* edge = dynamic_cast<FEEdge*>(prop->get(0));
if (edge == nullptr) throw XMLReader::InvalidValue(tag);
if (GetBuilder()->BuildEdge(*edge, *edgeList))
mesh.AddEdge(edge);
else
throw XMLReader::InvalidValue(tag);
}
else throw XMLReader::InvalidTag(tag);
}
else
{
// see if the property is already allocated
if ((prop->IsArray() == false) && (prop->get(0)))
{
// If so, let's just read the parameters
FECoreBase* pc = prop->get(0);
if (tag.isleaf() == false) ReadParameterList(tag, pc);
}
else
{
const char* sztype = tag.AttributeValue("type", true);
// If the type attribute is omitted we try the property's default type,
// otherwise assume the tag's name is the default type
if (sztype == nullptr)
{
if (prop->GetDefaultType()) sztype = prop->GetDefaultType();
else sztype = tag.Name();
}
// HACK for getting passed the old "user" fiber type.
if (strcmp(sztype, "user") == 0) sztype = "map";
// HACK for mapping load curves to FEFunction1D
const char* szlc = tag.AttributeValue("lc", true);
if (szlc && (tag.m_att.size() == 1) && (prop->GetSuperClassID() == FEFUNCTION1D_ID))
{
double v = 1;
tag.value(v);
FEPointFunction* f = fecore_alloc(FEPointFunction, GetFEModel()); assert(f);
prop->SetProperty(f);
int lc = atoi(szlc) - 1;
GetBuilder()->MapLoadCurveToFunction(f, lc, v);
}
else
{
// try to allocate the class
FECoreBase* pp = fecore_new<FECoreBase>(prop->GetSuperClassID(), sztype, GetFEModel());
if (pp == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
prop->SetProperty(pp);
// read the property data
if (tag.isleaf() == false)
{
ReadParameterList(tag, pp);
}
else if (tag.isempty() == false)
{
if ((tag.szvalue() != nullptr) && (tag.szvalue()[0] != 0))
{
// parse attributes first
ReadAttributes(tag, pp);
// There should be a parameter with the same name as the type
if (ReadParameter(tag, pp->GetParameterList(), sztype, pp) == false)
throw XMLReader::InvalidValue(tag);
}
}
else
{
// we get here if the property was defined with an empty tag.
// We should still validate it.
int NP = pp->PropertyClasses();
for (int i = 0; i < NP; ++i)
{
FEProperty* pi = pp->PropertyClass(i);
bool a = pi->IsRequired();
bool b = (pi->size() == 0);
if (a && b)
{
std::string name = pp->GetName();
if (name.empty()) name = prop->GetName();
throw FEBioImport::MissingProperty(name, pi->GetName());
}
}
}
}
}
return true;
}
}
else
{
// backward compatibility hack for older formats (< v 3.0)
/* if (strcmp(tag.Name(), "fiber") == 0)
{
return ReadParameter(tag, pc, "mat_axis", parseAttributes);
}
else return false;
*/ return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
void FEFileSection::ReadParameterList(XMLTag& tag, FEParameterList& pl)
{
// Make sure there is something to read
if (tag.isleaf() || tag.isempty()) return;
// parse the child tags
++tag;
do
{
if (ReadParameter(tag, pl, 0, 0) == false) throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
}
//-----------------------------------------------------------------------------
void FEFileSection::ReadParameterList(XMLTag& tag, FECoreBase* pc)
{
// parse attributes first
ReadAttributes(tag, pc);
// process the parameter lists
if (!tag.isleaf())
{
++tag;
do
{
if (ReadParameter(tag, pc) == false)
{
if ((m_ith == nullptr) || (m_ith->ProcessTag(tag) == false))
throw XMLReader::InvalidTag(tag);
}
++tag;
}
while (!tag.isend());
}
else if ((tag.isempty() == false) && (pc->Parameters() > 0))
{
// there should be one parameter with the same name as the tag
// Notice that we don't process attributes, since this situation should be synonymous
// to an additional tag that defines the parameter.
if (ReadParameter(tag, pc, 0, false) == false)
{
// try a parameter with the type string as name
if (ReadParameter(tag, pc, pc->GetTypeStr(), false) == false)
throw XMLReader::InvalidTag(tag);
}
}
// validate the class
int NP = pc->PropertyClasses();
for (int i = 0; i<NP; ++i)
{
FEProperty* pi = pc->PropertyClass(i);
bool a = pi->IsRequired();
bool b = (pi->size() == 0);
if (a && b)
{
throw FEBioImport::MissingProperty(pc->GetName(), pi->GetName());
}
}
}
//-----------------------------------------------------------------------------
FEFileSectionMap::~FEFileSectionMap()
{
Clear();
}
//-----------------------------------------------------------------------------
void FEFileSectionMap::Clear()
{
// clear the map
FEFileSectionMap::iterator is;
for (is = begin(); is != end(); ++is)
{
FEFileSection* ps = is->second; delete ps;
}
clear();
}
//-----------------------------------------------------------------------------
void FEFileSectionMap::Parse(XMLTag& tag)
{
++tag;
while (!tag.isend())
{
std::map<string, FEFileSection*>::iterator is = find(tag.Name());
if (is != end()) is->second->Parse(tag);
else throw XMLReader::InvalidTag(tag);
++tag;
};
}
//-----------------------------------------------------------------------------
//! class constructor
FEFileImport::FEFileImport()
{
m_fp = 0;
m_szerr[0] = 0;
m_builder = 0;
m_nversion = 0;
m_stopOnUnknownAttribute = false;
}
//-----------------------------------------------------------------------------
// class destructor. Closes file on call.
FEFileImport::~FEFileImport()
{
// make sure to close the file
Close();
}
//-----------------------------------------------------------------------------
//! Open a file and store the file name and file pointer.
bool FEFileImport::Open(const char* szfile, const char* szmode)
{
m_fp = fopen(szfile, szmode);
if (m_fp == 0) return false;
strcpy(m_szfile, szfile);
return true;
}
//-----------------------------------------------------------------------------
//! Close the file
void FEFileImport::Close()
{
if (m_fp)
{
fclose(m_fp);
m_fp = 0;
}
delete m_builder;
m_builder = nullptr;
}
//-----------------------------------------------------------------------------
//! parse the file
bool FEFileImport::ParseFile(XMLTag& tag)
{
// parse the file
try
{
m_map.Parse(tag);
}
catch (XMLReader::Error& e)
{
fprintf(stderr, "FATAL ERROR: %s (line %d)\n", e.what(), tag.m_ncurrent_line);
return false;
}
catch (FEBioImport::MissingProperty e)
{
fprintf(stderr, "FATAL ERROR: %s\n\n", e.GetErrorString());
return false;
}
catch (...)
{
fprintf(stderr, "FATAL ERROR: unknown exception occured while parsing file.\n\n");
return false;
}
return true;
}
//-----------------------------------------------------------------------------
FEModel* FEFileImport::GetFEModel()
{
return &m_builder->GetFEModel();
}
//-----------------------------------------------------------------------------
//! set a custom model builder
void FEFileImport::SetModelBuilder(FEModelBuilder* modelBuilder)
{
delete m_builder;
m_builder = modelBuilder;
}
//-----------------------------------------------------------------------------
//! Get the model builder
FEModelBuilder* FEFileImport::GetBuilder()
{
return m_builder;
}
//-----------------------------------------------------------------------------
// return the file path
const char* FEFileImport::GetFilePath() { return m_szpath; }
//-----------------------------------------------------------------------------
// set file version
void FEFileImport::SetFileVerion(int nversion)
{
FECoreKernel& fecore = FECoreKernel::GetInstance();
fecore.SetSpecID(nversion);
m_nversion = nversion;
}
//-----------------------------------------------------------------------------
// get file version
int FEFileImport::GetFileVersion() const
{
return m_nversion;
}
//-----------------------------------------------------------------------------
void FEFileImport::SetStopOnUnknownAttribute(bool b)
{
m_stopOnUnknownAttribute = b;
}
//-----------------------------------------------------------------------------
// throw exception if an unknown attribute is found
bool FEFileImport::StopOnUnknownAttribute() const
{
return m_stopOnUnknownAttribute;
}
//-----------------------------------------------------------------------------
//! Get the error message. Errors message are stored when calling the errf function.
void FEFileImport::GetErrorMessage(char* szerr)
{
strcpy(szerr, m_szerr);
}
//-----------------------------------------------------------------------------
//! Call this function to report an error message. The user can retrieve the
//! error message with the GetErrorMessage member function.
bool FEFileImport::errf(const char* szerr, ...)
{
// get a pointer to the argument list
va_list args;
// copy to string
va_start(args, szerr);
vsnprintf(m_szerr, sizeof(m_szerr), szerr, args);
va_end(args);
// close the file
Close();
return false;
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioMeshDataSection.cpp | .cpp | 25,685 | 926 | /*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 "FEBioMeshDataSection.h"
#include "FECore/FEModel.h"
#include <FECore/FEDataGenerator.h>
#include <FECore/FECoreKernel.h>
#include <FECore/FEDataMathGenerator.h>
#include <FECore/FEMaterial.h>
#include <FECore/FEModelParam.h>
#include <FECore/FEDomainMap.h>
#include <FECore/FEConstValueVec3.h>
#include <sstream>
// in FEBioMeshDataSection3.cpp
FEDataType str2datatype(const char* szdataType);
//-----------------------------------------------------------------------------
#ifdef WIN32
#define szcmp _stricmp
#else
#define szcmp strcmp
#endif
void FEBioMeshDataSection::Parse(XMLTag& tag)
{
// Make sure there is something in this tag
if (tag.isleaf()) return;
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// get the total nr of elements
int nelems = mesh.Elements();
//make sure we've read the element section
if (nelems == 0) throw XMLReader::InvalidTag(tag);
// get the largest ID
int max_id = 0;
for (int i = 0; i<mesh.Domains(); ++i)
{
FEDomain& d = mesh.Domain(i);
for (int j = 0; j<d.Elements(); ++j)
{
FEElement& el = d.ElementRef(j);
if (el.GetID() > max_id) max_id = el.GetID();
}
}
// create the pelem array
m_pelem.assign(max_id, static_cast<FEElement*>(0));
for (int nd = 0; nd<mesh.Domains(); ++nd)
{
FEDomain& d = mesh.Domain(nd);
for (int i = 0; i<d.Elements(); ++i)
{
FEElement& el = d.ElementRef(i);
assert(m_pelem[el.GetID() - 1] == 0);
m_pelem[el.GetID() - 1] = ⪙
}
}
FEBioImport* feb = GetFEBioImport();
// loop over all mesh data
++tag;
do
{
if (tag == "ElementData") ParseElementData(tag);
else if (tag == "SurfaceData") ParseSurfaceData(tag);
else if (tag == "EdgeData" ) ParseEdgeData(tag);
else if (tag == "NodeData" ) ParseNodeData(tag);
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
void FEBioMeshDataSection::ParseNodeData(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
const char* szset = tag.AttributeValue("node_set");
FENodeSet* nodeSet = mesh.FindNodeSet(szset);
if (nodeSet == 0) throw XMLReader::InvalidAttributeValue(tag, "node_set", szset);
const char* sztype = tag.AttributeValue("data_type", true);
if (sztype == 0) sztype = "scalar";
FEDataType dataType;
if (strcmp(sztype, "scalar") == 0) dataType = FE_DOUBLE;
else if (strcmp(sztype, "vec2") == 0) dataType = FE_VEC2D;
else if (strcmp(sztype, "vec3") == 0) dataType = FE_VEC3D;
else throw XMLReader::InvalidAttributeValue(tag, "data_type", sztype);
string sname = tag.AttributeValue("name");
FENodeDataMap* pdata = nullptr;
const char* szgen = tag.AttributeValue("generator", true);
if (szgen)
{
if (dataType != FE_DOUBLE) throw XMLReader::InvalidAttributeValue(tag, "generator", szgen);
++tag;
do
{
if (tag == "math")
{
FEDataMathGenerator gen(&fem);
gen.setExpression(tag.szvalue());
if (gen.Init() == false) throw XMLReader::InvalidValue(tag);
pdata = dynamic_cast<FENodeDataMap*>(gen.Generate());
if (pdata == nullptr) throw XMLReader::InvalidValue(tag);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
else
{
pdata = new FENodeDataMap(dataType);
pdata->Create(nodeSet);
ParseDataArray(tag, *pdata, "node");
}
if (pdata)
{
pdata->SetName(sname);
mesh.AddDataMap(pdata);
}
}
void FEBioMeshDataSection::ParseEdgeData(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
const char* szedge = tag.AttributeValue("edge");
FESegmentSet* pset = mesh.FindSegmentSet(szedge);
if (pset == 0) throw XMLReader::InvalidAttributeValue(tag, "edge", szedge);
const char* sztype = tag.AttributeValue("data_type", true);
if (sztype == 0) sztype = "scalar";
int dataType = -1;
if (strcmp(sztype, "scalar") == 0) dataType = FE_DOUBLE;
else if (strcmp(sztype, "vec2") == 0) dataType = FE_VEC2D;
else if (strcmp(sztype, "vec3") == 0) dataType = FE_VEC3D;
if (dataType == -1) throw XMLReader::InvalidAttributeValue(tag, "data_type", sztype);
/*
const char* szname = tag.AttributeValue("name");
FEDataArray* pdata = new FEDataArray(dataType);
fem.AddDataArray(szname, pdata);
pdata->resize(pset->Segments());
ParseDataArray(tag, *pdata, "edge");
*/
}
void FEBioMeshDataSection::ParseSurfaceData(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
const char* szsurf = tag.AttributeValue("surface");
FEFacetSet* psurf = mesh.FindFacetSet(szsurf);
if (psurf == 0) throw XMLReader::InvalidAttributeValue(tag, "surface", szsurf);
const char* sztype = tag.AttributeValue("data_type", true);
if (sztype == 0) sztype = "scalar";
FEDataType dataType;
if (strcmp(sztype, "scalar") == 0) dataType = FE_DOUBLE;
else if (strcmp(sztype, "vec2" ) == 0) dataType = FE_VEC2D;
else if (strcmp(sztype, "vec3" ) == 0) dataType = FE_VEC3D;
else throw XMLReader::InvalidAttributeValue(tag, "data_type", sztype);
string sname = tag.AttributeValue("name");
const char* szgen = tag.AttributeValue("generator", true);
if (szgen)
{
FEFaceDataGenerator* gen = fecore_new<FEFaceDataGenerator>(szgen, &fem);
if (gen == nullptr) throw XMLReader::InvalidAttributeValue(tag, "generator", szgen);
ReadParameterList(tag, gen);
FEDataMap* pdata = gen->Generate();
pdata->SetName(sname);
mesh.AddDataMap(pdata);
}
else
{
FESurfaceMap* pdata = new FESurfaceMap(dataType);
pdata->SetName(sname);
pdata->Create(psurf);
mesh.AddDataMap(pdata);
ParseDataArray(tag, *pdata, "face");
}
}
void FEBioMeshDataSection::ParseElementData(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
const char* szset = tag.AttributeValue("elem_set");
FEElementSet* part = mesh.FindElementSet(szset);
if (part == 0) throw XMLReader::InvalidAttributeValue(tag, "elem_set", szset);
// see if the data will be generated or tabulated
const char* szgen = tag.AttributeValue("generator", true);
if (szgen == nullptr)
{
// data is tabulated and mapped directly to a variable.
const char* szvar = tag.AttributeValue("var", true);
if (szvar)
{
if (strcmp(szvar, "shell thickness") == 0) ParseShellThickness(tag, *part);
else if (strcmp(szvar, "fiber" ) == 0) ParseMaterialFibers(tag, *part);
else if (strstr(szvar, ".fiber" ) != 0) ParseMaterialFiberProperty(tag, *part);
else if (strcmp(szvar, "mat_axis" ) == 0) ParseElementMaterialAxes(tag, *part);
else if (strstr(szvar, ".mat_axis" ) != 0) ParseMaterialAxesProperty(tag, *part);
else ParseMaterialData(tag, *part, szvar);
}
else
{
const char* szname = tag.AttributeValue("name");
string name = szname;
const char* szdatatype = tag.AttributeValue("datatype");
FEDataType dataType = str2datatype(szdatatype);
if (dataType == FEDataType::FE_INVALID_TYPE) throw XMLReader::InvalidAttributeValue(tag, "datatype", szdatatype);
// default format
Storage_Fmt fmt = (((dataType == FE_MAT3D) || (dataType == FE_MAT3DS)) ? Storage_Fmt::FMT_ITEM : Storage_Fmt::FMT_MULT);
// format overrider?
const char* szfmt = tag.AttributeValue("format", true);
if (szfmt)
{
if (szcmp(szfmt, "MAT_POINTS") == 0) fmt = Storage_Fmt::FMT_MATPOINTS;
else if (szcmp(szfmt, "ITEM") == 0) fmt = Storage_Fmt::FMT_ITEM;
else throw XMLReader::InvalidAttributeValue(tag, "format", szfmt);
}
FEDomainMap* map = new FEDomainMap(dataType, fmt);
map->Create(part);
// parse the data
ParseElementData(tag, *map);
// see if this map already exsits
FEDomainMap* oldMap = dynamic_cast<FEDomainMap*>(mesh.FindDataMap(name));
if (oldMap)
{
oldMap->Merge(*map);
delete map;
}
else
{
map->SetName(name);
mesh.AddDataMap(map);
}
}
}
else
{
// data will be generated
FEElemDataGenerator* gen = fecore_new<FEElemDataGenerator>(szgen, &fem);
if (gen == 0) throw XMLReader::InvalidAttributeValue(tag, "generator", szgen);
// get the variable or name
string mapName;
const char* szvar = tag.AttributeValue("var", true);
const char* szname = tag.AttributeValue("name", true);
if (szvar) mapName = szvar;
else if (szname) mapName = szname;
else { assert(false); }
// make sure the parameter is valid
FEParamDouble* pp = nullptr;
if (szvar)
{
// find the variable
ParamString paramName(szvar);
FEParam* pv = fem.FindParameter(paramName);
if (pv == nullptr) throw XMLReader::InvalidAttributeValue(tag, "var", szvar);
// make sure it's a mapped parameter
if (pv->type() != FE_PARAM_DOUBLE_MAPPED)throw XMLReader::InvalidAttributeValue(tag, "var", szvar);
// if it's an array parameter, get the right index
if (pv->dim() > 1)
{
ParamString l = paramName.last();
int m = l.Index();
assert(m >= 0);
pp = &(pv->value<FEParamDouble>(m));
}
else pp = &(pv->value<FEParamDouble>());
}
// create a new domain map (only scalars for now!)
FEDomainMap* map = new FEDomainMap(FE_DOUBLE);
map->Create(part);
map->SetName(mapName);
// read the parameters of the generator
ReadParameterList(tag, gen);
gen->SetElementSet(part);
// Add it to the list (will be evaluated later)
GetBuilder()->AddMeshDataGenerator(gen, map, pp);
}
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection::ParseShellThickness(XMLTag& tag, FEElementSet& set)
{
if (tag.isleaf())
{
FEMesh& mesh = GetFEModel()->GetMesh();
double h[FEElement::MAX_NODES];
int nval = tag.value(h, FEElement::MAX_NODES);
for (int i = 0; i<set.Elements(); ++i)
{
FEShellElement* pel = dynamic_cast<FEShellElement*>(m_pelem[set[i] - 1]);
if (pel == 0) throw XMLReader::InvalidValue(tag);
if (pel->Nodes() != nval) throw XMLReader::InvalidValue(tag);
for (int j = 0; j<nval; ++j) pel->m_h0[j] = h[j];
}
}
else
{
vector<ELEMENT_DATA> data;
ParseElementData(tag, set, data, FEElement::MAX_NODES);
for (int i = 0; i<(int)data.size(); ++i)
{
ELEMENT_DATA& di = data[i];
if (di.nval > 0)
{
FEElement& el = *m_pelem[set[i] - 1];
if (el.Class() != FE_ELEM_SHELL) throw XMLReader::InvalidTag(tag);
FEShellElement& shell = static_cast<FEShellElement&> (el);
int ne = shell.Nodes();
if (ne != di.nval) throw XMLReader::InvalidTag(tag);
for (int j = 0; j<ne; ++j) shell.m_h0[j] = di.val[j];
}
}
}
}
//-----------------------------------------------------------------------------
// Defined in FEBioGeometrySection.cpp
void set_element_fiber(FEElement& el, const vec3d& v, int ncomp);
void set_element_mat_axis(FEElement& el, const vec3d& v1, const vec3d& v2, int ncomp);
//-----------------------------------------------------------------------------
void FEBioMeshDataSection::ParseMaterialFibers(XMLTag& tag, FEElementSet& set)
{
// find the domain with the same name
string name = set.GetName();
FEMesh* mesh = const_cast<FEMesh*>(set.GetMesh());
FEDomain* dom = mesh->FindDomain(name);
if (dom == nullptr) throw XMLReader::InvalidAttributeValue(tag, "elem_set", name.c_str());
// get the material
FEMaterial* mat = dom->GetMaterial();
if (mat == nullptr) throw XMLReader::InvalidAttributeValue(tag, "elem_set", name.c_str());
// get the fiber property
FEProperty* fiber = mat->FindProperty("fiber");
if (fiber == nullptr) throw XMLReader::InvalidAttributeValue(tag, "elem_set", name.c_str());
if (fiber->GetSuperClassID() != FEVEC3DVALUATOR_ID) throw XMLReader::InvalidAttributeValue(tag, "elem_set", name.c_str());
// create a domain map
FEDomainMap* map = new FEDomainMap(FE_VEC3D, FMT_ITEM);
map->Create(&set);
FEMappedValueVec3* val = fecore_new<FEMappedValueVec3>("map", GetFEModel());
val->setDataMap(map);
fiber->SetProperty(val);
vector<ELEMENT_DATA> data;
ParseElementData(tag, set, data, 3);
for (int i = 0; i<(int)data.size(); ++i)
{
ELEMENT_DATA& di = data[i];
if (di.nval > 0)
{
FEElement& el = *m_pelem[set[i] - 1];
if (di.nval != 3) throw XMLReader::InvalidTag(tag);
vec3d v(di.val[0], di.val[1], di.val[2]);
v.unit();
map->set<vec3d>(i, v);
}
}
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection::ParseMaterialFiberProperty(XMLTag& tag, FEElementSet& set)
{
const char* szvar = tag.AttributeValue("var");
char szbuf[256] = { 0 };
strcpy(szbuf, szvar);
char* ch = strstr(szbuf, ".fiber");
if (ch == 0) return;
*ch = 0;
ch = strrchr(szbuf, ']');
if (ch == 0) return;
*ch = 0;
ch = strchr(szbuf, '[');
if (ch == 0) return;
*ch++ = 0;
int nindex = atoi(ch);
vector<ELEMENT_DATA> data;
ParseElementData(tag, set, data, 3);
for (int i = 0; i<(int)data.size(); ++i)
{
ELEMENT_DATA& di = data[i];
if (di.nval > 0)
{
FEElement& el = *m_pelem[set[i] - 1];
if (di.nval != 3) throw XMLReader::InvalidTag(tag);
vec3d v(di.val[0], di.val[1], di.val[2]);
set_element_fiber(el, v, nindex);
}
}
}
void FEBioMeshDataSection::ParseElementMaterialAxes(XMLTag& tag, FEElementSet& set)
{
// get the total nr of elements
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// find the domain
string domName = set.GetName();
FEDomainList& DL = set.GetDomainList();
if (DL.Domains() != 1)
{
throw XMLReader::InvalidAttributeValue(tag, "elem_set", domName.c_str());
}
FEDomain* dom = DL.GetDomain(0);
++tag;
do
{
if (tag == "elem")
{
// get the local element number
const char* szlid = tag.AttributeValue("lid");
int lid = atoi(szlid) - 1;
// make sure the number is valid
if ((lid < 0) || (lid >= set.Elements())) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
// get the element
FEElement* el = mesh.FindElementFromID(set[lid]);
if (el == 0) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
// read parameters
double a[3] = { 0 };
double d[3] = { 0 };
++tag;
do
{
if (tag == "a") tag.value(a, 3);
else if (tag == "d") tag.value(d, 3);
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
vec3d v1(a[0], a[1], a[2]);
vec3d v2(d[0], d[1], d[2]);
vec3d e1(v1);
vec3d e3 = v1 ^ v2;
vec3d e2 = e3 ^ e1;
// normalize
e1.unit();
e2.unit();
e3.unit();
// set the value
mat3d Q(e1, e2, e3);
for (int i = 0; i < el->GaussPoints(); ++i)
{
FEMaterialPoint& mp = *el->GetMaterialPoint(i);
mp.m_Q = Q;
}
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
void FEBioMeshDataSection::ParseMaterialAxesProperty(XMLTag& tag, FEElementSet& set)
{
const char* szvar = tag.AttributeValue("var");
char szbuf[256] = { 0 };
strcpy(szbuf, szvar);
char* ch = strstr(szbuf, ".mat_axis");
if (ch) *ch = 0;
// get the total nr of elements
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// find the domain
string domName = set.GetName();
FEDomainList& DL = set.GetDomainList();
if (DL.Domains() != 1)
{
throw XMLReader::InvalidAttributeValue(tag, "elem_set", domName.c_str());
}
FEDomain* dom = DL.GetDomain(0);
// get its material
FEMaterial* domMat = dom->GetMaterial();
// find the material property
FEMaterial* mat = domMat;
if (ch)
{
mat = dynamic_cast<FEMaterial*>(domMat->GetProperty(szbuf));
if (mat == nullptr) throw XMLReader::InvalidAttributeValue(tag, "var", szvar);
}
FEProperty* pQ = mat->FindProperty("mat_axis"); assert(pQ);
if (pQ == nullptr) throw XMLReader::InvalidAttributeValue(tag, "var", szvar);
// create the map's name.
stringstream ss;
if (ch)
ss << "material" << domMat->GetID() << "." << szbuf << ".mat_axis";
else
ss << "material" << domMat->GetID() << ".mat_axis";
string mapName = ss.str();
// create a domain map
FEDomainMap* map = new FEDomainMap(FE_MAT3D, FMT_ITEM);
map->SetName(mapName);
map->Create(&set);
++tag;
do
{
if (tag == "elem")
{
// get the local element number
const char* szlid = tag.AttributeValue("lid");
int lid = atoi(szlid) - 1;
// make sure the number is valid
if ((lid < 0) || (lid >= set.Elements())) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
// get the element
FEElement* el = mesh.FindElementFromID(set[lid]);
if (el == 0) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
// read parameters
double a[3] = { 0 };
double d[3] = { 0 };
++tag;
do
{
if (tag == "a") tag.value(a, 3);
else if (tag == "d") tag.value(d, 3);
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
vec3d v1(a[0], a[1], a[2]);
vec3d v2(d[0], d[1], d[2]);
vec3d e1(v1);
vec3d e3 = v1 ^ v2;
vec3d e2 = e3 ^ e1;
// normalize
e1.unit();
e2.unit();
e3.unit();
// set the value
mat3d Q(e1, e2, e3);
map->set<mat3d>(lid, Q);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
// see if this map already exists
FEDomainMap* oldMap = dynamic_cast<FEDomainMap*>(mesh.FindDataMap(mapName));
if (oldMap)
{
// It does, so merge it
oldMap->Merge(*map);
delete map;
}
else
{
// It does not, so add it
FEMappedValueMat3d* val = fecore_alloc(FEMappedValueMat3d, GetFEModel());
val->setDataMap(map);
pQ->SetProperty(val);
mesh.AddDataMap(map);
}
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection::ParseMaterialData(XMLTag& tag, FEElementSet& set, const string& pname)
{
// get the (optional) scale factor
double scale = 1.0;
const char* szscale = tag.AttributeValue("scale", true);
if (szscale) scale = atof(szscale);
// find the parameter
FEModel& fem = *GetFEModel();
ParamString PS(pname.c_str());
FEParam* p = fem.FindParameter(PS);
if (p == nullptr)
{
printf("Can't find parameter %s\n", pname.c_str());
throw XMLReader::InvalidAttributeValue(tag, "var", pname.c_str());
}
// get the format
Storage_Fmt fmt = FMT_ITEM;
const char* szfmt = tag.AttributeValue("data_format", true);
if (szfmt == nullptr) fmt = FMT_ITEM;
else if (strcmp(szfmt, "node") == 0) fmt = FMT_NODE;
else if (strcmp(szfmt, "item") == 0) fmt = FMT_ITEM;
else if (strcmp(szfmt, "mult") == 0) fmt = FMT_MULT;
else if (strcmp(szfmt, "region") == 0) fmt = FMT_REGION;
else throw XMLReader::InvalidAttributeValue(tag, "data_format", szfmt);
if (p->type() == FE_PARAM_DOUBLE_MAPPED)
{
vector<ELEMENT_DATA> data;
ParseElementData(tag, set, data, 1);
FEParamDouble& param = p->value<FEParamDouble>();
param.SetItemList(&set);
FEMappedValue* val = fecore_alloc(FEMappedValue, &fem);
if (val == nullptr)
{
printf("Something went horribly wrong.");
return;
}
if (fmt != FMT_ITEM) throw XMLReader::InvalidAttributeValue(tag, "data_format", szfmt);
FEDomainMap* map = new FEDomainMap(FEDataType::FE_DOUBLE, FMT_ITEM);
map->Create(&set);
val->setDataMap(map);
for (int i = 0; i < data.size(); ++i) map->set<double>(i, data[i].val[0] * scale);
param.setValuator(val);
}
else if (p->type() == FE_PARAM_MAT3DS_MAPPED)
{
FEParamMat3ds& param = p->value<FEParamMat3ds>();
param.SetItemList(&set);
FEMappedValueMat3ds* val = fecore_alloc(FEMappedValueMat3ds, &fem);
if (val == nullptr)
{
printf("Something went horribly wrong.");
return;
}
if (fmt == FMT_ITEM)
{
vector<ELEMENT_DATA> data;
ParseElementData(tag, set, data, 6);
FEDomainMap* map = new FEDomainMap(FEDataType::FE_MAT3DS, FMT_ITEM);
map->Create(&set);
val->setDataMap(map);
for (int i = 0; i < data.size(); ++i)
{
double* d = data[i].val;
mat3ds m(d[0], d[1], d[2], d[3], d[4], d[5]);
map->set<mat3ds>(i, m * scale);
}
param.setValuator(val);
}
else if (fmt == FMT_NODE)
{
// create a node set from an element set
FENodeList nodeList = set.GetNodeList();
// create domain map
FEDomainMap* map = new FEDomainMap(FEDataType::FE_MAT3DS, FMT_NODE);
map->Create(&set);
val->setDataMap(map);
// read values
++tag;
do
{
if (tag == "node")
{
const char* szid = tag.AttributeValue("id");
int nid = atoi(szid) - 1;
// convert global ID into local one
int lid = nodeList.GlobalToLocalID(nid);
if (lid < 0) throw XMLReader::InvalidAttributeValue(tag, "id", szid);
// read the value
double d[6];
tag.value(d, 6);
mat3ds m(d[0], d[1], d[2], d[3], d[4], d[5]);
map->set<mat3ds>(lid, m*scale);
}
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
param.setValuator(val);
}
}
else
{
printf("A mesh data map cannot be assigned to this parameter.");
throw XMLReader::InvalidAttribute(tag, "var");
}
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection::ParseElementData(XMLTag& tag, FEElementSet& set, vector<ELEMENT_DATA>& values, int nvalues)
{
// get the total nr of elements
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int nelems = set.Elements();
// resize the array
values.resize(nelems);
for (int i = 0; i<nelems; ++i) values[i].nval = 0;
++tag;
do
{
if (tag == "elem")
{
// get the local element number
const char* szlid = tag.AttributeValue("lid");
int n = atoi(szlid) - 1;
// make sure the number is valid
if ((n<0) || (n >= nelems)) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
ELEMENT_DATA& data = values[n];
data.nval = tag.value(data.val, nvalues);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection::ParseElementData(XMLTag& tag, FEDomainMap& map)
{
const FEElementSet* set = map.GetElementSet();
if (set == nullptr) throw XMLReader::InvalidTag(tag);
// get the total nr of elements
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int nelems = set->Elements();
FEDataType dataType = map.DataType();
int dataSize = map.DataSize();
int m = map.MaxNodes();
double data[3 * FEElement::MAX_NODES]; // make sure this array is large enough to store any data map type (current 3 for FE_VEC3D)
// TODO: For vec3d values, I sometimes need to normalize the vectors (e.g. for fibers). How can I do this?
int ncount = 0;
++tag;
do
{
// get the local element number
const char* szlid = tag.AttributeValue("lid");
int n = atoi(szlid) - 1;
// make sure the number is valid
if ((n < 0) || (n >= nelems)) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
int nread = tag.value(data, m*dataSize);
if (nread == dataSize)
{
double* v = data;
switch (dataType)
{
case FE_DOUBLE: map.setValue(n, v[0]); break;
case FE_VEC2D: map.setValue(n, vec2d(v[0], v[1])); break;
case FE_VEC3D: map.setValue(n, vec3d(v[0], v[1], v[2])); break;
case FE_MAT3D: map.setValue(n, mat3d(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8])); break;
case FE_MAT3DS: map.setValue(n, mat3ds(v[0], v[1], v[2], v[3], v[4], v[5])); break;
default:
assert(false);
}
}
else if (nread == m * dataSize)
{
double* v = data;
for (int i = 0; i < m; ++i, v += dataSize)
{
switch (dataType)
{
case FE_DOUBLE: map.setValue(n, i, v[0]); break;
case FE_VEC2D: map.setValue(n, i, vec2d(v[0], v[1])); break;
case FE_VEC3D: map.setValue(n, i, vec3d(v[0], v[1], v[2])); break;
default:
assert(false);
}
}
}
else throw XMLReader::InvalidValue(tag);
++tag;
ncount++;
} while (!tag.isend());
if (ncount != nelems) throw FEBioImport::MeshDataError();
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection::ParseDataArray(XMLTag& tag, FEDataArray& map, const char* sztag)
{
int dataType = map.DataType();
if (dataType == FE_DOUBLE)
{
++tag;
do
{
if (tag == sztag)
{
int nid;
tag.AttributeValue("lid", nid);
double v;
tag.value(v);
map.setValue(nid - 1, v);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
else if (dataType == FE_VEC3D)
{
++tag;
do
{
if (tag == sztag)
{
int nid;
tag.AttributeValue("lid", nid);
double v[3];
tag.value(v, 3);
map.setValue(nid - 1, vec3d(v[0], v[1], v[2]));
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioRigidSection.cpp | .cpp | 6,304 | 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.*/
#include "stdafx.h"
#include "FEBioRigidSection.h"
#include <FECore/FEModel.h>
#include <FECore/FECoreKernel.h>
#include <FECore/FEModelLoad.h>
#include <FECore/FENLConstraint.h>
#include <FECore/FEBoundaryCondition.h>
void FEBioRigidSection::Parse(XMLTag& tag)
{
if (tag.isleaf()) return;
++tag;
do
{
if (tag == "rigid_constraint") ParseRigidBC(tag);
else if (tag == "rigid_connector" ) ParseRigidConnector(tag);
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
}
void FEBioRigidSection::ParseRigidBC(XMLTag& tag)
{
FEModel* fem = GetFEModel();
FEModelBuilder& feb = *GetBuilder();
// get the type
const char* sztype = tag.AttributeValue("type");
if (strcmp(sztype, "fix") == 0)
{
// create the fixed dof
FEBoundaryCondition* pBC = fecore_new_class<FEBoundaryCondition>("FERigidFixedBCOld", fem);
feb.AddRigidComponent(pBC);
ReadParameterList(tag, pBC);
}
else if (strcmp(sztype, "prescribe") == 0)
{
// create the rigid displacement constraint
FEBoundaryCondition* pDC = fecore_new_class<FEBoundaryCondition>("FERigidPrescribedOld", fem);
feb.AddRigidComponent(pDC);
ReadParameterList(tag, pDC);
}
else if (strcmp(sztype, "force") == 0)
{
string name;
const char* szname = tag.AttributeValue("name", true);
if (szname) name = szname;
// we need to decide whether we want to apply a force or a moment, since these
// are now two separate classes. Unfortunately, this means we first need to
// read all parameters, before we can allocate the correct class.
int rb = -1;
int ntype = 0;
int bc = -1;
double val = 0.;
bool brel = false;
int lc = -1;
++tag;
do
{
if (tag == "rb" ) tag.value(rb);
else if (tag == "value")
{
tag.value(val);
const char* szlc = tag.AttributeValue("lc", true);
if (szlc) lc = atoi(szlc) - 1;
}
else if (tag == "load_type") tag.value(ntype);
else if (tag == "relative" ) tag.value(brel);
else if (tag == "dof" )
{
const char* sz = tag.szvalue();
if ((strcmp(sz, "Rx") == 0) || (strcmp(sz, "0") == 0)) bc = 0;
if ((strcmp(sz, "Ry") == 0) || (strcmp(sz, "1") == 0)) bc = 1;
if ((strcmp(sz, "Rz") == 0) || (strcmp(sz, "2") == 0)) bc = 2;
if ((strcmp(sz, "Ru") == 0) || (strcmp(sz, "3") == 0)) bc = 3;
if ((strcmp(sz, "Rv") == 0) || (strcmp(sz, "4") == 0)) bc = 4;
if ((strcmp(sz, "Rw") == 0) || (strcmp(sz, "5") == 0)) bc = 5;
if (bc < 0)
{
throw XMLReader::InvalidValue(tag);
}
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
FEModelLoad* pFC = nullptr;
if (bc < 3)
{
pFC = fecore_new_class<FEModelLoad>("FERigidBodyForce", fem);
pFC->SetParameter("load_type", ntype);
pFC->SetParameter("rb", rb);
pFC->SetParameter("dof", bc);
pFC->SetParameter("value", val);
pFC->SetParameter("relative", brel);
}
else
{
pFC = fecore_new_class<FEModelLoad>("FERigidBodyMoment", fem);
pFC->SetParameter("rb", rb);
pFC->SetParameter("dof", bc - 3);
pFC->SetParameter("value", val);
pFC->SetParameter("relative", brel);
}
if (lc >= 0)
{
FEParam* p = pFC->GetParameter("value");
if (p == nullptr) throw XMLReader::InvalidTag(tag);
GetFEModel()->AttachLoadController(p, lc);
}
if (name.empty() == false)
{
pFC->SetName(name);
}
feb.AddModelLoad(pFC);
}
else if (strcmp(sztype, "initial_rigid_velocity") == 0)
{
FEBoundaryCondition* pic = fecore_new_class<FEBoundaryCondition>("FERigidBodyVelocity", fem);
feb.AddRigidComponent(pic);
ReadParameterList(tag, pic);
}
else if (strcmp(sztype, "initial_rigid_angular_velocity") == 0)
{
FEBoundaryCondition* pic = fecore_new_class<FEBoundaryCondition>("FERigidBodyAngularVelocity", fem);
feb.AddRigidComponent(pic);
ReadParameterList(tag, pic);
}
else if (strcmp(sztype, "follower force") == 0)
{
FEModelLoad* rc = fecore_new_class<FEModelLoad>("FERigidFollowerForce", fem);
feb.AddModelLoad(rc);
ReadParameterList(tag, rc);
}
else if (strcmp(sztype, "follower moment") == 0)
{
FEModelLoad* rc = fecore_new_class<FEModelLoad>("FERigidFollowerMoment", fem);
feb.AddModelLoad(rc);
ReadParameterList(tag, rc);
}
else
{
// create the rigid constraint
FEBoundaryCondition* pBC = fecore_new<FEBoundaryCondition>(sztype, fem);
if (pBC == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
feb.AddRigidComponent(pBC);
ReadParameterList(tag, pBC);
}
}
void FEBioRigidSection::ParseRigidConnector(XMLTag& tag)
{
const char* sztype = tag.AttributeValue("type");
FENLConstraint* plc = fecore_new<FENLConstraint>(sztype, GetFEModel());
if (plc == 0) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
const char* szname = tag.AttributeValue("name", true);
if (szname) plc->SetName(szname);
// read the parameter list
ReadParameterList(tag, plc);
// add this constraint to the current step
GetBuilder()->AddNonlinearConstraint(plc);
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioDiscreteSection.h | .h | 1,970 | 55 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEBioImport.h"
//-----------------------------------------------------------------------------
class FEBioDiscreteSection : public FEFileSection
{
public:
FEBioDiscreteSection(FEFileImport* pim) : FEFileSection(pim){}
void Parse(XMLTag& tag);
protected:
void ParseSpringSection (XMLTag& tag);
void ParseRigidAxialForce(XMLTag& tag);
};
//-----------------------------------------------------------------------------
class FEBioDiscreteSection25 : public FEFileSection
{
public:
FEBioDiscreteSection25(FEFileImport* pim) : FEFileSection(pim){}
void Parse(XMLTag& tag);
protected:
void ParseRigidAxialForce(XMLTag& tag);
void ParseRigidCable(XMLTag& tag);
};
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FEBioMaterialSection.h | .h | 1,985 | 58 | /*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 "FEBioImport.h"
//-----------------------------------------------------------------------------
// Material Section
class FEBIOXML_API FEBioMaterialSection : public FEFileSection
{
public:
FEBioMaterialSection(FEFileImport* pim) : FEFileSection(pim){}
void Parse(XMLTag& tag);
protected:
FEMaterial* CreateMaterial(XMLTag& tag);
protected:
int m_nmat;
};
//-----------------------------------------------------------------------------
// Material Section
class FEBIOXML_API FEBioMaterialSection3 : public FEFileSection
{
public:
FEBioMaterialSection3(FEFileImport* pim) : FEFileSection(pim) {}
void Parse(XMLTag& tag);
protected:
FEMaterial* CreateMaterial(XMLTag& tag);
};
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FEBioBoundarySection3.cpp | .cpp | 6,701 | 241 | /*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 "FEBioBoundarySection3.h"
#include <FECore/FENodalBC.h>
#include <FECore/FESurfaceBC.h>
#include <FECore/FEModel.h>
#include <FECore/FELinearConstraintManager.h>
//-----------------------------------------------------------------------------
void FEBioBoundarySection3::Parse(XMLTag& tag)
{
if (tag.isleaf()) return;
// build the node set map for faster lookup
BuildNodeSetMap();
++tag;
do
{
if (tag == "bc") ParseBC(tag);
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
}
//-----------------------------------------------------------------------------
void FEBioBoundarySection3::ParseBC(XMLTag& tag)
{
FEModel* fem = GetFEModel();
FEMesh& mesh = fem->GetMesh();
// get the type string
const char* sztype = tag.AttributeValue("type");
// handle "rigid" bc separately
if (strcmp(sztype, "rigid") == 0)
{
ParseBCRigid(tag);
return;
}
// handle linar constraints
if (strcmp(sztype, "linear constraint") == 0)
{
ParseLinearConstraint(tag);
return;
}
// create the boundary condition
FEBoundaryCondition* pbc = fecore_new<FEBoundaryCondition>(sztype, fem);
if (pbc == 0) throw XMLReader::InvalidAttributeValue(tag, "type");
// read the (optional) name
const char* szname = tag.AttributeValue("name", true);
if (szname) pbc->SetName(szname);
// get the node set
if (dynamic_cast<FENodalBC*>(pbc))
{
FENodalBC* nbc = dynamic_cast<FENodalBC*>(pbc); assert(nbc);
// read required node_set attribute
const char* szset = tag.AttributeValue("node_set");
FENodeSet* nodeSet = GetBuilder()->FindNodeSet(szset);
if (nodeSet == nullptr) throw XMLReader::InvalidAttributeValue(tag, "node_set", szset);
nbc->SetNodeSet(nodeSet);
}
// get the surface
if (dynamic_cast<FESurfaceBC*>(pbc))
{
FESurfaceBC* sbc = dynamic_cast<FESurfaceBC*>(pbc);
// read required surface attribute
const char* surfaceName = tag.AttributeValue("surface");
FEFacetSet* pface = mesh.FindFacetSet(surfaceName);
if (pface == 0) throw XMLReader::InvalidAttributeValue(tag, "surface", surfaceName);
// create a surface from this facet set
FESurface* psurf = fecore_alloc(FESurface, fem);
GetBuilder()->BuildSurface(*psurf, *pface);
// assign it
mesh.AddSurface(psurf);
sbc->SetSurface(psurf);
}
// add this boundary condition to the current step
GetBuilder()->AddBC(pbc);
// Read the parameter list
ReadParameterList(tag, pbc);
}
//-----------------------------------------------------------------------------
// Rigid node sets are defined in the Boundary section since version 2.5
// (Used to be defined in the Contact section)
void FEBioBoundarySection3::ParseBCRigid(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
FEModelBuilder* feb = GetBuilder();
int NMAT = fem.Materials();
// get the nodeset
const char* szset = tag.AttributeValue("node_set");
FENodeSet* nodeSet = GetBuilder()->FindNodeSet(szset);
if (nodeSet == 0) throw XMLReader::InvalidAttributeValue(tag, "node_set", szset);
// create new rigid node set
FENodalBC* prn = fecore_new_class<FENodalBC>("FERigidNodeSet", &fem);
prn->SetNodeSet(nodeSet);
// the default shell bc depends on the shell formulation
// hinged shell = 0
// clamped shell = 1
prn->SetParameter("clamp_shells", feb->m_default_shell == OLD_SHELL ? 0 : 1);
feb->AddBC(prn);
// read the parameter list
ReadParameterList(tag, prn);
}
//-----------------------------------------------------------------------------
//! Parse the linear constraints section of the xml input file
//! This section is a subsection of the Boundary section
void FEBioBoundarySection3::ParseLinearConstraint(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
DOFS& dofs = fem.GetDOFS();
// make sure there is a constraint defined
if (tag.isleaf()) return;
FEModelBuilder* feb = GetBuilder();
FELinearConstraint* lc = fecore_alloc(FELinearConstraint, &fem);
++tag;
do
{
if (tag == "node")
{
int nodeId;
tag.value(nodeId);
lc->SetParentNode(feb->FindNodeFromID(nodeId));
}
else if (tag == "dof")
{
lc->SetParentDof(dofs.GetDOF(tag.szvalue()));
}
else if (tag == "offset")
{
double d = 0.0;
tag.value(d);
lc->SetOffset(d);
const char* szlc = tag.AttributeValue("lc", true);
if (szlc)
{
int l = atoi(szlc) - 1;
FEParam* pp = lc->FindParameter("offset"); assert(pp);
if (pp) fem.AttachLoadController(pp, l);
}
}
else if (tag == "child_dof")
{
FELinearConstraintDOF* dof = new FELinearConstraintDOF(&fem);
++tag;
do
{
if (tag == "node")
{
int nodeId;
tag.value(nodeId);
dof->node = feb->FindNodeFromID(nodeId);
}
else if (tag == "dof")
{
dof->dof = dofs.GetDOF(tag.szvalue());
}
else if (tag == "value")
{
double v;
tag.value(v);
dof->val = v;
const char* szlc = tag.AttributeValue("lc", true);
if (szlc)
{
int lc = atoi(szlc) - 1;
FEParam* pp = dof->FindParameter("value"); assert(pp);
if (pp) fem.AttachLoadController(pp, lc);
}
}
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
lc->AddChildDof(dof);
}
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
// add the linear constraint to the system
fem.GetLinearConstraintManager().AddLinearConstraint(lc);
GetBuilder()->AddComponent(lc);
} | C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioStepSection.h | .h | 2,096 | 58 | /*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 "FEBioImport.h"
//-----------------------------------------------------------------------------
// Step Section (old format)
class FEBioStepSection : public FEBioFileSection
{
public:
FEBioStepSection(FEBioImport* pim) : FEBioFileSection(pim){}
void Parse(XMLTag& tag);
};
//-----------------------------------------------------------------------------
// Step Section (2.0 format)
class FEBioStepSection2 : public FEBioFileSection
{
public:
FEBioStepSection2(FEBioImport* pim) : FEBioFileSection(pim){}
void Parse(XMLTag& tag);
};
//-----------------------------------------------------------------------------
// Step Section (2.5 format)
class FEBioStepSection25 : public FEFileSection
{
public:
FEBioStepSection25(FEFileImport* pim) : FEFileSection(pim){}
void Parse(XMLTag& tag);
};
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FileImport.h | .h | 7,861 | 256 | /*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 <FEBioXML/XMLReader.h>
#include <FECore/vec3d.h>
#include <FECore/mat3d.h>
#include <FECore/tens3d.h>
#include <FECore/FECoreBase.h>
#include "FEModelBuilder.h"
#include "febioxml_api.h"
#include <map>
//-----------------------------------------------------------------------------
// Forward declarations
class FEModel;
class FEFileImport;
//-----------------------------------------------------------------------------
// Base class for FEBio import exceptions
// Derived classes should set the error string in their constructor
class FEBIOXML_API FEFileException
{
public:
enum { MAX_ERR_STRING = 1024 };
FEFileException();
FEFileException(const char* sz, ...);
public:
// retrieve the error string
const char* GetErrorString() const { return m_szerr; }
protected:
// set the error string (used by derived classes)
void SetErrorString(const char* sz, ...);
protected:
char m_szerr[MAX_ERR_STRING];
};
//-----------------------------------------------------------------------------
// Class for handling unrecognized tags.
// Use FEFileSection::SetInvalidTagHandler to set the handler for unrecognized parameters.
class FEInvalidTagHandler
{
public:
FEInvalidTagHandler() {}
virtual ~FEInvalidTagHandler() {}
virtual bool ProcessTag(XMLTag& tag) { return false; }
};
//-----------------------------------------------------------------------------
// The FEObsoleteParamHandler class tries to map an unrecognized tag to
// a model parameter. Obsolete parameters are added with the AddParam function.
class FEObsoleteParamHandler : public FEInvalidTagHandler
{
struct FEObsoleteParam
{
const char* oldName = nullptr;
const char* newName = nullptr;
int paramType = FE_PARAM_INVALID;
bool readIn = false;
union {
bool bVal;
int iVal;
double gVal;
};
};
public:
FEObsoleteParamHandler(XMLTag& tag, FECoreBase* pc);
// Add an obsolete parameter.
// The oldname is a relative path w.r.t. the XMLTag passed in the constructor.
// the newName is a ParamString, relative to the pc parameter.
// To mark a parameter as ignored, set newName to nullptr, and paramType to FE_PARAM_INVALID.
void AddParam(const char* oldName, const char* newName, FEParamType paramType);
// This will try to find an entry in the m_param list. If a match is not find, this function returns false.
bool ProcessTag(XMLTag& tag) override;
// This function will try to map the obsolete parameters to model parameters.
// Or it will print a warning if the obsolete parameter will be ignored.
virtual void MapParameters();
private:
std::string m_root;
FECoreBase* m_pc;
vector<FEObsoleteParam> m_param;
};
//-----------------------------------------------------------------------------
// Base class for XML sections parsers
class FEBIOXML_API FEFileSection
{
public:
FEFileSection(FEFileImport* pim) { m_pim = pim; }
virtual ~FEFileSection() {}
virtual void Parse(XMLTag& tag) = 0;
FEFileImport* GetFileReader() { return m_pim; }
FEModel* GetFEModel();
FEModelBuilder* GetBuilder();
// Set the handler for unrecognized tags
void SetInvalidTagHandler(FEInvalidTagHandler* ith);
public:
//! read a nodal ID
//! This assumes the node ID is defined via the "id" attribute
int ReadNodeID(XMLTag& tag);
public:
bool ReadParameter(XMLTag& tag, FEParameterList& pl, const char* szparam = 0, FECoreBase* pc = 0, bool parseAttributes = true);
bool ReadParameter(XMLTag& tag, FECoreBase* pc, const char* szparam = 0, bool parseAttributes = true);
void ReadParameterList(XMLTag& tag, FEParameterList& pl);
void ReadParameterList(XMLTag& tag, FECoreBase* pc);
void ReadAttributes(XMLTag& tag, FECoreBase* pc);
public:
void value(XMLTag& tag, int& n);
void value(XMLTag& tag, double& g);
void value(XMLTag& tag, bool& b);
void value(XMLTag& tag, vec2d& v);
void value(XMLTag& tag, vec3d& v);
void value(XMLTag& tag, mat3d& m);
void value(XMLTag& tag, mat3ds& m);
void value(XMLTag& tag, tens3drs& m);
void value(XMLTag& tag, char* szstr);
int value(XMLTag& tag, int* pi, int n);
int value(XMLTag& tag, double* pf, int n);
void value(XMLTag& tag, std::string& v);
void value(XMLTag& tag, std::vector<int>& v);
void value(XMLTag& tag, std::vector<double>& v);
protected:
bool parseEnumParam(FEParam* pp, const char* val);
private:
FEFileImport* m_pim;
FEInvalidTagHandler* m_ith = nullptr;
};
//-----------------------------------------------------------------------------
// class that manages file section parsers
class FEBIOXML_API FEFileSectionMap : public std::map<string, FEFileSection*>
{
public:
~FEFileSectionMap();
void Clear();
void Parse(XMLTag& tag);
};
//-----------------------------------------------------------------------------
//! Base class for file import classes.
//! FEBio import files are XML formatted files, where each major section (children of root) is represented
//! by an FEFileSection.
//! This class also offers a simple error reporting mechanism and manages the FILE* pointer.
//! This class also manages "xml parameters". This is a feature of FEBio files that allow users to use parameters
//! as values for xml tag. A parameter is defined by a name-value pair and referenced in the input file using the $(parameter_name) syntax.
class FEBIOXML_API FEFileImport
{
public:
//! constructor
FEFileImport();
//! destructor
virtual ~FEFileImport();
//! get the error message
void GetErrorMessage(char* szerr);
//! Get the current FE model that is being processed
FEModel* GetFEModel();
//! set a custom model builder (takes ownership of modelBuilder)
void SetModelBuilder(FEModelBuilder* modelBuilder);
//! Get the model builder
FEModelBuilder* GetBuilder();
// return the file path
const char* GetFilePath();
// set file version
void SetFileVerion(int nversion);
// get file version
int GetFileVersion() const;
// throw exception if an unknown attribute is found
void SetStopOnUnknownAttribute(bool b);
bool StopOnUnknownAttribute() const;
protected:
//! open a file
bool Open(const char* szfile, const char* szmode);
//! close the file
void Close();
//! helper function for reporting errors
bool errf(const char* szerr, ...);
//! parse the file
bool ParseFile(XMLTag& tag);
protected:
FILE* m_fp; //!< file pointer
char m_szfile[256]; //!< file name
char m_szerr[256]; //!< error message
char m_szpath[512]; //!< file path
protected:
FEFileSectionMap m_map;
FEModelBuilder* m_builder;
bool m_stopOnUnknownAttribute;
private:
int m_nversion; // version of file
};
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FEBioInitialSection.cpp | .cpp | 8,018 | 286 | /*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 "FEBioInitialSection.h"
#include "FECore/FEModel.h"
#include "FECore/DOFS.h"
#include <FECore/FEInitialCondition.h>
#include <FECore/FECoreKernel.h>
//-----------------------------------------------------------------------------
void FEBioInitialSection::Parse(XMLTag& tag)
{
if (tag.isleaf()) return;
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
DOFS& dofs = fem.GetDOFS();
// make sure we've read the nodes section
if (mesh.Nodes() == 0) throw XMLReader::InvalidTag(tag);
// read nodal data
++tag;
do
{
if (tag == "velocity")
{
FENodalIC* pic = fecore_new<FENodalIC>("velocity", &fem);
// add it to the model
GetBuilder()->AddInitialCondition(pic);
// create a node set
FENodeSet* nset = new FENodeSet(&fem);
fem.GetMesh().AddNodeSet(nset);
pic->SetNodeSet(nset);
std::vector<vec3d> values;
++tag;
do
{
if (tag == "node")
{
int nid = ReadNodeID(tag);
vec3d v;
value(tag, v);
nset->Add(nid);
values.push_back(v);
}
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
// TODO: Fix this! I need to add a mechanism again for setting mapped data.
FEParam* param = pic->GetParameter("value"); assert(param);
FEParamVec3& val = param->value<FEParamVec3>();
val = values[0];
// for (int i = 0; i < values.size(); ++i) pic->SetValue(i, values[i]);
}
else if (tag == "ic")
{
const char* sztype = tag.AttributeValue("type");
FEInitialCondition* pic = fecore_new<FEInitialCondition>(sztype, &fem);
if (tag.isleaf() == false)
{
FEParameterList& pl = pic->GetParameterList();
++tag;
do
{
if (ReadParameter(tag, pl) == false) throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
}
// add it to the model
GetBuilder()->AddInitialCondition(pic);
}
else
{
// Get the degree of freedom
int ndof = -1;
if (tag == "temperature" ) ndof = dofs.GetDOF("T");
else if (tag == "fluid_pressure") ndof = dofs.GetDOF("p");
else if (tag == "shell_fluid_pressure") ndof = dofs.GetDOF("q");
else if (tag == "dilatation" ) ndof = dofs.GetDOF("ef");
else if (tag == "concentration" )
{
// TODO: Add a check to make sure that a solute with this ID exists
int isol = 0;
const char* sz = tag.AttributeValue("sol", true);
if (sz) isol = atoi(sz) - 1;
ndof = dofs.GetDOF("concentration", isol);
}
else if (tag == "shell_concentration" )
{
// TODO: Add a check to make sure that a solute with this ID exists
int isol = 0;
const char* sz = tag.AttributeValue("sol", true);
if (sz) isol = atoi(sz) - 1;
ndof = dofs.GetDOF("shell concentration", isol);
}
else throw XMLReader::InvalidTag(tag);
if (ndof == -1) throw XMLReader::InvalidTag(tag);
// allocate initial condition
FEInitialDOF* pic = dynamic_cast<FEInitialDOF*>(fecore_new<FEInitialCondition>("init_dof", &fem));
pic->SetDOF(ndof);
// add it to the model
GetBuilder()->AddInitialCondition(pic);
// create a node set
FENodeSet* nset = new FENodeSet(&fem);
fem.GetMesh().AddNodeSet(nset);
pic->SetNodeSet(nset);
std::vector<double> vals;
// read the node list and values
++tag;
do
{
if (tag == "node")
{
int nid = ReadNodeID(tag);
double p;
value(tag, p);
nset->Add(nid);
vals.push_back(p);
}
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
// TODO: Fix this! I need to add a mechanism again for setting mapped data.
pic->SetValue(vals[0]);
// for (int i = 0; i < vals.size(); ++i) pic->SetValue(i, vals[i]);
}
++tag;
}
while (!tag.isend());
}
//-----------------------------------------------------------------------------
void FEBioInitialSection25::Parse(XMLTag& tag)
{
if (tag.isleaf()) return;
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
DOFS& dofs = fem.GetDOFS();
// make sure we've read the nodes section
if (mesh.Nodes() == 0) throw XMLReader::InvalidTag(tag);
// read nodal data
++tag;
do
{
if (tag == "init")
{
// get the BC
const char* sz = tag.AttributeValue("bc");
int ndof = dofs.GetDOF(sz);
if (ndof == -1) throw XMLReader::InvalidAttributeValue(tag, "bc", sz);
// get the node set
const char* szset = tag.AttributeValue("node_set");
FENodeSet* pns = mesh.FindNodeSet(szset);
if (pns == 0) throw XMLReader::InvalidTag(tag);
// allocate initial condition
FEInitialDOF* pic = dynamic_cast<FEInitialDOF*>(fecore_new<FEInitialCondition>("init_dof", &fem));
pic->SetDOF(ndof);
pic->SetNodeSet(pns);
// add it to the model
GetBuilder()->AddInitialCondition(pic);
// read parameters
ReadParameterList(tag, pic);
}
else if (tag == "ic")
{
const char* sztype = tag.AttributeValue("type");
FEInitialCondition* pic = fecore_new<FEInitialCondition>(sztype, &fem);
FENodalIC* nic = dynamic_cast<FENodalIC*>(pic);
if (nic)
{
// get the node set
const char* szset = tag.AttributeValue("node_set");
FENodeSet* pns = mesh.FindNodeSet(szset);
if (pns == 0) throw XMLReader::InvalidTag(tag);
nic->SetNodeSet(pns);
}
ReadParameterList(tag, pic);
// add it to the model
GetBuilder()->AddInitialCondition(pic);
}
else if (tag == "rigid_body")
{
// get the material ID
const char* szm = tag.AttributeValue("mat");
int nmat = atoi(szm);
if ((nmat <= 0) || (nmat > fem.Materials())) throw XMLReader::InvalidAttributeValue(tag, "mat", szm);
++tag;
do
{
if (tag == "initial_velocity")
{
// get the initial velocity
vec3d v;
value(tag, v);
// create the initial condition
FEStepComponent* pic = fecore_new_class<FEInitialCondition>("FERigidBodyVelocity", &fem);
pic->SetParameter("rb", nmat);
pic->SetParameter("value", v);
// add this initial condition to the current step
GetBuilder()->AddRigidComponent(pic);
}
else if (tag == "initial_angular_velocity")
{
// get the initial angular velocity
vec3d w;
value(tag, w);
// create the initial condition
FEStepComponent* pic = fecore_new_class<FEInitialCondition>("FERigidBodyAngularVelocity", &fem);
pic->SetParameter("rb", nmat);
pic->SetParameter("value", w);
// add this initial condition to the current step
GetBuilder()->AddRigidComponent(pic);
}
++tag;
}
while (!tag.isend());
}
else
throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioMeshDataSection4.cpp | .cpp | 24,473 | 824 | /*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 "FEBioMeshDataSection.h"
#include "FECore/FEModel.h"
#include <FECore/FEDataGenerator.h>
#include <FECore/FECoreKernel.h>
#include <FECore/FEMaterial.h>
#include <FECore/FEDomainMap.h>
#include <FECore/FEConstValueVec3.h>
#include <sstream>
// defined in FEBioMeshDataSection3.cpp
extern FEDataType str2datatype(const char* szdataType);
//-----------------------------------------------------------------------------
#ifdef WIN32
#define szcmp _stricmp
#else
#define szcmp strcmp
#endif
//-----------------------------------------------------------------------------
void FEBioMeshDataSection4::Parse(XMLTag& tag)
{
// Make sure there is something in this tag
if (tag.isleaf()) return;
// make sure the MeshDomain section was processed.
FEMesh& mesh = GetFEModel()->GetMesh();
if (mesh.Domains() == 0)
{
throw FEFileException("MeshData must appear after MeshDomain section.");
}
// loop over all mesh data section
++tag;
do
{
if (tag == "NodeData" ) ParseNodalData (tag);
else if (tag == "SurfaceData") ParseSurfaceData(tag);
else if (tag == "ElementData") ParseElementData(tag);
else throw XMLReader::InvalidTag(tag);
++tag;
}
while (!tag.isend());
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection4::ParseNodalData(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// find the element set
const char* szset = tag.AttributeValue("node_set");
// find the element set in the mesh
FENodeSet* nset = GetBuilder()->FindNodeSet(szset);
if (nset == nullptr) throw XMLReader::InvalidAttributeValue(tag, "node_set", szset);
// get the type
const char* sztype = tag.AttributeValue("type", true);
// get the name (required!)
const char* szname = tag.AttributeValue("name");
// see if there is a generator
if (sztype)
{
// allocate the data generator
FENodeDataGenerator* gen = dynamic_cast<FENodeDataGenerator*>(fecore_new<FEMeshDataGenerator>(sztype, &fem));
if (gen == 0) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
gen->SetName(szname);
gen->SetNodeSet(nset);
GetBuilder()->GetFEModel().AddMeshDataGenerator(gen);
// read the parameters
ReadParameterList(tag, gen);
// Add it to the list (will be applied after the rest of the model was read in)
GetBuilder()->AddMeshDataGenerator(gen, nullptr, nullptr);
}
else
{
// get the data type
const char* szdataType = tag.AttributeValue("data_type", true);
if (szdataType == nullptr) szdataType = "scalar";
FEDataType dataType = str2datatype(szdataType);
if (dataType == FEDataType::FE_INVALID_TYPE) throw XMLReader::InvalidAttributeValue(tag, "data_type", szdataType);
// create the data map
FENodeDataMap* map = new FENodeDataMap(dataType);
map->Create(nset);
map->SetName(szname);
// add it to the mesh
mesh.AddDataMap(map);
// read the data
ParseNodeData(tag, *map);
}
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection4::ParseNodeData(XMLTag& tag, FENodeDataMap& map)
{
// get the total nr of nodes
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int nodes = map.DataCount();
FEDataType dataType = map.DataType();
int dataSize = map.DataSize();
double data[3]; // make sure this array is large enough to store any data map type (current 3 for FE_VEC3D)
++tag;
do
{
// get the local element number
const char* szlid = tag.AttributeValue("lid");
int n = atoi(szlid) - 1;
// make sure the number is valid
if ((n < 0) || (n >= nodes)) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
int nread = tag.value(data, dataSize);
if (nread == dataSize)
{
switch (dataType)
{
case FE_DOUBLE: map.setValue(n, data[0]); break;
case FE_VEC2D: map.setValue(n, vec2d(data[0], data[1])); break;
case FE_VEC3D: map.setValue(n, vec3d(data[0], data[1], data[2])); break;
default:
assert(false);
}
}
else throw XMLReader::InvalidValue(tag);
++tag;
}
while (!tag.isend());
}
void FEBioMeshDataSection4::ParseSurfaceData(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// find the element set
const char* szset = tag.AttributeValue("surface");
// find the element set in the mesh
FEFacetSet* surf = mesh.FindFacetSet(szset);
if (surf == nullptr) throw XMLReader::InvalidAttributeValue(tag, "surface", szset);
// get the type
const char* sztype = tag.AttributeValue("type", true);
// get the name (required!)
string sname = tag.AttributeValue("name");
// see if there is a generator
if (sztype)
{
if (strcmp(sztype, "const") == 0)
{
// get the data type
const char* szdataType = tag.AttributeValue("data_type", true);
if (szdataType == nullptr) szdataType = "scalar";
FEDataType dataType = str2datatype(szdataType);
if (dataType == FEDataType::FE_INVALID_TYPE) throw XMLReader::InvalidAttributeValue(tag, "datatype", szdataType);
FESurfaceMap* map = new FESurfaceMap(dataType);
map->Create(surf);
map->SetName(sname);
mesh.AddDataMap(map);
++tag;
do
{
if (tag == "value")
{
switch (dataType)
{
case FE_DOUBLE: { double v; tag.value(v); map->fillValue(v); } break;
case FE_VEC2D : { vec2d v; value(tag, v); map->fillValue(v); } break;
case FE_VEC3D : { vec3d v; value(tag, v); map->fillValue(v); } break;
case FE_MAT3D : { mat3d v; value(tag, v); map->fillValue(v); } break;
case FE_MAT3DS: { mat3ds v; value(tag, v); map->fillValue(v); } break;
default:
throw XMLReader::InvalidAttributeValue(tag, "type");
break;
}
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
else
{
FEFaceDataGenerator* gen = fecore_new<FEFaceDataGenerator>(sztype, &fem);
if (gen == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
GetBuilder()->GetFEModel().AddMeshDataGenerator(gen);
gen->SetFacetSet(surf);
gen->SetName(sname);
// read the parameters
ReadParameterList(tag, gen);
// Add it to the list (will be applied after the rest of the model was read in)
GetBuilder()->AddMeshDataGenerator(gen, nullptr, nullptr);
}
}
else
{
// get the data type
const char* szdataType = tag.AttributeValue("data_type", true);
if (szdataType == nullptr) szdataType = "scalar";
FEDataType dataType = str2datatype(szdataType);
if (dataType == FEDataType::FE_INVALID_TYPE) throw XMLReader::InvalidAttributeValue(tag, "data_type", szdataType);
// create the data map
FESurfaceMap* map = new FESurfaceMap(dataType);
map->Create(surf);
map->SetName(sname);
// add it to the mesh
mesh.AddDataMap(map);
// read the data
ParseSurfaceData(tag, *map);
}
}
void FEBioMeshDataSection4::ParseElementData(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
// process the attributes
const char* szset = nullptr;
const char* sztype = nullptr;
const char* szname = nullptr;
const char* szdataType = nullptr;
const char* szfmt = nullptr;
for (XMLAtt& att : tag.m_att)
{
if (strcmp(att.name(), "elem_set") == 0) { szset = att.cvalue(); att.m_bvisited = true; }
else if (strcmp(att.name(), "type" ) == 0) { sztype = att.cvalue(); att.m_bvisited = true;}
else if (strcmp(att.name(), "name" ) == 0) { szname = att.cvalue(); att.m_bvisited = true;}
else if (strcmp(att.name(), "data_type") == 0) { szdataType = att.cvalue(); att.m_bvisited = true;}
else if (strcmp(att.name(), "format" ) == 0) { szfmt = att.cvalue(); att.m_bvisited = true;}
else throw XMLReader::InvalidAttribute(tag, att.name());
}
// find the element set in the mesh
if (szset == nullptr) throw XMLReader::MissingAttribute(tag, "elem_set");
FEElementSet* elset = mesh.FindElementSet(szset);
if (elset == nullptr) throw XMLReader::InvalidAttributeValue(tag, "elem_set", szset);
if (sztype)
{
if (strcmp(sztype, "shell thickness") == 0) ParseShellThickness(tag, *elset);
else if (strcmp(sztype, "mat_axis" ) == 0) ParseMaterialAxes (tag, *elset);
else if (strcmp(sztype, "fiber" ) == 0) ParseMaterialFibers(tag, *elset);
else if (strstr(sztype, ".fiber" )) ParseMaterialFibers(tag, *elset);
else if (strcmp(sztype, "const") == 0)
{
// get the data type
const char* szdataType = tag.AttributeValue("data_type", true);
if (szdataType == nullptr) szdataType = "scalar";
FEDataType dataType = str2datatype(szdataType);
if (dataType == FEDataType::FE_INVALID_TYPE) throw XMLReader::InvalidAttributeValue(tag, "datatype", szdataType);
// create the data map
FEDomainMap* map = new FEDomainMap(dataType, Storage_Fmt::FMT_ITEM);
map->Create(elset);
map->SetName(szname);
mesh.AddDataMap(map);
++tag;
do
{
if (tag == "value")
{
switch (dataType)
{
case FE_DOUBLE: { double v; tag.value(v); map->fillValue(v); } break;
case FE_VEC2D: { vec2d v; value(tag, v); map->fillValue(v); } break;
case FE_VEC3D: { vec3d v; value(tag, v); map->fillValue(v); } break;
case FE_MAT3D: { mat3d v; value(tag, v); map->fillValue(v); } break;
case FE_MAT3DS: { mat3ds v; value(tag, v); map->fillValue(v); } break;
default:
throw XMLReader::InvalidAttributeValue(tag, "type");
break;
}
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
else
{
// allocate generator
FEElemDataGenerator* gen = dynamic_cast<FEElemDataGenerator*>(fecore_new<FEMeshDataGenerator>(sztype, &fem));
if (gen == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
// set the name and element set
gen->SetElementSet(elset);
gen->SetName(szname);
// add it to the model
GetBuilder()->GetFEModel().AddMeshDataGenerator(gen);
// read the parameters
ReadParameterList(tag, gen);
// Add it to the list (will be applied after the rest of the model was read in)
GetBuilder()->AddMeshDataGenerator(gen, nullptr, nullptr);
}
}
else
{
// name is required
if (szname == nullptr) throw XMLReader::MissingAttribute(tag, "name");
// copy the name
string name = szname;
// get the data type
if (szdataType == nullptr) szdataType = "scalar";
FEDataType dataType = str2datatype(szdataType);
if (dataType == FEDataType::FE_INVALID_TYPE) throw XMLReader::InvalidAttributeValue(tag, "data_type", szdataType);
// default format
Storage_Fmt fmt = (((dataType == FE_MAT3D) || (dataType == FE_MAT3DS)) ? Storage_Fmt::FMT_ITEM : Storage_Fmt::FMT_MULT);
// format overrider?
if (szfmt)
{
if (szcmp(szfmt, "MAT_POINTS") == 0) fmt = Storage_Fmt::FMT_MATPOINTS;
else if (szcmp(szfmt, "ITEM" ) == 0) fmt = Storage_Fmt::FMT_ITEM;
else throw XMLReader::InvalidAttributeValue(tag, "format", szfmt);
}
// create the data map
FEDomainMap* map = new FEDomainMap(dataType, fmt);
map->Create(elset);
map->SetName(name);
// read the data
ParseElementData(tag, *map);
// see if this map already exsits
FEDomainMap* oldMap = dynamic_cast<FEDomainMap*>(mesh.FindDataMap(name));
if (oldMap)
{
oldMap->Merge(*map);
delete map;
}
else
{
map->SetName(name);
mesh.AddDataMap(map);
}
}
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection4::ParseSurfaceData(XMLTag& tag, FESurfaceMap& map)
{
const FEFacetSet* set = map.GetFacetSet();
if (set == nullptr) throw XMLReader::InvalidTag(tag);
// get the total nr of elements
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int nelems = set->Faces();
FEDataType dataType = map.DataType();
int dataSize = map.DataSize();
int m = map.MaxNodes();
double data[3 * FEElement::MAX_NODES]; // make sure this array is large enough to store any data map type (current 3 for FE_VEC3D)
++tag;
do
{
// get the local element number
const char* szlid = tag.AttributeValue("lid");
int n = atoi(szlid) - 1;
// make sure the number is valid
if ((n < 0) || (n >= nelems)) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
int nread = tag.value(data, m * dataSize);
if (nread == dataSize)
{
switch (dataType)
{
case FE_DOUBLE: map.setValue(n, data[0]); break;
case FE_VEC2D: map.setValue(n, vec2d(data[0], data[1])); break;
case FE_VEC3D: map.setValue(n, vec3d(data[0], data[1], data[2])); break;
default:
assert(false);
}
}
else if (nread == m * dataSize)
{
double* pd = data;
for (int i = 0; i < m; ++i, pd += dataSize)
{
switch (dataType)
{
case FE_DOUBLE: map.setValue(n, i, pd[0]); break;
case FE_VEC2D: map.setValue(n, i, vec2d(pd[0], pd[1])); break;
case FE_VEC3D: map.setValue(n, i, vec3d(pd[0], pd[1], pd[2])); break;
default:
assert(false);
}
}
}
else throw XMLReader::InvalidValue(tag);
++tag;
} while (!tag.isend());
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection4::ParseShellThickness(XMLTag& tag, FEElementSet& set)
{
if (tag.isleaf())
{
FEMesh& mesh = GetFEModel()->GetMesh();
double h[FEElement::MAX_NODES];
int nval = tag.value(h, FEElement::MAX_NODES);
for (int i = 0; i < set.Elements(); ++i)
{
FEShellElement* pel = dynamic_cast<FEShellElement*>(&set.Element(i));
if (pel == 0) throw XMLReader::InvalidValue(tag);
if (pel->Nodes() != nval) throw XMLReader::InvalidValue(tag);
for (int j = 0; j < nval; ++j) pel->m_h0[j] = h[j];
}
}
else
{
vector<ELEMENT_DATA> data;
ParseElementData(tag, set, data, FEElement::MAX_NODES);
for (int i = 0; i < (int)data.size(); ++i)
{
ELEMENT_DATA& di = data[i];
if (di.nval > 0)
{
FEElement& el = set.Element(i);
if (el.Class() != FE_ELEM_SHELL) throw XMLReader::InvalidTag(tag);
FEShellElement& shell = static_cast<FEShellElement&> (el);
int ne = shell.Nodes();
if (ne != di.nval) throw XMLReader::InvalidTag(tag);
for (int j = 0; j < ne; ++j) shell.m_h0[j] = di.val[j];
}
}
}
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection4::ParseElementData(XMLTag& tag, FEElementSet& set, vector<ELEMENT_DATA>& values, int nvalues)
{
// get the total nr of elements
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int nelems = set.Elements();
// resize the array
values.resize(nelems);
for (int i = 0; i < nelems; ++i) values[i].nval = 0;
++tag;
do
{
// get the local element number
const char* szlid = tag.AttributeValue("lid");
int n = atoi(szlid) - 1;
// make sure the number is valid
if ((n < 0) || (n >= nelems)) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
ELEMENT_DATA& data = values[n];
data.nval = tag.value(data.val, nvalues);
++tag;
} while (!tag.isend());
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection4::ParseElementData(XMLTag& tag, FEDomainMap& map)
{
const FEElementSet* set = map.GetElementSet();
if (set == nullptr) throw XMLReader::InvalidTag(tag);
// get the total nr of elements
FEModel& fem = *GetFEModel();
FEMesh& mesh = fem.GetMesh();
int nelems = set->Elements();
FEDataType dataType = map.DataType();
int dataSize = map.DataSize();
int m = map.MaxNodes();
double data[3 * FEElement::MAX_NODES]; // make sure this array is large enough to store any data map type (current 3 for FE_VEC3D)
// TODO: For vec3d values, I sometimes need to normalize the vectors (e.g. for fibers). How can I do this?
int ncount = 0;
++tag;
do
{
// get the local element number
const char* szlid = tag.AttributeValue("lid");
int n = atoi(szlid) - 1;
// make sure the number is valid
if ((n < 0) || (n >= nelems)) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
int nread = tag.value(data, m * dataSize);
if (nread == dataSize)
{
double* v = data;
switch (dataType)
{
case FE_DOUBLE: map.setValue(n, v[0]); break;
case FE_VEC2D: map.setValue(n, vec2d(v[0], v[1])); break;
case FE_VEC3D: map.setValue(n, vec3d(v[0], v[1], v[2])); break;
case FE_MAT3D: map.setValue(n, mat3d(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8])); break;
case FE_MAT3DS: map.setValue(n, mat3ds(v[0], v[1], v[2], v[3], v[4], v[5])); break;
default:
assert(false);
}
}
else if (nread == m * dataSize)
{
double* v = data;
for (int i = 0; i < m; ++i, v += dataSize)
{
switch (dataType)
{
case FE_DOUBLE: map.setValue(n, i, v[0]); break;
case FE_VEC2D: map.setValue(n, i, vec2d(v[0], v[1])); break;
case FE_VEC3D: map.setValue(n, i, vec3d(v[0], v[1], v[2])); break;
default:
assert(false);
}
}
}
else throw XMLReader::InvalidValue(tag);
++tag;
ncount++;
} while (!tag.isend());
if (ncount != nelems) throw FEBioImport::MeshDataError();
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection4::ParseMaterialFibers(XMLTag& tag, FEElementSet& set)
{
// find the domain with the same name
string name = set.GetName();
FEMesh* mesh = const_cast<FEMesh*>(set.GetMesh());
FEDomain* dom = mesh->FindDomain(name);
if (dom == nullptr) throw XMLReader::InvalidAttributeValue(tag, "elem_set", name.c_str());
// get the material
FEMaterial* mat = dom->GetMaterial();
if (mat == nullptr) throw XMLReader::InvalidAttributeValue(tag, "elem_set", name.c_str());
// get the fiber property
const char* sztype = tag.Attribute("type").cvalue();
ParamString ps(sztype);
FEProperty* fiber = mat->FindProperty(ps);
if (fiber == nullptr) throw XMLReader::InvalidAttributeValue(tag, "type", "fiber");
if (fiber->GetSuperClassID() != FEVEC3DVALUATOR_ID) throw XMLReader::InvalidAttributeValue(tag, "type", "fiber");
// create a domain map
FEDomainMap* map = new FEDomainMap(FE_VEC3D, FMT_ITEM);
map->Create(&set);
FEMappedValueVec3* val = fecore_new<FEMappedValueVec3>("map", GetFEModel());
val->setDataMap(map);
fiber->SetProperty(val);
vector<ELEMENT_DATA> data;
ParseElementData(tag, set, data, 3);
for (int i = 0; i < (int)data.size(); ++i)
{
ELEMENT_DATA& di = data[i];
if (di.nval > 0)
{
FEElement& el = set.Element(i);
if (di.nval != 3) throw XMLReader::InvalidTag(tag);
vec3d v(di.val[0], di.val[1], di.val[2]);
v.unit();
map->set<vec3d>(i, v);
}
}
}
//-----------------------------------------------------------------------------
void FEBioMeshDataSection4::ParseMaterialAxes(XMLTag& tag, FEElementSet& set)
{
// find the domain with the same name
string name = set.GetName();
const char* szname = name.c_str();
FEMesh* mesh = const_cast<FEMesh*>(set.GetMesh());
// find the domain
string domName = set.GetName();
FEDomainList& DL = set.GetDomainList();
if (DL.Domains() != 1)
{
throw XMLReader::InvalidAttributeValue(tag, "elem_set", domName.c_str());
}
FEDomain* dom = DL.GetDomain(0);
// get the material
FEMaterial* mat = dom->GetMaterial();
if (mat == nullptr) throw XMLReader::InvalidAttributeValue(tag, "elem_set", szname);
Storage_Fmt fmt = FMT_ITEM;
const char* szfmt = tag.AttributeValue("format", true);
if (szfmt)
{
if (szcmp(szfmt, "mat_points") == 0) fmt = FMT_MATPOINTS;
}
// get the mat_axis property
FEProperty* pQ = mat->FindProperty("mat_axis", true);
if (pQ == nullptr)
{
// if the material does not have the mat_axis property, we'll assign it directly to the material points
// This only works for ITEM storage
if (fmt != FMT_ITEM) throw XMLReader::InvalidAttributeValue(tag, "format", szfmt);
++tag;
do
{
if ((tag == "e") || (tag == "elem"))
{
// get the local element number
const char* szlid = tag.AttributeValue("lid");
int lid = atoi(szlid) - 1;
// make sure the number is valid
if ((lid < 0) || (lid >= set.Elements())) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
// get the element
FEElement* el = mesh->FindElementFromID(set[lid]);
if (el == 0) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
// read parameters
vec3d a, d;
++tag;
do
{
if (tag == "a") value(tag, a);
else if (tag == "d") value(tag, d);
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
// convert to quaternion
mat3d A(a, d);
quatd Q(A);
// assign to all material points
int ni = el->GaussPoints();
for (int n=0; n<ni; ++n)
{
FEMaterialPoint* mp = el->GetMaterialPoint(n);
mp->m_Q = Q;
}
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
return;
}
if (pQ->GetSuperClassID() != FEMAT3DVALUATOR_ID) throw XMLReader::InvalidAttributeValue(tag, "elem_set", szname);
// create the map's name: material_name.mat_axis
stringstream ss;
ss << "material" << mat->GetID() << ".mat_axis";
string mapName = ss.str();
// the domain map we're about to create
FEDomainMap* map = nullptr;
// see if the generator is defined
const char* szgen = tag.AttributeValue("generator", true);
if (szgen)
{
// create a domain map
map = new FEDomainMap(FE_MAT3D, fmt);
map->SetName(mapName);
map->Create(&set);
// data will be generated
FEModel* fem = GetFEModel();
FEElemDataGenerator* gen = 0;
if (strcmp(szgen, "const") == 0)
{
++tag;
do {
if (tag == "value")
{
mat3d v;
tag.value(v);
map->fillValue(v);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
else throw XMLReader::InvalidAttributeValue(tag, "generator", szgen);
}
else
{
// This only works for ITEM storage
if (fmt != FMT_ITEM) throw XMLReader::InvalidAttributeValue(tag, "format", szfmt);
// create a domain map
map = new FEDomainMap(FE_MAT3D, FMT_ITEM);
map->SetName(mapName);
map->Create(&set);
++tag;
do
{
if ((tag == "e") || (tag == "elem"))
{
// get the local element number
const char* szlid = tag.AttributeValue("lid");
int lid = atoi(szlid) - 1;
// make sure the number is valid
if ((lid < 0) || (lid >= set.Elements())) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
// get the element
FEElement* el = mesh->FindElementFromID(set[lid]);
if (el == 0) throw XMLReader::InvalidAttributeValue(tag, "lid", szlid);
// read parameters
vec3d a, d;
++tag;
do
{
if (tag == "a") value(tag, a);
else if (tag == "d") value(tag, d);
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
// set the value
mat3d Q(a, d);
map->setValue(lid, Q);
}
else throw XMLReader::InvalidTag(tag);
++tag;
} while (!tag.isend());
}
assert(map);
// see if this map already exists
FEDomainMap* oldMap = dynamic_cast<FEDomainMap*>(mesh->FindDataMap(mapName));
if (oldMap)
{
// It does, so merge it
oldMap->Merge(*map);
delete map;
}
else
{
// It does not, so add it
FEMappedValueMat3d* val = fecore_alloc(FEMappedValueMat3d, GetFEModel());
val->setDataMap(map);
pQ->SetProperty(val);
mesh->AddDataMap(map);
}
}
| C++ |
3D | febiosoftware/FEBio | FEBioXML/FEBioMeshDomainsSection4.h | .h | 1,803 | 51 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEBioImport.h"
#include "FEBModel.h"
//-----------------------------------------------------------------------------
// MeshDomains section
class FEBioMeshDomainsSection4 : public FEBioFileSection
{
public:
FEBioMeshDomainsSection4(FEBioImport* pim);
void Parse(XMLTag& tag);
protected:
void ParseSolidDomainSection(XMLTag& tag);
void ParseShellDomainSection(XMLTag& tag);
void ParseBeamDomainSection(XMLTag& tag);
private:
void BuildNLT();
private:
std::vector<int> m_NLT;
int m_noff;
};
| Unknown |
3D | febiosoftware/FEBio | FEBioXML/FEModelBuilder.h | .h | 7,239 | 246 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FECore/FEModel.h>
#include "febioxml_api.h"
#include "FEBModel.h"
#include <string>
class FESolver;
class FEPointFunction;
class FEMeshDataGenerator;
class FEDomainMap;
class FENodalLoad;
class FEEdgeLoad;
class FESurfaceLoad;
class FEBodyLoad;
// This is a helper class for building the FEModel from file input.
class FEBIOXML_API FEModelBuilder
{
public:
struct ELEMENT
{
int nid;
int nodes;
int node[FEElement::MAX_NODES];
};
struct FEBIOXML_API NodeSetPair
{
char szname[256];
FENodeSet* set1;
FENodeSet* set2;
};
struct FEBIOXML_API NodeSetSet
{
NodeSetSet() { count = 0; }
enum { MAX_SETS = 32 };
char szname[256];
FENodeSet* set[MAX_SETS];
int count;
void add(FENodeSet* ps) { set[count++] = ps; }
};
struct FEBIOXML_API MappedParameter
{
FEParam* pp;
FECoreBase* pc;
const char* szname;
int index;
};
struct FEBIOXML_API MapLCToFunction
{
int lc;
double scale;
FEPointFunction* pf;
};
struct FEBIOXML_API DataGen
{
FEMeshDataGenerator* gen; // the data generator
FEDataMap* map; // the destination map
FEParamDouble* pp; // the param to which to apply the map (or null)
};
public:
//! constructor
FEModelBuilder(FEModel& fem);
virtual ~FEModelBuilder();
//! set the active module
void SetActiveModule(const std::string& moduleName);
//! Get the module name
std::string GetModuleName() const;
// create a new analysis step
FEAnalysis* CreateNewStep(bool allocSolver = true);
// create a material
FEMaterial* CreateMaterial(const char* sztype);
// get the current step (will create a new one if no step was defined yet)
FEAnalysis* GetStep(bool allocSolver = true);
// add component to current step
void AddComponent(FEStepComponent* mc);
// reset some data for reading next step
void NextStep();
//! Create a domain
virtual FEDomain* CreateDomain(FE_Element_Spec espec, FEMaterial* mat);
//! Get the mesh
FEMesh& GetMesh();
//! get the FE model
FEModel& GetFEModel();
public:
bool BuildSurface(FESurface& s, FEFacetSet& f, bool bnodal = false);
bool BuildEdge(FEEdge& s, FESegmentSet& f);
FE_Element_Spec ElementSpec(const char* sz);
// Call this to initialize default variables when reading older files.
void SetDefaultVariables();
public:
virtual void AddMaterial(FEMaterial* pmat);
void AddBC(FEBoundaryCondition* pbc);
void AddNodalLoad(FENodalLoad* pfc);
void AddEdgeLoad(FEEdgeLoad* pel);
void AddSurfaceLoad(FESurfaceLoad* psl);
void AddInitialCondition(FEInitialCondition* pic);
void AddContactInterface(FESurfacePairConstraint* pci);
void AddModelLoad(FEModelLoad* pml);
void AddNonlinearConstraint(FENLConstraint* pnc);
// TODO: Try to remove these
virtual void AddRigidComponent(FEStepComponent* prc);
public:
void AddNodeSetPair(NodeSetPair& p) { m_nsetPair.push_back(p); }
NodeSetPair* FindNodeSetPair(const char* szname);
void AddNodeSetSet(NodeSetSet& p) { m_nsetSet.push_back(p); }
NodeSetSet* FindNodeSetSet(const char* szname);
FENodeSet* FindNodeSet(const string& setName);
public:
void MapLoadCurveToFunction(FEPointFunction* pf, int lc, double scale = 1.0);
protected:
FESolver* BuildSolver(FEModel& fem);
public:
// Build the node ID table
void BuildNodeList();
// find a node index from its ID
int FindNodeFromID(int nid);
// convert an array of nodal ID to nodal indices
void GlobalToLocalID(int* l, int n, vector<int>& m);
public:
void AddMappedParameter(FEParam* p, FECoreBase* parent, const char* szmap, int index = 0);
void AddMeshDataGenerator(FEMeshDataGenerator* gen, FEDataMap* map, FEParamDouble* pp);
// This will associate all mapped parameters to their assigned maps.
void ApplyParameterMaps();
void ApplyLoadcurvesToFunctions();
bool GenerateMeshDataMaps();
// finish the build process
bool Finish();
FEBModel& GetFEBModel();
void SetDefaultSolver(const std::string& s) { m_defaultSolver = s; }
private:
FEModel& m_fem; //!< model that is being constructed
FEAnalysis* m_pStep; //!< pointer to current analysis step
int m_nsteps; //!< nr of step sections read
FEBModel m_feb;
std::string m_defaultSolver; //!< default solver
public:
int m_maxid; //!< max element ID
bool m_b3field_hex; //!< three-field element flag for hex (and wedge elements)
bool m_b3field_tet; //!< three-field element flag for quadratic tets
bool m_b3field_shell; //!< three-field element flag for shells
bool m_b3field_quad; //!< three-field element flag for quad shells
bool m_b3field_tri; //!< three-field element flag for tri shells
bool m_but4; //!< use UT4 formulation flag
int m_default_shell; //!< shell formulation
bool m_shell_norm_nodal; //!< shell normal flag (nodal or face)
double m_ut4_alpha; //!< UT4 integration alpha value
bool m_ut4_bdev; //!< UT4 integration deviatoric formulation flag
double m_udghex_hg; //!< hourglass parameter for UDGhex integration
FE_Element_Type m_nhex8; //!< hex integration rule
FE_Element_Type m_ntet4; //!< tet4 integration rule
FE_Element_Type m_ntet10; //!< tet10 integration rule
FE_Element_Type m_ntet15; //!< tet15 integration rule
FE_Element_Type m_ntet20; //!< tet20 integration rule
FE_Element_Type m_ntri3; //!< tri3 integration rule
FE_Element_Type m_ntri6; //!< tri6 integration rule
FE_Element_Type m_ntri7; //!< tri7 integration rule
FE_Element_Type m_ntri10; //!< tri10 integration rule
FE_Element_Type m_nquad4; //!< quad4 integration rule
FE_Element_Type m_nquad8; //!< quad8 integration rule
FE_Element_Type m_nquad9; //!< quad9 integration rule
protected:
vector<NodeSetPair> m_nsetPair;
vector<NodeSetSet> m_nsetSet;
vector<MappedParameter> m_mappedParams;
vector<MapLCToFunction> m_lc2fnc;
vector<DataGen> m_mapgen;
protected:
int m_node_off; //!< node offset (i.e. lowest node ID)
vector<int> m_node_list; //!< map node ID's to their nodes.
};
| Unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.